{"text": "#include \n#include \n#include \n#include \n#include \n#include \n// #include \"libiomp/omp.h\"\n#include \n#include \"../include/type.h\"\n#include \"../include/util.h\"\n#include \"../include/global.h\"\n\n\nextern clock_t dur;\nextern char *optarg;\nextern int optind;\n\n\nchar c_getopt(int argc, char *argv[], char *pattern) {\n static size_t i = 0;\n int j;\n char ret;\n ++optind;\n\n if (optind > (int)strlen(pattern)) {\n return -1;\n }\n\n ret = pattern[i++];\n\n for (j = 0; j < argc; ++j) {\n if (argv[j][0] == '-' && argv[j][1] == ret) {\n optarg = argv[j+1];\n }\n }\n\n return ret;\n}\n\n\n/**\n * @brief initiator of odiff.\n *\n * @param inc1\n * @param inc2\n * @param skp1\n * @param skp2\n * @param inclu_len\n * @param skip_len\n * @param flag\n * @param id\n *\n * @return \n */\nodiff* diff_alloc(gsl_vector* inc1, gsl_vector* inc2,\n gsl_vector* skp1, gsl_vector* skp2,\n int inclu_len, int skip_len, int flag, char* id) {\n odiff *diff = (odiff*)malloc(sizeof(odiff));\n diff->inc1 = inc1, diff->skp1 = skp1, diff->inc2 = inc2, diff->skp2 = skp2;\n diff->inclu_len = inclu_len, diff->skip_len = skip_len;\n diff->flag = flag, diff->id = (char*)malloc(sizeof(char)*(strlen(id)+1));\n strcpy(diff->id, id);\n return diff;\n}\n\n\n/**\n * @brief performing unary operation on gsl_vector.\n * @param vec\n * @param fun\n */\nvoid unary_operate_vec(gsl_vector *vec, double (*fun) (double)) {\n size_t i;\n for (i = 0; i < vec->size; ++i) {\n gsl_vector_set(vec, i, fun(gsl_vector_get(vec, i)));\n }\n return;\n}\n\n\n/**\n * @brief performing binary operation on gsl_vector.\n *\n * @param vec\n * @param pa\n * @param fun\n */\nvoid binary_operate_vec(gsl_vector *vec, double pa, double (*fun) (double, const double)) {\n size_t i;\n for (i = 0; i < vec->size; ++i) {\n gsl_vector_set(vec, i, fun(gsl_vector_get(vec, i), pa));\n }\n return;\n}\n\n\n/**\n * @brief performing element-wise operation on gsl_vector.\n *\n * @param vec\n * @param fun\n * @param argc\n * @param ...\n */\nvoid element_wise_vec(gsl_vector *vec, double (*fun) (double, va_list), int argc, ...) {\n va_list argv;\n size_t i;\n for (i = 0; i < vec->size; ++i) {\n va_start(argv, argc);\n gsl_vector_set(vec, i, fun(gsl_vector_get(vec, i), argv));\n va_end(argv);\n }\n return;\n}\n\n\n/**\n * @brief cumulative summation of a gsl_vector.\n *\n * @param vec\n * @param fun\n * @param argc\n * @param ...\n *\n * @return \n */\ndouble cuscumsum(gsl_vector *vec, double (*fun) (double, va_list), int argc, ...) {\n va_list argv, tmp;\n double sum = 0;\n size_t i;\n va_start(argv, argc);\n for (i = 0; i < vec->size; ++i) {\n va_copy(tmp, argv);\n sum += fun(gsl_vector_get(vec, i), tmp);\n }\n va_end(tmp);\n va_end(argv);\n return sum;\n}\n\n\nint parse_title(char* str, char** output) {\n int idx = 0;\n char *token = strtok(str, \" \\t\\r\\n\\v\\f\");\n while(token) {\n output[idx] = (char*)malloc(sizeof(char)*TITLE_ELEMENT_LEN);\n strcpy(output[idx++], token);\n token = strtok(NULL, \" \\t\\r\\n\\v\\f\");\n }\n\n // int base = 0;\n // do {\n // base += idx? strlen(output[idx-1]) + LEN_OF_NT : 0;\n // output[idx] = (char*)malloc(sizeof(char)*TITLE_ELEMENT_LEN);\n // } while(sscanf(str + base, \"%s \\t\\n\", output[idx++]) != EOF);\n\n return idx-1;\n}\n\n\n/**\n * @brief \n *\n * @param input a string in format '1,2,3,4,5,6,...'.\n * @param vec\n *\n * @return \n */\nint str_to_vector(char* input, gsl_vector** vec) {\n int idx = 0, count = 1;\n size_t i = 0;\n // gsl_vector_free(*vec);\n\n for (i = 0; i < strlen(input); ++i) {\n if (input[i] == ',') {\n ++count;\n }\n }\n\n *vec = gsl_vector_alloc(count);\n char *str = strtok(input, \",\");\n while(str) {\n if (strcmp(str, \"NA\") == 0 || strcmp(str, \"NAN\") == 0 ||\n strcmp(str, \"na\") == 0 || strcmp(str, \"nan\") == 0) {\n return -1;\n }\n gsl_vector_set(*vec, idx++, atof(str));\n str = strtok(NULL, \",\");\n }\n\n return count;\n}\n\n\nint parse_line(char* str, char* id, gsl_vector** inc1, gsl_vector** skp1,\n gsl_vector** inc2, gsl_vector** skp2,\n int* inclu_len, int* skip_len) {\n int idx = 0;\n char output[7][COLUMN_LEN];\n\n char *token = strtok(str, \" \\t\\r\\n\\v\\f\");\n while(token) {\n strcpy(output[idx++], token);\n token = strtok(NULL, \" \\t\\r\\n\\v\\f\");\n }\n\n // int base = 0;\n // do {\n // base += idx? strlen(output[idx-1]) + LEN_OF_NT : 0;\n // } while(sscanf(str + base, \"%s \\t\\n\", output[idx++]) != EOF);\n\n strcpy(id, output[0]);\n if (str_to_vector(output[1], inc1) == -1 ||\n str_to_vector(output[2], skp1) == -1 ||\n str_to_vector(output[3], inc2) == -1 ||\n str_to_vector(output[4], skp2) == -1) {\n printf(\"An error occured. rMATS cannot handle missing value. Sample Id: %s\\n\", id);\n printf(\"Exiting.\\n\");\n exit(0);\n \n }\n *inclu_len = atoi(output[5]);\n *skip_len = atoi(output[6]);\n\n return idx-1;\n}\n\n\nint parse_file(const char* filename, diff_list_node* list, char** title_element_list) {\n FILE *ifp;\n size_t olen = MAX_LINE;\n char *str_line = (char*)malloc(sizeof(char)*olen);\n char title[TITLE_LEN], id[MAX_LINE];\n int row_num=0, inclu_len, skip_len;\n gsl_vector *inc1 = NULL, *skp1 = NULL, *inc2 = NULL, *skp2 = NULL;\n\n if ((ifp = fopen(filename, \"r\")) == NULL) {\n printf(\"Fail to open!\");\n return 0;\n }\n fgets(title, TITLE_LEN, ifp);\n parse_title(title, title_element_list);\n\n while (getline(&str_line, &olen, ifp) != -1) {\n ++row_num;\n parse_line(str_line, id, &inc1, &skp1, &inc2, &skp2, &inclu_len, &skip_len);\n if (inc1->size != skp1->size || inc2->size != skp2->size) {\n printf(\"An error occured. The length of the pair of vector should be equal. Sample Id: %s\\n\", id);\n printf(\"Size of vector: %ld, %ld, %ld, %ld\\n\", inc1->size, skp1->size, inc2->size, skp2->size);\n printf(\"Exiting\\n\");\n exit(0);\n }\n gsl_vector_add(inc1, skp1), gsl_vector_add(inc2, skp2);\n\n // TODO | or || ?\n // According to original python code 'if (vecprod(vecadd(inc1,skp1))==0) | (vecprod(vecadd(inc2,skp2))==0):',\n // it's a bit arithmetic '|'. However, it should be a logical 'or' in such senario.\n if (cumprod(inc1) == 0 || cumprod(inc2) == 0) {\n gsl_vector_sub(inc1, skp1), gsl_vector_sub(inc2, skp2);\n diff_append(list, diff_alloc(inc1, inc2, skp1, skp2, inclu_len, skip_len, 0, id));\n } else {\n gsl_vector_sub(inc1, skp1), gsl_vector_sub(inc2, skp2);\n\n // TODO According to original python code, this function will not change anything.\n // original comment: add 1 in both inclusion and skipping counts for robustness in small sample size\n gsl_vector_add_constant(inc1, 0.0), gsl_vector_add_constant(skp1, 0.0);\n gsl_vector_add_constant(inc2, 0.0), gsl_vector_add_constant(skp2, 0.0);\n diff_append(list, diff_alloc(inc1, inc2, skp1, skp2, inclu_len, skip_len, 1, id));\n }\n }\n free(str_line);\n fclose(ifp);\n\n return row_num;\n}\n\n\nvoid display_dvector(const gsl_vector* vec) {\n size_t i;\n for (i = 0; i < vec->size; ++i) {\n printf(\"%.10f \", gsl_vector_get(vec, i));\n }\n}\n\n\n/**\n * @brief handy function.\n *\n * @param i\n * @param argv\n *\n * @return \n */\ndouble logit(double i) {\n if (i < 0.01) {\n i = 0.01;\n } else if (i > 0.99) {\n i = 0.99;\n }\n return log(i/(1-i));\n}\n\n\n/*\ndouble log_and_minus_x(const double i, va_list argv) {\n double pa = va_arg(argv, double);\n return logit(i) - logit(pa);\n}\n\n\ndouble rev_log_and_minus_x(const double i, va_list argv) {\n double pa = va_arg(argv, double);\n return pow(M_E, i + log(pa));\n}\n*/\n\n/**\n * @brief cumulative production of a gsl_vector.\n *\n * @param vec\n *\n * @return \n */\ndouble cumprod(const gsl_vector* vec) {\n double res = 1;\n size_t i;\n for (i = 0; i < vec->size; ++i) {\n res *= gsl_vector_get(vec, i);\n }\n return res;\n}\n\n\n// for multivar, 1, 2\ndouble sum_for_multivar(const double i, va_list argv) {\n double pa = va_arg(argv, double);\n return pow(logit(i)-logit(pa), 2);\n}\n\n\n// for multivar_der, 1_der, 2_der\ndouble sum_for_multivar_der(const double i, va_list argv) {\n double pa = va_arg(argv, double);\n // return -2 * (logit(i) - logit(pa))/(pa*(1-pa));\n return 2 * (logit(i) - logit(pa))/(pa*pa-pa);\n}\n\n\ndouble myfunc_marginal_2der(const double x, const double I, const double S,\n const double beta, const double var,\n const int inclu_len, const int skip_len) {\n double tmp1, tmp2, tmp3, one_x = 1-x;\n double powx = pow(x,2), pow1_x = pow(one_x,2), pow_len = pow(inclu_len*x + skip_len*one_x,2);\n\n tmp1 = (((2 * x - 1) * (logit(beta) - logit(x)) - 1)/var - 1)/(powx*pow1_x);\n tmp2 = I * skip_len * (2*inclu_len*x+skip_len)/(powx * pow_len);\n tmp3 = S * inclu_len * (inclu_len+2*skip_len*one_x)/(pow1_x * pow_len);\n\n return tmp1 - tmp2 - tmp3;\n}\n\n\n// for marginal\ndouble sum_for_marginal(const double i, va_list argv) {\n int *idx = va_arg(argv, int*);\n double beta = va_arg(argv, double);\n double I_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);\n double S_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);\n double var = va_arg(argv, double), new_psi, f1, f1_2der;\n int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);\n *idx += 1;\n\n new_psi = inclu_len * i/(inclu_len * i + skip_len * (1 - i));\n f1 = I_ * log(new_psi) + S_ * log(1 - new_psi) -\n pow(logit(i) - logit(beta),2)/(2*var) - log(i) - log(1-i);\n f1_2der = fabs(myfunc_marginal_2der(i, I_, S_, beta,\n var, inclu_len, skip_len));\n\n return 0.5 * log(fabs(f1_2der) + 0.00001) - f1;\n}\n\n\n// for marginal_der\ndouble sum_for_marginal_der(const double i, va_list argv) {\n int *idx = va_arg(argv, int*);\n double beta = va_arg(argv, double);\n double I_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);\n double S_ = gsl_vector_get(va_arg(argv, gsl_vector*), *idx);\n double var = va_arg(argv, double);\n int inclu_len = va_arg(argv, int), skip_len = va_arg(argv, int);\n double f1_1der, f1_2der, f1_3der, one_i = 1-i;\n *idx += 1;\n double powi = pow(i,2), pow1_i = pow(one_i,2);\n\n f1_3der = (2 * i - 1)/(powi * pow1_i*beta*(1-beta)*var);\n f1_2der = myfunc_marginal_2der(i, I_, S_, beta, var, inclu_len, skip_len);\n f1_1der = (logit(i) - logit(beta))/(beta * (1-beta) * var);\n\n return 0.5 * f1_3der/f1_2der - f1_1der;\n}\n\n\n// function used to manipulate our linked list.\nint diff_append(diff_list_node* header, odiff* data) {\n diff_list_node *tmp = (diff_list_node*)malloc(sizeof(diff_list_node));\n tmp->data = data;\n tmp->end = tmp;\n tmp->next = NULL;\n header->end->next = tmp;\n header->end->end = tmp;\n header->end = tmp;\n\n return 0;\n}\n\nint diff_insert(diff_list_node* header, odiff* data, int idx) {\n\n return 6;\n}\n\nint diff_get_next(diff_list_node* header, odiff* data) {\n\n return 6;\n}\n\nint diff_get_at(diff_list_node* header, odiff* data, int idx) {\n int i;\n diff_list_node* tmp = header;\n for (i = 0; i <= idx; ++i) {\n tmp = tmp->next;\n }\n *data = *(tmp->data);\n return 0;\n}\n\n\nvoid split_data_list(int lenofl, int batch_size, diff_list_node* list, batch_datum *ret) {\n int i = 0, group = lenofl/batch_size, carry = lenofl % batch_size;\n diff_list_node *node = list;\n odiff **datum = (odiff**)malloc(sizeof(odiff*)*(group+1));\n for (i = 0; i < group+1; ++i) {\n datum[i] = (odiff*)malloc(sizeof(odiff)*batch_size);\n }\n\n for (i = 0; i < lenofl; ++i) {\n node = node->next;\n datum[i/batch_size][i%batch_size] = *(node->data);\n }\n for (i = 0; i < group; ++i) {\n ret[i].batch_size = batch_size;\n ret[i].datum = (void**)&datum[i];\n }\n ret[group].batch_size = carry;\n ret[group].datum = (void**)&datum[group];\n\n return;\n}\n\n\nvoid mp_threadpool(int nthread, int ntask, void* (*func)(void *), void** datum, void **ret) {\n int i;\n omp_set_num_threads(nthread);\n\n #pragma omp parallel for private(i)\n for (i = 0; i < ntask; ++i) {\n ret[i] = (*func)(datum[i]);\n }\n\n return;\n}\n\n\n/**\n * @brief C wrapper of Fortran l_bfgs_b routine.\n *\n * @param n\n * @param m\n * @param x[]\n * @param l[]\n * @param u[]\n * @param nbd[]\n * @param fp\n * @param gp\n * @param factr\n * @param pgtol\n * @param iprint\n * @param maxiter\n * @param argc\n * @param ...\n *\n * @return \n********************************************************************\nc --------------------------------------------------------------\nc DESCRIPTION OF THE VARIABLES IN L-BFGS-B\nc --------------------------------------------------------------\nc\nc n is an INTEGER variable that must be set by the user to the\nc number of variables. It is not altered by the routine.\nc\nc m is an INTEGER variable that must be set by the user to the\nc number of corrections used in the limited memory matrix.\nc It is not altered by the routine. Values of m < 3 are\nc not recommended, and large values of m can result in excessive\nc computing time. The range 3 <= m <= 20 is recommended. \nc\nc x is a DOUBLE PRECISION array of length n. On initial entry\nc it must be set by the user to the values of the initial\nc estimate of the solution vector. Upon successful exit, it\nc contains the values of the variables at the best point\nc found (usually an approximate solution).\nc\nc l is a DOUBLE PRECISION array of length n that must be set by\nc the user to the values of the lower bounds on the variables. If\nc the i-th variable has no lower bound, l(i) need not be defined.\nc\nc u is a DOUBLE PRECISION array of length n that must be set by\nc the user to the values of the upper bounds on the variables. If\nc the i-th variable has no upper bound, u(i) need not be defined.\nc\nc nbd is an INTEGER array of dimension n that must be set by the\nc user to the type of bounds imposed on the variables:\nc nbd(i)=0 if x(i) is unbounded,\nc 1 if x(i) has only a lower bound,\nc 2 if x(i) has both lower and upper bounds, \nc 3 if x(i) has only an upper bound.\nc\nc f is a DOUBLE PRECISION variable. If the routine setulb returns\nc with task(1:2)= 'FG', then f must be set by the user to\nc contain the value of the function at the point x.\nc\nc g is a DOUBLE PRECISION array of length n. If the routine setulb\nc returns with taskb(1:2)= 'FG', then g must be set by the user to\nc contain the components of the gradient at the point x.\nc\nc factr is a DOUBLE PRECISION variable that must be set by the user.\nc It is a tolerance in the termination test for the algorithm.\nc The iteration will stop when\nc\nc (f^k - f^{k+1})/max{|f^k|,|f^{k+1}|,1} <= factr*epsmch\nc\nc where epsmch is the machine precision which is automatically\nc generated by the code. Typical values for factr on a computer\nc with 15 digits of accuracy in double precision are:\nc factr=1.d+12 for low accuracy;\nc 1.d+7 for moderate accuracy; \nc 1.d+1 for extremely high accuracy.\nc The user can suppress this termination test by setting factr=0.\nc\nc pgtol is a double precision variable.\nc On entry pgtol >= 0 is specified by the user. The iteration\nc will stop when\nc\nc max{|proj g_i | i = 1, ..., n} <= pgtol\nc\nc where pg_i is the ith component of the projected gradient.\nc The user can suppress this termination test by setting pgtol=0.\nc\nc wa is a DOUBLE PRECISION array of length \nc (2mmax + 4)nmax + 12mmax^2 + 12mmax used as workspace.\nc This array must not be altered by the user.\nc\nc iwa is an INTEGER array of length 3nmax used as\nc workspace. This array must not be altered by the user.\nc\nc task is a CHARACTER string of length 60.\nc On first entry, it must be set to 'START'.\nc On a return with task(1:2)='FG', the user must evaluate the\nc function f and gradient g at the returned value of x.\nc On a return with task(1:5)='NEW_X', an iteration of the\nc algorithm has concluded, and f and g contain f(x) and g(x)\nc respectively. The user can decide whether to continue or stop\nc the iteration. \nc When\nc task(1:4)='CONV', the termination test in L-BFGS-B has been \nc satisfied;\nc task(1:4)='ABNO', the routine has terminated abnormally\nc without being able to satisfy the termination conditions,\nc x contains the best approximation found,\nc f and g contain f(x) and g(x) respectively;\nc task(1:5)='ERROR', the routine has detected an error in the\nc input parameters;\nc On exit with task = 'CONV', 'ABNO' or 'ERROR', the variable task\nc contains additional information that the user can print.\nc This array should not be altered unless the user wants to\nc stop the run for some reason. See driver2 or driver3\nc for a detailed explanation on how to stop the run \nc by assigning task(1:4)='STOP' in the driver.\nc\nc iprint is an INTEGER variable that must be set by the user.\nc It controls the frequency and type of output generated:\nc iprint<0 no output is generated;\nc iprint=0 print only one line at the last iteration;\nc 0100 print details of every iteration including x and g;\nc When iprint > 0, the file iterate.dat will be created to\nc summarize the iteration.\nc\nc csave is a CHARACTER working array of length 60.\nc\nc lsave is a LOGICAL working array of dimension 4.\nc On exit with task = 'NEW_X', the following information is\nc available:\nc lsave(1) = .true. the initial x did not satisfy the bounds;\nc lsave(2) = .true. the problem contains bounds;\nc lsave(3) = .true. each variable has upper and lower bounds.\nc\nc isave is an INTEGER working array of dimension 44.\nc On exit with task = 'NEW_X', it contains information that\nc the user may want to access:\nc isave(30) = the current iteration number;\nc isave(34) = the total number of function and gradient\nc evaluations;\nc isave(36) = the number of function value or gradient\nc evaluations in the current iteration;\nc isave(38) = the number of free variables in the current\nc iteration;\nc isave(39) = the number of active constraints at the current\nc iteration;\nc\nc see the subroutine setulb.f for a description of other \nc information contained in isave\nc\nc dsave is a DOUBLE PRECISION working array of dimension 29.\nc On exit with task = 'NEW_X', it contains information that\nc the user may want to access:\nc dsave(2) = the value of f at the previous iteration;\nc dsave(5) = the machine precision epsmch generated by the code;\nc dsave(13) = the infinity norm of the projected gradient;\nc\nc see the subroutine setulb.f for a description of other \nc information contained in dsave\nc\nc --------------------------------------------------------------\nc END OF THE DESCRIPTION OF THE VARIABLES IN L-BFGS-B\nc --------------------------------------------------------------\nc\nc << An example of subroutine 'timer' for AIX Version 3.2 >>\nc\nc subroutine timer(ttime)\nc double precision ttime\nc integer itemp, integer mclock\nc itemp = mclock()\nc ttime = dble(itemp)*1.0d-2\nc return\nc end\n\n*********************************************************************\n */\ndouble l_bfgs_b_wrapper(integer n, integer m, doublereal x[], doublereal l[],\n doublereal u[], integer nbd[],\n double (*fp) (const double x[], va_list argv),\n void (*gp) (const double x[], double res[], va_list argv),\n doublereal factr, doublereal pgtol, integer iprint,\n int maxfun, int maxiter, int argc, ...) {\n va_list argv, tmp;\n char task[SIXTY], csave[SIXTY];\n logical lsave[4];\n integer iwa[3*n], isave[44];\n doublereal dsave[29], wa[2*m*n+5*n+11*m*m+8*m];\n va_start(argv, argc);\n\n strcpy(task,\"START\");\n int i, count = 0, funcount = 0, maxls = 20;\n for(i=5;i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"brains.h\"\n\n/*! \n * This function initialize the program.\n */\nvoid init()\n{\n int i, j;\n\n nq = 1 + parset.flag_trend;\n num_params_trend = nq;\n num_params_drw = 3; /* include systematic error */\n if(parset.flag_dim == 0)\n {\n num_params_resp = 0; /* no A and Ag for 0D */\n }\n else\n {\n num_params_resp = 2; /* response A and Ag */\n }\n\n if(parset.flag_trend_diff > 0)\n {\n num_params_difftrend = parset.flag_trend_diff; /* differences of the trends between continuum and line */\n }\n else\n {\n num_params_difftrend = 0;\n }\n \n num_params_var = num_params_drw + num_params_trend + num_params_resp + num_params_difftrend;\n\n /* number of parameters for narrow line, only valid for 2d RM. */\n num_params_nlr = 0;\n if(parset.flag_narrowline >= 2)\n num_params_nlr = 3;\n\n /* number of parameters for spectral broadening, only valid for 2d RM */\n num_params_res = 1;\n if(parset.flag_InstRes > 0)\n num_params_res = n_line_data;\n\n /* number of parameters for line center, only valid for 2d RM */\n num_params_linecenter = 0;\n if(parset.flag_linecenter > 0)\n num_params_linecenter = 1;\n else if(parset.flag_linecenter < 0)\n num_params_linecenter = n_line_data;\n \n switch(parset.flag_blrmodel)\n {\n case -1: /* user defined analytical transfer function */\n BLRmodel_size = num_params_MyTransfun2d * sizeof(double);\n set_blr_range_model = set_par_range_mytransfun;\n break;\n case 0:\n BLRmodel_size = num_params_MyBLRmodel2d * sizeof(double);\n set_blr_range_model = set_blr_range_mymodel;\n break;\n case 1:\n BLRmodel_size = sizeof(BLRmodel1);\n set_blr_range_model = set_blr_range_model1;\n break;\n case 2:\n BLRmodel_size = sizeof(BLRmodel2);\n set_blr_range_model = set_blr_range_model2;\n break;\n case 3:\n BLRmodel_size = sizeof(BLRmodel3);\n set_blr_range_model = set_blr_range_model3;\n break;\n case 4:\n BLRmodel_size = sizeof(BLRmodel4);\n set_blr_range_model = set_blr_range_model4;\n break;\n case 5:\n BLRmodel_size = sizeof(BLRmodel5);\n set_blr_range_model = set_blr_range_model5;\n break;\n case 6:\n BLRmodel_size = sizeof(BLRmodel6);\n set_blr_range_model = set_blr_range_model6;\n break;\n case 7:\n BLRmodel_size = sizeof(BLRmodel7);\n set_blr_range_model = set_blr_range_model7;\n break;\n case 8:\n BLRmodel_size = sizeof(BLRmodel8);\n set_blr_range_model = set_blr_range_model8;\n break;\n case 9:\n BLRmodel_size = sizeof(BLRmodel9);\n set_blr_range_model = set_blr_range_model9;\n break;\n default:\n BLRmodel_size = sizeof(BLRmodel1);\n set_blr_range_model = set_blr_range_model1;\n break;\n }\n\n#ifdef SA\n if(parset.flag_dim > 2 || parset.flag_dim < 0)\n {\n num_params_sa_extpar = sizeof(SAExtPar)/sizeof(double);\n switch(parset.flag_sa_blrmodel)\n {\n case 0:\n SABLRmodel_size = num_params_MyBLRmodel2d * sizeof(double);\n set_sa_blr_range_model = set_sa_blr_range_mymodel;\n break;\n case 1:\n SABLRmodel_size = sizeof(SABLRmodel1);\n set_sa_blr_range_model = set_sa_blr_range_model1;\n break;\n case 2:\n SABLRmodel_size = sizeof(SABLRmodel2);\n set_sa_blr_range_model = set_sa_blr_range_model2;\n break;\n case 3:\n SABLRmodel_size = sizeof(SABLRmodel3);\n set_sa_blr_range_model = set_sa_blr_range_model3;\n break;\n case 4:\n SABLRmodel_size = sizeof(SABLRmodel4);\n set_sa_blr_range_model = set_sa_blr_range_model4;\n break;\n case 5:\n SABLRmodel_size = sizeof(SABLRmodel5);\n set_sa_blr_range_model = set_sa_blr_range_model5;\n break;\n case 6:\n SABLRmodel_size = sizeof(SABLRmodel6);\n set_sa_blr_range_model = set_sa_blr_range_model6;\n break;\n case 7:\n SABLRmodel_size = sizeof(SABLRmodel7);\n set_sa_blr_range_model = set_sa_blr_range_model7;\n break;\n case 8:\n SABLRmodel_size = sizeof(SABLRmodel8);\n set_sa_blr_range_model = set_sa_blr_range_model8;\n break;\n case 9:\n SABLRmodel_size = sizeof(SABLRmodel9);\n set_sa_blr_range_model = set_sa_blr_range_model9;\n break;\n default:\n SABLRmodel_size = sizeof(SABLRmodel1);\n set_sa_blr_range_model = set_sa_blr_range_model1;\n break;\n }\n }\n#endif \n \n if(parset.flag_dim != 3)\n {\n /* set maximum continuum point */\n n_con_max = parset.n_con_recon;\n if(parset.flag_dim >=-1)\n {\n if(n_con_data > n_con_max)\n n_con_max = n_con_data;\n }\n }\n\n allocate_memory();\n\n /* initialize GSL */\n gsl_T = gsl_rng_default;\n gsl_r = gsl_rng_alloc (gsl_T);\n\n#ifndef Debug \n if(parset.flag_rng_seed != 1)\n {\n gsl_rng_set(gsl_r, time(NULL)+thistask+1350); \n }\n else\n {\n gsl_rng_set(gsl_r, parset.rng_seed+thistask+1350); \n }\n#else\n if(parset.flag_rng_seed != 1)\n {\n gsl_rng_set(gsl_r, 6666+thistask+1350); \n printf(\"# debugging, task %d brains random seed %d.\\n\", thistask, 6666+thistask+1350);\n }\n else\n {\n gsl_rng_set(gsl_r, parset.rng_seed+thistask+1350); \n }\n#endif\n\n /* default BH mass range */\n mass_range[0] = 1.0;\n mass_range[1] = 1.0e4;\n\n /* default rcloud_max_set */\n rcloud_max_set = 1.0e6;\n \n /* not RM */\n if(parset.flag_dim != 3)\n {\n gsl_acc = gsl_interp_accel_alloc();\n gsl_linear = gsl_interp_alloc(gsl_interp_linear, parset.n_con_recon);\n\n if(parset.flag_dim >=-1)\n {\n /* set Larr_data */\n for(i=0;i Tcon_data[i] - Tcon_data[i-1])\n Tcad_data = Tcon_data[i] - Tcon_data[i-1];\n }\n }\n \n if(parset.flag_dim > 0 || parset.flag_dim == -1)\n { \n /* set cadence and time span of data */\n Tspan_data_con = (Tcon_data[n_con_data -1] - Tcon_data[0]);\n Tspan_data = (Tline_data[n_line_data -1] - Tcon_data[0]);\n if(Tspan_data < 0.0)\n {\n if(thistask == roottask)\n {\n printf(\"# Incorrect epochs in continuum and line, please check the input data.\\n\");\n exit(0);\n }\n }\n Tcad_data = Tspan_data;\n for(i=1; i< n_con_data; i++)\n {\n if(Tcad_data > Tcon_data[i] - Tcon_data[i-1])\n Tcad_data = Tcon_data[i] - Tcon_data[i-1];\n }\n for(i=1; i< n_line_data; i++)\n {\n if(Tcad_data > Tline_data[i] - Tline_data[i-1])\n Tcad_data = Tline_data[i] - Tline_data[i-1];\n }\n \n /* set mediate time of continuum data */\n Tmed_data = 0.5*(Tcon_data[0] + Tcon_data[n_con_data-1]);\n \n for(i=0; i 0.0)\n {\n DT = fmax(DT, Tline_data[0] - parset.rcloud_max*2.0);\n }\n else if(parset.time_back > 0.0) /* neglect when parset.rcloud_max is set */\n { \n DT = fmax(DT, Tcon_data[0] - parset.time_back);\n }\n time_back_set = Tcon_data[0] - DT;\n \n /* set the range of cloud radial distribution */\n rcloud_min_set = 0.0;\n rcloud_max_set = Tspan_data/2.0;\n \n /* rcloud_max should smaller than (Tl0 - Tc0)/2 */\n rcloud_max_set = fmin( rcloud_max_set, (Tline_data[0] - Tcon_data[0] + time_back_set)/2.0 );\n \n if(parset.rcloud_max > 0.0)\n rcloud_max_set = fmin(rcloud_max_set, parset.rcloud_max);\n\n /* check whether n_con_recon is appropriate */\n double med_cad, med_cad_recon;\n //med_cad = get_mediate_cad(Tcon_data, n_con_data);\n med_cad = (Tcon_data[n_con_data-1] - Tcon_data[0])/(n_con_data -1);\n med_cad_recon = (Tcon_data[n_con_data-1] - Tcon_data[0] + time_back_set)/(parset.n_con_recon-1);\n if(med_cad_recon > 1.05*med_cad)\n {\n if(thistask == roottask)\n {\n printf(\"# Too small NConRecon.\\n\" \n \"# Better to change it to %d or set RCloudMax/TimeBack to smaller than %f/%f.\\n\", \n (int)(parset.n_con_recon * med_cad_recon/med_cad), \n (Tline_data[0] - Tcon_data[0] + time_back_set)/2.0 ,time_back_set);\n printf(\"\\e[1;35m\" \"# Use '-f' option in command line if want to ignore this check.\\n\" \"\\e[0m\");\n }\n if(parset.flag_force_run != 1)\n {\n exit(0);\n }\n }\n }\n\n if(thistask == roottask && parset.flag_dim >=-1)\n {\n printf(\"rcloud_min_max_set: %f %f\\n\", rcloud_min_set, rcloud_max_set);\n }\n \n // response range A and Ag\n resp_range[0][0] = log(0.1);\n resp_range[0][1] = log(10.0);\n \n resp_range[1][0] = -1.0;\n resp_range[1][1] = 3.0;\n\n /* set the range of continuum variation */\n var_range_model[0][0] = log(1.0); /* systematic error in continuum */\n var_range_model[0][1] = log(1.0+10.0);\n \n var_range_model[1][0] = -15.0; /* log(sigma) */\n var_range_model[1][1] = -1.0; \n \n var_range_model[2][0] = log(Tcad_data); /* log(tau) */\n var_range_model[2][1] = log(Tspan_data); \n \n var_range_model[3][0] = -10.0; /* mean value or trend parameter values */\n var_range_model[3][1] = 10.0; \n \n for(i=0; i 1)\n {\n if(parset.flag_narrowline == 2) /* Gaussian prior */\n {\n nlr_range_model[0][0] = -10.0;\n nlr_range_model[0][1] = 10.0;\n \n nlr_prior_model[0] = GAUSSIAN;\n }\n else\n {\n nlr_range_model[0][0] = log(1.0e-1); /* logrithmic prior */\n nlr_range_model[0][1] = log(1.0e4);\n \n nlr_prior_model[0] = UNIFORM;\n }\n \n nlr_range_model[1][0] = -10.0;\n nlr_range_model[1][1] = 10.0;\n \n nlr_prior_model[1] = GAUSSIAN;\n \n nlr_range_model[2][0] = -10.0;\n nlr_range_model[2][1] = 10.0;\n \n nlr_prior_model[2] = GAUSSIAN;\n }\n \n // range for systematic error\n sys_err_line_range[0] = log(1.0);\n sys_err_line_range[1] = log(1.0+10.0);\n \n set_blr_range_model();\n \n }\n \n#ifdef SA\n /* SA */\n if(parset.flag_dim > 2)\n {\n set_sa_blr_range_model();\n\n sa_extpar_range[0][0] = log(100.0); /* DA */\n sa_extpar_range[0][1] = log(1000.0); \n\n sa_extpar_range[1][0] = 0.0; /* PA */\n sa_extpar_range[1][1] = 180.0;\n\n sa_extpar_range[2][0] = log(0.5); /* FA */\n sa_extpar_range[2][1] = log(2.0);\n\n sa_extpar_range[3][0] = -(wave_sa_data[1]-wave_sa_data[0]); /* CO */\n sa_extpar_range[3][1] = (wave_sa_data[1]-wave_sa_data[0]);\n }\n#endif \n}\n\n/*!\n * This function allocates memory for variables used throughout the code. \n */\nvoid allocate_memory()\n{\n int i;\n\n if(parset.flag_dim != 3)\n {\n Tcon = malloc(parset.n_con_recon * sizeof(double));\n Fcerrs = malloc(parset.n_con_recon * sizeof(double));\n \n PSmat = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));\n //PNmat = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));\n USmat = malloc(parset.n_con_recon * n_con_data * sizeof(double));\n PSmat_data = malloc(n_con_data * n_con_data * sizeof(double));\n //PNmat_data = malloc(n_con_data * n_con_data * sizeof(double));\n PCmat_data = malloc(n_con_data * n_con_data * sizeof(double));\n IPCmat_data = malloc(n_con_data * n_con_data * sizeof(double));\n PQmat = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));\n PEmat1 = malloc(parset.n_con_recon * n_con_data * sizeof(double));\n PEmat2 = malloc(parset.n_con_recon * parset.n_con_recon * sizeof(double));\n \n blr_range_model = malloc(BLRmodel_size/sizeof(double) * sizeof(double *));\n for(i=0; i 2 || parset.flag_dim < 0)\n {\n sa_extpar_range = malloc(num_params_sa_extpar * sizeof(double *));\n for(i=0; i 2 || parset.flag_dim < 0)\n {\n for(i=0; i 0.0)\n {\n Fline_data[i] *= line_scale;\n Flerrs_data[i] *= line_scale;\n }\n\n if(parset.flag_dim==2 || parset.flag_dim == -1 || parset.flag_dim == 5)\n for(j=0; j 0.0)\n {\n Fline2d_data[i*n_vel_data + j] *= line_scale;\n Flerrs2d_data[i*n_vel_data + j] *= line_scale;\n } \n } \n }\n line_error_mean *= line_scale;\n\n if( (parset.flag_dim==2 || parset.flag_dim == -1 || parset.flag_dim == 5) && parset.flag_narrowline!=0)\n {\n parset.flux_narrowline *= line_scale;\n parset.flux_narrowline_err *= line_scale;\n }\n return;\n}\n\n/*!\n * This function copes with parameter fixing.\\n\n * Only fix BLR model parameters. \n */\nvoid set_par_fix_blrmodel()\n{\n int i;\n char *pstr;\n \n npar_fix = 0;\n\n if(thistask == roottask)\n {\n pstr = parset.str_par_fix_val;\n // set the default value if not provided.\n for(i=strlen(parset.str_par_fix); i\n#include \n#include \n#include \n#include \n#include \"parmt_config.h\"\n#include \"compearth.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#include \n#include \n#include \n#else\n#include \n#include \n#endif\n#include \"iscl/array/array.h\"\n#include \"iscl/linalg/linalg.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/statistics/statistics.h\"\n#include \"iscl/sorting/sorting.h\"\n\n\nstatic double median_sorted_array(int n, const double *__restrict x);\nstatic int setG64f(const int npts,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n double *__restrict__ G);\n\n#define LDG 8\n\nint parmt_computeL1Magnitude64f(const int ldm,\n const int nobs,\n const int nmtSolve,\n const int maxit, const double eps,\n const double tol, \n const int *__restrict__ signalPtr,\n const int *__restrict__ lags,\n const int *__restrict__ mtPtr,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n const double *__restrict__ mts,\n const double *__restrict__ d,\n double *__restrict__ mags)\n{\n const char *fcnm = \"parmt_computeL1Magnitude64f\\0\";\n double *G, *est, *obs, *wts, xmag;\n double m6[8] __attribute__((aligned(64))); \n int i, i1, i2, ierr, imt, jmt, k, maxlag, nptsAll, nptsPad;\n bool luseLag;\n const double p = 1.0;\n const double one = 1.0;\n const double zero = 0.0;\n nptsAll = signalPtr[nobs];\n if (nobs < 1)\n {\n printf(\"%s: Error no observations\\n\", fcnm);\n return -1;\n }\n // Get the max number of lags\n maxlag = 0;\n luseLag = false;\n if (lags != NULL)\n {\n luseLag = true;\n maxlag = lags[array_absArgmax32i(nobs, lags, &ierr)];\n }\n if (maxlag == 0){luseLag = false;}\n nptsPad = nptsAll + nobs*maxlag;\n G = memory_calloc64f(nptsPad*LDG);\n obs = memory_calloc64f(nptsPad);\n est = memory_calloc64f(nptsPad);\n wts = memory_calloc64f(nptsPad);\n // Insert the Green's functions and data into the moment tensor matrix\n if (!luseLag)\n {\n for (k=0; k average middle two elements\n if (fmod(n, 2) == 0)\n {\n xmed = half*(x[n2-1] + x[n2]);\n }\n // Median is middle element\n else\n {\n xmed = x[n2];\n }\n return xmed;\n}\n\nstatic int setG64f(const int npts,\n const double *__restrict__ Gxx,\n const double *__restrict__ Gyy,\n const double *__restrict__ Gzz,\n const double *__restrict__ Gxy,\n const double *__restrict__ Gxz,\n const double *__restrict__ Gyz,\n double *__restrict__ G)\n{\n const char *fcnm = \"setG64f\\0\";\n int i;\n bool lalign;\n if (Gxx == NULL || Gyy == NULL || Gzz == NULL || Gxy == NULL ||\n Gxz == NULL || G == NULL || npts < 1)\n \n {\n if (Gxx == NULL){printf(\"%s: Error Gxx is NULL\\n\", fcnm);}\n if (Gyy == NULL){printf(\"%s: Error Gyy is NULL\\n\", fcnm);}\n if (Gzz == NULL){printf(\"%s: Error Gzz is NULL\\n\", fcnm);}\n if (Gxy == NULL){printf(\"%s: Error Gxy is NULL\\n\", fcnm);}\n if (Gxz == NULL){printf(\"%s: Error Gxz is NULL\\n\", fcnm);}\n if (Gyz == NULL){printf(\"%s: ERror Gyz is NULL\\n\", fcnm);}\n if (npts < 1)\n {\n printf(\"%s: No points in Green's functions\\n\", fcnm);\n }\n return -1;\n }\n lalign = true;\n if (memory_isAligned(Gxx, 64) != 1 || memory_isAligned(Gyy, 64) != 1 ||\n memory_isAligned(Gzz, 64) != 1 || memory_isAligned(Gxy, 64) != 1 ||\n memory_isAligned(Gxz, 64) != 1 || memory_isAligned(Gyz, 64) != 1 ||\n memory_isAligned(G, 64) != 1)\n {\n lalign = false;\n }\n if (lalign)\n {\n #pragma omp simd aligned(G, Gxx, Gyy, Gzz, Gxy, Gxz, Gyz: 64)\n for (i=0; i\n#include \n#include \n#include \n#include \n\ngsl_multiroot_fdfsolver *\ngsl_multiroot_fdfsolver_alloc (const gsl_multiroot_fdfsolver_type * T, \n size_t n)\n{\n int status;\n\n gsl_multiroot_fdfsolver * s;\n\n s = (gsl_multiroot_fdfsolver *) malloc (sizeof (gsl_multiroot_fdfsolver));\n\n if (s == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for multiroot solver struct\",\n GSL_ENOMEM, 0);\n }\n\n s->x = gsl_vector_calloc (n);\n\n if (s->x == 0) \n {\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n }\n\n s->f = gsl_vector_calloc (n);\n\n if (s->f == 0) \n {\n gsl_vector_free (s->x);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for f\", GSL_ENOMEM, 0);\n }\n\n s->J = gsl_matrix_calloc (n,n);\n\n if (s->J == 0) \n {\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for g\", GSL_ENOMEM, 0);\n }\n\n s->dx = gsl_vector_calloc (n);\n\n if (s->dx == 0) \n {\n gsl_matrix_free (s->J);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n free (s);\n GSL_ERROR_VAL (\"failed to allocate space for dx\", GSL_ENOMEM, 0);\n }\n\n s->state = malloc (T->size);\n\n if (s->state == 0)\n {\n gsl_vector_free (s->dx);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n gsl_matrix_free (s->J);\n free (s); /* exception in constructor, avoid memory leak */\n \n GSL_ERROR_VAL (\"failed to allocate space for multiroot solver state\",\n GSL_ENOMEM, 0);\n }\n\n s->type = T ;\n\n status = (s->type->alloc)(s->state, n);\n\n if (status != GSL_SUCCESS)\n {\n free (s->state);\n gsl_vector_free (s->dx);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n gsl_matrix_free (s->J);\n free (s); /* exception in constructor, avoid memory leak */\n \n GSL_ERROR_VAL (\"failed to set solver\", status, 0);\n }\n \n s->fdf = NULL;\n \n return s;\n}\n\nint\ngsl_multiroot_fdfsolver_set (gsl_multiroot_fdfsolver * s, \n gsl_multiroot_function_fdf * f, \n const gsl_vector * x)\n{\n if (s->x->size != f->n)\n {\n GSL_ERROR (\"function incompatible with solver size\", GSL_EBADLEN);\n }\n \n if (x->size != f->n) \n {\n GSL_ERROR (\"vector length not compatible with function\", GSL_EBADLEN);\n } \n \n s->fdf = f;\n gsl_vector_memcpy(s->x,x);\n \n return (s->type->set) (s->state, s->fdf, s->x, s->f, s->J, s->dx);\n}\n\nint\ngsl_multiroot_fdfsolver_iterate (gsl_multiroot_fdfsolver * s)\n{\n return (s->type->iterate) (s->state, s->fdf, s->x, s->f, s->J, s->dx);\n}\n\nvoid\ngsl_multiroot_fdfsolver_free (gsl_multiroot_fdfsolver * s)\n{\n RETURN_IF_NULL (s);\n (s->type->free) (s->state);\n free (s->state);\n gsl_vector_free (s->dx);\n gsl_vector_free (s->x);\n gsl_vector_free (s->f);\n gsl_matrix_free (s->J);\n free (s);\n}\n\nconst char *\ngsl_multiroot_fdfsolver_name (const gsl_multiroot_fdfsolver * s)\n{\n return s->type->name;\n}\n\ngsl_vector *\ngsl_multiroot_fdfsolver_root (const gsl_multiroot_fdfsolver * s)\n{\n return s->x;\n}\n\ngsl_vector *\ngsl_multiroot_fdfsolver_dx (const gsl_multiroot_fdfsolver * s)\n{\n return s->dx;\n}\n\ngsl_vector *\ngsl_multiroot_fdfsolver_f (const gsl_multiroot_fdfsolver * s)\n{\n return s->f;\n}\n", "meta": {"hexsha": "82db3b46289fbd834ed708027af855f28e09e0c9", "size": 4282, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-an/multiroots/fdfsolver.c", "max_stars_repo_name": "juandesant/astrometry.net", "max_stars_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_stars_repo_licenses": ["Net-SNMP", "Xnet"], "max_stars_count": 460.0, "max_stars_repo_stars_event_min_datetime": "2015-01-06T13:20:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T00:37:55.000Z", "max_issues_repo_path": "gsl-an/multiroots/fdfsolver.c", "max_issues_repo_name": "juandesant/astrometry.net", "max_issues_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_issues_repo_licenses": ["Net-SNMP", "Xnet"], "max_issues_count": 208.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T20:26:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:21:34.000Z", "max_forks_repo_path": "gsl-an/multiroots/fdfsolver.c", "max_forks_repo_name": "juandesant/astrometry.net", "max_forks_repo_head_hexsha": "47849f0443b890c4a875360f881d2e60d1cba630", "max_forks_repo_licenses": ["Net-SNMP", "Xnet"], "max_forks_count": 173.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T18:01:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:27:04.000Z", "avg_line_length": 24.0561797753, "max_line_length": 81, "alphanum_fraction": 0.6193367585, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.29863342676099575}} {"text": "#include \n#include \n#include \n#include \n#include \n\n\n/*\n--------------------------------------------------------------------|\n ------------------------------ |\n | LAPACKE | |\n ------------------------------ |\n--------------------------------------------------------------------|\n*/\n\nvoid dgetrf_(int* M, int *N, double* A, int* lda, int* IPIV, int* INFO);\nvoid dgetri_(int* N, double* A, int* lda, int* IPIV, double* WORK, int* lwork, int* INFO);\n\n\n/*\n--------------------------------------------------------------------|\n ------------------------------ |\n | INIT FC | |\n ------------------------------ |\n--------------------------------------------------------------------|\n*/\n\n\nERL_NIF_TERM atom_nok;\nERL_NIF_TERM atom_true;\nERL_NIF_TERM atom_false;\nERL_NIF_TERM atom_matrix;\n\nErlNifResourceType *MULT_YIELDING_ARG = NULL;\n\nint load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info){\n atom_nok = enif_make_atom(env, \"nok\\0\");\n atom_true = enif_make_atom(env, \"true\\0\");\n atom_false = enif_make_atom(env, \"false\\0\");\n atom_matrix = enif_make_atom(env, \"matrix\\0\");\n return 0;\n}\n\nint upgrade(ErlNifEnv* caller_env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info){\n return 0;\n}\n\n//Gives easier access to an ErlangBinary containing a matrix.\ntypedef struct{\n int n_rows;\n int n_cols;\n \n //Content of the matrix, in row major format.\n double* content;\n\n //Erlang binary containing the matrix.\n ErlNifBinary bin;\n} Matrix;\n\n\n//Access asked coordinates of matrix\ndouble* matrix_at(int col, int row, Matrix m){\n return &m.content[row*m.n_cols + col];\n}\n\n//Allocates memory space of for matrix of dimensions n_rows, n_cols.\n//The matrix_content can be modified, until a call to array_to_erl.\n//Matrix content is stored in row major format.\nMatrix matrix_alloc(int n_rows, int n_cols){\n ErlNifBinary bin;\n\n enif_alloc_binary(sizeof(double)*n_rows*n_cols, &bin);\n\n Matrix matrix;\n matrix.n_cols = n_cols;\n matrix.n_rows = n_rows;\n matrix.bin = bin;\n matrix.content = (double*) bin.data;\n\n return matrix;\n}\n\n//Creates a duplicate of a matrix.\n//This duplicate can be modified until uploaded.\nMatrix matrix_dup(Matrix m){\n Matrix d = matrix_alloc(m.n_rows, m.n_cols);\n memcpy(d.content, m.content, d.bin.size);\n return d;\n}\n\n//Free an allocated matrix that was not sent back to Erlang.\nvoid matrix_free(Matrix m){\n enif_release_binary(&m.bin);\n}\n\n//Constructs a matrix erlang term.\n//No modifications can be made afterwards to the matrix.\nERL_NIF_TERM matrix_to_erl(ErlNifEnv* env, Matrix m){\n ERL_NIF_TERM term = enif_make_binary(env, &m.bin);\n return enif_make_tuple4(env, atom_matrix, enif_make_int(env,m.n_rows), enif_make_int(env,m.n_cols), term);\n}\n\nint enif_is_matrix(ErlNifEnv* env, ERL_NIF_TERM term){\n int arity;\n const ERL_NIF_TERM* content;\n\n if(!enif_is_tuple(env, term))\n return 0;\n\n enif_get_tuple(env, term, &arity, &content);\n if(arity != 4)\n return 0;\n \n if(content[0] != atom_matrix\n || !enif_is_number(env, content[1])\n || !enif_is_number(env, content[2])\n || !enif_is_binary(env, content[3]))\n \n return 0;\n return 1;\n}\n\n//Reads an erlang term as a matrix.\n//As such, no modifications can be made to the red matrix.\n//Returns true if it was possible to read a matrix, false otherwise\nint enif_get_matrix(ErlNifEnv* env, ERL_NIF_TERM term, Matrix *dest){\n \n int arity;\n const ERL_NIF_TERM* content;\n\n if(!enif_is_tuple(env, term))\n return 0;\n\n enif_get_tuple(env, term, &arity, &content);\n if(arity != 4)\n return 0;\n \n if(content[0] != atom_matrix\n || !enif_get_int(env, content[1], &dest->n_rows)\n || !enif_get_int(env, content[2], &dest->n_cols)\n || !enif_inspect_binary(env, content[3], &dest->bin))\n {\n return 0;\n }\n\n dest->content = (double*) (dest->bin.data); \n return 1;\n}\n\n//Used to translate at once a number of ERL_NIF_TERM.\n//Data types are inferred via content of format string:\n// n: number (int or double) translated to double.\n// m: matrix\n// i: int\nint enif_get(ErlNifEnv* env, const ERL_NIF_TERM* erl_terms, const char* format, ...){\n va_list valist;\n va_start(valist, format);\n int valid = 1;\n\n while(valid && *format != '\\0'){\n switch(*format++){\n case 'n':\n //Read a number as a double.\n ;\n double *d = va_arg(valist, double*);\n int i;\n if(!enif_get_double(env, *erl_terms, d))\n if(enif_get_int(env, *erl_terms, &i))\n *d = (double) i;\n else valid = 0;\n break;\n\n case 'm':\n //Reads a matrix.\n valid = enif_get_matrix(env, *erl_terms, va_arg(valist, Matrix*));\n break;\n \n case 'i':\n //Reads an int.\n valid = enif_get_int(env, *erl_terms, va_arg(valist, int*));\n break;\n \n default:\n //Unknown type... give an error.\n valid = 0;\n break;\n }\n erl_terms ++;\n }\n\n va_end(valist);\n return valid;\n}\n\n\n//----------------------------------------------------------------------------------------------------|\n// ------------------------------------------ |\n// | NIFS | |\n// ------------------------------------------ |\n//----------------------------------------------------------------------------------------------------|\n\n\n//@arg 0: List of Lists of numbers.\n//@return: Matrix of dimension\nERL_NIF_TERM nif_matrix(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n unsigned n_rows, line_length, dest = 0, n_cols = -1;\n ERL_NIF_TERM list = argv[0], row, elem;\n Matrix m;\n\n //Reading incoming matrix.\n if(!enif_get_list_length(env, list, &n_rows) && n_rows > 0)\n return enif_make_badarg(env);\n\n for(int i = 0; enif_get_list_cell(env, list, &row, &list); i++){\n if(!enif_get_list_length(env, row, &line_length)) \n return enif_make_badarg(env);\n \n if(n_cols == -1){\n //Allocate binary, make matrix accessor.\n n_cols = line_length;\n m = matrix_alloc(n_rows,n_cols);\n }\n\n if(n_cols != line_length)\n return enif_make_badarg(env);\n\n for(int j = 0; enif_get_list_cell(env, row, &elem, &row); j++){\n if(!enif_get_double(env, elem, &m.content[dest])){\n int i;\n if(enif_get_int(env, elem, &i)){\n m.content[dest] = (double) i;\n }\n else{\n return enif_make_badarg(env);\n }\n }\n dest++;\n }\n }\n\n return matrix_to_erl(env, m);\n}\n\n#define PRECISION 10\n\n//Used for debug purpose.\nvoid debug_write(char info[]){\n FILE* fp = fopen(\"debug.txt\", \"a\");\n fprintf(fp, info);\n fprintf(fp, \"\\n\");\n fclose(fp);\n}\n\nvoid debug_write_matrix(Matrix m){\n char *content = enif_alloc(sizeof(char)*((2*m.n_cols-1)*m.n_rows*PRECISION + m.n_rows*2 + 3));\n content[0] = '[';\n content[1] = '\\0';\n char converted[PRECISION];\n\n for(int i=0; i= matrix.n_rows || n < 0 || n >= matrix.n_cols)\n return enif_make_badarg(env);\n\n int index = m*matrix.n_cols+n;\n return enif_make_double(env, matrix.content[index]);\n}\n\nERL_NIF_TERM nif_at(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){\n int n;\n Matrix matrix;\n\n if(!enif_get(env, argv, \"mi\", &matrix, &n))\n return enif_make_badarg(env);\n n--;\n\n if( n < 0 || n >= matrix.n_cols * matrix.n_rows)\n return enif_make_badarg(env);\n\n return enif_make_double(env, matrix.content[n]);\n}\n\n//Matrix to flattened list of ints\nERL_NIF_TERM nif_mtfli(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){\n Matrix M;\n if(!enif_get(env, argv, \"m\", &M)){\n return enif_make_badarg(env);\n }\n\n int n_elems = M.n_cols * M.n_rows;\n ERL_NIF_TERM *arr = enif_alloc(sizeof(ERL_NIF_TERM)*n_elems);\n for(int i = 0; i 1e-6)\n return 0;\n }\n return 1;\n}\n\n//@arg 0: Array.\n//@arg 1: Array.\n//@return: true if arrays share content, false if they have different content || size..\nERL_NIF_TERM nif_equals(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n Matrix a,b;\n\n if(!enif_get(env, argv, \"mm\", &a, &b))\n return atom_false;\n\n //Compare number of columns and rows\n if((a.n_cols != b.n_cols || a.n_rows != b.n_rows))\n return atom_false;\n\n //Compare content of arrays\n if(!equal_ad(a.content, b.content, a.n_cols*a.n_rows))\n return atom_false;\n \n return atom_true;\n}\n\n\n//@arg 0: int.\n//@arg 1: Array.\n//@return: returns an array, containing requested row.\nERL_NIF_TERM nif_row(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){\n int row_req;\n Matrix matrix;\n if(!enif_get(env, argv, \"im\", &row_req, &matrix))\n return enif_make_badarg(env);\n\n row_req--;\n if(row_req<0 || row_req >= matrix.n_rows)\n return enif_make_badarg(env);\n\n Matrix row = matrix_alloc(1, matrix.n_cols);\n memcpy(row.content, matrix.content + (row_req * matrix.n_cols), matrix.n_cols*sizeof(double));\n\n return matrix_to_erl(env, row);\n}\n\n\n//@arg 0: int.\n//@arg 1: Array.\n//@return: returns an array, containing requested col.\nERL_NIF_TERM nif_col(ErlNifEnv * env, int argc, const ERL_NIF_TERM argv[]){\n int col_req;\n Matrix matrix;\n if(!enif_get(env, argv, \"im\", &col_req, &matrix))\n return enif_make_badarg(env);\n\n col_req--; \n if(col_req<0 || col_req >= matrix.n_cols)\n return enif_make_badarg(env);\n\n\n Matrix col = matrix_alloc(matrix.n_rows, 1);\n\n for(int i = 0; i < matrix.n_rows; i++){\n col.content[i] = matrix.content[i * matrix.n_rows + col_req];\n }\n\n return matrix_to_erl(env, col);\n}\n\n\n//@arg 0: int.\n//@arg 1: int.\n//@return: empty Matrix of requested dimension..\nERL_NIF_TERM nif_zeros(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n int m,n;\n if(!enif_get(env, argv, \"ii\", &m, &n))\n return enif_make_badarg(env);\n\n Matrix a = matrix_alloc(m,n);\n memset(a.content, 0, sizeof(double)*m*n);\n return matrix_to_erl(env, a);\n}\n\n//@arg 0: int.\n//@arg 1: int.\n//@return: empty matrix of dimension [arg 0, arg 1]..\nERL_NIF_TERM nif_eye(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n int m;\n if(!enif_get_int(env, argv[0], &m))\n return enif_make_badarg(env);\n \n if(m <= 0)\n return enif_make_badarg(env);\n\n Matrix a = matrix_alloc(m,m);\n memset(a.content, 0, sizeof(double)*m*m);\n for(int i = 0; i 0 || INFO2 > 0){\n result = enif_raise_exception(env, enif_make_atom(env, \"nif_inv: could not invert singular matrix.\"));\n matrix_free(inv);\n }\n else if(INFO1 < 0 || INFO2 < 0){\n result = enif_raise_exception(env, enif_make_atom(env, \"nif_inv: LAPACK error.\"));\n matrix_free(inv);\n }\n else result = matrix_to_erl(env, inv);\n\n\n return result;\n}\n\n//----------------------------------------------------------------------------------------------------|\n// ------------------------------------------ |\n// | CBLAS | |\n// ------------------------------------------ |\n//----------------------------------------------------------------------------------------------------|\n//Some CBLAS wrappers.\n\n//Calculates the norm of input vector/matrix, aka the square root of the sum of its composants.\nERL_NIF_TERM nif_dnrm2(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n Matrix x;\n\n if(!enif_get(env, argv, \"m\", &x)){\n return enif_make_badarg(env);\n }\n\n double result = cblas_dnrm2(x.n_cols*x.n_rows, x.content, 1);\n\n return enif_make_double(env, result);\n}\n\n\n//Performs blas_ddot\n//Input: two vectors / matrices\nERL_NIF_TERM nif_ddot(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n Matrix x,y;\n\n if(!enif_get(env, argv, \"mm\", &x, &y)){\n return enif_make_badarg(env);\n }\n\n int n = fmin(x.n_rows*x.n_cols, y.n_rows*y.n_cols);\n if(n <= 0){\n return enif_make_badarg(env);\n }\n\n double result = cblas_ddot(n, x.content, 1, y.content, 1);\n\n return enif_make_double(env, result);\n}\n\n\n//Performs blas_daxpy\n//Input: a number, vectors X and Y\n//Output: a vector of same dimension then Y, containing alpha X + Y\n//------------------------------------------------------------------------\nERL_NIF_TERM nif_daxpy(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n Matrix x,y;\n int n;\n double alpha;\n\n if(!enif_get(env, argv, \"inmm\", &n, &alpha, &x, &y)){\n return enif_make_badarg(env);\n }\n \n if(fmin(x.n_rows, x.n_cols) * fmin(y.n_rows, y.n_cols) != 1){\n //We are not using vectors...\n return enif_make_badarg(env);\n }\n\n Matrix ny = matrix_dup(y);\n\n cblas_daxpy(n, alpha, x.content, 1, ny.content, 1);\n\n return matrix_to_erl(env, ny);\n}\n\n// Arguments: alpha, A, x, beta, y\n// Performs alpha*A*x + beta*y.\n// alpha, beta are numbers\n// A, x, y are matrices (x and y being vectors)\n// x and y are expected to have a length of A.n_cols\nERL_NIF_TERM nif_dgemv(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n Matrix A,x,y;\n double alpha, beta;\n\n if(!enif_get(env, argv, \"nmmnm\", &alpha, &A, &x, &beta, &y)){\n enif_make_badarg(env);\n }\n\n //Check dimensions compatibility\n int vec_length = fmin(fmax(x.n_cols, x.n_rows), fmax(y.n_cols, y.n_rows));\n if(vec_length < A.n_cols || fmin(x.n_cols, x.n_rows) != 1 || fmin(y.n_cols, y.n_rows) != 1){\n enif_make_badarg(env);\n }\n\n Matrix ny = matrix_dup(y);\n\n cblas_dgemv(CblasRowMajor, CblasNoTrans, A.n_rows, A.n_cols, alpha, A.content, A.n_rows, x.content, 1, beta, ny.content, 1);\n\n return matrix_to_erl(env, ny);\n}\n\n\n\n//Arguments: double alpha, matrix A, matrix B, double beta, matrix C\nERL_NIF_TERM nif_dgemm(ErlNifEnv *env, int argc, const ERL_NIF_TERM argv[]){\n Matrix A, B;\n double alpha = 1.0;\n double beta = 0.0;\n\n if(!enif_get(env, argv, \"mm\", &A, &B)\n || A.n_cols != B.n_rows){\n\n return enif_make_badarg(env);\n }\n \n Matrix C = matrix_alloc(A.n_rows, B.n_cols);\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n A.n_rows, B.n_cols, A.n_cols,\n alpha, A.content, A.n_cols, B.content, B.n_rows, \n 1.0, C.content, C.n_cols);\n\n return matrix_to_erl(env, C);\n}\n\nErlNifFunc nif_funcs[] = {\n {\"matrix\", 1, nif_matrix},\n {\"get\", 3, nif_get},\n {\"at\", 2, nif_at},\n {\"mtfli\", 1, nif_mtfli},\n {\"mtfl\", 1, nif_mtfl},\n {\"equals\", 2, nif_equals},\n {\"row\", 2, nif_row},\n {\"col\", 2, nif_col},\n {\"zeros\", 2, nif_zeros},\n {\"eye\", 1, nif_eye},\n {\"mult\", 2, nif_mult},\n {\"add\", 2, nif_add},\n {\"sub\", 2, nif_sub},\n {\"divide\", 2, nif_divide},\n {\"transpose\", 1, nif_transpose},\n {\"inv\", 1, nif_inv},\n \n //--- BLAS----------\n {\"nrm2\", 1, nif_dnrm2},\n {\"vec_dot\", 2, nif_ddot},\n {\"dot\", 2, nif_dgemm}\n};\n\nERL_NIF_INIT(numerl, nif_funcs, load, NULL, upgrade, NULL)", "meta": {"hexsha": "d0d9cb3f4edeb8b25f91f5f65e559506c3295ed2", "size": 22085, "ext": "c", "lang": "C", "max_stars_repo_path": "c_src/numerl.c", "max_stars_repo_name": "tanguyl/numerl", "max_stars_repo_head_hexsha": "c0ca907ef54b05eb2e466a1de971361f10965086", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2021-12-18T02:51:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T04:16:14.000Z", "max_issues_repo_path": "c_src/numerl.c", "max_issues_repo_name": "tanguyl/numerl", "max_issues_repo_head_hexsha": "c0ca907ef54b05eb2e466a1de971361f10965086", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2022-01-09T15:55:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T12:26:23.000Z", "max_forks_repo_path": "c_src/numerl.c", "max_forks_repo_name": "tanguyl/numerl", "max_forks_repo_head_hexsha": "c0ca907ef54b05eb2e466a1de971361f10965086", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2022-01-08T19:51:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-20T04:29:43.000Z", "avg_line_length": 28.3868894602, "max_line_length": 129, "alphanum_fraction": 0.5474756622, "num_tokens": 6168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5273165382362518, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.2984709345571623}} {"text": "//#####################################################################\n// Header blas\n//#####################################################################\n#ifdef GEODE_BLAS\n\n// On Mac, we can't include Accelerate.h unless __SSE__ is available\n#if !defined(__APPLE__) || (defined(__SSE__) && !defined(__COVERITY__))\n\n#ifndef __blas_wrap_iterating__\n#ifndef __blas_wrap_h__\n#define __blas_wrap_h__\n\n#ifdef GEODE_MKL\n#include \n#include \n#include \n#include \n#else\n#ifdef __APPLE__\n#include \n#else\nextern \"C\" {\n#include \n}\n#endif\n#endif\n#include \n#include \n#include \nnamespace geode {\n\n// Problem-dependent parameter inspection\ntemplate GEODE_CORE_EXPORT int ilaenv(int ispec,const char* name,const char* opts,int m,int n);\n\ntemplate<> struct FromPython{GEODE_CORE_EXPORT static CBLAS_TRANSPOSE convert(PyObject* object);};\n\n#define WRAP(declaration) \\\n static declaration GEODE_UNUSED; \\\n static declaration\n\n#define __blas_wrap_iterating__\n\n#ifdef GEODE_MKL\n# define BC(name) s##name\n# define MKL_BC(name) mkl_s##name\n# define DECLARE(name,...)\n#else\n# define BC(name) s##name##_\n# define DECLARE(name,...) extern \"C\" { int s##name##_(__VA_ARGS__); }\n#endif\n#define CBC(name) cblas_s##name\n#define SA(name) (\"a\" #name)\n#define T float\n#include \"blas.h\"\n#undef SA\n#undef BC\n#undef CBC\n#undef MKL_BC\n#undef DECLARE\n#undef T\n\n#ifdef GEODE_MKL\n# define BC(name) d##name\n# define MKL_BC(name) mkl_d##name\n# define DECLARE(name,...)\n#else\n# define BC(name) d##name##_\n# define DECLARE(name,...) extern \"C\" { int d##name##_(__VA_ARGS__); }\n#endif\n#define CBC(name) cblas_d##name\n#define SA(name) (\"d\" #name)\n#define T double\n#include \"blas.h\"\n#undef SA\n#undef BC\n#undef CBC\n#undef MKL_BC\n#undef DECLARE\n#undef T\n\n#undef __blas_wrap_iterating__\n#undef WRAP\n\n}\n#endif\n#else // __blas_wrap_iterating__\n\n// Scale a vector: x = ax\nWRAP(void scal(int n, T alpha, T* x)) {\n if(alpha) CBC(scal)(n,alpha,x,1);\n else memset(x,0,n*sizeof(T)); // mkl scal doesn't work for alpha = 0\n}\n\n// Scale a vector: x = ax\nWRAP(void scal(T alpha, RawArray x)) {\n scal(x.size(),alpha,x.data());\n}\n\n// Scale a vector: x = ax\nWRAP(void scal(T alpha, Subarray x)) {\n if(alpha) CBC(scal)(x.m,alpha,x.data(),x.stride);\n else x.fill(0);\n}\n\nDECLARE(geqrf,int*,int*,T*,int*,T*,T*,int*,int*)\nDECLARE(gelqf,int*,int*,T*,int*,T*,T*,int*,int*)\n\n// QR factorize a dense matrix without pivoting. Call geqrf_work to define the required work size\nWRAP(void geqrf(CBLAS_UPLO uplo, RawArray A, RawArray tau, Array& work)) {\n int info,lda=max(1,A.n),r=min(A.m,A.n),lwork=work.max_size();\n GEODE_ASSERT(tau.size()==r);if(!r) return; // lapack requires tau.size()=1 here, so do nothing instead\n (uplo==CblasUpper?BC(gelqf):BC(geqrf))(const_cast(&A.n),const_cast(&A.m),A.data(),&lda,tau.data(),work.data(),&lwork,&info);\n GEODE_ASSERT(!info);\n}\n\n// Compute work.size() required for geqrf\nWRAP(int geqrf_work(CBLAS_UPLO uplo, RawArray A)) {\n if(!A.m || !A.n) return 0;\n T work;int info,lda=max(1,A.n),lwork=-1;\n (uplo==CblasUpper?BC(gelqf):BC(geqrf))(const_cast(&A.n),const_cast(&A.m),0,&lda,0,&work,&lwork,&info);\n return max((int)work,A.m,A.n); // Mkl returns the wrong work size, so grow it if necessary\n}\n\nDECLARE(geqp3,int*,int*,T*,int*,int*,T*,T*,int*,int*)\n\n// QR factorize a dense matrix with column pivoting\nWRAP(void geqp3(RawArray A, RawArray p, RawArray tau, Array& work)) {\n GEODE_ASSERT(tau.size()==max(1,min(A.m,A.n)) && p.size()==A.m);\n int info,lda=max(1,A.n),lwork=work.max_size();p.fill(0);\n BC(geqp3)(const_cast(&A.n),const_cast(&A.m),A.data(),&lda,p.data(),tau.data(),work.data(),&lwork,&info);\n}\n\n// Compute work.size() required for geqp3\nWRAP(int geqp3_work(RawArray A)) {\n T work;int info,lda=max(1,A.n),lwork=-1;\n BC(geqp3)(const_cast(&A.n),const_cast(&A.m),0,&lda,0,0,&work,&lwork,&info);\n return (int)work;\n}\n\nDECLARE(ormqr,char*,char*,int*,int*,int*,T*,int*,T*,T*,int*,T*,int*,int*)\nDECLARE(ormlq,char*,char*,int*,int*,int*,T*,int*,T*,T*,int*,T*,int*,int*)\n\n// Multiply a matrix C by Q or Q^T, where Q is computed by geqrf\nWRAP(void ormqr(CBLAS_UPLO uplo, CBLAS_SIDE s, CBLAS_TRANSPOSE t, Subarray A, RawArray tau, Subarray C, Array& work)) {\n const char *side=s==CblasLeft?\"R\":\"L\",*trans=t==CblasTrans?\"T\":\"N\"; // side flipped due to row-major vs. column major\n int k=min(A.m,A.n),c=s==CblasLeft?C.m:C.n,lda=max(1,A.stride),ldc=max(1,C.stride),lwork=work.max_size(),info;\n GEODE_ASSERT(k<=c && c<=(uplo==CblasUpper?A.m:A.n) && tau.size()==k);\n if(!k) return; // lapack requires tau.size()=1 here, so do nothing instead\n (uplo==CblasUpper?BC(ormlq):BC(ormqr))(const_cast(side),const_cast(trans),const_cast(&C.n),const_cast(&C.m),&k,\n const_cast(A.data()),&lda,const_cast(tau.data()),C.data(),&ldc,work.data(),&lwork,&info);\n GEODE_ASSERT(!info);\n}\n\n// Compute work.size() required by ormqr\nWRAP(int ormqr_work(CBLAS_UPLO uplo, CBLAS_SIDE s, CBLAS_TRANSPOSE t, Subarray A, Subarray C)) {\n const char *side=s==CblasLeft?\"R\":\"L\",*trans=t==CblasTrans?\"T\":\"N\"; // side flipped due to row-major vs. column major\n int k=min(A.m,A.n),lda=max(1,A.stride),ldc=max(1,C.stride),lwork=-1,info;T work;\n GEODE_ASSERT((uplo==CblasUpper?A.m:A.n)>=(s==CblasLeft?C.m:C.n));\n if(!k) return 0; // lapack requires tau.size()=1 here, so do nothing instead\n (uplo==CblasUpper?BC(ormlq):BC(ormqr))(const_cast(side),const_cast(trans),const_cast(&C.n),const_cast(&C.m),&k,0,&lda,0,0,&ldc,&work,&lwork,&info);\n GEODE_ASSERT(!info);\n return (int)work;\n}\n\n// Multiply a vector C by Q or Q^T, where Q is computed by geqrf (the single vector case of ormqr above)\nWRAP(void ormqr(CBLAS_UPLO uplo, CBLAS_SIDE s, CBLAS_TRANSPOSE t, Subarray A, RawArray tau, RawArray C, Array& work)) {\n int r=C.size(),c=1;if(s==CblasRight) swap(r,c);\n ormqr(uplo,s,t,A,tau,C.reshape(r,c),work);\n}\n\n// Compute work.size() required by the vector case of ormqr\nWRAP(int ormqr_work(CBLAS_UPLO uplo,CBLAS_SIDE s,CBLAS_TRANSPOSE t,Subarray A,RawArray C)) {\n int r=C.size(),c=1;if(s==CblasRight) swap(r,c);\n return ormqr_work(uplo,s,t,A,C.reshape(r,c));\n}\n\nDECLARE(orgqr,int*,int*,int*,T*,int*,T*,T*,int*,int*)\nDECLARE(orglq,int*,int*,int*,T*,int*,T*,T*,int*,int*)\n\n// Expand the QR factorization computed by geqrf into a dense matrix in standard format\nWRAP(void orgqr(CBLAS_UPLO uplo, int r, Subarray A, RawArray tau, Array& work)) {\n int info,m=A.m,n=A.n,lda=max(1,A.stride),lwork=work.max_size();\n GEODE_ASSERT(r<=min(m,n) && (uplo==CblasUpper?n<=m:m<=n) && tau.size()==r);\n (uplo==CblasUpper?BC(orglq):BC(orgqr))(&n,&m,&r,A.data(),&lda,const_cast(tau.data()),work.data(),&lwork,&info);\n}\n\n// Compute work.size() required by orgqr\nWRAP(int orgqr_work(CBLAS_UPLO uplo, int r, Subarray A)) {\n T work;int info,m=A.m,n=A.n,lda=max(1,A.stride),lwork=-1;\n GEODE_ASSERT(r<=min(m,n) && (uplo==CblasUpper?n<=m:m<=n));\n (uplo==CblasUpper?BC(orglq):BC(orgqr))(&n,&m,&r,0,&lda,0,&work,&lwork,&info);\n return (int)work;\n}\n\n// y = alpha*A^op x + beta*y\nWRAP(void gemv(CBLAS_TRANSPOSE t, T alpha, Subarray A, const T* x, T beta, T* y)) {\n int m=A.m,n=A.n;if(t==CblasTrans) swap(m,n);\n if(!n) scal(m,beta,y); // work around bug in mkl\n else CBC(gemv)(CblasRowMajor,t,A.m,A.n,alpha,A.data(),max(1,A.stride),x,1,beta,y,1);\n}\n\n// y = alpha*A^op x + beta*y\nWRAP(void gemv(CBLAS_TRANSPOSE t, T alpha, Subarray A, RawArray x, T beta, RawArray y)) {\n int m=A.m,n=A.n;if(t==CblasTrans) swap(m,n);\n GEODE_ASSERT(x.size()==n && m==y.size());\n gemv(t,alpha,A,x.data(),beta,y.data());\n}\n\n// y = alpha*A x + beta*y\nWRAP(void gemv(T alpha, Subarray A, const T* x, T beta, T* y)) {\n gemv(CblasNoTrans,alpha,A,x,beta,y);\n}\n\n// y = alpha*A x + beta*y\nWRAP(void gemv(T alpha, Subarray A, RawArray x, T beta, RawArray y)) {\n gemv(CblasNoTrans,alpha,A,x,beta,y);\n}\n\n// y = alpha*A x + beta*y for symmetric A\nWRAP(void symv(CBLAS_UPLO uplo, T alpha, Subarray A, RawArray x, T beta, RawArray y)) {\n GEODE_ASSERT(A.m==A.n && x.size()==A.m && y.size()==A.m);\n CBC(symv)(CblasRowMajor,uplo,A.m,alpha,A.data(),max(1,A.stride),x.data(),1,beta,y.data(),1);\n}\n\n// // y = alpha*A^op+beta*y for banded A with kl subdiagonals and ku superdiagonals.\nWRAP(void gbmv(CBLAS_TRANSPOSE t, int m, int n, int kl, int ku, T alpha, RawArray A, const T* x, T beta, T* y)) {\n int lda=kl+ku+1;GEODE_ASSERT(kl>=0 && ku>=0 && A.size()==n*lda);\n CBC(gbmv)(CblasColMajor,t,m,n,kl,ku,alpha,A.data(),lda,x,1,beta,y,1);\n}\n\nDECLARE(gesdd,char*,int*,int*,T*,int*,T*,T*,int*,T*,int*,T*,int*,int*,int*)\n\n// Compute the singular value decomposition of a dense matrix. A is destroyed.\nWRAP(void gesdd(Array& A, Array& s, Array& U, Array& Vt, Array& work, bool all)) {\n char job=all?'A':'S';int r=min(A.m,A.n),liwork=8*r,lwork=(work.max_size()*sizeof(T)-liwork*sizeof(int))/sizeof(T),info;\n U.resize(A.m,all?A.m:r);Vt.resize(all?A.n:r,A.n);s.resize(r);\n BC(gesdd)(&job,&A.n,&A.m,A.data(),&A.n,s.data(),Vt.data(),&Vt.n,U.data(),&U.n,work.data(),&lwork,reinterpret_cast(work.data()+lwork),&info);\n}\n\n// Compute work.size() required by gesdd with singular vectors\nWRAP(int gesdd_work(Array& A, Array& U, Array& Vt, bool all)) {\n T work;char job=all?'A':'S';int r=min(A.m,A.n),liwork=max(1,8*r),lwork=-1,iwork,info;\n BC(gesdd)(&job,&A.n,&A.m,0,&A.n,0,0,&A.n,0,&A.m,&work,&lwork,&iwork,&info);\n return int(work+(liwork*sizeof(int)+sizeof(T)-1)/sizeof(T));\n}\n\n// Compute the singular values of a dense matrix without the singular vectors. A is destroyed.\nWRAP(void gesdd(Array& A, Array& s, Array& work)) {\n char job='N';int r=min(A.m,A.n),one=1,info,liwork=8*r,lwork=(work.max_size()*sizeof(T)-liwork*sizeof(int))/sizeof(T);\n s.resize(r);\n BC(gesdd)(&job,&A.n,&A.m,A.data(),&A.n,s.data(),0,&one,0,&one,work.data(),&lwork,reinterpret_cast(work.data()+lwork),&info);\n}\n\n// Compute work.size() required by gesdd without singular vectors\nWRAP(int gesdd_work(Array& A)) {\n char job='N';T work;int r=min(A.m,A.n),one=1,info,liwork=8*r,iwork,lwork=-1;\n BC(gesdd)(&job,&A.n,&A.m,0,&A.n,0,0,&one,0,&one,&work,&lwork,&iwork,&info);\n return int(work+(liwork*sizeof(int)+sizeof(T)-1)/sizeof(T));\n}\n\nDECLARE(syevd,char*,char*,int*,T*,int*,T*,T*,int*,int*,int*,int*)\n\n// Compute the eigenvalues of a symmetric matrix. A is destroyed.\nWRAP(void syevd(CBLAS_UPLO uplo, Subarray A, Array& w, Array& work)) {\n int n=A.n;\n GEODE_ASSERT(A.m==n);\n T lwork_;int liwork,query=-1,lda=A.stride,info;\n char *job=const_cast(\"N\"),*uplo_=const_cast(uplo==CblasLower?\"U\":\"L\");\n BC(syevd)(job,uplo_,&n,A.data(),&lda,0,&lwork_,&query,&liwork,&query,&info);\n int lwork=(int)lwork_;\n GEODE_ASSERT(lwork*sizeof(T)+liwork*sizeof(int)>=work.max_size()*sizeof(T));\n w.resize(n);\n BC(syevd)(job,uplo_,&n,A.data(),&lda,w.data(),work.data(),&lwork,reinterpret_cast(work.data()+lwork),&liwork,&info);\n}\n\n// Compute work.size() required by syevd\nWRAP(int syevd_work(CBLAS_UPLO uplo, Subarray A)) {\n int n=A.n;\n GEODE_ASSERT(A.m==n);\n T work;int iwork,lda=A.stride,info,lwork=-1;\n char *job=const_cast(\"N\"),*uplo_=const_cast(uplo==CblasLower?\"U\":\"L\");\n BC(syevd)(job,uplo_,&n,const_cast(A.data()),&lda,0,&work,&lwork,&iwork,&lwork,&info);\n return int(work+(iwork*sizeof(int)+sizeof(T)-1)/sizeof(T));\n}\n\nDECLARE(stedc,char*,int*,T*,T*,T*,int*,T*,int*,int*,int*,int*)\n\n// Compute all eigenvalues and eigenvectors of a symmetric tridiagonal matrix. work is automatically resized.\nWRAP(void stedc(RawArray d, RawArray e, Array& z, Array& work)) {\n int n=d.size();\n GEODE_ASSERT(n-1<=e.size() && e.size()<=n);\n z.resize(n,n,uninit);\n if(!n) return;\n char *compz=const_cast(\"I\");\n T lwork_T;int liwork,query=-1,ldz=z.n,info;\n BC(stedc)(compz,&n,d.data(),e.data(),z.data(),&ldz,&lwork_T,&query,&liwork,&query,&info);\n GEODE_ASSERT(!info);\n int lwork=(int)lwork_T;\n static_assert(sizeof(T)/sizeof(int)*sizeof(int)==sizeof(T),\"\");\n work.preallocate(lwork*sizeof(T)+liwork*sizeof(int));\n BC(stedc)(compz,&n,d.data(),e.data(),z.data(),&ldz,reinterpret_cast(work.data()),&lwork,\n reinterpret_cast(work.data()+lwork*sizeof(T)),&liwork,&info);\n GEODE_ASSERT(!info);\n}\n\nDECLARE(stegr,char*,char*,int*,T*,T*,T*,T*,int*,int*,T*,int*,T*,T*,int*,int*,T*,int*,int*,int*,int*)\n\n// Compute selected eigenvalues and eigenvectors of a symmetric tridiagonal matrix. WARNING: Does not work in Mkl 10.2.3.\nWRAP(void stegr(RawArray d,RawArray e,Box range,Array& w,Array& z,Array& isuppz,Array& work)) {\n int n=d.size();\n GEODE_ASSERT(n==e.size());\n w.resize(n,uninit);z.resize(n,n,uninit);isuppz.resize(2*n,uninit);\n if(!n) return;\n char *jobz=const_cast(\"V\"),*ran=const_cast(range.contains(Box::full_box())?\"A\":\"V\");\n T lwork_T,unused_T;int liwork,m,query=-1,unused,ldz=z.n,info;\n BC(stegr)(jobz,ran,&n,d.data(),e.data(),&range.min,&range.max,&unused,&unused,&unused_T,&m,w.data(),z.data(),&ldz,\n isuppz.data(),&lwork_T,&query,&liwork,&query,&info);\n GEODE_ASSERT(!info);\n int lwork=(int)lwork_T;\n static_assert(sizeof(T)/sizeof(int)*sizeof(int)==sizeof(T),\"\");\n work.preallocate(lwork*sizeof(T)+liwork*sizeof(int));\n BC(stegr)(jobz,ran,&n,d.data(),e.data(),&range.min,&range.max,&unused,&unused,&unused_T,&m,w.data(),z.data(),&ldz,\n isuppz.data(),reinterpret_cast(work.data()),&lwork,reinterpret_cast(work.data()+lwork*sizeof(T)),&liwork,&info);\n GEODE_ASSERT(!info);\n w.resize(m);z.resize(m,n);isuppz.resize(m);\n}\n\n// Matrix-matrix multiply: C = alpha*A^ta B^tb+beta*C\nWRAP(void gemm(CBLAS_TRANSPOSE ta, CBLAS_TRANSPOSE tb, T alpha, Subarray A, Subarray B, T beta, Subarray C)) {\n int k=ta==CblasTrans?A.m:A.n;\n GEODE_ASSERT(C.m==A.m+A.n-k && k==(tb==CblasTrans?B.n:B.m) && B.m+B.n-k==C.n);\n int lda=max(1,A.stride),ldb=max(1,B.stride),ldc=max(1,C.stride);\n CBC(gemm)(CblasRowMajor,ta,tb,C.m,C.n,k,alpha,A.data(),lda,B.data(),ldb,beta,C.data(),ldc);\n}\n\n// Matrix-matrix multiply: C = alpha*AB+beta*C\nWRAP(void gemm(T alpha, Subarray A, Subarray B, T beta, Subarray C)) {\n gemm(CblasNoTrans,CblasNoTrans,alpha,A,B,beta,C);\n}\n\n// Perform a symmetric rank-k update of a matrix: C = alpha*A^t A^!t + beta*C\nWRAP(void syrk(CBLAS_UPLO uplo, CBLAS_TRANSPOSE t, T alpha, Subarray A, T beta, Subarray C)) {\n int k=t==CblasTrans?A.m:A.n,lda=max(A.stride,1),ldc=max(C.stride,1);\n GEODE_ASSERT(C.m==C.n && C.m==A.m+A.n-k);\n CBC(syrk)(CblasRowMajor,uplo,t,C.m,k,alpha,A.data(),lda,beta,C.data(),ldc);\n}\n\nDECLARE(gels,char*,int*,int*,int*,T*,int*,T*,int*,T*,int*,int*)\n\n// Solve a full rank least squares problem. work is automatically resized.\nWRAP(void gels(char t,Subarray A,RawArray b,Array& work)) {\n GEODE_ASSERT((t=='N' || t=='T') && max(A.m,A.n)==b.size() && (t=='N'?A.m:A.n)==b.size());\n char ot=t=='N'?'T':'N';int one=1,ldb=max(1,b.size()),lwork=work.size(),info;\n if(!lwork){work.resize(1);lwork=-1;}\n BC(gels)(&ot,const_cast(&A.n),const_cast(&A.m),&one,A.data(),const_cast(&A.stride),b.data(),&ldb,work.data(),&lwork,&info);\n if(lwork<0) work.resize(max(1,(int)work[0]));\n}\n\nDECLARE(gelsy,int*,int*,int*,T*,int*,T*,int*,int*,T*,int*,T*,int*,int*)\n\n// Compute a minimum-norm solution to the linear least squares problem A^T x = b. work is automatically resized.\nWRAP(void gelsy(Subarray A,RawArray b,Array& work)) {\n GEODE_ASSERT(max(A.m,A.n)==b.size() && A.n==b.size());\n int one=1,ldb=max(1,b.size()),lwork=work.size(),info;\n if(!lwork){work.resize(1);lwork=-1;}\n Array jpvt(A.m);T rcond;int rank;\n BC(gelsy)(const_cast(&A.n),const_cast(&A.m),&one,A.data(),const_cast(&A.stride),b.data(),&ldb,jpvt.data(),&rcond,&rank,work.data(),&lwork,&info);\n if(lwork<0) work.resize(max(1,(int)work[0]));\n}\n\nDECLARE(gelsd,int*,int*,int*,T*,int*,T*,int*,T*,T*,int*,T*,int*,int*,int*)\n\n// If iwork is zero size, we will call gelsd in workspace query mode.\n// This function will then resize work to be the proper size.\n// Nothing else will have been done, so you have to call this function again.\n// b.n must be equal to max(A.m,A.n). If A.m > A.n, only the first A.n rows\n// contain the solution, the rest contain residuals.\nWRAP(void gelsd(Subarray A,RawArray b,Array& work,Array& iwork)) { // solves A^T x = b\n int m=A.m,n=A.n;GEODE_ASSERT(max(m,n)==b.size());\n int one=1,ldb=max(1,b.size()),lwork=work.size(),info;\n if(!lwork){work.resize(1);iwork.resize(1);lwork=-1;}\n Array s(max(1,min(m,n)),uninit);T rcond;int rank;\n BC(gelsd)(&n,&m,&one,A.data(),const_cast(&A.stride),b.data(),&ldb,s.data(),&rcond,&rank,work.data(),&lwork,iwork.data(),&info);\n if(lwork<0){work.resize(max(1,(int)work[0]));iwork.resize(max(1,(int)iwork[0]));}\n if (info)\n std::cout << \"error in gelsd: \" << info << std::endl;\n}\n\n// If iwork is zero size, we will call gelsd in workspace query mode.\n// This function will then resize work to be the proper size.\n// Nothing else will have been done, so you have to call this function again.\nWRAP(void gelsd(Subarray A,Arrayb,Array& work,Array& iwork)) { // solves A^T X^T = B^T for all columns of X and B\n int m=A.m,n=A.n;\n GEODE_ASSERT(max(m,n)==b.n);\n int nrhs=b.m, ldb=b.n, lwork=work.size(), info;\n if(!lwork) {\n work.resize(1);\n iwork.resize(1);\n lwork=-1;\n }\n Array s(min(m,n),uninit);\n T rcond;\n int rank;\n BC(gelsd)(&n,&m,&nrhs,A.data(),const_cast(&A.stride),b.data(),&ldb,s.data(),&rcond,&rank,work.data(),&lwork,iwork.data(),&info);\n if (lwork<0) {\n work.resize((int)work[0]);\n iwork.resize((int)iwork[0]);\n }\n if (info)\n std::cout << \"error in gelsd: \" << info << std::endl;\n}\n\n// y = ax + y\nWRAP(void axpy(int n, T alpha, const T* x, T* y)) {\n CBC(axpy)(n,alpha,x,1,y,1);\n}\n\n// y = ax + y\nWRAP(void axpy(T alpha, RawArray x, RawArray y)) {\n int n=x.size();GEODE_ASSERT(n==y.size());\n CBC(axpy)(n,alpha,x.data(),1,y.data(),1);\n}\n\n// Squared norm: |x|^2 = dot(x,x)\nWRAP(T nrm2(RawArray x)) {\n return CBC(nrm2)(x.size(),x.data(),1);\n}\n\n// sum_i x_i\nWRAP(T asum(RawArray x)) {\n return CBC(asum)(x.size(),x.data(),1);\n}\n\n// dot(x,y)\nWRAP(T dot(RawArray x, RawArray y)) {\n int n=x.size();GEODE_ASSERT(n==y.size());\n return CBC(dot)(n,x.data(),1,y.data(),1);\n}\n\n// Swap the contents of two subarrays\nWRAP(void blas_swap(Subarray x, Subarray y)) {\n int n=x.size();GEODE_ASSERT(n==y.size());CBC(swap)(n,x.data(),x.stride,y.data(),y.stride);\n}\n\n// Rank one update: A = A + alpha*x y^T\nWRAP(void ger(T alpha, Subarray x, Subarray y, Subarray A)) {\n GEODE_ASSERT(x.size()==A.m && A.n==y.size());\n int lda=max(1,A.stride),xinc=max(1,x.stride),yinc=max(1,y.stride);\n CBC(ger)(CblasRowMajor,A.m,A.n,alpha,x.data(),xinc,y.data(),yinc,A.data(),lda);\n}\n\nDECLARE(laset,char*,int*,int*,T*,T*,T*,int*)\n\n// Initialize the diagonal and offdiagonal of a matrix to the given values\nWRAP(void laset(char uplo, T offdiagonal, T diagonal, Subarray A)) {\n char uplo_s[2]={uplo,0};int lda=max(1,A.stride);\n BC(laset)(uplo_s,const_cast(&A.n),const_cast(&A.m),&offdiagonal,&diagonal,A.data(),&lda);\n}\n\n// Compute a scalar matrix-matrix product with one matrix triangular. TODO: Give details.\nWRAP(void trmm(CBLAS_SIDE side, CBLAS_UPLO uplo, CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, T alpha, Subarray A, Subarray B)) {\n int k=side==CblasLeft?B.m:B.n;\n GEODE_ASSERT(A.m>=k && A.n>=k && (uplo==CblasLower?A.m:A.n)==k);\n CBC(trmm)(CblasRowMajor,side,uplo,transA,diag,B.m,B.n,alpha,A.data(),max(1,A.stride),B.data(),max(1,B.stride));\n}\n\n// Solve a triangular matrix equation. TODO: Give details.\nWRAP(void trsm(CBLAS_SIDE side, CBLAS_UPLO uplo, CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, T alpha, Subarray A, Subarray B)) {\n int k=side==CblasLeft?B.m:B.n;\n GEODE_ASSERT(A.m>=k && A.n>=k && (uplo==CblasLower?A.m:A.n)==k);\n CBC(trsm)(CblasRowMajor,side,uplo,transA,diag,B.m,B.n,alpha,A.data(),max(1,A.stride),B.data(),max(1,B.stride));\n}\n\n// Solve a triangular matrix equation. TODO: Give details.\nWRAP(void trsm(CBLAS_SIDE side, CBLAS_UPLO uplo, CBLAS_TRANSPOSE transA, CBLAS_DIAG diag, T alpha, Subarray A, RawArray B))\n{\n int r=B.size(),c=1;if(side==CblasRight) swap(r,c);\n trsm(side,uplo,transA,diag,alpha,A,B.reshape(r,c));\n}\n\nDECLARE(gesv,int*,int*,T*,int*,int*,T*,int*,int*)\n\n// Solve a linear system: b = A^-T b. WARNING: Note that the matrix is transposed.\nWRAP(void gesv(RawArray A,RawArray b)) {\n GEODE_ASSERT(A.m==A.n && A.m==b.size());\n int one=1,lda=max(1,A.n),info;\n Array ipiv(A.m,uninit);\n BC(gesv)(const_cast(&A.m),&one,A.data(),&lda,ipiv.data(),b.data(),const_cast(&A.n),&info);\n}\n\nDECLARE(getrf,int*,int*,T*,int*,int*,int*)\n\n// Compute the pivoted LU factorization of a square matrix.\nWRAP(void getrf(RawArray A, RawArray ipiv)) {\n int r=min(A.m,A.n),info;GEODE_ASSERT(ipiv.size()==r);\n if(!r) return;\n BC(getrf)(&A.n,&A.m,A.data(),&A.n,ipiv.data(),&info);\n}\n\nDECLARE(gecon,char*,int*,T*,int*,T*,T*,T*,int*,int*)\n\n// Estimate the reciprocal of the condition number of a general matrix in the 1-norm or the infinity-norm.\nWRAP(T gecon(char norm, RawArray A, T anorm)) {\n GEODE_ASSERT(A.m==A.n && (norm=='1' || norm=='0' || norm=='I'));\n T rcond;int info;\n Array work(max(1,4*A.m),uninit);\n Array iwork(max(1,A.m),uninit);\n BC(gecon)(&norm,&A.m,A.data(),&A.n,&anorm,&rcond,work.data(),iwork.data(),&info);\n return rcond;\n}\n\nDECLARE(sytrf,char*,int*,T*,int*,int*,T*,int*,int*)\n\n// Compute the Bunch-Kaufman factorization of a symmetric matrix.\nWRAP(void sytrf(CBLAS_UPLO uplo, Subarray A, RawArray ipiv, Array& work)) {\n GEODE_ASSERT(A.m==A.n && A.m==ipiv.size());\n const char *u=uplo==CblasLower?\"L\":\"U\";\n int n=A.m,lda=max(1,A.stride),lwork=work.max_size(),info;\n BC(sytrf)(const_cast(u),&n,A.data(),&lda,ipiv.data(),work.data(),&lwork,&info);\n}\n\n// Compute work.size() required by sytrf\nWRAP(int sytrf_work(CBLAS_UPLO uplo,Subarray A)) {\n // Mkl appears to have a bug in the sytrf work query, so we do it ourselves\n static const int nb=max(ilaenv(1,SA(sytrf),\"L\",1024,-1),ilaenv(1,SA(sytrf),\"U\",1024,-1));\n return max(1,nb*A.m);\n}\n\nDECLARE(sytrs,char*,int*,int*,T*,int*,int*,T*,int*,int*)\n\n// Solve a linear system given the Bunch-Kaufman factorization computed by sytrf. WARNING: Computes B = B A^{-1} since Lapack is column-major.\nWRAP(void sytrs(CBLAS_UPLO uplo,Subarray A,RawArray ipiv,Subarray B)) {\n GEODE_ASSERT(A.m==A.n && A.m==ipiv.size() && B.n==A.m);\n const char *u=uplo==CblasLower?\"L\":\"U\";\n int n=A.n,nrhs=B.m,lda=max(1,A.stride),ldb=max(1,B.stride),info;\n BC(sytrs)(const_cast(u),&n,&nrhs,const_cast(A.data()),&lda,const_cast(ipiv.data()),B.data(),&ldb,&info);\n}\n\n// Solve a linear system given the Bunch-Kaufman factorization computed by sytrf.\nWRAP(void sytrs(CBLAS_UPLO uplo,Subarray A,RawArray ipiv,RawArray B)) {\n sytrs(uplo,A,ipiv,B.reshape(1,B.size()));\n}\n\n#ifdef GEODE_MKL\n\n// Perform scaling and in-place transposition/copying of matrices.\nWRAP(void imatcopy(T alpha,Subarray A)) {\n MKL_BC(imatcopy)('r','t',A.m,A.n,alpha,A.data(),A.n,A.m);\n}\n\n// Perform scaling and out-place transposition/copying of matrices.\nWRAP(void omatcopy(CBLAS_TRANSPOSE trans,T alpha,Subarray A,Subarray B)) {\n int k=trans==CblasTrans?A.n:A.m,lda=max(1,A.stride),ldb=max(1,B.stride);\n GEODE_ASSERT(k==B.m && A.m+A.n-k==B.n);\n MKL_BC(omatcopy)('r',trans==CblasTrans?'t':'n',A.m,A.n,alpha,A.data(),lda,B.data(),ldb);\n}\n\n#endif\n\n#endif\n#endif\n#endif\n", "meta": {"hexsha": "dfd554d1d6d87979e805526d373ce61636f38672", "size": 24228, "ext": "h", "lang": "C", "max_stars_repo_path": "geode/vector/blas.h", "max_stars_repo_name": "jjqcat/geode", "max_stars_repo_head_hexsha": "157cc904c113cc5e29a1ffe7c091a83b8ec2cf8e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 75.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T22:04:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T14:31:43.000Z", "max_issues_repo_path": "geode/vector/blas.h", "max_issues_repo_name": "bantamtools/geode", "max_issues_repo_head_hexsha": "d906f1230b14953b68af63aeec2f7b0418d5fdfd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T15:11:38.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-05T13:27:22.000Z", "max_forks_repo_path": "geode/vector/blas.h", "max_forks_repo_name": "bantamtools/geode", "max_forks_repo_head_hexsha": "d906f1230b14953b68af63aeec2f7b0418d5fdfd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2015-03-11T16:43:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-15T09:37:51.000Z", "avg_line_length": 43.0337477798, "max_line_length": 175, "alphanum_fraction": 0.6585355787, "num_tokens": 8467, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.29847092614800336}} {"text": "#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\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#include \n#include \n\n#include \"../cosmolike_light/theory/baryons.h\"\n#include \"../cosmolike_light/theory/basics.c\"\n#include \"../cosmolike_light/theory/structs.c\"\n#include \"../cosmolike_light/theory/parameters.c\"\n#include \"../cosmolike_light/emu17/P_cb/emu.c\"\n#include \"../cosmolike_light/theory/recompute.c\"\n#include \"../cosmolike_light/theory/cosmo3D.c\"\n#include \"../cosmolike_light/theory/redshift_spline.c\"\n#include \"../cosmolike_light/theory/halo.c\"\n#include \"../cosmolike_light/theory/HOD.c\"\n#include \"../cosmolike_light/theory/cosmo2D_fourier.c\"\n#include \"../cosmolike_light/theory/IA.c\"\n#include \"../cosmolike_light/theory/BAO.c\"\n#include \"../cosmolike_light/theory/external_prior.c\"\n#include \"../cosmolike_light/theory/covariances_3D.c\"\n#include \"../cosmolike_light/theory/covariances_fourier.c\"\n#include \"../cosmolike_light/theory/covariances_real.c\"\n#include \"../cosmolike_light/theory/run_covariances_real.c\"\n#include \"../cosmolike_light/theory/init.c\"\n\n\nint main(int argc, char** argv)\n{\n int hit=atoi(argv[1]);\n FILE *F1,*F2;\n int i,l,m,n,o,s,p,output;\n double ktmp;\n char OUTFILE[400],filename[400];\n\n printf(\"-----------------\\n\");\n printf(\"This is not production mode covariance code\\n\");\n printf(\"Please only use with care and at your own risk\\n\");\n printf(\"-----------------\\n\");\n \n Ntable.N_a=20;\n set_cov_parameters_to_(\"cov_Y1/cov_y1_mcal_revision.ini\",1);\n //here: setting values internally\n\n // set this to zero to quickly run Gaussian-only covariances for testing\n if (covparams.ng==1){\n NG = 1;\n }\n else {\n NG = 0;\n }\n\n // set this to one to output details about inputs for diagnostics\n output = 0;\n FILE *F;\n printf(\"running multi_covariance_real with NG = %d\\n\",NG);\n \n set_cosmological_parameters_to_(\"cov_Y1/cov_y1_mcal_revision.ini\",1);\n //here: setting values internally \n // cosmology.Omega_m = 0.286;\n // cosmology.Omega_v = 1.0-cosmology.Omega_m;\n // cosmology.sigma_8 = 0.82;\n // cosmology.n_spec = 0.96;\n \n // cosmology.w0=-1.;\n // cosmology.wa=0.;\n // cosmology.omb=0.04868;\n // cosmology.h0=0.673;\n // cosmology.coverH0= 2997.92458; \n\n // cosmology.rho_crit = 7.4775e+21;\n // cosmology.f_NL = 0.0;\n // pdeltaparams.runmode=\"Halofit\"\n\n set_survey_parameters_to_(\"cov_Y1/cov_y1_mcal_revision.ini\",1);\n //here: setting values internally \n //survey.area=1000.0;\n //survey.m_lim=\n //survey.name=\n //survey.Kcorrect_File=\n // redshift.shear_REDSHIFT_FILE=source.nz\n // redshift.clustering_REDSHIFT_FILE=lens.nz\n // survey.sourcephotoz=\"multihisto\";\n // survey.lensphotoz=\"multihisto\";\n // survey.galsample=\n // tomo.shear_Nbin=5;\n // redshift.clustering_histogram_zbins =\n // tomo.clustering_Nbin=5;\n // tomo.clustering_Npowerspectra=tomo.clustering_Nbin;\n // survey.sigma_e=0.24;\n // survey.ggl_overlap_cut=\n // tomo.n_source[0]=1.07535691109;\n // tomo.n_source[1]=1.1606931903;\n // tomo.n_source[2]=1.2275933389;\n // tomo.n_source[3]=1.23453951309;\n // tomo.n_source[4]=1.3387876584;\n \n // tomo.n_lens[0]=0.02143277;\n // tomo.n_lens[1]=0.05426833;\n // tomo.n_lens[2]=0.08070083;\n // tomo.n_lens[3]=0.05130111;\n // tomo.n_lens[4]=0.01515694;\n // for (i=0;i\n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -real2hc 16 */\n\n/*\n * This function contains 58 FP additions, 12 FP multiplications,\n * (or, 54 additions, 8 multiplications, 4 fused multiply/add),\n * 30 stack variables, and 32 memory accesses\n */\nstatic const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);\nstatic const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);\nstatic const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);\n\n/*\n * Generator Id's : \n * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $\n * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $\n * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $\n */\n\nvoid fftw_real2hc_16(const fftw_real *input, fftw_real *real_output, fftw_real *imag_output, int istride, int real_ostride, int imag_ostride)\n{\n fftw_real tmp3;\n fftw_real tmp6;\n fftw_real tmp7;\n fftw_real tmp35;\n fftw_real tmp18;\n fftw_real tmp33;\n fftw_real tmp40;\n fftw_real tmp48;\n fftw_real tmp56;\n fftw_real tmp10;\n fftw_real tmp13;\n fftw_real tmp14;\n fftw_real tmp36;\n fftw_real tmp17;\n fftw_real tmp26;\n fftw_real tmp41;\n fftw_real tmp51;\n fftw_real tmp57;\n fftw_real tmp16;\n fftw_real tmp15;\n fftw_real tmp43;\n fftw_real tmp44;\n ASSERT_ALIGNED_DOUBLE;\n {\n\t fftw_real tmp1;\n\t fftw_real tmp2;\n\t fftw_real tmp4;\n\t fftw_real tmp5;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp1 = input[0];\n\t tmp2 = input[8 * istride];\n\t tmp3 = tmp1 + tmp2;\n\t tmp4 = input[4 * istride];\n\t tmp5 = input[12 * istride];\n\t tmp6 = tmp4 + tmp5;\n\t tmp7 = tmp3 + tmp6;\n\t tmp35 = tmp1 - tmp2;\n\t tmp18 = tmp4 - tmp5;\n }\n {\n\t fftw_real tmp29;\n\t fftw_real tmp46;\n\t fftw_real tmp32;\n\t fftw_real tmp47;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp27;\n\t fftw_real tmp28;\n\t fftw_real tmp30;\n\t fftw_real tmp31;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp27 = input[istride];\n\t tmp28 = input[9 * istride];\n\t tmp29 = tmp27 - tmp28;\n\t tmp46 = tmp27 + tmp28;\n\t tmp30 = input[5 * istride];\n\t tmp31 = input[13 * istride];\n\t tmp32 = tmp30 - tmp31;\n\t tmp47 = tmp30 + tmp31;\n\t }\n\t tmp33 = (K382683432 * tmp29) + (K923879532 * tmp32);\n\t tmp40 = (K923879532 * tmp29) - (K382683432 * tmp32);\n\t tmp48 = tmp46 - tmp47;\n\t tmp56 = tmp46 + tmp47;\n }\n {\n\t fftw_real tmp8;\n\t fftw_real tmp9;\n\t fftw_real tmp11;\n\t fftw_real tmp12;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp8 = input[2 * istride];\n\t tmp9 = input[10 * istride];\n\t tmp10 = tmp8 + tmp9;\n\t tmp16 = tmp8 - tmp9;\n\t tmp11 = input[14 * istride];\n\t tmp12 = input[6 * istride];\n\t tmp13 = tmp11 + tmp12;\n\t tmp15 = tmp11 - tmp12;\n }\n tmp14 = tmp10 + tmp13;\n tmp36 = K707106781 * (tmp16 + tmp15);\n tmp17 = K707106781 * (tmp15 - tmp16);\n {\n\t fftw_real tmp22;\n\t fftw_real tmp49;\n\t fftw_real tmp25;\n\t fftw_real tmp50;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp20;\n\t fftw_real tmp21;\n\t fftw_real tmp23;\n\t fftw_real tmp24;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp20 = input[15 * istride];\n\t tmp21 = input[7 * istride];\n\t tmp22 = tmp20 - tmp21;\n\t tmp49 = tmp20 + tmp21;\n\t tmp23 = input[3 * istride];\n\t tmp24 = input[11 * istride];\n\t tmp25 = tmp23 - tmp24;\n\t tmp50 = tmp23 + tmp24;\n\t }\n\t tmp26 = (K382683432 * tmp22) - (K923879532 * tmp25);\n\t tmp41 = (K923879532 * tmp22) + (K382683432 * tmp25);\n\t tmp51 = tmp49 - tmp50;\n\t tmp57 = tmp49 + tmp50;\n }\n {\n\t fftw_real tmp55;\n\t fftw_real tmp58;\n\t fftw_real tmp53;\n\t fftw_real tmp54;\n\t ASSERT_ALIGNED_DOUBLE;\n\t real_output[4 * real_ostride] = tmp7 - tmp14;\n\t tmp55 = tmp7 + tmp14;\n\t tmp58 = tmp56 + tmp57;\n\t real_output[8 * real_ostride] = tmp55 - tmp58;\n\t real_output[0] = tmp55 + tmp58;\n\t imag_output[4 * imag_ostride] = tmp57 - tmp56;\n\t tmp53 = tmp13 - tmp10;\n\t tmp54 = K707106781 * (tmp51 - tmp48);\n\t imag_output[2 * imag_ostride] = tmp53 + tmp54;\n\t imag_output[6 * imag_ostride] = tmp54 - tmp53;\n }\n {\n\t fftw_real tmp45;\n\t fftw_real tmp52;\n\t fftw_real tmp39;\n\t fftw_real tmp42;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp45 = tmp3 - tmp6;\n\t tmp52 = K707106781 * (tmp48 + tmp51);\n\t real_output[6 * real_ostride] = tmp45 - tmp52;\n\t real_output[2 * real_ostride] = tmp45 + tmp52;\n\t tmp39 = tmp35 + tmp36;\n\t tmp42 = tmp40 + tmp41;\n\t real_output[7 * real_ostride] = tmp39 - tmp42;\n\t real_output[real_ostride] = tmp39 + tmp42;\n }\n tmp43 = tmp18 + tmp17;\n tmp44 = tmp41 - tmp40;\n imag_output[3 * imag_ostride] = tmp43 + tmp44;\n imag_output[5 * imag_ostride] = tmp44 - tmp43;\n {\n\t fftw_real tmp19;\n\t fftw_real tmp34;\n\t fftw_real tmp37;\n\t fftw_real tmp38;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp19 = tmp17 - tmp18;\n\t tmp34 = tmp26 - tmp33;\n\t imag_output[imag_ostride] = tmp19 + tmp34;\n\t imag_output[7 * imag_ostride] = tmp34 - tmp19;\n\t tmp37 = tmp35 - tmp36;\n\t tmp38 = tmp33 + tmp26;\n\t real_output[5 * real_ostride] = tmp37 - tmp38;\n\t real_output[3 * real_ostride] = tmp37 + tmp38;\n }\n}\n\nfftw_codelet_desc fftw_real2hc_16_desc =\n{\n \"fftw_real2hc_16\",\n (void (*)()) fftw_real2hc_16,\n 16,\n FFTW_FORWARD,\n FFTW_REAL2HC,\n 354,\n 0,\n (const int *) 0,\n};\n", "meta": {"hexsha": "aa82ddaab6e1562b0f5256aa5e855e1e8840569e", "size": 6305, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_16.c", "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_16.c", "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/frc_16.c", "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "avg_line_length": 28.7899543379, "max_line_length": 141, "alphanum_fraction": 0.6448850119, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.29800590551871725}} {"text": "#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"AG.h\"\n#include \"bitarray.h\"\n#include \"CH.h\"\n\n#include \n#include \n\n\nCHForm * python_tuple_to_CHForm(PyObject * tuple){\n PyObject * py_n = PyTuple_GetItem(tuple, 0);\n PyArrayObject * py_F = (PyArrayObject *)PyTuple_GetItem(tuple, 1);\n PyArrayObject * py_G = (PyArrayObject *)PyTuple_GetItem(tuple, 2);\n PyArrayObject * py_M = (PyArrayObject *)PyTuple_GetItem(tuple, 3);\n PyArrayObject * py_g = (PyArrayObject *)PyTuple_GetItem(tuple, 4);\n PyArrayObject * py_v = (PyArrayObject *)PyTuple_GetItem(tuple, 5);\n PyArrayObject * py_s = (PyArrayObject *)PyTuple_GetItem(tuple, 6);\n PyObject * py_obj_phase = PyTuple_GetItem(tuple, 7);\n Py_complex py_phase = PyComplex_AsCComplex(py_obj_phase);\n int n = PyLong_AsLong(py_n);\n CHForm * state = calloc(1, sizeof(CHForm));\n\n init_zero_CHForm(n, state);\n\n for(int i = 0; i < n; i++){\n for(int j = 0; j < n; j++){\n state->F[i] |= (((uint_bitarray_t)py_F->data[i*py_F->strides[0] + j*py_F->strides[1]]) & ONE) << j;\n state->G[i] |= (((uint_bitarray_t)py_G->data[i*py_G->strides[0] + j*py_G->strides[1]]) & ONE) << j;\n state->M[i] |= (((uint_bitarray_t)py_M->data[i*py_M->strides[0] + j*py_M->strides[1]]) & ONE) << j;\n }\n\n state->g1 |= (((uint_bitarray_t)py_g->data[i*py_g->strides[0]]) & ONE) << i;\n state->g2 |= ((((uint_bitarray_t)py_g->data[i*py_g->strides[0]]) >> 1u) & ONE) << i;\n\n state->v |= (((uint_bitarray_t)py_v->data[i*py_v->strides[0]]) & ONE) << i;\n state->s |= (((uint_bitarray_t)py_s->data[i*py_s->strides[0]]) & ONE) << i;\n }\n state->w = py_phase.real + I*py_phase.imag;\n return state;\n}\n\nPyObject * CHForm_to_python_tuple(CHForm * state){\n const long int dimensions1[1] = {state->n};\n const long int dimensions2[2] = {state->n, state->n};\n\n PyArrayObject * F = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE);\n PyArrayObject * G = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE);\n PyArrayObject * M = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE);\n PyArrayObject * g = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE);\n PyArrayObject * v = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE);\n PyArrayObject * s = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE);\n\n for(int i = 0; i < state->n; i++){\n for(int j = 0; j < state->n; j++){\n //printf(\"(%d, %d)\\n\",i,j);\n F->data[i*F->strides[0] + j*F->strides[1]] = (unsigned char)((state->F[i] >> j) & ONE);\n G->data[i*G->strides[0] + j*G->strides[1]] = (unsigned char)((state->G[i] >> j) & ONE);\n M->data[i*M->strides[0] + j*M->strides[1]] = (unsigned char)((state->M[i] >> j) & ONE);\n }\n g->data[i*g->strides[0]] = 2*((state->g2 >> i) & ONE) + ((state->g1 >> i) & ONE);\n v->data[i*v->strides[0]] = ((state->v >> i) & ONE);\n s->data[i*s->strides[0]] = ((state->s >> i) & ONE);\n }\n //printf(\"%lf + %lf\\n\", creal(state->w), cimag(state->w));\n Py_complex phase;\n phase.real = creal(state->w);\n phase.imag = cimag(state->w);\n return Py_BuildValue(\"iOOOOOOD\", state->n, F, G, M, g, v, s, &phase);\n}\n\nCHForm * c_apply_gates_to_basis_state(int n, PyArrayObject * gates, PyArrayObject * controls, PyArrayObject * targets){\n CHForm * state = calloc(1, sizeof(CHForm));\n init_cb_CHForm(n, state);\n //printf(\"3\\n\");\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n switch((char)gates->data[i*gates->strides[0]]) {\n case 'X':\n CXL(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n case 'Z':\n CZL(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n case 's':\n SL(state, (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n case 'h':\n HL(state, (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n }\n }\n\n return state;\n}\n\n/*\n * Given a product of the form appearing in (55) of Bravyi et al\n * work out the minus sign you get if you pull all the Zs to the left hand side and all the xs to the right\n */\nunsigned int sort_pauli_string(uint n, uint_bitarray_t * x, uint_bitarray_t * z, uint_bitarray_t mask){\n uint_bitarray_t t = 0;\n unsigned int sign = 0;\n for(int i = 0; i < n; i++){\n if((mask >> i) & ONE){\n t ^= z[i];\n sign ^= parity(t & x[i]);\n }\n }\n\n return sign;\n}\n\ndouble complex measurement_overlap(CHForm * state, uint_bitarray_t x){\n //compute the inner product \n //where the bitstring x determines a computational basis state\n uint_fast64_t u = 0;\n // u = x F\n for(int i =0; i < state->n; i++){\n for(int j=0; j n;j++){\n u ^= ((x>>j) & (state->F[j] >>i) & ONE) << i;\n }\n }\n if((u ^ state->s ) & (~state->v)){\n return 0;\n }\n unsigned int signbit = sort_pauli_string(state->n, state->F, state->M, x);\n signbit ^= parity(u & state->s & state->v);\n\n unsigned int g = 0;\n for(int i = 0; i < state->n; i++){\n if(( x >> i) &ONE ){\n g += ((state->g1 >> i) & ONE) + 2*((state->g2 >> i) & ONE);\n }\n }\n if(signbit & ONE){\n g += 2;\n }\n\n double complex phase = state->w;\n g %= 4;\n if(g == 1){\n phase *= I;\n }else if(g == 2){\n phase *= -1;\n }else if(g == 3){\n phase *= -1*I;\n }\n\n double sqrt2 = sqrt(2.);\n for(int i = 0; i < state->n; i++){\n if((state->v >> i) & ONE){\n phase /= sqrt2;\n }\n }\n\n return phase;\n}\n\nvoid apply_z_projector(CHForm * state, int a, int q){\n //apply the projector |a>G[q] & (~state->v) & state->s);\n uint_bitarray_t t = (state->G[q] & state->v) ^ state->s;\n\n if(t == state->s){\n if(k){\n state->w = 0;\n }else{\n desupersitionise(state, t, 2*k);\n state->w /= 2; // 2 since P = (I +- Z)/2\n }\n }\n}\nvoid apply_z_projectors(CHForm * state, uint_bitarray_t a, uint_bitarray_t mask){\n //for each qubit i\n //if mask mask_i == 1\n //apply the projector |a_i>n; i++){\n if((mask >> i) & ONE){\n unsigned int k = ((a>>i) ^ parity(state->G[i] & (~state->v) & state->s)) & ONE;\n uint_bitarray_t t = (state->G[i] & state->v) ^ state->s;\n if(t == state->s){\n if(k){\n state->w = 0;\n }\n }else{\n desupersitionise(state, t, (2*k) % 4u);\n state->w /= 2; // 2 since P = (I +- Z)/2\n }\n }\n }\n}\n\nCHForm * postselect_and_reduce(CHForm * state, uint_bitarray_t a, uint_bitarray_t mask){\n //handle the case where we're actually doing a full inner product separately\n if(popcount(mask) == state->n){\n state->w = measurement_overlap(state, a);\n if(state->n > 0){\n free(state->F);\n free(state->G);\n free(state->M);\n state->F = NULL;\n state->G = NULL;\n state->M = NULL;\n }\n state->n = 0;\n return state;\n }\n\n for(unsigned int i = 0; i < state->n; i++){\n if(((a & mask) >> i) & ONE){\n XL(state, i);\n }\n }\n apply_z_projectors(state, 0u, mask);\n\n //now we arrange it so there is at most one qubit with s_i = 1, v_i = 0\n //first try to find a qubit that isn't being deleted with s_i = 1, v_i = 0\n if(((~state->v) & state->s) != 0){\n //inside this block we know there are some qubits with s_i = 1, v_i = 0\n int control_qubit = -1;\n for(int i = 0; i < state->n; i++){\n if((((~mask) & state->s & (~state->v)) >> i) & ONE){\n control_qubit = i;\n break;\n }\n }\n\n //we want to insert 4 cnots to swap an s_i = 1 onto a qubit with v_i = mask_i = 0\n if(control_qubit < 0){\n //first find a mask qubit with s_i = 1, v_i = 0\n //and a non-mask qubit with s_i = 0, v_i = 0\n int mask_qubit = -1;\n int non_mask = -1;\n\n for(int i = 0; i < state->n; i++){\n if(((state->s & (~state->v)) >> i) & ONE){\n mask_qubit = i;\n }\n if((((~mask) & (~state->s) & (~state->v)) >> i) & ONE){\n non_mask = i;\n }\n }\n //insert this which is the identity\n //CX(mask_qubit, non_mask) CX(non_mask, mask_qubit) CX(non_mask, mask_qubit) CX(mask_qubit, non_mask)\n //multiply the left hand two onto U_C\n //and the right ones onto U_H |s>\n //where they will swap the which qubit has s = 0 and which has s = 1\n CXR(state, mask_qubit, non_mask);\n CXR(state, non_mask, mask_qubit);\n\n state->s |= (ONE << non_mask);\n state->s &= (~(ONE << mask_qubit));\n control_qubit = non_mask;\n }\n\n //so now we have a control qubit and (possibly) some others with s_i = 1, v_i = 0\n //we go through and switch the s_i's to zero and insert cnots controlled on our control\n for(int i = 0; i < state->n; i++){\n if(i != control_qubit){\n if((((~state->v) & state->s) >> i) & ONE){\n CXR(state, control_qubit, i);\n }\n }\n }\n state->s ^= (state->s & (~state->v));\n state->s |= (ONE << control_qubit);\n }\n //at this point as many qubits are \"free\" as possible\n //i.e. there is at most one qubit with s_i = 1, v_i = 0\n //and this control qubit is /not/ one of our mask qubits\n //we also want to ensure that all of our mask qubits have s_i = v_i = 0\n //we know already at this point that if they have v_i = 0 they have s_i = 0\n //so we just swap those of them which have v_i = 1 with a qubit that has v_i = s_i = 0\n\n int swapCandidateIndex = 0;\n for(int i = 0; i < state->n; i++){\n if(((mask & state->v) >> i) & ONE){\n for(; ((mask | state->s | state->v)>>swapCandidateIndex) & ONE; swapCandidateIndex++){};\n SWAPR(state, i, swapCandidateIndex);\n state->s |= ((state->s >> i) & ONE) << swapCandidateIndex;\n state->v |= ((state->v >> i) & ONE) << swapCandidateIndex;\n\n state->s &= (~(ONE << i));\n state->v &= (~(ONE << i));\n }\n }\n\n //printf(\"confirmation!\\n\");\n //printBits(mask & state->s & state->v, state->n);printf(\"\\n\");\n\n //at this point all our mask qubits have s_i = v_i = 0\n //and there is at most one qubit with s_i=0, v_i = 1\n //now we ensure that for each mask qubit q we have G[q][q] == 1\n //and use that G is the inverse of F^T\n //to make each column we want to throw away \"simple\"\n //i.e. have a single 1 on the diagonal and zeros elsewhere\n uint_bitarray_t marked = 0;\n for(int q = 0; q < state->n; q++){\n if((mask >> q) & ONE){ //q is a masked qubit\n if(((state->G[q] >> q) & ONE) == 0){\n for(int i = 0; i < state->n; i++){\n if(((state->G[q] & (~marked)) >> i) & ONE){\n SWAPR(state,q,i);\n break;\n }\n }\n }\n for(int i=0; i < state->n; i++){\n if((i != q) && ((state->G[q] >> i) & ONE)){\n CXR(state, i, q);\n }\n }\n marked |= (ONE<n); printf(\"\\n\");\n /* printf(\"c mats\\n\"); */\n /* for(int q = 0; q < state->n; q++){ */\n /* printBits(state->F[q], state->n); */\n /* printf(\" \"); */\n /* printBits(state->G[q], state->n); */\n /* printf(\" \"); */\n /* printBits(state->M[q], state->n); */\n /* printf(\" \"); */\n /* printf(\"\\n\"); */\n /* } */\n //delete rows\n for(; i+shift < state->n; i++){\n while(((mask>>(i+shift)) & ONE)){\n shift += 1;\n }\n\n if(i+shift < state->n){\n state->F[i] = state->F[i+shift];\n state->G[i] = state->G[i+shift];\n state->M[i] = state->M[i+shift];\n\n for(int j = 0; j < state->n; j++){\n state->F[j] = (state->F[j] ^ (state->F[j] & (ONE<F[j] >> shift) & (ONE <G[j] = (state->G[j] ^ (state->G[j] & (ONE<G[j] >> shift) & (ONE <M[j] = (state->M[j] ^ (state->M[j] & (ONE<M[j] >> shift) & (ONE <v = (state->v ^ (state->v & (ONE<v >> shift) & (ONE <s = (state->s ^ (state->s & (ONE<s >> shift) & (ONE <g1 = (state->g1 ^ (state->g1 & (ONE<g1 >> shift) & (ONE <g2 = (state->g2 ^ (state->g2 & (ONE<g2 >> shift) & (ONE <n = state->n-shift;\n\n state->F = realloc(state->F, state->n * sizeof(uint_bitarray_t));\n state->G = realloc(state->G, state->n * sizeof(uint_bitarray_t));\n state->M = realloc(state->M, state->n * sizeof(uint_bitarray_t));\n\n uint_bitarray_t m = 0u;\n for(size_t i = 0; i < state->n; i++){\n m |= (ONE << i);\n }\n for(size_t i = 0; i < state->n; i++){\n state->F[i] &= m;\n state->G[i] &= m;\n state->M[i] &= m;\n }\n state->g1 &= m;\n state->g2 &= m;\n state->v &= m;\n state->s &= m;\n\n return state;\n}\n\nPyObject * apply_gates_to_basis_state_project_and_reduce(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>data[i*a->strides[0]]){\n bitA |= (ONE << i);\n }\n if((char)mask->data[i*mask->strides[0]]){\n bitMask |= (ONE << i);\n }\n }\n\n postselect_and_reduce(state, bitA, bitMask);\n\n PyObject * tuple = CHForm_to_python_tuple(state);\n dealocate_state(state);\n return tuple;\n}\n\n\n//equatorial matrices define equatorial states\n//they are symmetric matrices with binary off diagonal elements\n//and mod 4 diagonal elements\ntypedef struct equatorial_matrix{\n int n;\n uint_bitarray_t * mat;\n uint_bitarray_t d1;\n uint_bitarray_t d2;\n} equatorial_matrix_t;\n\nvoid init_zero_equatorial_matrix(equatorial_matrix_t * matrix, int n){\n matrix->n = n;\n matrix->mat = (uint_bitarray_t*)calloc(n, sizeof(uint_bitarray_t));\n matrix->d1 = 0u;\n matrix->d2 = 0u;\n}\n\nvoid init_random_equatorial_matrix(equatorial_matrix_t * matrix, int n){\n matrix->n = n;\n matrix->mat = (uint_bitarray_t*)calloc(n, sizeof(uint_bitarray_t));\n uint_bitarray_t mask = 0u;\n for(int i = 0; i < n; i++){\n mask |= (ONE<mat[i] = (bitarray_rand()) & mask;\n }\n for(int i = 0; i < n; i++){\n for(int j = 0; j < i; j++){\n matrix->mat[i] &= ~(ONE << j);//(((matrix->mat[j]>>i) &ONE) <mat[i] |= (((matrix->mat[j] >> i) & ONE) <mat[i] &= ~(ONE << i);\n }\n matrix->d1 = bitarray_rand() & mask;\n matrix->d2 = bitarray_rand() & mask;\n}\n\nvoid dealocate_equatorial_matrix(equatorial_matrix_t * matrix){\n matrix->n = 0;\n free(matrix->mat);\n}\n\ndouble complex equatorial_inner_product(CHForm* state, equatorial_matrix_t equatorial_state){\n if(state->n == 0){\n return conj(state->w);\n }\n //we store A+J in AJ\n uint_bitarray_t * AJ = calloc(state->n, sizeof(uint_bitarray_t));\n\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < i; j++){\n uint_bitarray_t bit = parity(state->M[i] & state->F[j]) & ONE;\n AJ[i] |= (bit << j);\n AJ[j] |= (bit << i);\n }\n }\n\n //add A to J\n for(size_t i = 0; i < state->n; i++){\n AJ[i] ^= equatorial_state.mat[i];\n AJ[i] &= ~(ONE<g1);\n AJd1 ^= state->g1;\n AJd2 ^= state->g2;\n\n uint_bitarray_t * GT = calloc(state->n, sizeof(uint_bitarray_t)); // store transpose of G\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < state->n; j++){\n GT[j] |= ((state->G[i] >> j) & ONE) << i;\n }\n }\n\n //now we want to compute (A G)^T = G^T A^T\n //this is because doing X Y^T is generally faster than doing XY\n //since we can do the row / row dot products with popcount(x & y)\n //we need to know the value of G^T A^T mod-4 so we can work out what the diagonal of G^T A G should be\n //so we store it in two binary matrices X and Y such that G^T A^T = 2X + Y\n\n uint_bitarray_t * X = calloc(state->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * Y = calloc(state->n, sizeof(uint_bitarray_t));\n\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < state->n; j++){\n uint_bitarray_t pc = (popcount(GT[i] & AJ[j]) % 4u);\n X[i] |= ((pc>>1) & ONE) << j;\n Y[i] |= ((pc) & ONE) << j;\n }\n }\n\n //add the contribution fron G^T D\n for(size_t i = 0; i < state->n; i++){\n X[i] ^= (Y[i] & GT[i] & AJd1); // carry if both bits are 1\n Y[i] ^= (GT[i] & AJd1);\n X[i] ^= (GT[i] & AJd2);\n }\n\n //now we compute K = G^T (A G) = G^T (G^T A^T)^T\n //we store K as a full symmetric matric of bits\n //we store the even part of the diagonal in bitarray bitKd2;\n //since the diagonal is the only bit we need mod-4\n //in other words K = bitK + 2*diag(bitKd2)\n uint_bitarray_t * bitK = calloc(state->n, sizeof(uint_bitarray_t));\n uint_bitarray_t bitKd2 = 0;\n\n\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < i; j++){ //symmetric\n uint_bitarray_t pb = parity(GT[i] & Y[j]) & ONE;\n bitK[i] |= pb << j;\n bitK[j] |= pb << i;\n }\n //now we need to work out the diagonal\n //slightly more care is needed here as we care about the diagonal mod-4\n uint_bitarray_t pc = popcount(GT[i] & Y[i]);\n bitK[i] |= (pc & ONE) << i;\n bitKd2 |= (((pc>>1) & ONE) ^ (parity(GT[i] & X[i]) & ONE)) << i;\n }\n free(X);\n free(Y);\n\n unsigned int n = popcount(state->v);\n\n uint_bitarray_t sK = 0;\n unsigned int sKs = 0;\n for(size_t a = 0; a < state->n; a++){\n unsigned int pc = popcount(state->s & bitK[a]) % 4u;\n sK |= (pc & ONE) << a;\n sKs += pc * ((state->s >> a) & ONE);\n }\n\n sKs += 2*popcount(bitKd2 & state->s);\n\n //add 2*diag(s + sK) onto K\n bitKd2 ^= (state->s ^ sK);\n\n\n double complex prefactor = pow(0.5, (state->n+n)/2.);\n //printf(\"c sKs: %d, sKs2: %u\\n\", popcount(state->s & sK), sKs);\n unsigned int d = (sKs + 2 * popcount(state->s & state->v)) % 4u;\n if(d == 1){\n prefactor *= I;\n }else if(d == 2){\n prefactor *= -1.;\n }else if(d == 3){\n prefactor *= -1.*I;\n }\n\n uint_bitarray_t k = 0;\n uint_bitarray_t L = 0;\n\n uint_bitarray_t * M = calloc(n+1, sizeof(uint_bitarray_t));\n int fill_count_a = 0;\n\n for(int a = 0; (an); a++){\n if((state->v >> a) & ONE){\n k |= ((bitK[a] >> a) & ONE) << fill_count_a;\n L |= ((bitKd2 >> a) & ONE) << fill_count_a;\n fill_count_a += 1;\n }\n }\n fill_count_a = 0;\n int fill_count_b = 0;\n for(int a = 0; (an); a++){\n if((state->v >> a) & ONE){\n for(int b = 0; (bv >> b) & ONE){\n M[fill_count_b] |= (((bitK[b] >> a) & ONE) ^ ((k >> fill_count_a) & (k >> fill_count_b) & ONE)) << fill_count_a;\n fill_count_b += 1;\n }\n }\n fill_count_a += 1;\n fill_count_b = 0;\n }\n }\n M[n] = k;\n n +=1;\n\n //at this point we only need M and l\n //so free everything else\n free(bitK);\n free(AJ);\n free(GT);\n double re=0, im=0;\n int killed = 0;\n int exponent_of_2 = 0;\n bool exponent_of_minus_1 = false;\n bool last_element_asymetric = false;\n bool mu1_consts = false;\n bool mu2_consts = false;\n\n uint_fast64_t mask = 0;\n for(uint i = 0; i < n; i++){\n mask |= (ONE << i);\n }\n //printf(\"eb\\n\");\n while(true){\n uint r=0, c=0;\n bool found = false;\n for(uint i = 0; i < n && !found; i++){\n for(uint j = 0; j < i && !found; j++){\n if(((M[i] >> j) & ONE) != ((M[j] >> i) & ONE)){\n r=i;\n c=j;\n found = true;\n }\n }\n }\n if(!found){\n //this is trivial apparently\n uint_bitarray_t diag = 0;\n for(uint i=0;i> i) & ONE) << i;\n }\n if(last_element_asymetric){\n if((diag & mask) == (L&mask)){\n //printf(\"c1\\n\");\n double signR = exponent_of_minus_1 ? (-1.) : 1.;\n bool new_exponent_of_minus_1 = (exponent_of_minus_1 ^ mu2_consts);\n double signI = new_exponent_of_minus_1 ? (-1.) : 1.;\n re = pow(2., exponent_of_2 + n - killed)*signR;\n im = pow(2., exponent_of_2 + n - killed)*signI;\n break;\n }else{\n re = 0.;\n im = 0.;\n break;\n }\n }else{\n if( ((diag & (~(ONE<<(n-1)))) & mask) == ((L & (~(ONE<<(n-1)))) & mask)){\n if( ((diag & (ONE << (n-1)))&mask) == ((L & (ONE << (n-1)))&mask)){\n double signR = exponent_of_minus_1 ? (-1.) : 1.;\n re = signR * pow(2., exponent_of_2+n-killed);\n im = 0;\n break;\n }else{\n re = 0;\n double signI = exponent_of_minus_1 ? (-1.) : 1.;\n im = signI * pow(2., exponent_of_2+n-killed);\n break;\n }\n\n }else{\n re = 0;\n im = 0;\n break;\n }\n }\n }else{\n if(r+1 == n){\n last_element_asymetric = true;\n }\n\n killed += 2;\n uint_fast64_t m1 = M[r];\n uint_fast64_t m2 = M[c];\n\n for(uint i=0; i> r) & ONE) << i);\n m2 ^= (((M[i] >> c) & ONE) << i);\n }\n m1 &= (~(ONE << r));\n m1 &= (~(ONE << c));\n m2 &= (~(ONE << r));\n m2 &= (~(ONE << c));\n\n mu1_consts = ((L>>r) & ONE) ^ ((M[r]>>r) & ONE);\n mu2_consts = ((L>>c) & ONE) ^ ((M[c]>>c) & ONE);\n\n M[r] = 0;\n M[c] = 0;\n for(uint i=0; i>i) & ONE){\n M[i] ^= m2;\n }\n }\n if(mu1_consts){\n L ^= m2;\n }\n if(mu2_consts){\n L ^= m1;\n }\n }\n }\n\n\n free(M);\n\n //printf(\"en\\n\");\n return conj(state->w) * prefactor * (re +im*I)/2;\n}\n\n\ndouble complex equatorial_inner_product_no_alloc(CHForm* state,\n equatorial_matrix_t equatorial_state,\n uint_bitarray_t * AJ,\n uint_bitarray_t * GT,\n uint_bitarray_t * X,\n uint_bitarray_t * Y,\n uint_bitarray_t * bitK,\n uint_bitarray_t * M){\n if(state->n == 0){\n return conj(state->w);\n }\n //we store A+J in AJ\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < i; j++){\n uint_bitarray_t bit = parity(state->M[i] & state->F[j]) & ONE;\n AJ[i] |= (bit << j);\n AJ[j] |= (bit << i);\n }\n }\n\n //add A to J\n for(size_t i = 0; i < state->n; i++){\n AJ[i] ^= equatorial_state.mat[i];\n AJ[i] &= ~(ONE<g1);\n AJd1 ^= state->g1;\n AJd2 ^= state->g2;\n\n //now we want to compute (A G)^T = G^T A^T\n //this is because doing X Y^T is generally faster than doing XY\n //since we can do the row / row dot products with popcount(x & y)\n //we need to know the value of G^T A^T mod-4 so we can work out what the diagonal of G^T A G should be\n //so we store it in two binary matrices X and Y such that G^T A^T = 2X + Y\n\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < state->n; j++){\n uint_bitarray_t pc = (popcount(GT[i] & AJ[j]) % 4u);\n X[i] |= ((pc>>1) & ONE) << j;\n Y[i] |= ((pc) & ONE) << j;\n }\n }\n\n //add the contribution fron G^T D\n for(size_t i = 0; i < state->n; i++){\n X[i] ^= (Y[i] & GT[i] & AJd1); // carry if both bits are 1\n Y[i] ^= (GT[i] & AJd1);\n X[i] ^= (GT[i] & AJd2);\n }\n\n //now we compute K = G^T (A G) = G^T (G^T A^T)^T\n //we store K as a full symmetric matric of bits\n //we store the even part of the diagonal in bitarray bitKd2;\n //since the diagonal is the only bit we need mod-4\n //in other words K = bitK + 2*diag(bitKd2)\n\n uint_bitarray_t bitKd2 = 0;\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < i; j++){ //symmetric\n uint_bitarray_t pb = parity(GT[i] & Y[j]) & ONE;\n bitK[i] |= pb << j;\n bitK[j] |= pb << i;\n }\n //now we need to work out the diagonal\n //slightly more care is needed here as we care about the diagonal mod-4\n uint_bitarray_t pc = popcount(GT[i] & Y[i]);\n bitK[i] |= (pc & ONE) << i;\n bitKd2 |= (((pc>>1) & ONE) ^ (parity(GT[i] & X[i]) & ONE)) << i;\n }\n //free(X);\n //free(Y);\n memset(X, 0, sizeof(uint_bitarray_t)*state->n);\n memset(Y, 0, sizeof(uint_bitarray_t)*state->n);\n\n unsigned int n = popcount(state->v);\n\n uint_bitarray_t sK = 0;\n unsigned int sKs = 0;\n for(size_t a = 0; a < state->n; a++){\n unsigned int pc = popcount(state->s & bitK[a]) % 4u;\n sK |= (pc & ONE) << a;\n sKs += pc * ((state->s >> a) & ONE);\n }\n\n sKs += 2*popcount(bitKd2 & state->s);\n\n //add 2*diag(s + sK) onto K\n bitKd2 ^= (state->s ^ sK);\n\n\n double complex prefactor = pow(0.5, (state->n+n)/2.);\n //printf(\"c sKs: %d, sKs2: %u\\n\", popcount(state->s & sK), sKs);\n unsigned int d = (sKs + 2 * popcount(state->s & state->v)) % 4u;\n if(d == 1){\n prefactor *= I;\n }else if(d == 2){\n prefactor *= -1.;\n }else if(d == 3){\n prefactor *= -1.*I;\n }\n\n uint_bitarray_t k = 0;\n uint_bitarray_t L = 0;\n\n //uint_bitarray_t * M = calloc(n+1, sizeof(uint_bitarray_t));\n int fill_count_a = 0;\n\n for(int a = 0; (an); a++){\n if((state->v >> a) & ONE){\n k |= ((bitK[a] >> a) & ONE) << fill_count_a;\n L |= ((bitKd2 >> a) & ONE) << fill_count_a;\n fill_count_a += 1;\n }\n }\n fill_count_a = 0;\n int fill_count_b = 0;\n for(int a = 0; (an); a++){\n if((state->v >> a) & ONE){\n for(int b = 0; (bv >> b) & ONE){\n M[fill_count_b] |= (((bitK[b] >> a) & ONE) ^ ((k >> fill_count_a) & (k >> fill_count_b) & ONE)) << fill_count_a;\n fill_count_b += 1;\n }\n }\n fill_count_a += 1;\n fill_count_b = 0;\n }\n }\n M[n] = k;\n n +=1;\n\n //at this point we only need M and l\n //so free everything else\n memset(bitK, 0, sizeof(uint_bitarray_t)*state->n);\n memset(AJ, 0, sizeof(uint_bitarray_t)*state->n);\n //memset(GT, 0, sizeof(uint_bitarray_t)*state->n);\n //free(bitK);\n //free(AJ);\n //free(GT);\n double re=0, im=0;\n int killed = 0;\n int exponent_of_2 = 0;\n bool exponent_of_minus_1 = false;\n bool last_element_asymetric = false;\n bool mu1_consts = false;\n bool mu2_consts = false;\n\n uint_bitarray_t mask = 0;\n for(uint i = 0; i < n; i++){\n mask |= (ONE << i);\n }\n //printf(\"eb\\n\");\n while(true){\n uint r=0, c=0;\n bool found = false;\n\n for(uint i = 0; i < n && !found; i++){\n for(uint j = 0; j < i && !found; j++){\n if(((M[i] >> j) & ONE) != ((M[j] >> i) & ONE)){\n r=i;\n c=j;\n found = true;\n }\n }\n }\n if(!found){\n //this is trivial apparently\n uint_bitarray_t diag = 0;\n for(uint i=0;i> i) & ONE) << i;\n }\n if(last_element_asymetric){\n if((diag & mask) == (L&mask)){\n //printf(\"c1\\n\");\n double signR = exponent_of_minus_1 ? (-1.) : 1.;\n bool new_exponent_of_minus_1 = (exponent_of_minus_1 ^ mu2_consts);\n double signI = new_exponent_of_minus_1 ? (-1.) : 1.;\n re = pow(2., exponent_of_2 + n - killed)*signR;\n im = pow(2., exponent_of_2 + n - killed)*signI;\n break;\n }else{\n re = 0.;\n im = 0.;\n break;\n }\n }else{\n if( ((diag & (~(ONE<<(n-1)))) & mask) == ((L & (~(ONE<<(n-1)))) & mask)){\n if( ((diag & (ONE << (n-1)))&mask) == ((L & (ONE << (n-1)))&mask)){\n double signR = exponent_of_minus_1 ? (-1.) : 1.;\n re = signR * pow(2., exponent_of_2+n-killed);\n im = 0;\n break;\n }else{\n re = 0;\n double signI = exponent_of_minus_1 ? (-1.) : 1.;\n im = signI * pow(2., exponent_of_2+n-killed);\n break;\n }\n\n }else{\n re = 0;\n im = 0;\n break;\n }\n }\n }else{\n\t //swap row r and column r to row killed and column killed\n //swap row c and column c to row killed+1 and column killed+1\n uint_bitarray_t scratch_space = M[c];\n if(c != killed){\n M[c] = M[killed];\n M[killed] = scratch_space;\n\t \tfor(uint i=0; i < n;i++){\n\t \t M[i] ^= (((M[i] >> c) & ONE) << killed);\n\t \t M[i] ^= (((M[i] >> killed) & ONE) << c);\n\t \t M[i] ^= (((M[i] >> c) & ONE) << killed);\n\t \t}\n }\n\n if(r != (killed+1)){\n scratch_space = M[r];\n M[r] = M[killed+1];\n M[killed+1] = scratch_space;\n\t \tfor(uint i=0; i < n;i++){\n\t \t M[i] ^= (((M[i] >> r) & ONE) << (killed+1));\n\t \t M[i] ^= (((M[i] >> (killed+1)) & ONE) << r);\n\t \t M[i] ^= (((M[i] >> r) & ONE) << (killed+1));\n\t \t}\n }\n\n\t if(r+1 == n){\n last_element_asymetric = true;\n }\n\t c = killed;\n\t r = killed+1;\n\n\t killed += 2;\n uint_bitarray_t m1 = M[r];\n uint_bitarray_t m2 = M[c];\n\n for(uint i=0; i> r) & ONE) << i);\n m2 ^= (((M[i] >> c) & ONE) << i);\n }\n m1 &= (~(ONE << r));\n m1 &= (~(ONE << c));\n m2 &= (~(ONE << r));\n m2 &= (~(ONE << c));\n\n mu1_consts = ((L>>r) & ONE) ^ ((M[r]>>r) & ONE);\n mu2_consts = ((L>>c) & ONE) ^ ((M[c]>>c) & ONE);\n \n L &= (~(ONE << r));\n L &= (~(ONE << c));\n exponent_of_2 += 1;\n exponent_of_minus_1 ^= (mu1_consts & mu2_consts);\n\n for(uint i=0;i>i) & ONE){\n M[i] ^= m2;\n }\n }\n if(mu1_consts){\n L ^= m2;\n }\n if(mu2_consts){\n L ^= m1;\n }\n\t M[r] = 0;\n M[c] = 0;\n for(uint i=0; in+1));\n //free(M);\n\n //printf(\"en\\n\");\n return conj(state->w) * prefactor * (re +im*I)/2;\n}\n\n\ndouble complex equatorial_inner_product2(CHForm* state, uint_bitarray_t * A, uint_bitarray_t * GT, equatorial_matrix_t equatorial_state){\n\n //we store A+J in AJ\n uint_bitarray_t * AJ = calloc(state->n, sizeof(uint_bitarray_t));\n\n //add A to J\n for(size_t i = 0; i < state->n; i++){\n AJ[i] |= (A[i] ^ equatorial_state.mat[i]);\n }\n //now we need to sort out the diagonal\n uint_bitarray_t AJd1 = equatorial_state.d1;\n uint_bitarray_t AJd2 = equatorial_state.d2;\n\n AJd2 ^= (AJd1 & state->g1);\n AJd1 ^= state->g1;\n AJd2 ^= state->g2;\n\n\n //now we want to compute (A G)^T = G^T A^T\n //this is because doing X Y^T is generally faster than doing XY\n //since we can do the row / row dot products with popcount(x & y)\n //we need to know the value of G^T A^T mod-4 so we can work out what the diagonal of G^T A G should be\n //so we store it in two binary matrices X and Y such that G^T A^T = 2X + Y\n\n uint_bitarray_t * X = calloc(state->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * Y = calloc(state->n, sizeof(uint_bitarray_t));\n\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < state->n; j++){\n uint_bitarray_t pc = (popcount(GT[i] & AJ[j]) % 4u);\n X[i] |= ((pc>>1) & ONE) << j;\n Y[i] |= ((pc) & ONE) << j;\n }\n }\n\n //add the contribution fron G^T D\n for(size_t i = 0; i < state->n; i++){\n X[i] ^= (Y[i] & GT[i] & AJd1); // carry if both bits are 1\n Y[i] ^= (GT[i] & AJd1);\n X[i] ^= (GT[i] & AJd2);\n }\n\n\n //now we compute K = G^T (A G) = G^T (G^T A^T)^T\n //we store K as a full symmetric matric of bits\n //we store the even part of the diagonal in bitarray bitKd2;\n //since the diagonal is the only bit we need mod-4\n //in other words K = bitK + 2*diag(bitKd2)\n uint_bitarray_t * bitK = calloc(state->n, sizeof(uint_bitarray_t));\n uint_bitarray_t bitKd2 = 0;\n\n\n for(size_t i = 0; i < state->n; i++){\n for(size_t j = 0; j < i; j++){ //symmetric\n uint_bitarray_t pb = parity(GT[i] & Y[j]) & ONE;\n bitK[i] |= pb << j;\n bitK[j] |= pb << i;\n }\n //now we need to work out the diagonal\n //slightly more care is needed here as we care about the diagonal mod-4\n uint_bitarray_t pc = popcount(GT[i] & Y[i]);\n bitK[i] |= (pc & ONE) << i;\n bitKd2 |= (((pc>>1) & ONE) ^ (parity(GT[i] & X[i]) & ONE)) << i;\n }\n free(X);\n free(Y);\n\n unsigned int n = popcount(state->v);\n\n uint_bitarray_t sK = 0;\n unsigned int sKs = 0;\n for(size_t a = 0; a < state->n; a++){\n unsigned int pc = popcount(state->s & bitK[a]) % 4u;\n sK |= (pc & ONE) << a;\n sKs += pc * ((state->s >> a) & ONE);\n }\n\n sKs += 2*popcount(bitKd2 & state->s);\n\n //add 2*diag(s + sK) onto K\n bitKd2 ^= (state->s ^ sK);\n\n\n double complex prefactor = pow(0.5, (state->n+n)/2.);\n //printf(\"c sKs: %d, sKs2: %u\\n\", popcount(state->s & sK), sKs);\n unsigned int d = (sKs + 2 * popcount(state->s & state->v)) % 4u;\n if(d == 1){\n prefactor *= I;\n }else if(d == 2){\n prefactor *= -1.;\n }else if(d == 3){\n prefactor *= -1.*I;\n }\n\n uint_bitarray_t k = 0;\n uint_bitarray_t L = 0;\n\n uint_bitarray_t * M = calloc(n+1, sizeof(uint_bitarray_t));\n int fill_count_a = 0;\n\n for(int a = 0; (an); a++){\n if((state->v >> a) & ONE){\n k |= ((bitK[a] >> a) & ONE) << fill_count_a;\n L |= ((bitKd2 >> a) & ONE) << fill_count_a;\n fill_count_a += 1;\n }\n }\n fill_count_a = 0;\n int fill_count_b = 0;\n for(int a = 0; (an); a++){\n if((state->v >> a) & ONE){\n for(int b = 0; (bv >> b) & ONE){\n M[fill_count_b] |= (((bitK[b] >> a) & ONE) ^ ((k >> fill_count_a) & (k >> fill_count_b) & ONE)) << fill_count_a;\n fill_count_b += 1;\n }\n }\n fill_count_a += 1;\n fill_count_b = 0;\n }\n }\n M[n] = k;\n n +=1;\n\n //at this point we only need M and l\n //so free everything else\n free(bitK);\n free(AJ);\n //free(GT);\n double re=0, im=0;\n int killed = 0;\n int exponent_of_2 = 0;\n bool exponent_of_minus_1 = false;\n bool last_element_asymetric = false;\n bool mu1_consts = false;\n bool mu2_consts = false;\n\n uint_fast64_t mask = 0;\n for(uint i = 0; i < n; i++){\n mask |= (ONE << i);\n }\n //printf(\"eb\\n\");\n while(true){\n uint r=0, c=0;\n bool found = false;\n for(uint i = 0; i < n && !found; i++){\n for(uint j = 0; j < i && !found; j++){\n if(((M[i] >> j) & ONE) != ((M[j] >> i) & ONE)){\n r=i;\n c=j;\n found = true;\n }\n }\n }\n if(!found){\n //this is trivial apparently\n uint_bitarray_t diag = 0;\n for(uint i=0;i> i) & ONE) << i;\n }\n if(last_element_asymetric){\n if((diag & mask) == (L&mask)){\n //printf(\"c1\\n\");\n double signR = exponent_of_minus_1 ? (-1.) : 1.;\n bool new_exponent_of_minus_1 = (exponent_of_minus_1 ^ mu2_consts);\n double signI = new_exponent_of_minus_1 ? (-1.) : 1.;\n re = pow(2., exponent_of_2 + n - killed)*signR;\n im = pow(2., exponent_of_2 + n - killed)*signI;\n break;\n }else{\n re = 0.;\n im = 0.;\n break;\n }\n }else{\n if( ((diag & (~(ONE<<(n-1)))) & mask) == ((L & (~(ONE<<(n-1)))) & mask)){\n if( ((diag & (ONE << (n-1)))&mask) == ((L & (ONE << (n-1)))&mask)){\n double signR = exponent_of_minus_1 ? (-1.) : 1.;\n re = signR * pow(2., exponent_of_2+n-killed);\n im = 0;\n break;\n }else{\n re = 0;\n double signI = exponent_of_minus_1 ? (-1.) : 1.;\n im = signI * pow(2., exponent_of_2+n-killed);\n break;\n }\n\n }else{\n re = 0;\n im = 0;\n break;\n }\n }\n }else{\n if(r+1 == n){\n last_element_asymetric = true;\n }\n\n killed += 2;\n uint_fast64_t m1 = M[r];\n uint_fast64_t m2 = M[c];\n\n for(uint i=0; i> r) & ONE) << i);\n m2 ^= (((M[i] >> c) & ONE) << i);\n }\n m1 &= (~(ONE << r));\n m1 &= (~(ONE << c));\n m2 &= (~(ONE << r));\n m2 &= (~(ONE << c));\n\n mu1_consts = ((L>>r) & ONE) ^ ((M[r]>>r) & ONE);\n mu2_consts = ((L>>c) & ONE) ^ ((M[c]>>c) & ONE);\n\n M[r] = 0;\n M[c] = 0;\n for(uint i=0; i>i) & ONE){\n M[i] ^= m2;\n }\n }\n if(mu1_consts){\n L ^= m2;\n }\n if(mu2_consts){\n L ^= m1;\n }\n }\n }\n\n\n\n free(M);\n\n //printf(\"en\\n\");\n return conj(state->w) * prefactor * (re +im*I)/2;\n}\n\n\nstatic void partial_equatorial_inner_product(CHForm* state, equatorial_matrix_t equatorial_state, uint_bitarray_t mask){\n int stateI = 0;\n int stateJ = 0;\n\n for(int i = 0; i < equatorial_state.n; i++){\n while((((mask >> stateI) & ONE) == 0) && (stateI < state->n)){\n stateI += 1;\n }\n //printf(\"%u, %u\\n\", (unsigned int)((equatorial_state.d1 >> i) & ONE) , (unsigned int)((equatorial_state.d2 >> i) & ONE));\n if(stateI < state->n){\n for(int k = 0; k < 4-((((equatorial_state.d1 >> i) & ONE) + 2*((equatorial_state.d2 >> i) & ONE))%4); k++){\n SL(state, stateI);\n }\n\n for(int j=0; j < i; j++){\n while((((mask >> stateJ) & ONE) == 0) && (stateJ < state->n)){\n stateJ += 1;\n }\n if(stateJ < state->n){\n if((equatorial_state.mat[i] >> j) & ONE){\n CZL(state, stateI, stateJ);\n }\n stateJ += 1;\n }\n\n }\n stateI += 1;\n }\n stateJ = 0;\n }\n\n stateI = 0;\n\n for(int i = 0; i < equatorial_state.n; i++){\n while((((mask >> stateI) & ONE) == 0) && (stateI < state->n)){\n stateI += 1;\n }\n if(stateI < state->n){\n HL(state, stateI);\n stateI += 1;\n }\n\n }\n postselect_and_reduce(state, 0u, mask);\n}\n\ndouble complex equatorial_inner_product3(CHForm* state, equatorial_matrix_t equatorial_state){\n CHForm copy = copy_CHForm(state);\n uint_bitarray_t mask = 0u;\n for(int i = 0; i < equatorial_state.n; i++){\n mask |= (ONE << i);\n for(int j = 0; j < i; j++){\n if((equatorial_state.mat[i] >> j) & ONE){\n CZL(©, i, j);\n }\n }\n\n if((equatorial_state.d1 >> i) & ONE){\n SL(©, i);\n }\n if((equatorial_state.d2 >> i) & ONE){\n SL(©, i);\n SL(©, i);\n }\n\n HL(©, i);\n }\n\n //now we are attempting to compute w <0| UC UH |s> = w<0|UH|s>\n //int v0s0 = popcount(mask & (~copy.v) & (~copy.s));\n int v0s1 = popcount(mask & (~copy.v) & ( copy.s));\n int v1s0 = popcount(mask & ( copy.v) & (~copy.s));\n int v1s1 = popcount(mask & ( copy.v) & ( copy.s));\n\n if(v0s1 > 0){\n dealocate_state(©);\n return 0.;\n }\n\n if(v1s1 % 2 == 1){\n copy.w *= -1;\n }\n double complex val = copy.w * cpowl(1./sqrt(2), v1s0 + v1s1);\n dealocate_state(©);\n return val;\n}\n\n\nstatic PyObject * magic_sample_1(PyObject* self, PyObject* args){\n\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == 't'){\n gates->data[i*gates->strides[0]] = 'X';\n controls->data[i*controls->strides[0]] = (unsigned char)targets->data[i*targets->strides[0]];\n targets->data[i*targets->strides[0]] = (unsigned char)(n + t);\n t += 1;\n }\n }\n //printf(\"c1 t = %d\\n\", t);\n //now we do the Clifford evolution \"precomputation\"\n\n CHForm * evolved_state = c_apply_gates_to_basis_state(n+t, gates, controls, targets);\n\n //now we project onto the measurement outcomes for the w qubits\n //and throw away those qubits\n //leaving us with an n+t-w qubit state\n uint_bitarray_t bitA = 0;\n uint_bitarray_t bitMask = 0;\n\n for(int i = 0; i < n; i++){\n if((char)a->data[i*a->strides[0]]){\n bitA |= (ONE << i);\n }\n if((char)mask->data[i*mask->strides[0]]){\n bitMask |= (ONE << i);\n }\n }\n\n postselect_and_reduce(evolved_state, bitA, bitMask);\n //printf(\"c1 after postselection\\n\");\n //print_CHForm(evolved_state);\n //at this point we want to generate a list of length equatorial_samples\n //containing n - w - qubit equatorial states\n //ie. (n-w) x (n-w) binary symmetric matrices\n\n equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t));\n for(int i = 0; i < equatorial_samples; i++){\n init_random_equatorial_matrix(&(equatorial_matrices[i]), evolved_state->n - t);\n }\n\n uint_bitarray_t magic_mask = 0u;\n int w = evolved_state->n - t;\n //printf(\"w = %d\\n\", w);\n for(int i = evolved_state->n - t; i < evolved_state->n; i++){\n magic_mask |= (ONE<n - t, sizeof(uint_bitarray_t));\n //uint_bitarray_t * GT = calloc(evolved_state->n - t, sizeof(uint_bitarray_t));\n for(int i = 0; i < magic_samples; i++){\n //sample a bitstring y of length t\n //printf(\"y: \");printBits(y, evolved_state->n);\n\n int hamming_weight = popcount(ys[i]);\n //printf(\"c1 copy 1\\n\");\n //print_CHForm(evolved_state);\n CHForm copy = copy_CHForm(evolved_state);\n\n for(int k = evolved_state->n - t; k < evolved_state->n; k++){\n if((ys[i] >> k ) & ONE){\n SL(©, k);\n }\n HL(©, k);\n }\n\n postselect_and_reduce(©, (uint_bitarray_t)0, magic_mask);\n\n /* for(size_t i = 0; i < copy.n; i++){ */\n /* A[i] = 0u; */\n /* GT[i] = 0u; */\n /* } */\n /* for(size_t i = 0; i < copy.n; i++){ */\n /* for(size_t j = 0; j < i; j++){ */\n /* uint_bitarray_t bit = parity(copy.M[i] & copy.F[j]) & ONE; */\n /* A[i] |= (bit << j); */\n /* A[j] |= (bit << i); */\n /* GT[i] |= ((copy.G[j] >> i) & ONE) << j; */\n /* GT[j] |= ((copy.G[i] >> j) & ONE) << i; */\n /* } */\n /* } */\n\n\n\n //now copy is a state of n-w qubits\n\n double complex prefactor = powl(2., (t+ beta*t)/2.)*cpowl(alpha_c_phase, t-hamming_weight)*cpowl(alpha_phase, hamming_weight);\n\n for(int j = 0; j < equatorial_samples; j++){\n CHForm copy2 = copy_CHForm(©);\n double complex d = conj(equatorial_inner_product(©2, equatorial_matrices[j]))/(double)(magic_samples);\n\n inner_prods[j] += prefactor*d;\n dealocate_state(©2);\n //printf(\"1[%d,%d]: %d, (%lf, %lf), (%lf, %lf)\\n\",i, j, hamming_weight, creal(prefactor), cimag(prefactor), creal(d), cimag(d));\n }\n dealocate_state(©);\n\n }\n\n free(ys);\n //free(A);\n //free(GT);\n double acc = 0;\n for(int j = 0; j < equatorial_samples; j++){\n acc += powl(2,w)* creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples;\n }\n free(inner_prods);\n\n for(int j = 0; j < equatorial_samples; j++){\n dealocate_equatorial_matrix(&equatorial_matrices[j]);\n }\n free(equatorial_matrices);\n dealocate_state(evolved_state);\n free(evolved_state);\n\n return PyComplex_FromDoubles(creal(acc), cimag(acc));\n}\n\n\n\nstatic PyObject * magic_sample_2(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == 't'){\n gates->data[i*gates->strides[0]] = 'X';\n controls->data[i*controls->strides[0]] = targets->data[i*targets->strides[0]];\n targets->data[i*targets->strides[0]] = (unsigned char)(n + t);\n t += 1;\n }\n }\n //printf(\"c2 t = %d\\n\", t);\n //now we do the Clifford evolution \"precomputation\"\n\n CHForm * evolved_state = c_apply_gates_to_basis_state(n+t, gates, controls, targets);\n\n //now we project onto the measurement outcomes for the w qubits\n //and throw away those qubits\n //leaving us with an n+t-w qubit state\n uint_bitarray_t bitA = 0;\n uint_bitarray_t bitMask = 0;\n\n for(int i = 0; i < n; i++){\n if((a->data[i*a->strides[0]]) & ONE){\n bitA |= (ONE << i);\n }\n if((mask->data[i*mask->strides[0]]) & ONE){\n bitMask |= (ONE << i);\n }\n }\n postselect_and_reduce(evolved_state, bitA, bitMask);\n //printf(\"c2 after postselection\\n\");\n //print_CHForm(evolved_state);\n\n\n //at this point we want to generate a list of length equatorial_samples\n //containing n - w - qubit equatorial states\n //ie. (n-w) x (n-w) binary symmetric matrices\n\n equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t));\n for(int i = 0; i < equatorial_samples; i++){\n init_random_equatorial_matrix(&(equatorial_matrices[i]), evolved_state->n - t);\n }\n\n uint_bitarray_t magic_mask = 0;\n int w = evolved_state->n - t;\n\n for(int i = evolved_state->n - t; i < evolved_state->n; i++){\n magic_mask |= (ONE<> (evolved_state->n - t);\n }\n\n\n uint_bitarray_t equatorial_mask = 0;\n for(int i = 0; i < evolved_state->n - t; i++){\n equatorial_mask |= (ONE << i);\n }\n\n\n /* printf(\"magic 2:\\n\"); */\n /* printf(\"equatorial mask\\n\"); */\n /* printBits(equatorial_mask, evolved_state->n);printf(\"\\n\"); */\n /* printf(\"magic mask\\n\"); */\n /* printBits(magic_mask, evolved_state->n);printf(\"\\n\"); */\n /* printf(\"ys[0]\\n\"); */\n /* printBits(ys[0], evolved_state->n);printf(\"\\n\"); */\n /* printf(\"\\n\"); */\n /* printf(\"c2 equatorial matrix\\n\"); */\n /* for(int i = 0; i < equatorial_matrices[0].n; i++){ */\n /* printBits(equatorial_matrices[0].mat[i], equatorial_matrices[0].n);printf(\"\\n\"); */\n /* } */\n /* printBits(equatorial_matrices[0].d1, equatorial_matrices[0].n);printf(\"\\n\"); */\n /* printBits(equatorial_matrices[0].d2, equatorial_matrices[0].n);printf(\"\\n\"); */\n\n\n double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.;\n double beta = log2(4. - 2.*sqrt(2.));\n double complex acc = 0;\n double complex alpha_phase = alpha / sqrt(1.-1./sqrt(2.));\n double complex alpha_c_phase = conj(alpha_phase);\n\n for(int j = 0; j < equatorial_samples; j++){\n CHForm copy = copy_CHForm(evolved_state);\n partial_equatorial_inner_product(©, equatorial_matrices[j], equatorial_mask);\n\n //printf(\"c2 copy after equatorial partial product\\n\");\n //print_CHForm(©);\n //at this point we have a t qubit state and we take the inner product with each magic sample\n double complex overlaps = 0;\n for(int i = 0; i < magic_samples; i++){\n CHForm inner_copy = copy_CHForm(©);\n //uint_bitarray_t y = bitarray_rand() & magic_mask;\n int hamming_weight = popcount(ys[i]);\n double complex prefactor = powl(2., (t+ beta*t)/2)*cpowl(alpha_c_phase, t-hamming_weight)*cpowl(alpha_phase, hamming_weight);\n //printf(\"c2 prefactor(%lf, %lf)\\n\", creal(prefactor), cimag(prefactor));\n for(int k = 0; k < inner_copy.n; k++){\n if((ys[i] >> k) & ONE){\n SL(&inner_copy, k);\n //SL(&inner_copy, k);\n //SL(&inner_copy, k);\n }\n HL(&inner_copy, k);\n }\n double complex d = measurement_overlap(&inner_copy, (uint_bitarray_t)0)/magic_samples;\n //printf(\"2[%d,%d]: %d, (%lf, %lf), (%lf, %lf)\\n\",i, j, hamming_weight, creal(prefactor), cimag(prefactor), creal(d), cimag(d));\n overlaps += prefactor*d;\n dealocate_state(&inner_copy);\n }\n acc += powl(2.,w)*creal(overlaps*conj(overlaps))/(double)equatorial_samples;\n dealocate_state(©);\n }\n\n for(int i = 0; i < equatorial_samples; i++){\n dealocate_equatorial_matrix(&equatorial_matrices[i]);\n }\n\n free(equatorial_matrices);\n dealocate_state(evolved_state);\n //printf(\"c2(%lf, %lf)\\n\", creal(acc), cimag(acc));\n return PyComplex_FromDoubles(creal(acc), cimag(acc));\n}\n\n\nstatic PyObject * main_simulation_algorithm(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n //controls->data[i*controls->strides[0]] = (unsigned int)targets->data[i*targets->strides[0]];\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n t += 1;\n }\n }\n\n //now we do the stabiliser evolution\n //to compute W\n\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((char)gates->data[i*gates->strides[0]]) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n for(int i = 0; i < measured_qubits; i++){\n if((unsigned char)a->data[i*a->strides[0]]){\n StabTable_X(state, i);\n }\n }\n\n\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n if(log_v < 0){\n return PyComplex_FromDoubles(0., 0.);\n }\n\n //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits\n //at this point we should just be left with t qubits\n int q_to_delete = state->n - t;\n int new_size = t;\n for(int s = 0; s < state->k; s++){\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-q_to_delete] = state->table[s][q];\n }\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n];\n }\n state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size);\n }\n state->n = new_size;\n\n\n QCircuit * W = StabTable_simplifying_unitary(state);\n //printf(\"after computing W\\n\");\n\n state->circ = NULL;\n\n //now we have to work out what we need to do magic sampling with this W circuit\n //we need the CH-form for W|\\tilde{0}>\n //and the AG tableau for W|0> (no tilde!)\n\n CHForm chState;\n init_cb_CHForm(t,&chState);\n //Hadamard everything because we want to know the evolution of |\\tilde{0}> = |+>\n for(int i = 0; i < t; i++){\n HL(&chState, i);\n }\n //printf(\"before computing chState & agState\\n\");\n StabTable * agState = StabTable_new(t,t);\n\n for(int i = 0; i < W->length; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, W->tape[i].tag, W->tape[i].control, W->tape[i].target);\n switch(W->tape[i].tag) {\n case CX:\n CXL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CX(agState, W->tape[i].control, W->tape[i].target);\n //StabTable_CX(stateCopy, W->tape[i].control, W->tape[i].target);\n break;\n case CZ:\n CZL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CZ(agState, W->tape[i].control, W->tape[i].target);\n //StabTable_CZ(stateCopy, W->tape[i].control, W->tape[i].target);\n break;\n case S:\n SL(&chState, W->tape[i].target);\n StabTable_S(agState, W->tape[i].target);\n //StabTable_S(stateCopy, W->tape[i].target);\n break;\n case H:\n HL(&chState, W->tape[i].target);\n StabTable_H(agState, W->tape[i].target);\n //StabTable_H(stateCopy, W->tape[i].target);\n break;\n }\n }\n /* printf(\"Action of W\\n\"); */\n /* StabTable_print(stateCopy); */\n /* StabTable_free(stateCopy); */\n /* return PyComplex_FromDoubles(0, 0); */\n //printf(\"after computing chState & agState\\n\");\n //now S_k^3 = e^{-i\\pi/4} (1/sqrt(2)) (I + i Z_k)\n //W S_k^3 W^\\dagger = e^{-i\\pi/4} (1/sqrt(2)) (I + i W Z_k W^\\dagger)\n //W Z_k W^\\dagger is exactly the k^th row of agState\n //Now we have to apply e^{-i\\pi/4} (1/sqrt(2)) (I + i W Z_k W^\\dagger) to w UC UH |s>\n //e^{-i\\pi/4} (1/sqrt(2)) w (I + i W Z_k W^\\dagger)UC UH |s> = e^{-i\\pi/4} (1/sqrt(2)) w UC (UC^\\dagger(I + i W Z_k W^\\dagger)UC) UH |s>\n // = e^{-i\\pi/4} (1/sqrt(2)) w UC (I + i UC^\\dagger W Z_k W^\\dagger UC) UH |s>\n\n //printf(\"before freeing W\\n\");\n //QCircuit_free(W);\n //printf(\"after freeing W\\n\");\n\n //at this point we want to generate a list of length equatorial_samples\n //containing t - r - qubit equatorial states\n //ie. (t-r) x (t-r) binary symmetric matrices\n equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t));\n for(int i = 0; i < equatorial_samples; i++){\n init_random_equatorial_matrix(&(equatorial_matrices[i]), state->n-state->k);\n }\n //printf(\"a\\n\");\n uint_bitarray_t magic_mask = 0;\n\n for(int i = 0; i < t; i++){\n magic_mask |= (ONE<n-state->k; i++){\n equatorial_mask |= (ONE << i);\n }\n //printf(\"d\\n\");\n //we project onto 0 and throw away the first t-r qubits\n //leaving us with an r qubit state\n uint_bitarray_t bitA = 0;\n uint_bitarray_t bitMask = 0;\n for(int i = 0; i < state->k; i++){\n bitMask |= (ONE << i);\n }\n\n //printf(\"e\\n\");\n double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex));\n double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.;\n double beta = log2(4. - 2.*sqrt(2.));\n double complex alpha_phase = alpha / cabs(alpha);\n double complex alpha_c_phase = conj(alpha_phase);\n\n double sampling_time = 0.;\n double norm_est_time = 0.;\n clock_t start;\n clock_t end;\n\n\n for(int i = 0; i < magic_samples; i++){\n start = clock();\n //printf(\"%d\\n\", i);\n //generate our state\n CHForm copy = copy_CHForm(&chState);\n\n for(int bit = 0; bit < t; bit++){\n if((ys[i] >> bit) & ONE){\n //apply W S^3_bit W^\\dagger to chState\n uint_bitarray_t * z_mat = calloc(t, sizeof(uint_bitarray_t));\n uint_bitarray_t * x_mat = calloc(t, sizeof(uint_bitarray_t));\n\n uint_bitarray_t mask = (uint_bitarray_t)0;\n uint_bitarray_t t_mask = (uint_bitarray_t)0;\n\n unsigned int g = 2*agState->phases[bit] ;\n for(int j = 0; j < t; j++){\n if(agState->table[bit][j]){\n x_mat[j] = copy.F[j];\n z_mat[j] = copy.M[j];\n mask |= (ONE << j);\n }\n if(agState->table[bit][j+agState->n]){\n z_mat[j] ^= copy.G[j];\n }\n t_mask |= (ONE << j);\n //if x and z are both 1 we get a factor of i because iXZ == Y\n if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){\n g += 1;\n }\n\n }\n g += popcount(copy.g1 & mask) + 2*popcount(copy.g2 & mask);\n g += 2*sort_pauli_string(t, x_mat, z_mat, mask);\n\n uint_bitarray_t u = 0u; // u_m is exponent of X_m\n uint_bitarray_t h = 0u; // h_m is exponent of Z_m\n\n for(int k = 0; k < t; k++){\n if(agState->table[bit][k]){\n u ^= (copy.F[k] & t_mask);\n h ^= (copy.M[k] & t_mask);\n }\n if(agState->table[bit][k+agState->n]){\n h ^= (copy.G[k] & t_mask);\n }\n }\n //at this point the state we want is w U_c [I + i^g \\prod_m Z_m^{h_m}X_m^{u_m}] U_H |s>\n //we need to commute the product through U_H\n //and then desuperpositionise\n //we pull the same trick again\n // (\\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\\dagger (\\prod_m Z_m^{h_m}X_m^{u_m}) U_H)\n //n.b. Hadamard is self-adjoint\n //what happens - if V_k is zero then nothing happens\n //if V_k is 1 then we swap X and Z\n //if V_k is 1 and X and Z are both 1 we get a minus sign\n\n uint_bitarray_t u2 = (u & (~copy.v)) ^ (h & (copy.v));\n uint_bitarray_t h2 = (h & (~copy.v)) ^ (u & (copy.v));\n g += 2*parity(u & h & copy.v & t_mask);\n\n\n //at this point the state we want is w U_c [I + i^g U_H \\prod_m Z_m^{h2_m} X_m^{u2_m}] |s>\n //we apply the paulis to |s>\n //every x flips a bit of s\n //every time a z hits a |1> we get a -1\n //xs happen first\n\n uint_bitarray_t y = (copy.s ^ u2) & t_mask;\n g += 2*parity(y & h2 & t_mask);\n g += 1; //an i appears in the expression for S^3 in terms of Z and I\n g %= 4;\n\n //at this point the state we want is w e^{-i\\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3\n if((y & t_mask) == (copy.s & t_mask)){\n double complex a = 1.;\n\n if(g == 0){\n a += 1.;\n }\n if(g == 1){\n a += (1.)*I;\n }\n if(g == 2){\n a += (-1.);\n }\n if(g == 3){\n a += (-1.*I);\n }\n\n copy.w *= (a*(1 - 1.*I)/2.);\n }else{\n desupersitionise(©, y, g);\n copy.w *= (1.-1.*I)/2.;\n }\n\n free(x_mat);\n free(z_mat);\n }\n }\n end = clock();\n sampling_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC;\n start = clock();\n //at this point copy contains our magic sample\n //we want to project it and do fastnorm estimation\n //printf(\"before: %d %lu\\n\", i, ys[i]);\n //print_CHForm(©);\n //printf(\"\\n\");\n\n //now we project onto the measurement outcomes for the w qubits\n postselect_and_reduce(©, bitA, bitMask);\n //printf(\"after: %d %lu\\n\", i, ys[i]);\n //print_CHForm(©);\n //printf(\"\\n\");\n int hamming_weight = popcount(ys[i]);\n //printf(\"%d\\n\", hamming_weight);\n //powl(2., log_v+t+beta*t+(agState->k-w)/2.)*cpowl(alpha, t-hamming_weight)*cpowl(alpha_c, hamming_weight);\n //printf(\"%lf, %d, %d, %d, %d\\n\", beta, t,log_v, measured_qubits, hamming_weight);\n //printf(\"%lf + %lf I\\n\", creal(alpha_phase), cimag(alpha_phase));\n //printf(\"%lf + %lf I\\n\", creal(alpha_c_phase), cimag(alpha_c_phase));\n double complex prefactor = powl(2., ((beta + 1)*t + log_v - measured_qubits)/2.)*cpowl(alpha_phase, t-hamming_weight)*cpowl(alpha_c_phase, hamming_weight);\n //printf(\"%lf + %lf I\\n\", creal(prefactor), cimag(prefactor));\n //equatorial_samples = 10;\n for(int j = 0; j < equatorial_samples; j++){\n //CHForm copy2 = copy_CHForm(©);\n double complex d = conj(equatorial_inner_product(©, equatorial_matrices[j]))/(double)(magic_samples);\n //printf(\"%lf + %lf*I\\n\", creal(d), cimag(d));\n inner_prods[j] += prefactor*d;\n //dealocate_state(©2);\n }\n\n end = clock();\n norm_est_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC;\n dealocate_state(©);\n }\n free(ys);\n //printf(\"sampling_time: %lf\\nnorm_est_time: %lf\\n\", sampling_time, norm_est_time);\n double acc = 0;\n for(int j = 0; j < equatorial_samples; j++){\n acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples;\n }\n free(inner_prods);\n\n for(int j = 0; j < equatorial_samples; j++){\n dealocate_equatorial_matrix(&equatorial_matrices[j]);\n }\n free(equatorial_matrices);\n StabTable_free(agState);\n dealocate_state(&chState);\n StabTable_free(state);\n //printf(\"c1(%lf, %lf)\\n\", creal(acc), cimag(acc));\n return PyComplex_FromDoubles(creal(acc), cimag(acc));\n}\n\nstatic PyObject * main_simulation_algorithm2(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n controls->data[i*controls->strides[0]] = targets->data[i*targets->strides[0]];\n targets->data[i*targets->strides[0]] = (unsigned char)(n + t);\n t += 1;\n }\n }\n\n //now we do the stabiliser evolution\n //to compute W\n\n StabTable * state = StabTable_new(n+t, n+t);\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n switch((char)gates->data[i*gates->strides[0]]) {\n case CX:\n StabTable_CX(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n case CZ:\n StabTable_CZ(state, (unsigned int)controls->data[i*controls->strides[0]], (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n case S:\n StabTable_S(state, (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n case H:\n StabTable_H(state, (unsigned int)targets->data[i*targets->strides[0]]);\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n for(int i = 0; i < measured_qubits; i++){\n if((unsigned char)a->data[i*a->strides[0]]){\n StabTable_X(state, i);\n }\n }\n\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n //printf(\"log_v = %d\\n\", log_v);\n if(log_v < 0){\n return PyComplex_FromDoubles(0., 0.);\n }\n /* //at this point state is a stab table with fewer stabs than qubits */\n /* //representing a mixed state */\n /* //it is still on n+t qubits */\n /* //but the first n qubits are trivial (the stabs are all the identity there) */\n /* //we can just delete them */\n //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits\n //at this point we should just be left with t qubits\n int q_to_delete = state->n - t;\n int new_size = t;\n for(int s = 0; s < state->k; s++){\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-q_to_delete] = state->table[s][q];\n }\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n];\n }\n state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size);\n }\n state->n = new_size;\n //printf(\"before computing W\\n\");\n QCircuit * W = StabTable_simplifying_unitary(state);\n //printf(\"after computing W\\n\");\n\n state->circ = NULL;\n\n //now we have to work out what we need to do magic sampling with this W circuit\n //we need the CH-form for W|\\tilde{0}>\n //and the AG tableau for W|0> (no tilde!)\n\n CHForm chState;\n init_cb_CHForm(t,&chState);\n //Hadamard everything because we want to know the evolution of |\\tilde{0}> = |+>\n for(int i = 0; i < t; i++){\n HL(&chState, i);\n }\n //printf(\"before computing chState & agState\\n\");\n StabTable * agState = StabTable_new(t,t);\n\n for(int i = 0; i < W->length; i++){\n switch(W->tape[i].tag) {\n case CX:\n CXL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CX(agState, W->tape[i].control, W->tape[i].target);\n break;\n case CZ:\n CZL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CZ(agState, W->tape[i].control, W->tape[i].target);\n break;\n case S:\n SL(&chState, W->tape[i].target);\n StabTable_S(agState, W->tape[i].target);\n break;\n case H:\n HL(&chState, W->tape[i].target);\n StabTable_H(agState, W->tape[i].target);\n break;\n }\n }\n //printf(\"after computing chState & agState\\n\");\n //now S_k^3 = e^{i\\pi/4} (1/sqrt(2)) (I + i Z_k)\n //W S_k^3 W^\\dagger = e^{i\\pi/4} (1/sqrt(2)) (I + i W Z_k W^\\dagger)\n //W Z_k W^\\dagger is exactly the k^th row of agState\n //Now we have to apply e^{i\\pi/4} (1/sqrt(2)) (I + i W Z_k W^\\dagger) to w UC UH |s>\n //e^{i\\pi/4} (1/sqrt(2)) w (I + i W Z_k W^\\dagger)UC UH |s> = e^{i\\pi/4} (1/sqrt(2)) w UC (UC^\\dagger(I + i W Z_k W^\\dagger)UC) UH |s>\n // = e^{i\\pi/4} (1/sqrt(2)) w UC (I + i UC^\\dagger W Z_k W^\\dagger UC) UH |s>\n\n //printf(\"before freeing W\\n\");\n //QCircuit_free(W);\n //printf(\"after freeing W\\n\");\n\n //at this point we want to generate a list of length equatorial_samples\n //containing t - r - qubit equatorial states\n //ie. (t-r) x (t-r) binary symmetric matrices\n equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t));\n for(int i = 0; i < equatorial_samples; i++){\n init_random_equatorial_matrix(&(equatorial_matrices[i]), state->n-state->k);\n }\n //printf(\"a\\n\");\n uint_bitarray_t magic_mask = 0;\n\n for(int i = 0; i < t; i++){\n magic_mask |= (ONE<n-state->k; i++){\n equatorial_mask |= (ONE << i);\n }\n //printf(\"d\\n\");\n //we project onto 0 and throw away the first t-r qubits\n //leaving us with an r qubit state\n uint_bitarray_t bitA = 0;\n uint_bitarray_t bitMask = 0;\n for(int i = 0; i < state->k; i++){\n bitMask |= (ONE << i);\n }\n\n //printf(\"e\\n\");\n double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex));\n double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.;\n double beta = log2(4. - 2.*sqrt(2.));\n double complex alpha_phase = alpha / cabs(alpha);\n double complex alpha_c_phase = conj(alpha_phase);\n\n double sampling_time = 0.;\n double norm_est_time = 0.;\n clock_t start;\n clock_t end;\n\n for(int i = 0; i < magic_samples; i++){\n start = clock();\n //printf(\"%d\\n\", i);\n //generate our state\n //CHForm copy = copy_CHForm(&chState);\n CHForm copy;\n init_cb_CHForm(t, ©);\n\n for(int bit = 0; bit < t; bit++){\n HL(©, bit);\n if((ys[i] >> bit) & ONE){\n SL(©, bit);\n SL(©, bit);\n SL(©, bit);\n }\n }\n\n for(int j = 0; j < W->length; j++){\n switch(W->tape[j].tag) {\n case CX:\n CXL(©, W->tape[j].control, W->tape[j].target);\n break;\n case CZ:\n CZL(©, W->tape[j].control, W->tape[j].target);\n break;\n case S:\n SL(©, W->tape[j].target);\n break;\n case H:\n HL(©, W->tape[j].target);\n break;\n }\n }\n\n end = clock();\n sampling_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC;\n start = clock();\n //at this point copy contains our magic sample\n //we want to project it and do fastnorm estimation\n\n //now we project onto the measurement outcomes for the w qubits\n postselect_and_reduce(©, bitA, bitMask);\n int hamming_weight = popcount(ys[i]);\n //powl(2., log_v+t+beta*t+(agState->k-w)/2.)*cpowl(alpha, t-hamming_weight)*cpowl(alpha_c, hamming_weight);\n //printf(\"%lf, %d, %d, %d, %d\\n\", beta, t,log_v, measured_qubits, hamming_weight);\n //printf(\"%lf + %lf I\\n\", creal(alpha_phase), cimag(alpha_phase));\n //printf(\"%lf + %lf I\\n\", creal(alpha_c_phase), cimag(alpha_c_phase));\n double complex prefactor = powl(2., ((beta + 1)*t + log_v - measured_qubits)/2.)*cpowl(alpha_phase, t-hamming_weight)*cpowl(alpha_c_phase, hamming_weight);\n //printf(\"%lf + %lf I\\n\", creal(prefactor), cimag(prefactor));\n for(int j = 0; j < equatorial_samples; j++){\n CHForm copy2 = copy_CHForm(©);\n double complex d = conj(equatorial_inner_product(©2, equatorial_matrices[j]))/(double)(magic_samples);\n inner_prods[j] += prefactor*d;\n dealocate_state(©2);\n }\n\n end = clock();\n norm_est_time += ((double)(end - start)) / (double)CLOCKS_PER_SEC;\n dealocate_state(©);\n }\n free(ys);\n //printf(\"sampling_time2: %lf\\nnorm_est_time2: %lf\\n\", sampling_time, norm_est_time);\n double complex acc = 0;\n for(int j = 0; j < equatorial_samples; j++){\n acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples;\n }\n free(inner_prods);\n\n for(int j = 0; j < equatorial_samples; j++){\n dealocate_equatorial_matrix(&equatorial_matrices[j]);\n }\n free(equatorial_matrices);\n StabTable_free(agState);\n dealocate_state(&chState);\n StabTable_free(state);\n //printf(\"c1(%lf, %lf)\\n\", creal(acc), cimag(acc));\n return PyComplex_FromDoubles(creal(acc), cimag(acc));\n}\n\n\n\nstatic PyObject * v_r_info(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n //controls->data[i*controls->strides[0]] = (unsigned int)targets->data[i*targets->strides[0]];\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n //printf(\"%d, %d, %u, %u\\n\", t, n, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n t += 1;\n }\n }\n\n //now we do the stabiliser evolution\n //to compute W\n\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((char)gates->data[i*gates->strides[0]]) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //StabTable_print(state);\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n //for(int i = 0; i < measured_qubits; i++){\n // if((unsigned char)a->data[i*a->strides[0]]){\n // StabTable_X(state, i);\n // }\n //}\n\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n return Py_BuildValue(\"ii\", log_v, t-state->k);\n\n //StabTable_free(state);\n\n //Py_RETURN_NONE;\n}\n\n\nstatic PyObject * lhs_rank_info(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n //controls->data[i*controls->strides[0]] = (unsigned int)targets->data[i*targets->strides[0]];\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n t += 1;\n }\n }\n\n //now we do the stabiliser evolution\n //to compute W\n\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((char)gates->data[i*gates->strides[0]]) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n //for(int i = 0; i < measured_qubits; i++){\n // if((unsigned char)a->data[i*a->strides[0]]){\n // StabTable_X(state, i);\n // }\n //}\n\n //printf(\"\\n\");StabTable_print(state);printf(\"\\n\");\n\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n //printf(\"\\n\");StabTable_print(state);printf(\"\\n\");\n int first_k = state->k;\n\n\n if(log_v < 0){\n return PyComplex_FromDoubles(0., 0.);\n }\n\n //StabTable * before_T_copy = StabTable_copy(state);\n //printf(\"state->k = %d\\n\", state->k);\n StabTable_apply_T_constraints(state, t);\n //printf(\"state->k = %d\\n\", state->k);\n //at this point the variable state contains the long G guys\n\n StabTable * longG = StabTable_copy(state);\n //now we evolve these back in time with V\n\n for(int i = gates->dimensions[0]-1; i >= 0 ; i--){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((char)gates->data[i*gates->strides[0]]) {\n case CX:\n StabTable_CX(longG, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(longG, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n StabTable_S(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n StabTable_S(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(longG, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //StabTable_print(longG);\n longG->n = longG->n - t;\n for(int i = 0; i < longG->k; i++){\n for(int j = 0; j < longG->n; j++){\n longG->table[i][j+longG->n] = longG->table[i][j+longG->n + t];\n }\n longG->table[i] = realloc(longG->table[i], 2*(longG->n)*sizeof(unsigned char));\n }\n //StabTable_print(longG);\n //now we have to do row echelon form on longG to work out the rank\n int h = 0;\n int k = longG->n;\n int rank = 0;\n while(h < longG->k && k < 2*longG->n){\n int poss_pivot = StabTable_first_non_zero_in_col(longG, k, h);\n if(poss_pivot < 0){\n k += 1;\n }else{\n int pivot = poss_pivot; //now known to be non-negative\n if(pivot != h){\n //swap rows h and pivot of the table\n StabTable_swap_rows(longG,h,pivot);\n }\n for(int j = 0; j < longG->k; j++){\n if((j != h) && (longG->table[j][k] != 0)){\n StabTable_rowsum(longG,j,h);\n }\n }\n h += 1;\n k += 1;\n rank += 1;\n\n }\n }\n\n //printf(\"idenits = %d\\n\", identity_qubits);\n //printf(\"Rank = %d\\n\", rank);\n //printf(\"lonG->k = %d\\n\", longG->k);\n //StabTable_print(longG);printf(\"\\n\");\n\n //StabTable_free(longG);\n return Py_BuildValue(\"iiii\", first_k, longG->n, longG->k, rank);\n\n}\n\nstatic PyObject * compute_algorithm(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n t += 1;\n }\n }\n\n //printf(\"\\n\");\n //now we do the stabiliser evolution\n //to compute W\n //printf(\"t = %d\\n\", t);\n //printf(\"w = %d\\n\", measured_qubits);\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n for(int i = 0; i < measured_qubits; i++){\n if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){\n //printf(\"flipping %d\\n\",i);\n StabTable_X(state, i);\n }\n }\n\n //printf(\"Entering constraints code\\n\");\n //StabTable_print(state);printf(\"\\n\");\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n //printf(\"constraints code returned log_v = %d\\n\",log_v);\n //StabTable_print(state);printf(\"\\n\");\n\n if(log_v < 0){\n return Py_BuildValue(\"d\", 0); //PyComplex_FromDoubles(0., 0.);\n }\n\n\n //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits\n // at this point we should just be left with t qubits\n int q_to_delete = state->n - t;\n int new_size = t;\n\n for(int s = 0; s < state->k; s++){\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-q_to_delete] = state->table[s][q];\n }\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n];\n }\n state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size);\n }\n state->n = new_size;\n\n //int d = state->k;\n //int r = state->n - state->k;\n\n StabTable_delete_all_identity_qubits(state, NULL);\n\n StabTable_apply_T_constraints(state,t);\n\n StabTable_delete_all_identity_qubits(state, NULL);\n\n //printf(\"final state:\\n\");\n //StabTable_print(state);\n //we explicitly compute the sum appearing in 10\n uint_bitarray_t full_mask = 0u;\n for(int i = 0; i < state->k; i++){\n full_mask |= (ONE << i);\n }\n double complex acc = 0.;\n //printf(\"final k = %d\\n\", state->k);\n //printBits(full_mask,5);printf(\"\\n\");\n for(uint_bitarray_t mask = 0u; mask <= full_mask; mask++){\n //printf(\"mask = \");printBits(mask,5);printf(\"\\n\");\n unsigned char * row = calloc(2*state->n, sizeof(unsigned char));\n unsigned char phase = 0;\n //we do the element of the sum corresponding to the bits of mask being 1\n for(int j = 0; j < state->k; j++){\n if((mask >> j) & ONE){\n //printf(\"%d, \", j);\n phase = StabTable_rowsum2(state, row, phase, j);\n }\n }\n //printf(\"\\n\");\n //so now (row, phase) indicate a particular length t string of pauli matrices\n //and we want to compute ^t\n int ICount = 0;\n int XCount = 0;\n int YCount = 0;\n int ZCount = 0;\n\n for(int j = 0; j < state->n; j++){\n if((row[j] == 0) && (row[j+state->n] == 0)){\n ICount += 1;\n }\n if((row[j] == 1) && (row[j+state->n] == 0)){\n XCount += 1;\n }\n if((row[j] == 0) && (row[j+state->n] == 1)){\n ZCount += 1;\n }\n if((row[j] == 1) && (row[j+state->n] == 1)){\n YCount += 1;\n }\n }\n\n double val = powl(1./2., (XCount + YCount)/2.);\n //printf(\"val=%lf\\n\", creal(val));\n //printf(\"I = %d, X = %d, Y = %d, Z = %d, total = %d\\n\", ICount, XCount, YCount, ZCount, ICount+ XCount+ YCount+ ZCount);\n if(ZCount == 0){\n if(((phase + YCount) % 2) == 0){\n acc += val;\n }else{\n acc -= val;\n }\n }\n free(row);\n }\n if(full_mask == 0u){\n acc = 1;\n }\n //printf(\"%lf\\n\",creal(acc));\n acc *= powl(2., log_v - measured_qubits);\n //printf(\"%lf\\n\",creal(acc));\n //end = clock();\n //double calc_time = ((double)(end - start)) / (double)CLOCKS_PER_SEC;\n StabTable_free(state);\n\n\n return Py_BuildValue(\"d\", acc);\n}\n\nstatic PyObject * StabTable_to_python_tuple(StabTable * table){\n\n const long int dimensions1[1] = {table->k};\n const long int dimensions2[2] = {table->k, 2*table->n};\n\n PyArrayObject * py_table = (PyArrayObject*)PyArray_SimpleNew(2, dimensions2, PyArray_UBYTE);\n PyArrayObject * py_phases = (PyArrayObject*)PyArray_SimpleNew(1, dimensions1, PyArray_UBYTE);\n for(int s = 0; s < table->k; s++){\n for(int q = 0; q < 2*table->n; q++){\n py_table->data[s*py_table->strides[0] + q*py_table->strides[1]] = (unsigned char)table->table[s][q];\n }\n py_phases->data[s*py_phases->strides[0]] = table->phases[s];\n }\n return Py_BuildValue(\"iiOO\", table->n, table->k, (PyObject*)py_table, (PyObject*)py_phases);\n}\n\nstatic StabTable * python_tuple_to_StabTable(PyObject * tuple){\n PyObject * py_n = PyTuple_GetItem(tuple, 0);\n PyObject * py_k = PyTuple_GetItem(tuple, 1);\n PyObject * py_table = PyTuple_GetItem(tuple, 2);\n PyObject * py_phases = PyTuple_GetItem(tuple, 3);\n\n int n = PyLong_AsLong(py_n);\n int k = PyLong_AsLong(py_k);\n\n StabTable * table = StabTable_new(n, k);\n for(int s = 0; s < table->k; s++){\n for(int q = 0; q < 2*table->n; q++){\n table->table[s][q] = *((unsigned char*)PyArray_GETPTR2(py_table, s, q));\n }\n table->phases[s]= *((unsigned char*)PyArray_GETPTR1(py_phases, s));\n }\n\n return table;\n}\n\n\nstatic PyObject * compress_algorithm(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n t += 1;\n }\n }\n //printf(\"\\n\");\n //now we do the stabiliser evolution\n //to compute W\n //printf(\"t = %d\\n\", t);\n //printf(\"w = %d\\n\", measured_qubits);\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n for(int i = 0; i < measured_qubits; i++){\n if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){\n //printf(\"flipping %d\\n\",i);\n StabTable_X(state, i);\n }\n }\n\n //printf(\"Entering constraints code\\n\");\n //StabTable_print(state);printf(\"\\n\");\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n //printf(\"constraints code returned log_v = %d\\n\",log_v);\n //StabTable_print(state);printf(\"\\n\");\n\n if(log_v < 0){\n return Py_BuildValue(\"d\", 0); //PyComplex_FromDoubles(0., 0.);\n }\n\n\n //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits\n // at this point we should just be left with t qubits\n int q_to_delete = state->n - t;\n int new_size = t;\n for(int s = 0; s < state->k; s++){\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-q_to_delete] = state->table[s][q];\n }\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n];\n }\n state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size);\n }\n state->n = new_size;\n\n int d = state->k;\n int r = state->n - state->k;\n\n int * magic_qubit_numbers = calloc(state->n, sizeof(int));\n for(int i = 0; i < state->n; i++){\n magic_qubit_numbers[i] = i;\n }\n\n int delta_t = StabTable_delete_all_identity_qubits(state, magic_qubit_numbers);\n\n int delta_d = StabTable_apply_T_constraints(state,t);\n\n int delta_t_prime = StabTable_delete_all_identity_qubits(state, magic_qubit_numbers);\n\n int final_d = state->k;\n int final_t = state->n;\n\n QCircuit * W = StabTable_simplifying_unitary(state);\n //printf(\"after computing W\\n\");\n\n state->circ = NULL;\n\n //now we have to work out what we need to do magic sampling with this W circuit\n //we need the CH-form for W|\\tilde{0}>\n //and the AG tableau for W|0> (no tilde!)\n\n CHForm chState;\n init_cb_CHForm(t,&chState);\n //Hadamard everything because we want to know the evolution of |\\tilde{0}> = |+>\n for(int i = 0; i < t; i++){\n HL(&chState, i);\n }\n //printf(\"before computing chState & agState\\n\");\n StabTable * agState = StabTable_new(t,t);\n\n for(int i = 0; i < W->length; i++){\n switch(W->tape[i].tag) {\n case CX:\n CXL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CX(agState, W->tape[i].control, W->tape[i].target);\n break;\n case CZ:\n CZL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CZ(agState, W->tape[i].control, W->tape[i].target);\n break;\n case S:\n SL(&chState, W->tape[i].target);\n StabTable_S(agState, W->tape[i].target);\n break;\n case H:\n HL(&chState, W->tape[i].target);\n StabTable_H(agState, W->tape[i].target);\n break;\n }\n }\n\n\n npy_intp dims[] = {state->n};\n PyObject * magic_arr = PyArray_SimpleNewFromData(1, dims, NPY_INT, (void*) magic_qubit_numbers);\n PyArray_ENABLEFLAGS((PyArrayObject *)magic_arr, NPY_ARRAY_OWNDATA); //tell the array it owns its data so the array gets free'd\n\n QCircuit_free(W);\n StabTable_free(state);\n PyObject * pyChState = CHForm_to_python_tuple(&chState);\n PyObject * pyAGState = StabTable_to_python_tuple(agState);\n dealocate_state(&chState);\n StabTable_free(agState);\n //printf(\"hi\\n\");\n //Py_DECREF(gates);\n //Py_DECREF(controls);\n //Py_DECREF(targets);\n //Py_DECREF(a);\n //printf(\"hi2\\n\");\n return Py_BuildValue(\"iiiiiiiiiOOO\", d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v, pyChState, pyAGState, magic_arr);\n}\n\nstatic PyObject * compress_algorithm_no_state_output(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n t += 1;\n }\n }\n //printf(\"\\n\");\n //now we do the stabiliser evolution\n //to compute W\n //printf(\"t = %d\\n\", t);\n //printf(\"w = %d\\n\", measured_qubits);\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n for(int i = 0; i < measured_qubits; i++){\n if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){\n //printf(\"flipping %d\\n\",i);\n StabTable_X(state, i);\n }\n }\n\n //printf(\"Entering constraints code\\n\");\n //StabTable_print(state);printf(\"\\n\");\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n //printf(\"constraints code returned log_v = %d\\n\",log_v);\n //StabTable_print(state);printf(\"\\n\");\n\n if(log_v < 0){\n return Py_BuildValue(\"d\", 0); //PyComplex_FromDoubles(0., 0.);\n }\n\n\n //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits\n // at this point we should just be left with t qubits\n int q_to_delete = state->n - t;\n int new_size = t;\n for(int s = 0; s < state->k; s++){\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-q_to_delete] = state->table[s][q];\n }\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n];\n }\n state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size);\n }\n state->n = new_size;\n\n int d = state->k;\n int r = state->n - state->k;\n\n //int * magic_qubit_numbers = calloc(state->n, sizeof(int));\n //for(int i = 0; i < state->n; i++){\n //magic_qubit_numbers[i] = i;\n //}\n\n int delta_t = StabTable_delete_all_identity_qubits(state, NULL);\n\n int delta_d = StabTable_apply_T_constraints(state,t);\n\n int delta_t_prime = StabTable_delete_all_identity_qubits(state, NULL);\n\n int final_d = state->k;\n int final_t = state->n;\n\n //QCircuit * W = StabTable_simplifying_unitary(state);\n //printf(\"after computing W\\n\");\n\n //state->circ = NULL;\n\n //now we have to work out what we need to do magic sampling with this W circuit\n //we need the CH-form for W|\\tilde{0}>\n //and the AG tableau for W|0> (no tilde!)\n\n //CHForm chState;\n //init_cb_CHForm(t,&chState);\n //Hadamard everything because we want to know the evolution of |\\tilde{0}> = |+>\n //for(int i = 0; i < t; i++){\n // HL(&chState, i);\n //}\n //printf(\"before computing chState & agState\\n\");\n /* StabTable * agState = StabTable_new(t,t); */\n\n /* for(int i = 0; i < W->length; i++){ */\n /* switch(W->tape[i].tag) { */\n /* case CX: */\n /* CXL(&chState, W->tape[i].control, W->tape[i].target); */\n /* StabTable_CX(agState, W->tape[i].control, W->tape[i].target); */\n /* break; */\n /* case CZ: */\n /* CZL(&chState, W->tape[i].control, W->tape[i].target); */\n /* StabTable_CZ(agState, W->tape[i].control, W->tape[i].target); */\n /* break; */\n /* case S: */\n /* SL(&chState, W->tape[i].target); */\n /* StabTable_S(agState, W->tape[i].target); */\n /* break; */\n /* case H: */\n /* HL(&chState, W->tape[i].target); */\n /* StabTable_H(agState, W->tape[i].target); */\n /* break; */\n /* } */\n /* } */\n\n\n /* npy_intp dims[] = {state->n}; */\n /* PyObject * magic_arr = PyArray_SimpleNewFromData(1, dims, NPY_INT, (void*) magic_qubit_numbers); */\n /* PyArray_ENABLEFLAGS((PyArrayObject *)magic_arr, NPY_ARRAY_OWNDATA); //tell the array it owns its data so the array gets free'd */\n\n //QCircuit_free(W);\n StabTable_free(state);\n //PyObject * pyChState = CHForm_to_python_tuple(&chState);\n //PyObject * pyAGState = StabTable_to_python_tuple(agState);\n //dealocate_state(&chState);\n //StabTable_free(agState);\n //printf(\"hi\\n\");\n //Py_DECREF(gates);\n //Py_DECREF(controls);\n //Py_DECREF(targets);\n //Py_DECREF(a);\n //printf(\"hi2\\n\");\n return Py_BuildValue(\"iiiiiiiii\", d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v);\n}\n\n\nstatic PyObject * compress_algorithm_no_region_c_constraints(PyObject* self, PyObject* args){\n PyArrayObject * gates;\n PyArrayObject * controls;\n PyArrayObject * targets;\n PyArrayObject * a; // project |a_i>dimensions[0]; i++){\n if(((char)gates->data[i*gates->strides[0]]) == T){\n gates->data[i*gates->strides[0]] = CX;\n unsigned int * ptr = (unsigned int *)PyArray_GETPTR1(controls, i);\n *ptr = *(unsigned int *)PyArray_GETPTR1(targets, i);\n ptr = (unsigned int *)PyArray_GETPTR1(targets, i);\n *ptr = (unsigned int)(n + t);\n t += 1;\n }\n }\n //printf(\"\\n\");\n //now we do the stabiliser evolution\n //to compute W\n //printf(\"t = %d\\n\", t);\n //printf(\"w = %d\\n\", measured_qubits);\n StabTable * state = StabTable_new(n+t, n+t);\n /* printf(\"0:\\n\"); */\n /* StabTable_print(state); */\n /* printf(\"\\n\"); */\n\n for(int i = 0; i < gates->dimensions[0]; i++){\n //printf(\"%d, %c, %d, %d\\n\", i, gates->data[i*gates->strides[0]],controls->data[i*controls->strides[0]], targets->data[i*targets->strides[0]]);\n switch((*(unsigned char *)PyArray_GETPTR1(gates,i))) {\n case CX:\n StabTable_CX(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case CZ:\n StabTable_CZ(state, (*(unsigned int *)PyArray_GETPTR1(controls,i)), (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case S:\n StabTable_S(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n case H:\n StabTable_H(state, (*(unsigned int *)PyArray_GETPTR1(targets,i)));\n break;\n }\n }\n\n //in the sequel we will assume that the CB measurement outcome we are interested in at the end is |0...0>\n //we \"fix\" this by applying a bunch of X gates to the measured qubits here\n for(int i = 0; i < measured_qubits; i++){\n if((*(unsigned char *)PyArray_GETPTR1(a,i)) == 1){\n //printf(\"flipping %d\\n\",i);\n StabTable_X(state, i);\n }\n }\n\n //printf(\"Entering constraints code\\n\");\n //StabTable_print(state);printf(\"\\n\");\n int log_v = StabTable_apply_constraints(state, measured_qubits, t);\n //printf(\"constraints code returned log_v = %d\\n\",log_v);\n //StabTable_print(state);printf(\"\\n\");\n\n if(log_v < 0){\n StabTable_free(state);\n return Py_BuildValue(\"d\", 0); //PyComplex_FromDoubles(0., 0.);\n }\n\n\n //now delete the first (n) = table->n - t (since table->n = n + t at this point) qubits\n // at this point we should just be left with t qubits\n int q_to_delete = state->n - t;\n int new_size = t;\n for(int s = 0; s < state->k; s++){\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-q_to_delete] = state->table[s][q];\n }\n for(int q = q_to_delete; q < state->n; q++){\n state->table[s][q-2*q_to_delete+state->n] = state->table[s][q+state->n];\n }\n state->table[s] = realloc(state->table[s], sizeof(unsigned char) * 2 * new_size);\n }\n state->n = new_size;\n\n int d = state->k;\n int r = state->n - state->k;\n\n //int * magic_qubit_numbers = calloc(state->n, sizeof(int));\n //for(int i = 0; i < state->n; i++){\n //magic_qubit_numbers[i] = i;\n //}\n\n int delta_t = -1;\n\n int delta_d = -1;\n\n int delta_t_prime = -1;\n\n int final_d = state->k;\n int final_t = state->n;\n\n QCircuit * W = StabTable_simplifying_unitary(state);\n\n state->circ = NULL;\n\n //now we have to work out what we need to do magic sampling with this W circuit\n //we need the CH-form for W|\\tilde{0}>\n //and the AG tableau for W|0> (no tilde!)\n\n CHForm chState;\n init_cb_CHForm(t,&chState);\n //Hadamard everything because we want to know the evolution of |\\tilde{0}> = |+>\n for(int i = 0; i < t; i++){\n HL(&chState, i);\n }\n //printf(\"before computing chState & agState\\n\");\n StabTable * agState = StabTable_new(t,t);\n\n for(int i = 0; i < W->length; i++){\n switch(W->tape[i].tag) {\n case CX:\n CXL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CX(agState, W->tape[i].control, W->tape[i].target);\n break;\n case CZ:\n CZL(&chState, W->tape[i].control, W->tape[i].target);\n StabTable_CZ(agState, W->tape[i].control, W->tape[i].target);\n break;\n case S:\n SL(&chState, W->tape[i].target);\n StabTable_S(agState, W->tape[i].target);\n break;\n case H:\n HL(&chState, W->tape[i].target);\n StabTable_H(agState, W->tape[i].target);\n break;\n }\n }\n\n\n\n //npy_intp dims[] = {state->n};\n //PyObject * magic_arr = PyArray_SimpleNewFromData(1, dims, NPY_INT, (void*) magic_qubit_numbers);\n //PyArray_ENABLEFLAGS((PyArrayObject *)magic_arr, NPY_ARRAY_OWNDATA); //tell the array it owns its data so the array gets free'd\n\n QCircuit_free(W);\n StabTable_free(state);\n PyObject * pyChState = CHForm_to_python_tuple(&chState);\n PyObject * pyAGState = StabTable_to_python_tuple(agState);\n\n dealocate_state(&chState);\n StabTable_free(agState);\n\n //d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v\n return Py_BuildValue(\"iiiiiiiiiOO\", d, r, t, delta_d, delta_t, delta_t_prime, final_d, final_t, log_v, pyChState, pyAGState);\n}\n\n\nstatic PyObject * estimate_algorithm(PyObject* self, PyObject* args){\n int magic_samples, equatorial_samples, r, log_v, measured_qubits, seed;\n PyObject * CHTuple;\n PyObject * AGTuple;\n\n if (!PyArg_ParseTuple(args, \"iiiiiiO!O!\", &magic_samples, &equatorial_samples, &measured_qubits, &log_v, &r, &seed,\n &PyTuple_Type, &CHTuple,\n &PyTuple_Type, &AGTuple\n )){\n return NULL;\n }\n srand(seed);\n\n CHForm * chState = python_tuple_to_CHForm(CHTuple);\n StabTable * agState = python_tuple_to_StabTable(AGTuple);\n\n\n //at this point we want to generate a list of length equatorial_samples\n //containing r - qubit equatorial states\n //ie. r x r binary symmetric matrices\n equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t));\n for(int i = 0; i < equatorial_samples; i++){\n init_random_equatorial_matrix(&(equatorial_matrices[i]), r);\n }\n //printf(\"a\\n\");\n uint_bitarray_t magic_mask = 0;\n\n for(int i = 0; i < agState->n; i++){\n magic_mask |= (ONE<n-r; i++){\n bitMask |= (ONE << i);\n }\n\n //printf(\"e\\n\");\n double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex));\n double complex alpha = (1. - I*(sqrt(2.) - 1.))/2.;\n double beta = log2(4. - 2.*sqrt(2.));\n double complex alpha_phase = alpha / cabs(alpha);\n double complex alpha_c_phase = conj(alpha_phase);\n\n\n for(int i = 0; i < magic_samples; i++){\n //printf(\"%d\\n\", i);\n //generate our state\n CHForm copy = copy_CHForm(chState);\n\n for(int bit = 0; bit < chState->n; bit++){\n if((ys[i] >> bit) & ONE){\n //apply W S^3_bit W^\\dagger to chState\n uint_bitarray_t * z_mat = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * x_mat = calloc(chState->n, sizeof(uint_bitarray_t));\n\n uint_bitarray_t mask = (uint_bitarray_t)0;\n uint_bitarray_t t_mask = (uint_bitarray_t)0;\n\n unsigned int g = 2*agState->phases[bit] ;\n for(int j = 0; j < chState->n; j++){\n if(agState->table[bit][j]){\n x_mat[j] = copy.F[j];\n z_mat[j] = copy.M[j];\n mask |= (ONE << j);\n }\n if(agState->table[bit][j+agState->n]){\n z_mat[j] ^= copy.G[j];\n }\n t_mask |= (ONE << j);\n //if x and z are both 1 we get a factor of i because iXZ == Y\n if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){\n g += 1;\n }\n\n }\n g += popcount(copy.g1 & mask) + 2*popcount(copy.g2 & mask);\n g += 2*sort_pauli_string(chState->n, x_mat, z_mat, mask);\n\n uint_bitarray_t u = 0u; // u_m is exponent of X_m\n uint_bitarray_t h = 0u; // h_m is exponent of Z_m\n\n for(int k = 0; k < chState->n; k++){\n if(agState->table[bit][k]){\n u ^= (copy.F[k] & t_mask);\n h ^= (copy.M[k] & t_mask);\n }\n if(agState->table[bit][k+agState->n]){\n h ^= (copy.G[k] & t_mask);\n }\n }\n //at this point the state we want is w U_c [I + i^g \\prod_m Z_m^{h_m}X_m^{u_m}] U_H |s>\n //we need to commute the product through U_H\n //and then desuperpositionise\n //we pull the same trick again\n // (\\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\\dagger (\\prod_m Z_m^{h_m}X_m^{u_m}) U_H)\n //n.b. Hadamard is self-adjoint\n //what happens - if V_k is zero then nothing happens\n //if V_k is 1 then we swap X and Z\n //if V_k is 1 and X and Z are both 1 we get a minus sign\n\n uint_bitarray_t u2 = (u & (~copy.v)) ^ (h & (copy.v));\n uint_bitarray_t h2 = (h & (~copy.v)) ^ (u & (copy.v));\n g += 2*parity(u & h & copy.v & t_mask);\n\n\n //at this point the state we want is w U_c [I + i^g U_H \\prod_m Z_m^{h2_m} X_m^{u2_m}] |s>\n //we apply the paulis to |s>\n //every x flips a bit of s\n //every time a z hits a |1> we get a -1\n //xs happen first\n\n uint_bitarray_t y = (copy.s ^ u2) & t_mask;\n g += 2*parity(y & h2 & t_mask);\n g += 1; //an i appears in the expression for S^3 in terms of Z and I\n g %= 4;\n\n //at this point the state we want is w e^{-i\\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3\n if((y & t_mask) == (copy.s & t_mask)){\n double complex a = 1.;\n\n if(g == 0){\n a += 1.;\n }\n if(g == 1){\n a += (1.)*I;\n }\n if(g == 2){\n a += (-1.);\n }\n if(g == 3){\n a += (-1.*I);\n }\n\n copy.w *= (a*(1 - 1.*I)/2.);\n }else{\n desupersitionise(©, y, g);\n copy.w *= (1.-1.*I)/2.;\n }\n\n free(x_mat);\n free(z_mat);\n }\n }\n\n //at this point copy contains our magic sample\n //we want to project it and do fastnorm estimation\n\n //now we project onto the measurement outcomes for the w qubits\n postselect_and_reduce(©, bitA, bitMask);\n int hamming_weight = popcount(ys[i]);\n double complex prefactor = powl(2., ((beta + 1)*chState->n + log_v - measured_qubits)/2.)*cpowl(alpha_phase, chState->n-hamming_weight)*cpowl(alpha_c_phase, hamming_weight);\n for(int j = 0; j < equatorial_samples; j++){\n //CHForm copy2 = copy_CHForm(©);\n double complex d = conj(equatorial_inner_product(©, equatorial_matrices[j]))/(double)(magic_samples);\n\n inner_prods[j] += prefactor*d;\n }\n dealocate_state(©);\n }\n free(ys);\n\n double acc = 0;\n for(int j = 0; j < equatorial_samples; j++){\n acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples;\n }\n free(inner_prods);\n\n for(int j = 0; j < equatorial_samples; j++){\n dealocate_equatorial_matrix(&equatorial_matrices[j]);\n }\n\n free(equatorial_matrices);\n StabTable_free(agState);\n dealocate_state(chState);\n free(chState);\n return PyComplex_FromDoubles(creal(acc), cimag(acc));\n}\n\nstatic PyObject * estimate_algorithm_r_equals_0(PyObject* self, PyObject* args){\n int magic_samples, log_v, seed;\n PyObject * CHTuple;\n PyObject * AGTuple;\n\n if (!PyArg_ParseTuple(args, \"iiiO!O!\", &magic_samples, &log_v, &seed,\n &PyTuple_Type, &CHTuple,\n &PyTuple_Type, &AGTuple\n )){\n return NULL;\n }\n srand(seed);\n\n CHForm * chState = python_tuple_to_CHForm(CHTuple);\n StabTable * agState = python_tuple_to_StabTable(AGTuple);\n\n uint_bitarray_t magic_mask = 0;\n\n for(int i = 0; i < agState->n; i++){\n magic_mask |= (ONE<n; bit++){\n if((ys[i] >> bit) & ONE){\n //apply W S^3_bit W^\\dagger to chState\n uint_bitarray_t * z_mat = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * x_mat = calloc(chState->n, sizeof(uint_bitarray_t));\n\n uint_bitarray_t mask = (uint_bitarray_t)0;\n uint_bitarray_t t_mask = (uint_bitarray_t)0;\n\n unsigned int g = 2*agState->phases[bit] ;\n for(int j = 0; j < chState->n; j++){\n if(agState->table[bit][j]){\n x_mat[j] = copy.F[j];\n z_mat[j] = copy.M[j];\n mask |= (ONE << j);\n }\n if(agState->table[bit][j+agState->n]){\n z_mat[j] ^= copy.G[j];\n }\n t_mask |= (ONE << j);\n //if x and z are both 1 we get a factor of i because iXZ == Y\n if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){\n g += 1;\n }\n\n }\n g += popcount(copy.g1 & mask) + 2*popcount(copy.g2 & mask);\n g += 2*sort_pauli_string(chState->n, x_mat, z_mat, mask);\n\n uint_bitarray_t u = 0u; // u_m is exponent of X_m\n uint_bitarray_t h = 0u; // h_m is exponent of Z_m\n\n for(int k = 0; k < chState->n; k++){\n if(agState->table[bit][k]){\n u ^= (copy.F[k] & t_mask);\n h ^= (copy.M[k] & t_mask);\n }\n if(agState->table[bit][k+agState->n]){\n h ^= (copy.G[k] & t_mask);\n }\n }\n //at this point the state we want is w U_c [I + i^g \\prod_m Z_m^{h_m}X_m^{u_m}] U_H |s>\n //we need to commute the product through U_H\n //and then desuperpositionise\n //we pull the same trick again\n // (\\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\\dagger (\\prod_m Z_m^{h_m}X_m^{u_m}) U_H)\n //n.b. Hadamard is self-adjoint\n //what happens - if V_k is zero then nothing happens\n //if V_k is 1 then we swap X and Z\n //if V_k is 1 and X and Z are both 1 we get a minus sign\n\n uint_bitarray_t u2 = (u & (~copy.v)) ^ (h & (copy.v));\n uint_bitarray_t h2 = (h & (~copy.v)) ^ (u & (copy.v));\n g += 2*parity(u & h & copy.v & t_mask);\n\n\n //at this point the state we want is w U_c [I + i^g U_H \\prod_m Z_m^{h2_m} X_m^{u2_m}] |s>\n //we apply the paulis to |s>\n //every x flips a bit of s\n //every time a z hits a |1> we get a -1\n //xs happen first\n\n uint_bitarray_t y = (copy.s ^ u2) & t_mask;\n g += 2*parity(y & h2 & t_mask);\n g += 1; //an i appears in the expression for S^3 in terms of Z and I\n g %= 4;\n\n //at this point the state we want is w e^{-i\\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3\n if((y & t_mask) == (copy.s & t_mask)){\n double complex a = 1.;\n\n if(g == 0){\n a += 1.;\n }\n if(g == 1){\n a += (1.)*I;\n }\n if(g == 2){\n a += (-1.);\n }\n if(g == 3){\n a += (-1.*I);\n }\n\n copy.w *= (a*(1 - 1.*I)/2.);\n }else{\n desupersitionise(©, y, g);\n copy.w *= (1.-1.*I)/2.;\n }\n\n free(x_mat);\n free(z_mat);\n }\n }\n\n //at this point copy contains our magic sample\n //we want to project it - no fast norm needed as r = 0\n int hamming_weight = popcount(ys[i]);\n double complex prefactor = powl(2., ((beta)*chState->n + log_v)/2.)*cpowl(alpha_phase, chState->n-hamming_weight)*cpowl(alpha_c_phase, hamming_weight);\n double complex overlap = measurement_overlap(©, (uint_bitarray_t)0);\n\n acc += prefactor*overlap/magic_samples;\n\n\n dealocate_state(©);\n }\n\n double complex prob = creal(acc*conj(acc));\n free(ys);\n\n StabTable_free(agState);\n dealocate_state(chState);\n free(chState);\n return PyComplex_FromDoubles(creal(prob), cimag(prob));\n}\n\n//if inverse == 1 apply H S^3 H, otherwise apply H S H\nstatic void applyHSH_to_CHForm(CHForm * chState, StabTable * agState, int bit, unsigned char inverse, uint_bitarray_t * x_mat, uint_bitarray_t * z_mat){\n uint_bitarray_t mask = (uint_bitarray_t)0;\n uint_bitarray_t t_mask = (uint_bitarray_t)0;\n\n unsigned int g = 2*agState->phases[bit];\n for(int j = 0; j < chState->n; j++){\n if(agState->table[bit][j]){\n x_mat[j] = chState->F[j];\n z_mat[j] = chState->M[j];\n mask |= (ONE << j);\n }\n if(agState->table[bit][j+agState->n]){\n z_mat[j] ^= chState->G[j];\n }\n t_mask |= (ONE << j);\n //if x and z are both 1 we get a factor of i because iXZ == Y\n if((agState->table[bit][j] == 1) && (agState->table[bit][j+agState->n] == 1)){\n g += 1;\n }\n\n }\n g += popcount(chState->g1 & mask) + 2*popcount(chState->g2 & mask);\n g += 2*sort_pauli_string(chState->n, x_mat, z_mat, mask);\n\n uint_bitarray_t u = 0u; // u_m is exponent of X_m\n uint_bitarray_t h = 0u; // h_m is exponent of Z_m\n\n for(int k = 0; k < chState->n; k++){\n if(agState->table[bit][k]){\n u ^= (chState->F[k] & t_mask);\n h ^= (chState->M[k] & t_mask);\n }\n if(agState->table[bit][k+agState->n]){\n h ^= (chState->G[k] & t_mask);\n }\n }\n //at this point the state we want is w U_c [I + i^g \\prod_m Z_m^{h_m}X_m^{u_m}] U_H |s>\n //we need to commute the product through U_H\n //and then desuperpositionise\n //we pull the same trick again\n // (\\prod_m X_m^{u_m}Z_m^{h_m} ) U_H = U_H (U_H^\\dagger (\\prod_m Z_m^{h_m}X_m^{u_m}) U_H)\n //n.b. Hadamard is self-adjoint\n //what happens - if V_k is zero then nothing happens\n //if V_k is 1 then we swap X and Z\n //if V_k is 1 and X and Z are both 1 we get a minus sign\n\n uint_bitarray_t u2 = (u & (~chState->v)) ^ (h & (chState->v));\n uint_bitarray_t h2 = (h & (~chState->v)) ^ (u & (chState->v));\n g += 2*parity(u & h & chState->v & t_mask);\n\n\n //at this point the state we want is w U_c [I + i^g U_H \\prod_m Z_m^{h2_m} X_m^{u2_m}] |s>\n //we apply the paulis to |s>\n //every x flips a bit of s\n //every time a z hits a |1> we get a -1\n //xs happen first\n\n uint_bitarray_t y = (chState->s ^ u2) & t_mask;\n g += 2*parity(y & h2 & t_mask);\n g += (3 + 2*inverse); //an i appears in the expression for S^3 in terms of Z and I, and a -i appears in the expression for S\n g %= 4;\n\n //at this point the state we want is w e^{\\pm i\\pi/4}/sqrt{2} U_c U_h( |s> + i^(g) |y>) //extra factors from the formula for S^3\n //if we're doing S^3 it should be e^{-i\\pi/4} and if we're doing S it should be e^{i\\pi/4}\n if((y & t_mask) == (chState->s & t_mask)){\n double complex a = 1.;\n\n if(g == 0){\n a += 1.;\n }\n if(g == 1){\n a += (1.)*I;\n }\n if(g == 2){\n a += (-1.);\n }\n if(g == 3){\n a += (-1.*I);\n }\n\n chState->w *= a; //(a*(1 - 1.*I)/2.);\n }else{\n desupersitionise(chState, y, g);\n }\n chState->w *= (1.+1.*I)/2.;\n if(inverse == 1){\n chState->w *= (-1.)*I;\n }\n\n memset(x_mat, 0, sizeof(uint_bitarray_t)*chState->n);\n memset(z_mat, 0, sizeof(uint_bitarray_t)*chState->n);\n}\n\nstatic PyObject * estimate_algorithm_with_arbitrary_phases(PyObject* self, PyObject* args){\n int magic_samples, equatorial_samples, r, log_v, measured_qubits, seed;\n PyObject * CHTuple;\n PyObject * AGTuple;\n PyArrayObject * phases;\n if (!PyArg_ParseTuple(args, \"iiiiiiO!O!O!\", &magic_samples, &equatorial_samples, &measured_qubits, &log_v, &r, &seed,\n &PyTuple_Type, &CHTuple,\n &PyTuple_Type, &AGTuple,\n &PyArray_Type, &phases\n )){\n return NULL;\n }\n srand(seed);\n\n gsl_rng * RNG = gsl_rng_alloc(gsl_rng_mt19937);\n gsl_rng_set(RNG, seed);\n\n CHForm * chState = python_tuple_to_CHForm(CHTuple);\n StabTable * agState = python_tuple_to_StabTable(AGTuple);\n\n double complex * alpha_phases = calloc(chState->n, sizeof(double complex)); //now we allow arbitrary phase gates different gates need different alphas\n double complex * alpha_prime_phases = calloc(chState->n, sizeof(double complex));\n double stab_extent_sqrt = 1.;\n //printf(\"chState->n = %d\\n\", chState->n);\n double * probs = calloc(chState->n, sizeof(double));\n for(int i = 0; i < chState->n; i++){\n double phase;\n phase = *(double *)PyArray_GETPTR1(phases, i);\n //printf(\"phase[%d] = %lf\\n\", i, phase);\n alpha_phases[i] = (I + cexpl(-1.*I*phase))/((1. + I)*sqrt(1. - sinl(phase)));\n alpha_prime_phases[i] = (1. - cexpl(-1.*I*phase))/((1. + I)*sqrt(1. - cosl(phase)));\n stab_extent_sqrt *= (sqrt(1. - sinl(phase)) + sqrt(1. - cosl(phase)));\n probs[i] = sqrt(1.-sin(phase))/(sqrt(1.-sin(phase)) + sqrt(1.-cos(phase)));\n //printf(\"%d: (%lf, %lf), (%lf, %lf)\\n\", i, creal(alpha_phases[i]), cimag(alpha_phases[i]), creal(alpha_prime_phases[i]), cimag(alpha_prime_phases[i]));\n\n }\n //printf(\"stab_extent_sqrt = %lf\\n\", stab_extent_sqrt);\n\n //at this point we want to generate a list of length equatorial_samples\n //containing r - qubit equatorial states\n //ie. r x r binary symmetric matrices\n equatorial_matrix_t * equatorial_matrices = calloc(equatorial_samples, sizeof(equatorial_matrix_t));\n for(int i = 0; i < equatorial_samples; i++){\n init_random_equatorial_matrix(&(equatorial_matrices[i]), r);\n }\n //printf(\"a\\n\");\n uint_bitarray_t magic_mask = 0;\n\n for(int i = 0; i < agState->n; i++){\n magic_mask |= (ONE<n; bit++){\n if(!gsl_ran_bernoulli(RNG, probs[bit])){\n ys[i] |= (ONE << bit);\n }\n }\n }\n //printf(\"c\\n\");\n uint_bitarray_t equatorial_mask = 0;\n for(int i = 0; i < r; i++){\n equatorial_mask |= (ONE << i);\n }\n //printf(\"d\\n\");\n //we project onto 0 and throw away the first t-r qubits\n //leaving us with an r qubit state\n uint_bitarray_t bitA = 0;\n uint_bitarray_t bitMask = 0;\n for(int i = 0; i < ((int)chState->n)-((int)r); i++){\n bitMask |= (ONE << i);\n }\n\n double complex * inner_prods = calloc(equatorial_samples, sizeof(double complex));\n\n //we will use this memory when doing the magic sampling\n uint_bitarray_t * z_mat = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * x_mat = calloc(chState->n, sizeof(uint_bitarray_t));\n\n\n //we will use this memory when doing fastnorm\n uint_bitarray_t * AJ = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * GT = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * bitK = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * X = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * Y = calloc(chState->n, sizeof(uint_bitarray_t));\n uint_bitarray_t * M = calloc(chState->n+1, sizeof(uint_bitarray_t));\n\n CHForm allOnesState = copy_CHForm(chState);\n for(int bit = 0; bit < chState->n; bit++){\n applyHSH_to_CHForm(&allOnesState, agState, bit, (unsigned char)1, x_mat, z_mat);\n }\n\n for(int i = 0; i < magic_samples; i++){\n double complex prefactor = stab_extent_sqrt * cpowl(2., (((int)chState->n) /*- ((int)r)*/ + ((int)log_v) - ((int)measured_qubits))/2.);\n /* printf(\"stab_extent_sqrt = %lf\\n\", stab_extent_sqrt); */\n /* printf(\"%d\\n\", chState->n); */\n /* printf(\"%d\\n\", r); */\n /* printf(\"%d\\n\", log_v); */\n /* printf(\"%d\\n\", measured_qubits); */\n /* printf(\"%lf\\n\", (((int)chState->n) - ((int)r) + ((int)log_v) - ((int)measured_qubits))/2.); */\n //printf(\"prefactor = %lf + %lf*I\\n\", creal(prefactor), cimag(prefactor));\n\n //printf(\"%d\\n\", i);\n //generate our state\n\n CHForm * state_to_copy = NULL;\n int hamming_weight = popcount(ys[i]);\n unsigned char inverse = 1;\n if(2*hamming_weight > chState->n){ //if the Hamming weight is big we're better starting with the all ones state\n state_to_copy = &allOnesState;\n inverse = 0; //apply H S H to flip bits from 1 to 0\n }else{ //if the Hamming weight is small we're better starting with the all zeros state\n state_to_copy = chState;\n inverse = 1; // apply H S^3 H to flip bits from 0 to 1\n }\n\n CHForm copy = copy_CHForm(state_to_copy);\n\n for(int bit = 0; bit < chState->n; bit++){\n if((ys[i] >> bit) & ONE){\n prefactor *= alpha_prime_phases[bit];\n }else{\n prefactor *= alpha_phases[bit];\n }\n\n if(((ys[i] >> bit) & ONE) == inverse){\n //apply W S^3_bit W^\\dagger to chState\n applyHSH_to_CHForm(©, agState, bit, inverse, x_mat, z_mat);\n }\n }\n //printf(\"prefactor = %lf + %lf *I\\n\", creal(prefactor), cimag(prefactor));\n\n //at this point copy contains our magic sample\n //we want to project it and do fastnorm estimation\n\n //now we project onto the measurement outcomes for the w qubits\n postselect_and_reduce(©, bitA, bitMask);\n //int hamming_weight = popcount(ys[i]);\n //double complex prefactor = powl(2., ((beta + 1)*chState->n + log_v - measured_qubits)/2.)*cpowl(alpha_phase, chState->n-hamming_weight)*cpowl(alpha_c_phase, hamming_weight);\n for(size_t i = 0; i < copy.n; i++){\n for(size_t j = 0; j < copy.n; j++){\n GT[j] |= ((copy.G[i] >> j) & ONE) << i;\n }\n }\n\n for(int j = 0; j < equatorial_samples; j++){\n //CHForm copy2 = copy_CHForm(©);\n double complex d = conj(equatorial_inner_product_no_alloc(©, equatorial_matrices[j], AJ, GT, X,Y, bitK,M))/(double)(magic_samples);\n //printf(\"(%lf, %lf), (%lf, %lf)\\n\", creal(prefactor), cimag(prefactor), creal(d), cimag(d));\n inner_prods[j] += prefactor*d;\n }\n memset(GT, 0, sizeof(uint_bitarray_t)*agState->n);\n dealocate_state(©);\n }\n free(x_mat);\n free(z_mat);\n free(AJ);\n free(GT);\n free(X);\n free(Y);\n free(bitK);\n free(M);\n free(probs);\n free(ys);\n free(alpha_phases);\n free(alpha_prime_phases);\n double acc = 0;\n for(int j = 0; j < equatorial_samples; j++){\n acc += creal(inner_prods[j]*conj(inner_prods[j]))/(double)equatorial_samples;\n }\n free(inner_prods);\n\n for(int j = 0; j < equatorial_samples; j++){\n dealocate_equatorial_matrix(&equatorial_matrices[j]);\n }\n gsl_rng_free(RNG);\n\n free(equatorial_matrices);\n StabTable_free(agState);\n dealocate_state(chState);\n free(chState);\n //dealocate_state(&allOnesState);\n return PyComplex_FromDoubles(creal(acc), cimag(acc));\n}\n\n\nstatic PyMethodDef myMethods[] = {\n { \"apply_gates_to_basis_state_project_and_reduce\", apply_gates_to_basis_state_project_and_reduce, METH_VARARGS, \"Applies a bunch of gates to an initial computational-basis state, then applies a bunch of z projectors and removes the (now product state) qubits we projected\"},\n { \"magic_sample_1\", magic_sample_1, METH_VARARGS, \"do the sampling algorithm with magic sampling first\"},\n { \"magic_sample_2\", magic_sample_2, METH_VARARGS, \"do the sampling algorithm with fastnorm first\"},\n { \"main_simulation_algorithm\", main_simulation_algorithm, METH_VARARGS, \"compute a computational basis measurement outcome overlap\"},\n { \"main_simulation_algorithm2\", main_simulation_algorithm2, METH_VARARGS, \"compute a computational basis measurement outcome overlap dumb sampling method\"},\n { \"v_r_info\", v_r_info, METH_VARARGS, \"stuff\"},\n { \"lhs_rank_info\", lhs_rank_info, METH_VARARGS, \"stuff\"},\n { \"compute_algorithm\", compute_algorithm, METH_VARARGS, \"stuff\"},\n { \"compress_algorithm\", compress_algorithm, METH_VARARGS, \"Run the compress algorithm precomputation\"},\n { \"compress_algorithm_no_region_c_constraints\", compress_algorithm_no_region_c_constraints, METH_VARARGS, \"Run the compress algorithm precomputation without region c constraints\"},\n { \"compress_algorithm_no_state_output\", compress_algorithm_no_state_output, METH_VARARGS, \"Run the compress algorithm precomputation without computing AG state and CH state\"},\n { \"estimate_algorithm\", estimate_algorithm, METH_VARARGS, \"Run the estimate algorithm\"},\n { \"estimate_algorithm_r_equals_0\", estimate_algorithm_r_equals_0, METH_VARARGS, \"Run the estimate algorithm when r = 0\"},\n { \"estimate_algorithm_with_arbitrary_phases\", estimate_algorithm_with_arbitrary_phases, METH_VARARGS, \"Run the estimate algorithm\"},\n { NULL, NULL, 0, NULL }\n};\n\n\n\n// Our Module Definition struct\nstatic struct PyModuleDef clifford_t_estim = {\n PyModuleDef_HEAD_INIT,\n \"clifford_t_estim\",\n \"Interface with c Cliffor+T estimation code\",\n -1,\n myMethods\n};\n\n// Initializes our module using our above struct\nPyMODINIT_FUNC PyInit_clifford_t_estim(void)\n{\n import_array();\n //double x = 5.0;\n //double y = gsl_sf_bessel_J0 (x);\n //printf (\"J0(%g) = %.18e\\n\", x, y);\n //printf(\"Hello!\\n\");\n return PyModule_Create(&clifford_t_estim);\n}\n", "meta": {"hexsha": "42c813ed310056b3b6174413151962796f01ab26", "size": 142438, "ext": "c", "lang": "C", "max_stars_repo_path": "cmodule.c", "max_stars_repo_name": "or1426/Cliford-T-estimator", "max_stars_repo_head_hexsha": "c460c143f25fc637aa18c2907e01afeea46112e0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-01T13:17:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-15T04:01:29.000Z", "max_issues_repo_path": "cmodule.c", "max_issues_repo_name": "or1426/Cliford-T-estimator", "max_issues_repo_head_hexsha": "c460c143f25fc637aa18c2907e01afeea46112e0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-02-02T11:18:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-02-02T11:18:49.000Z", "max_forks_repo_path": "cmodule.c", "max_forks_repo_name": "or1426/Cliford-T-estimator", "max_forks_repo_head_hexsha": "c460c143f25fc637aa18c2907e01afeea46112e0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-02T11:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-02T11:13:11.000Z", "avg_line_length": 36.4384753134, "max_line_length": 278, "alphanum_fraction": 0.5203667561, "num_tokens": 41486, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358548398979, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.29783261559320257}} {"text": "/* -*- linux-c -*- */\n/* fewbody_utils.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 \"fewbody.h\"\n\n/* allocate a vector */\ndouble *fb_malloc_vector(int n)\n{\n\treturn((double *) malloc(n * sizeof(double)));\n}\n\n/* allocate a matrix */\ndouble **fb_malloc_matrix(int nr, int nc)\n{\n\tint i;\n\tdouble **m;\n\n\tm = (double **) malloc(nr * sizeof(double *));\n\n\tm[0] = (double *) malloc(nr * nc * sizeof(double));\n\n\tfor (i=1; ix[k] - obj[i]->x[k];\n\t\t\t}\n\t\t\tpe += -obj[i]->m * obj[j]->m / fb_mod(r);\n\t\t}\n\t}\n\t\n\treturn(pe);\n}\n\n/* calculates the kinetic energy of the bound members of the system */\ndouble fb_outerketot(fb_obj_t **obj, int nobj)\n{\n\tint i;\n\tdouble ke=0.0;\n\n\tfor (i=0; im * fb_dot(obj[i]->v, obj[i]->v);\n\t}\n \n\treturn(ke);\n}\n\n/* solve the Kepler equation for the eccentric anomaly, given the mean anomaly and eccentricity */\ndouble fb_kepler(double e, double mean_anom)\n{\n\tint status, iter;\n\tdouble ecc_anom, params[2];\n\tgsl_function F;\n\tconst gsl_root_fsolver_type *T;\n\tgsl_root_fsolver *s;\n\t\n\t/* set up the root solver */\n\tF.function = &fb_keplerfunc;\n\tF.params = ¶ms;\n\n\t/* set the parameters */\n\tparams[0] = e;\n\tparams[1] = mean_anom;\n\n\tT = gsl_root_fsolver_brent;\n\ts = gsl_root_fsolver_alloc(T);\n\tgsl_root_fsolver_set(s, &F, 0.0, 2.0*FB_CONST_PI);\n\t\n\t/* get eccentric anomaly by root-finding */\n\titer = 0;\n\tdo {\n\t\titer++;\n\t\tgsl_root_fsolver_iterate(s);\n\t\tstatus = gsl_root_test_interval(gsl_root_fsolver_x_lower(s), gsl_root_fsolver_x_upper(s), \\\n\t\t\t\t\t\tFB_ROOTSOLVER_ABS_ACC, FB_ROOTSOLVER_REL_ACC);\n\t} while (status == GSL_CONTINUE && iter < FB_ROOTSOLVER_MAX_ITER);\n\n\tif (iter >= FB_ROOTSOLVER_MAX_ITER) {\n\t\tfprintf(stderr, \"Root finder failed to converge.\\n\");\n\t\texit(1);\n\t}\n\n\t/* we've got the root */\n\tecc_anom = gsl_root_fsolver_root(s);\n\t\n\t/* free memory associated with root solver */\n\tgsl_root_fsolver_free(s);\n\n\treturn(ecc_anom);\n}\n\n/* the Kepler function for the root finder */\ndouble fb_keplerfunc(double ecc_anom, void *params)\n{\n\tdouble e, mean_anom;\n\t\n\te = ((double *)params)[0];\n\tmean_anom = ((double *)params)[1];\n\t\n\treturn(ecc_anom - e * sin(ecc_anom) - mean_anom);\n}\n\n/* calculate the relative tidal acceleration */\ndouble fb_reltide(fb_obj_t *bin, fb_obj_t *single, double r)\n{\n\tdouble arel, atid;\n\n\tarel = bin->m / fb_sqr(bin->a * (1.0 + bin->e));\n\t/* Factor in numerator is (single->m + bin->m) instead of single->m for the case of \n\t small single->m, for which we want to at some point resolve \"bin\" to get the \n\t motion of \"single\". This will eventually be fixed when we we use full collapsed \n\t binary member positions in the integration, and not just the CM of the binary. */\n\tatid = 2.0 * (single->m + bin->m) / fb_cub(r) * bin->a * (1.0 + bin->e);\n\n\treturn(atid/arel);\n}\n", "meta": {"hexsha": "101a7464ee9b34fd7403ee4e845a4d8ff2366d58", "size": 6084, "ext": "c", "lang": "C", "max_stars_repo_path": "ext/fewbod/fewbody-0.26/fewbody_utils.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_utils.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_utils.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": 21.4982332155, "max_line_length": 98, "alphanum_fraction": 0.6254109139, "num_tokens": 1986, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813030906443133, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.29746244384854564}} {"text": "/*\r\n * Copyright (c) 2016-2021 lymastee, All rights reserved.\r\n * Contact: lymastee@hotmail.com\r\n *\r\n * This file is part of the gslib project.\r\n * \r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n * \r\n * The above copyright notice and this permission notice shall be included in all\r\n * copies or substantial portions of the Software.\r\n * \r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n * SOFTWARE.\r\n */\r\n\r\n#pragma once\r\n\r\n#ifndef linequ_546582d4_5f60_4938_9ce8_1beb1678ba61_h\r\n#define linequ_546582d4_5f60_4938_9ce8_1beb1678ba61_h\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n__gslib_begin__\r\n\r\nclass _trait_dimcol {};\r\nclass _trait_dimrow {};\r\n\r\ntemplate\r\nclass ledimsel\r\n{\r\npublic:\r\n typedef _fty type;\r\n typedef _mty matrix;\r\n typedef ledimsel<_fty, _mty, _trdim> selection;\r\n\r\npublic:\r\n ledimsel(matrix& mat, int cr): _mat(mat), _sel(cr) {}\r\n int index() const { return _sel; }\r\n int capacity() const { return capacity<_trdim>(); }\r\n int cols() const { return _mat.cols(); }\r\n int rows() const { return _mat.rows(); }\r\n type& get(int i) { return get<_trdim>(i); }\r\n const type& get_const(int i) const { return get_const<_trdim>(i); }\r\n void set(int i, const type& t) { get(i) = t; }\r\n\r\nprotected:\r\n template\r\n int capacity() const;\r\n template\r\n type& get(int i);\r\n template\r\n const type& get_const(int i) const;\r\n template<>\r\n int capacity<_trait_dimcol>() const { return rows(); }\r\n template<>\r\n int capacity<_trait_dimrow>() const { return cols(); }\r\n template<>\r\n type& get<_trait_dimcol>(int i) { return _mat.get(i, _sel); }\r\n template<>\r\n type& get<_trait_dimrow>(int i) { return _mat.get(_sel, i); }\r\n template<>\r\n const type& get_const<_trait_dimcol>(int i) const { return _mat.get_const(i, _sel); }\r\n template<>\r\n const type& get_const<_trait_dimrow>(int i) const { return _mat.get_const(_sel, i); }\r\n\r\nprotected:\r\n matrix& _mat;\r\n int _sel;\r\n\r\npublic:\r\n template\r\n ledimsel& operator*=(_op t)\r\n {\r\n for_each([&t](type& n) { n *= t; });\r\n return *this;\r\n }\r\n template\r\n ledimsel& operator/=(_op t) { return operator*=(t); }\r\n template\r\n ledimsel& operator+=(const _opset& rhs)\r\n {\r\n assert(capacity() == rhs.capacity());\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n get(i) += rhs.get_const(i);\r\n return *this;\r\n }\r\n template\r\n ledimsel& operator-=(const _opset& rhs)\r\n {\r\n assert(capacity() == rhs.capacity());\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n get(i) -= rhs.get_const(i);\r\n return *this;\r\n }\r\n\r\npublic:\r\n template\r\n void for_each(_lambda lam)\r\n {\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n lam(get(i));\r\n }\r\n template\r\n void const_for_each(_lambda lam) const\r\n {\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n lam(get_const(i));\r\n }\r\n};\r\n\r\n/* optimize for row selector */\r\ntemplate\r\nclass ledimsel<_fty, _mty, _trait_dimrow>\r\n{\r\npublic:\r\n typedef _fty type;\r\n typedef _mty matrix;\r\n typedef ledimsel<_fty, _mty, _trait_dimrow> selection;\r\n\r\npublic:\r\n ledimsel(matrix& mat, int cr): _mat(mat), _sel(cr), _data(mat.data() + mat.accpos(cr, 0)) {}\r\n int index() const { return _sel; }\r\n int capacity() const { return cols(); }\r\n int cols() const { return _mat.cols(); }\r\n int rows() const { return _mat.rows(); }\r\n type& get(int i) { return _data[i]; }\r\n const type& get_const(int i) const { return _data[i]; }\r\n void set(int i, const type& t) { get(i) = t; }\r\n\r\nprotected:\r\n matrix& _mat;\r\n int _sel;\r\n type* _data;\r\n\r\npublic:\r\n template\r\n ledimsel& operator*=(_op t)\r\n {\r\n for_each([&t](type& n) { n *= t; });\r\n return *this;\r\n }\r\n template\r\n ledimsel& operator/=(_op t) { return operator*=(t); }\r\n template\r\n ledimsel& operator+=(const _opset& rhs)\r\n {\r\n assert(capacity() == rhs.capacity());\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n get(i) += rhs.get_const(i);\r\n return *this;\r\n }\r\n template\r\n ledimsel& operator-=(const _opset& rhs)\r\n {\r\n assert(capacity() == rhs.capacity());\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n get(i) -= rhs.get_const(i);\r\n return *this;\r\n }\r\n\r\npublic:\r\n template\r\n void for_each(_lambda lam)\r\n {\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n lam(get(i));\r\n }\r\n template\r\n void const_for_each(_lambda lam) const\r\n {\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n lam(get_const(i));\r\n }\r\n};\r\n\r\ntemplate\r\nstatic void swap_opset(_opset1& ops1, _opset2& ops2)\r\n{\r\n assert(ops1.capacity() == ops2.capacity());\r\n int cap = ops1.capacity();\r\n for(int i = 0; i < cap; i ++)\r\n std::swap(ops1.get(i), ops2.get(i));\r\n}\r\n\r\ntemplate\r\nstatic int first_non_zero(const _opset& ops)\r\n{\r\n int cap = ops.capacity();\r\n for(int i = 0; i < cap; i ++) {\r\n if(ops.get_const(i) != 0)\r\n return i;\r\n }\r\n return cap;\r\n}\r\n\r\ntemplate\r\nstatic int last_non_zero(const _opset& ops)\r\n{\r\n for(int i = ops.capacity() - 1; i >= 0; i --) {\r\n if(ops.get_const(i) != 0)\r\n return i;\r\n }\r\n return ops.capacity();\r\n}\r\n\r\ntemplate\r\nclass levector\r\n{\r\npublic:\r\n typedef _fty type;\r\n typedef levector<_fty> vector;\r\n\r\nprotected:\r\n int _size;\r\n type* _data;\r\n\r\npublic:\r\n levector() { _data = 0, _size = 0; }\r\n levector(int s)\r\n {\r\n assert(s > 0);\r\n _data = 0;\r\n setup(s);\r\n }\r\n ~levector()\r\n {\r\n if(_data) {\r\n delete [] _data;\r\n _data = 0;\r\n }\r\n }\r\n void setup(int s)\r\n {\r\n if(_data != 0)\r\n delete [] _data;\r\n _size = s;\r\n _data = new type[s];\r\n }\r\n int capacity() const { return _size; }\r\n type& get(int i) { return _data[i]; }\r\n const type& get_const(int i) const { return _data[i]; }\r\n type* data() const { return _data; }\r\n void set(int i, const type& t) { get(i) = t; }\r\n\r\npublic:\r\n template\r\n void for_each(_lambda lam)\r\n {\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n lam(get(i));\r\n }\r\n template\r\n void const_for_each(_lambda lam) const\r\n {\r\n int cap = capacity();\r\n for(int i = 0; i < cap; i ++)\r\n lam(get_const(i));\r\n }\r\n};\r\n\r\ntemplate\r\nclass lematrix\r\n{\r\npublic:\r\n typedef _fty type;\r\n typedef lematrix<_fty> matrix;\r\n typedef levector<_fty> vector;\r\n typedef ledimsel<_fty, lematrix, _trait_dimrow> rowselector;\r\n typedef ledimsel<_fty, const lematrix, _trait_dimrow> const_rowselector;\r\n typedef ledimsel<_fty, lematrix, _trait_dimcol> colselector;\r\n typedef ledimsel<_fty, const lematrix, _trait_dimcol> const_colselector;\r\n\r\nprotected:\r\n int _rows;\r\n int _cols;\r\n type* _data;\r\n\r\npublic:\r\n lematrix()\r\n {\r\n _rows = _cols = 0;\r\n _data = 0;\r\n }\r\n lematrix(int r, int c)\r\n {\r\n assert(r > 0 && c > 0);\r\n _data = 0;\r\n set_dim(r, c);\r\n }\r\n ~lematrix()\r\n {\r\n if(_data != 0) {\r\n delete [] _data;\r\n _data = 0;\r\n }\r\n }\r\n void set_dim(int r, int c)\r\n {\r\n if(_data != 0)\r\n delete [] _data;\r\n assert(r > 0 && c > 0);\r\n _rows = r;\r\n _cols = c;\r\n _data = new type[r * c];\r\n }\r\n int accpos(int r, int c) const\r\n {\r\n assert(r >= 0 && r < _rows && c >= 0 && c < _cols);\r\n int p = r * _cols + c;\r\n return p;\r\n }\r\n type& get(int r, int c)\r\n {\r\n assert(r >= 0 && r < _rows && c >= 0 && c < _cols);\r\n int p = accpos(r, c);\r\n return _data[p];\r\n }\r\n const type& get_const(int r, int c) const\r\n {\r\n assert(r >= 0 && r < _rows && c >= 0 && c < _cols);\r\n int p = accpos(r, c);\r\n return _data[p];\r\n }\r\n int dump_row(vector& v, int r)\r\n {\r\n int s = cols();\r\n v.setup(s);\r\n memcpy_s(v.data(), sizeof(type) * s, &get(r, 0), sizeof(type) * s);\r\n return s;\r\n }\r\n int dump_col(vector& v, int c)\r\n {\r\n int s = rows();\r\n v.setup(s);\r\n auto& sel = select_col(c);\r\n assert(s == sel.capacity());\r\n for(int i = 0; i < s; i ++)\r\n v.set(i, sel.get_const(i));\r\n return s;\r\n }\r\n bool gauss_elim()\r\n {\r\n assert(rows() >= 2);\r\n int cap = rows();\r\n arrange(0, cap);\r\n for(int i = 1; i < cap; i ++)\r\n gauss_elim(i);\r\n return row_rank() <= col_rank();\r\n }\r\n\r\npublic:\r\n int rows() const { return _rows; }\r\n int cols() const { return _cols; }\r\n type* data() const { return _data; }\r\n colselector select_col(int c) { return colselector(*this, c); }\r\n const_colselector select_col(int c) const { return const_colselector(*this, c); }\r\n rowselector select_row(int r) { return rowselector(*this, r); }\r\n const_rowselector select_row(int r) const { return const_rowselector(*this, r); }\r\n bool fuzzy_solvable() const { return rows() >= cols() - 1; }\r\n int row_rank() const { return cols() - first_non_zero(select_row(0)) - 1; }\r\n int col_rank() const { return last_non_zero(select_col(cols() - 1)) + 1; }\r\n\r\nprotected:\r\n void arrange(int start, int end)\r\n {\r\n assert(start >= 0 && end <= rows());\r\n if(end - start <= 1)\r\n return;\r\n struct node\r\n {\r\n int index, first;\r\n node(int i, int f): index(i), first(f) {}\r\n };\r\n list stlist;\r\n for(int i = start; i < end; i ++)\r\n stlist.push_back(node(i, first_non_zero(select_row(i))));\r\n stlist.sort([](const node& n1, const node& n2)->bool { return n1.first < n2.first; });\r\n assert(!stlist.empty());\r\n matrix mt;\r\n mt.set_dim(end - start, cols());\r\n auto j = stlist.begin();\r\n for(int i = 0; j != stlist.end(); ++ i, ++ j) {\r\n auto& r = mt.select_row(i);\r\n memcpy_s(&r.get(0), sizeof(type)*cols(), &get_const(j->index, 0), sizeof(type)*cols());\r\n }\r\n int cpsize = sizeof(type) * cols() * (end - start);\r\n memcpy_s(&get(start, 0), cpsize, mt.data(), cpsize);\r\n }\r\n void gauss_elim(int i)\r\n {\r\n assert(i > 0 && i < rows());\r\n auto& select1 = select_row(i - 1);\r\n auto& select2 = select_row(i);\r\n int first1 = first_non_zero(select1);\r\n if(select2.get(first1) == 0)\r\n return;\r\n int cap = rows();\r\n for(int j = i; j < cap; j ++) {\r\n if(!gauss_elim(i - 1, j, first1))\r\n break;\r\n }\r\n arrange(i, cap);\r\n }\r\n bool gauss_elim(int i, int j, int first)\r\n {\r\n assert(i < j);\r\n auto& select1 = select_row(i);\r\n auto& select2 = select_row(j);\r\n if(select2.get(first) == 0)\r\n return false;\r\n select2 *= (select1.get_const(first) / select2.get_const(first));\r\n select2 -= select1;\r\n return true;\r\n }\r\n\r\nprotected:\r\n void trace_data() const\r\n {\r\n for(int i = 0; i < rows(); i ++) {\r\n auto& sel = select_row(i);\r\n for(int j = 0; j < sel.capacity(); j ++)\r\n trace(_t(\"%lf \"), sel.get_const(j));\r\n trace(_t(\"\\r\"));\r\n }\r\n }\r\n};\r\n\r\ntemplate\r\nclass linequ\r\n{\r\npublic:\r\n typedef _fty type;\r\n typedef linequ<_fty> myref;\r\n typedef levector<_fty> vector;\r\n typedef lematrix<_fty> matrix;\r\n static double qnan()\r\n {\r\n static const struct nan_struct { union { uint a[2]; double b; }; } qnan_struct = { 0xffffffff, 0x7fffffff };\r\n return qnan_struct.b;\r\n }\r\n\r\npublic:\r\n void set_variable_count(int c) { _variables.setup(c); }\r\n int get_variable_count() const { return _variables.capacity(); }\r\n void set_equation_count(int c) { _matrix.set_dim(c, get_variable_count() + 1); }\r\n int get_equation_count() const { return _matrix.rows(); }\r\n const vector& get_results() const { return _variables; }\r\n type get_variable(int i) const { return _variables.get_const(i); }\r\n void set_equation(int i, ...)\r\n {\r\n va_list ptr;\r\n va_start(ptr, i);\r\n auto& selection = _matrix.select_row(i);\r\n int cap = _matrix.cols();\r\n for(int j = 0; j < cap; j ++)\r\n selection.set(j, va_arg(ptr, type));\r\n }\r\n void set_equation(int i, const type d[], int s)\r\n {\r\n auto& selection = _matrix.select_row(i);\r\n if(s > selection.capacity())\r\n s = selection.capacity();\r\n for(int j = 0; j < s; j ++)\r\n selection.set(j, d[j]);\r\n }\r\n int solve()\r\n {\r\n if(!_matrix.fuzzy_solvable() || !_matrix.gauss_elim())\r\n return 0;\r\n set_unsolved<_fty>();\r\n int rkcol = _matrix.col_rank();\r\n int c = 0;\r\n for(int i = rkcol - 1; i >= 0; i --, c ++) {\r\n if(!solve(i))\r\n break;\r\n }\r\n return c;\r\n }\r\n\r\nprotected:\r\n vector _variables;\r\n matrix _matrix;\r\n\r\nprotected:\r\n template\r\n void set_unsolved();\r\n template<>\r\n void set_unsolved() { _variables.for_each([](type& v) { v = qnan(); }); }\r\n template<>\r\n void set_unsolved()\r\n {\r\n float fqnan = static_cast(qnan());\r\n assert(sizeof(fqnan) == sizeof(int));\r\n memset(_variables.data(), *(int*)&fqnan, _variables.capacity());\r\n }\r\n bool solve(int c)\r\n {\r\n auto& selection = _matrix.select_row(c);\r\n int first = first_non_zero(selection);\r\n for(int i = get_variable_count() - 1; i > c; i --) {\r\n if((((type)qnan())) == get_variable(i))\r\n return false;\r\n }\r\n int cap = get_variable_count();\r\n type s = selection.get_const(cap);\r\n for(int i = c + 1; i < cap; i ++)\r\n s += (selection.get_const(i) * get_variable(i));\r\n _variables.set(c, -s / selection.get_const(c));\r\n return true;\r\n }\r\n};\r\n\r\n__gslib_end__\r\n\r\n#endif\r\n", "meta": {"hexsha": "41f5107bd6e46a35286ec70a36f48b47319ccfd2", "size": 15688, "ext": "h", "lang": "C", "max_stars_repo_path": "include/gslib/linequ.h", "max_stars_repo_name": "lymastee/gslib", "max_stars_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T09:40:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T09:44:51.000Z", "max_issues_repo_path": "include/gslib/linequ.h", "max_issues_repo_name": "lymastee/gslib", "max_issues_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/gslib/linequ.h", "max_forks_repo_name": "lymastee/gslib", "max_forks_repo_head_hexsha": "1b165b7a812526c4b2a3179588df9a7c2ff602a6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-19T15:20:58.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-19T15:20:58.000Z", "avg_line_length": 29.2141527002, "max_line_length": 117, "alphanum_fraction": 0.5363972463, "num_tokens": 4187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.296804076309196}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"bitreverse.c\"\n#include \"templates_off.h\"\n#undef BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"bitreverse.c\"\n#include \"templates_off.h\"\n#undef BASE_FLOAT\n\n#include \"factorize.c\"\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"c_init.c\"\n#include \"c_main.c\"\n#include \"c_pass_2.c\"\n#include \"c_pass_3.c\"\n#include \"c_pass_4.c\"\n#include \"c_pass_5.c\"\n#include \"c_pass_6.c\"\n#include \"c_pass_7.c\"\n#include \"c_pass_n.c\"\n#include \"c_radix2.c\"\n#include \"templates_off.h\"\n#undef BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"c_init.c\"\n#include \"c_main.c\"\n#include \"c_pass_2.c\"\n#include \"c_pass_3.c\"\n#include \"c_pass_4.c\"\n#include \"c_pass_5.c\"\n#include \"c_pass_6.c\"\n#include \"c_pass_7.c\"\n#include \"c_pass_n.c\"\n#include \"c_radix2.c\"\n#include \"templates_off.h\"\n#undef BASE_FLOAT\n\n#include \n#include \n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"hc_init.c\"\n#include \"hc_main.c\"\n#include \"hc_pass_2.c\"\n#include \"hc_pass_3.c\"\n#include \"hc_pass_4.c\"\n#include \"hc_pass_5.c\"\n#include \"hc_pass_n.c\"\n#include \"hc_radix2.c\"\n#include \"hc_unpack.c\"\n#include \"templates_off.h\"\n#undef BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"hc_init.c\"\n#include \"hc_main.c\"\n#include \"hc_pass_2.c\"\n#include \"hc_pass_3.c\"\n#include \"hc_pass_4.c\"\n#include \"hc_pass_5.c\"\n#include \"hc_pass_n.c\"\n#include \"hc_radix2.c\"\n#include \"hc_unpack.c\"\n#include \"templates_off.h\"\n#undef BASE_FLOAT\n\n#include \n#include \n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"real_init.c\"\n#include \"real_main.c\"\n#include \"real_pass_2.c\"\n#include \"real_pass_3.c\"\n#include \"real_pass_4.c\"\n#include \"real_pass_5.c\"\n#include \"real_pass_n.c\"\n#include \"real_radix2.c\"\n#include \"real_unpack.c\"\n#include \"templates_off.h\"\n#undef BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"real_init.c\"\n#include \"real_main.c\"\n#include \"real_pass_2.c\"\n#include \"real_pass_3.c\"\n#include \"real_pass_4.c\"\n#include \"real_pass_5.c\"\n#include \"real_pass_n.c\"\n#include \"real_radix2.c\"\n#include \"real_unpack.c\"\n#include \"templates_off.h\"\n#undef BASE_FLOAT\n", "meta": {"hexsha": "9aa0da77b10e56473f5de226b97a573aae771eaa", "size": 2472, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/fft/fft.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/fft/fft.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/fft/fft.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": 20.9491525424, "max_line_length": 42, "alphanum_fraction": 0.7552588997, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.29670206685186795}} {"text": "#ifndef __MMA__\n#define __MMA__\n\n#include \n\n/* -----------------------------------------------------------------------------\nAuthors: Niels Aage\n Copyright (C) 2013-2020,\nThis MMA implementation is free software; you can redistribute it and/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\nThis Module is distributed in the hope that it will be useful,implementation\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this Module; if not, write to the Free Software\nFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n-------------------------------------------------------------------------- */\nclass MMA {\n public:\n // Construct using defaults subproblem penalization\n MMA(PetscInt n, PetscInt m, Vec x);\n // User defined subproblem penalization\n MMA(PetscInt n, PetscInt m, Vec x, PetscScalar* a, PetscScalar* c, PetscScalar* d);\n // Initialize with restart from itr\n MMA(PetscInt n, PetscInt m, PetscInt itr, Vec xo1, Vec xo2, Vec U, Vec L);\n // Initialize with restart and specify subproblem parameters\n MMA(PetscInt n, PetscInt m, PetscInt itr, Vec xo1, Vec xo2, Vec U, Vec L, PetscScalar* a, PetscScalar* c,\n PetscScalar* d);\n // Destructor\n ~MMA();\n\n // Set and solve a subproblem: return new xval\n PetscErrorCode Update(Vec xval, Vec dfdx, PetscScalar* gx, Vec* dgdx, Vec xmin, Vec xmax);\n\n // Return necessary data for possible restart\n PetscErrorCode Restart(Vec xo1, Vec xo2, Vec U, Vec L);\n\n // Set the aggresivity of the moving asymptotes\n PetscErrorCode SetAsymptotes(PetscScalar init, PetscScalar decrease, PetscScalar increase);\n\n // do/don't add convexity approx to constraints: default=false\n PetscErrorCode ConstraintModification(PetscBool conMod) {\n constraintModification = conMod;\n return 0;\n };\n\n // val=0: default, val=1: increase robustness, i.e\n // control the spacing between L < alp < x < beta < U,\n PetscErrorCode SetRobustAsymptotesType(PetscInt val);\n\n // Sets outer movelimits on all primal design variables\n // This is often requires to prevent the solver from oscilating\n PetscErrorCode SetOuterMovelimit(PetscScalar Xmin, PetscScalar Xmax, PetscScalar movelim, Vec x, Vec xmin,\n Vec xmax);\n\n // Return KKT residual norms (norm2 and normInf)\n PetscErrorCode KKTresidual(Vec xval, Vec dfdx, PetscScalar* gx, Vec* dgdx, Vec xmin, Vec xmax, PetscScalar* norm2,\n PetscScalar* normInf);\n\n // Inf norm on diff between two vectors: SHOULD NOT BE HERE - USE BASIC\n // PETSc!!!!!\n PetscScalar DesignChange(Vec x, Vec xold);\n\n private:\n // Set up the MMA subproblem based on old x's and xval\n PetscErrorCode GenSub(Vec xval, Vec dfdx, PetscScalar* gx, Vec* dgdx, Vec xmin, Vec xmax);\n\n // Interior point solver for the subproblem\n PetscErrorCode SolveDIP(Vec xval);\n\n // Compute primal vars based on dual solution\n PetscErrorCode XYZofLAMBDA(Vec x);\n\n // Dual gradient\n PetscErrorCode DualGrad(Vec x);\n\n // Dual Hessian\n PetscErrorCode DualHess(Vec x);\n\n // Dual line search\n PetscErrorCode DualLineSearch();\n\n // Dual residual\n PetscScalar DualResidual(Vec x, PetscScalar epsi);\n\n // Problem size and iteration counter\n PetscInt n, m, k;\n\n // \"speed-control\" for the asymptotes\n PetscScalar asyminit, asymdec, asyminc;\n\n // do/don't add convexity constraint approximation in subproblem\n PetscBool constraintModification; // default = FALSE\n\n // Bool specifying if non lin constraints are included or not\n PetscBool NonLinConstraints;\n\n // 0: (default) span between alp L x U beta,\n // 1: increase the span for further robustness\n PetscInt RobustAsymptotesType;\n\n // Local vectors: penalty numbers for subproblem\n PetscScalar *a, *c, *d;\n\n // Local vectors: elastic variables\n PetscScalar* y;\n PetscScalar z;\n\n // Local vectors: Lagrange multipliers:\n PetscScalar *lam, *mu, *s;\n\n // Global: Asymptotes, bounds, objective approx., constraint approx.\n Vec L, U, alpha, beta, p0, q0, *pij, *qij;\n\n // Local: subproblem constant terms, dual gradient, dual hessian\n PetscScalar *b, *grad, *Hess;\n\n // Global: Old design variables\n Vec xo1, xo2;\n\n // Math helpers\n PetscErrorCode Factorize(PetscScalar* K, PetscInt nn);\n PetscErrorCode Solve(PetscScalar* K, PetscScalar* x, PetscInt nn);\n PetscScalar Min(PetscScalar d1, PetscScalar d2);\n PetscScalar Max(PetscScalar d1, PetscScalar d2);\n PetscInt Min(PetscInt d1, PetscInt d2);\n PetscInt Max(PetscInt d1, PetscInt d2);\n PetscScalar Abs(PetscScalar d1);\n};\n\n#endif\n", "meta": {"hexsha": "1f24e3b266e175bcf3a7a75a46b69ccfbf301420", "size": 5057, "ext": "h", "lang": "C", "max_stars_repo_path": "py_mma/MMA.h", "max_stars_repo_name": "TTitscher/BitJug", "max_stars_repo_head_hexsha": "7f590a4cc5b0d17080ec9acb9896c3739791dad1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "py_mma/MMA.h", "max_issues_repo_name": "TTitscher/BitJug", "max_issues_repo_head_hexsha": "7f590a4cc5b0d17080ec9acb9896c3739791dad1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "py_mma/MMA.h", "max_forks_repo_name": "TTitscher/BitJug", "max_forks_repo_head_hexsha": "7f590a4cc5b0d17080ec9acb9896c3739791dad1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4592592593, "max_line_length": 118, "alphanum_fraction": 0.6802452047, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737473266735, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2962243547015159}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C code for structures representing a waveform as a list of modes in amplitude/phase form.\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\n\n/* Call a function that references an object */\ndouble ObjectFunctionCall(const ObjectFunction* this,double f){return this->function(this->object,f);};\n \n/**************************************************************/\n/* Functions computing the max and min between two int */\nint max (int a, int b) { return a > b ? a : b; }\nint min (int a, int b) { return a < b ? a : b; }\n\n/************** GSL error handling and I/O ********************/\n\n/* GSL error handler */\nvoid Err_Handler(const char *reason, const char *file, int line, int gsl_errno) {\n printf(\"gsl: %s:%d: %s - %d\\n\", file, line, reason, gsl_errno);\n exit(1);\n}\n\n/* Functions to read binary data from files */\nint Read_Vector(const char dir[], const char fname[], gsl_vector *v) {\n char *path=malloc(strlen(dir)+64);\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"rb\");\n if (!f) {\n fprintf(stderr, \"Error reading data from %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_vector_fread(f, v);\n if (ret != 0) {\n fprintf(stderr, \"Error reading data from %s.\\n\",path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\nint Read_Matrix(const char dir[], const char fname[], gsl_matrix *m) {\n char *path=malloc(strlen(dir)+64);\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"rb\");\n if (!f) {\n fprintf(stderr, \"Error reading data from %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_matrix_fread(f, m);\n if (ret != 0) {\n fprintf(stderr, \"Error reading data from %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\n/* Functions to read text data from files */\nint Read_Text_Vector(const char dir[], const char fname[], gsl_vector *v) {\n char *path=malloc(strlen(dir)+64);\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"rb\");\n if (!f) {\n fprintf(stderr, \"Error reading data from %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_vector_fscanf(f, v);\n if (ret != 0) {\n fprintf(stderr, \"Error reading data from %s.\\n\",path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\nint Read_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m) {\n char *path=malloc(strlen(dir)+64);\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"rb\");\n if (!f) {\n fprintf(stderr, \"Error reading data from %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_matrix_fscanf(f, m);\n if (ret != 0) {\n fprintf(stderr, \"Error reading data from %s.\\n\",path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\n/* Functions to write data to files */\nint Write_Vector(const char dir[], const char fname[], gsl_vector *v) {\n char *path=malloc(strlen(dir)+64);\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"w\");\n if (!f) {\n fprintf(stderr, \"Error writing data to %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_vector_fwrite(f, v);\n if (ret != 0) {\n fprintf(stderr, \"Error writing data to %s\\n\",path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\nint Write_Matrix(const char dir[], const char fname[], gsl_matrix *m) {\n char *path=malloc(strlen(dir)+64);\n\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"w\");\n if (!f) {\n fprintf(stderr, \"Error writing data to %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_matrix_fwrite(f, m);\n if (ret != 0) {\n fprintf(stderr, \"Error writing data to %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\n/* Functions to write text data to files */\nint Write_Text_Vector(const char dir[], const char fname[], gsl_vector *v) {\n char *path=malloc(strlen(dir)+64);\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"w\");\n if (!f) {\n fprintf(stderr, \"Error writing data to %s\\n\", path);\n free(path);\n return(FAILURE);\n }\n int ret = gsl_vector_fprintf(f, v, \"%.16e\");\n if (ret != 0) {\n fprintf(stderr, \"Error writing data to %s\\n\",path);\n free(path);\n return(FAILURE);\n }\n fclose(f);\n free(path);\n return(SUCCESS);\n}\nint Write_Text_Matrix(const char dir[], const char fname[], gsl_matrix *m) {\n char *path=malloc(strlen(dir)+64);\n int ret = 0;\n\n sprintf(path,\"%s/%s\", dir, fname);\n FILE *f = fopen(path, \"w\");\n if (!f) {\n fprintf(stderr, \"Error writing data to %s\\n\",path);\n free(path);\n return(FAILURE);\n }\n int N = (int) m->size1;\n int M = (int) m->size2;\n for(int i=0; ifreq = gsl_vector_alloc(n);\n (*freqseries)->amp_real = gsl_vector_alloc(n);\n (*freqseries)->amp_imag = gsl_vector_alloc(n);\n (*freqseries)->phase = gsl_vector_alloc(n);\n}\nvoid CAmpPhaseFrequencySeries_Cleanup(CAmpPhaseFrequencySeries *freqseries) {\n if(freqseries->freq) gsl_vector_free(freqseries->freq);\n if(freqseries->amp_real) gsl_vector_free(freqseries->amp_real);\n if(freqseries->amp_imag) gsl_vector_free(freqseries->amp_imag);\n if(freqseries->phase) gsl_vector_free(freqseries->phase);\n free(freqseries);\n}\n\n/******** Functions to initialize and clean up CAmpPhaseSpline structure ********/\nvoid CAmpPhaseSpline_Init(CAmpPhaseSpline **splines, const int n) {\n if(!splines) exit(1);\n /* Create storage for structures */\n if(!*splines) *splines=malloc(sizeof(CAmpPhaseSpline));\n else\n {\n CAmpPhaseSpline_Cleanup(*splines);\n }\n gsl_set_error_handler(&Err_Handler);\n (*splines)->spline_amp_real = gsl_matrix_alloc(n, 5);\n (*splines)->spline_amp_imag = gsl_matrix_alloc(n, 5);\n (*splines)->quadspline_phase = gsl_matrix_alloc(n, 4);\n}\nvoid CAmpPhaseSpline_Cleanup(CAmpPhaseSpline *splines) {\n if(splines->spline_amp_real) gsl_matrix_free(splines->spline_amp_real);\n if(splines->spline_amp_imag) gsl_matrix_free(splines->spline_amp_imag);\n if(splines->quadspline_phase) gsl_matrix_free(splines->quadspline_phase);\n free(splines);\n}\n\n/******** Functions to initialize and clean up CAmpPhaseGSLSpline structure ********/\nvoid CAmpPhaseGSLSpline_Init(CAmpPhaseGSLSpline **splines, const int n) {\n if(!splines) exit(1);\n /* Create storage for structures */\n if(!*splines) *splines=malloc(sizeof(CAmpPhaseGSLSpline));\n else\n {\n CAmpPhaseGSLSpline_Cleanup(*splines);\n }\n gsl_set_error_handler(&Err_Handler);\n /* Note: for freq we won't copy the vector but simply copy the pointer to the existing one, so we don't allocate anything here */\n (*splines)->spline_amp_real = gsl_spline_alloc(gsl_interp_cspline, n);\n (*splines)->spline_amp_imag = gsl_spline_alloc(gsl_interp_cspline, n);\n (*splines)->spline_phase = gsl_spline_alloc(gsl_interp_cspline, n);\n (*splines)->accel_amp_real = gsl_interp_accel_alloc();\n (*splines)->accel_amp_imag = gsl_interp_accel_alloc();\n (*splines)->accel_phase = gsl_interp_accel_alloc();\n}\nvoid CAmpPhaseGSLSpline_Cleanup(CAmpPhaseGSLSpline *splines) {\n if(splines->spline_amp_real) gsl_spline_free(splines->spline_amp_real);\n if(splines->spline_amp_imag) gsl_spline_free(splines->spline_amp_imag);\n if(splines->spline_phase) gsl_spline_free(splines->spline_phase);\n if(splines->accel_amp_real) gsl_interp_accel_free(splines->accel_amp_real);\n if(splines->accel_amp_imag) gsl_interp_accel_free(splines->accel_amp_imag);\n if(splines->accel_phase) gsl_interp_accel_free(splines->accel_phase);\n free(splines);\n}\n\n/******** Functions to initialize and clean up ReImFrequencySeries structure ********/\nvoid ReImFrequencySeries_Init(ReImFrequencySeries **freqseries, const int n) {\n if(!freqseries) exit(1);\n /* Create storage for structures */\n if(!*freqseries) *freqseries=malloc(sizeof(ReImFrequencySeries));\n else\n {\n ReImFrequencySeries_Cleanup(*freqseries);\n }\n gsl_set_error_handler(&Err_Handler);\n (*freqseries)->freq = gsl_vector_alloc(n);\n (*freqseries)->h_real = gsl_vector_alloc(n);\n (*freqseries)->h_imag = gsl_vector_alloc(n);\n}\nvoid ReImFrequencySeries_Cleanup(ReImFrequencySeries *freqseries) {\n if(freqseries->freq) gsl_vector_free(freqseries->freq);\n if(freqseries->h_real) gsl_vector_free(freqseries->h_real);\n if(freqseries->h_imag) gsl_vector_free(freqseries->h_imag);\n free(freqseries);\n}\n\n/******** Functions to initialize and clean up ReImTimeSeries structure ********/\nvoid ReImTimeSeries_Init(ReImTimeSeries **timeseries, const int n) {\n if(!timeseries) exit(1);\n /* Create storage for structures */\n if(!*timeseries) *timeseries=malloc(sizeof(ReImTimeSeries));\n else\n {\n ReImTimeSeries_Cleanup(*timeseries);\n }\n gsl_set_error_handler(&Err_Handler);\n (*timeseries)->times = gsl_vector_alloc(n);\n (*timeseries)->h_real = gsl_vector_alloc(n);\n (*timeseries)->h_imag = gsl_vector_alloc(n);\n}\nvoid ReImTimeSeries_Cleanup(ReImTimeSeries *timeseries) {\n if(timeseries->times) gsl_vector_free(timeseries->times);\n if(timeseries->h_real) gsl_vector_free(timeseries->h_real);\n if(timeseries->h_imag) gsl_vector_free(timeseries->h_imag);\n free(timeseries);\n}\n/******** Functions to initialize and clean up AmpPhaseTimeSeries structure ********/\nvoid AmpPhaseTimeSeries_Init(AmpPhaseTimeSeries **timeseries, const int n) {\n if(!timeseries) exit(1);\n /* Create storage for structures */\n if(!*timeseries) *timeseries=malloc(sizeof(AmpPhaseTimeSeries));\n else\n {\n AmpPhaseTimeSeries_Cleanup(*timeseries);\n }\n gsl_set_error_handler(&Err_Handler);\n (*timeseries)->times = gsl_vector_alloc(n);\n (*timeseries)->h_amp = gsl_vector_alloc(n);\n (*timeseries)->h_phase = gsl_vector_alloc(n);\n}\nvoid AmpPhaseTimeSeries_Cleanup(AmpPhaseTimeSeries *timeseries) {\n if(timeseries->times) gsl_vector_free(timeseries->times);\n if(timeseries->h_amp) gsl_vector_free(timeseries->h_amp);\n if(timeseries->h_phase) gsl_vector_free(timeseries->h_phase);\n free(timeseries);\n}\n\n/******** Functions to initialize and clean up RealTimeSeries structure ********/\nvoid RealTimeSeries_Init(RealTimeSeries **timeseries, const int n) {\n if(!timeseries) exit(1);\n /* Create storage for structures */\n if(!*timeseries) *timeseries=malloc(sizeof(RealTimeSeries));\n else\n {\n RealTimeSeries_Cleanup(*timeseries);\n }\n gsl_set_error_handler(&Err_Handler);\n (*timeseries)->times = gsl_vector_alloc(n);\n (*timeseries)->h = gsl_vector_alloc(n);\n}\nvoid RealTimeSeries_Cleanup(RealTimeSeries *timeseries) {\n if(timeseries->times) gsl_vector_free(timeseries->times);\n if(timeseries->h) gsl_vector_free(timeseries->h);\n free(timeseries);\n}\n\n/***************** Functions for the ListmodesCAmpPhaseFrequencySeries structure ****************/\nListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_AddModeNoCopy(\n\t ListmodesCAmpPhaseFrequencySeries* appended, /* List structure to prepend to */\n\t CAmpPhaseFrequencySeries* freqseries, /* data to contain */\n\t int l, /* major mode number */\n\t int m /* minor mode number */)\n{\n ListmodesCAmpPhaseFrequencySeries* list;\n /* Check if the node with this mode already exists */\n list = appended;\n while( list ){\n if( l == list->l && m == list->m ){\n\tbreak;\n }\n list = list->next;\n }\n if( list ){ /* We don't allow for the case where the mode already exists in the list*/\n printf(\"Error: Tried to add an already existing mode to a ListmodesCAmpPhaseFrequencySeries \");\n return(NULL);\n } else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be\n\t\tused anywhere else; this will be acceptable as these operations will only be done\n\t\twhen interpolating the initialization data */\n list = malloc( sizeof(ListmodesCAmpPhaseFrequencySeries) );\n }\n list->l = l;\n list->m = m;\n if( freqseries ){\n list->freqseries = freqseries;\n } else {\n list->freqseries = NULL;\n }\n if( appended ){\n list->next = appended;\n } else {\n list->next = NULL;\n }\n return list;\n}\n/* Get the element of a ListmodesCAmpPhaseFrequencySeries with a given index */\nListmodesCAmpPhaseFrequencySeries* ListmodesCAmpPhaseFrequencySeries_GetMode(\n\t ListmodesCAmpPhaseFrequencySeries* const list, /* List structure to get a particular mode from */\n\t int l, /*< major mode number */\n\t int m /*< minor mode number */ )\n{\n if( !list ) return NULL;\n\n ListmodesCAmpPhaseFrequencySeries *itr = list;\n while( itr->l != l || itr->m != m ){\n itr = itr->next;\n if( !itr ) return NULL;\n }\n return itr; /* The element returned is itself a pointer to a ListmodesCAmpPhaseFrequencySeries */\n}\nvoid ListmodesCAmpPhaseFrequencySeries_Destroy(\n\t ListmodesCAmpPhaseFrequencySeries* list /* List structure to destroy; notice that the data is destroyed too */\n)\n{\n ListmodesCAmpPhaseFrequencySeries* pop;\n while( (pop = list) ){\n if( pop->freqseries ){ /* Destroying the CAmpPhaseFrequencySeries data */\n CAmpPhaseFrequencySeries_Cleanup( pop->freqseries );\n }\n /* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */\n list = pop->next;\n free( pop );\n }\n}\n\n/***************** Functions for the ListmodesCAmpPhaseSpline structure ****************/\nListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_AddModeNoCopy(\n\t ListmodesCAmpPhaseSpline* appended, /* List structure to prepend to */\n\t CAmpPhaseSpline* splines, /* data to contain */\n\t int l, /* major mode number */\n\t int m /* minor mode number */)\n{\n ListmodesCAmpPhaseSpline* list;\n /* Check if the node with this mode already exists */\n list = appended;\n while( list ){\n if( l == list->l && m == list->m ){\n\tbreak;\n }\n list = list->next;\n }\n if( list ){ /* We don't allow for the case where the mode already exists in the list*/\n printf(\"Error: Tried to add an already existing mode to a ListmodesCAmpPhaseSpline \");\n return(NULL);\n } else { /* In that case, we do NOT COPY the input interpolated data, which therefore can't be\n\t\tused anywhere else; this will be acceptable as these operations will only be done\n\t\twhen interpolating the initialization data */\n list = malloc( sizeof(ListmodesCAmpPhaseSpline) );\n }\n list->l = l;\n list->m = m;\n if( splines ){\n list->splines = splines;\n } else {\n list->splines = NULL;\n }\n if( appended ){\n list->next = appended;\n } else {\n list->next = NULL;\n }\n return list;\n}\n/* Get the element of a ListmodesCAmpPhaseSpline with a given index */\nListmodesCAmpPhaseSpline* ListmodesCAmpPhaseSpline_GetMode(\n\t ListmodesCAmpPhaseSpline* const list, /* List structure to get a particular mode from */\n\t int l, /*< major mode number */\n\t int m /*< minor mode number */ )\n{\n if( !list ) return NULL;\n\n ListmodesCAmpPhaseSpline *itr = list;\n while( itr->l != l || itr->m != m ){\n itr = itr->next;\n if( !itr ) return NULL;\n }\n return itr; /* The element returned is itself a pointer to a ListmodesCAmpPhaseSpline */\n}\nvoid ListmodesCAmpPhaseSpline_Destroy(\n\t ListmodesCAmpPhaseSpline* list /* List structure to destroy; notice that the data is destroyed too */\n)\n{\n ListmodesCAmpPhaseSpline* pop;\n while( (pop = list) ){\n if( pop->splines ){ /* Destroying the CAmpPhaseSpline data */\n CAmpPhaseSpline_Cleanup( pop->splines );\n }\n /* Notice that the mode indices l and m are not freed, like in SphHarmTimeSeries struct indices l and m */\n list = pop->next;\n free( pop );\n }\n}\n\n/***********************************************************************/\n/**************** I/O functions for internal structures ****************/\n\n/* Read waveform Real time series */\nint Read_RealTimeSeries(RealTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary)\n{\n /* Initalize and read input */\n int ret;\n gsl_matrix* inmatrix = gsl_matrix_alloc(nblines, 2);\n if(!binary) ret = Read_Text_Matrix(dir, file, inmatrix);\n else ret = Read_Matrix(dir, file, inmatrix);\n\n /* Initialize structures */\n RealTimeSeries_Init(timeseries, nblines);\n\n /* Set values */\n gsl_vector_view timesview = gsl_matrix_column(inmatrix, 0);\n gsl_vector_view hview = gsl_matrix_column(inmatrix, 1);\n gsl_vector_memcpy((*timeseries)->times, ×view.vector);\n gsl_vector_memcpy((*timeseries)->h, &hview.vector);\n\n /* Clean up */\n gsl_matrix_free(inmatrix);\n\n return ret;\n}\n\n/* Read waveform Amp/Phase time series */\nint Read_AmpPhaseTimeSeries(AmpPhaseTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary)\n{\n /* Initalize and read input */\n int ret;\n gsl_matrix* inmatrix = gsl_matrix_alloc(nblines, 3);\n if(!binary) ret = Read_Text_Matrix(dir, file, inmatrix);\n else ret = Read_Matrix(dir, file, inmatrix);\n\n /* Initialize structures */\n AmpPhaseTimeSeries_Init(timeseries, nblines);\n\n /* Set values */\n gsl_vector_view timesview = gsl_matrix_column(inmatrix, 0);\n gsl_vector_view hampview = gsl_matrix_column(inmatrix, 1);\n gsl_vector_view hphaseview = gsl_matrix_column(inmatrix, 2);\n gsl_vector_memcpy((*timeseries)->times, ×view.vector);\n gsl_vector_memcpy((*timeseries)->h_amp, &hampview.vector);\n gsl_vector_memcpy((*timeseries)->h_phase, &hphaseview.vector);\n\n /* Clean up */\n gsl_matrix_free(inmatrix);\n\n return ret;\n}\n\n/* Read waveform Re/Im time series */\nint Read_ReImTimeSeries(ReImTimeSeries** timeseries, const char dir[], const char file[], const int nblines, const int binary)\n{\n /* Initalize and read input */\n int ret;\n gsl_matrix* inmatrix = gsl_matrix_alloc(nblines, 3);\n if(!binary) ret = Read_Text_Matrix(dir, file, inmatrix);\n else ret = Read_Matrix(dir, file, inmatrix);\n\n /* Initialize structures */\n ReImTimeSeries_Init(timeseries, nblines);\n\n /* Set values */\n gsl_vector_view timesview = gsl_matrix_column(inmatrix, 0);\n gsl_vector_view hrealview = gsl_matrix_column(inmatrix, 1);\n gsl_vector_view himagview = gsl_matrix_column(inmatrix, 2);\n gsl_vector_memcpy((*timeseries)->times, ×view.vector);\n gsl_vector_memcpy((*timeseries)->h_real, &hrealview.vector);\n gsl_vector_memcpy((*timeseries)->h_imag, &himagview.vector);\n\n /* Clean up */\n gsl_matrix_free(inmatrix);\n\n return ret;\n}\n\n/* Output Re/Im frequency series */\nint Write_ReImFrequencySeries(const char dir[], const char file[], ReImFrequencySeries* freqseries, const int binary)\n{\n /* Initialize output */\n /* Note: assumes hplus, hcross have same length as expected */\n int nbfreq = freqseries->freq->size;\n gsl_matrix* outmatrix = gsl_matrix_alloc(nbfreq, 3);\n\n /* Set output matrix */\n gsl_matrix_set_col(outmatrix, 0, freqseries->freq);\n gsl_matrix_set_col(outmatrix, 1, freqseries->h_real);\n gsl_matrix_set_col(outmatrix, 2, freqseries->h_imag);\n\n /* Output */\n int ret;\n if (!binary) ret = Write_Text_Matrix(dir, file, outmatrix);\n else ret = Write_Matrix(dir, file, outmatrix);\n\n return ret;\n}\n\n/* Output real time series */\nint Write_RealTimeSeries(const char dir[], const char file[], RealTimeSeries* timeseries, int binary)\n{\n /* Initialize output */\n int nbtimes = timeseries->times->size;\n gsl_matrix* outmatrix = gsl_matrix_alloc(nbtimes, 2);\n\n /* Set data */\n gsl_matrix_set_col(outmatrix, 0, timeseries->times);\n gsl_matrix_set_col(outmatrix, 1, timeseries->h);\n\n /* Output */\n int ret;\n if(!binary) ret = Write_Text_Matrix(dir, file, outmatrix);\n else ret = Write_Matrix(dir, file, outmatrix);\n\n return ret;\n}\n\n/* Output Amp/Phase time series */\nint Write_AmpPhaseTimeSeries(const char dir[], const char file[], AmpPhaseTimeSeries* timeseries, int binary)\n{\n /* Initialize output */\n int nbtimes = timeseries->times->size;\n gsl_matrix* outmatrix = gsl_matrix_alloc(nbtimes, 3);\n\n /* Set data */\n gsl_matrix_set_col(outmatrix, 0, timeseries->times);\n gsl_matrix_set_col(outmatrix, 1, timeseries->h_amp);\n gsl_matrix_set_col(outmatrix, 2, timeseries->h_phase);\n\n /* Output */\n int ret;\n if(!binary) ret = Write_Text_Matrix(dir, file, outmatrix);\n else ret = Write_Matrix(dir, file, outmatrix);\n\n return ret;\n}\n\n/* Output Re/Im time series */\nint Write_ReImTimeSeries(const char dir[], const char file[], ReImTimeSeries* timeseries, int binary)\n{\n /* Initialize output */\n int nbtimes = timeseries->times->size;\n gsl_matrix* outmatrix = gsl_matrix_alloc(nbtimes, 3);\n\n /* Set data */\n gsl_matrix_set_col(outmatrix, 0, timeseries->times);\n gsl_matrix_set_col(outmatrix, 1, timeseries->h_real);\n gsl_matrix_set_col(outmatrix, 2, timeseries->h_imag);\n\n /* Output */\n int ret;\n if(!binary) ret = Write_Text_Matrix(dir, file, outmatrix);\n else ret = Write_Matrix(dir, file, outmatrix);\n\n return ret;\n}\n", "meta": {"hexsha": "c7ada6c74937a020e68bf69785c32ff6be36c170", "size": 22102, "ext": "c", "lang": "C", "max_stars_repo_path": "tools/struct.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": "tools/struct.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/struct.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": 33.0868263473, "max_line_length": 134, "alphanum_fraction": 0.6835128043, "num_tokens": 5959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.29613235052132963}} {"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#include \n#include \n#include \n\n#include \n#include \n\n#include \"common-driver-utils.h\"\n#include \"stokes_block_scaling.h\"\n#include \"stokes_Kblock_scaling.h\"\n#include \n#include \n#include \n#include \"Solvers/SLE/src/SLE.h\" /* to give the AugLagStokes_SLE type */\n#include \"Solvers/KSPSolvers/src/KSPSolvers.h\" /* for __KSP_COMMON */\n\n#include \"BSSCR.h\"\n\n#undef __FUNCT__ \n#define __FUNCT__ \"KSPUnscale_BSSCR\" \nPetscErrorCode KSPUnscale_BSSCR(KSP ksp)\n{\n KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;\n Mat Amat,Pmat;\n Vec B,X;\n Mat ApproxS;\n MatStokesBlockScaling BA=bsscr->BA;\n PetscTruth sym;\n MatStructure pflag;\n PetscErrorCode ierr;\n\n PetscFunctionBegin;\n X = ksp->vec_sol;\n B = ksp->vec_rhs;\n ApproxS = bsscr->preconditioner->matrix;\n sym = bsscr->DIsSym;\n ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);\n if( BA->scaling_exists == PETSC_FALSE ){\n\tPetscPrintf( PETSC_COMM_WORLD, \"SCALING does not EXIST in %s\\n\", __func__);\n }else{\n\tif( DEFAULT == bsscr->scaletype ){\n\t PetscPrintf( PETSC_COMM_WORLD, \"Operator scales (pre-Unscaling)\\n\");\n\t BSSCR_MatStokesBlockReportOperatorScales(Amat, sym);\n\t BSSCR_MatStokesBlockUnScaleSystem( BA, Amat, B, X, ApproxS, sym);\n\t PetscPrintf( PETSC_COMM_WORLD, \"Operator scales (post-Unscaling)\\n\");\n\t BSSCR_MatStokesBlockReportOperatorScales(Amat, sym);\n\t}\n\tif( KONLY == bsscr->scaletype ){\n\t PetscPrintf( PETSC_COMM_WORLD, \"Operator scales KONLY (pre-Unscaling)\\n\");\n\t BSSCR_MatStokesKBlockReportOperatorScales(Amat, sym);\n\t BSSCR_MatStokesKBlockUnScaleSystem( BA, Amat, B, X, ApproxS, sym);\n\t PetscPrintf( PETSC_COMM_WORLD, \"Operator scales KONLY (post-Unscaling)\\n\");\n\t BSSCR_MatStokesKBlockReportOperatorScales(Amat, sym);\n\t}\n }\n bsscr->scaled = PETSC_FALSE;\n PetscFunctionReturn(0);\n}\n/*\n KSPScale_BSSCR constructs scaling and applies scaling to system.\n Want to do both here when doing nonlinear iterations to keep the\n scaling up to date with each iteration.\n */\n#undef __FUNCT__ \n#define __FUNCT__ \"KSPScale_BSSCR\" \nPetscErrorCode KSPScale_BSSCR(KSP ksp)\n{\n KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;\n Mat Amat,Pmat;\n Vec B,X;\n Mat ApproxS;\n MatStokesBlockScaling BA=bsscr->BA;\n PetscTruth sym;\n MatStructure pflag;\n PetscErrorCode ierr;\n\n PetscFunctionBegin;\n X = ksp->vec_sol;\n B = ksp->vec_rhs;\n ApproxS = bsscr->preconditioner->matrix;\n sym = bsscr->DIsSym;\n ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);\n\n if( DEFAULT == bsscr->scaletype ){\n\tif( BA->scaling_exists ){\n\t BSSCR_MatStokesBlockDefaultBuildScaling( BA, Amat);/* rebuild scaling vectors on struct */\n\t BA->scalings_have_been_inverted = PETSC_FALSE;\n\t}else{\n\t BSSCR_MatBlock_ConstructScaling( BA, Amat, B, X );/* allocates scaling vectors then calls the above function */\n\t BA->scalings_have_been_inverted = PETSC_FALSE;/* above function sets this but I am making it explicit here */\n\t}\n\tPetscPrintf( PETSC_COMM_WORLD, \"Operator scales (pre-scaling)\\n\");\n\tBSSCR_MatStokesBlockReportOperatorScales(Amat, sym);\n\tBSSCR_MatStokesBlockScaleSystem( BA, Amat, B, X, ApproxS, sym );\n\tPetscPrintf( PETSC_COMM_WORLD, \"Operator scales (post-scaling)\\n\");\n\tBSSCR_MatStokesBlockReportOperatorScales(Amat, sym);\n\tbsscr->scaled = PETSC_TRUE;\n }\n\n if( KONLY == bsscr->scaletype ){\n\tif( BA->scaling_exists ){\n\t BSSCR_MatStokesKBlockDefaultBuildScaling( BA, Amat, B, X, sym);/* rebuild scaling vectors on struct */\n\t BA->scalings_have_been_inverted = PETSC_FALSE;\n\t}else{\n\t BSSCR_MatKBlock_ConstructScaling( BA, Amat, B, X, sym);/* allocates scaling vectors then calls the above function */\n\t BA->scalings_have_been_inverted = PETSC_FALSE;/* above function sets this but I am making it explicit here */\n\t}\n\tPetscPrintf( PETSC_COMM_WORLD, \"Operator scales KONLY (pre-scaling)\\n\");\n\tBSSCR_MatStokesKBlockReportOperatorScales(Amat, sym);\n\tBSSCR_MatStokesKBlockScaleSystem( BA, Amat, B, X, ApproxS, sym );\n\tPetscPrintf( PETSC_COMM_WORLD, \"Operator scales KONLY (post-scaling)\\n\");\n\tBSSCR_MatStokesKBlockReportOperatorScales(Amat, sym);\n\tbsscr->scaled = PETSC_TRUE;\n }\n PetscFunctionReturn(0);\n}\n\n", "meta": {"hexsha": "2ce12e7a24bad82a3deb24145eb23b6117ed6a70", "size": 5284, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_scale.c", "max_stars_repo_name": "rbeucher/underworld2", "max_stars_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_scale.c", "max_issues_repo_name": "rbeucher/underworld2", "max_issues_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_scale.c", "max_forks_repo_name": "rbeucher/underworld2", "max_forks_repo_head_hexsha": "76991c475ac565e092e99a364370fbae15bb40ac", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9365079365, "max_line_length": 121, "alphanum_fraction": 0.6449659349, "num_tokens": 1614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.5195213219520929, "lm_q1q2_score": 0.29605060278058803}} {"text": "/* movstat/gsl_movstat.h\r\n * \r\n * Copyright (C) 2018 Patrick Alken\r\n * \r\n * This program is free software; you can redistribute it and/or modify\r\n * it under the terms of the GNU General Public License as published by\r\n * the Free Software Foundation; either version 3 of the License, or (at\r\n * your option) any later version.\r\n * \r\n * This program is distributed in the hope that it will be useful, but\r\n * WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n * General Public License for more details.\r\n * \r\n * You should have received a copy of the GNU General Public License\r\n * along with this program; if not, write to the Free Software\r\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\r\n */\r\n\r\n#ifndef __GSL_MOVSTAT_H__\r\n#define __GSL_MOVSTAT_H__\r\n\r\n#if !defined( GSL_FUN )\r\n# if !defined( GSL_DLL )\r\n# define GSL_FUN extern\r\n# elif defined( BUILD_GSL_DLL )\r\n# define GSL_FUN extern __declspec(dllexport)\r\n# else\r\n# define GSL_FUN extern __declspec(dllimport)\r\n# endif\r\n#endif\r\n\r\n#include \r\n#include \r\n\r\n#undef __BEGIN_DECLS\r\n#undef __END_DECLS\r\n#ifdef __cplusplus\r\n# define __BEGIN_DECLS extern \"C\" {\r\n# define __END_DECLS }\r\n#else\r\n# define __BEGIN_DECLS /* empty */\r\n# define __END_DECLS /* empty */\r\n#endif\r\n\r\n__BEGIN_DECLS\r\n\r\ntypedef enum\r\n{\r\n GSL_MOVSTAT_END_PADZERO,\r\n GSL_MOVSTAT_END_PADVALUE,\r\n GSL_MOVSTAT_END_TRUNCATE\r\n} gsl_movstat_end_t;\r\n\r\n/* accumulator struct\r\n * size - return number of bytes needed for accumulator with maximum of n elements\r\n * init - initialize accumulator state\r\n * insert - insert a single sample into accumulator; if there are already n\r\n * samples in accumulator, oldest sample is overwritten\r\n * delete_oldest - delete oldest sample from accumulator\r\n * get - return accumulated value\r\n */\r\ntypedef struct\r\n{\r\n size_t (*size) (const size_t n);\r\n int (*init) (const size_t n, void * vstate);\r\n int (*insert) (const double x, void * vstate);\r\n int (*delete_oldest) (void * vstate);\r\n int (*get) (void * params, double * result, const void * vstate);\r\n} gsl_movstat_accum;\r\n\r\ntypedef struct\r\n{\r\n double (* function) (const size_t n, double x[], void * params);\r\n void * params;\r\n} gsl_movstat_function;\r\n\r\n#define GSL_MOVSTAT_FN_EVAL(F,n,x) (*((F)->function))((n),(x),(F)->params)\r\n\r\n/* workspace for moving window statistics */\r\n\r\ntypedef struct\r\n{\r\n size_t H; /* number of previous samples in window */\r\n size_t J; /* number of after samples in window */\r\n size_t K; /* window size K = H + J + 1 */\r\n double *work; /* workspace, size K */\r\n void *state; /* state workspace for various accumulators */\r\n size_t state_size; /* bytes allocated for 'state' */\r\n} gsl_movstat_workspace;\r\n\r\n/* alloc.c */\r\n\r\nGSL_FUN gsl_movstat_workspace *gsl_movstat_alloc(const size_t K);\r\nGSL_FUN gsl_movstat_workspace *gsl_movstat_alloc2(const size_t H, const size_t J);\r\nGSL_FUN gsl_movstat_workspace *gsl_movstat_alloc_with_size(const size_t accum_state_size, const size_t H, const size_t J);\r\nGSL_FUN void gsl_movstat_free(gsl_movstat_workspace * w);\r\n\r\n/* apply.c */\r\nGSL_FUN int gsl_movstat_apply_accum(const gsl_movstat_end_t endtype, const gsl_vector * x,\r\n const gsl_movstat_accum * accum, void * accum_params,\r\n gsl_vector * y, gsl_vector * z,\r\n gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_apply(const gsl_movstat_end_t endtype, const gsl_movstat_function * F,\r\n const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\n\r\n/* fill.c */\r\nGSL_FUN size_t gsl_movstat_fill(const gsl_movstat_end_t endtype, const gsl_vector * x, const size_t idx,\r\n const size_t H, const size_t J, double * window);\r\n\r\nGSL_FUN int gsl_movstat_mean(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_variance(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_sd(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_median(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_min(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_max(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_minmax(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y_min, gsl_vector * y_max, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_mad0(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian,\r\n gsl_vector * xmad, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_mad(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * xmedian,\r\n gsl_vector * xmad, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_qqr(const gsl_movstat_end_t endtype, const gsl_vector * x, const double q,\r\n gsl_vector * xqqr, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_Sn(const gsl_movstat_end_t endtype, const gsl_vector * x,\r\n gsl_vector * xscale, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_Qn(const gsl_movstat_end_t endtype, const gsl_vector * x,\r\n gsl_vector * xscale, gsl_movstat_workspace * w);\r\nGSL_FUN int gsl_movstat_sum(const gsl_movstat_end_t endtype, const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w);\r\n\r\n/* accumulator variables */\r\n\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_mad;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_max;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_mean;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_median;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_min;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_minmax;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_sd;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_Sn;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_sum;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_Qn;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_qqr;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_userfunc;\r\nGSL_VAR const gsl_movstat_accum * gsl_movstat_accum_variance;\r\n\r\n__END_DECLS\r\n\r\n#endif /* __GSL_MOVSTAT_H__ */\r\n", "meta": {"hexsha": "d21ba936858917d7451fedd17b40dc879af819ec", "size": 6673, "ext": "h", "lang": "C", "max_stars_repo_path": "vendor/gsl/gsl/gsl_movstat.h", "max_stars_repo_name": "mgreter/astrometrylib", "max_stars_repo_head_hexsha": "ef4d4539a537ab49329b77648aac893d2b4ad318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-01-09T05:48:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T16:18:47.000Z", "max_issues_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_movstat.h", "max_issues_repo_name": "zzpwahaha/VimbaCamJILA", "max_issues_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-01-11T01:08:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-13T16:28:48.000Z", "max_forks_repo_path": "VimbaCam/ExternLib/GSL_MSVC/gsl/gsl_movstat.h", "max_forks_repo_name": "zzpwahaha/VimbaCamJILA", "max_forks_repo_head_hexsha": "3baed1b5313e6c198d54a33c2c84357035d5146a", "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": 44.7852348993, "max_line_length": 154, "alphanum_fraction": 0.7247115241, "num_tokens": 1666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.29580001210277695}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n\n#ifdef SUBFIND\n\n#include \"fof.h\"\n#include \"subfind.h\"\n\n#ifdef PERIODIC\n#define NEAREST(x) (((x)>boxhalf)?((x)-boxsize):(((x)<-boxhalf)?((x)+boxsize):(x)))\n#else\n#define NEAREST(x) (x)\n#endif\n\n/*! Structure for communication during the density computation. Holds data that is sent to other processors.\n */\nstatic struct SOdens_in\n{\n MyDouble Pos[3];\n double R200;\n int NodeList[NODELISTLENGTH];\n}\n *SOdensIn, *SOdensGet;\n\n\nstatic struct SOdens_out\n{\n double Mass;\n#ifdef SO_VEL_DISPERSIONS\n double Vx200, Vy200, Vz200, Disp200;\n#endif\n}\n *SOdensResult, *SOdensOut;\n\n\nstatic double *R200, *M200;\n\n#ifdef SO_VEL_DISPERSIONS\nstatic double *Vx200, *Vy200, *Vz200, *Disp200;\n#endif\n\nvoid subfind_overdensity(void)\n{\n long long ntot;\n int i, j, ndone, ndone_flag, npleft, dummy, rep, iter;\n MyFloat *Left, *Right;\n char *Todo;\n int ngrp, sendTask, recvTask, place, nexport, nimport;\n double t0, t1, rguess, overdensity, Deltas[3], rhoback, z, omegaz, x, DeltaMean200, DeltaCrit200,\n DeltaTopHat;\n\n\n /* allocate buffers to arrange communication */\n\n Ngblist = (int *) mymalloc(NumPart * sizeof(int));\n All.BunchSize =\n (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +\n\t\t\t\t\t sizeof(struct SOdens_in) + sizeof(struct SOdens_out) +\n\t\t\t\t\t sizemax(sizeof(struct SOdens_in), sizeof(struct SOdens_out))));\n DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));\n DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));\n\n\n Left = (MyFloat *) mymalloc(sizeof(MyFloat) * Ngroups);\n Right = (MyFloat *) mymalloc(sizeof(MyFloat) * Ngroups);\n R200 = (double *) mymalloc(sizeof(double) * Ngroups);\n M200 = (double *) mymalloc(sizeof(double) * Ngroups);\n#ifdef SO_VEL_DISPERSIONS\n Vx200 = (double *) mymalloc(sizeof(double) * Ngroups);\n Vy200 = (double *) mymalloc(sizeof(double) * Ngroups);\n Vz200 = (double *) mymalloc(sizeof(double) * Ngroups);\n Disp200 = (double *) mymalloc(sizeof(double) * Ngroups);\n#endif\n\n Todo = mymalloc(sizeof(char) * Ngroups);\n\n z = 1 / All.Time - 1;\n\n rhoback = 3 * All.Omega0 * All.Hubble * All.Hubble / (8 * M_PI * All.G);\n\n omegaz =\n All.Omega0 * pow(1 + z,\n\t\t 3) / (All.Omega0 * pow(1 + z, 3) + (1 - All.Omega0 - All.OmegaLambda) * pow(1 + z,\n\t\t\t\t\t\t\t\t\t\t\t\t 2) +\n\t\t\t All.OmegaLambda);\n\n DeltaMean200 = 200.0;\n DeltaCrit200 = 200.0 / omegaz;\n\n x = omegaz - 1;\n DeltaTopHat = 18 * M_PI * M_PI + 82 * x - 39 * x * x;\n DeltaTopHat /= omegaz;\n\n Deltas[0] = DeltaMean200;\t/* standard fixed overdensity with respect to background */\n Deltas[1] = DeltaTopHat;\t/* tophat overdensity with respect to background */\n Deltas[2] = DeltaCrit200;\t/* overdensity of 200 relative to critical, expressed relative to background density */\n\n\n for(rep = 0; rep < 3; rep++)\t/* repeat for all three overdensity values */\n {\n for(i = 0; i < Ngroups; i++)\n\t{\n\t if(Group[i].Nsubs > 0)\n\t {\n\t rguess = pow(All.G * Group[i].Mass / (100 * All.Hubble * All.Hubble), 1.0 / 3);\n\n\t Right[i] = 3 * rguess;\n\t Left[i] = 0;\n\n\t Todo[i] = 1;\n\t }\n\t else\n\t {\n\t Todo[i] = 0;\n\t }\n\t}\n\n iter = 0;\n\n /* we will repeat the whole thing for those groups where we didn't converge to a SO radius yet */\n do\n\t{\n\t t0 = second();\n\n\t i = 0;\t\t/* begin with this index */\n\n\t do\n\t {\n\t for(j = 0; j < NTask; j++)\n\t\t{\n\t\t Send_count[j] = 0;\n\t\t Exportflag[j] = -1;\n\t\t}\n\n\t /* do local particles and prepare export list */\n\n\t for(nexport = 0; i < Ngroups; i++)\n\t\t{\n\t\t if(Todo[i])\n\t\t {\n\t\t R200[i] = 0.5 * (Left[i] + Right[i]);\n\t\t if(subfind_overdensity_evaluate(i, 0, &nexport, Send_count) < 0)\n\t\t\tbreak;\n\t\t }\n\t\t}\n\n\t qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n\n\t MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);\n\n\t for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)\n\t\t{\n\t\t Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];\n\t\t nimport += Recv_count[j];\n\n\t\t if(j > 0)\n\t\t {\n\t\t Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\t\t Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];\n\t\t }\n\t\t}\n\n\t SOdensGet = (struct SOdens_in *) mymalloc(nimport * sizeof(struct SOdens_in));\n\t SOdensIn = (struct SOdens_in *) mymalloc(nexport * sizeof(struct SOdens_in));\n\n\t /* prepare particle data for export */\n\t for(j = 0; j < nexport; j++)\n\t\t{\n\t\t place = DataIndexTable[j].Index;\n\n\t\t SOdensIn[j].Pos[0] = Group[place].Pos[0];\n\t\t SOdensIn[j].Pos[1] = Group[place].Pos[1];\n\t\t SOdensIn[j].Pos[2] = Group[place].Pos[2];\n\t\t SOdensIn[j].R200 = R200[place];\n\n\t\t memcpy(SOdensIn[j].NodeList,\n\t\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\t\t}\n\n\t /* exchange data */\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t\t{\n\t\t sendTask = ThisTask;\n\t\t recvTask = ThisTask ^ ngrp;\n\n\t\t if(recvTask < NTask)\n\t\t {\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t\t{\n\t\t\t /* get the data */\n\t\t\t MPI_Sendrecv(&SOdensIn[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A,\n\t\t\t\t &SOdensGet[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t\t}\n\t\t }\n\t\t}\n\n\t myfree(SOdensIn);\n\t SOdensResult = (struct SOdens_out *) mymalloc(nimport * sizeof(struct SOdens_out));\n\t SOdensOut = (struct SOdens_out *) mymalloc(nexport * sizeof(struct SOdens_out));\n\n\n\t /* now do the locations that were sent to us */\n\t for(j = 0; j < nimport; j++)\n\t\tsubfind_overdensity_evaluate(j, 1, &dummy, &dummy);\n\n\t if(i >= Ngroups)\n\t\tndone_flag = 1;\n\t else\n\t\tndone_flag = 0;\n\n\t MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n\t /* get the result */\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t\t{\n\t\t sendTask = ThisTask;\n\t\t recvTask = ThisTask ^ ngrp;\n\t\t if(recvTask < NTask)\n\t\t {\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t\t{\n\t\t\t /* send the results */\n\t\t\t MPI_Sendrecv(&SOdensResult[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct SOdens_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B,\n\t\t\t\t &SOdensOut[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct SOdens_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t\t}\n\t\t }\n\t\t}\n\n\t /* add the result to the local particles */\n\t for(j = 0; j < nexport; j++)\n\t\t{\n\t\t place = DataIndexTable[j].Index;\n\n\t\t M200[place] += SOdensOut[j].Mass;\n\t\t}\n\n\t myfree(SOdensOut);\n\t myfree(SOdensResult);\n\t myfree(SOdensGet);\n\t }\n\t while(ndone < NTask);\n\n\n\t /* do final operations on results */\n\t for(i = 0, npleft = 0; i < Ngroups; i++)\n\t {\n\t if(Todo[i])\n\t\t{\n\t\t overdensity = M200[i] / (4.0 * M_PI / 3.0 * R200[i] * R200[i] * R200[i]) / rhoback;\n\n\t\t if((Right[i] - Left[i]) > 1.0e-4 * Left[i])\n\t\t {\n\t\t /* need to redo this group */\n\t\t npleft++;\n\n\t\t if(overdensity > Deltas[rep])\n\t\t\tLeft[i] = R200[i];\n\t\t else\n\t\t\tRight[i] = R200[i];\n\n\t\t if(iter >= MAXITER - 10)\n\t\t\t{\n\t\t\t printf\n\t\t\t (\"gr=%d task=%d R200=%g Left=%g Right=%g Menclosed=%g Right-Left=%g\\n pos=(%g|%g|%g)\\n\",\n\t\t\t i, ThisTask, R200[i], Left[i], Right[i],\n\t\t\t M200[i], Right[i] - Left[i], Group[i].Pos[0], Group[i].Pos[1], Group[i].Pos[2]);\n\t\t\t fflush(stdout);\n\t\t\t}\n\t\t }\n\t\t else\n\t\t Todo[i] = 0;\n\t\t}\n\t }\n\n\t sumup_large_ints(1, &npleft, &ntot);\n\n\t t1 = second();\n\n\t if(ntot > 0)\n\t {\n\t iter++;\n\n\t if(iter > 0 && ThisTask == 0)\n\t\t{\n\t\t printf(\"SO iteration %d: need to repeat for %d%09d particles. (took %g sec)\\n\", iter,\n\t\t\t (int) (ntot / 1000000000), (int) (ntot % 1000000000), timediff(t0, t1));\n\t\t fflush(stdout);\n\t\t}\n\n\t if(iter > MAXITER)\n\t\t{\n\t\t printf(\"failed to converge in neighbour iteration in density()\\n\");\n\t\t fflush(stdout);\n\t\t endrun(1155);\n\t\t}\n\t }\n\t}\n while(ntot > 0);\n\n\n#ifdef SO_VEL_DISPERSIONS\n i = 0;\t\t\t/* begin with this index */\n do\n\t{\n\t for(j = 0; j < NTask; j++)\n\t {\n\t Send_count[j] = 0;\n\t Exportflag[j] = -1;\n\t }\n\n\t /* do local particles and prepare export list */\n\n\t for(nexport = 0; i < Ngroups; i++)\n\t {\n\t if(subfind_overdensity_evaluate_dispersion(i, 0, &nexport, Send_count) < 0)\n\t\tbreak;\n\t }\n\n\t qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n\n\t MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);\n\n\t for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)\n\t {\n\t Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];\n\t nimport += Recv_count[j];\n\n\t if(j > 0)\n\t\t{\n\t\t Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\t\t Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];\n\t\t}\n\t }\n\n\t SOdensGet = (struct SOdens_in *) mymalloc(nimport * sizeof(struct SOdens_in));\n\t SOdensIn = (struct SOdens_in *) mymalloc(nexport * sizeof(struct SOdens_in));\n\n\t /* prepare particle data for export */\n\t for(j = 0; j < nexport; j++)\n\t {\n\t place = DataIndexTable[j].Index;\n\n\t SOdensIn[j].Pos[0] = Group[place].Pos[0];\n\t SOdensIn[j].Pos[1] = Group[place].Pos[1];\n\t SOdensIn[j].Pos[2] = Group[place].Pos[2];\n\t SOdensIn[j].R200 = R200[place];\n\n\t memcpy(SOdensIn[j].NodeList,\n\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\t }\n\n\t /* exchange data */\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t {\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t {\n\t\t /* get the data */\n\t\t MPI_Sendrecv(&SOdensIn[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A,\n\t\t\t\t &SOdensGet[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct SOdens_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t }\n\t\t}\n\t }\n\n\t myfree(SOdensIn);\n\t SOdensResult = (struct SOdens_out *) mymalloc(nimport * sizeof(struct SOdens_out));\n\t SOdensOut = (struct SOdens_out *) mymalloc(nexport * sizeof(struct SOdens_out));\n\n\t /* now do the locations that were sent to us */\n\t for(j = 0; j < nimport; j++)\n\t subfind_overdensity_evaluate_dispersion(j, 1, &dummy, &dummy);\n\n\t if(i >= Ngroups)\n\t ndone_flag = 1;\n\t else\n\t ndone_flag = 0;\n\n\t MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n\t /* get the result */\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t {\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t {\n\t\t /* send the results */\n\t\t MPI_Sendrecv(&SOdensResult[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct SOdens_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B,\n\t\t\t\t &SOdensOut[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct SOdens_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t }\n\t\t}\n\t }\n\n\t /* add the result to the local particles */\n\t for(j = 0; j < nexport; j++)\n\t {\n\t place = DataIndexTable[j].Index;\n\n\t Vx200[place] += SOdensOut[j].Vx200;\n\t Vy200[place] += SOdensOut[j].Vy200;\n\t Vz200[place] += SOdensOut[j].Vz200;\n\t Disp200[place] += SOdensOut[j].Disp200;\n\t }\n\n\t myfree(SOdensOut);\n\t myfree(SOdensResult);\n\t myfree(SOdensGet);\n\t}\n while(ndone < NTask);\n#endif\n\n for(i = 0; i < Ngroups; i++)\n\t{\n\t if(Group[i].Nsubs > 0)\n\t {\n\t overdensity = M200[i] / (4.0 * M_PI / 3.0 * R200[i] * R200[i] * R200[i]) / rhoback;\n\n\t if((overdensity - Deltas[rep]) > 0.1 * Deltas[rep])\n\t\t{\n\t\t R200[i] = M200[i] = 0;\n\t\t}\n\t else if(M200[i] < 5 * Group[i].Mass / Group[i].Len)\n\t\t{\n\t\t R200[i] = M200[i] = 0;\n\t\t}\n\t }\n\t else\n\t R200[i] = M200[i] = 0;\n\n\t switch (rep)\n\t {\n\t case 0:\n\t Group[i].M_Mean200 = M200[i];\n\t Group[i].R_Mean200 = R200[i];\n\t break;\n\t case 1:\n\t Group[i].M_TopHat200 = M200[i];\n\t Group[i].R_TopHat200 = R200[i];\n\t break;\n\t case 2:\n\t Group[i].M_Crit200 = M200[i];\n\t Group[i].R_Crit200 = R200[i];\n\t break;\n\t }\n\n#ifdef SO_VEL_DISPERSIONS\n\t if(R200[i] > 0 && M200[i] > 0)\n\t {\n\t Vx200[i] /= M200[i];\n\t Vy200[i] /= M200[i];\n\t Vz200[i] /= M200[i];\n\t Disp200[i] /= M200[i];\n\t Disp200[i] -= (Vx200[i] * Vx200[i] + Vy200[i] * Vy200[i] + Vz200[i] * Vz200[i]);\n\t Disp200[i] = sqrt(Disp200[i] / 3);\t/* convert to 1D velocity dispersion */\n\t }\n\t else\n\t {\n\t Disp200[i] = 0;\n\t }\n\n\t switch (rep)\n\t {\n\t case 0:\n\t Group[i].VelDisp_Mean200 = Disp200[i];\n\t break;\n\t case 1:\n\t Group[i].VelDisp_TopHat200 = Disp200[i];\n\t break;\n\t case 2:\n\t Group[i].VelDisp_Crit200 = Disp200[i];\n\t break;\n\t }\n#endif\n\t}\n }\n\n myfree(Todo);\n#ifdef SO_VEL_DISPERSIONS\n myfree(Disp200);\n myfree(Vz200);\n myfree(Vy200);\n myfree(Vx200);\n#endif\n myfree(M200);\n myfree(R200);\n myfree(Right);\n myfree(Left);\n\n myfree(DataNodeList);\n myfree(DataIndexTable);\n myfree(Ngblist);\n}\n\n\n/*! This function represents the core of the SPH density computation. The\n * target particle may either be local, or reside in the communication\n * buffer.\n */\nint subfind_overdensity_evaluate(int target, int mode, int *nexport, int *nsend_local)\n{\n int startnode, listindex = 0;\n double h, mass, massret;\n MyDouble *pos;\n\n\n if(mode == 0)\n {\n pos = Group[target].Pos;\n h = R200[target];\n }\n else\n {\n pos = SOdensGet[target].Pos;\n h = SOdensGet[target].R200;\n }\n\n if(mode == 0)\n {\n startnode = All.MaxPart;\t/* root node */\n }\n else\n {\n startnode = SOdensGet[target].NodeList[0];\n startnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n }\n\n mass = 0;\n\n while(startnode >= 0)\n {\n while(startnode >= 0)\n\t{\n\t massret = subfind_ovderdens_treefind(pos, h, target, &startnode, mode, nexport, nsend_local);\n\n\t if(massret < 0)\n\t return -1;\n\n\t mass += massret;\n\t}\n\n if(mode == 1)\n\t{\n\t listindex++;\n\t if(listindex < NODELISTLENGTH)\n\t {\n\t startnode = SOdensGet[target].NodeList[listindex];\n\t if(startnode >= 0)\n\t\tstartnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n\t }\n\t}\n }\n\n if(mode == 0)\n M200[target] = mass;\n else\n SOdensResult[target].Mass = mass;\n\n return 0;\n}\n\n\ndouble subfind_ovderdens_treefind(MyDouble searchcenter[3], MyFloat hsml, int target, int *startnode,\n\t\t\t\t int mode, int *nexport, int *nsend_local)\n{\n int no, p, task, nexport_save;\n struct NODE *current;\n double mass;\n MyDouble dx, dy, dz, dist, r2;\n\n#define FACT2 0.86602540\n#ifdef PERIODIC\n MyDouble xtmp;\n#endif\n nexport_save = *nexport;\n\n mass = 0;\n no = *startnode;\n\n while(no >= 0)\n {\n if(no < All.MaxPart)\t/* single particle */\n\t{\n\t p = no;\n\t no = Nextnode[no];\n\n\t dist = hsml;\n\t dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t if(dx * dx + dy * dy + dz * dz > dist * dist)\n\t continue;\n\n\t mass += P[p].Mass;\n\t}\n else\n\t{\n\t if(no >= All.MaxPart + MaxNodes)\t/* pseudo particle */\n\t {\n\t if(mode == 1)\n\t\tendrun(12312);\n\n\t if(mode == 0)\n\t\t{\n\t\t if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target)\n\t\t {\n\t\t Exportflag[task] = target;\n\t\t Exportnodecount[task] = NODELISTLENGTH;\n\t\t }\n\n\t\t if(Exportnodecount[task] == NODELISTLENGTH)\n\t\t {\n\t\t if(*nexport >= All.BunchSize)\n\t\t\t{\n\t\t\t *nexport = nexport_save;\n\t\t\t if(nexport_save == 0)\n\t\t\t endrun(13005);\t/* in this case, the buffer is too small to process even a single particle */\n\t\t\t for(task = 0; task < NTask; task++)\n\t\t\t nsend_local[task] = 0;\n\t\t\t for(no = 0; no < nexport_save; no++)\n\t\t\t nsend_local[DataIndexTable[no].Task]++;\n\t\t\t return -1;\n\t\t\t}\n\t\t Exportnodecount[task] = 0;\n\t\t Exportindex[task] = *nexport;\n\t\t DataIndexTable[*nexport].Task = task;\n\t\t DataIndexTable[*nexport].Index = target;\n\t\t DataIndexTable[*nexport].IndexGet = *nexport;\n\t\t *nexport = *nexport + 1;\n\t\t nsend_local[task]++;\n\t\t }\n\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] =\n\t\t DomainNodeIndex[no - (All.MaxPart + MaxNodes)];\n\n\t\t if(Exportnodecount[task] < NODELISTLENGTH)\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1;\n\t\t}\n\n\t no = Nextnode[no - MaxNodes];\n\t continue;\n\t }\n\n\t current = &Nodes[no];\n\n\t if(mode == 1)\n\t {\n\t if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL))\t/* we reached a top-level node again, which means that we are done with the branch */\n\t\t{\n\t\t *startnode = -1;\n\t\t return mass;\n\t\t}\n\t }\n\n\t no = current->u.d.sibling;\t/* in case the node can be discarded */\n\t dist = hsml + 0.5 * current->len;\n\t dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t /* now test against the minimal sphere enclosing everything */\n\t dist += FACT1 * current->len;\n\t if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist)\n\t continue;\n\n\t if((current->u.d.bitflags & ((1 << BITFLAG_TOPLEVEL) + (1 << BITFLAG_DEPENDS_ON_LOCAL_MASS))) == 0)\t/* only use fully local nodes */\n\t {\n\t /* test whether the node is contained within the sphere */\n\t dist = hsml - FACT2 * current->len;\n\t if(dist > 0)\n\t\tif(r2 < dist * dist)\n\t\t {\n\t\t mass += current->u.d.mass;\n\t\t continue;\n\t\t }\n\t }\n\n\t no = current->u.d.nextnode;\t/* ok, we need to open the node */\n\t}\n }\n\n *startnode = -1;\n return mass;\n}\n\n\n\n#ifdef SO_VEL_DISPERSIONS\n\nint subfind_overdensity_evaluate_dispersion(int target, int mode, int *nexport, int *nsend_local)\n{\n int ngb, n, j, startnode, listindex = 0;\n double h, vx, vy, vz, v2, vvx, vvy, vvz;\n MyDouble *pos;\n double boxsize, boxhalf, vel_to_peculiar, H_of_a;\n\n boxsize = All.BoxSize;\n boxhalf = 0.5 * All.BoxSize;\n\n H_of_a = hubble_function(All.Time);\n vel_to_peculiar = 1.0 / All.Time;\n\n if(mode == 0)\n {\n pos = Group[target].Pos;\n h = R200[target];\n }\n else\n {\n pos = SOdensGet[target].Pos;\n h = SOdensGet[target].R200;\n }\n\n if(mode == 0)\n {\n startnode = All.MaxPart;\t/* root node */\n }\n else\n {\n startnode = SOdensGet[target].NodeList[0];\n startnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n }\n\n vx = vy = vz = v2 = 0;\n\n while(startnode >= 0)\n {\n while(startnode >= 0)\n\t{\n\t ngb = subfind_ovderdens_treefind_dispersion(pos, h, target, &startnode, mode, nexport, nsend_local);\n\n\t if(ngb < 0)\n\t return -1;\n\n\t for(n = 0; n < ngb; n++)\n\t {\n\t j = Ngblist[n];\n\n\t vvx = vel_to_peculiar * P[j].Vel[0] + H_of_a * All.Time * NEAREST(P[j].Pos[0] - pos[0]);\n\t vvy = vel_to_peculiar * P[j].Vel[1] + H_of_a * All.Time * NEAREST(P[j].Pos[1] - pos[1]);\n\t vvz = vel_to_peculiar * P[j].Vel[2] + H_of_a * All.Time * NEAREST(P[j].Pos[2] - pos[2]);\n\n\t vx += P[j].Mass * vvx;\n\t vy += P[j].Mass * vvy;\n\t vz += P[j].Mass * vvz;\n\n\t v2 += P[j].Mass * (vvx * vvx + vvy * vvy + vvz * vvz);\n\t }\n\t}\n\n if(mode == 1)\n\t{\n\t listindex++;\n\t if(listindex < NODELISTLENGTH)\n\t {\n\t startnode = SOdensGet[target].NodeList[listindex];\n\t if(startnode >= 0)\n\t\tstartnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n\t }\n\t}\n }\n\n if(mode == 0)\n {\n Disp200[target] = v2;\n Vx200[target] = vx;\n Vy200[target] = vy;\n Vz200[target] = vz;\n }\n else\n {\n SOdensResult[target].Disp200 = v2;\n SOdensResult[target].Vx200 = vx;\n SOdensResult[target].Vy200 = vy;\n SOdensResult[target].Vz200 = vz;\n }\n\n return 0;\n}\n\nint subfind_ovderdens_treefind_dispersion(MyDouble searchcenter[3], MyFloat hsml, int target, int *startnode,\n\t\t\t\t\t int mode, int *nexport, int *nsend_local)\n{\n int no, p, task, nexport_save, numngb;\n struct NODE *current;\n MyDouble dx, dy, dz, dist, r2;\n\n#define FACT2 0.86602540\n#ifdef PERIODIC\n MyDouble xtmp;\n#endif\n nexport_save = *nexport;\n\n numngb = 0;\n no = *startnode;\n\n while(no >= 0)\n {\n if(no < All.MaxPart)\t/* single particle */\n\t{\n\t p = no;\n\t no = Nextnode[no];\n\n\t dist = hsml;\n\t dx = NGB_PERIODIC_LONG_X(P[p].Pos[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(P[p].Pos[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(P[p].Pos[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t if(dx * dx + dy * dy + dz * dz > dist * dist)\n\t continue;\n\n\t Ngblist[numngb++] = p;\n\t}\n else\n\t{\n\t if(no >= All.MaxPart + MaxNodes)\t/* pseudo particle */\n\t {\n\t if(mode == 1)\n\t\tendrun(12312);\n\n\t if(mode == 0)\n\t\t{\n\t\t if(Exportflag[task = DomainTask[no - (All.MaxPart + MaxNodes)]] != target)\n\t\t {\n\t\t Exportflag[task] = target;\n\t\t Exportnodecount[task] = NODELISTLENGTH;\n\t\t }\n\n\t\t if(Exportnodecount[task] == NODELISTLENGTH)\n\t\t {\n\t\t if(*nexport >= All.BunchSize)\n\t\t\t{\n\t\t\t *nexport = nexport_save;\n\t\t\t if(nexport_save == 0)\n\t\t\t endrun(13005);\t/* in this case, the buffer is too small to process even a single particle */\n\t\t\t for(task = 0; task < NTask; task++)\n\t\t\t nsend_local[task] = 0;\n\t\t\t for(no = 0; no < nexport_save; no++)\n\t\t\t nsend_local[DataIndexTable[no].Task]++;\n\t\t\t return -1;\n\t\t\t}\n\t\t Exportnodecount[task] = 0;\n\t\t Exportindex[task] = *nexport;\n\t\t DataIndexTable[*nexport].Task = task;\n\t\t DataIndexTable[*nexport].Index = target;\n\t\t DataIndexTable[*nexport].IndexGet = *nexport;\n\t\t *nexport = *nexport + 1;\n\t\t nsend_local[task]++;\n\t\t }\n\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]++] =\n\t\t DomainNodeIndex[no - (All.MaxPart + MaxNodes)];\n\n\t\t if(Exportnodecount[task] < NODELISTLENGTH)\n\t\t DataNodeList[Exportindex[task]].NodeList[Exportnodecount[task]] = -1;\n\t\t}\n\n\t no = Nextnode[no - MaxNodes];\n\t continue;\n\t }\n\n\t current = &Nodes[no];\n\n\t if(mode == 1)\n\t {\n\t if(current->u.d.bitflags & (1 << BITFLAG_TOPLEVEL))\t/* we reached a top-level node again, which means that we are done with the branch */\n\t\t{\n\t\t *startnode = -1;\n\t\t return numngb;\n\t\t}\n\t }\n\n\t no = current->u.d.sibling;\t/* in case the node can be discarded */\n\t dist = hsml + 0.5 * current->len;\n\t dx = NGB_PERIODIC_LONG_X(current->center[0] - searchcenter[0]);\n\t if(dx > dist)\n\t continue;\n\t dy = NGB_PERIODIC_LONG_Y(current->center[1] - searchcenter[1]);\n\t if(dy > dist)\n\t continue;\n\t dz = NGB_PERIODIC_LONG_Z(current->center[2] - searchcenter[2]);\n\t if(dz > dist)\n\t continue;\n\t /* now test against the minimal sphere enclosing everything */\n\t dist += FACT1 * current->len;\n\t if((r2 = (dx * dx + dy * dy + dz * dz)) > dist * dist)\n\t continue;\n\n\t no = current->u.d.nextnode;\t/* ok, we need to open the node */\n\t}\n }\n\n *startnode = -1;\n return numngb;\n}\n\n#endif\n\n\n\n\n#endif\n", "meta": {"hexsha": "04db7eb203a982210b9d2a34ef9c5f54c9baab03", "size": 23874, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_so.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/subfind_so.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/subfind_so.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.1041009464, "max_line_length": 144, "alphanum_fraction": 0.5880455726, "num_tokens": 7610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2954263550278007}} {"text": "/*\n * vbHmmTs.c\n * Model-specific core functions for VB-HMM-TS.\n *\n * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN\n * Copyright 2011-2015\n * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.\n * All rights reserved.\n *\n * Ver. 1.1.0\n * Last modified on 2015.09.17\n */\n\n#include \"vbHmmTs.h\"\n#include \n#include \n#include \n#include \"rand.h\"\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n//// Uncomment one/both of the following defenitions to activate constraint on I or/and K.\n//#define INTENSITY_CAP\n//#define TRANSITION_RATE_CAP\n#ifdef INTENSITY_CAP\n#define maxIntensityRatio 10.0\n#endif\n#ifdef TRANSITION_RATE_CAP\n#define minPhotonNumPerState 10.0\n#endif\n\n#define MAX(a,b) ((a)>(b)?(a):(b))\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n//static int isGlobalAnalysis = 0;\n\nvoid setFunctions_ts(){\n commonFunctions funcs;\n funcs.newModelParameters = newModelParameters_ts;\n funcs.freeModelParameters = freeModelParameters_ts;\n funcs.newModelStats = newModelStats_ts;\n funcs.freeModelStats = freeModelStats_ts;\n funcs.initializeVbHmm = initializeVbHmm_ts;\n funcs.pTilde_z1 = pTilde_z1_ts;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1_ts;\n funcs.pTilde_xn_zn = pTilde_xn_zn_ts;\n funcs.calcStatsVars = calcStatsVars_ts;\n funcs.maximization = maximization_ts;\n funcs.varLowerBound = varLowerBound_ts;\n funcs.reorderParameters = reorderParameters_ts;\n funcs.outputResults = outputResults_ts;\n setFunctions( funcs );\n}\n\n//void setGFunctions_ts(){\n// gCommonFunctions funcs;\n// funcs.newModelParameters = newModelParameters_ts;\n// funcs.freeModelParameters = freeModelParameters_ts;\n// funcs.newModelStats = newModelStats_ts;\n// funcs.freeModelStats = freeModelStats_ts;\n// funcs.newModelStatsG = newModelStatsG_ts;\n// funcs.freeModelStatsG = freeModelStatsG_ts;\n// funcs.initializeVbHmmG = initializeVbHmmG_ts;\n// funcs.pTilde_z1 = pTilde_z1_ts;\n// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_ts;\n// funcs.pTilde_xn_zn = pTilde_xn_zn_ts;\n// funcs.calcStatsVarsG = calcStatsVarsG_ts;\n// funcs.maximizationG = maximizationG_ts;\n// funcs.varLowerBoundG = varLowerBoundG_ts;\n// funcs.reorderParametersG = reorderParametersG_ts;\n// funcs.outputResultsG = outputResultsG_ts;\n// setGFunctions( funcs );\n// isGlobalAnalysis = 1;\n//}\n\n\nvoid outputResults_ts( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n outputTsResults( xn, gv, iv, logFP );\n}\n\n//void outputResultsG_ts( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n// outputTsResultsG( xns, gv, ivs, logFP );\n//}\n\n\nvoid *newModelParameters_ts( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n int i;\n tsParameters *p = (void*)malloc( sizeof(tsParameters) );\n \n p->uPiArr = (double*)malloc( sNo * sizeof(double) );\n p->sumUPi = 0.0;\n // hyperparameter for p( k(i,j) ) (i != j)\n p->uKMat = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->uKMat[i] = (double*)malloc( sNo * sizeof(double) );\n }\n p->sumUKArr = (double*)malloc( sNo * sizeof(double) );\n // hyperparameter for p( I(k) )\n p->aIArr = (double*)malloc( sNo * sizeof(double) );\n p->bIArr = (double*)malloc( sNo * sizeof(double) );\n \n p->avgPi = (double *)malloc( sNo * sizeof(double) );\n p->avgLnPi = (double *)malloc( sNo * sizeof(double) );\n p->avgI = (double *)malloc( sNo * sizeof(double) );\n p->avgLnI = (double *)malloc( sNo * sizeof(double) );\n p->avgK = (double **)malloc( sNo * sizeof(double*) );\n p->avgLnK = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->avgK[i] = (double *)malloc( sNo * sizeof(double) );\n p->avgLnK[i] = (double *)malloc( sNo * sizeof(double) );\n }\n p->avgLnKI = (double *)malloc( sNo * sizeof(double) );\n \n return p;\n}\n\nvoid freeModelParameters_ts( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n tsParameters *gp = *p;\n int i;\n \n free( gp->uPiArr );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->uKMat[i] );\n }\n free( gp->uKMat );\n free( gp->sumUKArr );\n free( gp->aIArr );\n free( gp->bIArr );\n \n free( gp->avgPi );\n free( gp->avgLnPi );\n free( gp->avgI );\n free( gp->avgLnI );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->avgK[i] );\n free( gp->avgLnK[i] );\n }\n free( gp->avgK );\n free( gp->avgLnK );\n free( gp->avgLnKI );\n \n free( *p );\n *p = NULL;\n}\n\n\nvoid *newModelStats_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n tsStats *s = (tsStats*)malloc( sizeof(tsStats) );\n \n int i;\n s->Ni = (double *)malloc( sNo * sizeof(double) );\n s->Ti = (double *)malloc( sNo * sizeof(double) );\n s->Nii = (double *)malloc( sNo * sizeof(double) );\n s->Nij = (double *)malloc( sNo * sizeof(double) );\n s->Mij = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s->Mij[i] = (double *)malloc( sNo * sizeof(double) ); }\n \n return s;\n \n// } else {\n// \n// return NULL;\n// \n// }\n}\n\nvoid freeModelStats_ts( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n tsStats *gs = *s;\n int i;\n free( gs->Ni );\n free( gs->Ti );\n free( gs->Nii );\n free( gs->Nij );\n for( i = 0 ; i < sNo ; i++ )\n { free( gs->Mij[i] ); }\n free( gs->Mij );\n \n free( gs );\n *s = NULL;\n// }\n}\n\n//void *newModelStatsG_ts( xns, gv, ivs)\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// int sNo = gv->sNo;\n// tsGlobalStats *gs = (tsGlobalStats*)malloc( sizeof(tsGlobalStats) );\n// \n// return gs;\n//}\n\n//void freeModelStatsG_ts( gs, xns, gv, ivs )\n//void **gs;\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// \n// free( *gs );\n// *gs = NULL;\n//}\n\n\nvoid initializeVbHmm_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsData *d = xn->data;\n int sNo = gv->sNo;\n tsParameters *p = gv->params;\n \n int i, j;\n\n // hyperparameter for p( pi(k) )\n p->sumUPi = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n p->uPiArr[i] = 1.0;\n p->sumUPi += p->uPiArr[i];\n }\n\n // hyperparameter for p( k(i,j) ) (i != j)\n for( i = 0 ; i < sNo ; i++ ){\n p->sumUKArr[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n p->uKMat[i][j] = 1.0;\n if( j != i ){\n p->sumUKArr[i] += p->uKMat[i][j];\n }\n }\n }\n\n double meanI = (double)xn->N / d->T;\n\n // hyperparameter for p( I(k) )\n for( i = 0 ; i < sNo ; i++ ){\n p->aIArr[i] = 1.0;\n p->bIArr[i] = 1.0 / meanI;\n }\n \n initialize_indVars_ts( xn, gv, iv );\n \n calcStatsVars_ts( xn, gv, iv );\n maximization_ts( xn, gv, iv );\n}\n\n//void initializeVbHmmG_ts( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid initialize_indVars_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n \n int i;\n size_t n;\n double sumPar;\n for( n = 0 ; n < dLen ; n++ ){\n sumPar = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] = enoise(1.0) + 1.0;\n sumPar += gmMat[n][i];\n }\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] /= sumPar;\n }\n }\n}\n\n\nxnDataSet *newXnDataSet_ts( filename )\nconst char *filename;\n{\n xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );\n xn->name = (char*)malloc( strlen(filename) + 2 );\n strncpy( xn->name, filename, strlen(filename)+1 );\n xn->data = (tsData*)malloc( sizeof(tsData) );\n tsData *d = (tsData*)xn->data;\n d->T = 0.0;\n d->dt = NULL;\n d->time = NULL;\n return xn;\n}\n\nvoid freeXnDataSet_ts( xn )\nxnDataSet **xn;\n{\n tsData *d = (tsData*)(*xn)->data;\n free( d->dt );\n free( d->time );\n free( (*xn)->data );\n free( (*xn)->name );\n free( *xn );\n *xn = NULL;\n}\n\n\ndouble pTilde_z1_ts( i, params )\nint i;\nvoid *params;\n{\n tsParameters *p = (tsParameters*)params;\n return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1_ts( i, j, params )\nint i, j;\nvoid *params;\n{\n tsParameters *p = (tsParameters*)params;\n if( i == j ){\n return exp( p->avgLnI[i] - p->avgLnKI[i] );\n } else {\n return exp( p->avgLnK[i][i] + p->avgLnK[i][j] - p->avgLnKI[i] );\n }\n}\n\ndouble pTilde_xn_zn_ts( xnWv, n, i, params )\nxnDataSet *xnWv;\nsize_t n;\nint i;\nvoid *params;\n{\n tsParameters *p = (tsParameters*)params;\n tsData *d = (tsData*)xnWv->data;\n return exp( p->avgLnI[i] - p->avgI[i] * d->dt[n] );\n}\n\n\nvoid calcStatsVars_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsData *d = (tsData*)xn->data;\n tsStats *s = (tsStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *Ni = s->Ni, *Ti = s->Ti;\n double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;\n size_t n;\n int i, j;\n\n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] = 1e-10;\n Ti[i] = 1e-10;\n Nii[i] = 0.0;\n Nij[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n Mij[i][j] = 1e-10;\n }\n }\n for( n = 0 ; n < dLen ; n++ ){\n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] += gmMat[n][i];\n Ti[i] += gmMat[n][i] * d->dt[n];\n Nii[i] += xiMat[n][i][i];\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n Mij[i][j] += xiMat[n][i][j];\n Nij[i] += xiMat[n][i][j];\n }\n }\n }\n }\n for( i = 0 ; i < sNo ; i++ ){\n Nii[i] = MAX( Nii[i], 1.0 );\n Nij[i] = MAX( Nij[i], 1.0 );\n }\n}\n\n//void calcStatsVarsG_ts( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid maximization_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsParameters *p = (tsParameters*)gv->params;\n tsStats *s = (tsStats*)iv->stats;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK, **avgLnK = p->avgLnK;\n double *avgLnKI = p->avgLnKI, *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;\n double *Ni = s->Ni, *Ti = s->Ti;\n double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;\n int i, j;\n\n for( i = 0 ; i < sNo ; i++ ){\n avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );\n avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );\n\n avgK[i][i] = (Ni[i] + aIArr[i]) * Nij[i] / (Nii[i] - 1.0) / (Ti[i] + bIArr[i]);\n avgLnK[i][i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nij[i]);\n avgLnK[i][i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);\n\n avgI[i] = (Ni[i] + aIArr[i]) / (Ti[i] + bIArr[i]);\n avgLnI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) - log(Ti[i] + bIArr[i]);\n \n avgLnKI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nii[i] + Nij[i]);\n avgLnKI[i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);\n\n#ifdef INTENSITY_CAP\n double meanI = (double)xnWv->N / xnWv->T;\n avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );\n avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );\n#endif\n#ifdef TRANSITION_RATE_CAP\n avgK[i][i] = MIN( avgK[i][i], avgI[i]/minPhotonNumPerState );\n avgLnK[i][i] = MIN( avgLnK[i][i], avgLnI[i] - log(minPhotonNumPerState) );\n avgLnKI[i] = MIN( avgLnKI[i], avgLnI[i] + log(1.0 + 1.0/minPhotonNumPerState) );\n#endif\n \n for( j = 0 ; j < sNo ; j++ ){\n if( i != j ){\n avgK[i][j] = ( uKMat[i][j] + Mij[i][j] ) / ( sumUKArr[i] + Nij[i] );\n avgLnK[i][j] = gsl_sf_psi( uKMat[i][j] + Mij[i][j] ) - gsl_sf_psi( sumUKArr[i] + Nij[i] );\n }\n }\n }\n}\n\n//void maximizationG_ts( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\ndouble varLowerBound_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsParameters *p = (tsParameters*)gv->params;\n tsStats *s = (tsStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, *cn = iv->cn;\n double *avgLnPi = p->avgLnPi, **avgLnK = p->avgLnK;\n double *avgLnKI = p->avgLnKI, *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;\n double *Ni = s->Ni, *Ti = s->Ti;\n double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;\n size_t n;\n int i, j;\n \n double lnpPi;\n lnpPi = gsl_sf_lngamma(sumUPi);\n double Ck = 1.0, lnpKii = (double)sNo * log(Ck);\n double lnpKij = 0.0;\n double lnpI = 0.0;\n double lnqPi;\n lnqPi = gsl_sf_lngamma(sumUPi + 1.0);\n double lnqKiiI = 0.0;\n double lnqKij = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]); \n\n lnpKii -= avgLnK[i][i];\n\n lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);\n lnpI += (aIArr[i]-1.0)*avgLnI[i] - bIArr[i]*avgI[i];\n\n lnqPi += (uPiArr[i]+gmMat[0][i]-1) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1));\n lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);\n\n lnqKiiI += gsl_sf_lngamma(Nii[i] + Nij[i]) + (Ni[i] + aIArr[i]) * log(Ti[i] + bIArr[i]);\n lnqKiiI += -gsl_sf_lngamma(Ni[i] + aIArr[i]) -gsl_sf_lngamma(Nii[i]);\n lnqKiiI += -gsl_sf_lngamma(Nij[i]) + (Nij[i]-1.0)*avgLnK[i][i];\n lnqKiiI += (Ni[i] + Nii[i] + aIArr[i] - 1.0)*avgLnI[i];\n lnqKiiI += -(Nii[i] + Nij[i])*avgLnKI[i] - (Ti[i] + bIArr[i])*avgI[i];\n \n lnpKij += gsl_sf_lngamma(sumUKArr[i]);\n lnqKij += gsl_sf_lngamma(sumUKArr[i] + Nij[i]);\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n lnpKij += (uKMat[i][j]-1)*avgLnK[i][j] - gsl_sf_lngamma(uKMat[i][j]);\n lnqKij += (uKMat[i][j]+Mij[i][j]-1)*(gsl_sf_psi(uKMat[i][j]+Mij[i][j])-gsl_sf_psi(sumUKArr[i]+Nij[i]));\n lnqKij -= gsl_sf_lngamma( uKMat[i][j] + Mij[i][j] );\n }\n }\n }\n\n double lnpX = 0.0;\n for( n = 0 ; n < dLen ; n++ ){\n lnpX += log( cn[n] );\n }\n \n double val;\n val = lnpPi + lnpKii + lnpKij + lnpI;\n val -= lnqPi + lnqKiiI + lnqKij;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n \n return val;\n}\n\n//double varLowerBoundG_ts( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid reorderParameters_ts( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsParameters *p = (tsParameters*)gv->params;\n tsStats *s = (tsStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK;\n double **avgLnK = p->avgLnK, *avgLnKI = p->avgLnKI;\n double *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *Ni = s->Ni, *Ti = s->Ti;\n size_t n;\n int i, j;\n \n int *index = (int*)malloc( sNo * sizeof(int) );\n double *store = (double*)malloc( sNo * sizeof(double) );\n double **s2D = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s2D[i] = (double*)malloc( sNo * sizeof(double) ); }\n\n // index indicates order of avgI values (0=biggest avgI -- sNo=smallest avgI).\n for( i = 0 ; i < sNo ; i++ ){\n index[i] = sNo - 1;\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n if( avgI[i] < avgI[j] ){\n index[i]--;\n } else if( avgI[i] == avgI[j] ){\n if( i < j )\n { index[i]--; }\n }\n }\n }\n }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgI[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnI[i] = store[i]; }\n\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgK[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgK[i][j] = s2D[i][j]; }\n }\n\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnK[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgLnK[i][j] = s2D[i][j]; }\n }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnKI[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnKI[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ti[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ti[i] = store[i]; }\n\n for( n = 0 ; n < dLen ; n++ ){\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }\n for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }\n }\n\n for( n = 0 ; n < dLen ; n++ ){\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }\n }\n }\n\n for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }\n free( s2D );\n free( store );\n free( index );\n}\n\n//void reorderParametersG_ts( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid outputTsResults( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n tsParameters *p = (tsParameters*)gv->params;\n int sNo = gv->sNo;\n int i, j;\n\n fprintf(logFP, \" results: K = %d \\n\", sNo);\n \n fprintf(logFP, \" intensities: ( %g\", p->avgI[0]);\n for( i = 1 ; i < sNo ; i++ )\n { fprintf(logFP, \", %g\", p->avgI[i]); }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" pi: ( %g\", p->avgPi[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgPi[i]);\n }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" k_matrix: [\");\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(logFP, \" ( %g\", p->avgK[i][0]);\n for( j = 1 ; j < sNo ; j++ )\n { fprintf(logFP, \", %g\", p->avgK[i][j]); }\n fprintf(logFP, \")\");\n }\n fprintf(logFP, \" ] \\n\\n\");\n\n char fn[256];\n FILE *fp;\n size_t n;\n\n sprintf( fn, \"%s.param%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n fprintf(fp, \"I, pi\");\n for( i = 0 ; i < sNo ; i++ )\n { fprintf(fp, \", K%dx\", i); }\n fprintf(fp, \"\\n\");\n \n for( i = 0 ; i < sNo ; i++ ){\n fprintf(fp, \"%g, %g\", p->avgI[i], p->avgPi[i]);\n for( j = 0 ; j < sNo ; j++ )\n { fprintf(fp, \", %g\", p->avgK[j][i]); }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.Lq%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < gv->iteration ; n++ ){\n fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n }\n fclose(fp);\n }\n\n sprintf( fn, \"%s.maxS%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < xn->N ; n++ ){\n fprintf( fp, \"%d\\n\", iv->stateTraj[n] );\n }\n fclose(fp);\n }\n\n}\n\n//void outputTsResultsG( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n//}\n\n//\n", "meta": {"hexsha": "7efd7e768717c88b54d9328760280d10c81517a4", "size": 20599, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmmTs.c", "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_issues_repo_path": "C/vbHmmTs.c", "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_licenses": ["MIT"], "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/vbHmmTs.c", "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": ["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.7614555256, "max_line_length": 119, "alphanum_fraction": 0.498907714, "num_tokens": 7545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.2948898862989504}} {"text": "#include \n#include \n#include \"erl_nif.h\"\n#include \n\n#define MAX(a,b) (((a)>(b))?(a):(b))\n\nstatic ERL_NIF_TERM atom_ok;\nstatic ERL_NIF_TERM atom_true;\n\nstatic ERL_NIF_TERM atom_rowmaj;\nstatic ERL_NIF_TERM atom_colmaj;\n\nstatic ERL_NIF_TERM atom_notransp;\nstatic ERL_NIF_TERM atom_transpose;\nstatic ERL_NIF_TERM atom_conjugatet;\n\nstatic ERL_NIF_TERM atom_upper;\nstatic ERL_NIF_TERM atom_lower;\n\nstatic ERL_NIF_TERM atom_left;\nstatic ERL_NIF_TERM atom_right;\n\nstatic ERL_NIF_TERM atom_nonunit;\nstatic ERL_NIF_TERM atom_unit;\n\nstatic ERL_NIF_TERM make_cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM from_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM to_values(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM to_idx_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM cont_size(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM cont_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\n\nstatic ERL_NIF_TERM drotg(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM drot(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM dcopy(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM l1d_1cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM l1d_2cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM dgemv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM dtrmv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\nstatic ERL_NIF_TERM dgemm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]);\n\nstatic ErlNifFunc nif_funcs[] = {\n {\"make_cont\", 2, make_cont},\n {\"from_list\", 1, from_list},\n {\"to_tuple_list_impl\", 4, to_values},\n {\"cont_size\", 1, cont_size},\n {\"values\", 2, to_idx_list},\n {\"update\", 2, cont_update},\n {\"update\", 3, cont_update},\n\n {\"rotg\", 2, drotg},\n {\"rot\", 9, drot},\n {\"copy\", 4, dcopy},\n {\"copy\", 7, dcopy},\n {\"one_vec\", 6, l1d_1cont},\n {\"two_vec\", 9, l1d_2cont},\n\n {\"gemv_impl\", 15, dgemv},\n {\"trmv_impl\", 11, dtrmv},\n {\"trmv_impl\", 12, dtrmv},\n\n {\"gemm_impl\", 15, dgemm},\n {\"trmm_impl\", 15, dgemm},\n};\n\nstatic ErlNifResourceType *avec_r;\n\ntypedef struct {\n double v[1];\n} Avec;\n\nstatic ERL_NIF_TERM mk_avec(ErlNifEnv *env, unsigned int n, Avec **avec) {\n ERL_NIF_TERM term;\n *avec = enif_alloc_resource(avec_r, n*sizeof(double));\n term = enif_make_resource(env, *avec);\n enif_release_resource(*avec);\n return term;\n}\n\n#define AVEC_SIZE(AV) \t(enif_sizeof_resource(AV) / 8)\n\n/* ---------------------------------------------------*/\n\nstatic ERL_NIF_TERM make_cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int n;\n ERL_NIF_TERM res;\n Avec *avec = NULL;\n double *data;\n\n if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);\n res = mk_avec(env, n, &avec);\n\n if(enif_is_binary(env, argv[1])) {\n\tErlNifBinary bin;\n\tenif_inspect_binary(env, argv[1], &bin);\n\tif(n*sizeof(double) != bin.size)\n\t return enif_make_badarg(env);\n\tmemcpy(avec->v, bin.data, sizeof(double)*n);\n } else if(enif_is_identical(argv[1], atom_true)) {\n\tdata = avec->v;\n\tmemset(data, 0, sizeof(double)*n);\n }\n\n return res;\n}\n\nstatic ERL_NIF_TERM from_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int len;\n int dim, i,j, tmp;\n ERL_NIF_TERM hd, tail, res;\n const ERL_NIF_TERM *current;\n Avec *avec = NULL;\n double *data;\n\n if(!enif_get_list_length(env, argv[0], &len) || len == 0)\n\treturn enif_make_badarg(env);\n\n enif_get_list_cell(env, argv[0], &hd, &tail);\n if(!enif_get_tuple(env, hd, &dim, ¤t))\n\tdim = 1;\n res = mk_avec(env, len*dim, &avec);\n\n enif_consume_timeslice(env, (len*dim)/1000);\n\n data = avec->v;\n if(dim == 1) {\n\tfor(i=0; i max) return enif_make_badarg(env);\n\n if(n == 1 && dim == 0) /* get_value() */\n\treturn enif_make_double(env, avec->v[idx]);\n\n if(dim == 0) { /* to_list */\n\ttail = enif_make_list(env, 0);\n\tarr = avec->v + idx + n-1;\n\tfor(i=0; i < max; i++) {\n\t tail = enif_make_list_cell(env, enif_make_double(env, *arr), tail);\n\t arr -= 1;\n\t}\n\treturn tail;\n }\n if(dim == n) { /* to_tuple */\n\ttmp = (ERL_NIF_TERM*) malloc(sizeof(ERL_NIF_TERM)*n);\n\tarr = avec->v;\n\tfor(i=0; i < n; i++) {\n\t tmp[i] = enif_make_double(env, arr[idx+i]);\n\t}\n\ttail = enif_make_tuple_from_array(env, tmp, n);\n\tfree(tmp);\n\treturn tail;\n }\n\n /* list of tuples */\n if(n % dim != 0)\n\treturn enif_make_badarg(env);\n\n arr = avec->v + idx + n-dim;\n tmp = (ERL_NIF_TERM*) malloc(sizeof(ERL_NIF_TERM)*dim);\n tail = enif_make_list(env, 0);\n\n for(i=0; i < max / dim; i++) {\n\tfor(j=0; j < dim; j++, arr++) {\n\t tmp[j] = enif_make_double(env, *arr);\n\t}\n\ttail = enif_make_list_cell(env, enif_make_tuple_from_array(env, tmp, dim), tail);\n\tarr -= 2*dim;\n }\n free(tmp);\n return tail;\n}\n\n\nstatic ERL_NIF_TERM to_idx_list(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ERL_NIF_TERM hd, tail, *tmp;\n Avec *avec = NULL;\n double *arr;\n unsigned int idx, n, i;\n\n if(!enif_get_list_length(env, argv[0], &n) || n == 0)\n\treturn enif_make_badarg(env);\n if(!enif_get_resource(env, argv[1], avec_r, (void **) &avec))\n\treturn enif_make_badarg(env);\n\n enif_consume_timeslice(env, n/1000);\n tmp = (ERL_NIF_TERM*) malloc(sizeof(ERL_NIF_TERM)*n);\n arr = avec->v;\n tail = argv[0];\n for(i=0; i < n; i++) {\n\tenif_get_list_cell(env, tail, &hd, &tail);\n\tif(!enif_get_uint(env, hd, &idx) || idx >= AVEC_SIZE(avec))\n\t return enif_make_badarg(env);\n\ttmp[i] = enif_make_tuple2(env, hd, enif_make_double(env, arr[idx]));\n }\n return enif_make_list_from_array(env, tmp, n);\n}\n\nstatic ERL_NIF_TERM cont_size(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n Avec *avec = NULL;\n\n if(!enif_get_resource(env, argv[0], avec_r, (void **) &avec)) {\n\treturn enif_make_badarg(env);\n }\n\n return enif_make_uint(env, AVEC_SIZE(avec));\n}\n\nstatic ERL_NIF_TERM cont_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n ERL_NIF_TERM hd, tail;\n const ERL_NIF_TERM *curr;\n Avec *avec = NULL;\n double *arr, temp;\n int i=0, n=0;\n unsigned int idx, max;\n\n if(argc == 2) { /* tuple list of values */\n\tif(!enif_is_list(env, argv[0]))\n\t return enif_make_badarg(env);\n\tif(!enif_get_resource(env, argv[1], avec_r, (void **) &avec))\n\t return enif_make_badarg(env);\n\tarr = avec->v;\n\tmax = AVEC_SIZE(avec);\n\ttail = argv[0];\n\twhile(!enif_is_empty_list(env, tail)) {\n\t if(!enif_get_list_cell(env, tail, &hd, &tail))\n\t\treturn enif_make_badarg(env);\n\t if(!enif_get_tuple(env, hd, &i, &curr) || i != 2)\n\t\treturn enif_make_badarg(env);\n\t if(!enif_get_uint(env, curr[0], &idx) || idx >= max)\n\t\treturn enif_make_badarg(env);\n\t if(!enif_get_double(env, curr[1], &temp))\n\t\treturn enif_make_badarg(env);\n\t arr[idx] = temp;\n\t n++;\n\t}\n\tenif_consume_timeslice(env, n/1000);\n\treturn atom_ok;\n }\n /* update(Idx, V|[Vs], Vec) */\n if(!enif_get_uint(env, argv[0], &idx))\n\treturn enif_make_badarg(env);\n if(!enif_is_list(env, argv[1])) {\n\t/* update(Idx, Double, Vec) */\n\tif(!enif_get_double(env, argv[1], &temp))\n\t return enif_make_badarg(env);\n\tif(!enif_get_resource(env, argv[2], avec_r, (void **) &avec))\n\t return enif_make_badarg(env);\n\tmax = AVEC_SIZE(avec);\n\tif(idx >= max)\n\t return enif_make_badarg(env);\n\tarr = avec->v;\n\tarr[idx] = temp;\n\treturn atom_ok;\n }\n /* update(Idx, [Values], Vec) */\n tail = argv[1];\n if(!enif_get_resource(env, argv[2], avec_r, (void **) &avec))\n\treturn enif_make_badarg(env);\n max = AVEC_SIZE(avec);\n arr = avec->v+idx;\n while(!enif_is_empty_list(env, tail)) {\n\tif(!enif_get_list_cell(env, tail, &hd, &tail))\n\t return enif_make_badarg(env);\n\tif(!enif_get_double(env, hd, &temp))\n\t return enif_make_badarg(env);\n\t*arr = temp;\n\tarr++;\n\tidx++;\n\tn++;\n\tif(idx > max)\n\t return enif_make_badarg(env);\n }\n enif_consume_timeslice(env, n/1000);\n return atom_ok;\n}\n\n\n\n/* ---------------------------------------------------*/\n\nstatic ERL_NIF_TERM drotg(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{/* (a, b) */\n double a,b,c,s;\n\n if(!enif_get_double(env, argv[0], &a) || !enif_get_double(env, argv[1], &b)) {\n\treturn enif_make_badarg(env);\n }\n\n cblas_drotg(&a,&b,&c,&s);\n return enif_make_tuple4(env,\n\t\t\t enif_make_double(env, a), enif_make_double(env, b),\n\t\t\t enif_make_double(env, c), enif_make_double(env, s));\n\n}\n\nstatic ERL_NIF_TERM drot(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int n, xs, ys;\n int xi, yi;\n Avec *ax, *ay;\n double *x, *y, c, s;\n\n if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[1], avec_r, (void **) &ax)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[2], &xs)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[3], &xi)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[4], avec_r, (void **) &ay)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[5], &ys)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[6], &yi)) return enif_make_badarg(env);\n if(!enif_get_double(env, argv[7], &c)) return enif_make_badarg(env);\n if(!enif_get_double(env, argv[8], &s)) return enif_make_badarg(env);\n\n x = ax->v + xs;\n y = ay->v + ys;\n /* array limit checks */\n if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n if((ys+n*abs(yi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n\n enif_consume_timeslice(env, n/1000);\n cblas_drot(n, x, xi, y, xi, c, s);\n\n return atom_ok;\n}\n\nstatic ERL_NIF_TERM l1d_1cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int op, n, xs;\n int xi, tmp;\n Avec *ax;\n double *x, alpha;\n ERL_NIF_TERM res = atom_ok;\n\n if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);\n if(!enif_get_double(env, argv[1], &alpha)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[2], avec_r, (void **) &ax)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[3], &xs)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[4], &xi)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[5], &op)) return enif_make_badarg(env);\n x = ax->v + xs;\n /* array limit checks */\n if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n\n switch(op) {\n case 0:\n\tcblas_dscal(n, alpha, x, xi);\n\tbreak;\n case 1:\n\tres = enif_make_double(env, cblas_dnrm2(n, x, xi));\n\tbreak;\n case 2:\n\tres = enif_make_double(env, cblas_dasum(n, x, xi));\n\tbreak;\n case 3:\n\ttmp = cblas_idamax(n, x, xi);\n\tres = enif_make_tuple2(env,\n\t\t\t enif_make_uint(env, tmp),\n\t\t\t enif_make_double(env, x[tmp]));\n\tbreak;\n }\n enif_consume_timeslice(env, n/1000);\n return res;\n}\n\n\nstatic ERL_NIF_TERM dcopy(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int n, xs, ys = 0;\n int xi, yi=1;\n Avec *ax, *ay;\n double *x, *y;\n ERL_NIF_TERM res;\n\n if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[1], avec_r, (void **) &ax)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[2], &xs)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[3], &xi)) return enif_make_badarg(env);\n /* array limit checks */\n if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n\n if(argc == 4) { /* copy to new vector */\n\tres = mk_avec(env, n, &ay);\n } else {\n\tif(!enif_get_resource(env, argv[4], avec_r, (void **) &ay)) return enif_make_badarg(env);\n\tif(!enif_get_uint(env, argv[5], &ys)) return enif_make_badarg(env);\n\tif(!enif_get_int(env, argv[6], &yi)) return enif_make_badarg(env);\n\tif((ys+n*abs(yi)-1) > AVEC_SIZE(ay)) return enif_make_badarg(env);\n\tres = atom_ok;\n }\n\n x = ax->v + xs;\n y = ay->v + ys;\n cblas_dcopy(n, x, xi, y, yi);\n enif_consume_timeslice(env, n/1000);\n\n return res;\n}\n\nstatic ERL_NIF_TERM l1d_2cont(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int op, n, xs, ys;\n int xi, yi;\n Avec *ax, *ay;\n double *x, *y, alpha, res;\n\n if(!enif_get_uint(env, argv[0], &n)) return enif_make_badarg(env);\n if(!enif_get_double(env, argv[1], &alpha)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[2], avec_r, (void **) &ax)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[3], &xs)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[4], &xi)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[5], avec_r, (void **) &ay)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[6], &ys)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[7], &yi)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[8], &op)) return enif_make_badarg(env);\n x = ax->v + xs;\n y = ay->v + ys;\n /* array limit checks */\n if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n if((ys+n*abs(yi)-1) > AVEC_SIZE(ay)) return enif_make_badarg(env);\n\n enif_consume_timeslice(env, n/1000);\n switch(op) {\n case 0:\n\tcblas_daxpy(n, alpha, x, xi, y, yi);\n\tbreak;\n case 1:\n\tcblas_dswap(n, x, xi, y, yi);\n\tbreak;\n case 2:\n\tres = cblas_ddot(n, x, xi, y, yi);\n\treturn enif_make_double(env, res);\n }\n return atom_ok;\n}\n\n/* ---------------------------------------------------*/\n\nstatic ERL_NIF_TERM dgemv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int m, n, lda, xs, ys, op;\n int xi, yi;\n Avec *aa, *ax, *ay;\n double *a, *x, *y, alpha, beta;\n enum CBLAS_ORDER order = 0;\n enum CBLAS_TRANSPOSE trans = 0;\n enum CBLAS_UPLO uplo = 0;\n\n if(enif_is_identical(argv[0], atom_rowmaj)) order = CblasRowMajor;\n else if(enif_is_identical(argv[0], atom_colmaj)) order = CblasColMajor;\n else return enif_make_badarg(env);\n\n if(enif_is_identical(argv[1], atom_notransp)) trans = CblasNoTrans;\n else if(enif_is_identical(argv[1], atom_transpose)) trans = CblasTrans;\n else if(enif_is_identical(argv[1], atom_conjugatet)) trans = CblasConjTrans;\n else if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;\n else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;\n else return enif_make_badarg(env);\n\n if(!enif_get_uint(env, argv[2], &m)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[3], &n)) return enif_make_badarg(env);\n if(!enif_get_double(env, argv[4], &alpha)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[5], avec_r, (void **) &aa)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[6], &lda)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[7], avec_r, (void **) &ax)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[8], &xs)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[9], &xi)) return enif_make_badarg(env);\n if(!enif_get_double(env, argv[10], &beta)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[11], avec_r, (void **) &ay)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[12], &ys)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[13], &yi)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[14], &op)) return enif_make_badarg(env);\n\n a = aa->v;\n x = ax->v + xs;\n y = ay->v + ys;\n\n /* array limit checks */\n if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n if((ys+n*abs(yi)-1) > AVEC_SIZE(ay)) return enif_make_badarg(env);\n\n switch(op) {\n case 0:\n\tcblas_dgemv(order, trans, m, n, alpha, a, lda, x, xi, beta, y, yi); break;\n case 1:\n\tcblas_dsymv(order, uplo, n, alpha, a, lda, x, xi, beta, y, yi); break;\n case 2:\n\tcblas_dspmv(order, uplo, n, alpha, a, x, xi, beta, y, yi); break;\n case 3:\n\tcblas_dger(order, m, n, alpha, x, xi, y, yi, a, lda); break;\n case 4:\n\tcblas_dsyr2(order, uplo, n, alpha, x, xi, y, yi, a, lda); break;\n case 5:\n\tcblas_dspr2(order, uplo, n, alpha, x, xi, y, yi, a); break;\n }\n enif_consume_timeslice(env, MAX(1,m)*n/1000);\n return atom_ok;\n}\n\nstatic ERL_NIF_TERM dtrmv(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int n, lda, xs, op;\n int xi;\n Avec *aa, *ax;\n double *a, *x, alpha;\n enum CBLAS_ORDER order = 0;\n enum CBLAS_TRANSPOSE trans = 0;\n enum CBLAS_UPLO uplo = 0;\n enum CBLAS_DIAG diag = 0;\n\n if(enif_is_identical(argv[0], atom_rowmaj)) order = CblasRowMajor;\n else if(enif_is_identical(argv[0], atom_colmaj)) order = CblasColMajor;\n else return enif_make_badarg(env);\n\n if(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;\n else if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;\n else return enif_make_badarg(env);\n\n if(!enif_get_uint(env, argv[10], &op)) return enif_make_badarg(env);\n if(op < 4) {\n\tif(enif_is_identical(argv[2], atom_notransp)) trans = CblasNoTrans;\n\telse if(enif_is_identical(argv[2], atom_transpose)) trans = CblasTrans;\n\telse if(enif_is_identical(argv[2], atom_conjugatet)) trans = CblasConjTrans;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[3], atom_nonunit)) diag = CblasNonUnit;\n\telse if(enif_is_identical(argv[3], atom_unit)) diag = CblasUnit;\n\telse return enif_make_badarg(env);\n }\n\n if(!enif_get_uint(env, argv[4], &n)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[5], avec_r, (void **) &aa)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[6], &lda)) return enif_make_badarg(env);\n if(!enif_get_resource(env, argv[7], avec_r, (void **) &ax)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[8], &xs)) return enif_make_badarg(env);\n if(!enif_get_int(env, argv[9], &xi)) return enif_make_badarg(env);\n if(argc > 11)\n\tif(!enif_get_double(env, argv[11], &alpha)) return enif_make_badarg(env);\n\n a = aa->v;\n x = ax->v + xs;\n\n /* array limit checks */\n if((xs+n*abs(xi)-1) > AVEC_SIZE(ax)) return enif_make_badarg(env);\n\n switch(op) {\n case 0:\n\tcblas_dtrmv(order, uplo, trans, diag, n, a, lda, x, xi);break;\n case 1:\n\tcblas_dtpmv(order, uplo, trans, diag, n, a, x, xi); break;\n case 2:\n\tcblas_dtrsv(order, uplo, trans, diag, n, a, lda, x, xi);break;\n case 3:\n\tcblas_dtpsv(order, uplo, trans, diag, n, a, x, xi);break;\n case 4:\n\tcblas_dsyr(order, uplo, n, alpha, x, xi, a, lda); break;\n case 5:\n\tcblas_dspr(order, uplo, n, alpha, x, xi, a); break;\n }\n\n enif_consume_timeslice(env, n*n/1000);\n return atom_ok;\n}\n\n/* ---------------------------------------------------*/\n\nstatic ERL_NIF_TERM dgemm(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])\n{\n unsigned int m, n, k, lda, ldb, ldc, op;\n Avec *aa, *ab, *ac;\n double alpha, beta, *a, *b, *c = NULL;\n enum CBLAS_ORDER order = 0;\n enum CBLAS_TRANSPOSE ta = 0, tb = 0;\n enum CBLAS_UPLO uplo = 0;\n enum CBLAS_SIDE side = 0;\n enum CBLAS_DIAG diag = 0;\n\n if(enif_is_identical(argv[0], atom_rowmaj)) order = CblasRowMajor;\n else if(enif_is_identical(argv[0], atom_colmaj)) order = CblasColMajor;\n else return enif_make_badarg(env);\n\n if(!enif_get_uint(env, argv[3], &m)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[4], &n)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[5], &k)) return enif_make_badarg(env);\n\n if(!enif_get_double(env, argv[6], &alpha)) return enif_make_badarg(env);\n\n if(!enif_get_resource(env, argv[7], avec_r, (void **) &aa)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[8], &lda)) return enif_make_badarg(env);\n\n if(!enif_get_resource(env, argv[9], avec_r, (void **) &ab)) return enif_make_badarg(env);\n if(!enif_get_uint(env, argv[10], &ldb)) return enif_make_badarg(env);\n\n if(!enif_get_double(env, argv[11], &beta)) return enif_make_badarg(env);\n\n if(!enif_get_uint(env, argv[12], &op)) return enif_make_badarg(env);\n if(op < 3) {\n\tif(!enif_get_resource(env, argv[13], avec_r, (void **) &ac))\n\t return enif_make_badarg(env);\n\tif(!enif_get_uint(env, argv[14], &ldc)) return enif_make_badarg(env);\n\tc = ac->v;\n }\n a = aa->v;\n b = ab->v;\n switch(op) {\n case 0: {\n\tif(enif_is_identical(argv[1], atom_notransp)) ta = CblasNoTrans;\n\telse if(enif_is_identical(argv[1], atom_transpose)) ta = CblasTrans;\n\telse if(enif_is_identical(argv[1], atom_conjugatet)) ta = CblasConjTrans;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;\n\telse if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;\n\telse if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;\n\telse return enif_make_badarg(env);\n\n\tcblas_dgemm(order, ta,tb, m,n,k, alpha, a,lda, b,ldb, beta, c,ldc);\n\tbreak;}\n case 1: {\n\tif(enif_is_identical(argv[1], atom_left)) side = CblasLeft;\n\telse if(enif_is_identical(argv[1], atom_right)) side = CblasRight;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[2], atom_lower)) uplo = CblasLower;\n\telse if(enif_is_identical(argv[2], atom_upper)) uplo = CblasUpper;\n\telse return enif_make_badarg(env);\n\n\tcblas_dsymm(order, side, uplo, m,n, alpha, a,lda, b,ldb, beta, c,ldc);\n\tbreak; }\n case 2: {\n\tif(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;\n\telse if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;\n\telse if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;\n\telse if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;\n\n\t// fprintf(stderr, \"%d %d,%d,%d %.2f %.2f %d,%d,%d\\r\\n\", __LINE__, m,n,k, alpha, beta, lda,ldb,ldc);\n\tcblas_dsyr2k(order, uplo, tb, n, k, alpha, a,lda, b,ldb, beta, c,ldc);\n\tbreak; }\n case 3: {\n\tif(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;\n\telse if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;\n\telse if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;\n\telse if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;\n\n\tif(enif_is_identical(argv[13], atom_left)) side = CblasLeft;\n\telse if(enif_is_identical(argv[13], atom_right)) side = CblasRight;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[14], atom_nonunit)) diag = CblasNonUnit;\n\telse if(enif_is_identical(argv[14], atom_unit)) diag = CblasUnit;\n\telse return enif_make_badarg(env);\n\n\tcblas_dtrmm(order,side,uplo,tb,diag, m,n, alpha, a,lda, b, ldb);\n\tbreak; }\n case 4: {\n\tif(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;\n\telse if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;\n\telse if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;\n\telse if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;\n\n\tif(enif_is_identical(argv[13], atom_left)) side = CblasLeft;\n\telse if(enif_is_identical(argv[13], atom_right)) side = CblasRight;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[14], atom_nonunit)) diag = CblasNonUnit;\n\telse if(enif_is_identical(argv[14], atom_unit)) diag = CblasUnit;\n\telse return enif_make_badarg(env);\n\n\tcblas_dtrsm(order,side,uplo,tb,diag, m,n, alpha, a,lda, b, ldb);\n\tbreak; }\n case 5: {\n\tif(enif_is_identical(argv[1], atom_lower)) uplo = CblasLower;\n\telse if(enif_is_identical(argv[1], atom_upper)) uplo = CblasUpper;\n\telse return enif_make_badarg(env);\n\n\tif(enif_is_identical(argv[2], atom_notransp)) tb = CblasNoTrans;\n\telse if(enif_is_identical(argv[2], atom_transpose)) tb = CblasTrans;\n\telse if(enif_is_identical(argv[2], atom_conjugatet)) tb = CblasConjTrans;\n\n\tcblas_dsyrk(order,uplo,tb, n,k, alpha, a,lda, beta, b,ldb);\n\tbreak; }\n }\n\n enif_consume_timeslice(env, MAX(m,k)*n/1000);\n return atom_ok;\n}\n\n/* ---------------------------------------------------*/\n\nstatic int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info)\n{\n atom_ok = enif_make_atom(env,\"ok\");\n atom_true = enif_make_atom(env,\"true\");\n\n atom_notransp = enif_make_atom(env,\"no_transp\");\n atom_transpose = enif_make_atom(env,\"transp\");\n atom_conjugatet = enif_make_atom(env,\"conj_transp\");\n\n atom_rowmaj = enif_make_atom(env,\"row_maj\");\n atom_colmaj = enif_make_atom(env,\"col_maj\");\n\n atom_upper = enif_make_atom(env,\"upper\");\n atom_lower = enif_make_atom(env,\"lower\");\n\n atom_left = enif_make_atom(env,\"left\");\n atom_right = enif_make_atom(env,\"right\");\n\n atom_nonunit = enif_make_atom(env,\"non_unit\");\n atom_unit = enif_make_atom(env,\"unit\");\n\n avec_r = enif_open_resource_type(env, \"eblas\", \"avec\", NULL, ERL_NIF_RT_CREATE, NULL);\n return 0;\n}\n\nstatic int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data,\n\t\t ERL_NIF_TERM load_info)\n{\n return 0;\n}\n\nstatic void unload(ErlNifEnv* env, void* priv_data)\n{\n\n}\n\nERL_NIF_INIT(blasd_raw,nif_funcs,load,NULL,upgrade,unload)\n", "meta": {"hexsha": "c3df77ef3067f698126b98bcedc64d0dd167ec5e", "size": 26288, "ext": "c", "lang": "C", "max_stars_repo_path": "c_src/eblas.c", "max_stars_repo_name": "5HT/blas", "max_stars_repo_head_hexsha": "dc493f42753eaae1756b040e8e40575caedf5931", "max_stars_repo_licenses": ["TCL"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c_src/eblas.c", "max_issues_repo_name": "5HT/blas", "max_issues_repo_head_hexsha": "dc493f42753eaae1756b040e8e40575caedf5931", "max_issues_repo_licenses": ["TCL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c_src/eblas.c", "max_forks_repo_name": "5HT/blas", "max_forks_repo_head_hexsha": "dc493f42753eaae1756b040e8e40575caedf5931", "max_forks_repo_licenses": ["TCL"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T13:47:56.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T13:47:56.000Z", "avg_line_length": 33.8762886598, "max_line_length": 101, "alphanum_fraction": 0.6630401704, "num_tokens": 8699, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.2942546202574461}} {"text": "// Sammlung verwendeter Funktionen\n#include \"global.h\"\n#include \"targets.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utility.h\"\n#include \n#include \n#include \n\nint Get_Lattice_Targets_Center_Circle( int *pos, double *targets, \t// leaves esc_cell radius free\n\t\t\t\t\t\t double lattice_spacing, int escape_cells)\t// targets one in cell center\n{\n\tint ret_value = 0; //leave starting cell empty, else particle starts in Target\n\tif \t(\t(pos[0] == 0)&&\n\t\t\t(pos[1] == 0) \n\t\t)\n\n\t{\n\t\tret_value = 0; //catch mistake if zero cell was still supposed to have target\n\t\treturn (ret_value);\n\t}\n\tif \t(pos[0] * pos[0] + pos[1] * pos[1] > escape_cells * escape_cells ) //If outside circle\n\t{\n\t\tret_value = 1; //single target center cell\n\t\ttargets[0] = pos[0] * lattice_spacing; \n\t\ttargets[1] = pos[1] * lattice_spacing;\n\t\treturn (ret_value);\n\t}\n\treturn (ret_value);\n}\n\nint Get_Lattice_Targets_PORE_3( int *pos, double *targets, \t// leaves esc_cell radius free\n\t\t\t\t\t\t double lattice_spacing, int escape_cells)\t// targets one in cell center\n{\t\n\tdouble corner_vec[2];\n\tint corner = 0;\n\t//corner one oben links\n\tfor (double i_x = -1.0; i_x < 2.0; i_x+= 2.0)\n\t{\n\t\tfor (double i_y = -1.0; i_y < 2.0; i_y+= 2.0)\n\t\t{ \n\t\t\tint stride = 2 * corner * (NUMBER_PORE_OBSTACLES + 1);\n\t\t\tcorner_vec[0] = (pos[0] + i_x *0.5) * LATTICE_SPACING;\n\t\t\tcorner_vec[1] = (pos[1] + i_y *0.5) * LATTICE_SPACING;\n\t\t\ttargets[0 + stride] = corner_vec[0];\n\t\t\ttargets[1 + stride] = corner_vec[1];\n\t\t\tfor (int i_pore = 0; i_pore < NUMBER_PORE_OBSTACLES; i_pore++)\n\t\t\t{\n\t\t\t\ttargets[2 + stride + i_pore * 4] = corner_vec[0] - i_x * TARGET_LENGTH * (i_pore + 1);\n\t\t\t\ttargets[3 + stride + i_pore * 4] = corner_vec[1];\n\n\t\t\t\ttargets[4 + stride + i_pore * 4] = corner_vec[0];\n\t\t\t\ttargets[5 + stride + i_pore * 4] = corner_vec[1] - i_y * TARGET_LENGTH * (i_pore + 1);\n\t\t\t}\n\t\t\tcorner++;\n\t\t}\n\t\tcorner++;\n\t}\n\treturn (4 *(1 + 2* NUMBER_PORE_OBSTACLES));\n}\n\nint Get_Lattice_Targets_Center_Square( int *pos, double *targets,\t// leaves esc_cell^2 square free\n\t\t\t\t\t\t double lattice_spacing, int escape_cells)\t// targets one in cell center\n{\n\tint ret_value = 0; //leave starting cell empty, else particle starts in Target\n\tif \t(\t(pos[0] == 0)&&\n\t\t\t(pos[1] == 0) \n\t\t)\n\n\t{\n\t\tret_value = 0; //catch mistake if zero cell was still supposed to have target\n\t\treturn (ret_value);\n\t}\n\tif \t( \t(abs(pos[0]) > escape_cells)||\n\t\t\t(abs(pos[1]) > escape_cells) \n\t\t)\n\t{\n\t\tret_value = 1; //single target center cell\n\t\ttargets[0] = pos[0] * lattice_spacing; \n\t\ttargets[1] = pos[1] * lattice_spacing;\n\t\treturn (ret_value);\n\t}\n\treturn (ret_value);\n}\n\nint Get_Lattice_Targets_Corner_Square( int *pos, double *targets,\n\t\t\t\t\t\t double lattice_spacing, int escape_cells)\n// get target vectors for corner, middle or porous region. save in targest[4*DIM], return number targets\n{\n\tint ret_value = 0;\n\tif(escape_cells == 0)\t\t// catch case no free cells\n\t{\n\t\tret_value = 4; // 4 targets per lattice cell\n\t\tint count = -1;\n\t\tfor (int i = -1; i< 2; i+=2) //i,j in (-1,1)\n\t\t{\n\t\t\tfor (int j = -1; j< 2; j+=2)\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\ttargets[0 + count * DIM] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing; \n\t\t\t\ttargets[1 + count * DIM] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;\n\t\t\t}\n\t\t}\n\t\treturn (ret_value);\n\t}\n\t// check porous are\n\tif( (abs(pos[0]) > escape_cells)||\n\t\t(abs(pos[1]) > escape_cells) )\n\t{\n\t\tret_value = 4; // 4 targets per lattice cell\n\t\tint count = -1;\n\t\tfor (int i = -1; i< 2; i+=2) //i,j in (-1,1)\n\t\t{\n\t\t\tfor (int j = -1; j< 2; j+=2)\n\t\t\t{\n\t\t\t\tcount++;\n\t\t\t\ttargets[0 + count * DIM] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing; \n\t\t\t\ttargets[1 + count * DIM] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;\n\t\t\t}\n\t\t}\n\t\treturn (ret_value);\n\t}\n\t//Check corner \n\tfor (int i = -1; i< 2; i+=2) //i,j in (-1,1)\n\t{\n\t\tfor (int j = -1; j< 2; j+=2)\n\t\t{\n\t\t\tif( (pos[0] == i * escape_cells)&&\n\t\t\t\t(pos[1] == j * escape_cells))\n\t\t\t{\t\n\t\t\t\tret_value = 3; // corner and two sides\n\t\t\t\ttargets[0] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing; \t\t//corner\n\t\t\t\ttargets[1] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;\n\n\t\t\t\ttargets[2] = i * (-1) * lattice_spacing/2.0 + pos[0] * lattice_spacing;\t//first side\n\t\t\t\ttargets[3] = j * lattice_spacing/2.0 + pos[1] * lattice_spacing;\n\t\t\t\ttargets[4] = i * lattice_spacing/2.0 + pos[0] * lattice_spacing;\t//first side\n\t\t\t\ttargets[5] = j * (-1) * lattice_spacing/2.0 + pos[1] * lattice_spacing;\n\t\t\t\treturn (ret_value);\n\t\t\t}\t// corner\n\t\t}\n\t}\n\t// check sides after sure you are not in corner\n\tfor( int d = 0; d < DIM; d++)// loop over dimension\n\t{\n\t\tint e = 1-d;\n\t\tfor (int i = -1; i< 2; i+=2)\n\t\t{\n\t\t\tif(pos[d] == i * escape_cells)\n\t\t\t{\n\t\t\t\tret_value = 2; //two sides\n\t\t\t\ttargets[d] \t\t\t= i * lattice_spacing/2.0 + pos[d] * lattice_spacing;\n\t\t\t\ttargets[e] \t\t\t= (-1) * lattice_spacing/2.0 + pos[e] * lattice_spacing;\n\t\t\t\ttargets[d +DIM] \t= i * lattice_spacing/2.0 + pos[d] * lattice_spacing;\n\t\t\t\ttargets[e +DIM] \t= (1) * lattice_spacing/2.0 + pos[e] * lattice_spacing;\n\t\t\t\treturn (ret_value);\n\t\t\t}\n\t\t}\n\t}\n\treturn (ret_value);\n}", "meta": {"hexsha": "82e5dae58f4807acf988a34b34f44b88870b6639", "size": 5150, "ext": "c", "lang": "C", "max_stars_repo_path": "targets.c", "max_stars_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_stars_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "targets.c", "max_issues_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_issues_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "targets.c", "max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_forks_repo_licenses": ["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.0240963855, "max_line_length": 104, "alphanum_fraction": 0.6188349515, "num_tokens": 1845, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.2940586976544659}} {"text": "\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"adkGSL.h\"\n#include \"AFS.h\"\n#include \"cs.h\"\n#include \"adkCSparse.h\"\n#include \"AFS_ctmc.h\"\n#include \n\n\nvoid coalMarkovChainTopologyMatrix_pthread(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz);\nvoid coalMarkovChainTopologyMatrix_sparse_pthread(afsStateSpace *S,double *topol, int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz);\n\n\ntypedef struct matrixThreadObject\n{\n\tint nnz,start, stop;\n\tint *dim1,*dim2; \n\tstruct island_lik_params *island_params;\n}\nmatrixThreadObject;\n\n\ntypedef struct matrixThreadObject_sparse\n{\n\tint nnz,start, stop, nnzA;\n\tint *dim1,*dim2, *moveType;\n\tdouble *topol;\n\tstruct im_lik_params *im_params;\n}\nmatrixThreadObject_sparse;\n\n\n//gonna try to use a global declared in island.c\nvoid *threadDoRows(void* arg){\n\tmatrixThreadObject *obj = (matrixThreadObject*)(arg);\n\t\n\tcoalMarkovChainTopologyMatrix_pthread(obj->island_params->stateSpace,obj->island_params->topol, obj->island_params->moveType, \n\tobj->dim1,obj->dim2,obj->start,obj->stop,&(obj->nnz));\n\t//obj->nnz -= 1;\n\t\n\tpthread_exit((void* )obj);\n}\n\n//sparse matrix version\nvoid *threadDoRows_sparse(void* arg){\n\tmatrixThreadObject_sparse *obj = (matrixThreadObject_sparse*)(arg);\n\t\n\tcoalMarkovChainTopologyMatrix_sparse_pthread(obj->im_params->stateSpace,obj->topol, obj->moveType, \n\tobj->dim1,obj->dim2,obj->start,obj->stop,&(obj->nnz));\n\t//obj->nnz -= 1;\n\t\n\tpthread_exit((void* )obj);\n}\n\n//sparse matrix version on reduced state space\nvoid *threadDoRows_sparse_reduced(void* arg){\n\tmatrixThreadObject_sparse *obj = (matrixThreadObject_sparse*)(arg);\n\t\n\tcoalMarkovChainTopologyMatrix_sparse_pthread(obj->im_params->reducedStateSpace,obj->topol, obj->moveType, \n\tobj->dim1,obj->dim2,obj->start,obj->stop,&(obj->nnzA));\n\t//obj->nnz -= 1;\n\t\n\tpthread_exit((void* )obj);\n}\n\nvoid coalMarkovChainTopologyMatrix_pthread(afsStateSpace *S,gsl_matrix *topol, gsl_matrix_int *moveType, int *dim1, int *dim2, int start, int stop, int *nnz){\n\tint i,j,k,steps,x,y;\n\tdouble top,bottom;\n\tafsObject *delta;\n\tint **activePos1, **activePos2; //first dimension here relates to 2 popns\n\tint nlin1,nlin2,compat;\n\tint nonZeroCount, tot, tCount;\n\tint size = 200;\n\tnlin1 = nlin2 = 0;\n\tnonZeroCount = 0;\n\tif(S->nstates != topol->size1 || S->nstates != moveType->size1){\n\t\tfprintf(stderr,\"Error: StateSpace and matrices are not of equal size\\n\");\n\t\texit(1);\n\t}\n\t*nnz = 0;\n\t//arrays for finding positions of entries\n\tactivePos1 = malloc(size*sizeof(int *));\n\tactivePos2 = malloc(size*sizeof(int *));\n\tfor(i=0;instates * S->nstates;\n\ttCount = 0;\n\tdelta = afsObjectNewFrom(S->states[0]);\n\tfor(i=start;instates;j++){\n\t\t\tgsl_matrix_int_set(moveType,i,j,666);\n\n\t\t\t//is ith state root state?\n\t\t\tif(S->states[i]->nalleles == 1){\n\t\t\t\t//set correct absorbing conditions\n\t\t\t\tif(i==j){\n\t\t\t\t\tgsl_matrix_set(topol,i,j,1.0);\n\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,-1);\n\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tgsl_matrix_set(topol,i,j,0.0);\n\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,-1);\n\t\t\t\t}\t\t\n\t\t\t}\n\t\t\telse{ //ith not root; what is the move?\n\t\t\t\tsteps = S->states[i]->nalleles - S->states[j]->nalleles ;\n\t\t\t\tif(steps < 2){\n\t\t\t\t//\tdelta = afsObjectDelta(S->states[i],S->states[j]);\n\t\t\t\t\tafsObjectDeltaPre(S->states[i],S->states[j],delta);\n\t\t\t\t\tswitch(steps){\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t// 0 \"steps\", so no changes in nalleles between two\n\t\t\t\t\t\t//check counts and positions\t\n\t\t\t\t\t\tif(abs(matrixSum(delta->popMats[0])) == 1){\n\t\t\t\t\t\t\tnonZeroEntries(delta->popMats[0], activePos1, &nlin1);\n\t\t\t\t\t\t\tnonZeroEntries(delta->popMats[1], activePos2, &nlin2);\n\n\t\t\t\t\t\t\t//migration?\n\t\t\t\t\t\t\tif(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] &&\n\t\t\t\t\t\t\t\t(gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0))\n\t\t\t\t\t\t\t{\n\n\t\t\t\t\t\t\t\t//migration popn1?\n\t\t\t\t\t\t\t\tif(matrixSum(delta->popMats[0]) == 1){\n\t\t\t\t\t\t\t\t\tgsl_matrix_set(topol,i,j,\n\t\t\t\t\t\t\t\t\t\t(double) gsl_matrix_int_get(S->states[i]->popMats[0],\n\t\t\t\t\t\t\t\t\t\tactivePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0]);\n\t\t\t\t\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,2);\n\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{ //migration popn2\n\t\t\t\t\t\t\t\t\tgsl_matrix_set(topol,i,j,\n\t\t\t\t\t\t\t\t\t\t(double) gsl_matrix_int_get(S->states[i]->popMats[1],\n\t\t\t\t\t\t\t\t\t\tactivePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1]);\n\t\t\t\t\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,3);\n\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase 1://coalescent?\n\t\t\t\t\t\t//coal popn1?\n\t\t\t\t\t\tif(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 ){\n\t\t\t\t\t\t\tentriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages\n\t\t\t\t\t\t\tentriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages\n\t\t\t\t\t\t\tif(nlin2 != 0 && nlin2 < 2){\n\n\t\t\t\t\t\t\t\tcompat=0;\n\t\t\t\t\t\t\t\tif(nlin1 == 1){\n\t\t\t\t\t\t\t\t\tif(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(nlin1==2){\n\t\t\t\t\t\t\t\t\tif(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] &&\n\t\t\t\t\t\t\t\t\t\tactivePos1[0][1] + activePos1[1][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(compat != 1){\n\t\t\t\t\t\t\t\t\tgsl_matrix_set(topol,i,j,0.0);\n\t\t\t\t\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,666);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{\n\n\t\t\t\t\t\t\t\t\ttop = 1.0;\n\t\t\t\t\t\t\t\t\tbottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ;\n\t\t\t\t\t\t\t\t\tfor(k=0;kstates[i]->popMats[0],x,y),\n\t\t\t\t\t\t\t\t\t\t\tgsl_matrix_int_get(delta->popMats[0],x,y));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tgsl_matrix_set(topol,i,j,top/bottom);\n\t\t\t\t\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,0);\n\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 ){\n\t\t\t\t\t\t\t\tentriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages\n\t\t\t\t\t\t\t\tentriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages\n\t\t\t\t\t\t\t\tif(nlin2 != 0 && nlin2 < 2){\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcompat=0;\n\t\t\t\t\t\t\t\t\tif(nlin1 == 1){\n\t\t\t\t\t\t\t\t\t\tif(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(nlin1==2){\n\t\t\t\t\t\t\t\t\t\tif(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] &&\n\t\t\t\t\t\t\t\t\t\t\tactivePos1[0][1] + activePos1[1][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(compat != 1){\n\n\t\t\t\t\t\t\t\t\t\tgsl_matrix_set(topol,i,j,0.0);\n\t\t\t\t\t\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,666);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\t\t\ttop = 1.0;\n\n\t\t\t\t\t\t\t\t\t\tbottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ;\n\t\t\t\t\t\t\t\t\t\tfor(k=0;kstates[i]->popMats[1],x,y),\n\t\t\t\t\t\t\t\t\t\t\t\tgsl_matrix_int_get(delta->popMats[1],x,y));\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tgsl_matrix_set(topol,i,j,top/bottom);\n\t\t\t\t\t\t\t\t\t\tgsl_matrix_int_set(moveType,i,j,1);\n\t\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t//afsObjectFree(delta);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\t//cleanup and free\n\tfor(i=0;instates * S->nstates;\n\ttCount = 0;\n\tdelta = afsObjectNewFrom(S->states[0]);\n\tfor(i=start;instates;j++){\n\t\t//\tprintf(\"nonzerocount=%d\\n\",nonZeroCount);\n\t\t\t\n\t\t\tif(S->states[i]->nalleles == 1){\n\t\t\t\t//set correct absorbing conditions\n\t\t\t\tif(i==j){\n\t\t\t\t\ttopol[nonZeroCount] = 1.0;\n\t\t\t\t\tmoveType[nonZeroCount] = -1;\n\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\telse{ //ith not root; what is the move?\n\t\t\t\tsteps = S->states[i]->nalleles - S->states[j]->nalleles ;\n\t\t\t\tif(steps < 2){\n\t\t\t\t\tdelta = afsObjectDelta(S->states[i],S->states[j]);\t\t\t\t\t\n\t\t\t\t\tswitch(steps){\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t// 0 \"steps\", so no changes in nalleles between two\n\t\t\t\t\t\t//check counts and positions\t\n\t\t\t\t\t\tif(abs(matrixSum(delta->popMats[0])) == 1){\n\t\t\t\t\t\t\tnonZeroEntries(delta->popMats[0], activePos1, &nlin1);\n\t\t\t\t\t\t\tnonZeroEntries(delta->popMats[1], activePos2, &nlin2);\n\n\t\t\t\t\t\t\t//migration?\n\t\t\t\t\t\t\tif(nlin1 == nlin2 && activePos1[0][0] == activePos2[0][0] &&\n\t\t\t\t\t\t\t\t(gsl_matrix_int_min(delta->popMats[0]) >= 0 || gsl_matrix_int_min(delta->popMats[1]) >= 0)){\n\n\t\t\t\t\t\t\t\t//migration popn1?\n\t\t\t\t\t\t\t\tif(matrixSum(delta->popMats[0]) == 1){\n\t\t\t\t\t\t\t\t\ttopol[nonZeroCount] = (double) gsl_matrix_int_get(S->states[i]->popMats[0],\n\t\t\t\t\t\t\t\t\t\tactivePos1[0][0], activePos1[0][1]) / S->states[i]->aCounts[0];\n\t\t\t\t\t\t\t\t\tmoveType[nonZeroCount] = 2;\n\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse{ //migration popn2\n\t\t\t\t\t\t\t\t\ttopol[nonZeroCount] = (double) gsl_matrix_int_get(S->states[i]->popMats[1],\n\t\t\t\t\t\t\t\t\t\tactivePos2[0][0],activePos2[0][1]) / S->states[i]->aCounts[1];\n\t\t\t\t\t\t\t\t\tmoveType[nonZeroCount] = 3;\n\n\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\tcase 1://coalescent?\n\t\t\t\t\t\t\t\t//coal popn1?\n\t\t\t\t\t\tif(matrixSum(delta->popMats[0]) == 1 && countNegativeEntries(delta->popMats[1]) == 0 && S->states[j]->aCounts[0] >= 1 ){\n\t\t\t\t\t\t\tentriesGreaterThan(delta->popMats[0], activePos1, &nlin1,0);//old lineages\n\t\t\t\t\t\t\tentriesLessThan(delta->popMats[0], activePos2, &nlin2,0);//new lineages\n\t\t\t\t\t\t\tif(nlin2 != 0 && nlin2 < 2){\n\n\t\t\t\t\t\t\t\tcompat=0;\n\t\t\t\t\t\t\t\tif(nlin1 == 1){\n\t\t\t\t\t\t\t\t\tif(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(nlin1==2){\n\t\t\t\t\t\t\t\t\tif(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] &&\n\t\t\t\t\t\t\t\t\t\tactivePos1[0][1] + activePos1[1][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(compat == 1){\n\t\t\t\t\t\t\t\t\ttop = 1.0;\n\t\t\t\t\t\t\t\t\tbottom = S->states[i]->aCounts[0] * (S->states[i]->aCounts[0]-1) /2.0 ;\n\t\t\t\t\t\t\t\t\tfor(k=0;kstates[i]->popMats[0],x,y),\n\t\t\t\t\t\t\t\t\t\t\tgsl_matrix_int_get(delta->popMats[0],x,y));\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\ttopol[nonZeroCount] = top/bottom;\n\t\t\t\t\t\t\t\t\tmoveType[nonZeroCount] = 0;\n\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} \n\t\t\t\t\t\telse{\n\t\t\t\t\t\t\tif(matrixSum(delta->popMats[1]) == 1 && countNegativeEntries(delta->popMats[0]) == 0 && S->states[j]->aCounts[1] >= 1 ){\n\t\t\t\t\t\t\t\tentriesGreaterThan(delta->popMats[1], activePos1, &nlin1,0);//old lineages\n\t\t\t\t\t\t\t\tentriesLessThan(delta->popMats[1], activePos2, &nlin2,0);//new lineages\n\t\t\t\t\t\t\t\tif(nlin2 != 0 && nlin2 < 2){\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcompat=0;\n\t\t\t\t\t\t\t\t\tif(nlin1 == 1){\n\t\t\t\t\t\t\t\t\t\tif(2*activePos1[0][0] == activePos2[0][0] && 2*activePos1[0][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(nlin1==2){\n\t\t\t\t\t\t\t\t\t\tif(activePos1[0][0] + activePos1[1][0] == activePos2[0][0] &&\n\t\t\t\t\t\t\t\t\t\t\tactivePos1[0][1] + activePos1[1][1] == activePos2[0][1])\n\t\t\t\t\t\t\t\t\t\t\tcompat = 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tif(compat == 1){\n\t\t\t\t\t\t\t\t\t\ttop = 1.0;\n\t\t\t\t\t\t\t\t\t\tbottom = S->states[i]->aCounts[1] * (S->states[i]->aCounts[1]-1) /2.0 ;\n\t\t\t\t\t\t\t\t\t\tfor(k=0;kstates[i]->popMats[1],x,y),\n\t\t\t\t\t\t\t\t\t\t\t\tgsl_matrix_int_get(delta->popMats[1],x,y));\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\ttopol[nonZeroCount] = top/bottom;\n\t\t\t\t\t\t\t\t\t\tmoveType[nonZeroCount] = 1;\n\t\t\t\t\t\t\t\t\t\tdim1[nonZeroCount] = i;\n\t\t\t\t\t\t\t\t\t\tdim2[nonZeroCount] = j;\n\t\t\t\t\t\t\t\t\t\tnonZeroCount += 1;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\t//afsObjectFree(delta);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t//cleanup and free\n\tfor(i=0;i\n#include \n#include \n\n#include \n#include \n\n#include \"common-driver-utils.h\"\n#include \"stokes_block_scaling.h\"\n#include \n#include \n#include \n#include \"Solvers/SLE/SLE.h\" /* to give the AugLagStokes_SLE type */\n#include \"Solvers/KSPSolvers/KSPSolvers.h\" /* for __KSP_COMMON */\n\n#include \"BSSCR.h\"\n#include \"writeMatVec.h\"\n\n/* creates and builds the \"checker-board\" null-space vectors for pressure\n and sets the t and v \"Vec pointers\" on the bsscr struct to point to them */\n#undef __FUNCT__\n#define __FUNCT__ \"KSPBuildPressure_CB_Nullspace_BSSCR\"\nPetscErrorCode KSPBuildPressure_CB_Nullspace_BSSCR(KSP ksp)\n{\n KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;\n FeEquationNumber *eq_num = bsscr->solver->st_sle->pSolnVec->eqNum;\n FeMesh *feMesh = bsscr->solver->st_sle->pSolnVec->feVariable->feMesh; /* is the pressure mesh */\n unsigned ijk[3];\n Vec t, v;\n int numLocalNodes, globalNodeNumber, i, j, eq;\n MatStokesBlockScaling BA = bsscr->BA;\n PetscErrorCode ierr;\n Mat Amat,Pmat, G;\n MatStructure pflag;\n\n PetscFunctionBegin;\n /* get G matrix from Amat matrix operator on ksp */\n ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);\n MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */\n /* now create Vecs t and v to match size of G: i.e. pressure */ /* NOTE: not using \"h\" vector from ksp->vec_rhs because this part of the block vector doesn't always exist */\n MatGetVecs( G, &t, PETSC_NULL );/* t and v are destroyed in KSPDestroy_BSSCR */\n MatGetVecs( G, &v, PETSC_NULL );/* t and v such that can do G*t */\n\n numLocalNodes = Mesh_GetLocalSize( feMesh, MT_VERTEX); /* number of nodes on current proc not counting any shadow nodes */\n for(j=0;jmapNodeDof2Eq[j][0];/* get global equation number -- 2nd arg is always 0 because pressure has only one dof */\n\tif(eq != -1){\n\t if( (ijk[0]+ijk[1]+ijk[2])%2 ==0 ){\n\t\tVecSetValue(t,eq,1.0,INSERT_VALUES);\n\t }\n\t else{\n\t\tVecSetValue(v,eq,1.0,INSERT_VALUES);\t }}}\n\n VecAssemblyBegin( t );\n VecAssemblyEnd( t );\n VecAssemblyBegin( v );\n VecAssemblyEnd( v );\n\n /* Scaling the null vectors here because it easier at the moment *//* maybe should do this in the original scaling function */\n if( BA->scaling_exists == PETSC_TRUE ){\n\tVec R2;\n\t/* Get the scalings out the block mat data */\n\tVecNestGetSubVec( BA->Rz, 1, &R2 );\n\tVecPointwiseDivide( t, t, R2); /* x <- x * 1/R2 */\n\tVecPointwiseDivide( v, v, R2);\n }\n\n // bsscr_writeVec( t, \"t\", \"Writing t vector\");\n // bsscr_writeVec( v, \"v\", \"Writing v vector\");\n\n bsscr->t=t;\n bsscr->v=v;\n\n PetscFunctionReturn(0);\n}\n/* creates and builds the \"constant\" null-space vector for pressure\n and sets the t \"Vec pointer\" on the bsscr struct to point to it */\n#undef __FUNCT__\n#define __FUNCT__ \"KSPBuildPressure_Const_Nullspace_BSSCR\"\nPetscErrorCode KSPBuildPressure_Const_Nullspace_BSSCR(KSP ksp)\n{\n KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;\n FeEquationNumber *eq_num = bsscr->solver->st_sle->pSolnVec->eqNum;\n FeMesh *feMesh = bsscr->solver->st_sle->pSolnVec->feVariable->feMesh; /* is the pressure mesh */\n unsigned ijk[3];\n Vec t;\n int numLocalNodes, globalNodeNumber, i, eq;\n MatStokesBlockScaling BA = bsscr->BA;\n PetscErrorCode ierr;\n Mat Amat,Pmat, G;\n MatStructure pflag;\n\n PetscFunctionBegin;\n /* get G matrix from Amat matrix operator on ksp */\n ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);\n MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */\n /* now create Vec t to match size of G: i.e. pressure */ /* NOTE: not using \"h\" vector from ksp->vec_rhs because this part of the block vector doesn't always exist */\n MatGetVecs( G, &t, PETSC_NULL );/* t is destroyed in KSPDestroy_BSSCR */\n\n VecSet(t, 1.0);\n\n VecAssemblyBegin( t );\n VecAssemblyEnd( t );\n\n /* Scaling the null vectors here because it easier at the moment */\n if( BA->scaling_exists == PETSC_TRUE ){\n\tVec R2;\n\t/* Get the scalings out the block mat data */\n\tVecNestGetSubVec( BA->Rz, 1, &R2 );\n\tVecPointwiseDivide( t, t, R2); /* x <- x * 1/R2 */\n }\n // bsscr_writeVec( t, \"t\", \"Writing t vector\");\n bsscr->t=t;\n\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"KSPRemovePressureNullspace_BSSCR\"\nPetscErrorCode KSPRemovePressureNullspace_BSSCR(KSP ksp, Vec h_hat)\n{\n KSP_BSSCR *bsscr = (KSP_BSSCR *)ksp->data;\n MatStokesBlockScaling BA = bsscr->BA;\n PetscErrorCode ierr;\n PetscScalar norm, a, a1, a2, hnorm, pnorm, gnorm;\n Vec t2, t,v;\n Mat Amat,Pmat, D;\n MatStructure pflag;\n double nstol = bsscr->nstol; /* set in KSPCreate_BSSCR */\n\n PetscFunctionBegin;\n t=bsscr->t;\n v=bsscr->v;\n /* get G matrix from Amat matrix operator on ksp */\n ierr=Stg_PCGetOperators(ksp->pc,&Amat,&Pmat,&pflag);CHKERRQ(ierr);\n //MatNestGetSubMat( Amat, 0,1, &G );/* G should always exist */\n MatNestGetSubMat( Amat, 1,0, &D );/* D should always exist */\n /* now create Vec t2 to match left hand size of G: i.e. velocity */\n MatGetVecs( D, &t2, PETSC_NULL );\n MatNorm(D,NORM_INFINITY,&gnorm); /* seems like not a bad estimate of the largest eigenvalue for this matrix */\n if(t){/* assumes that v and t are initially set to PETSC_NULL (in KSPCreate_BSSCR ) */\n\tMatMultTranspose( D, t, t2);\n\tVecNorm(t2, NORM_2, &norm);\n\tVecNorm(t, NORM_2, &a);\n\tnorm=norm/a;/* so we are using unit null vector */\n\tif(norm < nstol*gnorm){/* then t in NS of G */\n\t VecDot(t,h_hat, &a1);\n\t VecDot(t,t, &a2);\n\t a=-a1/a2;\n\t VecAXPY(h_hat, a, t);\n\t VecDot(t,h_hat, &a1);\n\t PetscPrintf( PETSC_COMM_WORLD, \"\\n\\t* Found t NS norm= %g : Dot = %g\\n\\n\", norm, a1);\n\t}\n }\n if(v){\n\tMatMultTranspose( D, v, t2);\n\tVecNorm(t2, NORM_2, &norm);\n\tVecNorm(v, NORM_2, &a);\n\tnorm=norm/a;/* so we are using unit null vector */\n\tif(norm < nstol*gnorm){/* then v in NS of G */\n\t VecDot(v,h_hat, &a1);\n\t VecDot(v,v, &a2);\n\t a=-a1/a2;\n\t VecAXPY(h_hat, a, v);\n\t VecDot(v,h_hat, &a1);\n\t PetscPrintf( PETSC_COMM_WORLD, \"\\n\\t* Found v NS norm= %g : Dot = %g\\n\\n\", norm, a1);\n\t}\n }\n // bsscr_writeVec( h_hat, \"h\", \"Writing h_hat Vector in Solver\");\n Stg_VecDestroy(&t2);\n\n PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "522d06726cca1a4bdd468d83ff29c02959bf5f20", "size": 7376, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/ksp_pressure_nullspace.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/ksp_pressure_nullspace.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/ksp_pressure_nullspace.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": 40.0869565217, "max_line_length": 177, "alphanum_fraction": 0.6161876356, "num_tokens": 2377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.29255872599718435}} {"text": "/**\n *\n * @file core_ztsrfb.c\n *\n * PLASMA core_blas kernel\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Azzam Haidar\n * @date 2010-11-15\n * @precisions normal z -> c d s\n *\n **/\n#include \n#include \n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex64_t\n *\n * CORE_ztsrfb applies a complex block reflector H or its transpose H' to a\n * complex rectangular matrix formed by coupling two tiles A1 and A2,\n * from either the left or the right.\n *\n *******************************************************************************\n *\n * @param[in] side\n * @arg PlasmaLeft : apply Q or Q**H from the Left;\n * @arg PlasmaRight : apply Q or Q**H from the Right.\n *\n * @param[in] trans\n * @arg PlasmaNoTrans : No transpose, apply Q;\n * @arg PlasmaConjTrans : ConjTranspose, apply Q**H.\n *\n * @param[in] direct\n * Indicates how H is formed from a product of elementary\n * reflectors\n * @arg PlasmaForward : H = H(1) H(2) . . . H(k) (Forward)\n * @arg PlasmaBackward : H = H(k) . . . H(2) H(1) (Backward)\n *\n * @param[in] storev\n * Indicates how the vectors which define the elementary\n * reflectors are stored:\n * @arg PlasmaColumnwise\n * @arg PlasmaRowwise\n *\n * @param[in] M1\n * The number of columns of the tile A1. M1 >= 0.\n *\n * @param[in] N1\n * The number of rows of the tile A1. N1 >= 0.\n *\n * @param[in] M2\n * The number of columns of the tile A2. M2 >= 0.\n *\n * @param[in] N2\n * The number of rows of the tile A2. N2 >= 0.\n *\n * @param[in] K\n * The order of the matrix T (= the number of elementary\n * reflectors whose product defines the block reflector).\n *\n * @param[in,out] A1\n * On entry, the M1-by-N1 tile A1.\n * On exit, A1 is overwritten by the application of Q.\n *\n * @param[in] LDA1\n * The leading dimension of the array A1. LDA1 >= max(1,N1).\n *\n * @param[in,out] A2\n * On entry, the M2-by-N2 tile A2.\n * On exit, A2 is overwritten by the application of Q.\n *\n * @param[in] LDA2\n * The leading dimension of the tile A2. LDA2 >= max(1,N2).\n *\n * @param[in] V\n * (LDV,K) if STOREV = 'C'\n * (LDV,M2) if STOREV = 'R' and SIDE = 'L'\n * (LDV,N2) if STOREV = 'R' and SIDE = 'R'\n * The matrix V.\n *\n * @param[in] LDV\n * The leading dimension of the array V.\n * If STOREV = 'C' and SIDE = 'L', LDV >= max(1,M2);\n * if STOREV = 'C' and SIDE = 'R', LDV >= max(1,N2);\n * if STOREV = 'R', LDV >= K.\n *\n * @param[out] T\n * The triangular K-by-K matrix T in the representation of the\n * block reflector.\n * T is upper triangular by block (economic storage);\n * The rest of the array is not referenced.\n *\n * @param[in] LDT\n * The leading dimension of the array T. LDT >= K.\n *\n * @param[in,out] WORK\n *\n * @param[in] LDWORK\n * The dimension of the array WORK.\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_ztsrfb = PCORE_ztsrfb\n#define CORE_ztsrfb PCORE_ztsrfb\n#endif\nint\nCORE_ztsrfb(PLASMA_enum side, PLASMA_enum trans, int direct, int storev,\n int M1, int N1, int M2, int N2, int K,\n PLASMA_Complex64_t *A1, int LDA1,\n PLASMA_Complex64_t *A2, int LDA2,\n const PLASMA_Complex64_t *V, int LDV,\n const PLASMA_Complex64_t *T, int LDT,\n PLASMA_Complex64_t *WORK, int LDWORK)\n{\n static PLASMA_Complex64_t zone = 1.0;\n static PLASMA_Complex64_t mzone = -1.0;\n\n int j;\n\n /* Check input arguments */\n if (M1 < 0) {\n coreblas_error(5, \"Illegal value of M1\");\n return -5;\n }\n if (N1 < 0) {\n coreblas_error(6, \"Illegal value of N1\");\n return -6;\n }\n if ( (M2 < 0) ||\n ( (M2 != M1) && (side == PlasmaRight) ) ){\n coreblas_error(7, \"Illegal value of M2\");\n return -7;\n }\n if ( (N2 < 0) ||\n ( (N2 != N1) && (side == PlasmaLeft) ) ){\n coreblas_error(8, \"Illegal value of N2\");\n return -8;\n }\n if (K < 0) {\n coreblas_error(9, \"Illegal value of K\");\n return -9;\n }\n\n /* Quick return */\n if ((M1 == 0) || (N1 == 0) || (M2 == 0) || (N2 == 0) || (K == 0))\n return PLASMA_SUCCESS;\n\n if (storev == PlasmaColumnwise) {\n if (direct == PlasmaForward) {\n if (side == PlasmaLeft) {\n /*\n * B = A1 + V' * A2\n */\n LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,\n lapack_const(PlasmaUpperLower),\n K, N1,\n A1, LDA1, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasConjTrans, CblasNoTrans,\n K, N2, M2,\n CBLAS_SADDR(zone), V, LDV,\n A2, LDA2,\n CBLAS_SADDR(zone), WORK, LDWORK);\n /*\n * A2 = A2 - V*T*B -> B = T*B, A2 = A2 - V*B\n */\n cblas_ztrmm(\n CblasColMajor, CblasLeft, CblasUpper,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, K, N2,\n CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasNoTrans, CblasNoTrans,\n M2, N2, K,\n CBLAS_SADDR(mzone), V, LDV,\n WORK, LDWORK,\n CBLAS_SADDR(zone), A2, LDA2);\n /*\n * A1 = A1 - B\n */\n for(j = 0; j < N1; j++) {\n cblas_zaxpy(\n K, CBLAS_SADDR(mzone),\n &WORK[LDWORK*j], 1,\n &A1[LDA1*j], 1);\n }\n }\n /*\n * Columnwise / Forward / Right\n */\n else {\n /*\n * B = A1 + A2 * V\n */\n LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,\n lapack_const(PlasmaUpperLower),\n M1, K,\n A1, LDA1, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasNoTrans, CblasNoTrans,\n M2, K, N2,\n CBLAS_SADDR(zone), A2, LDA2,\n V, LDV,\n CBLAS_SADDR(zone), WORK, LDWORK);\n /*\n * A2 = A2 - B*T*V' -> B = B*T, A2 = A2 - B*V'\n */\n cblas_ztrmm(\n CblasColMajor, CblasRight, CblasUpper,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, M1, K,\n CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasNoTrans, CblasConjTrans,\n M2, N2, K,\n CBLAS_SADDR(mzone), WORK, LDWORK,\n V, LDV,\n CBLAS_SADDR(zone), A2, LDA2);\n /*\n * A1 = A1 - B\n */\n for(j = 0; j < K; j++) {\n cblas_zaxpy(\n M1, CBLAS_SADDR(mzone),\n &WORK[LDWORK*j], 1,\n &A1[LDA1*j], 1);\n }\n }\n }\n else {\n coreblas_error(3, \"Not implemented (ColMajor / Backward / Left or Right)\");\n return PLASMA_ERR_NOT_SUPPORTED;\n }\n }\n else {\n if (direct == PlasmaForward) {\n /*\n * Rowwise / Forward / Left\n */\n if (side == PlasmaLeft) {\n /*\n * B = A1 + V * A2\n */\n LAPACKE_zlacpy_work(LAPACK_COL_MAJOR,\n lapack_const(PlasmaUpperLower),\n K, N1,\n A1, LDA1, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasNoTrans, CblasNoTrans,\n K, N2, M2,\n CBLAS_SADDR(zone), V, LDV,\n A2, LDA2,\n CBLAS_SADDR(zone), WORK, LDWORK);\n /*\n * A2 = A2 - V'*T*B -> B = T*B, A2 = A2 - V'*B\n */\n cblas_ztrmm(\n CblasColMajor, CblasLeft, CblasUpper,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, K, N2,\n CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasConjTrans, CblasNoTrans,\n M2, N2, K,\n CBLAS_SADDR(mzone), V, LDV,\n WORK, LDWORK,\n CBLAS_SADDR(zone), A2, LDA2);\n /*\n * A1 = A1 - B\n */\n for(j=0; j B = B*T, A2 = A2 - B*V'\n */\n cblas_ztrmm(\n CblasColMajor, CblasRight, CblasUpper,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, M1, K,\n CBLAS_SADDR(zone), T, LDT, WORK, LDWORK);\n\n cblas_zgemm(\n CblasColMajor, CblasNoTrans, CblasNoTrans,\n M2, N2, K,\n CBLAS_SADDR(mzone), WORK, LDWORK,\n V, LDV,\n CBLAS_SADDR(zone), A2, LDA2);\n /*\n * A1 = A1 - B\n */\n for(j = 0; j < K; j++) {\n cblas_zaxpy(\n M1, CBLAS_SADDR(mzone),\n &WORK[LDWORK*j], 1,\n &A1[LDA1*j], 1);\n }\n }\n }\n else {\n coreblas_error(3, \"Not implemented (RowMajor / Backward / Left or Right)\");\n return PLASMA_ERR_NOT_SUPPORTED;\n }\n }\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "022273d071b019fcdac0a4d8308451c8ee9e25f6", "size": 11246, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_ztsrfb.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_ztsrfb.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_ztsrfb.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7871720117, "max_line_length": 87, "alphanum_fraction": 0.4319758136, "num_tokens": 3055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.29243506406617575}} {"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\nvoid analyze_MCMC(MCMC_info *MCMC) {\n char filename_output_dir[SID_MAX_FILENAME_LENGTH];\n char filename_chain_dir[SID_MAX_FILENAME_LENGTH];\n char filename_results_dir[SID_MAX_FILENAME_LENGTH];\n char filename_plots_dir[SID_MAX_FILENAME_LENGTH];\n char filename_run[SID_MAX_FILENAME_LENGTH];\n char filename_chain[SID_MAX_FILENAME_LENGTH];\n char filename_chain_config[SID_MAX_FILENAME_LENGTH];\n char filename_stats[SID_MAX_FILENAME_LENGTH];\n char filename_coverage[SID_MAX_FILENAME_LENGTH];\n char filename_chain_covariance[SID_MAX_FILENAME_LENGTH];\n char filename_covariance[SID_MAX_FILENAME_LENGTH];\n char filename_histograms[SID_MAX_FILENAME_LENGTH];\n char filename_results[SID_MAX_FILENAME_LENGTH];\n char filename_stop[SID_MAX_FILENAME_LENGTH];\n char column_txt[SID_MAX_FILENAME_LENGTH];\n char problem_name_test[MCMC_NAME_SIZE];\n char P_name_test[MCMC_NAME_SIZE];\n char name_test[MCMC_NAME_SIZE];\n char array_name_test[MCMC_NAME_SIZE];\n char array_name_temp[MCMC_NAME_SIZE];\n int n_avg_test;\n int flag_autocor_on_test;\n int flag_no_map_write;\n int n_P_test;\n int n_DS_test;\n int n_arrays_test;\n int n_M_test;\n double P_init_test;\n double M_target_test;\n double dM_target_test;\n int i_P, j_P, k_P;\n int i_M, j_M;\n int ii_P, jj_P;\n int i_avg;\n int i_C;\n int i_DS, n_DS;\n int i_iteration, j_iteration;\n int flag_continue;\n char flag_success;\n int flag_stop = GBP_FALSE;\n int i_coverage;\n int j_coverage;\n int i_proposal;\n int bin_x;\n int bin_y;\n int n_avg;\n int n_avg_burn;\n int n_avg_integrate;\n int n_P, n_C;\n int n_gals;\n size_t n_success, n_fail;\n size_t n_success_all, n_fail_all;\n double * x_P;\n double ** x_M;\n double * M_target;\n double * dM_target;\n double * V;\n double ** C;\n double * P_min;\n double * P_max;\n double * P_new;\n double * P_last;\n double * P_avg;\n double * dP_avg;\n double ** M_best;\n double ** M_best_parameters;\n double ** M_peak_parameters;\n double * ln_likelihood_DS_peak;\n double * ln_likelihood_DS_best;\n size_t n_residual;\n double * residual;\n double ** M_min;\n double ** M_max;\n double ** M_new;\n double ** M_lo_68;\n double ** M_hi_68;\n double ** M_lo_95;\n double ** M_hi_95;\n size_t *** M_histogram;\n double ** M_last;\n double ** M_avg;\n double ** dM_avg;\n size_t ** P_histogram;\n size_t ** coverage_true;\n size_t ** coverage_false;\n size_t ** coverage_keep;\n double ** mean_L_histogram;\n double ** max_L_histogram;\n uint64_t * temp_out;\n double ** max_L_surface;\n double ** mean_L_surface;\n double L_x, L_y, L_z;\n int n_x, n_y, n_z;\n int n_C_x;\n double ln_likelihood_new;\n double ln_likelihood_last;\n double ln_likelihood_best;\n double ln_likelihood_peak;\n FILE * fp_run;\n FILE * fp_chain;\n FILE * fp_chain_config;\n FILE * fp_stats;\n FILE * fp_coverage;\n FILE * fp_chain_covariance;\n FILE * fp_covariance;\n FILE * fp_histograms;\n FILE * fp_results;\n FILE * fp_stop;\n int seed = 182743;\n int i_report;\n int i_iteration_start;\n int i_iteration_next_report;\n int n_accepted;\n int n_active;\n int n_iterations;\n int n_iterations_burn;\n int n_iterations_integrate;\n int n_iterations_phase;\n int n_thin;\n int n_thin_burn;\n int n_thin_integrate;\n int i_thin;\n double temperature;\n int flag_autocor_on;\n int n_coverage;\n int coverage_size;\n int i_phase;\n int i_array;\n int * n_M;\n int flag_initialized;\n int n_used;\n gsl_matrix * m;\n gsl_vector * b;\n double RN;\n MCMC_DS_info *current_DS;\n MCMC_DS_info *next_DS;\n double *** M_arrays;\n double *** P_arrays;\n int * n_P_arrays;\n int * n_M_arrays;\n double constant;\n size_t * histogram_index;\n size_t * coverage_keep_index;\n size_t P_best_index;\n size_t M_best_index;\n double accumulator;\n size_t P_lo_68_index;\n size_t P_hi_68_index;\n size_t P_lo_95_index;\n size_t P_hi_95_index;\n size_t M_lo_68_index;\n size_t M_hi_68_index;\n size_t M_lo_95_index;\n size_t M_hi_95_index;\n double * P_lo_68;\n double * P_hi_68;\n double * P_lo_95;\n double * P_hi_95;\n double * P_contour_68;\n double * P_contour_95;\n double * P_best;\n double * P_peak;\n int my_chain;\n int flag_init;\n int i_column;\n int dummy_t;\n double * P_i_bar_accum;\n double * P_ij_bar_accum;\n double * P_i_bar;\n double * P_ij_bar;\n double * V_compute;\n int n_covariance;\n int i_covariance;\n int j_covariance;\n int n_iterations_file_total;\n int n_iterations_file_burn;\n int flag_restart = GBP_FALSE;\n int size_temp1;\n int size_temp2[2];\n\n int flag_minimize_IO;\n size_t i_iteration_buffer;\n size_t i_P_buffer;\n size_t i_M_buffer;\n\n SID_log(\"Performing MCMC analysis...\", SID_LOG_OPEN | SID_LOG_TIMER);\n\n SID_log(\"Initializing...\", SID_LOG_OPEN);\n\n // Initialize dataset arrays\n init_MCMC_arrays(MCMC);\n\n // Initialize some constants etc.\n n_P = MCMC->n_P;\n n_DS = MCMC->n_DS;\n n_avg = MCMC->n_avg;\n my_chain = MCMC->my_chain;\n n_iterations = MCMC->n_iterations;\n n_iterations_burn = MCMC->n_iterations_burn;\n n_iterations_integrate = n_iterations - n_iterations_burn;\n n_thin = MCMC->n_thin;\n coverage_size = MCMC->coverage_size;\n flag_autocor_on = MCMC->flag_autocor_on;\n flag_no_map_write = MCMC->flag_no_map_write;\n flag_minimize_IO = SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_MINIMIZE_IO);\n\n // Initialize arrays used for computing the covariance matrix\n P_i_bar_accum = (double *)SID_malloc(sizeof(double) * n_P);\n P_ij_bar_accum = (double *)SID_malloc(sizeof(double) * n_P * n_P);\n P_i_bar = (double *)SID_malloc(sizeof(double) * n_P);\n P_ij_bar = (double *)SID_malloc(sizeof(double) * n_P * n_P);\n V_compute = (double *)SID_malloc(sizeof(double) * n_P * n_P);\n for(i_P = 0, k_P = 0; i_P < n_P; i_P++) {\n P_i_bar_accum[i_P] = 0.;\n P_i_bar[i_P] = 0.;\n for(j_P = 0; j_P < n_P; j_P++, k_P++) {\n P_ij_bar_accum[k_P] = 0.;\n P_ij_bar[k_P] = 0.;\n if(i_P == j_P)\n V_compute[k_P] = 1.;\n else\n V_compute[k_P] = 0.;\n }\n }\n\n // Initialize chain arrays etc\n n_M = MCMC->n_M;\n M_new = MCMC->M_new;\n M_last = MCMC->M_last;\n n_M_arrays = (int *)SID_malloc(sizeof(int) * n_DS);\n M_arrays = (double ***)SID_malloc(sizeof(double **) * n_DS);\n current_DS = MCMC->DS;\n i_DS = 0;\n while(current_DS != NULL) {\n next_DS = current_DS->next;\n n_M[i_DS] = current_DS->n_M;\n n_M_arrays[i_DS] = current_DS->n_arrays;\n M_arrays[i_DS] = current_DS->array;\n current_DS = next_DS;\n i_DS++;\n }\n P_new = MCMC->P_new;\n P_last = MCMC->P_last;\n\n // Set default directories\n sprintf(filename_output_dir, \"%s/\", MCMC->filename_output_dir);\n sprintf(filename_chain_dir, \"%s/chains/\", filename_output_dir);\n sprintf(filename_results_dir, \"%s/results/\", filename_output_dir);\n sprintf(filename_plots_dir, \"%s/plots/\", filename_output_dir);\n\n // Set default filenames\n sprintf(filename_run, \"%s/run.dat\", filename_output_dir);\n sprintf(filename_chain, \"%s/chain_trace_%06d.dat\", filename_chain_dir, my_chain);\n sprintf(filename_chain_config, \"%s/chain_config_%06d.dat\", filename_chain_dir, my_chain);\n sprintf(filename_chain_covariance, \"%s/chain_covariance_%06d.dat\", filename_chain_dir, my_chain);\n sprintf(filename_stats, \"%s/chain_stats_%06d.dat\", filename_chain_dir, my_chain);\n sprintf(filename_coverage, \"%s/coverage.dat\", filename_results_dir);\n sprintf(filename_histograms, \"%s/histograms.dat\", filename_results_dir);\n sprintf(filename_covariance, \"%s/covariance.dat\", filename_results_dir);\n sprintf(filename_stop, \"%s/stop\", filename_output_dir);\n\n // Initialize coverage arrays\n for(i_P = 0, n_coverage = 0; i_P < n_P; i_P++) {\n for(j_P = i_P + 1; j_P < n_P; j_P++)\n n_coverage++;\n }\n P_min = MCMC->P_min;\n P_max = MCMC->P_max;\n P_avg = MCMC->P_avg;\n dP_avg = MCMC->dP_avg;\n P_best = MCMC->P_best;\n P_peak = MCMC->P_peak;\n P_lo_68 = MCMC->P_lo_68;\n P_hi_68 = MCMC->P_hi_68;\n P_lo_95 = MCMC->P_lo_95;\n P_hi_95 = MCMC->P_hi_95;\n P_contour_68 = (double *)SID_malloc(sizeof(double) * n_coverage);\n P_contour_95 = (double *)SID_malloc(sizeof(double) * n_coverage);\n P_histogram = (size_t **)SID_malloc(sizeof(size_t *) * n_P);\n mean_L_histogram = (double **)SID_malloc(sizeof(double *) * n_P);\n max_L_histogram = (double **)SID_malloc(sizeof(double *) * n_P);\n for(i_P = 0; i_P < n_P; i_P++) {\n P_histogram[i_P] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size);\n mean_L_histogram[i_P] = (double *)SID_malloc(sizeof(double) * coverage_size);\n max_L_histogram[i_P] = (double *)SID_malloc(sizeof(double) * coverage_size);\n P_min[i_P] = DBL_MAX;\n P_max[i_P] = -DBL_MAX;\n P_avg[i_P] = 0.;\n dP_avg[i_P] = 0.;\n for(j_P = 0; j_P < coverage_size; j_P++) {\n P_histogram[i_P][j_P] = 0;\n mean_L_histogram[i_P][j_P] = 0.;\n max_L_histogram[i_P][j_P] = -1e10;\n }\n }\n M_best = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_best_parameters = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_peak_parameters = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_min = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_max = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_lo_68 = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_hi_68 = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_lo_95 = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_hi_95 = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_avg = (double **)SID_malloc(sizeof(double *) * n_DS);\n dM_avg = (double **)SID_malloc(sizeof(double *) * n_DS);\n M_histogram = (size_t ***)SID_malloc(sizeof(size_t **) * n_DS);\n\n current_DS = MCMC->DS;\n for(i_DS = 0, n_residual = 0; i_DS < n_DS; i_DS++) {\n next_DS = current_DS->next;\n if(current_DS->M_best == NULL)\n current_DS->M_best = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_best_parameters == NULL)\n current_DS->M_best_parameters = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_peak_parameters == NULL)\n current_DS->M_peak_parameters = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_min == NULL)\n current_DS->M_min = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_max == NULL)\n current_DS->M_max = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_lo_68 == NULL)\n current_DS->M_lo_68 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_hi_68 == NULL)\n current_DS->M_hi_68 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_lo_95 == NULL)\n current_DS->M_lo_95 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_hi_95 == NULL)\n current_DS->M_hi_95 = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->M_avg == NULL)\n current_DS->M_avg = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n if(current_DS->dM_avg == NULL)\n current_DS->dM_avg = (double *)SID_malloc(sizeof(double) * n_M[i_DS]);\n M_best[i_DS] = current_DS->M_best;\n M_best_parameters[i_DS] = current_DS->M_best_parameters;\n M_peak_parameters[i_DS] = current_DS->M_peak_parameters;\n M_min[i_DS] = current_DS->M_min;\n M_max[i_DS] = current_DS->M_max;\n M_lo_68[i_DS] = current_DS->M_lo_68;\n M_hi_68[i_DS] = current_DS->M_hi_68;\n M_lo_95[i_DS] = current_DS->M_lo_95;\n M_hi_95[i_DS] = current_DS->M_hi_95;\n M_avg[i_DS] = current_DS->M_avg;\n dM_avg[i_DS] = current_DS->dM_avg;\n M_histogram[i_DS] = (size_t **)SID_malloc(sizeof(size_t *) * n_M[i_DS]);\n for(i_M = 0; i_M < n_M[i_DS]; i_M++) {\n M_histogram[i_DS][i_M] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size);\n M_avg[i_DS][i_M] = 0.;\n dM_avg[i_DS][i_M] = 0.;\n M_min[i_DS][i_M] = DBL_MAX;\n M_max[i_DS][i_M] = -DBL_MAX;\n for(j_M = 0; j_M < coverage_size; j_M++)\n M_histogram[i_DS][i_M][j_M] = 0;\n }\n n_residual = GBP_MAX(n_residual, (size_t)n_M[i_DS]);\n current_DS = next_DS;\n }\n if(next_DS != NULL)\n SID_exit_error(\"Invalid dataset count in analyze_MCMC().\", SID_ERROR_LOGIC);\n residual = (double *)SID_malloc(sizeof(double) * n_residual);\n coverage_true = (size_t **)SID_malloc(sizeof(size_t *) * n_coverage);\n coverage_false = (size_t **)SID_malloc(sizeof(size_t *) * n_coverage);\n coverage_keep = (size_t **)SID_malloc(sizeof(size_t *) * n_coverage);\n max_L_surface = (double **)SID_malloc(sizeof(double *) * n_coverage);\n mean_L_surface = (double **)SID_malloc(sizeof(double *) * n_coverage);\n for(i_coverage = 0; i_coverage < n_coverage; i_coverage++) {\n coverage_true[i_coverage] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size * coverage_size);\n coverage_false[i_coverage] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size * coverage_size);\n coverage_keep[i_coverage] = (size_t *)SID_malloc(sizeof(size_t) * coverage_size * coverage_size);\n max_L_surface[i_coverage] = (double *)SID_malloc(sizeof(double) * coverage_size * coverage_size);\n mean_L_surface[i_coverage] = (double *)SID_malloc(sizeof(double) * coverage_size * coverage_size);\n for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++) {\n coverage_true[i_coverage][j_coverage] = 0;\n coverage_false[i_coverage][j_coverage] = 0;\n coverage_keep[i_coverage][j_coverage] = 0;\n max_L_surface[i_coverage][j_coverage] = -1e10;\n mean_L_surface[i_coverage][j_coverage] = 0.;\n }\n }\n temp_out = (uint64_t *)SID_malloc(sizeof(uint64_t) * coverage_size * coverage_size);\n SID_log(\"Done.\", SID_LOG_CLOSE);\n\n // Process the chain(s)\n SID_log(\"Process chain file(s)...\", SID_LOG_OPEN);\n if(flag_no_map_write)\n SID_log(\"Mapping results are *not* available.\", SID_LOG_COMMENT);\n else\n SID_log(\"Mapping results are available.\", SID_LOG_COMMENT);\n\n // Count the number of runs we will analyze\n int n_runs;\n int i_run;\n if(flag_minimize_IO || !SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_ANALYZE_ALL_RUNS))\n n_runs = 1;\n else {\n int flag_continue = GBP_TRUE;\n while(flag_continue) {\n // Set chain filename\n if(n_runs == 0)\n sprintf(filename_output_dir, \"%s/\", MCMC->filename_output_root);\n else\n sprintf(filename_output_dir, \"%s.%d/\", MCMC->filename_output_root, n_runs);\n sprintf(filename_chain_dir, \"%s/chains/\", filename_output_dir);\n sprintf(filename_chain, \"%s/chain_trace_%06d.dat\", filename_chain_dir, my_chain);\n if((fp_chain = fopen(filename_chain, \"r\")) != NULL) {\n n_runs++;\n fclose(fp_chain);\n } else\n flag_continue = GBP_FALSE;\n }\n SID_log(\"Analyzing %d chain(s).\", SID_LOG_COMMENT, n_runs);\n }\n\n if(my_chain == SID.My_rank) {\n // Loop over all the chains\n for(i_run = 0, n_used = 0; i_run < n_runs; i_run++) {\n if(!flag_minimize_IO) {\n // Set chain filename (use default if we are not analyzing all runs)\n if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_ANALYZE_ALL_RUNS)) {\n if(i_run == 0)\n sprintf(filename_output_dir, \"%s/\", MCMC->filename_output_root);\n else\n sprintf(filename_output_dir, \"%s.%d/\", MCMC->filename_output_root, i_run);\n sprintf(filename_chain_dir, \"%s/chains/\", filename_output_dir);\n sprintf(filename_chain, \"%s/chain_trace_%06d.dat\", filename_chain_dir, my_chain);\n sprintf(filename_chain_config, \"%s/chain_config_%06d.dat\", filename_chain_dir, my_chain);\n }\n\n // Read number of iterations\n if((fp_chain = fopen(filename_chain_config, \"rb\")) == NULL)\n SID_exit_error(\"Could not open chain configuration file {%s}.\", SID_ERROR_IO_OPEN,\n filename_chain_config);\n SID_fread_verify(&n_iterations, sizeof(int), 1, fp_chain);\n SID_fread_verify(&n_iterations_burn, sizeof(int), 1, fp_chain);\n fclose(fp_chain);\n\n // Open chain file\n if((fp_chain = fopen(filename_chain, \"rb\")) == NULL)\n SID_exit_error(\"Could not open chain file {%s}.\", SID_ERROR_IO_OPEN, filename_chain);\n }\n i_iteration_buffer = 0;\n i_P_buffer = 0;\n i_M_buffer = 0;\n ln_likelihood_peak = -1e20;\n for(i_iteration = 0, flag_init = GBP_TRUE; i_iteration < n_iterations; i_iteration++) {\n for(i_avg = 0; i_avg < n_avg; i_avg++) {\n switch(flag_minimize_IO) {\n case GBP_TRUE:\n flag_success = MCMC->flag_success_buffer[i_iteration_buffer];\n ln_likelihood_new = MCMC->ln_likelihood_new_buffer[i_iteration_buffer];\n i_iteration_buffer++;\n memcpy(P_new, &(MCMC->P_new_buffer[i_P_buffer]), (size_t)n_P * sizeof(double));\n i_P_buffer += n_P;\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n memcpy(M_new[i_DS], &(MCMC->M_new_buffer[i_M_buffer]), (size_t)n_M[i_DS] * sizeof(double));\n i_M_buffer += n_M[i_DS];\n }\n }\n break;\n default:\n SID_fread_verify(&flag_success, sizeof(char), 1, fp_chain);\n SID_fread_verify(&ln_likelihood_new, sizeof(double), 1, fp_chain);\n SID_fread_verify(P_new, sizeof(double), n_P, fp_chain);\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++)\n SID_fread_verify(M_new[i_DS], sizeof(double), n_M[i_DS], fp_chain);\n }\n break;\n }\n if(i_iteration >= n_iterations_burn) {\n if(flag_init || flag_success) {\n memcpy(P_last, P_new, (size_t)n_P * sizeof(double));\n ln_likelihood_last = ln_likelihood_new;\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++)\n memcpy(M_last[i_DS], M_new[i_DS], (size_t)n_M[i_DS] * sizeof(double));\n }\n flag_init = GBP_FALSE;\n }\n n_used++;\n // Compute covariance matrix\n for(i_P = 0, k_P = 0; i_P < n_P; i_P++) {\n P_i_bar_accum[i_P] += P_last[i_P];\n for(j_P = 0; j_P < n_P; j_P++, k_P++)\n P_ij_bar_accum[k_P] += P_last[i_P] * P_last[j_P];\n }\n\n // Compute parameter extrema and averages\n for(i_P = 0; i_P < n_P; i_P++) {\n if(P_last[i_P] < P_min[i_P])\n P_min[i_P] = P_last[i_P];\n if(P_last[i_P] > P_max[i_P])\n P_max[i_P] = P_last[i_P];\n P_avg[i_P] += P_last[i_P];\n }\n\n // Store parameters with highest likelihood\n if(ln_likelihood_last > ln_likelihood_peak) {\n memcpy(P_peak, P_last, (size_t)n_P * sizeof(double));\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++)\n memcpy(M_peak_parameters[i_DS], M_last[i_DS], (size_t)n_M[i_DS] * sizeof(double));\n }\n ln_likelihood_peak = ln_likelihood_last;\n }\n\n // Compute mapping-space extrema and averages\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++) {\n if(M_last[i_DS][i_M] < M_min[i_DS][i_M])\n M_min[i_DS][i_M] = M_last[i_DS][i_M];\n if(M_last[i_DS][i_M] > M_max[i_DS][i_M])\n M_max[i_DS][i_M] = M_last[i_DS][i_M];\n M_avg[i_DS][i_M] += M_last[i_DS][i_M];\n }\n }\n }\n }\n }\n }\n if(!flag_minimize_IO)\n fclose(fp_chain);\n }\n\n // Finish averages\n for(i_P = 0; i_P < n_P; i_P++) {\n P_avg[i_P] /= (double)n_used;\n }\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++)\n M_avg[i_DS][i_M] /= (double)n_used;\n }\n }\n\n for(i_run = 0; i_run < n_runs; i_run++) {\n if(!flag_minimize_IO) {\n // Set chain filename (use default if we are not analyzing all runs)\n if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_ANALYZE_ALL_RUNS)) {\n if(i_run == 0)\n sprintf(filename_output_dir, \"%s/\", MCMC->filename_output_root);\n else\n sprintf(filename_output_dir, \"%s.%d/\", MCMC->filename_output_root, i_run);\n sprintf(filename_chain_dir, \"%s/chains/\", filename_output_dir);\n sprintf(filename_chain, \"%s/chain_trace_%06d.dat\", filename_chain_dir, my_chain);\n sprintf(filename_chain_config, \"%s/chain_config_%06d.dat\", filename_chain_dir, my_chain);\n }\n\n // Read number of iterations\n if((fp_chain = fopen(filename_chain_config, \"rb\")) == NULL)\n SID_exit_error(\"Could not open chain configuration file {%s}.\", SID_ERROR_IO_OPEN, filename_chain);\n SID_fread_verify(&n_iterations, sizeof(int), 1, fp_chain);\n SID_fread_verify(&n_iterations_burn, sizeof(int), 1, fp_chain);\n fclose(fp_chain);\n\n // Open chain file\n if((fp_chain = fopen(filename_chain, \"rb\")) == NULL)\n SID_exit_error(\"Could not open chain file {%s}.\", SID_ERROR_IO_OPEN, filename_chain);\n }\n i_iteration_buffer = 0;\n i_P_buffer = 0;\n i_M_buffer = 0;\n for(i_iteration = 0, flag_init = GBP_TRUE; i_iteration < n_iterations; i_iteration++) {\n for(i_avg = 0; i_avg < n_avg; i_avg++) {\n switch(flag_minimize_IO) {\n case GBP_TRUE:\n flag_success = MCMC->flag_success_buffer[i_iteration_buffer];\n ln_likelihood_new = MCMC->ln_likelihood_new_buffer[i_iteration_buffer];\n i_iteration_buffer++;\n memcpy(P_new, &(MCMC->P_new_buffer[i_P_buffer]), (size_t)n_P * sizeof(double));\n i_P_buffer += n_P;\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n memcpy(M_new[i_DS], &(MCMC->M_new_buffer[i_M_buffer]), (size_t)n_M[i_DS] * sizeof(double));\n i_M_buffer += n_M[i_DS];\n }\n }\n break;\n default:\n SID_fread_verify(&flag_success, sizeof(char), 1, fp_chain);\n SID_fread_verify(&ln_likelihood_new, sizeof(double), 1, fp_chain);\n SID_fread_verify(P_new, sizeof(double), n_P, fp_chain);\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++)\n SID_fread_verify(M_new[i_DS], sizeof(double), n_M[i_DS], fp_chain);\n }\n break;\n }\n if(i_iteration >= n_iterations_burn) {\n if(flag_init || flag_success) {\n memcpy(P_last, P_new, (size_t)n_P * sizeof(double));\n ln_likelihood_last = ln_likelihood_new;\n for(i_DS = 0; i_DS < n_DS; i_DS++)\n memcpy(M_last[i_DS], M_new[i_DS], (size_t)n_M[i_DS] * sizeof(double));\n flag_init = GBP_FALSE;\n }\n // Build coverage maps\n if(flag_success) {\n for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) {\n bin_x = (int)((double)(coverage_size) * (P_last[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P]));\n for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) {\n bin_y = (int)((double)(coverage_size) * (P_last[j_P] - P_min[j_P]) / (P_max[j_P] - P_min[j_P]));\n if(bin_x >= 0 && bin_x < coverage_size && bin_y >= 0 && bin_y < coverage_size)\n coverage_true[i_coverage][bin_x * coverage_size + bin_y]++;\n }\n }\n } else {\n for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) {\n bin_x = (int)((double)(coverage_size) * (P_new[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P]));\n for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) {\n bin_y = (int)((double)(coverage_size) * (P_new[j_P] - P_min[j_P]) / (P_max[j_P] - P_min[j_P]));\n if(bin_x >= 0 && bin_x < coverage_size && bin_y >= 0 && bin_y < coverage_size)\n coverage_false[i_coverage][bin_x * coverage_size + bin_y]++;\n }\n }\n }\n for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) {\n bin_x = (int)((double)(coverage_size) * (P_last[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P]));\n for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) {\n bin_y = (int)((double)(coverage_size) * (P_last[j_P] - P_min[j_P]) / (P_max[j_P] - P_min[j_P]));\n if(bin_x >= 0 && bin_x < coverage_size && bin_y >= 0 && bin_y < coverage_size) {\n coverage_keep[i_coverage][bin_x * coverage_size + bin_y]++;\n max_L_surface[i_coverage][bin_x * coverage_size + bin_y] =\n GBP_MAX(max_L_surface[i_coverage][bin_x * coverage_size + bin_y], ln_likelihood_last);\n mean_L_surface[i_coverage][bin_x * coverage_size + bin_y] += ln_likelihood_last;\n }\n }\n }\n\n // Build histograms\n for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) {\n bin_x = (int)((double)(coverage_size) * (P_last[i_P] - P_min[i_P]) / (P_max[i_P] - P_min[i_P]));\n if(bin_x >= 0 && bin_x < coverage_size) {\n P_histogram[i_P][bin_x]++;\n mean_L_histogram[i_P][bin_x] += ln_likelihood_last;\n max_L_histogram[i_P][bin_x] = GBP_MAX(max_L_histogram[i_P][bin_x], ln_likelihood_last);\n }\n }\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++) {\n bin_x =\n (int)((double)(coverage_size) * (M_last[i_DS][i_M] - M_min[i_DS][i_M]) / (M_max[i_DS][i_M] - M_min[i_DS][i_M]));\n if(bin_x >= 0 && bin_x < coverage_size)\n M_histogram[i_DS][i_M][bin_x]++;\n }\n }\n\n // Compute parameter standard deviations\n for(i_P = 0; i_P < n_P; i_P++) {\n dP_avg[i_P] += pow(P_last[i_P] - P_avg[i_P], 2.);\n }\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++)\n dM_avg[i_DS][i_M] += pow(M_last[i_DS][i_M] - M_avg[i_DS][i_M], 2.);\n }\n }\n }\n }\n } // i_iteration\n if(!flag_minimize_IO)\n fclose(fp_chain);\n }\n SID_log(\"Number of used propositions: %d\", SID_LOG_COMMENT, n_used);\n\n // Finish mean likelihood histograms & surfaces\n for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) {\n for(j_coverage = 0; j_coverage < coverage_size; j_coverage++)\n mean_L_histogram[i_P][j_coverage] /= (double)P_histogram[i_P][j_coverage];\n for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) {\n for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++)\n mean_L_surface[i_coverage][j_coverage] /= (double)coverage_keep[i_coverage][j_coverage];\n }\n }\n\n // Finish standard deviations\n for(i_P = 0; i_P < n_P; i_P++)\n dP_avg[i_P] = sqrt(dP_avg[i_P] / (double)n_used);\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++)\n dM_avg[i_DS][i_M] = sqrt(dM_avg[i_DS][i_M] / (double)n_used);\n }\n }\n\n // Finish covariance matrix\n for(i_P = 0; i_P < n_P; i_P++)\n P_i_bar[i_P] = P_i_bar_accum[i_P] / (double)n_used;\n for(i_P = 0, k_P = 0; i_P < n_P; i_P++) {\n for(j_P = 0; j_P < n_P; j_P++, k_P++) {\n P_ij_bar[k_P] = P_ij_bar_accum[k_P] / (double)n_used;\n V_compute[k_P] = P_ij_bar[k_P] - P_i_bar[i_P] * P_i_bar[j_P];\n }\n }\n\n // Write covariance matrix\n if(SID.I_am_Master) {\n if((fp_covariance = fopen(filename_covariance, \"wb\")) == NULL)\n SID_exit_error(\"Could not open {%s} for writing.\", SID_ERROR_IO_OPEN, filename_covariance);\n fwrite(&n_P, sizeof(int), 1, fp_covariance);\n fwrite(V_compute, sizeof(double), n_P * n_P, fp_covariance);\n fclose(fp_covariance);\n }\n\n // Compute mapped dataset confidence intervals from histograms\n SID_log(\"Compute confidence intervals...\", SID_LOG_OPEN);\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++) {\n merge_sort(M_histogram[i_DS][i_M], (size_t)coverage_size, &histogram_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n accumulator = M_histogram[i_DS][i_M][histogram_index[coverage_size - 1]];\n M_best_index = histogram_index[coverage_size - 1];\n M_lo_68_index = histogram_index[coverage_size - 1];\n M_hi_68_index = histogram_index[coverage_size - 1];\n for(j_P = coverage_size - 2; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.68; j_P--) {\n if(histogram_index[j_P] < M_lo_68_index)\n M_lo_68_index = histogram_index[j_P];\n if(histogram_index[j_P] > M_hi_68_index)\n M_hi_68_index = histogram_index[j_P];\n accumulator += M_histogram[i_DS][i_M][histogram_index[j_P]];\n }\n M_lo_95_index = M_lo_68_index;\n M_hi_95_index = M_hi_68_index;\n for(; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.95; j_P--) {\n if(histogram_index[j_P] < M_lo_95_index)\n M_lo_95_index = histogram_index[j_P];\n if(histogram_index[j_P] > M_hi_95_index)\n M_hi_95_index = histogram_index[j_P];\n accumulator += M_histogram[i_DS][i_M][histogram_index[j_P]];\n }\n M_best[i_DS][i_M] =\n M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_best_index) + 0.5) / (double)coverage_size;\n M_lo_68[i_DS][i_M] =\n M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_lo_68_index) + 0.5) / (double)coverage_size;\n M_hi_68[i_DS][i_M] =\n M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_hi_68_index) + 0.5) / (double)coverage_size;\n M_lo_95[i_DS][i_M] =\n M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_lo_95_index) + 0.5) / (double)coverage_size;\n M_hi_95[i_DS][i_M] =\n M_min[i_DS][i_M] + (M_max[i_DS][i_M] - M_min[i_DS][i_M]) * ((double)(M_hi_95_index) + 0.5) / (double)coverage_size;\n SID_free(SID_FARG histogram_index);\n }\n }\n }\n\n // Compute parameter confidence intervals from histograms\n for(i_P = 0; i_P < n_P; i_P++) {\n merge_sort(P_histogram[i_P], (size_t)coverage_size, &histogram_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n accumulator = P_histogram[i_P][histogram_index[coverage_size - 1]];\n P_best_index = histogram_index[coverage_size - 1];\n P_lo_68_index = histogram_index[coverage_size - 1];\n P_hi_68_index = histogram_index[coverage_size - 1];\n for(j_P = 1, k_P = 0; j_P < coverage_size; j_P++)\n if(max_L_histogram[i_P][j_P] > max_L_histogram[i_P][k_P])\n k_P = j_P;\n for(j_P = coverage_size - 2; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.68; j_P--) {\n if(histogram_index[j_P] < P_lo_68_index)\n P_lo_68_index = histogram_index[j_P];\n if(histogram_index[j_P] > P_hi_68_index)\n P_hi_68_index = histogram_index[j_P];\n accumulator += P_histogram[i_P][histogram_index[j_P]];\n }\n P_lo_95_index = P_lo_68_index;\n P_hi_95_index = P_hi_68_index;\n for(; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.95; j_P--) {\n if(histogram_index[j_P] < P_lo_95_index)\n P_lo_95_index = histogram_index[j_P];\n if(histogram_index[j_P] > P_hi_95_index)\n P_hi_95_index = histogram_index[j_P];\n accumulator += P_histogram[i_P][histogram_index[j_P]];\n }\n P_best[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_best_index) + 0.5) / (double)coverage_size;\n P_lo_68[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_lo_68_index) + 0.5) / (double)coverage_size;\n P_hi_68[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_hi_68_index) + 0.5) / (double)coverage_size;\n P_lo_95[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_lo_95_index) + 0.5) / (double)coverage_size;\n P_hi_95[i_P] = P_min[i_P] + (P_max[i_P] - P_min[i_P]) * ((double)(P_hi_95_index) + 0.5) / (double)coverage_size;\n SID_free(SID_FARG histogram_index);\n }\n\n // Compute parameter confidence contours from coverage maps\n for(i_coverage = 0; i_coverage < n_coverage; i_coverage++) {\n merge_sort(\n coverage_keep[i_coverage], (size_t)(coverage_size * coverage_size), &coverage_keep_index, SID_SIZE_T, SORT_COMPUTE_INDEX, GBP_FALSE);\n accumulator = coverage_keep[i_coverage][coverage_keep_index[coverage_size * coverage_size - 1]];\n P_contour_68[i_coverage] = coverage_keep[i_coverage][coverage_keep_index[coverage_size * coverage_size - 1]];\n for(j_P = (coverage_size * coverage_size) - 2; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.68; j_P--) {\n P_contour_68[i_coverage] = coverage_keep[i_coverage][coverage_keep_index[j_P]];\n accumulator += coverage_keep[i_coverage][coverage_keep_index[j_P]];\n }\n P_contour_95[i_coverage] = P_contour_68[i_coverage];\n for(; j_P >= 0 && ((double)accumulator / (double)n_used) < 0.95; j_P--) {\n P_contour_95[i_coverage] = coverage_keep[i_coverage][coverage_keep_index[j_P]];\n accumulator += coverage_keep[i_coverage][coverage_keep_index[j_P]];\n }\n SID_free(SID_FARG coverage_keep_index);\n }\n SID_log(\"Done.\", SID_LOG_CLOSE);\n\n // Write coverage maps\n SID_log(\"Writing coverage maps...\", SID_LOG_OPEN);\n fp_coverage = fopen(filename_coverage, \"wb\");\n fwrite(&n_coverage, sizeof(int), 1, fp_coverage);\n fwrite(&coverage_size, sizeof(int), 1, fp_coverage);\n fwrite(P_min, sizeof(double), n_P, fp_coverage);\n fwrite(P_max, sizeof(double), n_P, fp_coverage);\n for(i_P = 0, i_coverage = 0; i_P < n_P; i_P++) {\n for(j_P = i_P + 1; j_P < n_P; j_P++, i_coverage++) {\n fwrite(&P_contour_68[i_coverage], sizeof(double), 1, fp_coverage);\n fwrite(&P_contour_95[i_coverage], sizeof(double), 1, fp_coverage);\n\n // We need to covert to uint64_t so that allresults_MCMC.py works on 32-bit systems\n for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++)\n temp_out[j_coverage] = coverage_true[i_coverage][j_coverage];\n fwrite(temp_out, sizeof(uint64_t), coverage_size * coverage_size, fp_coverage);\n for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++)\n temp_out[j_coverage] = coverage_false[i_coverage][j_coverage];\n fwrite(temp_out, sizeof(uint64_t), coverage_size * coverage_size, fp_coverage);\n for(j_coverage = 0; j_coverage < coverage_size * coverage_size; j_coverage++)\n temp_out[j_coverage] = coverage_keep[i_coverage][j_coverage];\n fwrite(temp_out, sizeof(uint64_t), coverage_size * coverage_size, fp_coverage);\n\n fwrite(max_L_surface[i_coverage], sizeof(double), coverage_size * coverage_size, fp_coverage);\n fwrite(mean_L_surface[i_coverage], sizeof(double), coverage_size * coverage_size, fp_coverage);\n }\n }\n fclose(fp_coverage);\n SID_log(\"Done.\", SID_LOG_CLOSE);\n\n // Write histograms\n SID_log(\"Writing histograms...\", SID_LOG_OPEN);\n fp_histograms = fopen(filename_histograms, \"wb\");\n for(i_P = 0; i_P < n_P; i_P++) {\n fwrite(&P_best[i_P], sizeof(double), 1, fp_histograms);\n fwrite(&P_lo_68[i_P], sizeof(double), 1, fp_histograms);\n fwrite(&P_hi_68[i_P], sizeof(double), 1, fp_histograms);\n fwrite(&P_lo_95[i_P], sizeof(double), 1, fp_histograms);\n fwrite(&P_hi_95[i_P], sizeof(double), 1, fp_histograms);\n fwrite(&P_peak[i_P], sizeof(double), 1, fp_histograms);\n // We need to covert to uint64_t so that allresults_MCMC.py works on 32-bit systems\n for(j_coverage = 0; j_coverage < coverage_size; j_coverage++)\n temp_out[j_coverage] = P_histogram[i_P][j_coverage];\n fwrite(temp_out, sizeof(uint64_t), coverage_size, fp_histograms);\n fwrite(mean_L_histogram[i_P], sizeof(double), coverage_size, fp_histograms);\n fwrite(max_L_histogram[i_P], sizeof(double), coverage_size, fp_histograms);\n }\n if(!flag_no_map_write) {\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(i_M = 0; i_M < n_M[i_DS]; i_M++) {\n fwrite(&M_best[i_DS][i_M], sizeof(double), 1, fp_histograms);\n fwrite(&M_lo_68[i_DS][i_M], sizeof(double), 1, fp_histograms);\n fwrite(&M_hi_68[i_DS][i_M], sizeof(double), 1, fp_histograms);\n fwrite(&M_lo_95[i_DS][i_M], sizeof(double), 1, fp_histograms);\n fwrite(&M_hi_95[i_DS][i_M], sizeof(double), 1, fp_histograms);\n // We need to covert to uint64_t so that allresults_MCMC.py works on 32-bit systems\n for(j_coverage = 0; j_coverage < coverage_size; j_coverage++)\n temp_out[j_coverage] = M_histogram[i_DS][i_M][j_coverage];\n fwrite(temp_out, sizeof(uint64_t), coverage_size, fp_histograms);\n }\n }\n }\n fclose(fp_histograms);\n SID_log(\"Done.\", SID_LOG_CLOSE);\n }\n SID_log(\"Done.\", SID_LOG_CLOSE);\n\n // Compute best fit models and their likelihoods\n if(MCMC->map_P_to_M != NULL) {\n SID_Bcast(P_best, n_P, SID_DOUBLE, my_chain, MCMC->comm);\n MCMC->map_P_to_M(P_best, MCMC, M_best_parameters);\n MCMC->compute_MCMC_ln_likelihood(\n MCMC, M_best_parameters, P_best, MCMC->ln_likelihood_DS_best, MCMC->n_DoF_DS_best, &(MCMC->ln_likelihood_best), &(MCMC->n_DoF_best));\n SID_Bcast(P_peak, n_P, SID_DOUBLE, my_chain, MCMC->comm);\n MCMC->map_P_to_M(P_peak, MCMC, M_peak_parameters);\n MCMC->compute_MCMC_ln_likelihood(\n MCMC, M_peak_parameters, P_peak, MCMC->ln_likelihood_DS_peak, MCMC->n_DoF_DS_peak, &(MCMC->ln_likelihood_peak), &(MCMC->n_DoF_peak));\n }\n\n if(my_chain == SID.My_rank) {\n // Write fit results\n SID_log(\"Writing final statistics...\", SID_LOG_OPEN);\n sprintf(filename_results, \"%s/fit_for_parameters.dat\", filename_results_dir);\n fp_results = fopen(filename_results, \"w\");\n fprintf(fp_results, \"# MCMC parameter fit results to %s\\n\", MCMC->problem_name);\n if(MCMC->map_P_to_M != NULL) {\n fprintf(fp_results, \"# ln(likelihood)+constant=%le w/ %d DoF (marginalized PDF)\\n\", MCMC->ln_likelihood_best, MCMC->n_DoF_best);\n fprintf(fp_results, \"# ln(likelihood)+constant=%le w/ %d DoF (maximum likelihood)\\n\", MCMC->ln_likelihood_peak, MCMC->n_DoF_peak);\n }\n fprintf(fp_results, \"# n_samples_used=%d\\n\", n_used);\n fprintf(fp_results, \"# n_parameters =%d\\n\", n_P);\n fprintf(fp_results, \"# n_data_sets =%d\\n\", n_DS);\n fprintf(fp_results, \"# used data sets:\\n\");\n current_DS = MCMC->DS;\n while(current_DS != NULL) {\n next_DS = current_DS->next;\n fprintf(fp_results, \"# %s\\n\", current_DS->name);\n current_DS = next_DS;\n i_DS++;\n }\n sprintf(column_txt, \"Column:\");\n i_column = 1;\n fprintf(fp_results, \"# %s (%02d) Parameter name\\n\", column_txt, i_column++);\n sprintf(column_txt, \" \");\n for(i_array = 0; i_array < MCMC->n_arrays; i_array++)\n fprintf(fp_results, \"# %s (%02d) %s\\n\", column_txt, i_column++, MCMC->array_name[i_array]);\n fprintf(fp_results, \"# %s (%02d) Initial value\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Average\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Standard deviation\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Maximum likelihood value\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Lower limit (68%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Upper limit (68%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Lower limit (95%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Upper limit (95%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Best fit value\\n\", column_txt, i_column++);\n for(i_P = 0; i_P < n_P; i_P++) {\n strcpy(array_name_temp, MCMC->P_names[i_P]);\n search_and_replace(array_name_temp, \" \", \"~\");\n fprintf(fp_results, MCMC->P_name_format, array_name_temp);\n for(i_array = 0; i_array < MCMC->n_arrays; i_array++)\n fprintf(fp_results, \" %13.6le\", MCMC->array[i_array][i_P]);\n fprintf(fp_results,\n \" %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le\\n\",\n MCMC->P_init[i_P],\n P_avg[i_P],\n dP_avg[i_P],\n P_best[i_P],\n P_lo_68[i_P],\n P_hi_68[i_P],\n P_lo_95[i_P],\n P_hi_95[i_P],\n P_peak[i_P]);\n }\n fclose(fp_results);\n\n // Write the fits for each dataset\n i_DS = 0;\n current_DS = MCMC->DS;\n while(current_DS != NULL) {\n next_DS = current_DS->next;\n M_target = current_DS->M_target;\n dM_target = current_DS->dM_target;\n if(current_DS->n_D <= 1) {\n if(n_DS > 1)\n sprintf(filename_results, \"%s/fit_for_dataset_%05d.dat\", filename_results_dir, i_DS);\n else\n sprintf(filename_results, \"%s/fit_for_dataset.dat\", filename_results_dir);\n fp_results = fopen(filename_results, \"w\");\n fprintf(fp_results, \"# MCMC data set fit results for %s\\n\", current_DS->name);\n fprintf(fp_results, \"# n_samples_used=%d\\n\", n_used);\n fprintf(fp_results, \"# dataset size =%d\\n\", n_M[i_DS]);\n if(MCMC->map_P_to_M != NULL) {\n fprintf(fp_results,\n \"# ln(likelihood)+constant=%le w/ %d DoF (marginalized PDF)\\n\",\n MCMC->ln_likelihood_DS_best[i_DS],\n MCMC->n_DoF_DS_best[i_DS]);\n fprintf(fp_results,\n \"# ln(likelihood)+constant=%le w/ %d DoF (maximum likelihood)\\n\",\n MCMC->ln_likelihood_DS_peak[i_DS],\n MCMC->n_DoF_DS_peak[i_DS]);\n }\n sprintf(column_txt, \"Column:\");\n for(i_array = 0, i_column = 1; i_array < MCMC->n_arrays; i_array++) {\n fprintf(fp_results, \"# %s (%02d) %s\\n\", column_txt, i_column++, current_DS->array_name[i_array]);\n sprintf(column_txt, \" \");\n }\n sprintf(column_txt, \" \");\n fprintf(fp_results, \"# %s (%02d) Dataset\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Dataset uncertainty\\n\", column_txt, i_column++);\n if(!flag_no_map_write) {\n fprintf(fp_results, \"# %s (%02d) Average\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Standard deviation\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Marginalized likelihood value\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Lower limit (68%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Upper limit (68%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Lower limit (95%% confidence)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Upper limit (95%% confidence)\\n\", column_txt, i_column++);\n }\n if(MCMC->map_P_to_M != NULL) {\n fprintf(fp_results, \"# %s (%02d) Model (Marginalized likelihood parameters)\\n\", column_txt, i_column++);\n fprintf(fp_results, \"# %s (%02d) Model (Maximum likelihood parameters)\\n\", column_txt, i_column++);\n }\n for(i_P = 0; i_P < n_M[i_DS]; i_P++) {\n for(i_array = 0; i_array < n_M_arrays[i_DS]; i_array++)\n fprintf(fp_results, \"%13.6le \", M_arrays[i_DS][i_array][i_P]);\n fprintf(fp_results, \"%13.6le %13.6le\", M_target[i_P], dM_target[i_P]);\n if(!flag_no_map_write)\n fprintf(fp_results,\n \" %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le %13.6le\",\n M_avg[i_DS][i_P],\n dM_avg[i_DS][i_P],\n M_best[i_DS][i_P],\n M_lo_68[i_DS][i_P],\n M_hi_68[i_DS][i_P],\n M_lo_95[i_DS][i_P],\n M_hi_95[i_DS][i_P]);\n if(MCMC->map_P_to_M != NULL)\n fprintf(fp_results, \" %13.6le %13.6le\", M_best_parameters[i_DS][i_P], M_peak_parameters[i_DS][i_P]);\n fprintf(fp_results, \"\\n\");\n }\n fclose(fp_results);\n } else {\n if(n_DS > 1)\n sprintf(filename_results, \"%s/fit_for_dataset_%05d.fits\", filename_results_dir, i_DS);\n else\n sprintf(filename_results, \"%s/fit_for_dataset.fits\", filename_results_dir);\n#if USE_CFITSIO\n write_image_FITS(M_target, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"DATASET\");\n append_image_FITS(dM_target, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"UNCERTAINTY\");\n if(!flag_no_map_write) {\n append_image_FITS(M_best[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MAP_MAXL\");\n append_image_FITS(M_lo_68[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MAP_68PC_LO\");\n append_image_FITS(M_hi_68[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MAP_68PC_HI\");\n append_image_FITS(M_lo_95[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MAP_95PC_LO\");\n append_image_FITS(M_hi_95[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MAP_95PC_HI\");\n }\n if(MCMC->map_P_to_M != NULL) {\n // Write the fit from the maximum likelihood of the marginalized pdf\n append_image_FITS(M_best_parameters[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MODEL_MAXL\");\n for(i_P = 0; i_P < n_M[i_DS]; i_P++)\n residual[i_P] = M_target[i_P] - M_best_parameters[i_DS][i_P];\n append_image_FITS(residual, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"RESIDUAL_MAXL\");\n // Write the best fit\n append_image_FITS(M_peak_parameters[i_DS], SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"MODEL_BEST\");\n for(i_P = 0; i_P < n_M[i_DS]; i_P++)\n residual[i_P] = M_target[i_P] - M_peak_parameters[i_DS][i_P];\n append_image_FITS(residual, SID_DOUBLE, current_DS->n_D, current_DS->D, filename_results, \"RESIDUAL_BEST\");\n }\n#else\n SID_exit_error(\"2D analysis can only be written if you compile with USE_CFITSIO=1\", SID_ERROR_LOGIC);\n#endif\n }\n current_DS = next_DS;\n i_DS++;\n }\n SID_log(\"Done.\", SID_LOG_CLOSE);\n } // if this is my chain\n\n // Clean-up\n SID_log(\"Cleaning-up...\", SID_LOG_OPEN);\n SID_free(SID_FARG P_i_bar_accum);\n SID_free(SID_FARG P_ij_bar_accum);\n SID_free(SID_FARG P_i_bar);\n SID_free(SID_FARG P_ij_bar);\n SID_free(SID_FARG V_compute);\n for(i_DS = 0; i_DS < n_DS; i_DS++) {\n for(j_M = 0; j_M < n_M[i_DS]; j_M++)\n SID_free(SID_FARG M_histogram[i_DS][j_M]);\n SID_free(SID_FARG M_histogram[i_DS]);\n }\n SID_free(SID_FARG M_avg);\n SID_free(SID_FARG dM_avg);\n SID_free(SID_FARG M_best);\n SID_free(SID_FARG residual);\n SID_free(SID_FARG M_best_parameters);\n SID_free(SID_FARG M_peak_parameters);\n SID_free(SID_FARG M_min);\n SID_free(SID_FARG M_max);\n SID_free(SID_FARG M_lo_68);\n SID_free(SID_FARG M_hi_68);\n SID_free(SID_FARG M_lo_95);\n SID_free(SID_FARG M_hi_95);\n SID_free(SID_FARG M_histogram);\n SID_free(SID_FARG P_contour_68);\n SID_free(SID_FARG P_contour_95);\n for(i_P = 0; i_P < n_P; i_P++) {\n SID_free(SID_FARG P_histogram[i_P]);\n SID_free(SID_FARG mean_L_histogram[i_P]);\n SID_free(SID_FARG max_L_histogram[i_P]);\n }\n SID_free(SID_FARG P_histogram);\n SID_free(SID_FARG n_M_arrays);\n SID_free(SID_FARG M_arrays);\n SID_free(SID_FARG M_avg);\n SID_free(SID_FARG dM_avg);\n for(i_P = 0; i_P < n_coverage; i_P++) {\n SID_free(SID_FARG coverage_true[i_P]);\n SID_free(SID_FARG coverage_false[i_P]);\n SID_free(SID_FARG coverage_keep[i_P]);\n SID_free(SID_FARG max_L_surface[i_P]);\n SID_free(SID_FARG mean_L_surface[i_P]);\n }\n SID_free(SID_FARG coverage_true);\n SID_free(SID_FARG coverage_false);\n SID_free(SID_FARG coverage_keep);\n SID_free(SID_FARG max_L_surface);\n SID_free(SID_FARG mean_L_surface);\n SID_free(SID_FARG temp_out);\n SID_log(\"Done.\", SID_LOG_CLOSE);\n\n SID_log(\"Done.\", SID_LOG_CLOSE);\n}\n", "meta": {"hexsha": "3cdf38caf8da04584422b4fe1710743b7424adf9", "size": 57543, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/analyze_MCMC.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/analyze_MCMC.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/analyze_MCMC.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": 51.9810298103, "max_line_length": 149, "alphanum_fraction": 0.5346089012, "num_tokens": 14236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6619228891883799, "lm_q2_score": 0.44167300566462553, "lm_q1q2_score": 0.2923534719860446}} {"text": "/* stable/stable.h\n * \n * Main header file of Libstable. Contains all declarations of the\n * usable functions in the library.\n *\n * Copyright (C) 2013. Javier Royuela del Val\n * Federico Simmross Wattenberg\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; version 3 of the License.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; If not, see .\n *\n *\n * Javier Royuela del Val.\n * E.T.S.I. Telecomunicación\n * Universidad de Valladolid\n * Paseo de Belén 15, 47002 Valladolid, Spain.\n * jroyval@lpi.tel.uva.es \n */\n \n#ifndef _stable_H_\n#define _stable_H_\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define TINY 1e-50\n#define EPS 2.2204460492503131E-16\n\n#define max(a,b) (((a) > (b)) ? (a) : (b))\n#define min(a,b) (((a) < (b)) ? (a) : (b))\n\n/******************************************************************************/\n/* Library parameters */\n/******************************************************************************/\n\nextern FILE * FLOG; // Log file (optional)\nextern FILE * FINTEG; // Integrand evaluations output file (debug purposes)\n\nextern unsigned short THREADS; // threads of execution (0 => total available)\nextern unsigned short IT_MAX; // Maximum # of iterations in quadrature methods\nextern unsigned short SUBS; // # of integration subintervals\nextern unsigned short METHOD1; // Integration method on main subinterval\nextern unsigned short METHOD2; // Integration method on second subinterval\nextern unsigned short METHOD3; // Integration method on third subinterval\n\nextern unsigned short INV_MAXITER; // Maximum # of iterations inversion method\n\nextern double relTOL; // Relative error tolerance\nextern double absTOL; // Absolut error tolerance\n//extern double FACTOR; // \nextern double ALPHA_TH; // Alpha threshold\nextern double BETA_TH; // Beta threshold\nextern double EXP_MAX; // Exponent maximum value\nextern double XXI_TH; // Zeta threshold\nextern double THETA_TH; // Theta threshold\n\nextern double AUX1; // Auxiliary values\nextern double AUX2;\n\n#ifdef DEBUG\nextern unsigned int integ_eval; // # of integrand evaluations\n#endif\n\n/******************************************************************************/\n/******************************************************************************/\n// Particular cases\nenum\n {\n NOVALID =-1,\n STABLE,\n ALPHA_1,\n GAUSS ,\n CAUCHY,\n LEVY,\n STABLE_B1,\n ALPHA_1_B1\n };\n\n// Function to evaluate\nenum\n {\n CDF,\n PDF\n };\n\n// Quadrature methods\nenum\n {\n STABLE_QAG2 = 0,\n STABLE_QUADSTEP,\n STABLE_QROMBPOL,\n STABLE_QROMBRAT,\n STABLE_QNG,\n STABLE_QAG1,\n STABLE_QAG5,\n STABLE_VECT\n };\n\n\n/************************************************************************\n ************************************************************************\n * Scalar methods *\n ************************************************************************\n ************************************************************************/\n/* Scalar methods are those that, for each thread of execution, obtain a\n single evaluation of the desired function, at a single point.\n*/\n\n/******************************************************************************/\n/* Stable distribution structure. */\n/******************************************************************************/\nstruct StableDistStruct\n {\n /* Parameters:\n 0-parametrization describen in Nolan, 1997 is employed by default\n alpha : stability index\n beta : skewness parameter\n scale: scale parameter\n mu_0 : 0-parametrization location parameter\n mu_1 : correspondig 1-parametrization location parameter */\n double alpha;\n double beta;\n double sigma;\n double mu_0; \n double mu_1;\n \n\n /* Particular cases indicator (Gauss, Cauchy, Levy distribution, alpha==1, etc.) */\n int ZONE;\n\n /* Pointers to pdf and cdf evaluation functions */\n double(*stable_pdf_point)(struct StableDistStruct *, const double, double *); \n double(*stable_cdf_point)(struct StableDistStruct *, const double, double *);\n\n /* Precalculated values. */\n double alphainvalpha1; /* alpha/(alpha-1)*/\n double xi; /* -beta*tan(alpha*pi/2)*/\n double theta0; /* 1/alpha*atan(beta*(tan(alpha*pi/2))=atan(-xi)/alpha;*/\n double c1, c2_part, c3; /* additive and multiplicative constants*/\n double k1; /* cos(alpha*theta0)^(1/(alpha-1)) = (1+xi^2)^(-0.5/(alpha-1));*/\n double S; /* (1+xi^2)^(1/(2*alpha));*/\n double Vbeta1; /*pow(1/dist->alpha,dist->alphainvalpha1) *\n (dist->alpha-1)*pow(-cos(dist->alpha*PI_2),1/(dist->alpha-1))*/\n\n /* These ones change from point to point of evaluation */\n double theta0_; /* theta0_ = +-theta0 */\n double beta_;\n double xxipow; /* (x-xi)^(alpha/(alpha-1))*/\n\n /* gsl integration workspace */\n gsl_integration_workspace * gslworkspace;\n\n /* gsl random numbers generator */\n gsl_rng * gslrand;\n };\n\ntypedef struct StableDistStruct StableDist;\n/******************************************************************************/\n/* Auxiliary functions */\n/******************************************************************************/\nunsigned int stable_get_THREADS();\nvoid stable_set_THREADS(unsigned int threads);\n\nunsigned int stable_get_IT_MAX();\nvoid stable_set_IT_MAX(unsigned int itmax);\n\nunsigned int stable_get_INV_MAXITER();\nvoid stable_set_INV_MAXITER(unsigned int invmaxiter);\n\nint stable_get_METHOD1();\nvoid stable_set_METHOD1(int method);\n\nint stable_get_METHOD2();\nvoid stable_set_METHOD2(int method);\n\nint stable_get_METHOD3();\nvoid stable_set_METHOD3(int method);\n\ndouble stable_get_relTOL();\nvoid stable_set_relTOL(double reltol);\n\ndouble stable_get_absTOL();\nvoid stable_set_absTOL(double abstol);\n\ndouble stable_get_ALPHA_TH();\nvoid stable_set_ALPHA_TH(double alphath);\n\ndouble stable_get_BETA_TH();\nvoid stable_set_BETA_TH(double betath);\n\ndouble stable_get_XXI_TH();\nvoid stable_set_XXI_TH(double xxith);\n\ndouble stable_get_THETA_TH();\nvoid stable_set_THETA_TH(double thetath);\n\nFILE * stable_get_FINTEG();\nFILE * stable_set_FINTEG(char * filename);\n\nFILE * stable_get_FLOG();\nFILE * stable_set_FLOG(char * filename);\n\n\nStableDist *stable_create(double alpha, double beta, double sigma, double mu,\n int parametrization);\n\nStableDist *stable_copy(StableDist *src_dist);\n\nvoid stable_free(StableDist *dist);\n\nint stable_setparams(StableDist *dist,\n double alpha, double beta, double sigma, double mu,\n int parametrization);\n\nint stable_checkparams(double alpha, double beta, double sigma, double mu,\n int parametrization);\n\nvoid error_handler (const char * reason, const char * file,\n int line, int gsl_errno);\n\n/******************************************************************************/\n/* PDF in particular cases */\n/******************************************************************************/\n\ndouble stable_pdf_point_GAUSS(StableDist *dist, const double x, double *err);\n\ndouble stable_pdf_point_CAUCHY(StableDist *dist, const double x, double *err);\n\ndouble stable_pdf_point_LEVY(StableDist *dist, const double x, double *err);\n\n/******************************************************************************/\n/* PDF otherwise */\n/******************************************************************************/\n\ndouble stable_pdf_point_STABLE(StableDist *dist, const double x, double *err);\n\ndouble stable_pdf_point_ALPHA_1(StableDist *dist, const double x, double *err);\n\ndouble stable_pdf_point(StableDist *dist, const double x, double *err);\n\nvoid stable_pdf(StableDist *dist, const double* x, const unsigned int Nx,\n double *pdf, double *err);\n\n/******************************************************************************/\n/* PDF integrand functions */\n/******************************************************************************/\n\ndouble stable_pdf_g(double theta, void *dist);\ndouble stable_pdf_g_aux1(double theta, void *args);\ndouble stable_pdf_g_aux2(double theta, void *args);\n\n/******************************************************************************/\n/* CDF in particular cases */\n/******************************************************************************/\n\ndouble stable_cdf_point_GAUSS(StableDist *dist, const double x, double *err);\n\ndouble stable_cdf_point_CAUCHY(StableDist *dist, const double x, double *err);\n\ndouble stable_cdf_point_LEVY(StableDist *dist, const double x, double *err);\n\n/******************************************************************************/\n/* CDF otherwise */\n/******************************************************************************/\n\ndouble stable_cdf_point_STABLE(StableDist *dist, const double x, double *err);\n\ndouble stable_cdf_point_ALPHA_1(StableDist *dist, const double x, double *err);\n\ndouble stable_cdf_point(StableDist *dist, const double x, double *err);\n\nvoid stable_cdf(StableDist *dist, const double* x, const unsigned int Nx,\n double *cdf, double *err);\n\n/******************************************************************************/\n/* CDF integrad functions */\n/******************************************************************************/\n\ndouble stable_cdf_g(double theta, void *dist);\n\n/******************************************************************************/\n/* CDF^{-1} (quantiles) */\n/******************************************************************************/\n\ndouble stable_q_point(StableDist * dist, const double q, double * err);\nvoid stable_q(StableDist *dist, const double* q, const unsigned int Nq,\n double * inv, double * err);\n\n/************************************************************************\n ************************************************************************\n * Vectorial methods *\n ************************************************************************\n ************************************************************************/\n/*\n Alternative non-parallelized methods of evaluation have been implemented.\n These methods exploit the fact that some calculations are shared between\n different points of evaluation when evaluating the PDF or CDF, so these\n calculations can be realized just once.\n\n The performance achieved is high, sometimes comparable with parallel\n methods when little precision is required. However, achievable precision\n with these methods is low and non desired behavior of the PDF and CDF\n evaluation is observed.\n*/\n\n/* Stable distribution structure for vectorial methods*/\n\ntypedef struct\n {\n/* Parameters:\n 0-parametrization describen in Nolan, 1997 is employed by default\n alpha : stability index\n beta : skewness parameter\n scale: scale parameter\n mu_0 : 0-parametrization location parameter\n mu_1 : correspondig 1-parametrization location parameter */\n double alpha;\n double beta;\n double sigma;\n double mu_0; \n double mu_1;\n\n /* Particular cases indicator (Gauss, Cauchy, Levy distribution, alpha==1, etc.) */\n int ZONE;\n\n /* Precalculated values */\n double alphainvalpha1; /* alpha/(alpha-1)*/\n double xi; /* -beta*tan(alpha*pi/2)*/\n double theta0; /* 1/alpha*atan(beta*(tan(alpha*pi/2))=atan(-xi)/alpha;*/\n double c1, c2_part, c3; /* additive and multiplicative constants*/\n double k1; /* cos(alpha*theta0)^(1/(alpha-1)) = (1+xi^2)^(-0.5/(alpha-1));*/\n double S; /* (1+xi^2)^(1/(2*alpha));*/\n double Vbeta1; /*pow(1/dist->alpha,dist->alphainvalpha1) *\n (dist->alpha-1)*pow(-cos(dist->alpha*PI_2),1/(dist->alpha-1))*/\n\n /* These ones change from point to point of evaluation */\n double theta0_; /* theta0_ = +-theta0 */\n double beta_;\n double *xxipow; /* (x-xi)^(alpha/(alpha-1))*/\n\n gsl_integration_workspace * gslworkspace;\n gsl_rng * gslrand;\n }\nStableDistV;\n\ntypedef struct\n {\n double (*ptr_funcion)(StableDist *dist, const double x, double *err);\n StableDist *dist;\n const double *x;\n int Nx;\n double *pdf;\n double *err;\n }\nStableArgsPdf;\n\ntypedef struct\n {\n double (*ptr_funcion)(StableDist *dist, const double x, double *err);\n StableDist *dist;\n const double *x;\n int Nx;\n double *cdf;\n double *err;\n }\nStableArgsCdf;\n\n/************************************************************************\n ************************************************************************\n * Parameter estimation *\n ************************************************************************\n ************************************************************************/\n\n\n/******************************************************************************/\n/* Parameter estimation structure */\n/******************************************************************************/\ntypedef struct\n {\n StableDist *dist;\n double *data;\n unsigned int length;\n double nu_c;\n double nu_z;\n }\nstable_like_params;\n\n/* Estimation functions */\n\nvoid stable_fit_init(StableDist *dist, const double *data,\n const unsigned int length, double *nu_c,double *nu_z);\n\nint stable_fit_koutrouvelis(StableDist *dist, const double *data, const unsigned int length);\n\nint stable_fit(StableDist *dist, const double *data, const unsigned int length);\n\nint stable_fit_mle(StableDist *dist, const double *data, const unsigned int length);\n\nint stable_fit_mle2d(StableDist *dist, const double *data, const unsigned int length);\n\nint stable_fit_whole(StableDist *dist, const double *data, const unsigned int length);\n\n/* Auxiliary functions */\n\ngsl_complex stable_samplecharfunc_point(const double* x,\n const unsigned int N, double t);\n\nvoid stable_samplecharfunc(const double* x, const unsigned int Nx,\n const double* t, const unsigned int Nt, gsl_complex * z);\n \nvoid stable_fft(double *data, const unsigned int length, double * y);\n\ndouble stable_loglikelihood(StableDist *dist, double *data, const unsigned int length);\n\n//stable_like_params\n\nint stable_fit_iter_whole(StableDist *dist, const double * data, const unsigned int length);\n \nint stable_fit_iter(StableDist *dist, const double * data,\n const unsigned int length, const double nu_c, const double nu_z);\n\ndouble stable_loglike_p(stable_like_params *params);\n\ndouble stable_minusloglikelihood(const gsl_vector * theta, void * p);\n\n/************************************************************************\n ************************************************************************\n * Random numbers generation *\n ************************************************************************\n ************************************************************************/\nvoid stable_rnd(StableDist *dist, double* rnd, unsigned int n);\n\ndouble stable_rnd_point(StableDist *dist);\n\nvoid stable_rnd_seed(StableDist * dist, unsigned long int s);\n#endif //stable_H\n", "meta": {"hexsha": "2f3e7b60f9db335e4b1d6a35c7c337de5311561a", "size": 16452, "ext": "h", "lang": "C", "max_stars_repo_path": "stat/distuv/libs/libstable/stable/src/stable.h", "max_stars_repo_name": "TantraLabs/gonum", "max_stars_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stat/distuv/libs/libstable/stable/src/stable.h", "max_issues_repo_name": "TantraLabs/gonum", "max_issues_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stat/distuv/libs/libstable/stable/src/stable.h", "max_forks_repo_name": "TantraLabs/gonum", "max_forks_repo_head_hexsha": "784ef78fc0bd9e1dd83e1e9ccaaa2e50a8003a50", "max_forks_repo_licenses": ["BSD-3-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.3982300885, "max_line_length": 98, "alphanum_fraction": 0.5316678823, "num_tokens": 3287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.29180309992347}} {"text": "/**\n *\n * Copyright 2018, Planet Labs, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \n\n#include \n#include \n#include \n\n\n/* A wrapper around the GSL multi-variate robust regression routine.\n\n This routine should only ever be called from the Python wrapper function, so if the\n parameters need to be changed, only these two files have to be changed.\n\n The array variables are given as pointers to doubles, and are referenced as\n 1-d arrays. However, the indexes are calculated as though they were multi-dimensional\n arrays, and the dimensions are described below.\n\n Input Variables\n ***************\n\n numParams is the number of parameters to be fitted, also equal\n to the number of independent variables\n numImages is the number of images in the stack, and corresponds to the number\n of points in each fit (before removing nulls)\n numRows is the number of rows in the image\n numCols is the number of columns in the image\n\n The x parameter contains the values of all the independent variables.\n It comes in one of two flavours, depending on the value of the\n perPixelX parameter. If perPixelX is 1, then the x parameter is a 4-dimensional\n array of doubles, with shape\n (numParams, numImages, numRows, numCols)\n otherwise it is a 2-dimensional array with shape\n (numParams, numImages)\n and it is assumed that the independent variables are constant over all pixels.\n This latter is the most likely case.\n\n The Y variable is notionally a 3-dimensional array of doubles.\n The shape should be\n (numImages, numRows, numCols)\n It contains the values of the dependent variable.\n\n The nullVal parameter is a scalar double value. Any occurrence of this value in the\n y array will exclude that point from the fit.\n\n Output Variables\n ****************\n\n The following variables are calculated within this routine, and passed back via the\n pointers in the parameter list.\n\n The c array is a 3-dimensional array of doubles. It corresponds to an image\n stack of the fitted coefficients, and its shape is\n (numParams, numRows, numCols)\n\n The adj_Rsqrd array stores the adjusted R^2 coefficient of determination\n statistic.\n\n*/\nvoid wrap_gsl_multifit_robust(double *x, double *y, double *c, double *adj_Rsqrd,\n int *numIter, double *rmse, int method, int perPixelX,\n int numRows, int numCols, int numImages, int numParams,\n int numRowsX, int numColsX, double nullVal) {\n int row, col, img, param, n, xNdx, yNdx, pixNdx;\n gsl_matrix *gslX, *gslCov;\n gsl_vector *gslY, *gslC;\n gsl_multifit_robust_workspace *workspace;\n gsl_multifit_robust_type *regressionType;\n gsl_multifit_robust_stats stats;\n int gslErrorCode;\n\n /* Turn off the default error handler, which aborts at the first error. */\n gsl_set_error_handler_off();\n\n /* Translate the integer type given into the corresponding GSL pointer */\n switch (method) {\n case 1: regressionType = gsl_multifit_robust_bisquare; break;\n case 2: regressionType = gsl_multifit_robust_cauchy; break;\n case 3: regressionType = gsl_multifit_robust_fair; break;\n case 4: regressionType = gsl_multifit_robust_huber; break;\n case 5: regressionType = gsl_multifit_robust_ols; break;\n case 6: regressionType = gsl_multifit_robust_welsch; break;\n }\n\n /* These structures can be allocated outside the pixel loop */\n gslCov = gsl_matrix_calloc(numParams, numParams);\n gslC = gsl_vector_calloc(numParams);\n\n /* Loop over all pixels */\n for (row=0; row= numParams) {\n workspace = gsl_multifit_robust_alloc(regressionType, n, numParams);\n gslX = gsl_matrix_calloc(n, numParams);\n gslY = gsl_vector_calloc(n);\n\n /* Copy the data from this pixel into the relevant GSL structures. Note\n that we skip over null values, based on nulls in the y variable.\n */\n n = 0;\n for (img=0; imgdata[n*gslY->stride] = y[yNdx];\n for (param=0; paramdata[n*gslX->tda + param] = x[xNdx];\n }\n n++;\n }\n }\n\n /* Do the regression fit */\n gslErrorCode = gsl_multifit_robust(gslX, gslY, gslC, gslCov, workspace);\n\n if (gslErrorCode == 0) {\n /* Copy the coefficients back into the image stack of coefficients */\n for (param=0; paramdata[param*gslC->stride];\n }\n\n /* Copy some useful statistics into their arrays */\n stats = gsl_multifit_robust_statistics(workspace);\n pixNdx = row*numCols + col;\n adj_Rsqrd[pixNdx] = stats.adj_Rsq;\n numIter[pixNdx] = stats.numit;\n rmse[pixNdx] = stats.rmse;\n }\n\n /* Free per-pixel structures */\n gsl_matrix_free(gslX);\n gsl_vector_free(gslY);\n gsl_multifit_robust_free(workspace);\n }\n }\n }\n\n\n /* Free the other structures */\n gsl_vector_free(gslC);\n gsl_matrix_free(gslCov);\n}\n", "meta": {"hexsha": "c1e0359178c8c66691978a3c2fa718202f2c3e09", "size": 6917, "ext": "c", "lang": "C", "max_stars_repo_path": "tmask/robreg.c", "max_stars_repo_name": "planetlabs/planet-tmask", "max_stars_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-08-14T04:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-09T08:49:02.000Z", "max_issues_repo_path": "tmask/robreg.c", "max_issues_repo_name": "planetlabs/planet-tmask", "max_issues_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tmask/robreg.c", "max_forks_repo_name": "planetlabs/planet-tmask", "max_forks_repo_head_hexsha": "f1f46e07c7ee45c3d11e066795e110a0019518e5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-20T10:39:55.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T02:08:24.000Z", "avg_line_length": 40.4502923977, "max_line_length": 102, "alphanum_fraction": 0.6116813648, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.29123481789530364}} {"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\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\n/* This file was automatically generated --- DO NOT EDIT */\n/* Generated on Sun Nov 7 20:45:16 EST 1999 */\n\n#include \n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-backward 16 */\n\n/*\n * This function contains 298 FP additions, 134 FP multiplications,\n * (or, 244 additions, 80 multiplications, 54 fused multiply/add),\n * 49 stack variables, and 128 memory accesses\n */\nstatic const fftw_real K1_961570560 = FFTW_KONST(+1.961570560806460898252364472268478073947867462);\nstatic const fftw_real K390180644 = FFTW_KONST(+0.390180644032256535696569736954044481855383236);\nstatic const fftw_real K1_111140466 = FFTW_KONST(+1.111140466039204449485661627897065748749874382);\nstatic const fftw_real K1_662939224 = FFTW_KONST(+1.662939224605090474157576755235811513477121624);\nstatic const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);\nstatic const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);\nstatic const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);\nstatic const fftw_real K765366864 = FFTW_KONST(+0.765366864730179543456919968060797733522689125);\nstatic const fftw_real K1_847759065 = FFTW_KONST(+1.847759065022573512256366378793576573644833252);\nstatic const fftw_real K1_414213562 = FFTW_KONST(+1.414213562373095048801688724209698078569671875);\nstatic const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);\n\n/*\n * Generator Id's : \n * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $\n * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $\n * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $\n */\n\nvoid fftw_hc2hc_backward_16(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist)\n{\n int i;\n fftw_real *X;\n fftw_real *Y;\n X = A;\n Y = A + (16 * iostride);\n {\n\t fftw_real tmp279;\n\t fftw_real tmp324;\n\t fftw_real tmp312;\n\t fftw_real tmp299;\n\t fftw_real tmp276;\n\t fftw_real tmp296;\n\t fftw_real tmp309;\n\t fftw_real tmp323;\n\t fftw_real tmp283;\n\t fftw_real tmp291;\n\t fftw_real tmp286;\n\t fftw_real tmp294;\n\t fftw_real tmp301;\n\t fftw_real tmp319;\n\t fftw_real tmp327;\n\t fftw_real tmp326;\n\t fftw_real tmp316;\n\t fftw_real tmp302;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp277;\n\t fftw_real tmp278;\n\t fftw_real tmp310;\n\t fftw_real tmp297;\n\t fftw_real tmp298;\n\t fftw_real tmp311;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp277 = X[2 * iostride];\n\t tmp278 = X[6 * iostride];\n\t tmp310 = tmp277 - tmp278;\n\t tmp297 = Y[-2 * iostride];\n\t tmp298 = Y[-6 * iostride];\n\t tmp311 = tmp298 + tmp297;\n\t tmp279 = K2_000000000 * (tmp277 + tmp278);\n\t tmp324 = K1_414213562 * (tmp310 + tmp311);\n\t tmp312 = K1_414213562 * (tmp310 - tmp311);\n\t tmp299 = K2_000000000 * (tmp297 - tmp298);\n\t }\n\t {\n\t fftw_real tmp275;\n\t fftw_real tmp308;\n\t fftw_real tmp273;\n\t fftw_real tmp306;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp274;\n\t\t fftw_real tmp307;\n\t\t fftw_real tmp271;\n\t\t fftw_real tmp272;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp274 = X[4 * iostride];\n\t\t tmp275 = K2_000000000 * tmp274;\n\t\t tmp307 = Y[-4 * iostride];\n\t\t tmp308 = K2_000000000 * tmp307;\n\t\t tmp271 = X[0];\n\t\t tmp272 = X[8 * iostride];\n\t\t tmp273 = tmp271 + tmp272;\n\t\t tmp306 = tmp271 - tmp272;\n\t }\n\t tmp276 = tmp273 + tmp275;\n\t tmp296 = tmp273 - tmp275;\n\t tmp309 = tmp306 - tmp308;\n\t tmp323 = tmp306 + tmp308;\n\t }\n\t {\n\t fftw_real tmp314;\n\t fftw_real tmp318;\n\t fftw_real tmp317;\n\t fftw_real tmp315;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp281;\n\t\t fftw_real tmp282;\n\t\t fftw_real tmp289;\n\t\t fftw_real tmp290;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp281 = X[iostride];\n\t\t tmp282 = X[7 * iostride];\n\t\t tmp283 = tmp281 + tmp282;\n\t\t tmp314 = tmp281 - tmp282;\n\t\t tmp289 = Y[-iostride];\n\t\t tmp290 = Y[-7 * iostride];\n\t\t tmp291 = tmp289 - tmp290;\n\t\t tmp318 = tmp289 + tmp290;\n\t }\n\t {\n\t\t fftw_real tmp284;\n\t\t fftw_real tmp285;\n\t\t fftw_real tmp292;\n\t\t fftw_real tmp293;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp284 = X[3 * iostride];\n\t\t tmp285 = X[5 * iostride];\n\t\t tmp286 = tmp284 + tmp285;\n\t\t tmp317 = tmp285 - tmp284;\n\t\t tmp292 = Y[-3 * iostride];\n\t\t tmp293 = Y[-5 * iostride];\n\t\t tmp294 = tmp292 - tmp293;\n\t\t tmp315 = tmp293 + tmp292;\n\t }\n\t tmp301 = tmp283 - tmp286;\n\t tmp319 = tmp317 + tmp318;\n\t tmp327 = tmp318 - tmp317;\n\t tmp326 = tmp314 + tmp315;\n\t tmp316 = tmp314 - tmp315;\n\t tmp302 = tmp294 + tmp291;\n\t }\n\t {\n\t fftw_real tmp280;\n\t fftw_real tmp287;\n\t fftw_real tmp288;\n\t fftw_real tmp295;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp280 = tmp276 + tmp279;\n\t tmp287 = K2_000000000 * (tmp283 + tmp286);\n\t X[8 * iostride] = tmp280 - tmp287;\n\t X[0] = tmp280 + tmp287;\n\t tmp288 = tmp276 - tmp279;\n\t tmp295 = K2_000000000 * (tmp291 - tmp294);\n\t X[12 * iostride] = tmp288 + tmp295;\n\t X[4 * iostride] = tmp288 - tmp295;\n\t }\n\t {\n\t fftw_real tmp300;\n\t fftw_real tmp303;\n\t fftw_real tmp304;\n\t fftw_real tmp305;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp300 = tmp296 - tmp299;\n\t tmp303 = K1_414213562 * (tmp301 - tmp302);\n\t X[10 * iostride] = tmp300 - tmp303;\n\t X[2 * iostride] = tmp300 + tmp303;\n\t tmp304 = tmp296 + tmp299;\n\t tmp305 = K1_414213562 * (tmp301 + tmp302);\n\t X[6 * iostride] = tmp304 - tmp305;\n\t X[14 * iostride] = tmp304 + tmp305;\n\t }\n\t {\n\t fftw_real tmp313;\n\t fftw_real tmp320;\n\t fftw_real tmp321;\n\t fftw_real tmp322;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp313 = tmp309 + tmp312;\n\t tmp320 = (K1_847759065 * tmp316) - (K765366864 * tmp319);\n\t X[9 * iostride] = tmp313 - tmp320;\n\t X[iostride] = tmp313 + tmp320;\n\t tmp321 = tmp309 - tmp312;\n\t tmp322 = (K765366864 * tmp316) + (K1_847759065 * tmp319);\n\t X[5 * iostride] = tmp321 - tmp322;\n\t X[13 * iostride] = tmp321 + tmp322;\n\t }\n\t {\n\t fftw_real tmp325;\n\t fftw_real tmp328;\n\t fftw_real tmp329;\n\t fftw_real tmp330;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp325 = tmp323 - tmp324;\n\t tmp328 = (K765366864 * tmp326) - (K1_847759065 * tmp327);\n\t X[11 * iostride] = tmp325 - tmp328;\n\t X[3 * iostride] = tmp325 + tmp328;\n\t tmp329 = tmp323 + tmp324;\n\t tmp330 = (K1_847759065 * tmp326) + (K765366864 * tmp327);\n\t X[7 * iostride] = tmp329 - tmp330;\n\t X[15 * iostride] = tmp329 + tmp330;\n\t }\n }\n X = X + dist;\n Y = Y - dist;\n for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 15) {\n\t fftw_real tmp73;\n\t fftw_real tmp98;\n\t fftw_real tmp135;\n\t fftw_real tmp160;\n\t fftw_real tmp182;\n\t fftw_real tmp236;\n\t fftw_real tmp210;\n\t fftw_real tmp248;\n\t fftw_real tmp95;\n\t fftw_real tmp124;\n\t fftw_real tmp138;\n\t fftw_real tmp164;\n\t fftw_real tmp197;\n\t fftw_real tmp216;\n\t fftw_real tmp244;\n\t fftw_real tmp252;\n\t fftw_real tmp80;\n\t fftw_real tmp128;\n\t fftw_real tmp105;\n\t fftw_real tmp161;\n\t fftw_real tmp213;\n\t fftw_real tmp237;\n\t fftw_real tmp189;\n\t fftw_real tmp249;\n\t fftw_real tmp88;\n\t fftw_real tmp115;\n\t fftw_real tmp137;\n\t fftw_real tmp163;\n\t fftw_real tmp204;\n\t fftw_real tmp215;\n\t fftw_real tmp241;\n\t fftw_real tmp251;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp69;\n\t fftw_real tmp180;\n\t fftw_real tmp131;\n\t fftw_real tmp209;\n\t fftw_real tmp72;\n\t fftw_real tmp208;\n\t fftw_real tmp134;\n\t fftw_real tmp181;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp67;\n\t\t fftw_real tmp68;\n\t\t fftw_real tmp129;\n\t\t fftw_real tmp130;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp67 = X[0];\n\t\t tmp68 = Y[-8 * iostride];\n\t\t tmp69 = tmp67 + tmp68;\n\t\t tmp180 = tmp67 - tmp68;\n\t\t tmp129 = Y[0];\n\t\t tmp130 = X[8 * iostride];\n\t\t tmp131 = tmp129 - tmp130;\n\t\t tmp209 = tmp129 + tmp130;\n\t }\n\t {\n\t\t fftw_real tmp70;\n\t\t fftw_real tmp71;\n\t\t fftw_real tmp132;\n\t\t fftw_real tmp133;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp70 = X[4 * iostride];\n\t\t tmp71 = Y[-12 * iostride];\n\t\t tmp72 = tmp70 + tmp71;\n\t\t tmp208 = tmp70 - tmp71;\n\t\t tmp132 = Y[-4 * iostride];\n\t\t tmp133 = X[12 * iostride];\n\t\t tmp134 = tmp132 - tmp133;\n\t\t tmp181 = tmp132 + tmp133;\n\t }\n\t tmp73 = tmp69 + tmp72;\n\t tmp98 = tmp69 - tmp72;\n\t tmp135 = tmp131 - tmp134;\n\t tmp160 = tmp131 + tmp134;\n\t tmp182 = tmp180 - tmp181;\n\t tmp236 = tmp180 + tmp181;\n\t tmp210 = tmp208 + tmp209;\n\t tmp248 = tmp209 - tmp208;\n\t }\n\t {\n\t fftw_real tmp91;\n\t fftw_real tmp194;\n\t fftw_real tmp119;\n\t fftw_real tmp192;\n\t fftw_real tmp94;\n\t fftw_real tmp191;\n\t fftw_real tmp122;\n\t fftw_real tmp195;\n\t fftw_real tmp116;\n\t fftw_real tmp123;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp89;\n\t\t fftw_real tmp90;\n\t\t fftw_real tmp117;\n\t\t fftw_real tmp118;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp89 = Y[-15 * iostride];\n\t\t tmp90 = X[7 * iostride];\n\t\t tmp91 = tmp89 + tmp90;\n\t\t tmp194 = tmp89 - tmp90;\n\t\t tmp117 = Y[-7 * iostride];\n\t\t tmp118 = X[15 * iostride];\n\t\t tmp119 = tmp117 - tmp118;\n\t\t tmp192 = tmp117 + tmp118;\n\t }\n\t {\n\t\t fftw_real tmp92;\n\t\t fftw_real tmp93;\n\t\t fftw_real tmp120;\n\t\t fftw_real tmp121;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp92 = X[3 * iostride];\n\t\t tmp93 = Y[-11 * iostride];\n\t\t tmp94 = tmp92 + tmp93;\n\t\t tmp191 = tmp92 - tmp93;\n\t\t tmp120 = Y[-3 * iostride];\n\t\t tmp121 = X[11 * iostride];\n\t\t tmp122 = tmp120 - tmp121;\n\t\t tmp195 = tmp120 + tmp121;\n\t }\n\t tmp95 = tmp91 + tmp94;\n\t tmp116 = tmp91 - tmp94;\n\t tmp123 = tmp119 - tmp122;\n\t tmp124 = tmp116 + tmp123;\n\t tmp138 = tmp123 - tmp116;\n\t tmp164 = tmp119 + tmp122;\n\t {\n\t\t fftw_real tmp193;\n\t\t fftw_real tmp196;\n\t\t fftw_real tmp242;\n\t\t fftw_real tmp243;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp193 = tmp191 - tmp192;\n\t\t tmp196 = tmp194 - tmp195;\n\t\t tmp197 = (K923879532 * tmp193) - (K382683432 * tmp196);\n\t\t tmp216 = (K382683432 * tmp193) + (K923879532 * tmp196);\n\t\t tmp242 = tmp194 + tmp195;\n\t\t tmp243 = tmp191 + tmp192;\n\t\t tmp244 = (K382683432 * tmp242) - (K923879532 * tmp243);\n\t\t tmp252 = (K382683432 * tmp243) + (K923879532 * tmp242);\n\t }\n\t }\n\t {\n\t fftw_real tmp76;\n\t fftw_real tmp183;\n\t fftw_real tmp104;\n\t fftw_real tmp184;\n\t fftw_real tmp79;\n\t fftw_real tmp186;\n\t fftw_real tmp101;\n\t fftw_real tmp187;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp74;\n\t\t fftw_real tmp75;\n\t\t fftw_real tmp102;\n\t\t fftw_real tmp103;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp74 = X[2 * iostride];\n\t\t tmp75 = Y[-10 * iostride];\n\t\t tmp76 = tmp74 + tmp75;\n\t\t tmp183 = tmp74 - tmp75;\n\t\t tmp102 = Y[-2 * iostride];\n\t\t tmp103 = X[10 * iostride];\n\t\t tmp104 = tmp102 - tmp103;\n\t\t tmp184 = tmp102 + tmp103;\n\t }\n\t {\n\t\t fftw_real tmp77;\n\t\t fftw_real tmp78;\n\t\t fftw_real tmp99;\n\t\t fftw_real tmp100;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp77 = Y[-14 * iostride];\n\t\t tmp78 = X[6 * iostride];\n\t\t tmp79 = tmp77 + tmp78;\n\t\t tmp186 = tmp77 - tmp78;\n\t\t tmp99 = Y[-6 * iostride];\n\t\t tmp100 = X[14 * iostride];\n\t\t tmp101 = tmp99 - tmp100;\n\t\t tmp187 = tmp99 + tmp100;\n\t }\n\t tmp80 = tmp76 + tmp79;\n\t tmp128 = tmp76 - tmp79;\n\t tmp105 = tmp101 - tmp104;\n\t tmp161 = tmp104 + tmp101;\n\t {\n\t\t fftw_real tmp211;\n\t\t fftw_real tmp212;\n\t\t fftw_real tmp185;\n\t\t fftw_real tmp188;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp211 = tmp183 + tmp184;\n\t\t tmp212 = tmp186 + tmp187;\n\t\t tmp213 = K707106781 * (tmp211 - tmp212);\n\t\t tmp237 = K707106781 * (tmp211 + tmp212);\n\t\t tmp185 = tmp183 - tmp184;\n\t\t tmp188 = tmp186 - tmp187;\n\t\t tmp189 = K707106781 * (tmp185 + tmp188);\n\t\t tmp249 = K707106781 * (tmp185 - tmp188);\n\t }\n\t }\n\t {\n\t fftw_real tmp84;\n\t fftw_real tmp201;\n\t fftw_real tmp110;\n\t fftw_real tmp199;\n\t fftw_real tmp87;\n\t fftw_real tmp198;\n\t fftw_real tmp113;\n\t fftw_real tmp202;\n\t fftw_real tmp107;\n\t fftw_real tmp114;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp82;\n\t\t fftw_real tmp83;\n\t\t fftw_real tmp108;\n\t\t fftw_real tmp109;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp82 = X[iostride];\n\t\t tmp83 = Y[-9 * iostride];\n\t\t tmp84 = tmp82 + tmp83;\n\t\t tmp201 = tmp82 - tmp83;\n\t\t tmp108 = Y[-iostride];\n\t\t tmp109 = X[9 * iostride];\n\t\t tmp110 = tmp108 - tmp109;\n\t\t tmp199 = tmp108 + tmp109;\n\t }\n\t {\n\t\t fftw_real tmp85;\n\t\t fftw_real tmp86;\n\t\t fftw_real tmp111;\n\t\t fftw_real tmp112;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp85 = X[5 * iostride];\n\t\t tmp86 = Y[-13 * iostride];\n\t\t tmp87 = tmp85 + tmp86;\n\t\t tmp198 = tmp85 - tmp86;\n\t\t tmp111 = Y[-5 * iostride];\n\t\t tmp112 = X[13 * iostride];\n\t\t tmp113 = tmp111 - tmp112;\n\t\t tmp202 = tmp111 + tmp112;\n\t }\n\t tmp88 = tmp84 + tmp87;\n\t tmp107 = tmp84 - tmp87;\n\t tmp114 = tmp110 - tmp113;\n\t tmp115 = tmp107 - tmp114;\n\t tmp137 = tmp107 + tmp114;\n\t tmp163 = tmp110 + tmp113;\n\t {\n\t\t fftw_real tmp200;\n\t\t fftw_real tmp203;\n\t\t fftw_real tmp239;\n\t\t fftw_real tmp240;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp200 = tmp198 + tmp199;\n\t\t tmp203 = tmp201 - tmp202;\n\t\t tmp204 = (K923879532 * tmp200) + (K382683432 * tmp203);\n\t\t tmp215 = (K923879532 * tmp203) - (K382683432 * tmp200);\n\t\t tmp239 = tmp201 + tmp202;\n\t\t tmp240 = tmp199 - tmp198;\n\t\t tmp241 = (K382683432 * tmp239) - (K923879532 * tmp240);\n\t\t tmp251 = (K382683432 * tmp240) + (K923879532 * tmp239);\n\t }\n\t }\n\t {\n\t fftw_real tmp81;\n\t fftw_real tmp96;\n\t fftw_real tmp158;\n\t fftw_real tmp162;\n\t fftw_real tmp165;\n\t fftw_real tmp166;\n\t fftw_real tmp157;\n\t fftw_real tmp159;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp81 = tmp73 + tmp80;\n\t tmp96 = tmp88 + tmp95;\n\t tmp158 = tmp81 - tmp96;\n\t tmp162 = tmp160 + tmp161;\n\t tmp165 = tmp163 + tmp164;\n\t tmp166 = tmp162 - tmp165;\n\t X[0] = tmp81 + tmp96;\n\t Y[-15 * iostride] = tmp162 + tmp165;\n\t tmp157 = c_re(W[7]);\n\t tmp159 = c_im(W[7]);\n\t X[8 * iostride] = (tmp157 * tmp158) + (tmp159 * tmp166);\n\t Y[-7 * iostride] = (tmp157 * tmp166) - (tmp159 * tmp158);\n\t }\n\t {\n\t fftw_real tmp170;\n\t fftw_real tmp176;\n\t fftw_real tmp174;\n\t fftw_real tmp178;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp168;\n\t\t fftw_real tmp169;\n\t\t fftw_real tmp172;\n\t\t fftw_real tmp173;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp168 = tmp160 - tmp161;\n\t\t tmp169 = tmp88 - tmp95;\n\t\t tmp170 = tmp168 - tmp169;\n\t\t tmp176 = tmp169 + tmp168;\n\t\t tmp172 = tmp73 - tmp80;\n\t\t tmp173 = tmp164 - tmp163;\n\t\t tmp174 = tmp172 - tmp173;\n\t\t tmp178 = tmp172 + tmp173;\n\t }\n\t {\n\t\t fftw_real tmp167;\n\t\t fftw_real tmp171;\n\t\t fftw_real tmp175;\n\t\t fftw_real tmp177;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp167 = c_re(W[11]);\n\t\t tmp171 = c_im(W[11]);\n\t\t Y[-3 * iostride] = (tmp167 * tmp170) - (tmp171 * tmp174);\n\t\t X[12 * iostride] = (tmp171 * tmp170) + (tmp167 * tmp174);\n\t\t tmp175 = c_re(W[3]);\n\t\t tmp177 = c_im(W[3]);\n\t\t Y[-11 * iostride] = (tmp175 * tmp176) - (tmp177 * tmp178);\n\t\t X[4 * iostride] = (tmp177 * tmp176) + (tmp175 * tmp178);\n\t }\n\t }\n\t {\n\t fftw_real tmp126;\n\t fftw_real tmp142;\n\t fftw_real tmp140;\n\t fftw_real tmp144;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp106;\n\t\t fftw_real tmp125;\n\t\t fftw_real tmp136;\n\t\t fftw_real tmp139;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp106 = tmp98 + tmp105;\n\t\t tmp125 = K707106781 * (tmp115 + tmp124);\n\t\t tmp126 = tmp106 - tmp125;\n\t\t tmp142 = tmp106 + tmp125;\n\t\t tmp136 = tmp128 + tmp135;\n\t\t tmp139 = K707106781 * (tmp137 + tmp138);\n\t\t tmp140 = tmp136 - tmp139;\n\t\t tmp144 = tmp136 + tmp139;\n\t }\n\t {\n\t\t fftw_real tmp97;\n\t\t fftw_real tmp127;\n\t\t fftw_real tmp141;\n\t\t fftw_real tmp143;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp97 = c_re(W[9]);\n\t\t tmp127 = c_im(W[9]);\n\t\t X[10 * iostride] = (tmp97 * tmp126) + (tmp127 * tmp140);\n\t\t Y[-5 * iostride] = (tmp97 * tmp140) - (tmp127 * tmp126);\n\t\t tmp141 = c_re(W[1]);\n\t\t tmp143 = c_im(W[1]);\n\t\t X[2 * iostride] = (tmp141 * tmp142) + (tmp143 * tmp144);\n\t\t Y[-13 * iostride] = (tmp141 * tmp144) - (tmp143 * tmp142);\n\t }\n\t }\n\t {\n\t fftw_real tmp148;\n\t fftw_real tmp154;\n\t fftw_real tmp152;\n\t fftw_real tmp156;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp146;\n\t\t fftw_real tmp147;\n\t\t fftw_real tmp150;\n\t\t fftw_real tmp151;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp146 = tmp135 - tmp128;\n\t\t tmp147 = K707106781 * (tmp115 - tmp124);\n\t\t tmp148 = tmp146 - tmp147;\n\t\t tmp154 = tmp146 + tmp147;\n\t\t tmp150 = tmp98 - tmp105;\n\t\t tmp151 = K707106781 * (tmp138 - tmp137);\n\t\t tmp152 = tmp150 - tmp151;\n\t\t tmp156 = tmp150 + tmp151;\n\t }\n\t {\n\t\t fftw_real tmp145;\n\t\t fftw_real tmp149;\n\t\t fftw_real tmp153;\n\t\t fftw_real tmp155;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp145 = c_re(W[13]);\n\t\t tmp149 = c_im(W[13]);\n\t\t Y[-iostride] = (tmp145 * tmp148) - (tmp149 * tmp152);\n\t\t X[14 * iostride] = (tmp149 * tmp148) + (tmp145 * tmp152);\n\t\t tmp153 = c_re(W[5]);\n\t\t tmp155 = c_im(W[5]);\n\t\t Y[-9 * iostride] = (tmp153 * tmp154) - (tmp155 * tmp156);\n\t\t X[6 * iostride] = (tmp155 * tmp154) + (tmp153 * tmp156);\n\t }\n\t }\n\t {\n\t fftw_real tmp206;\n\t fftw_real tmp220;\n\t fftw_real tmp218;\n\t fftw_real tmp222;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp190;\n\t\t fftw_real tmp205;\n\t\t fftw_real tmp214;\n\t\t fftw_real tmp217;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp190 = tmp182 - tmp189;\n\t\t tmp205 = tmp197 - tmp204;\n\t\t tmp206 = tmp190 - tmp205;\n\t\t tmp220 = tmp190 + tmp205;\n\t\t tmp214 = tmp210 - tmp213;\n\t\t tmp217 = tmp215 - tmp216;\n\t\t tmp218 = tmp214 - tmp217;\n\t\t tmp222 = tmp214 + tmp217;\n\t }\n\t {\n\t\t fftw_real tmp179;\n\t\t fftw_real tmp207;\n\t\t fftw_real tmp219;\n\t\t fftw_real tmp221;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp179 = c_re(W[12]);\n\t\t tmp207 = c_im(W[12]);\n\t\t X[13 * iostride] = (tmp179 * tmp206) + (tmp207 * tmp218);\n\t\t Y[-2 * iostride] = (tmp179 * tmp218) - (tmp207 * tmp206);\n\t\t tmp219 = c_re(W[4]);\n\t\t tmp221 = c_im(W[4]);\n\t\t X[5 * iostride] = (tmp219 * tmp220) + (tmp221 * tmp222);\n\t\t Y[-10 * iostride] = (tmp219 * tmp222) - (tmp221 * tmp220);\n\t }\n\t }\n\t {\n\t fftw_real tmp226;\n\t fftw_real tmp232;\n\t fftw_real tmp230;\n\t fftw_real tmp234;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp224;\n\t\t fftw_real tmp225;\n\t\t fftw_real tmp228;\n\t\t fftw_real tmp229;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp224 = tmp210 + tmp213;\n\t\t tmp225 = tmp204 + tmp197;\n\t\t tmp226 = tmp224 - tmp225;\n\t\t tmp232 = tmp224 + tmp225;\n\t\t tmp228 = tmp182 + tmp189;\n\t\t tmp229 = tmp215 + tmp216;\n\t\t tmp230 = tmp228 - tmp229;\n\t\t tmp234 = tmp228 + tmp229;\n\t }\n\t {\n\t\t fftw_real tmp223;\n\t\t fftw_real tmp227;\n\t\t fftw_real tmp231;\n\t\t fftw_real tmp233;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp223 = c_re(W[8]);\n\t\t tmp227 = c_im(W[8]);\n\t\t Y[-6 * iostride] = (tmp223 * tmp226) - (tmp227 * tmp230);\n\t\t X[9 * iostride] = (tmp227 * tmp226) + (tmp223 * tmp230);\n\t\t tmp231 = c_re(W[0]);\n\t\t tmp233 = c_im(W[0]);\n\t\t Y[-14 * iostride] = (tmp231 * tmp232) - (tmp233 * tmp234);\n\t\t X[iostride] = (tmp233 * tmp232) + (tmp231 * tmp234);\n\t }\n\t }\n\t {\n\t fftw_real tmp246;\n\t fftw_real tmp256;\n\t fftw_real tmp254;\n\t fftw_real tmp258;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp238;\n\t\t fftw_real tmp245;\n\t\t fftw_real tmp250;\n\t\t fftw_real tmp253;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp238 = tmp236 - tmp237;\n\t\t tmp245 = tmp241 + tmp244;\n\t\t tmp246 = tmp238 - tmp245;\n\t\t tmp256 = tmp238 + tmp245;\n\t\t tmp250 = tmp248 + tmp249;\n\t\t tmp253 = tmp251 - tmp252;\n\t\t tmp254 = tmp250 - tmp253;\n\t\t tmp258 = tmp250 + tmp253;\n\t }\n\t {\n\t\t fftw_real tmp235;\n\t\t fftw_real tmp247;\n\t\t fftw_real tmp255;\n\t\t fftw_real tmp257;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp235 = c_re(W[10]);\n\t\t tmp247 = c_im(W[10]);\n\t\t X[11 * iostride] = (tmp235 * tmp246) + (tmp247 * tmp254);\n\t\t Y[-4 * iostride] = (tmp235 * tmp254) - (tmp247 * tmp246);\n\t\t tmp255 = c_re(W[2]);\n\t\t tmp257 = c_im(W[2]);\n\t\t X[3 * iostride] = (tmp255 * tmp256) + (tmp257 * tmp258);\n\t\t Y[-12 * iostride] = (tmp255 * tmp258) - (tmp257 * tmp256);\n\t }\n\t }\n\t {\n\t fftw_real tmp262;\n\t fftw_real tmp268;\n\t fftw_real tmp266;\n\t fftw_real tmp270;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp260;\n\t\t fftw_real tmp261;\n\t\t fftw_real tmp264;\n\t\t fftw_real tmp265;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp260 = tmp248 - tmp249;\n\t\t tmp261 = tmp241 - tmp244;\n\t\t tmp262 = tmp260 + tmp261;\n\t\t tmp268 = tmp260 - tmp261;\n\t\t tmp264 = tmp236 + tmp237;\n\t\t tmp265 = tmp251 + tmp252;\n\t\t tmp266 = tmp264 - tmp265;\n\t\t tmp270 = tmp264 + tmp265;\n\t }\n\t {\n\t\t fftw_real tmp259;\n\t\t fftw_real tmp263;\n\t\t fftw_real tmp267;\n\t\t fftw_real tmp269;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp259 = c_re(W[6]);\n\t\t tmp263 = c_im(W[6]);\n\t\t Y[-8 * iostride] = (tmp259 * tmp262) - (tmp263 * tmp266);\n\t\t X[7 * iostride] = (tmp263 * tmp262) + (tmp259 * tmp266);\n\t\t tmp267 = c_re(W[14]);\n\t\t tmp269 = c_im(W[14]);\n\t\t Y[0] = (tmp267 * tmp268) - (tmp269 * tmp270);\n\t\t X[15 * iostride] = (tmp269 * tmp268) + (tmp267 * tmp270);\n\t }\n\t }\n }\n if (i == m) {\n\t fftw_real tmp7;\n\t fftw_real tmp51;\n\t fftw_real tmp19;\n\t fftw_real tmp43;\n\t fftw_real tmp39;\n\t fftw_real tmp47;\n\t fftw_real tmp59;\n\t fftw_real tmp64;\n\t fftw_real tmp14;\n\t fftw_real tmp56;\n\t fftw_real tmp24;\n\t fftw_real tmp32;\n\t fftw_real tmp29;\n\t fftw_real tmp33;\n\t fftw_real tmp54;\n\t fftw_real tmp65;\n\t fftw_real tmp63;\n\t fftw_real tmp66;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp3;\n\t fftw_real tmp15;\n\t fftw_real tmp38;\n\t fftw_real tmp57;\n\t fftw_real tmp6;\n\t fftw_real tmp35;\n\t fftw_real tmp18;\n\t fftw_real tmp58;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp1;\n\t\t fftw_real tmp2;\n\t\t fftw_real tmp36;\n\t\t fftw_real tmp37;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp1 = X[0];\n\t\t tmp2 = X[7 * iostride];\n\t\t tmp3 = tmp1 + tmp2;\n\t\t tmp15 = tmp1 - tmp2;\n\t\t tmp36 = Y[0];\n\t\t tmp37 = Y[-7 * iostride];\n\t\t tmp38 = tmp36 + tmp37;\n\t\t tmp57 = tmp36 - tmp37;\n\t }\n\t {\n\t\t fftw_real tmp4;\n\t\t fftw_real tmp5;\n\t\t fftw_real tmp16;\n\t\t fftw_real tmp17;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp4 = X[4 * iostride];\n\t\t tmp5 = X[3 * iostride];\n\t\t tmp6 = tmp4 + tmp5;\n\t\t tmp35 = tmp4 - tmp5;\n\t\t tmp16 = Y[-4 * iostride];\n\t\t tmp17 = Y[-3 * iostride];\n\t\t tmp18 = tmp16 + tmp17;\n\t\t tmp58 = tmp16 - tmp17;\n\t }\n\t tmp7 = tmp3 + tmp6;\n\t tmp51 = tmp3 - tmp6;\n\t tmp19 = tmp15 - tmp18;\n\t tmp43 = tmp15 + tmp18;\n\t tmp39 = tmp35 + tmp38;\n\t tmp47 = tmp38 - tmp35;\n\t tmp59 = tmp57 - tmp58;\n\t tmp64 = tmp58 + tmp57;\n\t }\n\t {\n\t fftw_real tmp10;\n\t fftw_real tmp20;\n\t fftw_real tmp23;\n\t fftw_real tmp53;\n\t fftw_real tmp13;\n\t fftw_real tmp25;\n\t fftw_real tmp28;\n\t fftw_real tmp52;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp8;\n\t\t fftw_real tmp9;\n\t\t fftw_real tmp21;\n\t\t fftw_real tmp22;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp8 = X[2 * iostride];\n\t\t tmp9 = X[5 * iostride];\n\t\t tmp10 = tmp8 + tmp9;\n\t\t tmp20 = tmp8 - tmp9;\n\t\t tmp21 = Y[-2 * iostride];\n\t\t tmp22 = Y[-5 * iostride];\n\t\t tmp23 = tmp21 + tmp22;\n\t\t tmp53 = tmp21 - tmp22;\n\t }\n\t {\n\t\t fftw_real tmp11;\n\t\t fftw_real tmp12;\n\t\t fftw_real tmp26;\n\t\t fftw_real tmp27;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp11 = X[iostride];\n\t\t tmp12 = X[6 * iostride];\n\t\t tmp13 = tmp11 + tmp12;\n\t\t tmp25 = tmp11 - tmp12;\n\t\t tmp26 = Y[-iostride];\n\t\t tmp27 = Y[-6 * iostride];\n\t\t tmp28 = tmp26 + tmp27;\n\t\t tmp52 = tmp27 - tmp26;\n\t }\n\t tmp14 = tmp10 + tmp13;\n\t tmp56 = tmp10 - tmp13;\n\t tmp24 = tmp20 - tmp23;\n\t tmp32 = tmp20 + tmp23;\n\t tmp29 = tmp25 - tmp28;\n\t tmp33 = tmp25 + tmp28;\n\t tmp54 = tmp52 - tmp53;\n\t tmp65 = tmp53 + tmp52;\n\t }\n\t X[0] = K2_000000000 * (tmp7 + tmp14);\n\t X[8 * iostride] = -(K2_000000000 * (tmp65 + tmp64));\n\t tmp63 = tmp7 - tmp14;\n\t tmp66 = tmp64 - tmp65;\n\t X[4 * iostride] = K1_414213562 * (tmp63 - tmp66);\n\t X[12 * iostride] = -(K1_414213562 * (tmp63 + tmp66));\n\t {\n\t fftw_real tmp61;\n\t fftw_real tmp62;\n\t fftw_real tmp55;\n\t fftw_real tmp60;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp61 = tmp51 - tmp54;\n\t tmp62 = tmp59 - tmp56;\n\t X[6 * iostride] = (K765366864 * tmp61) - (K1_847759065 * tmp62);\n\t X[14 * iostride] = -((K1_847759065 * tmp61) + (K765366864 * tmp62));\n\t tmp55 = tmp51 + tmp54;\n\t tmp60 = tmp56 + tmp59;\n\t X[2 * iostride] = (K1_847759065 * tmp55) - (K765366864 * tmp60);\n\t X[10 * iostride] = -((K765366864 * tmp55) + (K1_847759065 * tmp60));\n\t }\n\t {\n\t fftw_real tmp45;\n\t fftw_real tmp49;\n\t fftw_real tmp48;\n\t fftw_real tmp50;\n\t fftw_real tmp44;\n\t fftw_real tmp46;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp44 = K707106781 * (tmp32 + tmp33);\n\t tmp45 = tmp43 - tmp44;\n\t tmp49 = tmp43 + tmp44;\n\t tmp46 = K707106781 * (tmp24 - tmp29);\n\t tmp48 = tmp46 + tmp47;\n\t tmp50 = tmp47 - tmp46;\n\t X[3 * iostride] = (K1_662939224 * tmp45) - (K1_111140466 * tmp48);\n\t X[11 * iostride] = -((K1_111140466 * tmp45) + (K1_662939224 * tmp48));\n\t X[7 * iostride] = (K390180644 * tmp49) - (K1_961570560 * tmp50);\n\t X[15 * iostride] = -((K1_961570560 * tmp49) + (K390180644 * tmp50));\n\t }\n\t {\n\t fftw_real tmp31;\n\t fftw_real tmp41;\n\t fftw_real tmp40;\n\t fftw_real tmp42;\n\t fftw_real tmp30;\n\t fftw_real tmp34;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp30 = K707106781 * (tmp24 + tmp29);\n\t tmp31 = tmp19 + tmp30;\n\t tmp41 = tmp19 - tmp30;\n\t tmp34 = K707106781 * (tmp32 - tmp33);\n\t tmp40 = tmp34 + tmp39;\n\t tmp42 = tmp39 - tmp34;\n\t X[iostride] = (K1_961570560 * tmp31) - (K390180644 * tmp40);\n\t X[9 * iostride] = -((K390180644 * tmp31) + (K1_961570560 * tmp40));\n\t X[5 * iostride] = (K1_111140466 * tmp41) - (K1_662939224 * tmp42);\n\t X[13 * iostride] = -((K1_662939224 * tmp41) + (K1_111140466 * tmp42));\n\t }\n }\n}\n\nstatic const int twiddle_order[] =\n{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};\nfftw_codelet_desc fftw_hc2hc_backward_16_desc =\n{\n \"fftw_hc2hc_backward_16\",\n (void (*)()) fftw_hc2hc_backward_16,\n 16,\n FFTW_BACKWARD,\n FFTW_HC2HC,\n 366,\n 15,\n twiddle_order,\n};\n", "meta": {"hexsha": "9d65fa1e7f5442f7463eff4903cebda6bed53f85", "size": 28453, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_16.c", "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_16.c", "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_16.c", "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "avg_line_length": 29.1228249744, "max_line_length": 126, "alphanum_fraction": 0.5712578638, "num_tokens": 9029, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.29033666119826085}} {"text": "/* im_invfft\n *\n * Copyright: 1990, N. Dessipris.\n *\n * Author: Nicos Dessipris \n * Written on: 12/04/1990\n * Modified on :\n * 28/6/95 JC\n *\t- rewritten, based on new im_fwfft() code\n * 10/9/98 JC\n *\t- frees memory more quickly\n * 2/4/02 JC\n *\t- fftw code added\n * 13/7/02 JC\n *\t- Type reset\n * 27/2/03 JC\n *\t- tiny speed-up ... save 1 copy on write\n * 22/1/04 JC\n *\t- oops, fix for segv on wider than high fftw transforms\n * 3/11/04\n *\t- added fftw3 support\n * 7/2/10\n * \t- gtkdoc\n */\n\n/*\n\n This file is part of VIPS.\n \n VIPS is free software; you can redistribute it and/or modify\n it under the terms of the GNU Lesser General Public License as published by\n the Free Software Foundation; either version 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 Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public License\n along with 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\n/*\n\n These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk\n\n */\n\n#ifdef HAVE_CONFIG_H\n#include \n#endif /*HAVE_CONFIG_H*/\n#include \n\n#include \n#include \n\n#ifdef HAVE_FFTW\n#include \n#endif /*HAVE_FFTW*/\n\n#ifdef HAVE_FFTW3\n#include \n#endif /*HAVE_FFTW3*/\n\n#include \n#include \n\n#ifdef WITH_DMALLOC\n#include \n#endif /*WITH_DMALLOC*/\n\n#ifdef HAVE_FFTW\n/* Call fftw for a 1 band image.\n */\nstatic int \ninvfft1( IMAGE *dummy, IMAGE *in, IMAGE *out )\n{\n\tfftwnd_plan plan;\n\n\tIMAGE *cmplx = im_open_local( out, \"invfft1:1\", \"t\" );\n\n\t/* Make dp complex image.\n\t */\n\tif( !cmplx || im_pincheck( in ) || im_poutcheck( out ) )\n\t\treturn( -1 );\n\tif( in->Coding != IM_CODING_NONE || in->Bands != 1 ) {\n im_error( \"im_invfft\", \"%s\", _( \"one band uncoded only\" ) );\n return( -1 );\n\t}\n\tif( im_clip2fmt( in, cmplx, IM_BANDFMT_DPCOMPLEX ) )\n return( -1 );\n\n\t/* Make the plan for the transform. Yes, they really do use nx for\n\t * height and ny for width.\n\t */\n\tif( !(plan = fftw2d_create_plan( in->Ysize, in->Xsize,\n\t\tFFTW_BACKWARD, \n\t\tFFTW_MEASURE | FFTW_USE_WISDOM | FFTW_IN_PLACE )) ) {\n im_error( \"im_invfft\", \n\t\t\t\"%s\", _( \"unable to create transform plan\" ) );\n\t\treturn( -1 );\n\t}\n\n\tfftwnd_one( plan, (fftw_complex *) cmplx->data, NULL );\n\n\tfftwnd_destroy_plan( plan );\n\n\t/* Copy to out.\n\t */\n if( im_copy( cmplx, out ) )\n return( -1 );\n\n\treturn( 0 );\n}\n#else /*!HAVE_FFTW*/\n#ifdef HAVE_FFTW3\n/* Complex to complex inverse transform.\n */\nstatic int \ninvfft1( IMAGE *dummy, IMAGE *in, IMAGE *out )\n{\n\tfftw_plan plan;\n\n\tIMAGE *cmplx = im_open_local( out, \"invfft1:1\", \"t\" );\n\n\t/* We have to have a separate buffer for the planner to work on.\n\t */\n\tdouble *planner_scratch = IM_ARRAY( dummy, \n\t\tin->Xsize * in->Ysize * 2, double );\n\n\t/* Make dp complex image.\n\t */\n\tif( !cmplx || im_pincheck( in ) || im_poutcheck( out ) )\n\t\treturn( -1 );\n\tif( in->Coding != IM_CODING_NONE || in->Bands != 1 ) {\n im_error( \"im_invfft\", \n\t\t\t\"%s\", _( \"one band uncoded only\" ) );\n return( -1 );\n\t}\n\tif( im_clip2fmt( in, cmplx, IM_BANDFMT_DPCOMPLEX ) )\n return( -1 );\n\n\t/* Make the plan for the transform. Yes, they really do use nx for\n\t * height and ny for width.\n\t */\n\tif( !(plan = fftw_plan_dft_2d( in->Ysize, in->Xsize,\n\t\t(fftw_complex *) planner_scratch, \n\t\t(fftw_complex *) planner_scratch,\n\t\tFFTW_BACKWARD, \n\t\t0 )) ) {\n im_error( \"im_invfft\", \n\t\t\t\"%s\", _( \"unable to create transform plan\" ) );\n\t\treturn( -1 );\n\t}\n\n\tfftw_execute_dft( plan, \n\t\t(fftw_complex *) cmplx->data, (fftw_complex *) cmplx->data );\n\n\tfftw_destroy_plan( plan );\n\n\t/* Copy to out.\n\t */\n if( im_copy( cmplx, out ) )\n return( -1 );\n\n\treturn( 0 );\n}\n#else /*!HAVE_FFTW3*/\n/* Fall back to VIPS's built-in fft\n */\nstatic int \ninvfft1( IMAGE *dummy, IMAGE *in, IMAGE *out )\n{\n\tint bpx = im_ispoweroftwo( in->Xsize );\n\tint bpy = im_ispoweroftwo( in->Ysize );\n\tfloat *buf, *q, *p1, *p2;\n\tint x, y;\n\n\t/* Buffers for real and imaginary parts.\n\t */\n\tIMAGE *real = im_open_local( dummy, \"invfft1:1\", \"t\" );\n\tIMAGE *imag = im_open_local( dummy, \"invfft1:2\", \"t\" );\n\n\t/* Temps.\n\t */\n\tIMAGE *t1 = im_open_local( dummy, \"invfft1:3\", \"p\" );\n\tIMAGE *t2 = im_open_local( dummy, \"invfft1:4\", \"p\" );\n\n\tif( !real || !imag || !t1 )\n\t\treturn( -1 );\n if( im_pincheck( in ) || im_outcheck( out ) )\n return( -1 );\n if( in->Coding != IM_CODING_NONE || \n\t\tin->Bands != 1 || !im_iscomplex( in ) ) {\n im_error( \"im_invfft\", \n\t\t\t\"%s\", _( \"one band complex uncoded only\" ) );\n return( -1 );\n\t}\n\tif( !bpx || !bpy ) {\n\t\tim_error( \"im_invfft\", \n\t\t\t\"%s\", _( \"sides must be power of 2\" ) );\n\t\treturn( -1 );\n\t}\n\n\t/* Make sure we have a single-precision complex input image.\n\t */\n\tif( im_clip2fmt( in, t1, IM_BANDFMT_COMPLEX ) )\n\t\treturn( -1 );\n\n\t/* Extract real and imag parts. We have to complement the imaginary.\n\t */\n\tif( im_c2real( t1, real ) )\n\t\treturn( -1 );\n\tif( im_c2imag( t1, t2 ) || im_lintra( -1.0, t2, 0.0, imag ) )\n\t\treturn( -1 );\n\n\t/* Transform!\n\t */\n\tif( im__fft_sp( (float *) real->data, (float *) imag->data, \n\t\tbpx - 1, bpy - 1 ) ) {\n im_error( \"im_invfft\", \n\t\t\t\"%s\", _( \"fft_sp failed\" ) );\n return( -1 );\n\t}\n\n\t/* WIO to out.\n\t */\n if( im_cp_desc( out, in ) )\n return( -1 );\n\tout->BandFmt = IM_BANDFMT_COMPLEX;\n if( im_setupout( out ) )\n return( -1 );\n\tif( !(buf = (float *) IM_ARRAY( dummy, \n\t\tIM_IMAGE_SIZEOF_LINE( out ), PEL )) )\n\t\treturn( -1 );\n\n\t/* Gather together real and imag parts. \n\t */\n\tfor( p1 = (float *) real->data, p2 = (float *) imag->data,\n\t\ty = 0; y < out->Ysize; y++ ) {\n\t\tq = buf;\n\n\t\tfor( x = 0; x < out->Xsize; x++ ) {\n\t\t\tq[0] = *p1++;\n\t\t\tq[1] = *p2++;\n\t\t\tq += 2;\n\t\t}\n\n\t\tif( im_writeline( y, out, (PEL *) buf ) )\n\t\t\treturn( -1 );\n\t}\n\n\treturn( 0 );\n}\n#endif /*HAVE_FFTW3*/\n#endif /*HAVE_FFTW*/\n\n/**\n * im_invfft:\n * @in: input image\n * @out: output image\n *\n * Transform an image from Fourier space to real space. The result is complex.\n * If you are OK with a real result, use im_invfftr() instead, it's quicker.\n *\n * VIPS uses the fftw3 or fftw2 Fourier transform libraries if possible. If \n * they were not available when VIPS was built, it falls back to it's own \n * FFT functions which are slow and only work for square images whose sides\n * are a power of two.\n *\n * See also: im_invfftr(), im_fwfft(), im_disp_ps().\n *\n * Returns: 0 on success, -1 on error.\n */\nint \nim_invfft( IMAGE *in, IMAGE *out )\n{\n\tIMAGE *dummy = im_open( \"im_invfft:1\", \"p\" );\n\n\tif( !dummy )\n\t\treturn( -1 );\n\tif( im__fftproc( dummy, in, out, invfft1 ) ) {\n\t\tim_close( dummy );\n\t\treturn( -1 );\n\t}\n\tim_close( dummy );\n\n\tif( out->Bands == 1 )\n\t\tout->Type = IM_TYPE_B_W;\n\telse\n\t\tout->Type = IM_TYPE_MULTIBAND;\n\n\treturn( 0 );\n}\n", "meta": {"hexsha": "444495d79c8c2bde1a553d39047d640f480bd0a8", "size": 7222, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/apps/vips/src/libvips/freq_filt/im_invfft.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/apps/vips/src/libvips/freq_filt/im_invfft.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/apps/vips/src/libvips/freq_filt/im_invfft.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.2348993289, "max_line_length": 79, "alphanum_fraction": 0.5992799778, "num_tokens": 2338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.29017636909969685}} {"text": "/*\n Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch\n\n This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2, or (at your option)\n any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n\n $Id: parse_exp.c 13079 2015-02-18 16:06:42Z dstrubbe $\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"liboct_parser.h\"\n#include \"symbols.h\"\n\nstatic char *par_string;\nstatic int par_pos;\nparse_result par_res;\n\nstatic int oct_parser_lex(void);\nstatic int oct_parser_error (char *s) /* Called by oct_parser_parse on error */\n{\n /* Do nothing */\n /* printf(\"%s\\n\", s); */\n return 0;\n}\n\n/* include the parser */\n#include \"grammar.c\"\n\nint parse_exp(char *exp, parse_result *r)\n{\n int o;\n\n par_string = exp;\n par_pos = 0;\n\n o = oct_parser_parse();\n if(o == 0){\n r->type = par_res.type;\n if(r->type == PR_CMPLX)\n r->value.c = par_res.value.c;\n else\n r->value.s = par_res.value.s;\n }\n return o;\n}\n\nint get_real(char *s, double *d)\n{\n int n=0;\n sscanf(s, \"%lg\", d);\n while(*s && (isdigit(*s) || *s=='.' || *s=='e' || *s=='E')){\n if((*s=='e' || *s=='E') && (*(s+1)=='+' || *(s+1)=='-')) {s++; n++;}\n s++; n++;\n }\n return n;\n}\n\nstatic int oct_parser_lex (){\n int c;\n char *symbuf = 0, *symbuf2 = 0;\n int length = 0;\n \n /* Ignore whitespace, get first nonwhite character. */\n while ((c = par_string[par_pos++]) == ' ' || c == '\\t');\n\t\n if (c == '\\0')\n return '\\n';\n\t\n /* Char starts a number => parse the number. */\n if (c == '.' || isdigit (c)){\n par_pos--;\n par_pos += get_real(&par_string[par_pos], &GSL_REAL(yylval.val));\n return NUM;\n }\n\n /* get the logical operators */\n if (c == '<' && par_string[par_pos] == '='){\n par_pos++;\n return LE;\n }\n\n if (c == '>' && par_string[par_pos] == '='){\n par_pos++;\n return GE;\n }\n\n if (c == '=' && par_string[par_pos] == '='){\n par_pos++;\n return EQUAL;\n }\n\n /*\n if (c == ':' && par_string[par_pos] == '='){\n par_pos++;\n return SET;\n }\n */\n\n if (c == '&' && par_string[par_pos] == '&'){\n par_pos++;\n return LAND;\n }\n\n if (c == '|' && par_string[par_pos] == '|'){\n par_pos++;\n return LOR;\n }\n \n /* Char starts an identifier => read the name. */\n if (isalpha (c) || c == '\\'' || c == '\\\"'){\n symrec *s;\n char startc = (char)c;\n int i;\n\t\t\n /* Initially make the buffer long enough\n for a 40-character symbol name. */\n if (length == 0)\n length = 40, symbuf = (char *)malloc (length + 1);\n \n if(startc == '\\'' || startc == '\\\"')\n c = par_string[par_pos++];\n else\n startc = 0; /* false */\n \n i = 0;\n do{\n /* If buffer is full, make it larger. */\n if (i == length){\n\tlength *= 2;\n\tsymbuf2 = (char *)realloc (symbuf, length + 1);\n\tif (symbuf2 == NULL) {\n\t fprintf(stderr, \"Parser error: failed to reallocate buffer to size %i.\\n\", length);\n\t exit(1);\n\t} else {\n\t symbuf = symbuf2;\n\t}\n }\n /* Add this character to the buffer. */\n symbuf[i++] = (char)c;\n /* Get another character. */\n c = par_string[par_pos++];\n }while (c != '\\0' && \n\t ((startc && c!=startc) || (!startc && (isalnum(c) || c == '_' ))));\n \n if(!startc) par_pos--;\n symbuf[i] = '\\0';\n \n if(!startc){\n s = getsym (symbuf);\n if (s == 0){\n\tint jj;\n\tfor (jj = 0; reserved_symbols[jj] != 0; jj++){\n\t if(strcmp(symbuf, reserved_symbols[jj]) == 0){\n\t fprintf(stderr, \"Parser error: trying to redefine reserved symbol '%s'.\\n\", symbuf);\n\t exit(1);\n\t }\n\t}\n\t\n\ts = putsym (symbuf, S_CMPLX);\n }\n yylval.tptr = s;\n\n free(symbuf);\n if(s->type == S_CMPLX)\n\treturn VAR;\n else\n\treturn FNCT;\n }else{\n yylval.str = strdup(symbuf);\n\n free(symbuf);\n return STR;\n }\n }\n\t\n /* Any other character is a token by itself. */\n return c;\n}\n", "meta": {"hexsha": "b1dd98f258c11b7c27f106785ec5be933ce8b366", "size": 4511, "ext": "c", "lang": "C", "max_stars_repo_path": "liboct_parser/parse_exp.c", "max_stars_repo_name": "gimunu/octopus-metric", "max_stars_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "liboct_parser/parse_exp.c", "max_issues_repo_name": "gimunu/octopus-metric", "max_issues_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "liboct_parser/parse_exp.c", "max_forks_repo_name": "gimunu/octopus-metric", "max_forks_repo_head_hexsha": "baabccd5402922a2f62f5cf6030d15e7ea76dc9b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8984771574, "max_line_length": 89, "alphanum_fraction": 0.5570826868, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5467381519846138, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.28830406150349597}} {"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 \"psrsalsa.h\"\n#define AmoebaAlgorithm 0\nint readVonMisesModel(char *filename, vonMises_collection_definition *components, verbose_definition verbose)\n{\n int i;\n FILE *fin;\n if(verbose.verbose) printf(\"Opening %s for reading\\n\", filename);\n fin = fopen(filename, \"r\");\n if(fin == NULL) {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR readVonMisesModel: Cannot open %s\", filename);\n return 0;\n }\n for(components->nrcomponents = 0; components->nrcomponents < maxNrVonMisesComponents; (components->nrcomponents)++) {\n i = fscanf(fin, \"%lf %lf %lf\", &(components->centre[components->nrcomponents]), &(components->concentration[components->nrcomponents]), &(components->height[components->nrcomponents]));\n if(i != 3) {\n break;\n }else if(verbose.verbose) {\n printf(\" component %d: phase=%e concentration=%e amplitude=%e\\n\", components->nrcomponents, components->centre[components->nrcomponents], components->concentration[components->nrcomponents], components->height[components->nrcomponents]);\n }\n }\n if(verbose.verbose) printf(\"Closing %s\\n\", filename);\n fclose(fin);\n if(components->nrcomponents == 0) {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR readVonMisesModel: No components found in %s\", filename);\n return 0;\n }\n return 1;\n}\ndouble calcVonMisesFunction2(double centre, double concentration, double height, double phase, double shift)\n{\n double y;\n y = exp((cos(2.0*M_PI*(phase-centre-shift))-1.0)*concentration) * height;\n return y;\n}\ndouble integrateVonMisesFunction2(double concentration, double height)\n{\n double area;\n area = 2*M_PI*height*gsl_sf_bessel_I0_scaled(concentration);\n return area;\n}\ndouble widthVonMisesFunction2(double concentration, double ampfrac)\n{\n double value = log(ampfrac)/concentration + 1.0;\n if(value < -1.0 || value >= 1.0) {\n return sqrt(-1);\n }\n return 2.0*acos(value);\n}\ndouble calcVonMisesFunction(vonMises_collection_definition *components, double phase, double shift)\n{\n int n;\n double y;\n y = 0;\n if(components->nrcomponents > 0) {\n for(n = 0; n < components->nrcomponents; n++) {\n y += calcVonMisesFunction2(components->centre[n], components->concentration[n], components->height[n], phase, shift);\n }\n }\n return y;\n}\nvoid calcVonMisesProfile(vonMises_collection_definition *components, int nrbins, float *profile, double shift, int normalize)\n{\n int i;\n double x, Imax = -1;\n for(i = 0; i < nrbins; i++) {\n profile[i] = 0;\n }\n for(i = 0; i < nrbins; i++) {\n x = i/(double)nrbins;\n profile[i] = calcVonMisesFunction(components, x, shift);\n }\n if(normalize) {\n for(i = 0; i < nrbins; i++) {\n if(profile[i] > Imax)\n Imax = profile[i];\n }\n for(i = 0; i < nrbins; i++) {\n profile[i] /= Imax;\n }\n }\n}\nfloat correlateVonMisesFunction(vonMises_collection_definition *components, int nrbins, float *profile, verbose_definition verbose)\n{\n float correl_max, *profile2;\n int i;\n int ishift;\n if(verbose.verbose) {\n for(i = 0; i < verbose.indent; i++)\n printf(\" \");\n printf(\"Correlating template with profile\\n\");\n verbose.indent += 2;\n }\n profile2 = (float *)malloc(nrbins*sizeof(float));\n if(profile2 == NULL) {\n fflush(stdout);\n printerror(verbose.debug, \"ERROR correlateVonMisesFunction: Memory allocation error.\");\n return 0;\n }\n calcVonMisesProfile(components, nrbins, profile2, 0, 0);\n find_peak_correlation(profile, profile2, nrbins, 0, 1, 1, 1, &ishift, &correl_max, verbose);\n if(verbose.verbose) {\n for(i = 0; i < verbose.indent; i++)\n printf(\" \");\n printf(\"Found a shift of %d bins (%f phase) and max/min correlation is %f.\\n\", ishift, ishift/(float)nrbins, correl_max);\n for(i = 0; i < verbose.indent; i++)\n printf(\" \");\n printf(\"so you could do a shift by %d bins (%f phase) to rotate profile to align with model.\\n\", -ishift, -ishift/(float)nrbins);\n }\n free(profile2);\n return ishift/(float)nrbins;\n}\n", "meta": {"hexsha": "bd77928754fac898d0c0477b0560a80795450631", "size": 5530, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/vonMises.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/vonMises.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/vonMises.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": 41.5789473684, "max_line_length": 755, "alphanum_fraction": 0.7150090416, "num_tokens": 1436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.4649015713733885, "lm_q1q2_score": 0.2876719959826228}} {"text": "#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef VRNA_WITH_GSL\n#include \n#endif\n\n#include \"ViennaRNA/eval.h\"\n#include \"ViennaRNA/fold_vars.h\"\n#include \"ViennaRNA/constraints/hard.h\"\n#include \"ViennaRNA/constraints/soft.h\"\n#include \"ViennaRNA/fold.h\"\n#include \"ViennaRNA/part_func.h\"\n#include \"ViennaRNA/utils/basic.h\"\n#include \"ViennaRNA/params/basic.h\"\n#include \"ViennaRNA/perturbation_fold.h\"\n\nstatic void\ncalculate_probability_unpaired(vrna_fold_compound_t *vc,\n double *probability)\n{\n int length = vc->length;\n FLT_OR_DBL *probs = vc->exp_matrices->probs;\n int *iidx = vc->iindx;\n int i, j;\n\n for (i = 0; i <= length; ++i)\n probability[i] = 1;\n\n for (i = 1; i <= length; ++i)\n for (j = i + 1; j <= length; ++j) {\n probability[i] -= probs[iidx[i] - j];\n probability[j] -= probs[iidx[i] - j];\n }\n}\n\n\n#if 0\nstatic double\ncalculate_norm(double *vector,\n int length)\n{\n double sum = 0;\n int i;\n\n for (i = 1; i <= length; ++i)\n sum += vector[i] * vector[i];\n\n return sqrt(sum);\n}\n\n\n#endif\n\nstatic void\naddSoftConstraint(vrna_fold_compound_t *vc,\n const double *epsilon,\n int length)\n{\n /* remove previous soft constraints */\n vrna_sc_init(vc);\n\n /* prepare vector of unpaired constraints in kcal/mol */\n FLT_OR_DBL *constraints = (FLT_OR_DBL *)vrna_alloc(sizeof(FLT_OR_DBL) * (length + 1));\n\n memcpy(constraints + 1, epsilon + 1, sizeof(FLT_OR_DBL) * length);\n\n /* add new soft constraints */\n vrna_sc_set_up(vc, (const FLT_OR_DBL *)constraints, VRNA_OPTION_DEFAULT);\n\n free(constraints);\n}\n\n\nstatic double\nevaluate_objective_function_contribution(double value,\n int objective_function)\n{\n if (objective_function == VRNA_OBJECTIVE_FUNCTION_QUADRATIC)\n return value * value;\n\n if (objective_function == VRNA_OBJECTIVE_FUNCTION_ABSOLUTE)\n return fabs(value);\n\n assert(0);\n return 0;\n}\n\n\nstatic double\nevaluate_perturbation_vector_score(vrna_fold_compound_t *vc,\n const double *epsilon,\n const double *q_prob_unpaired,\n double sigma_squared,\n double tau_squared,\n int objective_function)\n{\n double ret = 0;\n double ret2 = 0.;\n double *p_prob_unpaired;\n int i;\n int length = vc->length;\n\n /* calculate pairing probabilty in the pertubated energy model */\n p_prob_unpaired = vrna_alloc(sizeof(double) * (length + 1));\n\n addSoftConstraint(vc, epsilon, length);\n\n vc->params->model_details.compute_bpp = 1;\n vc->exp_params->model_details.compute_bpp = 1;\n\n /* get new (constrained) MFE to scale pf computations properly */\n double mfe = (double)vrna_mfe(vc, NULL);\n\n vrna_exp_params_rescale(vc, &mfe);\n\n vrna_pf(vc, NULL);\n\n calculate_probability_unpaired(vc, p_prob_unpaired);\n\n vrna_sc_remove(vc);\n\n\n for (i = 1; i <= length; ++i) {\n /* add penalty for pertubation energies */\n ret += evaluate_objective_function_contribution(epsilon[i], objective_function) / tau_squared;\n\n /* add penalty for mismatches between observed and predicted probabilities */\n if (q_prob_unpaired[i] >= 0) /* ignore positions with missing data */\n ret2 += evaluate_objective_function_contribution(p_prob_unpaired[i] - q_prob_unpaired[i],\n objective_function) / sigma_squared;\n }\n\n vrna_message_info(stderr, \"Score: pertubation: %g\\tdiscrepancy: %g\", ret, ret2);\n free(p_prob_unpaired);\n\n return ret + ret2;\n}\n\n\nstatic void\npairing_probabilities_from_restricted_pf(vrna_fold_compound_t *vc,\n const double *epsilon,\n double *prob_unpaired,\n double **conditional_prob_unpaired)\n{\n int length = vc->length;\n int i;\n\n addSoftConstraint(vc, epsilon, length);\n vc->params->model_details.compute_bpp = 1;\n vc->exp_params->model_details.compute_bpp = 1;\n\n /* get new (constrained) MFE to scale pf computations properly */\n double mfe = (double)vrna_mfe(vc, NULL);\n\n vrna_exp_params_rescale(vc, &mfe);\n\n vrna_pf(vc, NULL);\n\n calculate_probability_unpaired(vc, prob_unpaired);\n\n#ifdef _OPENMP\n#pragma omp parallel for private(i)\n#endif\n for (i = 1; i <= length; ++i) {\n vrna_fold_compound_t *restricted_vc;\n char *hc_string;\n unsigned int constraint_options = VRNA_CONSTRAINT_DB\n | VRNA_CONSTRAINT_DB_PIPE\n | VRNA_CONSTRAINT_DB_DOT\n | VRNA_CONSTRAINT_DB_X\n | VRNA_CONSTRAINT_DB_ANG_BRACK\n | VRNA_CONSTRAINT_DB_RND_BRACK;\n\n hc_string = vrna_alloc(sizeof(char) * (length + 1));\n memset(hc_string, '.', length);\n hc_string[i - 1] = 'x';\n\n restricted_vc = vrna_fold_compound(vc->sequence,\n &(vc->exp_params->model_details),\n VRNA_OPTION_DEFAULT);\n vrna_constraints_add(restricted_vc, hc_string, constraint_options);\n free(hc_string);\n\n vrna_exp_params_subst(restricted_vc, vc->exp_params);\n\n vrna_pf(restricted_vc, NULL);\n calculate_probability_unpaired(restricted_vc, conditional_prob_unpaired[i]);\n\n restricted_vc->sc = NULL;\n vrna_fold_compound_free(restricted_vc);\n }\n\n vrna_sc_remove(vc);\n}\n\n\nstatic void\npairing_probabilities_from_sampling(vrna_fold_compound_t *vc,\n const double *epsilon,\n int sample_size,\n double *prob_unpaired,\n double **conditional_prob_unpaired,\n unsigned int options)\n{\n char **samples, **ptr;\n int length, i, j;\n double mfe;\n\n length = vc->length;\n addSoftConstraint(vc, epsilon, length);\n\n vc->params->model_details.compute_bpp = 0;\n vc->exp_params->model_details.compute_bpp = 0;\n\n /* get new (constrained) MFE to scale pf computations properly */\n mfe = (double)vrna_mfe(vc, NULL);\n vrna_exp_params_rescale(vc, &mfe);\n\n vrna_pf(vc, NULL);\n\n samples = vrna_pbacktrack_num(vc,\n (unsigned int)sample_size,\n options);\n\n for (ptr = samples; (*ptr); ptr++) {\n for (i = length; i > 0; i--) {\n if ((*ptr)[i - 1] == '.') {\n ++prob_unpaired[i];\n\n for (j = length; j > 0; j--)\n if ((*ptr)[j - 1] == '.')\n ++conditional_prob_unpaired[i][j];\n }\n }\n\n free(*ptr);\n }\n\n free(samples);\n\n for (i = 1; i <= length; ++i) {\n if (prob_unpaired[i])\n for (j = 1; j <= length; ++j)\n conditional_prob_unpaired[i][j] /= prob_unpaired[i];\n\n prob_unpaired[i] /= sample_size;\n\n assert(prob_unpaired[i] >= 0 && prob_unpaired[i] <= 1);\n }\n\n vrna_sc_remove(vc);\n}\n\n\nstatic void\nallocateProbabilityArrays(double **unpaired,\n double ***conditional_unpaired,\n int length)\n{\n int i;\n\n *unpaired = vrna_alloc(sizeof(double) * (length + 1));\n *conditional_unpaired = vrna_alloc(sizeof(double *) * (length + 1));\n\n for (i = 1; i <= length; ++i)\n (*conditional_unpaired)[i] = vrna_alloc(sizeof(double) * (length + 1));\n}\n\n\nstatic void\nfreeProbabilityArrays(double *unpaired,\n double **conditional_unpaired,\n int length)\n{\n int i;\n\n free(unpaired);\n for (i = 1; i <= length; ++i)\n free(conditional_unpaired[i]);\n free(conditional_unpaired);\n}\n\n\nstatic void\nevaluate_perturbation_vector_gradient(vrna_fold_compound_t *vc,\n const double *epsilon,\n const double *q_prob_unpaired,\n double sigma_squared,\n double tau_squared,\n int objective_function,\n int sample_size,\n double *gradient)\n{\n double *p_prob_unpaired;\n double **p_conditional_prob_unpaired;\n int i, mu;\n int length = vc->length;\n double kT = vc->exp_params->kT / 1000;\n\n allocateProbabilityArrays(&p_prob_unpaired, &p_conditional_prob_unpaired, length);\n\n if (sample_size > 0) {\n pairing_probabilities_from_sampling(vc,\n epsilon,\n sample_size,\n p_prob_unpaired,\n p_conditional_prob_unpaired,\n VRNA_PBACKTRACK_DEFAULT);\n } else if (sample_size < 0) {\n pairing_probabilities_from_sampling(vc,\n epsilon,\n -sample_size,\n p_prob_unpaired,\n p_conditional_prob_unpaired,\n VRNA_PBACKTRACK_NON_REDUNDANT);\n } else {\n pairing_probabilities_from_restricted_pf(vc,\n epsilon,\n p_prob_unpaired,\n p_conditional_prob_unpaired);\n }\n\n for (mu = 1; mu <= length; ++mu) {\n double sum = 0;\n\n if (objective_function == VRNA_OBJECTIVE_FUNCTION_QUADRATIC) {\n for (i = 1; i <= length; ++i) {\n if (q_prob_unpaired[i] < 0) /* ignore positions with missing data */\n continue;\n\n sum += (p_prob_unpaired[i] - q_prob_unpaired[i])\n * p_prob_unpaired[i] * (p_prob_unpaired[mu] - p_conditional_prob_unpaired[i][mu])\n / sigma_squared;\n }\n\n gradient[mu] = 2 * (epsilon[mu] / tau_squared + sum / kT);\n } else if (objective_function == VRNA_OBJECTIVE_FUNCTION_ABSOLUTE) {\n for (i = 1; i <= length; ++i)\n if (q_prob_unpaired[i] >= 0 && p_prob_unpaired[i] != q_prob_unpaired[i]) {\n sum += (p_prob_unpaired[i] * (p_prob_unpaired[mu] - p_conditional_prob_unpaired[i][mu])) /\n kT\n / sigma_squared\n * (p_prob_unpaired[i] > q_prob_unpaired[i] ? 1. : -1.);\n }\n\n if (epsilon[mu])\n sum += (epsilon[mu] > 0 ? 1. : -1.) / tau_squared;\n\n gradient[mu] = sum;\n }\n }\n\n freeProbabilityArrays(p_prob_unpaired, p_conditional_prob_unpaired, length);\n}\n\n\n#ifdef VRNA_WITH_GSL\ntypedef struct parameters_gsl {\n vrna_fold_compound_t *vc;\n const double *q_prob_unpaired;\n double sigma_squared;\n double tau_squared;\n int objective_function;\n int sample_size;\n} parameters_gsl;\n\nstatic double\nf_gsl(const gsl_vector *x,\n void *params)\n{\n parameters_gsl *p = params;\n\n return evaluate_perturbation_vector_score(p->vc,\n x->data,\n p->q_prob_unpaired,\n p->sigma_squared,\n p->tau_squared,\n p->objective_function);\n}\n\n\nstatic void\ndf_gsl(const gsl_vector *x,\n void *params,\n gsl_vector *df)\n{\n parameters_gsl *p = params;\n\n gsl_vector_set(df, 0, 0);\n evaluate_perturbation_vector_gradient(p->vc,\n x->data,\n p->q_prob_unpaired,\n p->sigma_squared,\n p->tau_squared,\n p->objective_function,\n p->sample_size,\n df->data);\n}\n\n\nstatic void\nfdf_gsl(const gsl_vector *x,\n void *params,\n double *f,\n gsl_vector *g)\n{\n *f = f_gsl(x, params);\n df_gsl(x, params, g);\n}\n\n\n#endif /* VRNA_WITH_GSL */\n\nPUBLIC void\nvrna_sc_minimize_pertubation(vrna_fold_compound_t *vc,\n const double *q_prob_unpaired,\n int objective_function,\n double sigma_squared,\n double tau_squared,\n int algorithm,\n int sample_size,\n double *epsilon,\n double initialStepSize,\n double minStepSize,\n double minImprovement,\n double minimizerTolerance,\n progress_callback callback)\n{\n int iteration_count = 0;\n const int max_iterations = 100;\n int length = vc->length;\n\n#ifdef VRNA_WITH_GSL\n const gsl_multimin_fdfminimizer_type *minimizer_type = 0;\n\n struct {\n int type;\n const gsl_multimin_fdfminimizer_type *gsl_type;\n } algorithms[] =\n { { VRNA_MINIMIZER_CONJUGATE_FR,\n gsl_multimin_fdfminimizer_conjugate_fr },\n { VRNA_MINIMIZER_CONJUGATE_PR,\n gsl_multimin_fdfminimizer_conjugate_pr },\n { VRNA_MINIMIZER_VECTOR_BFGS,\n gsl_multimin_fdfminimizer_vector_bfgs },\n { VRNA_MINIMIZER_VECTOR_BFGS2,\n gsl_multimin_fdfminimizer_vector_bfgs2 },\n { VRNA_MINIMIZER_STEEPEST_DESCENT,\n gsl_multimin_fdfminimizer_steepest_descent },\n { 0,\n NULL } };\n int i;\n for (i = 0; algorithms[i].type; ++i)\n if (algorithms[i].type == algorithm) {\n minimizer_type = algorithms[i].gsl_type;\n break;\n }\n\n if (minimizer_type) {\n parameters_gsl parameters;\n gsl_multimin_function_fdf fdf;\n gsl_multimin_fdfminimizer *minimizer;\n gsl_vector *vector;\n\n int status;\n\n parameters.vc = vc;\n parameters.q_prob_unpaired = q_prob_unpaired;\n parameters.sigma_squared = sigma_squared;\n parameters.tau_squared = tau_squared;\n parameters.objective_function = objective_function;\n parameters.sample_size = sample_size;\n\n fdf.n = length + 1;\n fdf.f = &f_gsl;\n fdf.df = &df_gsl;\n fdf.fdf = &fdf_gsl;\n fdf.params = (void *)¶meters;\n\n minimizer = gsl_multimin_fdfminimizer_alloc(minimizer_type, length + 1);\n vector = gsl_vector_calloc(length + 1);\n\n /* gsl_multimin_fdfminimizer_set(minimizer, &fdf, vector, 0.01, 1e-4); */\n gsl_multimin_fdfminimizer_set(minimizer, &fdf, vector, initialStepSize, minimizerTolerance);\n\n if (callback)\n callback(0, minimizer->f, minimizer->x->data);\n\n do {\n ++iteration_count;\n status = gsl_multimin_fdfminimizer_iterate(minimizer);\n\n if (callback)\n callback(iteration_count, minimizer->f, minimizer->x->data);\n\n if (status)\n break;\n\n status = gsl_multimin_test_gradient(minimizer->gradient, minimizerTolerance);\n } while (status == GSL_CONTINUE && iteration_count < max_iterations);\n\n memcpy(epsilon, minimizer->x->data, sizeof(double) * (length + 1));\n\n gsl_multimin_fdfminimizer_free(minimizer);\n gsl_vector_free(vector);\n\n return;\n }\n\n#endif /* VRNA_WITH_GSL */\n\n double improvement;\n const double min_improvement = minImprovement;\n\n double *new_epsilon = vrna_alloc(sizeof(double) * (length + 1));\n double *gradient = vrna_alloc(sizeof(double) * (length + 1));\n\n double score = evaluate_perturbation_vector_score(vc,\n epsilon,\n q_prob_unpaired,\n sigma_squared,\n tau_squared,\n objective_function);\n\n if (callback)\n callback(0, score, epsilon);\n\n do {\n double new_score;\n double step_size;\n\n ++iteration_count;\n\n evaluate_perturbation_vector_gradient(vc,\n epsilon,\n q_prob_unpaired,\n sigma_squared,\n tau_squared,\n objective_function,\n sample_size,\n gradient);\n\n /* step_size = 0.5 / calculate_norm(gradient, length);*/\n step_size = initialStepSize;\n\n do {\n int i;\n for (i = 1; i <= length; ++i)\n new_epsilon[i] = epsilon[i] - step_size * gradient[i];\n\n new_score = evaluate_perturbation_vector_score(vc,\n new_epsilon,\n q_prob_unpaired,\n sigma_squared,\n tau_squared,\n objective_function);\n improvement = 1 - new_score / score;\n step_size /= 2;\n } while ((improvement < min_improvement) && (step_size >= minStepSize));\n\n if (new_score > score)\n break;\n\n if (callback)\n callback(iteration_count, new_score, new_epsilon);\n\n score = new_score;\n memcpy(epsilon, new_epsilon, sizeof(double) * (length + 1));\n } while (improvement >= min_improvement && iteration_count < max_iterations);\n\n free(gradient);\n free(new_epsilon);\n}\n", "meta": {"hexsha": "2c612f0415ec2b8c9ac95aa740d19c8d43d043d7", "size": 18593, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ViennaRNA/perturbation_fold.c", "max_stars_repo_name": "tsjzz/ViennaRNA", "max_stars_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_stars_repo_licenses": ["Python-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-02T06:38:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-02T06:38:05.000Z", "max_issues_repo_path": "src/ViennaRNA/perturbation_fold.c", "max_issues_repo_name": "tsjzz/ViennaRNA", "max_issues_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_issues_repo_licenses": ["Python-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ViennaRNA/perturbation_fold.c", "max_forks_repo_name": "tsjzz/ViennaRNA", "max_forks_repo_head_hexsha": "f58f58ac6fb3e050f12e69cbbf7f0a95bc625d99", "max_forks_repo_licenses": ["Python-2.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.8919382504, "max_line_length": 100, "alphanum_fraction": 0.5231000914, "num_tokens": 4071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6791786991753931, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2869561482686749}} {"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/*\n * Spline the linear power spectrum for mu-Sigma MG cosmologies.\n * @param cosmo Cosmological parameters\n ^ @param psp The linear power spectrum to spline.\n * @param status, integer indicating the status\n */\nvoid ccl_cosmology_spline_linpower_musigma(ccl_cosmology* cosmo, ccl_f2d_t *psp, int rescaled_mg_flag, int* status) {\n double kmin, kmax, ndecades, amin, amax, ic, sigma8, log_sigma8;\n int nk, na, s;\n double *lk = NULL, *aa = NULL, *lpk_ln = NULL, *lpk_nl = NULL;\n double norm_pk;\n double *mnu_list = NULL;\n ccl_parameters params_GR;\n params_GR.m_nu = NULL;\n params_GR.z_mgrowth = NULL;\n params_GR.df_mgrowth = NULL;\n ccl_cosmology * cosmo_GR = NULL;\n double *D_mu = NULL;\n double *D_GR = NULL;\n\n if (*status == 0) {\n //calculations done - now allocate CCL splines\n kmin = 2*exp(psp->lkmin);\n kmax = cosmo->spline_params.K_MAX_SPLINE;\n //Compute nk from number of decades and N_K = # k per decade\n ndecades = log10(kmax) - log10(kmin);\n nk = (int)ceil(ndecades*cosmo->spline_params.N_K);\n amin = cosmo->spline_params.A_SPLINE_MINLOG_PK;\n amax = cosmo->spline_params.A_SPLINE_MAX;\n na = cosmo->spline_params.A_SPLINE_NA_PK+cosmo->spline_params.A_SPLINE_NLOG_PK-1;\n\n // The lk array is initially k, but will later\n // be overwritten with log(k)\n lk = ccl_log_spacing(kmin, kmax, nk);\n if (lk == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\\n\");\n }\n }\n\n if (*status == 0) {\n aa = ccl_linlog_spacing(\n amin, cosmo->spline_params.A_SPLINE_MIN_PK,\n amax, cosmo->spline_params.A_SPLINE_NLOG_PK,\n cosmo->spline_params.A_SPLINE_NA_PK);\n if (aa == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\\n\");\n }\n }\n\n if (*status == 0) {\n lpk_ln = malloc(nk * na * sizeof(double));\n if (lpk_ln == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\\n\");\n }\n }\n\n if (*status == 0) {\n lpk_nl = malloc(nk * na * sizeof(double));\n if(lpk_nl == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\\n\");\n }\n }\n\n if (*status == 0) {\n // After this loop lk will contain log(k),\n // lpk_ln will contain log(P_lin), all in Mpc, not Mpc/h units!\n double psout_l;\n s = 0;\n\n // If scale-independent mu / Sigma modified gravity is in use\n // and mu ! = 0 : get the unnormalized growth factor in MG and for\n // corresponding GR case, to rescale CLASS power spectrum\n if (fabs(cosmo->params.mu_0) > 1e-14) {\n // Set up another cosmology which is exactly the same as the\n // current one but with mu_0 and Sigma_0=0, for scaling P(k)\n\n // Get a list of the three neutrino masses already calculated\n mnu_list = malloc(3*sizeof(double));\n if (mnu_list == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\\n\");\n }\n\n if (*status == 0) {\n for (int i=0; i< cosmo->params.N_nu_mass; i=i+1) {\n mnu_list[i] = cosmo->params.m_nu[i];\n }\n if (cosmo->params.N_nu_mass < 3) {\n for (int j=cosmo->params.N_nu_mass; j<3; j=j+1) {\n mnu_list[j] = 0.;\n }\n }\n\n if (isfinite(cosmo->params.A_s)) {\n norm_pk = cosmo->params.A_s;\n }\n else if (isfinite(cosmo->params.sigma8)) {\n norm_pk = cosmo->params.sigma8;\n }\n else {\n *status = CCL_ERROR_PARAMETERS;\n strcpy(\n cosmo->status_message,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): neither A_s nor sigma8 defined.\\n\");\n }\n }\n\n if (*status == 0) {\n params_GR = ccl_parameters_create(\n cosmo->params.Omega_c, cosmo->params.Omega_b, cosmo->params.Omega_k,\n cosmo->params.Neff, mnu_list, cosmo->params.N_nu_mass,\n cosmo->params.w0, cosmo->params.wa, cosmo->params.h,\n norm_pk, cosmo->params.n_s,\n cosmo->params.bcm_log10Mc, cosmo->params.bcm_etab,\n cosmo->params.bcm_ks, 0., 0., cosmo->params.nz_mgrowth,\n cosmo->params.z_mgrowth, cosmo->params.df_mgrowth, status);\n\n if (*status) {\n *status = CCL_ERROR_PARAMETERS;\n strcpy(\n cosmo->status_message,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): could not make MG params.\\n\");\n }\n }\n\n if (*status == 0) {\n cosmo_GR = ccl_cosmology_create(params_GR, cosmo->config);\n D_mu = malloc(na * sizeof(double));\n D_GR = malloc(na * sizeof(double));\n\n if (cosmo_GR == NULL || D_mu == NULL || D_GR == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(\n cosmo,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): memory allocation\\n\");\n }\n }\n\n if (*status == 0) {\n ccl_cosmology_compute_growth(cosmo_GR, status);\n\n if (*status) {\n *status = CCL_ERROR_PARAMETERS;\n strcpy(\n cosmo->status_message,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): could not init GR growth.\\n\");\n }\n }\n\n if (*status == 0) {\n for (int i=0; istatus_message,\n \"ccl_power.c: ccl_cosmology_spline_linpower_musigma(): could not make MG and GR growth.\\n\");\n }\n }\n\n if (*status == 0) {\n for (int i=0; idata.p_lin = ccl_f2d_t_new(\n na, aa, nk, lk, lpk_ln, NULL, NULL, 0,\n 1, 2, ccl_f2d_cclgrowth, 1, NULL, 0, 2,\n ccl_f2d_3,status);\n }\n\n // if desried, renomalize to a given sigma8\n if (isfinite(cosmo->params.sigma8) && (!isfinite(cosmo->params.A_s))) {\n if (*status == 0) {\n cosmo->computed_linear_power = true;\n sigma8 = ccl_sigma8(cosmo, status);\n cosmo->computed_linear_power = false;\n }\n\n if (*status == 0) {\n // Calculate normalization factor using computed value of sigma8, then\n // recompute P(k, a) using this normalization\n log_sigma8 = 2*(log(cosmo->params.sigma8) - log(sigma8));\n for(int j = 0; jdata.p_lin);\n cosmo->data.p_lin = ccl_f2d_t_new(\n na, aa, nk, lk, lpk_ln, NULL, NULL, 0,\n 1, 2, ccl_f2d_cclgrowth, 1, NULL, 0, 2,\n ccl_f2d_3,status);\n }\n }\n\n free(D_mu);\n free(D_GR);\n free(mnu_list);\n ccl_parameters_free(¶ms_GR);\n ccl_cosmology_free(cosmo_GR);\n free(lk);\n free(aa);\n free(lpk_nl);\n free(lpk_ln);\n}\n", "meta": {"hexsha": "344f85a89e03597af0bda10978d8b8220b726a9d", "size": 8711, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_musigma.c", "max_stars_repo_name": "timothydmorton/CCL", "max_stars_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_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_musigma.c", "max_issues_repo_name": "timothydmorton/CCL", "max_issues_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-28T12:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-28T12:22:35.000Z", "max_forks_repo_path": "src/ccl_musigma.c", "max_forks_repo_name": "timothydmorton/CCL", "max_forks_repo_head_hexsha": "46692a38afd249946ac004cec391f47fd7c34f63", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3828996283, "max_line_length": 117, "alphanum_fraction": 0.5938468603, "num_tokens": 2672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2868212054061679}} {"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_PHYSICS_WIND_H_\n#define SIM_PHYSICS_WIND_H_\n\n#include \n\n#include \n\n#include \"common/c_math/mat3.h\"\n#include \"common/c_math/vec3.h\"\n#include \"common/macros.h\"\n\n// Functions related to wind shear and turbulence.\n//\n// Many of these functions define a \"mean wind frame\" denoted by\n// the \"mw\" subscript. This should not be confused with the\n// wind frame defined in sim/physics/aero_frame.h, which related to\n// the apparent wind at a body.\n//\n// The origin of the mean wind frame lies at ground level directly\n// below the ground station origin. The axes are defined by:\n// x: Points along the predominate wind vector.\n// y: Completes a right-handed frame.\n// z: Points up.\n// These are chosen to be consistent with NREL's TurbSim software\n// and various IEC standards.\n\nnamespace sim {\n\nnamespace physics {\n\nnamespace wind {\n\ndouble CalcWindShear(double height_agl, double ref_height_agl,\n double ref_wind_speed, double wind_shear_exponent);\n\nclass FrozenTurbulenceWindDatabase {\n friend class FrozenTurbulenceWindDatabaseTest;\n\n public:\n FrozenTurbulenceWindDatabase(double t0, double y0,\n const std::string &filename);\n ~FrozenTurbulenceWindDatabase() {\n gsl_vector_free(u_);\n gsl_vector_free(v_);\n gsl_vector_free(w_);\n }\n void CalcWind(double t, const Vec3 &pos_mw, Vec3 *wind_mw) const;\n\n private:\n // Time offset [s] to apply. At t = 0, positions whose x coordinate\n // (in the mw frame) is zero will fetch the database entry given at\n // time t0_.\n double t0_;\n // Y offset [m] to apply from the center of the wind database.\n double y0_;\n // Mean wind speed [m/s] that sets the rate at which the database\n // is \"advected\" along the mean wind coordinate x axis.\n double mean_wind_speed_;\n // Number [#] of t, y, and z grid points.\n int32_t num_t_, num_y_, num_z_;\n // Duration [s], width [m], and height [m] of the grid defining\n // the database.\n double duration_, width_, height_;\n // Vectors storing the components of the wind velocity [m/s]. Each\n // vector has num_t * num_y * num_z elements. The u, v, and w\n // components point along the x, y, and z axes of the mean wind\n // coordinate system.\n gsl_vector *u_;\n gsl_vector *v_;\n gsl_vector *w_;\n\n DISALLOW_COPY_AND_ASSIGN(FrozenTurbulenceWindDatabase);\n};\n\nenum class IecTurbulenceCategory { kA, kB, kC };\n\nenum class IecWindTurbineClass { kI, kII, kIII };\n\nclass IecWindModel {\n public:\n IecWindModel(double hub_height_agl__, double rotor_diameter,\n double hub_wind_speed, IecTurbulenceCategory turbulence_category,\n IecWindTurbineClass wind_turbine_class);\n\n double hub_height_agl() const { return hub_height_agl_; }\n double ntm_sigma_1() const { return ntm_sigma_1_; }\n double ewm_sigma_1() const { return ewm_sigma_1_; }\n double etm_sigma_1() const { return etm_sigma_1_; }\n\n // IEC 61400-1 Design situations.\n\n // IEC 61400-1 Sec. 6.3.1.2 -- Normal Wind Profile Model (NWP).\n double CalcNormalWindProfile(double height_agl) const;\n\n // IEC 61400-1 Sec. 6.3.2.1 -- Extreme wind speed model (EWM).\n double CalcExtremeWindSpeed1YearRecurrence(double height_agl,\n bool is_turbulent) const;\n double CalcExtremeWindSpeed50YearRecurrence(double height_agl,\n bool is_turbulent) const;\n\n // IEC 61400-1 Sec. 6.3.2.2 -- Extreme Operating Gust (EOG).\n double CalcExtremeOperatingGust(double t, double height_agl) const;\n\n // IEC 61400-1 Sec. 6.3.2.4 -- Extreme direction change (EDC).\n double CalcExtremeDirectionChange(double t) const;\n\n // IEC 61400-1 Sec. 6.3.2.5 -- Extreme coherent gust with direction\n // change (ECD).\n double CalcExtremeCoherentGustWithDirectionChange(\n double t, double height_agl, double *wind_direction) const;\n\n // IEC 61400-1 Sec. 6.3.2.6 -- Extreme wind shear (EWS).\n double CalcExtremeWindShearVertical(double t, double height_agl) const;\n double CalcExtremeWindShearHorizontal(double t, double height_agl,\n double y) const;\n\n private:\n // Hub height above ground level [m].\n const double hub_height_agl_;\n\n // Rotor diameter [m].\n const double rotor_diameter_;\n\n // Nominal wind speed [m/s] at hub height.\n const double hub_wind_speed_;\n\n // Reference wind speed [m/s], see IEC 61400-1 Sec. 6.2.\n const double v_ref_;\n\n // Expected value of the turbulence intensity [#] at 15 m/s.\n const double I_ref_;\n\n // Longitudinal turbulence scale parameter [#].\n const double lambda_1_;\n\n // Normal turbulence model (NTM) standard deviation [m/s].\n const double ntm_sigma_1_;\n\n // Extreme wind model (EWM) standard deviation [m/s].\n const double ewm_sigma_1_;\n\n // Extreme turbulence model (ETM) standard deviation [m/s].\n const double etm_sigma_1_;\n};\n\n} // namespace wind\n\n} // namespace physics\n\n} // namespace sim\n\n#endif // SIM_PHYSICS_WIND_H_\n", "meta": {"hexsha": "b015b6d5ec3c7d87477c35ed2c75107b00fe7539", "size": 5578, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/physics/wind.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/physics/wind.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/physics/wind.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 33.0059171598, "max_line_length": 80, "alphanum_fraction": 0.7059878093, "num_tokens": 1470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6113819874558603, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.28661014500743104}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"common.h\"\n#include \"graph.h\"\n#include \"utils.h\"\n\nvoid graph_init(graph *g, int vertices)\n{\n g->num_v = vertices;\n g->num_e = (int*)malloc(vertices * sizeof(int));\n g->capacity = (int*)malloc(vertices * sizeof(int));\n g->adj_list = (int**)malloc(vertices * sizeof(int*));\n g->w_list = (double**)malloc(vertices * sizeof(double*));\n\n int i = 0;\n for (; i < vertices; ++i) \n {\n g->num_e[i] = 0;\n g->capacity[i] = GRAPH_INIT_CAPACITY;\n g->adj_list[i] = (int*)malloc(GRAPH_INIT_CAPACITY * sizeof(int));\n g->w_list[i] = (double*)malloc(GRAPH_INIT_CAPACITY * sizeof(double));\n }\n}\n\nORIGIN_INLINE int graph_edges(const graph *g)\n{\n const int num_v = g->num_v;\n int sum = 0;\n int v = 0;\n for (; v < num_v; ++v) \n {\n sum += g->num_e[v];\n }\n return sum;\n}\n\nORIGIN_INLINE int graph_proper_edges(const graph *g)\n{\n const int num_v = g->num_v;\n int sum = 0;\n int v = 0;\n for (; v < num_v; ++v) \n {\n int e = 0;\n for (; e < g->num_e[v]; ++e)\n {\n if (g->adj_list[v][e] != v)\n {\n ++sum;\n }\n }\n }\n return sum;\n}\n\nORIGIN_INLINE int graph_loops(const graph *g)\n{\n const int num_v = g->num_v;\n int sum = 0;\n int v = 0;\n for (; v < num_v; ++v) \n {\n int e = 0;\n for (; e < g->num_e[v]; ++e)\n {\n if (g->adj_list[v][e] == v)\n {\n ++sum;\n }\n }\n }\n return sum;\n}\n\nORIGIN_INLINE int graph_outdegree(const graph *g, int u)\n{\n return g->num_e[u];\n}\n\nORIGIN_INLINE int graph_indegree(const graph *g, int u)\n{\n const int num_v = g->num_v;\n int sum = 0;\n int v = 0;\n for (; v < num_v; ++v) \n {\n int e = 0;\n for (; e < g->num_e[v]; ++e)\n {\n if (g->adj_list[v][e] == u)\n {\n ++sum;\n }\n }\n }\n return sum;\n}\n\nORIGIN_INLINE int graph_is_balanced(const graph *g)\n{\n const int num_v = g->num_v;\n int u = 0;\n for (; u < num_v; ++u)\n {\n if (graph_indegree(g, u) != graph_outdegree(g, u))\n {\n return FALSE;\n }\n }\n return TRUE;\n}\n\nORIGIN_INLINE void graph_add_edge(graph *g, int u, int v, double weight)\n{\n if (g->num_e[u] == g->capacity[u]) \n {\n graph_grow_lists(g, u);\n }\n g->adj_list[u][g->num_e[u]] = v;\n g->w_list[u][g->num_e[u]] = weight;\n g->num_e[u]++;\n}\n\nvoid graph_add_sym_edges(graph *g, int u, int v, double weight) \n{\n graph_add_edge(g, u, v, weight);\n graph_add_edge(g, v, u, weight);\n}\n\nint graph_rmv_edge(graph *g, int u, int v)\n{\n const int num_e = g->num_e[u];\n int e = 0;\n for (; e < num_e; ++e) \n {\n if (g->adj_list[u][e] == v) \n {\n g->num_e[u]--;\n int f = e;\n for (; f < num_e - 1; ++f) \n {\n g->adj_list[u][f] = g->adj_list[u][f+1];\n g->w_list[u][f] = g->w_list[u][f+1];\n }\n return TRUE;\n }\n }\n return FALSE;\n}\n\nint graph_rmv_sym_edges(graph *g, int u, int v)\n{\n return (graph_rmv_edge(g, u, v) && graph_rmv_edge(g, v, u));\n}\n\nint graph_has_edge(graph *g, int u, int v)\n{\n const int num_e = g->num_e[u];\n int e = 0;\n for (; e < num_e; ++e) \n {\n if (g->adj_list[u][e] == v) \n {\n return TRUE;\n }\n }\n return FALSE;\n}\n\nint graph_strongly_connected(const graph *g)\n{\n const int num_v = g->num_v;\n int *group = (int*)malloc(num_v * sizeof(int));\n\n int u = 0;\n for (; u < num_v; ++u) \n {\n int v = 0;\n for (; v < num_v; ++v) \n {\n group[v] = FALSE;\n }\n\n group[u] = TRUE;\n graph_test_cc(g, group, u); // Call recursive function\n\n for (v = 0; v < num_v; ++v) \n {\n if (group[v] == FALSE) \n {\n free(group);\n return FALSE;\n }\n }\n }\n free(group);\n return TRUE;\n}\n\nvoid graph_svg(const graph *g, double *x, double *y, double size, double offset, FILE *out)\n{\n fprintf(out, \"\");\n const int num_v = g->num_v;\n for (int i = 0; i < num_v; ++i)\n {\n const int num_e = g->num_e[i];\n for (int j = 0; j < num_e; ++j)\n {\n const int e = g->adj_list[i][j];\n fprintf(out, \" \\n\", offset + x[i] * size, offset + y[i] * size, offset + x[e] * size, offset + y[e] * size);\n }\n }\n for (int i = 0; i < num_v; ++i)\n {\n fprintf(out, \" \\n\", i, offset + x[i] * size, offset + y[i] * size);\n }\n fprintf(out, \"\");\n}\n\nvoid graph_svg_abun(const graph *g, double *x, double *y, double size, double offset, double *abun, int color, FILE *out)\n{\n fprintf(out, \"\");\n const int num_v = g->num_v;\n for (int i = 0; i < num_v; ++i)\n {\n const int num_e = g->num_e[i];\n for (int j = 0; j < num_e; ++j)\n {\n const int e = g->adj_list[i][j];\n fprintf(out, \" \\n\", offset + x[i] * size, offset + y[i] * size, offset + x[e] * size, offset + y[e] * size);\n }\n }\n int clr[3] = {0, 0, 0};\n for (int i = 0; i < num_v; ++i)\n {\n clr[color] = (int)(abun[i] * 255);\n fprintf(out, \" \\n\", i, offset + x[i] * size, offset + y[i] * size, clr[0], clr[1], clr[2]);\n }\n fprintf(out, \"\");\n}\n\nvoid graph_graphml(const graph *g, FILE *out, unsigned int id)\n{\n const int num_v = g->num_v;\n fprintf(out, \"\\n\");\n fprintf(out, \"\\n\");\n\n fprintf(out, \" \\n\", id);\n for (int i = 0; i < num_v; ++i)\n {\n fprintf(out, \" \\n\", i);\n }\n for (int i = 0; i < num_v; ++i)\n {\n for (int e = 0; e < g->num_e[i]; ++e) \n {\n fprintf(out, \" \\n\", i, g->adj_list[i][e]);\n }\n }\n fprintf(out, \" \\n\");\n fprintf(out, \"\\n\");\n}\n\nvoid graph_print(const graph *g, FILE *out)\n{\n for (int i = 0; i < g->num_v; ++i) \n {\n fprintf(out, \"%5d -> \", i);\n for (int e = 0; e < g->num_e[i]; ++e) \n {\n fprintf(out, \"%d \", g->adj_list[i][e]);\n }\n fprintf(out, \"\\n\");\n }\n}\n\nvoid graph_free(graph *g)\n{\n const int num_v = g->num_v;\n for (int i = 0; i < num_v; ++i) \n {\n free(g->adj_list[i]);\n free(g->w_list[i]);\n }\n free(g->adj_list);\n g->adj_list = NULL;\n free(g->w_list);\n g->w_list = NULL;\n free(g->num_e);\n g->num_e = NULL;\n free(g->capacity);\n g->capacity = NULL;\n}\n\nvoid graph_get_rgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng)\n{\n graph_init(g, vertices);\n\n for (int i = 0; i < vertices; ++i)\n {\n x[i] = gsl_rng_uniform(rng);\n y[i] = gsl_rng_uniform(rng);\n }\t\n double d;\n for (int i = 0; i < vertices; ++i) \n {\n for (int j = 0; j < vertices; ++j) \n {\n const double a = x[i] - x[j];\n const double b = y[i] - y[j];\n d = hypot(a, b);\n if (d < r) \n {\n graph_add_edge(g, i, j, r - d);\n }\n }\n }\n}\n\nvoid graph_get_crgg(graph *g, int vertices, double r, double *x, double *y, gsl_rng *rng)\n{\n graph_init(g, vertices);\n graph_get_rgg(g, vertices, r, x, y, rng);\n\n while (graph_strongly_connected(g) == FALSE)\n {\n graph_free(g);\n graph_get_rgg(g, vertices, r, x, y, rng);\n }\n}\n\nvoid graph_get_rec_rgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng)\n{\n graph_init(g, vertices);\n\n const double length = 1.0 / width; // A = l * w so l = 1 / w\n\n for (int i = 0; i < vertices; ++i) \n {\n x[i] = gsl_rng_uniform(rng) * length;\n y[i] = gsl_rng_uniform(rng) * width;\n }\n double d;\n for (int i = 0; i < vertices; ++i) \n {\n for (int j = 0; j < vertices; ++j) \n {\n const double a = x[i] - x[j];\n const double b = y[i] - y[j];\n d = hypot(a, b);\n if (d < r) \n {\n graph_add_edge(g, i, j, r - d);\n }\n }\n }\n}\n\nvoid graph_get_rec_crgg(graph *g, int vertices, double width, double r, double *x, double *y, gsl_rng *rng)\n{\n graph_init(g, vertices);\n graph_get_rec_rgg(g, vertices, width, r, x, y, rng);\n\n while (graph_strongly_connected(g) == FALSE) \n {\n graph_free(g);\n graph_get_rec_rgg(g, vertices, width, r, x, y, rng);\n }\n}\n\nvoid graph_get_complete(graph *g, int vertices)\n{\n graph_init(g, vertices);\n\n for (int i = 0; i < vertices; ++i) \n {\n for (int j = 0; j < vertices; ++j) \n {\n graph_add_edge(g, i, j, 1.0);\n }\n }\n}\n\nvoid graph_get_circle(graph *g, int vertices)\n{\n graph_init(g, vertices);\n\n graph_add_edge(g, vertices - 1, vertices - 1, 1.0);\n graph_add_sym_edges(g, 0, vertices - 1, 1.0);\n\n for (int u = 0; u < vertices - 1; ++u)\n {\n graph_add_edge(g, u, u, 1.0);\n graph_add_sym_edges(g, u, u + 1, 1.0);\n }\n}\n\nvoid graph_get_star(graph *g, int vertices)\n{\n graph_init(g, vertices);\n\n for (int u = 0; u < vertices; ++u)\n {\n graph_add_edge(g, u, u, 1.0);\n graph_add_sym_edges(g, u, 0, 1.0);\n }\n}\n\n///////////////////////////////////////////////////////////////\n// 'Private' functions\n\nvoid graph_test_cc(const graph *g, int *group, int u)\n{\n const int num_e = g->num_e[u];\n int e = 0;\n for (; e < num_e; ++e) \n {\n const int head = g->adj_list[u][e];\n if (head != u && group[head] == FALSE)\n {\n group[head] = TRUE;\n graph_test_cc(g, group, head);\n }\n }\n}\n\n// Grow the edge list of some vertex v.\nvoid graph_grow_lists(graph *g, int u)\n{\n g->capacity[u] <<= 1;\n\n int *tmp_adj = (int*)malloc(g->capacity[u] * sizeof(int));\n double *tmp_w = (double*)malloc(g->capacity[u] * sizeof(double));\n\n const int num_e = g->num_e[u];\n int e = 0;\n for (; e < num_e; ++e) \n {\n tmp_adj[e] = g->adj_list[u][e];\n tmp_w[e] = g->w_list[u][e];\n }\n int *swap_adj = g->adj_list[u];\n double *swap_w = g->w_list[u];\n\n g->adj_list[u] = tmp_adj;\n g->w_list[u] = tmp_w;\n\n free(swap_adj);\n free(swap_w);\n}\n", "meta": {"hexsha": "7e3f73e58093c549eb693582b05687003b62e3bc", "size": 11284, "ext": "c", "lang": "C", "max_stars_repo_path": "src/graph.c", "max_stars_repo_name": "PhDP/Origin", "max_stars_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graph.c", "max_issues_repo_name": "PhDP/Origin", "max_issues_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graph.c", "max_forks_repo_name": "PhDP/Origin", "max_forks_repo_head_hexsha": "79d02f0d850a9b078e58d5f5af6ff1d2143cf712", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6375545852, "max_line_length": 211, "alphanum_fraction": 0.4871499468, "num_tokens": 3617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.28622434432602906}} {"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/*! \\file dnest_sa1d.c\n * \\brief run dnest sampling for sa and 2d rm analysis.\n */\n\n#ifdef SpecAstro\n\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 \"brains.h\"\n\nDNestFptrSet *fptrset_sa2d;\n\nint dnest_sa2d(int argc, char **argv)\n{\n int i;\n double logz_sa2d;\n \n if(parset.flag_sa_par_mutual == 0) /* SA and RM have the same BLR */\n {\n set_blr_model2d();\n num_params_sa_blr_model = 0;\n }\n else if(parset.flag_sa_par_mutual == 1) /* SA and RM have different BLRs but share the same mbh and inc. */\n {\n set_blr_model2d();\n set_sa_blr_model();\n }\n else \n {\n set_blr_model2d();\n set_sa_blr_model();\n }\n \n /* parameter order: RM BLR, SA BLR, RM continuum */\n /* RM */\n num_params_blr = num_params_blr_model + num_params_nlr \n + num_params_res + num_params_linecenter + 1; /* include and line sys err */\n num_params_rm = parset.n_con_recon + num_params_blr + num_params_var;\n \n /* SA */\n num_params_sa_blr = num_params_sa_blr_model + num_params_sa_extpar;\n num_params_sa = num_params_sa_blr;\n \n /* total */\n num_params_blr_tot = num_params_blr + num_params_sa_blr;\n num_params = num_params_sa + num_params_rm;\n idx_resp = num_params_blr_tot + num_params_drw + num_params_trend;\n idx_difftrend = idx_resp + num_params_resp;\n idx_linecenter = num_params_blr_model + num_params_nlr + num_params_res;\n\n rnd_frac = fmax(0.2, 1.0*(num_params_blr_tot+num_params_var)/num_params);\n\n par_fix = (int *) malloc(num_params * sizeof(int));\n par_fix_val = (double *) malloc(num_params * sizeof(double));\n par_range_model = malloc( num_params * sizeof(double *));\n par_prior_gaussian = malloc( num_params * sizeof(double *));\n for(i=0; ifrom_prior = from_prior_sa2d;\n fptrset_sa2d->print_particle = print_particle_sa2d;\n fptrset_sa2d->restart_action = restart_action_sa;\n fptrset_sa2d->accept_action = accept_action_sa2d;\n fptrset_sa2d->kill_action = kill_action_sa2d;\n fptrset_sa2d->perturb = perturb_sa2d;\n fptrset_sa2d->read_particle = read_particle_sa2d;\n\n fptrset_sa2d->log_likelihoods_cal_initial = log_likelihoods_cal_initial_sa2d;\n fptrset_sa2d->log_likelihoods_cal_restart = log_likelihoods_cal_restart_sa2d;\n fptrset_sa2d->log_likelihoods_cal = log_likelihoods_cal_sa2d;\n\n set_par_range_sa2d();\n set_par_fix_blrmodel();\n set_par_fix_sa_blrmodel();\n\n /* the rest parameters */\n for(i=num_params_blr_model; i 0.0)\n {\n par_range_model[i][0] = var_param[i-num_params_blr_tot] - 5.0 * var_param_std[i-num_params_blr_tot];\n par_range_model[i][1] = var_param[i-num_params_blr_tot] + 5.0 * var_param_std[i-num_params_blr_tot];\n\n /* make sure that the range lies within the initial range */\n par_range_model[i][0] = fmax(par_range_model[i][0], var_range_model[i-num_params_blr_tot][0]);\n par_range_model[i][1] = fmin(par_range_model[i][1], var_range_model[i-num_params_blr_tot][1]);\n\n par_prior_model[i] = GAUSSIAN;\n par_prior_gaussian[i][0] = var_param[i-num_params_blr_tot];\n par_prior_gaussian[i][1] = var_param_std[i-num_params_blr_tot];\n }\n else\n {\n par_range_model[i][0] = var_range_model[i-num_params_blr_tot][0];\n par_range_model[i][1] = var_range_model[i-num_params_blr_tot][1];\n\n par_prior_model[i] = UNIFORM;\n par_prior_gaussian[i][0] = 0.0;\n par_prior_gaussian[i][1] = 0.0;\n }\n }\n /* long-term trend of continuum */\n for(i=num_params_drw + num_params_blr_tot; i< num_params_drw + num_params_trend + num_params_blr_tot; i++)\n {\n par_range_model[i][0] = var_range_model[3][0];\n par_range_model[i][1] = var_range_model[3][1];\n\n par_prior_model[i] = GAUSSIAN;\n par_prior_gaussian[i][0] = 0.0;\n par_prior_gaussian[i][1] = 1.0;\n }\n\n /* response A and Ag */\n j = 0;\n i1 = idx_resp;\n i2 = idx_resp + num_params_resp;\n for(i=i1; i (size_levels-10)?(size_levels-10):which_level_update;\n\n if( which_level > 0)\n {\n limit1 = limits[(which_level-1) * num_params *2 + which *2];\n limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1];\n width = (limit2 - limit1);\n }\n else\n {\n limit1 = par_range_model[which][0];\n limit2 = par_range_model[which][1];\n width = (par_range_model[which][1] - par_range_model[which][0]);\n }\n width /= (2.35);\n\n if(par_prior_model[which] == GAUSSIAN)\n {\n logH -= (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );\n pm[which] += dnest_randh() * width;\n dnest_wrap(&pm[which], par_range_model[which][0], par_range_model[which][1]);\n //dnest_wrap(&pm[which], limit1, limit2);\n logH += (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );\n }\n else\n {\n pm[which] += dnest_randh() * width;\n dnest_wrap(&(pm[which]), par_range_model[which][0], par_range_model[which][1]);\n //dnest_wrap(&pm[which], limit1, limit2);\n }\n\n return logH;\n}\n\n\n/*!\n * this function calculates likelihood.\n */\ndouble log_likelihoods_cal_sa2d_exam(const void *model)\n{\n return 0.0;\n}\n\nvoid accept_action_sa2d()\n{\n int param;\n double *ptemp;\n\n // the parameter previously updated\n param = which_parameter_update;\n\n /* continuum parameter is updated */\n if( param >= num_params_blr_tot )\n {\n /* \n *note that (response) Fline is also changed as long as Fcon is changed.\n *num_params_blr-the parameter is the systematic error of continuum.\n *the change of this parameter also changes continuum reconstruction.\n */\n\n ptemp = Fcon_rm_particles[which_particle_update];\n Fcon_rm_particles[which_particle_update] = Fcon_rm_particles_perturb[which_particle_update];\n Fcon_rm_particles_perturb[which_particle_update] = ptemp;\n }\n else if((\n param < num_params_blr_model || \n (param >= num_params_blr && param < num_params_blr_tot)\n ) && force_update != 1 )\n {\n /* RM and SA BLR parameter is updated \n * Note a) that the (num_par_blr-1)-th parameter is systematic error of line.\n * when this parameter is updated, Trans2D, Fline, phase_sa, and Fline_sa are unchanged.\n * b) Fline is always changed, except param = num_params_blr-1.\n */\n \n ptemp = TransTau_particles[which_particle_update];\n TransTau_particles[which_particle_update] = TransTau_particles_perturb[which_particle_update];\n TransTau_particles_perturb[which_particle_update] = ptemp;\n\n ptemp = Trans2D_at_veldata_particles[which_particle_update];\n Trans2D_at_veldata_particles[which_particle_update] = Trans2D_at_veldata_particles_perturb[which_particle_update];\n Trans2D_at_veldata_particles_perturb[which_particle_update] = ptemp;\n\n prob_sa_particles[which_particle_update] = prob_sa_particles_perturb[which_particle_update];\n }\n \n //Fline is always updated except param = num_params_blr - 1\n if( param != num_params_blr-1 && force_update != 1)\n {\n ptemp = Fline_at_data_particles[which_particle_update];\n Fline_at_data_particles[which_particle_update] = Fline_at_data_particles_perturb[which_particle_update];\n Fline_at_data_particles_perturb[which_particle_update] = ptemp;\n }\n return;\n}\n\n/*\n * action when particle i is killed in cdnest sampling.\n * particle i_copy's properties is copyed to particle i. \n */\nvoid kill_action_sa2d(int i, int i_copy)\n{\n memcpy(Fcon_rm_particles[i], Fcon_rm_particles[i_copy], parset.n_con_recon * sizeof(double));\n memcpy(Fline_at_data_particles[i], Fline_at_data_particles[i_copy], n_line_data * n_vel_data_ext * sizeof(double));\n memcpy(TransTau_particles[i], TransTau_particles[i_copy], parset.n_tau*sizeof(double));\n memcpy(Trans2D_at_veldata_particles[i], Trans2D_at_veldata_particles[i_copy], parset.n_tau * n_vel_data_ext * sizeof(double));\n\n prob_sa_particles[i] = prob_sa_particles[i_copy];\n\n return;\n}\n\n\n#endif", "meta": {"hexsha": "3691d2332de7831f058f3740c3dbb46d32622027", "size": 21297, "ext": "c", "lang": "C", "max_stars_repo_path": "src/dnest_sa2d.c", "max_stars_repo_name": "LiyrAstroph/BRAINS", "max_stars_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-11-16T13:37:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T07:46:45.000Z", "max_issues_repo_path": "src/dnest_sa2d.c", "max_issues_repo_name": "LiyrAstroph/BRAINS", "max_issues_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dnest_sa2d.c", "max_forks_repo_name": "LiyrAstroph/BRAINS", "max_forks_repo_head_hexsha": "39ff93e2c26a20d5d79d37e5a7a4895b93cf48e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-06-12T13:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-22T12:54:58.000Z", "avg_line_length": 29.8695652174, "max_line_length": 128, "alphanum_fraction": 0.6595764662, "num_tokens": 6499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7431680086124811, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2860543919068845}} {"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_TYPES_H\n#define UKF_TYPES_H\n\n#include \n#include \n#include \n#include \n#include \n#include \"ukf_math.h\"\n\nnamespace ukf\n{\n\n /**\n * @short The different types of implemented process noise for UKF state estimation\n */\n typedef enum\n {\n /**\n * @brief The covariance of the evolution noise is fixed to \\f$\\textbf{P}_{\\theta\\theta_i} = \\alpha . \\textbf{I}\\f$\n */\n UKF_PROCESS_FIXED,\n /**\n * @brief The covariance of the evolution noise is defined as \\f$\\textbf{P}_{\\theta\\theta_i} = (\\alpha^{-1} - 1)\\textbf{P}_i\\f$\n */\n UKF_PROCESS_RLS\n } ProcessNoise; \n\n namespace parameter\n {\n class EvolutionNoise;\n /**\n * @short Structure holding the parameters of the Unscented Kalman Filter\n *\n */\n typedef struct\n {\n /**\n * @short \\f$\\kappa \\geq 0\\f$, \\f$\\kappa = 0\\f$ is a good choice. According to van der Merwe, its value is not critical\n */\n double kpa;\n\n /**\n * @short \\f$0 \\leq \\alpha \\leq 1\\f$ : \"Size\" of sigma-point distribution. Should be small if the function is strongly non-linear\n */\n double alpha;\n\n /**\n * @short Non negative weights used to introduce knowledge about the higher order moments of the distribution. For gaussian distributions, \\f$\\beta = 2\\f$ is a good choice\n */\n double beta;\n\n /**\n * @short \\f$\\lambda = \\alpha^2 (n + \\kappa) - n\\f$\n */\n double lambda;\n\n /**\n * @short \\f$\\gamma = \\sqrt{\\lambda + n}\\f$\n */\n double gamma;\n\n /**\n * @short Parameter used for the evolution noise\n */\n //double evolution_noise_parameter;\n\n /**\n * @short Initial value of the evolution noise\n */\n //double evolution_noise;\n\n /**\n * @short Evolution noise type\n */\n //EvolutionNoise evolution_noise_type;\n EvolutionNoise * evolution_noise;\n\n /**\n * @short Covariance of the observation noise\n */\n double observation_noise;\n\n /**\n * @short Prior estimate of the covariance matrix\n */\n double prior_pi;\n\n /**\n * @short Number of parameters to estimate\n */\n int n;\n\n /**\n * @short \\f$nbSamples = (2 n + 1)\\f$ Number of sigma-points\n */\n int nbSamples;\n\n /**\n * @short Dimension of the output\n */\n int no;\n\n } ukf_param;\n\n /**\n * @short Pointer to the function to approximate in the scalar case\n *\n */\n //typedef double (*ukf_function_scalar) (gsl_vector * param, gsl_vector * input);\n\n /**\n * @short Structure holding the matrices manipulated by the statistical linearization\n * in the scalar case\n *\n */\n typedef struct\n {\n /**\n * @short Kalman gain, a vector of size \\f$n\\f$\n */\n gsl_vector * Kk;\n\n /**\n * @short Temporary matrix for the kalman gain, a matrix of size \\f$(n,1)\\f$\n */\n gsl_matrix * Kk_mat;\n\n /**\n * @short Temporary matrix for the transpose of the kalman gain, a matrix of size \\f$(1,n)\\f$\n */\n gsl_matrix * Kk_mat_T;\n\n /**\n * @short Covariance of \\f$(w, d)\\f$: \\f$P_{w_k d_k}\\f$, of size \\f$n\\f$\n */\n gsl_vector * Pwdk;\n\n /**\n * @short Covariance of the evolution noise\n */\n gsl_matrix * Prrk;\n\n /**\n * @short Covariance of the observation noise\n */\n double Peek;\n\n /**\n * @short Covariance of the output\n */\n double Pddk;\n\n /**\n * @short Parameter vector, of size \\f$n\\f$\n */\n gsl_vector * w;\n\n /**\n * @short Temporary vector, holding a sigma-point\n */\n gsl_vector * wk;\n\n /**\n * @short Covariance matrix of the parameters, of size \\f$(n,n)\\f$\n */\n gsl_matrix * Pk;\n\n /**\n * @short Matrix holding the Cholesky decomposition of \\f$P_k\\f$, of size \\f$(n,n)\\f$\n */\n gsl_matrix * Sk;\n\n /**\n * @short Vector holding one column of Sk, of size \\f$n\\f$\n */\n gsl_vector * cSk;\n\n /**\n * @short Weights used to compute the mean of the sigma points' images\n * @brief \\f$wm_0 = \\frac{\\lambda}{n + \\lambda}\\f$\n * \\f$wm_i = \\frac{1}{2(n + \\lambda)}\\f$\n */\n gsl_vector * wm;\n\n /**\n * @short Weights used to update the covariance matrices\n * @brief \\f$wc_0 = \\frac{\\lambda}{n + \\lambda} + (1 - \\alpha^2 + \\beta)\\f$\n * \\f$wc_i = \\frac{1}{2(n + \\lambda)}\\f$\n */\n gsl_vector * wc;\n\n /**\n * @short Temporary vector holding the image of the sigma points, of size \\f$nbSamples\\f$\n */\n gsl_vector * dk;\n\n /**\n * @short Innovation\n */\n double ino_dk;\n\n /**\n * @short Variable holding the mean of the sigma points image\n */\n double d_mean;\n\n /**\n * @short Matrix holding the sigma points in the columns, of size \\f$(n,nbSamples)\\f$\n */\n gsl_matrix * sigmaPoints;\n\n /**\n * @short Temporary vector\n */\n gsl_vector * temp_n;\n\n /**\n * @short Temporary matrix\n */\n gsl_matrix * temp_n_n;\n\n } ukf_scalar_state;\n\n /**\n * @short Structure holding the matrices manipulated by the unscented kalman filter\n * in the vectorial case, for Parameter estimation\n *\n */\n typedef struct\n {\n /**\n * @short Kalman gain, a matrix of size \\f$n \\times no\\f$\n */\n gsl_matrix * Kk;\n\n /**\n * @short The tranposed Kalman gain, a vector of size \\f$no \\times n\\f$\n */\n gsl_matrix * Kk_T;\n\n /**\n * @short Covariance of \\f$(w, d)\\f$: \\f$P_{w_k d_k}\\f$, of size \\f$n \\times no\\f$\n */\n gsl_matrix * Pwdk;\n\n /**\n * @short Covariance of the output, a matrix of size \\f$ no \\times no \\f$\n */\n gsl_matrix * Pddk;\n\n /**\n * @short Covariance of the observation noise, of size \\f$ no \\times no \\f$\n */\n gsl_matrix * Peek;\n\n /**\n * @short Covariance of the evolution noise, of size \\f$ n \\times n \\f$\n */\n gsl_matrix * Prrk;\n\n /**\n * @short Parameter vector, of size \\f$n\\f$\n */\n gsl_vector * w;\n\n /**\n * @short Temporary vector holding one sigma point, of size \\f$n\\f$\n */\n gsl_vector * wk;\n\n /**\n * @short Covariance matrix of the parameters, of size \\f$(n,n)\\f$\n */\n gsl_matrix * Pk;\n\n /**\n * @short Matrix holding the Cholesky decomposition of \\f$P_k\\f$, of size \\f$(n,n)\\f$\n */\n gsl_matrix * Sk;\n\n /**\n * @short Vector holding one column of Sk, of size \\f$n\\f$\n */\n gsl_vector * cSk;\n\n /**\n * @short Weights used to compute the mean of the sigma points' images\n * @brief \\f$wm_0 = \\frac{\\lambda}{n + \\lambda}\\f$\n * \\f$wm_i = \\frac{1}{2(n + \\lambda)}\\f$\n */\n gsl_vector * wm;\n\n /**\n * @short Weights used to update the covariance matrices\n * @brief \\f$wc_0 = \\frac{\\lambda}{n + \\lambda} + (1 - \\alpha^2 + \\beta)\\f$\n * \\f$wc_i = \\frac{1}{2(n + \\lambda)}\\f$\n */\n gsl_vector * wc;\n\n /**\n * @short Temporary matrix holding the image of the sigma points, of size \\f$ no \\times nbSamples\\f$\n */\n gsl_matrix * dk;\n\n /**\n * @short Vector holding the mean of the sigma points image, of size \\f$ no \\f$ŝ\n */\n gsl_vector * d_mean;\n\n /**\n * @short Vector holding the inovation, of size \\f$ no \\f$ŝ\n */\n gsl_vector * ino_dk;\n\n /**\n * @short Matrix holding the sigma points in the columns, of size \\f$(n,nbSamples)\\f$\n */\n gsl_matrix * sigmaPoints;\n\n /**\n * @short Temporary vector of size \\f$ n \\f$\n */\n gsl_vector * vec_temp_n;\n\n /**\n * @short Temporary vector of size \\f$ no \\f$\n */\n gsl_vector * vec_temp_output;\n\n /**\n * @short Temporary matrix of size \\f$ n \\times 1 \\f$\n */\n gsl_matrix * mat_temp_n_1;\n\n /**\n * @short Temporary matrix of size \\f$ n \\times no \\f$\n */\n gsl_matrix * mat_temp_n_output;\n\n /**\n * @short Temporary matrix of size \\f$ no \\times n \\f$\n */\n gsl_matrix * mat_temp_output_n;\n\n /**\n * @short Temporary matrix of size \\f$ 1 \\times no \\f$\n */\n gsl_matrix * mat_temp_1_output;\n\n /**\n * @short Temporary matrix of size \\f$ no \\times 1 \\f$\n */\n gsl_matrix * mat_temp_output_1;\n\n /**\n * @short Temporary matrix of size \\f$ no \\times no \\f$\n */\n gsl_matrix * mat_temp_output_output;\n\n /**\n * @short Temporary matrix of size \\f$ n \\times n \\f$\n */\n gsl_matrix * mat_temp_n_n;\n } ukf_state;\n\n /**\n * @short Mother class from which the evolution noises inherit\n */\n class EvolutionNoise\n {\n protected:\n double _initial_value;\n public:\n EvolutionNoise(double initial_value) : _initial_value(initial_value) {};\n void init(ukf_param &p, ukf_state &s)\n {\n gsl_matrix_set_identity(s.Prrk);\n gsl_matrix_scale(s.Prrk, _initial_value);\n }\n void init(ukf_param &p, ukf_scalar_state &s)\n {\n gsl_matrix_set_identity(s.Prrk);\n gsl_matrix_scale(s.Prrk, _initial_value);\n }\n\n virtual void updateEvolutionNoise(ukf_param &p, ukf_state &s) = 0;\n virtual void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s) = 0;\n };\n\n /**\n * @short Annealing type evolution noise\n */\n class EvolutionAnneal : public EvolutionNoise\n {\n double _decay, _lower_bound;\n public:\n EvolutionAnneal(double initial_value, double decay, double lower_bound) : EvolutionNoise(initial_value),\n _decay(decay),\n _lower_bound(lower_bound)\n { };\n\n void updateEvolutionNoise(ukf_param &p, ukf_state &s)\n {\n for(int i = 0 ; i < p.n ; ++i)\n {\n for(int j = 0 ; j < p.n ; ++j)\n {\n if(i == j)\n gsl_matrix_set(s.Prrk, i, i, ukf::math::max(_decay * gsl_matrix_get(s.Prrk,i,i),_lower_bound));\n else\n gsl_matrix_set(s.Prrk, i, j, 0.0);\n }\n }\n }\n void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s)\n {\n for(int i = 0 ; i < p.n ; ++i)\n {\n for(int j = 0 ; j < p.n ; ++j)\n {\n if(i == j)\n gsl_matrix_set(s.Prrk, i, i, ukf::math::max(_decay * gsl_matrix_get(s.Prrk,i,i),_lower_bound));\n else\n gsl_matrix_set(s.Prrk, i, j, 0.0);\n }\n }\n }\n };\n\n /**\n * @short Forgetting type evolution noise\n */\n class EvolutionRLS : public EvolutionNoise\n {\n double _decay;\n public:\n EvolutionRLS(double initial_value, double decay) : EvolutionNoise(initial_value), _decay(decay)\n {\n if(ukf::math::cmp_equal(_decay, 0.0))\n printf(\"Forgetting factor should not be null !!\\n\");\n };\n\n void updateEvolutionNoise(ukf_param &p, ukf_state &s)\n {\n gsl_matrix_memcpy(s.Prrk, s.Pk);\n gsl_matrix_scale(s.Prrk, 1.0 / _decay - 1.0);\n }\n void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s)\n {\n gsl_matrix_memcpy(s.Prrk, s.Pk);\n gsl_matrix_scale(s.Prrk, 1.0 / _decay - 1.0);\n }\n };\n\n /**\n * @short Robbins-Monro evolution noise\n */\n class EvolutionRobbinsMonro : public EvolutionNoise\n {\n double _alpha;\n public:\n EvolutionRobbinsMonro(double initial_value, double alpha) : EvolutionNoise(initial_value),\n _alpha(alpha)\n { };\n\n void updateEvolutionNoise(ukf_param &p, ukf_state &s)\n {\n // Compute Kk * ino_yk\n\t gsl_matrix_view mat_view = gsl_matrix_view_array(s.ino_dk->data, p.no, 1);\n\t gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Kk, &mat_view.matrix, 0.0, s.mat_temp_n_1);\n\t // Compute : Prrk = (1 - alpha) Prrk + alpha . (Kk * ino_dk) * (Kk * ino_dk)^T\n\t gsl_blas_dgemm(CblasNoTrans, CblasTrans, _alpha, s.mat_temp_n_1, s.mat_temp_n_1, (1.0 - _alpha),s.Prrk);\n }\n void updateEvolutionNoise(ukf_param &p, ukf_scalar_state &s)\n {\n // Compute Prrk = (1 - alpha) Prrk + alpha . ino_dk^2 Kk Kk^T\n\t gsl_matrix_view mat_view = gsl_matrix_view_array(s.Kk->data,p.n,1);\n gsl_blas_dgemm(CblasNoTrans, CblasTrans, gsl_pow_2(s.ino_dk) * _alpha, &mat_view.matrix, &mat_view.matrix, 1.0 - _alpha, s.Prrk);\n }\n };\n\n\n } // parameter\n\n namespace state\n {\n\n class EvolutionNoise;\n /**\n * @short Structure holding the parameters of the statistical linearization\n *\n */\n typedef struct\n {\n /**\n * @short \\f$\\kappa \\geq 0\\f$, \\f$\\kappa = 0\\f$ is a good choice. According to van der Merwe, its value is not critical\n */\n double kpa;\n\n /**\n * @short \\f$0 \\leq \\alpha \\leq 1\\f$ : \"Size\" of sigma-point distribution. Should be small if the function is strongly non-linear\n */\n double alpha;\n\n /**\n * @short Non negative weights used to introduce knowledge about the higher order moments of the distribution. For gaussian distributions, \\f$\\beta = 2\\f$ is a good choice\n */\n double beta;\n\n /**\n * @short \\f$\\lambda = \\alpha^2 (n + \\kappa) - n\\f$\n */\n double lambda;\n double lambda_aug;\n\n /**\n * @short \\f$\\gamma = \\sqrt{\\lambda + n}\\f$\n */\n double gamma;\n double gamma_aug;\n\n /**\n * @short Size of the state vector\n */\n int n;\n\n /**\n * @short \\f$nbSamples = (2 n + 1)\\f$ Number of sigma-points\n */\n int nbSamples;\n\n /**\n * @short \\f$nbSamplesMeasure = (4 n + 1)\\f$ Number of sigma-points\n */\n int nbSamplesMeasure;\n\n /**\n * @short Dimension of the output : the measurements\n */\n int no;\n\n /**\n * @short Prior estimate of the covariance matrix of the state\n */\n double prior_x;\n\n /**\n * @short Type of process noise\n */\n EvolutionNoise * evolution_noise;\n\n /**\n * @short Parameter used for the evolution noise\n */\n //double process_noise;\n\n /**\n * @short Covariance of the observation noise\n */\n double measurement_noise;\n\n } ukf_param;\n\n /**\n * @short Structure holding the matrices manipulated by the statistical linearization\n * in the vectorial case for state estimation\n *\n */\n typedef struct\n {\n gsl_vector * params; // The parameters of the process equation or anything you need to give to the process function\n\n gsl_vector * xi; // State vector\n gsl_matrix * xi_prediction; // Prediction of the states for each sigma-point\n gsl_vector * xi_mean; // Mean state vector\n gsl_matrix * Pxxi; // State covariance matrix\n gsl_matrix * cholPxxi; // Cholesky decomposition of Pxxi\n gsl_matrix * Pvvi; // Process noise covariance\n gsl_matrix * cholPvvi; // Cholesky decomposition of the process noise\n\n gsl_matrix * yi_prediction; // Prediction of the measurements for each sigma-point\n gsl_vector * yi_mean; // Mean measurement vector\n gsl_vector * ino_yi; // Innovations\n gsl_matrix * Pyyi; // Measurement covariance matrix\n gsl_matrix * Pnni; // Measurement noise covariance\n\n gsl_matrix * Pxyi; // State-Measurement covariance matrix\n\n gsl_vector * sigmaPoint; // Vector holding one sigma point\n gsl_matrix * sigmaPoints; // Matrix holding all the sigma points\n\n gsl_vector * sigmaPointMeasure; // one sigma point for the observation equation\n gsl_matrix * sigmaPointsMeasure; // Sigma points for the observation equation\n\n gsl_vector * wm_j; // Weights used to compute the mean of the sigma points images\n gsl_vector * wc_j; // Weights used to update the covariance matrices\n\n gsl_vector * wm_aug_j; // Augmented set of Weights used to compute the mean of the sigma points images for the observations\n gsl_vector * wc_aug_j; // Augmented set of Weights used to update the covariance matrices of the observations\n\n gsl_matrix * Ki; // Kalman gain\n gsl_matrix * Ki_T; // Its transpose\n\n gsl_vector * temp_n;\n gsl_matrix * temp_n_n;\n gsl_matrix * temp_n_1;\n gsl_matrix * temp_1_n;\n\n gsl_matrix * temp_n_no;\n\n gsl_matrix * temp_no_no;\n gsl_matrix * temp_no_1;\n gsl_matrix * temp_1_no;\n } ukf_state;\n\n /**\n * @short Mother class from which the evolution noises inherit\n */\n class EvolutionNoise\n {\n protected:\n double _initial_value;\n public:\n EvolutionNoise(double initial_value) : _initial_value(initial_value) {};\n void init(ukf_param &p, ukf_state &s)\n {\n gsl_matrix_set_identity(s.Pvvi);\n gsl_matrix_scale(s.Pvvi, _initial_value);\n gsl_matrix_set_identity(s.cholPvvi);\n gsl_matrix_scale(s.cholPvvi, sqrt(_initial_value));\n }\n\n virtual void updateEvolutionNoise(ukf_param &p, ukf_state &s) = 0;\n };\n\n /**\n * @short Annealing type evolution noise\n */\n class EvolutionAnneal : public EvolutionNoise\n {\n double _decay, _lower_bound;\n public:\n EvolutionAnneal(double initial_value, double decay, double lower_bound) : EvolutionNoise(initial_value),\n _decay(decay),\n _lower_bound(lower_bound)\n { };\n\n void updateEvolutionNoise(ukf_param &p, ukf_state &s)\n {\n double value;\n for(int i = 0 ; i < p.n ; ++i)\n {\n for(int j = 0 ; j < p.n ; ++j)\n {\n if(i == j)\n {\n value = ukf::math::max(_decay * gsl_matrix_get(s.Pvvi,i,i),_lower_bound);\n gsl_matrix_set(s.Pvvi, i, i, value);\n gsl_matrix_set(s.cholPvvi, i ,i, sqrt(value));\n }\n else\n {\n gsl_matrix_set(s.Pvvi, i, j, 0.0);\n gsl_matrix_set(s.cholPvvi, i, j, 0.0);\n }\n }\n }\n }\n };\n\n /**\n * @short Forgetting type evolution noise\n */\n class EvolutionRLS : public EvolutionNoise\n {\n double _decay;\n public:\n EvolutionRLS(double initial_value, double decay) : EvolutionNoise(initial_value), _decay(decay)\n {\n if(ukf::math::cmp_equal(_decay, 0.0))\n printf(\"Forgetting factor should not be null !!\\n\");\n };\n\n void updateEvolutionNoise(ukf_param &p, ukf_state &s)\n {\n gsl_matrix_memcpy(s.Pvvi, s.Pxxi);\n gsl_matrix_scale(s.Pvvi, 1.0 / _decay - 1.0);\n gsl_matrix_memcpy(s.cholPvvi, s.Pvvi);\n gsl_linalg_cholesky_decomp(s.cholPvvi);\n // Set all the elements of cholPvvi strictly above the diagonal to zero\n for(int j = 0 ; j < p.n ; j++)\n for(int k = j+1 ; k < p.n ; k++)\n gsl_matrix_set(s.cholPvvi,j,k,0.0);\n }\n };\n\n /**\n * @short Robbins-Monro evolution noise\n */\n class EvolutionRobbinsMonro : public EvolutionNoise\n {\n double _alpha;\n public:\n EvolutionRobbinsMonro(double initial_value, double alpha) : EvolutionNoise(initial_value),\n _alpha(alpha)\n { };\n\n void updateEvolutionNoise(ukf_param &p, ukf_state &s)\n {\n // Compute Kk * ino_yk\n gsl_blas_dgemv(CblasNoTrans, 1.0, s.Ki, s.ino_yi, 0.0, s.temp_n);\n // Compute : Prrk = (1 - alpha) Prrk + alpha . (Kk * ino_dk) * (Kk * ino_dk)^T\n\t\tgsl_matrix_view mat_view = gsl_matrix_view_array(s.temp_n->data,p.n,1);\n gsl_blas_dgemm(CblasNoTrans, CblasTrans, _alpha, &mat_view.matrix, &mat_view.matrix, (1.0 - _alpha),s.Pvvi);\n }\n };\n\n\n } // namespace for state estimation\n\n namespace srstate\n {\n\n\n /**\n * @short Structure holding the parameters of the statistical linearization\n *\n */\n typedef struct\n {\n /**\n * @short \\f$\\kappa \\geq 0\\f$, \\f$\\kappa = 0\\f$ is a good choice. According to van der Merwe, its value is not critical\n */\n double kpa;\n\n /**\n * @short \\f$0 \\leq \\alpha \\leq 1\\f$ : \"Size\" of sigma-point distribution. Should be small if the function is strongly non-linear\n */\n double alpha;\n\n /**\n * @short Non negative weights used to introduce knowledge about the higher order moments of the distribution. For gaussian distributions, \\f$\\beta = 2\\f$ is a good choice\n */\n double beta;\n\n /**\n * @short \\f$\\lambda = \\alpha^2 (n + \\kappa) - n\\f$\n */\n double lambda;\n double lambda_aug;\n\n /**\n * @short \\f$\\gamma = \\sqrt{\\lambda + n}\\f$\n */\n double gamma;\n double gamma_aug;\n\n /**\n * @short Size of the state vector\n */\n int n;\n\n /**\n * @short \\f$nbSamples = (2 n + 1)\\f$ Number of sigma-points\n */\n int nbSamples;\n\n /**\n * @short \\f$nbSamplesMeasure = (4 n + 1)\\f$ Number of sigma-points\n */\n int nbSamplesMeasure;\n\n /**\n * @short Dimension of the output : the measurements\n */\n int no;\n\n /**\n * @short Prior estimate of the covariance matrix of the state\n */\n double prior_x;\n\n /**\n * @short Type of process noise\n */\n ProcessNoise process_noise_type;\n\n /**\n * @short Parameter used for the evolution noise\n */\n double process_noise;\n\n /**\n * @short Covariance of the observation noise\n */\n double measurement_noise;\n\n } ukf_param;\n\n /**\n * @short Structure holding the matrices manipulated by the statistical linearization\n * in the vectorial case for state estimation\n *\n */\n typedef struct\n {\n gsl_vector * params; // The parameters of the process equation or anything you need to give to the process function\n\n gsl_vector * xi; // State vector\n gsl_matrix * xi_prediction; // Prediction of the states for each sigma-point\n gsl_vector * xi_mean; // Mean state vector\n gsl_matrix * Sxi; // Cholesky factor of variance covariance of the state\n gsl_matrix * Svi; // Cholesky factor of the process noise\n\n gsl_matrix * yi_prediction; // Prediction of the measurements for each sigma-point\n gsl_vector * yi_mean; // Mean measurement vector\n gsl_vector * ino_yi; // Innovations\n gsl_matrix * Syi; // Cholesky factor of the variance covariance of the output\n gsl_matrix * Sni; // Cholesky factor of the measurement noise\n\n gsl_matrix * Pxyi; // State-Measurement covariance matrix\n\n gsl_vector * sigmaPoint; // Vector holding one sigma point\n gsl_matrix * sigmaPoints; // Matrix holding all the sigma points\n\n gsl_vector * sigmaPointMeasure; // one sigma point for the observation equation\n gsl_matrix * sigmaPointsMeasure; // Sigma points for the observation equation\n\n gsl_matrix * U;\n\n gsl_vector * wm_j; // Weights used to compute the mean of the sigma points images\n gsl_vector * wc_j; // Weights used to update the covariance matrices\n\n gsl_vector * wm_aug_j; // Augmented set of Weights used to compute the mean of the sigma points images for the observations\n gsl_vector * wc_aug_j; // Augmented set of Weights used to update the covariance matrices of the observations\n\n gsl_matrix * Ki; // Kalman gain\n gsl_matrix * Ki_T; // Its transpose\n\n gsl_vector * temp_n;\n gsl_vector * temp_no;\n\n gsl_matrix * temp_n_n;\n gsl_matrix * temp_n_1;\n gsl_matrix * temp_1_n;\n\n gsl_matrix * temp_n_no;\n\n gsl_matrix * temp_no_no;\n gsl_matrix * temp_no_1;\n gsl_matrix * temp_1_no;\n\n gsl_matrix * temp_3n_n;\n gsl_matrix * temp_2nno_no;\n } ukf_state; \n\n\n } // namespace for state estimation, square root implementation\n\n}\n\n\n#endif // UKF_TYPES_H\n", "meta": {"hexsha": "6ceb9b8093d459ccf32d8231c19c82db55fdbc98", "size": 29827, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ukf_types.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_types.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_types.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": 33.588963964, "max_line_length": 184, "alphanum_fraction": 0.5024306836, "num_tokens": 6638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2854685920681385}} {"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 dnest_con.c\n * \\brief run dnest for continuum analysis\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"brains.h\"\n\nDNestFptrSet *fptrset_con;\n\n/*!\n * This function run dnest sampling for continuum.\n */\nint dnest_con(int argc, char **argv)\n{\n int i;\n\n num_params = parset.n_con_recon + num_params_var;\n\n par_range_model = malloc( num_params * sizeof(double *));\n par_prior_gaussian = malloc(num_params * sizeof(double *));\n for(i=0; ifrom_prior = from_prior_con;\n fptrset_con->perturb = perturb_con;\n fptrset_con->print_particle = print_particle_con;\n fptrset_con->restart_action = restart_action_con;\n fptrset_con->accept_action = accept_action_con;\n fptrset_con->kill_action = kill_action_con;\n fptrset_con->read_particle = read_particle_con;\n \n if(parset.flag_exam_prior != 1)\n {\n fptrset_con->log_likelihoods_cal = log_likelihoods_cal_con;\n fptrset_con->log_likelihoods_cal_initial = log_likelihoods_cal_initial_con;\n fptrset_con->log_likelihoods_cal_restart = log_likelihoods_cal_restart_con;\n }\n else\n {\n fptrset_con->log_likelihoods_cal = log_likelihoods_cal_con_exam;\n fptrset_con->log_likelihoods_cal_initial = log_likelihoods_cal_con_exam;\n fptrset_con->log_likelihoods_cal_restart = log_likelihoods_cal_con_exam;\n }\n \n set_par_range_con();\n \n /* setup fixed parameters */\n for(i=0; i (size_levels - 10)?(size_levels-10):which_level_update;\n if( which_level > 0)\n {\n limit1 = limits[(which_level-1) * num_params *2 + which *2];\n limit2 = limits[(which_level-1) * num_params *2 + which *2 + 1];\n width = limit2 - limit1;\n }\n else\n {\n width = ( par_range_model[which][1] - par_range_model[which][0] );\n }\n\n if(par_prior_model[which] == GAUSSIAN)\n {\n logH -= (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );\n pm[which] += dnest_randh() * width;\n dnest_wrap(&pm[which], par_range_model[which][0], par_range_model[which][1]);\n logH += (-0.5*pow((pm[which] - par_prior_gaussian[which][0])/par_prior_gaussian[which][1], 2.0) );\n }\n else\n {\n pm[which] += dnest_randh() * width;\n dnest_wrap(&(pm[which]), par_range_model[which][0], par_range_model[which][1]);\n }\n return logH;\n}\n\n/*!\n * This function print the particle into the file.\n */\nvoid print_particle_con(FILE *fp, const void *model)\n{\n int i;\n double *pm = (double *)model;\n\n for(i=0; i libnetlib.so\n\ngcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -L. -lnetlib -I../../../../netlib/CBLAS\n./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-CBLAS.csv\n\ngcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -I/System/Library/Frameworks/vecLib.framework/Headers -framework veclib\n./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-veclib.csv\n\ngcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -I/opt/local/include /opt/local/lib/libatlas.a /opt/local/lib/libcblas.a /opt/local/lib/liblapack.a /opt/local/lib/libf77blas.a -lgfortran\n./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-atlas.csv\n\ngcc-mp-4.8 -O3 dgemmtest.c common.c -o dgemmtest -I../../../../netlib/CBLAS -L/opt/intel/composerxe/mkl/lib -lmkl_rt\nexport DYLD_LIBRARY_PATH=/opt/intel/composerxe/mkl/lib:/opt/intel/composerxe/lib/\n./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-mkl.csv\n\ngcc-mp-4.8 -O3 dgemmtest.c cudawrapper.c common.c -o dgemmtest -I../../../../netlib/CBLAS -I/usr/local/cuda/include/ -L/usr/local/cuda/lib -lcublas\nexport DYLD_LIBRARY_PATH=/usr/local/cuda/lib\n./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-cuda.csv\n\nCLB=/Users/samuel/Documents/Projects/clBLAS/src\ngcc-mp-4.8 -O3 dgemmtest.c clwrapper.c common.c -o dgemmtest -I../../../../netlib/CBLAS -I$CLB -I$CLB/include -L. -lclBLAS -framework OpenCL\n./dgemmtest > ../../../results/mac_os_x-x86_64-dgemm-clblas.csv\n\n*/\n\n#include \n#include \n#include \n#include \n#include \"common.h\"\n\n// does AB == C ? If not, complain on stderr\nvoid test(int m, double* a, double *b, double *c) {\n\tint i, j, k, exact = 0, wrong = 0;\n\tdouble diff;\n\tdouble* d = calloc(m * m, sizeof(double));\n\tfor (i = 0 ; i < m ; i++) {\n\t\tfor (j = 0 ; j < m ; j++) {\n\t\t\tfor (k = 0 ; k < m ; k++) {\n\t\t\t\td[i + j * m] += a[i + k * m] * b[j * m + k];\n\t\t\t}\n\t\t}\n\t}\n\tfor (i = 0 ; i < m ; i++) {\n\t\tfor (j = 0 ; j < m ; j++) {\n\t\t\tdiff = c[i * m + j] - d[i * m + j];\n\t\t\tif (diff != 0.0) {\n\t\t\t\texact++;\n\t\t\t}\n\t\t\tif (abs(diff) > 0.000001) {\n\t\t\t\twrong++;\n\t\t\t}\n\t\t}\t\t\n\t}\n\tfree(d);\n\tif (wrong > 0) {\n\t\tfprintf(stderr, \"not exact = %d, wrong = %d\\n\", exact, wrong);\n\t}\n}\n\nlong benchmark(int size) {\n int m = sqrt(size);\n\tlong requestStart, requestEnd;\n\n double* a = random_array(m * m);\n double* b = random_array(m * m);\n double* c = calloc(m * m, sizeof(double));\n\n\trequestStart = currentTimeNanos();\n\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, m, m, 1, a, m, b, m, 0, c, m);\n\n\trequestEnd = currentTimeNanos();\n\n#ifdef __TEST__\n\ttest(m, a, b, c);\n#endif\n\n free(a);\n free(b);\n free(c);\n\n return (requestEnd - requestStart);\n }\n\nmain()\n{\n\tsrand(time(NULL));\n\n double factor = 6.0 / 100.0;\n int i, j;\n for (i = 0 ; i < 10 ; i++) {\n for (j = 1 ; j <= 100 ; j++) {\n int size = (int) pow(10.0, factor * j);\n if (size < 10) continue;\n long took = benchmark(size);\n printf(\"\\\"%d\\\",\\\"%lu\\\"\\n\", size, took);\n\t\t\tfflush(stdout);\n }\n }\n}", "meta": {"hexsha": "4589c1685d468d181e6e83a75a6229be0344400c", "size": 3034, "ext": "c", "lang": "C", "max_stars_repo_path": "perf/src/main/c/dgemmtest.c", "max_stars_repo_name": "debasish83/netlib-java", "max_stars_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-10T02:29:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T22:06:35.000Z", "max_issues_repo_path": "perf/src/main/c/dgemmtest.c", "max_issues_repo_name": "debasish83/netlib-java", "max_issues_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-01-01T10:34:19.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-24T14:20:38.000Z", "max_forks_repo_path": "perf/src/main/c/dgemmtest.c", "max_forks_repo_name": "debasish83/netlib-java", "max_forks_repo_head_hexsha": "38a78797d57339395bf10f3d65baeda8570d27e3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 154.0, "max_forks_repo_forks_event_min_datetime": "2015-01-03T22:48:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-07T04:58:57.000Z", "avg_line_length": 29.4563106796, "max_line_length": 187, "alphanum_fraction": 0.5945945946, "num_tokens": 1077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.28454901502425395}} {"text": "/*\n * author: Achim Gaedke\n * created: January 2002\n * file: pygsl/src/multiminmodule.c\n * $Id: multimin.c,v 1.6 2008/10/25 20:45:04 schnizer Exp $\n */\n#include \n\n#include \n#include \n#include \"multiminmodule_doc.h\"\n\n\nconst char * filename = __FILE__;\nPyObject *module = NULL;\n\n/* \n * I have two different types to minimize and I am too lazy to implement the same\n * twice. Therefore I use unions and add a flag to the minimizer for the type\n */\n\n/* The Callbacks */\ndouble \nPyGSL_multimin_function_f(const gsl_vector* x, void* params) \n{\n double result;\n int flag;\n int i;\n\n FUNC_MESS_BEGIN(); \n PyGSL_solver *min_o; \n min_o = (PyGSL_solver *) params;\n assert(PyGSL_solver_check(min_o)); \n for(i = 0; isize; i++){\n\t DEBUG_MESS(2, \"Got a x[%d] of %f\", i, gsl_vector_get(x, i));\n }\n assert(min_o->mstatic->n_cbs >= 1);\n flag = PyGSL_function_wrap_On_O(x, min_o->cbs[0], min_o->args, &result,\n\t\t\t\t NULL, x->size, __FUNCTION__);\n if (flag!= GSL_SUCCESS){\n\t result = gsl_nan();\n\t if(min_o->isset == 1) longjmp(min_o->buffer,flag);\t \n } \n DEBUG_MESS(2, \"Got a result of %f\", result);\n FUNC_MESS_END();\n return result;\n}\n\nvoid \nPyGSL_multimin_function_df(const gsl_vector* x, void* params, gsl_vector *df)\n{\n int flag, i;\n PyGSL_solver *min_o; \n min_o = (PyGSL_solver *) params;\n\n FUNC_MESS_BEGIN();\n assert(PyGSL_solver_check(min_o)); \n for(i = 0; isize; i++){\n\t DEBUG_MESS(2, \"Got a x[%d] of %f\", i, gsl_vector_get(x, i));\n }\n assert(min_o->mstatic->n_cbs >= 2);\n flag = PyGSL_function_wrap_Op_On(x, df, min_o->cbs[1], min_o->args,\n\t\t\t\t x->size, x->size, __FUNCTION__);\n for(i = 0; isize; i++){\n\t DEBUG_MESS(2, \"Got df x[%d] of %f\", i, gsl_vector_get(df, i));\n }\n if(flag!=GSL_SUCCESS){\n\t if(min_o->isset == 1) longjmp(min_o->buffer,flag);\t \n }\n FUNC_MESS_END();\n} \n\nvoid \nPyGSL_multimin_function_fdf(const gsl_vector* x, void* params, double *f, gsl_vector *df)\n{\n int flag, i;\n PyGSL_solver *min_o; \n\n FUNC_MESS_BEGIN();\n min_o = (PyGSL_solver *) params;\n assert(PyGSL_solver_check(min_o)); \n for(i = 0; isize; i++){\n\t DEBUG_MESS(2, \"Got a x[%d] of %f\", i, gsl_vector_get(x, i));\n }\n assert(min_o->mstatic->n_cbs >= 3);\n flag = PyGSL_function_wrap_On_O(x, min_o->cbs[2], min_o->args, f,\n\t\t\t\t df, x->size, __FUNCTION__);\n DEBUG_MESS(2, \"Got a result of %f\", *f);\n for(i = 0; isize; i++){\n\t DEBUG_MESS(2, \"Got df x[%d] of %f\", i, gsl_vector_get(df, i));\n }\n if (flag!= GSL_SUCCESS){\n\t *f = gsl_nan();\n\t if(min_o->isset == 1) longjmp(min_o->buffer,flag); \n } \n FUNC_MESS_END();\n return;\n}\n\n\nstatic PyObject* \nPyGSL_multimin_set_f(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) \n{\n\n PyObject* func = NULL, * args = Py_None, * x = NULL, * steps = NULL;\n PyArrayObject * xa = NULL, * stepsa = NULL;\n int n=0, flag=GSL_EFAILED;\n PyGSL_array_index_t stride_recalc;\n gsl_vector_view gsl_x;\n gsl_vector_view gsl_steps;\n gsl_multimin_function * c_sys = NULL;\n static const char *kwlist[] = {\"f\", \"x0\", \"args\", \"steps\", NULL};\n\n FUNC_MESS_BEGIN();\n assert(PyGSL_solver_check(self)); \n if (self->solver == NULL) {\n\t pygsl_error(\"Got a NULL Pointer of min.f\", filename, __LINE__ - 3, GSL_EFAULT);\n\t return NULL;\n }\n\n assert(pyargs);\n /* arguments PyFunction, Parameters, start Vector, step Vector */\n if (0==PyArg_ParseTupleAndKeywords(pyargs,kw,\"OOOO\", (char **)kwlist, &func,\n\t\t\t\t\t&x,&args,&steps))\n\t return NULL;\n\n if(!PyCallable_Check(func)){\n\t pygsl_error(\"First argument must be callable\", filename, __LINE__ - 3, GSL_EBADFUNC);\n\t return NULL;\t \n }\n n=self->problem_dimensions[0]; \n xa = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(4), &stride_recalc, NULL);\n if (xa == NULL){\n\t PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t goto fail;\n }\n\n gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]);\n stepsa = PyGSL_vector_check(steps, n, PyGSL_DARRAY_INPUT(5), &stride_recalc, NULL);\n if (stepsa == NULL){\n\t PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t goto fail;\n }\n gsl_steps = gsl_vector_view_array_with_stride((double *)(stepsa->data), stride_recalc, stepsa->dimensions[0]);\n\n if (self->c_sys != NULL) {\n\t /* free the previous function and args */\n\t c_sys = self->c_sys;\n } else {\n\t /* allocate function space */\n\t c_sys=calloc(1, sizeof(gsl_multimin_function));\n\t if (c_sys == NULL) {\n\t pygsl_error(\"Could not allocate the object for the minimizer function\", \n\t\t\t filename, __LINE__ - 3, GSL_ENOMEM);\n\t goto fail;\n\t }\n }\n DEBUG_MESS(3, \"Everything allocated args = %p\", args);\n /* add new function and parameters */\n\n if(PyGSL_solver_func_set(self, args, func, NULL, NULL) != GSL_SUCCESS)\n\t goto fail;\n \n /* initialize the function struct */\n c_sys->n=n;\n c_sys->f=PyGSL_multimin_function_f;\n c_sys->params=(void*)self;\n \n DEBUG_MESS(3, \"Setting jmp buffer isset = % d\", self->isset);\n if((flag = setjmp(self->buffer)) == 0){\n\t self->isset = 1;\n\t flag = gsl_multimin_fminimizer_set(self->solver,c_sys, &gsl_x.vector, &gsl_steps.vector);\n\t if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t goto fail;\n\t }\n } else {\n\t goto fail;\n }\n DEBUG_MESS(4, \"Set evaluated. flag = %d\", flag);\n self->c_sys = c_sys;\n Py_DECREF(xa);\n Py_DECREF(stepsa);\n self->set_called = 1;\n\n Py_INCREF(Py_None);\n self->isset = 0;\n FUNC_MESS_END();\n return Py_None;\n\n \n fail:\n FUNC_MESS(\"Fail\");\n PyGSL_ERROR_FLAG(flag);\n self->isset = 0;\n Py_XDECREF(xa);\n Py_XDECREF(stepsa);\n return NULL;\n \n}\n\nstatic PyObject* \nPyGSL_multimin_set_fdf(PyGSL_solver *self, PyObject *pyargs, PyObject *kw) \n{\n\n PyObject * f = NULL, * df = NULL, * fdf = NULL, * args = Py_None,\n\t * x = NULL;\n PyArrayObject * xa = NULL;\n int n=0, flag=GSL_EFAILED;\n PyGSL_array_index_t stride_recalc=-1;\n double step=0.01, tol=1e-4;\n gsl_vector_view gsl_x;\n gsl_multimin_function_fdf * c_sys;\n static const char *kwlist[] = {\"f\", \"df\", \"fdf\", \"x0\", \"args\", \"step\", \"tol\", NULL};\n\n FUNC_MESS_BEGIN();\n assert(PyGSL_solver_check(self)); \n if (self->solver == NULL) {\n\t pygsl_error(\"Got a NULL Pointer of min.fdf\", filename, __LINE__ - 3, GSL_EFAULT);\n\t return NULL;\n\t }\t \n\n /* arguments PyFunction, Parameters, start Vector, step Vector */\n if (0==PyArg_ParseTupleAndKeywords(pyargs, kw, \"OOOO|Odd\", (char **)kwlist, \n\t\t\t\t\t&f, &df, &fdf, &x, &args, &step, &tol))\n\t return NULL;\n\n n=self->problem_dimensions[0];\n xa = PyGSL_vector_check(x, n, PyGSL_DARRAY_INPUT(4), &stride_recalc, NULL);\n if (xa == NULL){\n\t PyGSL_add_traceback(module, filename, __FUNCTION__, __LINE__ - 1);\n\t goto fail;\n }\n gsl_x = gsl_vector_view_array_with_stride((double *)(xa->data), stride_recalc, xa->dimensions[0]);\n\n\n if (self->c_sys != NULL) {\n\t /* free the previous function and args */\n\t c_sys = self->c_sys;\n } else {\n\t /* allocate function space */\n\t c_sys=malloc(sizeof(gsl_multimin_function_fdf));\n\t if (c_sys==NULL) {\n\t pygsl_error(\"Could not allocate the object for the minimizer function\", \n\t\t\t filename, __LINE__ - 3, GSL_ENOMEM);\n\t goto fail;\n\t }\n }\n if(PyGSL_solver_func_set(self, args, f, df, fdf) != GSL_SUCCESS)\n\t goto fail;\n \n /* initialize the function struct */\n c_sys->n=n;\n c_sys->f =PyGSL_multimin_function_f;\n c_sys->df =PyGSL_multimin_function_df; \n c_sys->fdf=PyGSL_multimin_function_fdf;\n c_sys->params=(void*)self;\n\n if((flag = setjmp(self->buffer)) == 0){\n\t self->isset = 1;\t \n\t flag = gsl_multimin_fdfminimizer_set(self->solver, c_sys, &gsl_x.vector, step, tol);\n\t if(PyGSL_ERROR_FLAG(flag) != GSL_SUCCESS){\n\t goto fail;\n\t }\n }else{\n\t goto fail;\n }\n self->c_sys = c_sys;\n self->isset = 0;\n Py_DECREF(xa);\n self->set_called = 1;\n\n Py_INCREF(Py_None);\n FUNC_MESS_END();\n return Py_None;\n\n fail:\n PyGSL_ERROR_FLAG(flag);\n self->isset = 0;\n Py_XDECREF(xa);\n return NULL;\n \n}\n\nstatic PyObject* \nPyGSL_multimin_dx(PyGSL_solver *self, PyObject *args)\n{\n return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fdfminimizer_dx);\n}\n\nstatic PyObject* \nPyGSL_multimin_gradient(PyGSL_solver *self, PyObject *args)\n{\n return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fdfminimizer_gradient);\n}\n\nstatic PyObject* \nPyGSL_multimin_f_x(PyGSL_solver *self, PyObject *args) \n{\n return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fminimizer_x);\n}\n\nstatic PyObject* \nPyGSL_multimin_fdf_x(PyGSL_solver *self, PyObject *args) \n{\n return PyGSL_solver_ret_vec(self, args, (ret_vec)gsl_multimin_fdfminimizer_x);\n}\n\nstatic PyObject* \nPyGSL_multimin_f_minimum(PyGSL_solver *self, PyObject *args) \n{\n return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_multimin_fminimizer_minimum);\n}\n\nstatic PyObject* \nPyGSL_multimin_fdf_minimum(PyGSL_solver *self, PyObject *args) \n{\n return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_multimin_fdfminimizer_minimum);\n}\n\n\nstatic PyObject* \nPyGSL_multimin_f_size(PyGSL_solver *self, PyObject *args) \n{\n return PyGSL_solver_ret_double(self, args, (double_m_t) gsl_multimin_fminimizer_size);\n}\n\nstatic PyObject* \nPyGSL_multimin_test_size_method(PyGSL_solver *self, PyObject *args) \n{\n int flag=GSL_EFAILED;\n double epsabs;\n\n FUNC_MESS_BEGIN();\n\n if (0==PyArg_ParseTuple(args,\"d\", &epsabs))\n\t return NULL; \n flag = gsl_multimin_test_size(gsl_multimin_fminimizer_size(self->solver), epsabs);\n FUNC_MESS_END();\n return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n}\n\n\nstatic PyObject*\nPyGSL_multimin_test_gradient_method(PyGSL_solver * self, PyObject *args)\n{\n\n double epsabs;\n int flag;\n FUNC_MESS_BEGIN();\n\n assert(PyGSL_solver_check(self)); \n if (0==PyArg_ParseTuple(args,\"d\", &epsabs))\n\t return NULL; \n\n flag = gsl_multimin_test_gradient(gsl_multimin_fdfminimizer_gradient(self->solver), epsabs);\n FUNC_MESS_END();\n return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n \n}\n\n\n\nstatic PyMethodDef PyGSL_multimin_fmethods[] = { \n {\"x\", (PyCFunction)PyGSL_multimin_f_x, METH_NOARGS,(char *)multimin_x_doc, }, \n {\"minimum\", (PyCFunction)PyGSL_multimin_f_minimum,METH_NOARGS,(char *)multimin_minimum_doc,}, \n {\"set\", (PyCFunction)PyGSL_multimin_set_f, METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_f_doc }, \n {\"size\", (PyCFunction)PyGSL_multimin_f_size, METH_NOARGS, (char *)multimin_size_doc },\n {\"test_size\",(PyCFunction)PyGSL_multimin_test_size_method,METH_VARARGS, (char *)multimin_test_size_doc},\n {NULL, NULL, 0, NULL} /* sentinel */\n};\n\nstatic PyMethodDef PyGSL_multimin_fdfmethods[] = {\n {\"x\", (PyCFunction)PyGSL_multimin_fdf_x, METH_NOARGS,(char *)multimin_x_doc, }, \n {\"minimum\", (PyCFunction)PyGSL_multimin_fdf_minimum,METH_NOARGS,(char *)multimin_minimum_doc,}, \n {\"set\", (PyCFunction)PyGSL_multimin_set_fdf, METH_VARARGS|METH_KEYWORDS, (char *)multimin_set_fdf_doc },\n {\"dx\", (PyCFunction)PyGSL_multimin_dx, METH_NOARGS, (char *)multimin_dx_doc }, \n {\"gradient\", (PyCFunction)PyGSL_multimin_gradient, METH_NOARGS, (char *)multimin_gradient_doc }, \n {\"test_gradient\",(PyCFunction)PyGSL_multimin_test_gradient_method,METH_VARARGS, (char *)multimin_test_gradient_doc}, \n {NULL, NULL, 0, NULL} /* sentinel */\n};\n\nconst struct _GSLMethods \nmultimin_f = { (void_m_t) gsl_multimin_fminimizer_free, \n\t\t/* gsl_multimin_fminimizer_restart */ (void_m_t) NULL,\n\t\t (name_m_t) gsl_multimin_fminimizer_name, \n\t\t (int_m_t) gsl_multimin_fminimizer_iterate};\n\nconst struct _GSLMethods\nmultimin_fdf = {(void_m_t) gsl_multimin_fdfminimizer_free, \n\t\t(void_m_t) gsl_multimin_fdfminimizer_restart,\n\t\t(name_m_t) gsl_multimin_fdfminimizer_name, \n\t\t(int_m_t) gsl_multimin_fdfminimizer_iterate};\n\nstatic const char multimin_f_type_name[] = \"F-MultiMinimizer\";\nstatic const char multimin_fdf_type_name[] = \"FdF-MultiMinimizer\";\n\nconst struct _SolverStatic \nmultimin_solver_f = {{(void_m_t) gsl_multimin_fminimizer_free, \n\t\t\t(void_m_t) NULL,\n\t\t\t(name_m_t) gsl_multimin_fminimizer_name, \n\t\t\t(int_m_t) gsl_multimin_fminimizer_iterate}, \n\t\t 1, PyGSL_multimin_fmethods, multimin_f_type_name},\nmultimin_solver_fdf = {{(void_m_t) gsl_multimin_fdfminimizer_free, \n\t\t\t(void_m_t) gsl_multimin_fdfminimizer_restart,\n\t\t\t(name_m_t) gsl_multimin_fdfminimizer_name, \n\t\t\t(int_m_t) gsl_multimin_fdfminimizer_iterate},\n\t\t 3, PyGSL_multimin_fdfmethods, multimin_fdf_type_name};\n\nstatic PyObject* \nPyGSL_multimin_f_init(PyObject *self, PyObject *args, \n\t\t const gsl_multimin_fminimizer_type * type) \n{\n\n PyObject *tmp=NULL;\n solver_alloc_struct s = {type, (void_an_t) gsl_multimin_fminimizer_alloc,\n\t\t\t &multimin_solver_f};\n FUNC_MESS_BEGIN(); \n tmp = PyGSL_solver_dn_init(self, args, &s, 1);\n FUNC_MESS_END(); \n return tmp;\n}\n\nstatic PyObject* \nPyGSL_multimin_fdf_init(PyObject *self, PyObject *args, \n\t\t const gsl_multimin_fdfminimizer_type * type) \n{\n\n PyObject *tmp=NULL;\n solver_alloc_struct s = {type, (void_an_t) gsl_multimin_fdfminimizer_alloc,\n\t\t\t &multimin_solver_fdf};\n FUNC_MESS_BEGIN(); \n tmp = PyGSL_solver_dn_init(self, args, &s, 1);\n FUNC_MESS_END(); \n return tmp;\n}\n\n\n#define AMINIMIZER_F(name) \\\nstatic PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\\\n{ \\\n PyObject *tmp = NULL; \\\n FUNC_MESS_BEGIN(); \\\n tmp = PyGSL_multimin_f_init(self, args, gsl_multimin_fminimizer_ ## name); \\\n if (tmp == NULL){ \\\n\t PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \\\n } \\\n FUNC_MESS_END(); \\\n return tmp; \\\n}\n\n#define AMINIMIZER_FDF(name) \\\nstatic PyObject* PyGSL_multimin_init_ ## name (PyObject *self, PyObject *args)\\\n{ \\\n PyObject *tmp = NULL; \\\n FUNC_MESS_BEGIN(); \\\n tmp = PyGSL_multimin_fdf_init(self, args, gsl_multimin_fdfminimizer_ ## name); \\\n if (tmp == NULL){ \\\n\t PyGSL_add_traceback(module, __FILE__, __FUNCTION__, __LINE__); \\\n } \\\n FUNC_MESS_END(); \\\n return tmp; \\\n}\n\nAMINIMIZER_F(nmsimplex)\nAMINIMIZER_FDF(steepest_descent)\nAMINIMIZER_FDF(vector_bfgs)\nAMINIMIZER_FDF(conjugate_pr)\nAMINIMIZER_FDF(conjugate_fr)\n\nstatic PyObject*\nPyGSL_multimin_test_size(PyObject * self, PyObject *args)\n{\n double size, epsabs;\n int flag = GSL_EFAILED;\n FUNC_MESS_BEGIN();\n if (0==PyArg_ParseTuple(args,\"dd\", &size, &epsabs))\n\t return NULL; \n flag = gsl_multimin_test_size(size, epsabs);\n FUNC_MESS_END();\n return PyGSL_ERROR_FLAG_TO_PYINT(flag);\n \n}\n\nstatic PyObject*\nPyGSL_multimin_test_gradient(PyObject * self, PyObject *args)\n{\n return PyGSL_solver_vd_i (self, args, gsl_multimin_test_gradient); \n}\n\n\nstatic PyMethodDef mMethods[] = {\n /* solvers */\n {\"nmsimplex\", PyGSL_multimin_init_nmsimplex, METH_VARARGS, (char *)nmsimplex_doc },\n {\"steepest_descent\", PyGSL_multimin_init_steepest_descent, METH_VARARGS, (char *)steepest_descent_doc},\n {\"vector_bfgs\", PyGSL_multimin_init_vector_bfgs, METH_VARARGS, (char *)vector_bfgs_doc },\n {\"conjugate_pr\", PyGSL_multimin_init_conjugate_pr, METH_VARARGS, (char *)conjugate_pr_doc },\n {\"conjugate_fr\", PyGSL_multimin_init_conjugate_fr, METH_VARARGS, (char *)conjugate_fr_doc },\n /* multimin funcs */\n {\"test_size\", PyGSL_multimin_test_size, METH_VARARGS, (char *)test_size_doc },\n {\"test_gradient\", PyGSL_multimin_test_gradient, METH_VARARGS, (char *)test_gradient_doc },\n {NULL, NULL, 0, NULL}\n};\n\nvoid\ninitmultimin(void)\n{\n PyObject* m, *dict, *item;\n FUNC_MESS_BEGIN();\n\n m=Py_InitModule(\"multimin\", mMethods);\n module = m;\n assert(m);\n dict = PyModule_GetDict(m);\n if(!dict)\n\t goto fail;\n\n init_pygsl()\n import_pygsl_solver();\n assert(PyGSL_API);\n\n\n if (!(item = PyString_FromString((char*)PyGSL_multimin_module_doc))){\n\t PyErr_SetString(PyExc_ImportError, \n\t\t\t \"I could not generate module doc string!\");\n\t goto fail;\n }\n if (PyDict_SetItemString(dict, \"__doc__\", item) != 0){\n\t PyErr_SetString(PyExc_ImportError, \n\t\t\t \"I could not init doc string!\");\n\t goto fail;\n }\n \n FUNC_MESS_END();\n\n fail:\n FUNC_MESS(\"FAIL\");\n return;\n}\n", "meta": {"hexsha": "c6694fc7752b83bc770296a17cd587e43da933a6", "size": 17914, "ext": "c", "lang": "C", "max_stars_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multimin.c", "max_stars_repo_name": "juhnowski/FishingRod", "max_stars_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multimin.c", "max_issues_repo_name": "juhnowski/FishingRod", "max_issues_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "production/pygsl-0.9.5/testing/src/solvers/multimin.c", "max_forks_repo_name": "juhnowski/FishingRod", "max_forks_repo_head_hexsha": "457e7afb5cab424296dff95e1acf10ebf70d32a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-02T06:18:07.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T06:18:07.000Z", "avg_line_length": 33.2356215213, "max_line_length": 135, "alphanum_fraction": 0.6235346656, "num_tokens": 5062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5234203340678567, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.28414568103132615}} {"text": "#include \n#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 \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_switch, 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]=\"\",file_end[200]=\"\" ;\n char buf[10]=\"\";\n int i=0, j=0, k=0, elem=0, elem_factor=0;\n int phi_min_index=0, phi_max_index=0, r_min_index=0, r_max_index=0, theta_min_index=0, theta_max_index=0; //all_index_buffer contains phi_min, phi_max, theta_min, theta_max, r_min, r_max indexes to get from grid files\n int r_index=0, theta_index=0, phi_index=0, hydro_index=0, all_index_buffer=0, adjusted_remapping_index=0, dr_index=0;\n int *remapping_indexes=NULL;\n float buffer=0;\n float *dens_unprc=NULL;\n float *vel_r_unprc=NULL;\n float *vel_theta_unprc=NULL;\n float *vel_phi_unprc=NULL;\n float *pres_unprc=NULL;\n double ph_rmin=0, ph_rmax=0;\n double r_in=1e10, r_ref=2e13;\n double *r_edge=NULL;\n double *dr=NULL;\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_switch==0)\n {\n ph_rmin=min_r;\n ph_rmax=max_r;\n }\n \n snprintf(file_end,sizeof(file_end),\"%s\",\"small.data\" );\n \n //density\n snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"u0\", 1,\"-\" );\n modifyFlashName(file_num, hydrofile, frame,1);\n \n fprintf(fPtr,\">> Opening file %s\\n\", file_num);\n fflush(fPtr);\n \n snprintf(full_file, sizeof(full_file), \"%s%s\", file_num, file_end);\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(&phi_min_index, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid\n fread(&phi_max_index, sizeof(int)*1, 1,hydroPtr);\n fread(&theta_min_index, sizeof(int)*1, 1,hydroPtr);\n fread(&theta_max_index, sizeof(int)*1, 1,hydroPtr);\n fread(&r_min_index, sizeof(int)*1, 1,hydroPtr);\n fread(&r_max_index, sizeof(int)*1, 1,hydroPtr);\n fclose(hydroPtr);\n \n //fortran indexing starts @ 1, but C starts @ 0\n r_min_index--;\n r_max_index--;\n theta_min_index--;\n theta_max_index--;\n phi_min_index--;\n phi_max_index--;\n \n //number of elements defined by this now\n elem=(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index)*(phi_max_index+1-phi_min_index); //add 1 b/c max_index is 1 less than max number of elements in file\n /*\n fprintf(fPtr,\"Elem %d\\n\", elem);\n fprintf(fPtr,\"Limits %d, %d, %d, %d, %d, %d\\n\", phi_min_index, phi_max_index, theta_min_index, theta_max_index, r_min_index, r_max_index); \n fflush(fPtr);\n */\n //now with number of elements allocate data, remember last element is some garbage that only fortran uses\n dens_unprc=malloc(elem*sizeof(float));\n vel_r_unprc=malloc(elem*sizeof(float));\n vel_theta_unprc=malloc(elem*sizeof(float));\n pres_unprc=malloc(elem*sizeof(float));\n vel_phi_unprc=malloc(elem*sizeof(float));\n \n hydroPtr=fopen(full_file, \"rb\");\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran \n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n fread(dens_unprc, sizeof(float),elem, 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, file_end);\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(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n fread(vel_r_unprc, sizeof(float),elem, 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, file_end);\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(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n fread(vel_theta_unprc, sizeof(float),elem, 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, file_end);\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(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n fread(vel_phi_unprc, sizeof(float),elem, 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, file_end);\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(&all_index_buffer, sizeof(int)*1, 1,hydroPtr); //min and max indexes for the grid, dont need anymore so just save to dummy variable\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&all_index_buffer, sizeof(int)*1, 1,hydroPtr);\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n fread(&buffer, sizeof(float), 1,hydroPtr); //random stuff about the file from fortran\n \n fread(pres_unprc, sizeof(float),elem, hydroPtr);\n fclose(hydroPtr);\n /*\n for (i=PHI_DIM-1;i0\n elem_factor=0;\n elem=0;\n while (elem==0)\n {\n elem=0;\n elem_factor++;\n for (i=0;i<(phi_max_index+1-phi_min_index);i++)\n {\n for (j=0;j<(theta_max_index+1-theta_min_index);j++)\n {\n for (k=0;k<(r_max_index+1-r_min_index);k++)\n {\n r_index=r_min_index+k;\n //if I have photons do selection differently than if injecting photons\n if (ph_inj_switch==0)\n {\n //printf(\"R's:%d, %e\\n\", k, *(r_unprc+r_index));\n //if calling this function when propagating photons, choose blocks based on where the photons are\n if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) ))\n {\n // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )\n elem++;\n }\n }\n else\n {\n //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient \n if (((r_inj - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + elem_factor*C_LIGHT/fps) ))\n {\n // *(pres_unprc+(i*R_DIM*THETA_DIM + j*R_DIM + k )\n elem++;\n }\n \n }\n \n }\n }\n }\n }\n \n fprintf(fPtr,\"Number of post restricted Elems: %d %e\\n\", elem, r_inj);\n //fprintf(fPtr,\"Ph_min, Ph_max: %e, %e\\n With c: min: %e max: %e \\n\", ph_rmin, ph_rmax, (ph_rmin - 2*C_LIGHT/fps), (ph_rmax + 2*C_LIGHT/fps));\n fflush(fPtr);\n \n //allocate space for new set of data\n (*pres)=malloc (elem * sizeof (double ));\n (*velx)=malloc (elem * sizeof (double ));\n (*vely)=malloc (elem * sizeof (double ));\n (*velz)=malloc (elem * sizeof (double ));\n (*dens)=malloc (elem * sizeof (double ));\n (*x)=malloc (elem * sizeof (double ));\n (*y)=malloc (elem * sizeof (double ));\n (*z)=malloc (elem * sizeof (double ));\n (*r)=malloc (elem * sizeof (double ));\n (*theta)=malloc (elem * sizeof (double ));\n (*phi)=malloc (elem * sizeof (double ));\n (*gamma)=malloc (elem * sizeof (double ));\n (*dens_lab)=malloc (elem * sizeof (double ));\n (*szx)=malloc (elem * sizeof (double )); //theta and phi resolution \n (*szy)=malloc (elem * sizeof (double )); //r resolution\n (*temp)=malloc (elem * sizeof (double ));\n \n //limit number of array elements\n elem=0;\n for (i=0;i<(phi_max_index+1-phi_min_index);i++)\n {\n for (j=0;j<(theta_max_index+1-theta_min_index);j++)\n {\n for (k=0;k<(r_max_index+1-r_min_index);k++)\n {\n r_index=r_min_index+k; //look at indexes of r that are included in small hydro file\n theta_index=theta_min_index+j;\n phi_index=phi_min_index+i;\n dr_index=adjusted_remapping_index+k;\n hydro_index=(i*(r_max_index+1-r_min_index)*(theta_max_index+1-theta_min_index) + j*(r_max_index+1-r_min_index) + k );\n \n //if I have photons do selection differently than if injecting photons\n if (ph_inj_switch==0)\n {\n //if calling this function when propagating photons, choose blocks based on where the photons are\n if (((ph_rmin - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (ph_rmax + elem_factor*C_LIGHT/fps) ))\n {\n (*pres)[elem] = *(pres_unprc+hydro_index);\n (*dens)[elem] = *(dens_unprc+hydro_index);\n (*temp)[elem] = pow(3*(*(pres_unprc+hydro_index))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n \n (*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1);\n (*dens_lab)[elem] = (*(dens_unprc+hydro_index))*pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1);\n (*r)[elem] = *(r_unprc+r_index);\n (*theta)[elem] = *(theta_unprc+theta_index);\n (*phi)[elem] = *(phi_unprc+phi_index);\n (*x)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index));\n (*y)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index));\n (*z)[elem] = (*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));\n (*szx)[elem] = *(dr+dr_index);\n (*szy)[elem] = M_PI/560;\n (*velx)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) - ((*(vel_phi_unprc+hydro_index))*sin(*(phi_unprc+phi_index)));\n (*vely)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_phi_unprc+hydro_index))*cos(*(phi_unprc+phi_index)));\n (*velz)[elem]=((*(vel_r_unprc+hydro_index))*cos(*(theta_unprc+theta_index))) - ((*(vel_theta_unprc+hydro_index))*sin(*(theta_unprc+theta_index)));\n\n elem++;\n \n }\n }\n else\n {\n //if calling this function to inject photons choose blocks based on injection parameters, r_inj, which is sufficient \n if (((r_inj - elem_factor*C_LIGHT/fps)<(*(r_unprc+r_index))) && (*(r_unprc+r_index) < (r_inj + elem_factor*C_LIGHT/fps) ))\n {\n (*pres)[elem] = *(pres_unprc+hydro_index);\n (*dens)[elem] = *(dens_unprc+hydro_index);\n (*temp)[elem] = pow(3*(*(pres_unprc+hydro_index))*pow(C_LIGHT,2.0)/(A_RAD) ,1.0/4.0);\n (*gamma)[elem] = pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1);\n (*dens_lab)[elem] = (*(dens_unprc+hydro_index))*pow(pow(1.0-(pow(*(vel_r_unprc+hydro_index),2)+ pow(*(vel_theta_unprc+hydro_index),2)+pow(*(vel_phi_unprc+hydro_index),2)),0.5),-1);\n (*r)[elem] = *(r_unprc+r_index);\n (*theta)[elem] = *(theta_unprc+theta_index);\n (*phi)[elem] = *(phi_unprc+phi_index);\n (*x)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index));\n (*y)[elem] = (*(r_unprc+r_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index));\n (*z)[elem] = (*(r_unprc+r_index))*cos(*(theta_unprc+theta_index));\n (*szx)[elem] = *(dr+dr_index);\n (*szy)[elem] = M_PI/560;\n (*velx)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*cos(*(phi_unprc+phi_index))) - ((*(vel_phi_unprc+hydro_index))*sin(*(phi_unprc+phi_index)));\n (*vely)[elem]=((*(vel_r_unprc+hydro_index))*sin(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_theta_unprc+hydro_index))*cos(*(theta_unprc+theta_index))*sin(*(phi_unprc+phi_index))) + ((*(vel_phi_unprc+hydro_index))*cos(*(phi_unprc+phi_index)));\n (*velz)[elem]=((*(vel_r_unprc+hydro_index))*cos(*(theta_unprc+theta_index))) - ((*(vel_theta_unprc+hydro_index))*sin(*(theta_unprc+theta_index)));\n\n elem++;\n }\n \n }\n \n }\n }\n }\n \n *number=elem;\n \n free(pres_unprc); free(dens_unprc); free(r_unprc); free(theta_unprc); free(phi_unprc);free(dr);free(vel_r_unprc); free(vel_theta_unprc); free(vel_phi_unprc); \n \n}\n\n\nvoid photonInjection3D( struct photon **ph, int *ph_num, double r_inj, double ph_weight, int min_photons, int max_photons, char spect, int array_length, double fps, double theta_min, double theta_max,\\\n double *x, double *y, double *z, double *szx, double *szy, double *r, double *theta, double *phi, double *temps, double *vx, double *vy, double *vz, gsl_rng * rand, FILE *fPtr)\n{\n int i=0, block_cnt=0, *ph_dens=NULL, ph_tot=0, j=0,k=0;\n double ph_dens_calc=0.0, fr_dum=0.0, y_dum=0.0, yfr_dum=0.0, fr_max=0, bb_norm=0, position_phi, ph_weight_adjusted, theta_prime=0;\n double com_v_phi, com_v_theta, *p_comv=NULL, *boost=NULL; //comoving phi, theta, comoving 4 momentum for a photon, and boost for photon(to go to lab frame)\n double *l_boost=NULL; //pointer to hold array of lorentz boost, to lab frame, values\n float num_dens_coeff;\n \n if (spect=='w') //from MCRAT paper, w for wien spectrum \n {\n num_dens_coeff=8.44;\n //printf(\"in wien spectrum\\n\");\n }\n else\n {\n num_dens_coeff=20.29; //this is for black body spectrum\n //printf(\"in BB spectrum\");\n }\n \n //find how many blocks are near the injection radius within the angles defined in mc.par, get temperatures and calculate number of photons to allocate memory for \n //and then rcord which blocks have to have \"x\" amount of photons injected there\n printf(\"%e, %e\\n\",*(phi+i), theta_max);\n for(i=0;i= 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(*(szy+i),2.0)*(*(szx+i)) /(ph_weight_adjusted))*pow(pow(1.0-(pow(*(vx+i),2)+pow(*(vy+i),2)+pow(*(vz+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', fPtr);\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\nvoid phMinMax(struct photon *ph, int ph_num, double *min, double *max, double *min_theta, double *max_theta, FILE *fPtr)\n{\n double temp_r_max=0, temp_r_min=DBL_MAX, temp_theta_max=0, temp_theta_min=DBL_MAX;\n int i=0, num_thread=omp_get_num_threads();\n double ph_r=0, ph_theta=0;\n \n#pragma omp parallel for num_threads(num_thread) firstprivate(ph_r, ph_theta) reduction(min:temp_r_min) reduction(max:temp_r_max) reduction(min:temp_theta_min) reduction(max:temp_theta_max)\n for (i=0;iweight != 0)\n {\n ph_r=pow(pow( ((ph+i)->r0), 2.0) + pow(((ph+i)->r1),2.0 ) + pow(((ph+i)->r2) , 2.0),0.5);\n ph_theta=acos(((ph+i)->r2) /ph_r); //this is the photons theta psition in the FLASH grid, gives in radians\n if (ph_r > temp_r_max )\n {\n temp_r_max=ph_r;\n //fprintf(fPtr, \"The new max is: %e from photon %d with x: %e y: %e z: %e\\n\", temp_r_max, i, ((ph+i)->r0), (ph+i)->r1, (ph+i)->r2);\n }\n \n //if ((i==0) || (ph_rr0), (ph+i)->r1, (ph+i)->r2);\n }\n \n if (ph_theta > temp_theta_max )\n {\n temp_theta_max=ph_theta;\n //fprintf(fPtr, \"The new max is: %e from photon %d with x: %e y: %e z: %e\\n\", temp_r_max, i, ((ph+i)->r0), (ph+i)->r1, (ph+i)->r2);\n }\n \n //if ((i==0) || (ph_rr0), (ph+i)->r1, (ph+i)->r2);\n }\n }\n }\n \n *max=temp_r_max;\n *min=temp_r_min;\n *max_theta=temp_theta_max;\n *min_theta=temp_theta_min;\n}\n\nint *getIndexesForRadialRemapping(char hydro_prefix[200])\n{\n FILE *hydroPtr=NULL;\n char hydrofile[200]=\"\";\n char buf[10]=\"\";\n int i=0, j=0;\n int *remapping_start_index=malloc(sizeof(int)*7); //what index out of total range of r does each remapping begin at\n double r_in=1e10, r_ref=2e13;\n double *r_unprc_0=malloc(sizeof(double)*R_DIM), *r_unprc_1=malloc(sizeof(double)*R_DIM), *r_unprc_2=malloc(sizeof(double)*R_DIM), *r_unprc_3=malloc(sizeof(double)*R_DIM);\n double *r_unprc_4=malloc(sizeof(double)*R_DIM), *r_unprc_5=malloc(sizeof(double)*R_DIM), *r_unprc_6=malloc(sizeof(double)*R_DIM);\n double *r_edge=NULL, *dr=NULL, *rPtr=NULL;\n \n for (i=0;i<7;i++)\n {\n snprintf(hydrofile,sizeof(hydrofile),\"%s%s%d%s\",hydro_prefix,\"grid0\", i,\"-x1.data\" );\n \n hydroPtr=fopen(hydrofile, \"r\");\n \n j=0;\n while (j\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 \"waveform.h\"\n#include \"EOBNRv2HMROMstruct.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/**************** Prototypes **********************/\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 */\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//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//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// int LISASimFDResponseTDI1Chan(\n// struct tagListmodesCAmpPhaseFrequencySeries **list, /* Input: list of modes in Frequency-domain amplitude and phase form as produced by the ROM */\n// struct tagListmodesCAmpPhaseFrequencySeries **listTDI, /* Output: list of contribution of each mode in Frequency-domain amplitude and phase form, in the TDI channel 1 */\n// const double tRef, /* Time at coalescence */\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 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\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _LISAFDRESPONSE_H */\n", "meta": {"hexsha": "0a3a2e84833ed4f67e76dcccd676499f599b4d98", "size": 7630, "ext": "h", "lang": "C", "max_stars_repo_path": "LISAsim/LISAFDresponse.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/LISAFDresponse.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/LISAFDresponse.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": 66.9298245614, "max_line_length": 301, "alphanum_fraction": 0.6197903014, "num_tokens": 1556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.2841025422335752}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n#include \"domain.h\"\n\n#include \n\n\n\n\nstatic struct peano_hilbert_data\n{\n peanokey key;\n int index;\n}\n *mp;\n\nstatic int *Id;\n\nvoid peano_hilbert_order(void)\n{\n int i;\n\n if(ThisTask == 0)\n printf(\"begin Peano-Hilbert order...\\n\");\n\n if(N_gas)\n {\n mp = (struct peano_hilbert_data *) mymalloc(sizeof(struct peano_hilbert_data) * N_gas);\n Id = (int *) mymalloc(sizeof(int) * N_gas);\n\n for(i = 0; i < N_gas; i++)\n\t{\n\t mp[i].index = i;\n\t mp[i].key = Key[i];\n\t}\n\n#ifdef MYSORT\n mysort_peano(mp, N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);\n#else\n qsort(mp, N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);\n#endif\n\n for(i = 0; i < N_gas; i++)\n\tId[mp[i].index] = i;\n\n reorder_gas();\n\n myfree(Id);\n myfree(mp);\n }\n\n\n if(NumPart - N_gas > 0)\n {\n mp = (struct peano_hilbert_data *) mymalloc(sizeof(struct peano_hilbert_data) * (NumPart - N_gas));\n mp -= (N_gas);\n\n Id = (int *) mymalloc(sizeof(int) * (NumPart - N_gas));\n Id -= (N_gas);\n\n for(i = N_gas; i < NumPart; i++)\n\t{\n\t mp[i].index = i;\n\t mp[i].key = Key[i];\n\t}\n\n#ifdef MYSORT\n mysort_peano(mp + N_gas, NumPart - N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);\n#else\n qsort(mp + N_gas, NumPart - N_gas, sizeof(struct peano_hilbert_data), peano_compare_key);\n#endif\n\n for(i = N_gas; i < NumPart; i++)\n\tId[mp[i].index] = i;\n\n reorder_particles();\n\n Id += N_gas;\n myfree(Id);\n mp += N_gas;\n myfree(mp);\n }\n\n if(ThisTask == 0)\n printf(\"Peano-Hilbert done.\\n\");\n}\n\n\nint peano_compare_key(const void *a, const void *b)\n{\n if(((struct peano_hilbert_data *) a)->key < (((struct peano_hilbert_data *) b)->key))\n return -1;\n\n if(((struct peano_hilbert_data *) a)->key > (((struct peano_hilbert_data *) b)->key))\n return +1;\n\n return 0;\n}\n\nvoid reorder_gas(void)\n{\n int i;\n struct particle_data Psave, Psource;\n struct sph_particle_data SphPsave, SphPsource;\n int idsource, idsave, dest;\n\n for(i = 0; i < N_gas; i++)\n {\n if(Id[i] != i)\n\t{\n\t Psource = P[i];\n\t SphPsource = SphP[i];\n\n\t idsource = Id[i];\n\t dest = Id[i];\n\n\t do\n\t {\n\t Psave = P[dest];\n\t SphPsave = SphP[dest];\n\t idsave = Id[dest];\n\n\t P[dest] = Psource;\n\t SphP[dest] = SphPsource;\n\t Id[dest] = idsource;\n\n\t if(dest == i)\n\t\tbreak;\n\n\t Psource = Psave;\n\t SphPsource = SphPsave;\n\t idsource = idsave;\n\n\t dest = idsource;\n\t }\n\t while(1);\n\t}\n }\n}\n\n\nvoid reorder_particles(void)\n{\n int i;\n struct particle_data Psave, Psource;\n int idsource, idsave, dest;\n\n for(i = N_gas; i < NumPart; i++)\n {\n if(Id[i] != i)\n\t{\n\t Psource = P[i];\n\t idsource = Id[i];\n\n\t dest = Id[i];\n\n\t do\n\t {\n\t Psave = P[dest];\n\t idsave = Id[dest];\n\n\t P[dest] = Psource;\n\t Id[dest] = idsource;\n#ifdef LT_STELLAREVOLUTION\n\t if(P[dest].Type == 4)\n\t\tMetP[P[dest].MetID].PID = dest;\n#endif\n\t if(dest == i)\n\t\tbreak;\n\n\t Psource = Psave;\n\t idsource = idsave;\n\n\t dest = idsource;\n\t }\n\t while(1);\n\t}\n }\n}\n\n\n\n\n\n/* The following rewrite of the original function\n * peano_hilbert_key_old() has been written by MARTIN REINECKE. \n * It is about a factor 2.3 - 2.5 faster than Volker's old routine!\n */\nconst unsigned char rottable3[48][8] = {\n {36, 28, 25, 27, 10, 10, 25, 27},\n {29, 11, 24, 24, 37, 11, 26, 26},\n {8, 8, 25, 27, 30, 38, 25, 27},\n {9, 39, 24, 24, 9, 31, 26, 26},\n {40, 24, 44, 32, 40, 6, 44, 6},\n {25, 7, 33, 7, 41, 41, 45, 45},\n {4, 42, 4, 46, 26, 42, 34, 46},\n {43, 43, 47, 47, 5, 27, 5, 35},\n {33, 35, 36, 28, 33, 35, 2, 2},\n {32, 32, 29, 3, 34, 34, 37, 3},\n {33, 35, 0, 0, 33, 35, 30, 38},\n {32, 32, 1, 39, 34, 34, 1, 31},\n {24, 42, 32, 46, 14, 42, 14, 46},\n {43, 43, 47, 47, 25, 15, 33, 15},\n {40, 12, 44, 12, 40, 26, 44, 34},\n {13, 27, 13, 35, 41, 41, 45, 45},\n {28, 41, 28, 22, 38, 43, 38, 22},\n {42, 40, 23, 23, 29, 39, 29, 39},\n {41, 36, 20, 36, 43, 30, 20, 30},\n {37, 31, 37, 31, 42, 40, 21, 21},\n {28, 18, 28, 45, 38, 18, 38, 47},\n {19, 19, 46, 44, 29, 39, 29, 39},\n {16, 36, 45, 36, 16, 30, 47, 30},\n {37, 31, 37, 31, 17, 17, 46, 44},\n {12, 4, 1, 3, 34, 34, 1, 3},\n {5, 35, 0, 0, 13, 35, 2, 2},\n {32, 32, 1, 3, 6, 14, 1, 3},\n {33, 15, 0, 0, 33, 7, 2, 2},\n {16, 0, 20, 8, 16, 30, 20, 30},\n {1, 31, 9, 31, 17, 17, 21, 21},\n {28, 18, 28, 22, 2, 18, 10, 22},\n {19, 19, 23, 23, 29, 3, 29, 11},\n {9, 11, 12, 4, 9, 11, 26, 26},\n {8, 8, 5, 27, 10, 10, 13, 27},\n {9, 11, 24, 24, 9, 11, 6, 14},\n {8, 8, 25, 15, 10, 10, 25, 7},\n {0, 18, 8, 22, 38, 18, 38, 22},\n {19, 19, 23, 23, 1, 39, 9, 39},\n {16, 36, 20, 36, 16, 2, 20, 10},\n {37, 3, 37, 11, 17, 17, 21, 21},\n {4, 17, 4, 46, 14, 19, 14, 46},\n {18, 16, 47, 47, 5, 15, 5, 15},\n {17, 12, 44, 12, 19, 6, 44, 6},\n {13, 7, 13, 7, 18, 16, 45, 45},\n {4, 42, 4, 21, 14, 42, 14, 23},\n {43, 43, 22, 20, 5, 15, 5, 15},\n {40, 12, 21, 12, 40, 6, 23, 6},\n {13, 7, 13, 7, 41, 41, 22, 20}\n};\n\nconst unsigned char subpix3[48][8] = {\n {0, 7, 1, 6, 3, 4, 2, 5},\n {7, 4, 6, 5, 0, 3, 1, 2},\n {4, 3, 5, 2, 7, 0, 6, 1},\n {3, 0, 2, 1, 4, 7, 5, 6},\n {1, 0, 6, 7, 2, 3, 5, 4},\n {0, 3, 7, 4, 1, 2, 6, 5},\n {3, 2, 4, 5, 0, 1, 7, 6},\n {2, 1, 5, 6, 3, 0, 4, 7},\n {6, 1, 7, 0, 5, 2, 4, 3},\n {1, 2, 0, 3, 6, 5, 7, 4},\n {2, 5, 3, 4, 1, 6, 0, 7},\n {5, 6, 4, 7, 2, 1, 3, 0},\n {7, 6, 0, 1, 4, 5, 3, 2},\n {6, 5, 1, 2, 7, 4, 0, 3},\n {5, 4, 2, 3, 6, 7, 1, 0},\n {4, 7, 3, 0, 5, 6, 2, 1},\n {6, 7, 5, 4, 1, 0, 2, 3},\n {7, 0, 4, 3, 6, 1, 5, 2},\n {0, 1, 3, 2, 7, 6, 4, 5},\n {1, 6, 2, 5, 0, 7, 3, 4},\n {2, 3, 1, 0, 5, 4, 6, 7},\n {3, 4, 0, 7, 2, 5, 1, 6},\n {4, 5, 7, 6, 3, 2, 0, 1},\n {5, 2, 6, 1, 4, 3, 7, 0},\n {7, 0, 6, 1, 4, 3, 5, 2},\n {0, 3, 1, 2, 7, 4, 6, 5},\n {3, 4, 2, 5, 0, 7, 1, 6},\n {4, 7, 5, 6, 3, 0, 2, 1},\n {6, 7, 1, 0, 5, 4, 2, 3},\n {7, 4, 0, 3, 6, 5, 1, 2},\n {4, 5, 3, 2, 7, 6, 0, 1},\n {5, 6, 2, 1, 4, 7, 3, 0},\n {1, 6, 0, 7, 2, 5, 3, 4},\n {6, 5, 7, 4, 1, 2, 0, 3},\n {5, 2, 4, 3, 6, 1, 7, 0},\n {2, 1, 3, 0, 5, 6, 4, 7},\n {0, 1, 7, 6, 3, 2, 4, 5},\n {1, 2, 6, 5, 0, 3, 7, 4},\n {2, 3, 5, 4, 1, 0, 6, 7},\n {3, 0, 4, 7, 2, 1, 5, 6},\n {1, 0, 2, 3, 6, 7, 5, 4},\n {0, 7, 3, 4, 1, 6, 2, 5},\n {7, 6, 4, 5, 0, 1, 3, 2},\n {6, 1, 5, 2, 7, 0, 4, 3},\n {5, 4, 6, 7, 2, 3, 1, 0},\n {4, 3, 7, 0, 5, 2, 6, 1},\n {3, 2, 0, 1, 4, 5, 7, 6},\n {2, 5, 1, 6, 3, 4, 0, 7}\n};\n\n/*! This function computes a Peano-Hilbert key for an integer triplet (x,y,z),\n * with x,y,z in the range between 0 and 2^bits-1.\n */\npeanokey peano_hilbert_key(int x, int y, int z, int bits)\n{\n int mask;\n unsigned char rotation = 0;\n peanokey key = 0;\n\n for(mask = 1 << (bits - 1); mask > 0; mask >>= 1)\n {\n unsigned char pix = ((x & mask) ? 4 : 0) | ((y & mask) ? 2 : 0) | ((z & mask) ? 1 : 0);\n\n key <<= 3;\n key |= subpix3[rotation][pix];\n rotation = rottable3[rotation][pix];\n }\n\n return key;\n}\n\n\n\npeanokey morton_key(int x, int y, int z, int bits)\n{\n int mask;\n peanokey morton = 0;\n\n for(mask = 1 << (bits - 1); mask > 0; mask >>= 1)\n {\n morton <<= 3;\n morton += ((z & mask) ? 4 : 0) + ((y & mask) ? 2 : 0) + ((x & mask) ? 1 : 0);\n }\n\n return morton;\n}\n\n\npeanokey peano_and_morton_key(int x, int y, int z, int bits, peanokey * morton_key)\n{\n int mask;\n unsigned char rotation = 0;\n peanokey key = 0;\n peanokey morton = 0;\n\n\n for(mask = 1 << (bits - 1); mask > 0; mask >>= 1)\n {\n unsigned char pix = ((x & mask) ? 4 : 0) | ((y & mask) ? 2 : 0) | ((z & mask) ? 1 : 0);\n\n key <<= 3;\n key |= subpix3[rotation][pix];\n rotation = rottable3[rotation][pix];\n\n morton <<= 3;\n morton += ((z & mask) ? 4 : 0) + ((y & mask) ? 2 : 0) + ((x & mask) ? 1 : 0);\n }\n\n *morton_key = morton;\n\n return key;\n}\n\n\n\n\nstatic int quadrants[24][2][2][2] = {\n /* rotx=0, roty=0-3 */\n {{{0, 7}, {1, 6}}, {{3, 4}, {2, 5}}},\n {{{7, 4}, {6, 5}}, {{0, 3}, {1, 2}}},\n {{{4, 3}, {5, 2}}, {{7, 0}, {6, 1}}},\n {{{3, 0}, {2, 1}}, {{4, 7}, {5, 6}}},\n /* rotx=1, roty=0-3 */\n {{{1, 0}, {6, 7}}, {{2, 3}, {5, 4}}},\n {{{0, 3}, {7, 4}}, {{1, 2}, {6, 5}}},\n {{{3, 2}, {4, 5}}, {{0, 1}, {7, 6}}},\n {{{2, 1}, {5, 6}}, {{3, 0}, {4, 7}}},\n /* rotx=2, roty=0-3 */\n {{{6, 1}, {7, 0}}, {{5, 2}, {4, 3}}},\n {{{1, 2}, {0, 3}}, {{6, 5}, {7, 4}}},\n {{{2, 5}, {3, 4}}, {{1, 6}, {0, 7}}},\n {{{5, 6}, {4, 7}}, {{2, 1}, {3, 0}}},\n /* rotx=3, roty=0-3 */\n {{{7, 6}, {0, 1}}, {{4, 5}, {3, 2}}},\n {{{6, 5}, {1, 2}}, {{7, 4}, {0, 3}}},\n {{{5, 4}, {2, 3}}, {{6, 7}, {1, 0}}},\n {{{4, 7}, {3, 0}}, {{5, 6}, {2, 1}}},\n /* rotx=4, roty=0-3 */\n {{{6, 7}, {5, 4}}, {{1, 0}, {2, 3}}},\n {{{7, 0}, {4, 3}}, {{6, 1}, {5, 2}}},\n {{{0, 1}, {3, 2}}, {{7, 6}, {4, 5}}},\n {{{1, 6}, {2, 5}}, {{0, 7}, {3, 4}}},\n /* rotx=5, roty=0-3 */\n {{{2, 3}, {1, 0}}, {{5, 4}, {6, 7}}},\n {{{3, 4}, {0, 7}}, {{2, 5}, {1, 6}}},\n {{{4, 5}, {7, 6}}, {{3, 2}, {0, 1}}},\n {{{5, 2}, {6, 1}}, {{4, 3}, {7, 0}}}\n};\n\n\nstatic int rotxmap_table[24] = { 4, 5, 6, 7, 8, 9, 10, 11,\n 12, 13, 14, 15, 0, 1, 2, 3, 17, 18, 19, 16, 23, 20, 21, 22\n};\n\nstatic int rotymap_table[24] = { 1, 2, 3, 0, 16, 17, 18, 19,\n 11, 8, 9, 10, 22, 23, 20, 21, 14, 15, 12, 13, 4, 5, 6, 7\n};\n\nstatic int rotx_table[8] = { 3, 0, 0, 2, 2, 0, 0, 1 };\nstatic int roty_table[8] = { 0, 1, 1, 2, 2, 3, 3, 0 };\n\nstatic int sense_table[8] = { -1, -1, -1, +1, +1, -1, -1, -1 };\n\n\npeanokey peano_hilbert_key_old(int x, int y, int z, int bits)\n{\n int i, quad, bitx, bity, bitz;\n int mask, rotation, rotx, roty, sense;\n peanokey key;\n\n\n mask = 1 << (bits - 1);\n key = 0;\n rotation = 0;\n sense = 1;\n\n\n for(i = 0; i < bits; i++, mask >>= 1)\n {\n bitx = (x & mask) ? 1 : 0;\n bity = (y & mask) ? 1 : 0;\n bitz = (z & mask) ? 1 : 0;\n\n quad = quadrants[rotation][bitx][bity][bitz];\n\n key <<= 3;\n key += (sense == 1) ? (quad) : (7 - quad);\n\n rotx = rotx_table[quad];\n roty = roty_table[quad];\n sense *= sense_table[quad];\n\n while(rotx > 0)\n\t{\n\t rotation = rotxmap_table[rotation];\n\t rotx--;\n\t}\n\n while(roty > 0)\n\t{\n\t rotation = rotymap_table[rotation];\n\t roty--;\n\t}\n }\n\n return key;\n}\n\n\npeanokey peano_and_morton_key_old(int x, int y, int z, int bits, peanokey * morton_key)\n{\n int i, quad, bitx, bity, bitz;\n int mask, rotation, rotx, roty, sense;\n peanokey key, morton;\n\n\n mask = 1 << (bits - 1);\n key = 0;\n rotation = 0;\n sense = 1;\n morton = 0;\n\n for(i = 0; i < bits; i++, mask >>= 1)\n {\n bitx = (x & mask) ? 1 : 0;\n bity = (y & mask) ? 1 : 0;\n bitz = (z & mask) ? 1 : 0;\n\n quad = quadrants[rotation][bitx][bity][bitz];\n\n key <<= 3;\n key += (sense == 1) ? (quad) : (7 - quad);\n\n rotx = rotx_table[quad];\n roty = roty_table[quad];\n sense *= sense_table[quad];\n\n while(rotx > 0)\n\t{\n\t rotation = rotxmap_table[rotation];\n\t rotx--;\n\t}\n\n while(roty > 0)\n\t{\n\t rotation = rotymap_table[rotation];\n\t roty--;\n\t}\n\n morton <<= 3;\n morton += (bitz << 2) + (bity << 1) + bitx;\n }\n\n *morton_key = morton;\n\n return key;\n}\n\n\npeanokey morton_key_old(int x, int y, int z, int bits)\n{\n int i, bitx, bity, bitz;\n int mask;\n peanokey morton;\n\n\n mask = 1 << (bits - 1);\n morton = 0;\n\n for(i = 0; i < bits; i++, mask >>= 1)\n {\n bitx = (x & mask) ? 1 : 0;\n bity = (y & mask) ? 1 : 0;\n bitz = (z & mask) ? 1 : 0;\n\n morton <<= 3;\n morton += (bitz << 2) + (bity << 1) + bitx;\n }\n\n return morton;\n}\n\n\nstatic void msort_peano_with_tmp(struct peano_hilbert_data *b, size_t n, struct peano_hilbert_data *t)\n{\n struct peano_hilbert_data *tmp;\n struct peano_hilbert_data *b1, *b2;\n size_t n1, n2;\n\n if(n <= 1)\n return;\n\n n1 = n / 2;\n n2 = n - n1;\n b1 = b;\n b2 = b + n1;\n\n msort_peano_with_tmp(b1, n1, t);\n msort_peano_with_tmp(b2, n2, t);\n\n tmp = t;\n\n while(n1 > 0 && n2 > 0)\n {\n if(b1->key <= b2->key)\n\t{\n\t --n1;\n\t *tmp++ = *b1++;\n\t}\n else\n\t{\n\t --n2;\n\t *tmp++ = *b2++;\n\t}\n }\n\n if(n1 > 0)\n memcpy(tmp, b1, n1 * sizeof(struct peano_hilbert_data));\n memcpy(b, t, (n - n2) * sizeof(struct peano_hilbert_data));\n}\n\nvoid mysort_peano(void *b, size_t n, size_t s, int (*cmp) (const void *, const void *))\n{\n const size_t size = n * s;\n\n struct peano_hilbert_data *tmp = (struct peano_hilbert_data *) mymalloc(size);\n\n msort_peano_with_tmp((struct peano_hilbert_data *) b, n, tmp);\n\n myfree(tmp);\n}\n", "meta": {"hexsha": "903be2b2dc2dcb4b97a382d7ed7dc510b1ae554c", "size": 12508, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/peano.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/peano.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/peano.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": 21.6401384083, "max_line_length": 105, "alphanum_fraction": 0.474176527, "num_tokens": 6184, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241772283033, "lm_q2_score": 0.4532618480153861, "lm_q1q2_score": 0.2837982016576139}} {"text": "/*\n * vbHmm_template.c\n * Template for original model to be analyzed by VB-HMM.\n *\n * Created by OKAMOTO Kenji and SAKO Yasushi\n * Copyright 2011\n * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.\n * All rights reserved.\n *\n * Ver. 1.0.0\n * Last modified on 2011.04.19\n */\n\n#include \n#include \n\n// Special functions is probably necessary.\n#include \n#include \n\n#include \"vbHmm_template.h\"\n\n// For random number generation.\n#include \"rand.h\"\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n#define MAX(a,b) ((a)>(b)?(a):(b))\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n\nstatic int isGlobalAnalysis = 0;\n\nvoid setFunctions__(){\n commonFunctions funcs;\n funcs.newModelParameters = newModelParameters__;\n funcs.freeModelParameters = freeModelParameters__;\n funcs.newModelStats = newModelStats__;\n funcs.freeModelStats = freeModelStats__;\n funcs.initializeVbHmm = initializeVbHmm__;\n funcs.pTilde_z1 = pTilde_z1__;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1__;\n funcs.pTilde_xn_zn = pTilde_xn_zn__;\n funcs.calcStatsVars = calcStatsVars__;\n funcs.maximization = maximization__;\n funcs.varLowerBound = varLowerBound__;\n funcs.reorderParameters = reorderParameters__;\n funcs.outputResults = outputResults__;\n setFunctions( funcs );\n}\n\nvoid setGFunctions__(){\n gCommonFunctions funcs;\n funcs.newModelParameters = newModelParameters__;\n funcs.freeModelParameters = freeModelParameters__;\n funcs.newModelStats = newModelStats__;\n funcs.freeModelStats = freeModelStats__;\n funcs.newModelStatsG = newModelStatsG__;\n funcs.freeModelStatsG = freeModelStatsG__;\n funcs.initializeVbHmmG = initializeVbHmmG__;\n funcs.pTilde_z1 = pTilde_z1__;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1__;\n funcs.pTilde_xn_zn = pTilde_xn_zn__;\n funcs.calcStatsVarsG = calcStatsVarsG__;\n funcs.maximizationG = maximizationG__;\n funcs.varLowerBoundG = varLowerBoundG__;\n funcs.reorderParametersG = reorderParametersG__;\n funcs.outputResultsG = outputResultsG__;\n setGFunctions( funcs );\n isGlobalAnalysis = 1;\n}\n\n\n// Redirect output function to that for model-specific data.\nvoid outputResults__( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n output__Results( xn, gv, iv, logFP );\n}\n\nvoid outputResultsG__( xns, gv, ivs, logFP )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\nFILE *logFP;\n{\n output__ResultsG( xns, gv, ivs, logFP );\n}\n\n\nvoid *newModelParameters__( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n int i;\n tempParameters *p = (void*)malloc( sizeof(tempParameters) );\n \n p->uPiArr = (double*)malloc( sNo * sizeof(double) );\n p->sumUPi = 0.0;\n p->uAMat = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );\n }\n p->sumUAArr = (double*)malloc( sNo * sizeof(double) );\n \n p->avgPi = (double *)malloc( sNo * sizeof(double) );\n p->avgLnPi = (double *)malloc( sNo * sizeof(double) );\n p->avgA = (double **)malloc( sNo * sizeof(double*) );\n p->avgLnA = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->avgA[i] = (double *)malloc( sNo * sizeof(double) );\n p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );\n }\n\n return p;\n}\n\nvoid freeModelParameters__( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n tempParameters *gp = *p;\n int i;\n \n free( gp->uPiArr );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->uAMat[i] );\n }\n free( gp->uAMat );\n free( gp->sumUAArr );\n \n free( gp->avgPi );\n free( gp->avgLnPi );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->avgA[i] );\n free( gp->avgLnA[i] );\n }\n free( gp->avgA );\n free( gp->avgLnA );\n \n free( *p );\n *p = NULL;\n}\n\n\nvoid *newModelStats__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n tempStats *s = (tempStats*)malloc( sizeof(tempStats) );\n \n int i;\n s->Ni = (double *)malloc( sNo * sizeof(double) );\n s->Nij = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }\n s->Nii = (double *)malloc( sNo * sizeof(double) );\n \n return s;\n \n } else {\n \n return NULL;\n \n }\n}\n\nvoid freeModelStats__( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n tempStats *gs = *s;\n int i;\n free( gs->Ni );\n for( i = 0 ; i < sNo ; i++ )\n { free( gs->Nij[i] ); }\n free( gs->Nij );\n free( gs->Nii );\n \n free( gs );\n *s = NULL;\n }\n}\n\nvoid *newModelStatsG__( xns, gv, ivs)\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n int sNo = gv->sNo;\n tempGlobalStats *gs = (tempGlobalStats*)malloc( sizeof(tempGlobalStats) );\n \n int i;\n gs->NiR = (double *)malloc( sNo * sizeof(double) );\n gs->NijR = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { gs->NijR[i] = (double *)malloc( sNo * sizeof(double) ); }\n gs->NiiR = (double *)malloc( sNo * sizeof(double) );\n gs->z1iR = (double *)malloc( sNo * sizeof(double) );\n \n return gs;\n}\n\nvoid freeModelStatsG__( gs, xns, gv, ivs )\nvoid **gs;\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n int sNo = gv->sNo;\n tempGlobalStats *ggs = *gs;\n int i;\n free( ggs->NiR );\n for( i = 0 ; i < sNo ; i++ )\n { free( ggs->NijR[i] ); }\n free( ggs->NijR );\n free( ggs->NiiR );\n free( ggs->z1iR );\n \n free( *gs );\n *gs = NULL;\n}\n\n\nvoid initializeVbHmm__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n // an example of hyperparameter initialization\n\n int sNo = gv->sNo;\n tempParameters *p = gv->params;\n\n int i, j;\n // hyper parameter for p( pi(i) )\n p->sumUPi = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n p->uPiArr[i] = 1.0;\n p->sumUPi += p->uPiArr[i];\n }\n \n // hyper parameter for p( A(i,j) )\n for( i = 0 ; i < sNo ; i++ ){\n p->sumUAArr[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n if( j == i ){\n p->uAMat[i][j] = 5.0;\n } else {\n p->uAMat[i][j] = 1.0;\n }\n p->sumUAArr[i] += p->uAMat[i][j];\n }\n }\n \n initialize_indVars__( xn, gv, iv );\n \n calcStatsVars__( xn, gv, iv );\n maximization__( xn, gv, iv );\n}\n\nvoid initializeVbHmmG__( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n // an example of hyperparameter initialization\n\n int sNo = gv->sNo, rNo = xns->R;\n tempParameters *p = gv->params;\n\n int i, j, r;\n \n p->sumUPi = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n p->uPiArr[i] = 1.0;\n p->sumUPi += p->uPiArr[i];\n }\n \n for( i = 0 ; i < sNo ; i++ ){\n p->sumUAArr[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n if( j == i ){\n p->uAMat[i][j] = 5.0;\n } else {\n p->uAMat[i][j] = 1.0;\n }\n p->sumUAArr[i] += p->uAMat[i][j];\n }\n }\n \n for( r = 0 ; r < rNo ; r++ ){\n initialize_indVars__( xns->xn[r], gv, ivs->indVars[r] );\n }\n \n calcStatsVarsG__( xns, gv, ivs );\n maximizationG__( xns, gv, ivs );\n}\n\n\nvoid initialize_indVars__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n // an example of latent variable distribution\n \n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n \n int i;\n size_t n;\n double sumPar;\n for( n = 0 ; n < dLen ; n++ ){\n sumPar = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] = enoise(1.0) + 1.0;\n sumPar += gmMat[n][i];\n }\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] /= sumPar;\n }\n }\n}\n\n\nxnDataSet *newXnDataSet__( filename )\nconst char *filename;\n{\n xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );\n xn->name = (char*)malloc( strlen(filename) + 2 );\n strncpy( xn->name, filename, strlen(filename)+1 );\n xn->data = (tempData*)malloc( sizeof(tempData) );\n tempData *d = (tempData*)xn->data;\n return xn;\n}\n\nvoid freeXnDataSet__( xn )\nxnDataSet **xn;\n{\n tempData *d = (tempData*)(*xn)->data;\n free( (*xn)->data );\n free( (*xn)->name );\n free( *xn );\n *xn = NULL;\n}\n\n\ndouble pTilde_z1__( i, params )\nint i;\nvoid *params;\n{\n // Return the value for p(z_{1i}|pi_i) for given i.\n\n // for common HMM\n tempParameters *p = (tempParameters*)params;\n return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1__( i, j, params )\nint i, j;\nvoid *params;\n{\n // Return the value for p(z_{nj}|z_{n-1,i},theta) for given i and j.\n\n // for common HMM\n tempParameters *p = (tempParameters*)params;\n return exp( p->avgLnA[i][j] );\n}\n\ndouble pTilde_xn_zn__( xnWv, n, i, params )\nxnDataSet *xnWv;\nsize_t n;\nint i;\nvoid *params;\n{\n // Return the value for p(x_{mi}|z_{ni},phi) for given i.\n\n // return emission probability for the model.\n tempParameters *p = (tempParameters*)params;\n return 0.0;\n}\n\n\nvoid calcStatsVars__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n // Execute calculation of statistics, which may be necessary for M-step.\n\n // calculation of stats for common HMM\n tempStats *s = (tempStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *Nii = s->Nii, **Nij = s->Nij, *Ni = s->Ni;\n size_t n;\n int i, j;\n \n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] = 1e-10;\n Nii[i] = 1e-10;\n for( j = 0 ; j < sNo ; j++ ){\n Nij[i][j] = 1e-10;\n }\n \n for( n = 0 ; n < dLen ; n++ ){\n Ni[i] += gmMat[n][i];\n for( j = 0 ; j < sNo ; j++ ){\n Nii[i] += xiMat[n][i][j];\n Nij[i][j] += xiMat[n][i][j];\n }\n }\n }\n}\n\nvoid calcStatsVarsG__( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n // Execute calculation of statistics for global analysis, which may be necessary for M-step.\n \n // calculation of stats for global analysis of common HMM\n tempGlobalStats *gs = (tempGlobalStats*)ivs->stats;\n int sNo = gv->sNo, rNo = xns->R;\n double **gmMat, ***xiMat;\n double *NiiR = gs->NiiR, **NijR = gs->NijR, *NiR = gs->NiR, *z1iR = gs->z1iR;\n size_t dLen, n;\n int i, j, r;\n \n for( i = 0 ; i < sNo ; i++ ){\n NiR[i] = 1e-10;\n NiiR[i] = 1e-10;\n for( j = 0 ; j < sNo ; j++ ){\n NijR[i][j] = 1e-10;\n }\n z1iR[i] = 1e-10;\n }\n for( r = 0 ; r < rNo ; r++ ){\n dLen = xns->xn[r]->N;\n gmMat = ivs->indVars[r]->gmMat;\n xiMat = ivs->indVars[r]->xiMat;\n for( i = 0 ; i < sNo ; i++ ){\n z1iR[i] += gmMat[0][i];\n for( n = 0 ; n < dLen ; n++ ){\n NiR[i] += gmMat[n][i];\n for( j = 0 ; j < sNo ; j++ ){\n NiiR[i] += xiMat[n][i][j];\n NijR[i][j] += xiMat[n][i][j];\n }\n }\n }\n }\n}\n\n\nvoid maximization__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n // Calculation of M-step, depending on the model.\n\n // calculation of M-step for common HMM\n tempParameters *p = (tempParameters*)gv->params;\n tempStats *s = (tempStats*)iv->stats;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n double *Nii = s->Nii, **Nij = s->Nij;\n int i, j;\n \n for( i = 0 ; i < sNo ; i++ ){\n avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );\n avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );\n \n for( j = 0 ; j < sNo ; j++ ){\n avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] );\n avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] );\n }\n }\n}\n\nvoid maximizationG__( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n // Calculation of M-step for global analysis, depending on the model.\n \n // calculation of stats for global analysis of common HMM\n tempParameters *p = (tempParameters*)gv->params;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n tempGlobalStats *gs = (tempGlobalStats*)ivs->stats;\n double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)(xns->R);\n int sNo = gv->sNo;\n int i, j;\n \n for( i = 0 ; i < sNo ; i++ ){\n avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR );\n avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR );\n \n for( j = 0 ; j < sNo ; j++ ){\n avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] );\n avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] );\n }\n }\n}\n\n\ndouble varLowerBound__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n // Calculation of lower bound, depending on the model.\n\n // calculation of lower bound of common HMM\n tempParameters *p = (tempParameters*)gv->params;\n tempStats *s = (tempStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, *cn = iv->cn;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n double *Nii = s->Nii, **Nij = s->Nij;\n size_t n;\n int i, j;\n \n double lnpPi = gsl_sf_lngamma(sumUPi);\n double lnpA = 0.0;\n double lnpPhi = 0.0; // ln p(phi) for model-specific parameters\n double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);\n double lnqA = 0.0;\n double lnqPhi = 0.0; // ln q(phi) for model-specific parameters\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n \n lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));\n lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);\n \n lnpA += gsl_sf_lngamma(sumUAArr[i]);\n lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]);\n for( j = 0 ; j < sNo ; j++ ){\n lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);\n \n lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i]));\n lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );\n }\n }\n \n double lnpX = 0.0;\n for( n = 0 ; n < dLen ; n++ ){\n lnpX += log( cn[n] );\n }\n \n double val;\n val = lnpPi + lnpA + lnpPhi;\n val -= lnqPi + lnqA + lnqPhi;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n \n return val;\n}\n\ndouble varLowerBoundG__( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n // Calculation of lower bound for global analysis, depending on the model.\n \n // calculation of lower bound for global analysis of common HMM\n int sNo = gv->sNo, rNo = xns->R;\n tempParameters *p = (tempParameters*)gv->params;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n tempGlobalStats *gs = (tempGlobalStats*)ivs->stats;\n double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R;\n size_t n;\n int i, j, r;\n \n double lnpPi = gsl_sf_lngamma(sumUPi);\n double lnpA = 0.0;\n double lnpPhi = 0.0; // ln p(phi) for model-specific parameters\n double lnqPi = gsl_sf_lngamma(sumUPi + dR);\n double lnqA = 0.0;\n double lnqPhi = 0.0; // ln q(phi) for model-specific parameters\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n \n lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR));\n lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]);\n \n lnpA += gsl_sf_lngamma(sumUAArr[i]);\n lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]);\n for( j = 0 ; j < sNo ; j++ ){\n lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);\n \n lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i]));\n lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] );\n }\n }\n \n double lnpX = 0.0;\n for( r = 0 ; r < rNo ; r++ ){\n size_t dLen = xns->xn[r]->N;\n for( n = 0 ; n < dLen ; n++ ){\n lnpX += log( ivs->indVars[r]->cn[n] );\n }\n }\n \n double val;\n val = lnpPi + lnpA + lnpPhi;\n val -= lnqPi + lnqA + lnqPhi;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n \n return val;\n} \n\n\nvoid reorderParameters__( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n // Reorder states in the final result, for example, in the order of intensity.\n\n // an example for common HMM.\n tempParameters *p = (tempParameters*)gv->params;\n tempStats *s = (tempStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n double *Ni = s->Ni;\n size_t n;\n int i, j;\n \n int *index = (int*)malloc( sNo * sizeof(int) );\n double *store = (double*)malloc( sNo * sizeof(double) );\n double **s2D = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }\n \n // index indicates order of avgPi values (0=biggest avgMu -- sNo=smallest avgMu).\n for( i = 0 ; i < sNo ; i++ ){\n index[i] = sNo - 1;\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n if( avgPi[i] < avgPi[j] ){\n index[i]--;\n } else if( avgPi[i] == avgPi[j] ){\n if( j > i )\n { index[i]--; }\n }\n }\n }\n }\n \n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }\n \n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }\n \n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }\n }\n \n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }\n }\n \n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }\n \n for( n = 0 ; n < dLen ; n++ ){\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }\n for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }\n }\n \n for( n = 0 ; n < dLen ; n++ ){\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }\n }\n }\n \n for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }\n free( s2D );\n free( store );\n free( index );\n}\n\nvoid reorderParametersG__( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n // Reorder states in the final result, for example, in the order of intensity.\n \n // an example for global analysis of common HMM.\n size_t dLen;\n int sNo = gv->sNo, rNo = xns->R;\n tempParameters *p = (tempParameters*)gv->params;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n \n size_t n;\n int i, j, r;\n \n int *index = (int*)malloc( sNo * sizeof(int) );\n double *store = (double*)malloc( sNo * sizeof(double) );\n double **s2D = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }\n \n // index indicates order of avgPi values (0=biggest avgMu -- sNo=smallest avgMu).\n for( i = 0 ; i < sNo ; i++ ){\n index[i] = sNo - 1;\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n if( avgPi[i] < avgPi[j] ){\n index[i]--;\n } else if( avgPi[i] == avgPi[j] ){\n if( j > i )\n { index[i]--; }\n }\n }\n }\n }\n \n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }\n \n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }\n \n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgA[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgA[i][j] = s2D[i][j]; }\n }\n \n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnA[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgLnA[i][j] = s2D[i][j]; }\n }\n \n double *NiR = ((tempGlobalStats*)ivs->stats)->NiR;\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = NiR[i]; }\n for( i = 0 ; i < sNo ; i++ ){ NiR[i] = store[i]; }\n \n for( r = 0 ; r < rNo ; r++ ){\n double **gmMat = ivs->indVars[r]->gmMat;\n dLen = xns->xn[r]->N;\n for( n = 0 ; n < dLen ; n++ ){\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }\n for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }\n }\n }\n \n for( r = 0 ; r < rNo ; r++ ){\n double ***xiMat = ivs->indVars[r]->xiMat;\n dLen = xns->xn[r]->N;\n for( n = 0 ; n < dLen ; n++ ){\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }\n }\n }\n }\n \n for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }\n free( s2D );\n free( store );\n free( index );\n}\n\n\nvoid output__Results( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n // Output the final result (after reordering) in any format, e.g. stdout, stderr or files.\n\n // an example for common HMM parameters.\n tempParameters *p = (tempParameters*)gv->params;\n int sNo = gv->sNo;\n \n int i, j;\n fprintf(logFP, \" results: K = %d \\n\", sNo);\n \n fprintf(logFP, \" pi: ( %g\", p->avgPi[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgPi[i]);\n }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" A_matrix: [\");\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(logFP, \" ( %g\", p->avgA[i][0]);\n for( j = 1 ; j < sNo ; j++ )\n { fprintf(logFP, \", %g\", p->avgA[i][j]); }\n fprintf(logFP, \")\");\n }\n fprintf(logFP, \" ] \\n\\n\");\n \n char fn[256];\n FILE *fp;\n size_t n;\n \n sprintf( fn, \"%s.param%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n fprintf(fp, \"pi\");\n for( i = 0 ; i < sNo ; i++ )\n { fprintf(fp, \", A%dx\", i); }\n fprintf(fp, \"\\n\");\n \n for( i = 0 ; i < sNo ; i++ ){\n fprintf(fp, \"%g\", p->avgPi[i]);\n for( j = 0 ; j < sNo ; j++ )\n { fprintf(fp, \", %g\", p->avgA[j][i]); }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.Lq%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < gv->iteration ; n++ ){\n fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.maxS%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < xn->N ; n++ ){\n fprintf( fp, \"%d\\n\", iv->stateTraj[n] );\n }\n fclose(fp);\n }\n \n}\n\nvoid output__ResultsG( xns, gv, ivs, logFP )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\nFILE *logFP;\n{\n // Output the final result (after reordering) in any format, e.g. stdout, stderr or files.\n \n // an example for parameters of global analysis of common HMM.\n int sNo = gv->sNo, rNo = xns->R;\n tempParameters *p = (tempParameters*)gv->params;\n int i, j, r;\n \n fprintf(logFP, \" results: K = %d \\n\", sNo);\n \n fprintf(logFP, \" pi: ( %g\", p->avgPi[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgPi[i]);\n }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" A_matrix: [\");\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(logFP, \" ( %g\", p->avgA[i][0]);\n for( j = 1 ; j < sNo ; j++ )\n { fprintf(logFP, \", %g\", p->avgA[i][j]); }\n fprintf(logFP, \")\");\n }\n fprintf(logFP, \" ] \\n\\n\");\n \n char fn[256];\n FILE *fp;\n size_t n;\n \n sprintf( fn, \"%s.param%03d\", xns->xn[0]->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n fprintf(fp, \"pi\");\n for( i = 0 ; i < sNo ; i++ )\n { fprintf(fp, \", A%dx\", i); }\n fprintf(fp, \"\\n\");\n \n for( i = 0 ; i < sNo ; i++ ){\n fprintf(fp, \"%g\", p->avgPi[i]);\n for( j = 0 ; j < sNo ; j++ )\n { fprintf(fp, \", %g\", p->avgA[j][i]); }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.Lq%03d\", xns->xn[0]->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < gv->iteration ; n++ ){\n fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n }\n fclose(fp);\n }\n \n for( r = 0 ; r < rNo ; r++ ){\n xnDataSet *xn = xns->xn[r];\n indVars *iv = ivs->indVars[r];\n \n sprintf( fn, \"%s.maxS%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < xn->N ; n++ ){\n fprintf( fp, \"%d\\n\", iv->stateTraj[n] );\n }\n fclose(fp);\n }\n }\n}\n\n//\n", "meta": {"hexsha": "2b4d85589d332f492a8b757218096442c7aa4a27", "size": 27439, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmm_template.c", "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_issues_repo_path": "C/vbHmm_template.c", "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_licenses": ["MIT"], "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/vbHmm_template.c", "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": ["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.6419624217, "max_line_length": 126, "alphanum_fraction": 0.4891213237, "num_tokens": 9694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.28294867800151635}} {"text": "/* specfunc/bessel_I0.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_bessel.h\"\n\n#include \"error.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n\n/* based on SLATEC besi0 */\n\n/* chebyshev expansions\n\n series for bi0 on the interval 0.\t to 9.00000d+00\n\t\t\t\t\twith weighted error 2.46e-18\n\t\t\t\t\t log weighted error 17.61\n\t\t\t significant figures required 17.90\n\t\t\t\t decimal places required 18.15\n\n series for ai0 on the interval 1.25000d-01 to 3.33333d-01\n\t\t\t\t\twith weighted error 7.87e-17\n\t\t\t\t\t log weighted error 16.10\n\t\t\t significant figures required 14.69\n\t\t\t\t decimal places required 16.76\n\n\n series for ai02 on the interval 0.\t to 1.25000d-01\n\t\t\t\t\twith weighted error 3.79e-17\n\t\t\t\t\t log weighted error 16.42\n\t\t\t significant figures required 14.86\n\t\t\t\t decimal places required 17.09\n*/\n\nstatic double bi0_data[12] = {\n -.07660547252839144951,\n 1.92733795399380827000,\n .22826445869203013390, \n .01304891466707290428,\n .00043442709008164874,\n .00000942265768600193,\n .00000014340062895106,\n .00000000161384906966,\n .00000000001396650044,\n .00000000000009579451,\n .00000000000000053339,\n .00000000000000000245\n};\nstatic cheb_series bi0_cs = {\n bi0_data,\n 11,\n -1, 1,\n 11\n};\n\nstatic double ai0_data[21] = {\n .07575994494023796, \n .00759138081082334,\n .00041531313389237,\n .00001070076463439,\n -.00000790117997921,\n -.00000078261435014,\n .00000027838499429,\n .00000000825247260,\n -.00000001204463945,\n .00000000155964859,\n .00000000022925563,\n -.00000000011916228,\n .00000000001757854,\n .00000000000112822,\n -.00000000000114684,\n .00000000000027155,\n -.00000000000002415,\n -.00000000000000608,\n .00000000000000314,\n -.00000000000000071,\n .00000000000000007\n};\nstatic cheb_series ai0_cs = {\n ai0_data,\n 20,\n -1, 1,\n 13\n};\n\nstatic double ai02_data[22] = {\n .05449041101410882,\n .00336911647825569,\n .00006889758346918,\n .00000289137052082,\n .00000020489185893,\n .00000002266668991,\n .00000000339623203,\n .00000000049406022,\n .00000000001188914,\n -.00000000003149915,\n -.00000000001321580,\n -.00000000000179419,\n .00000000000071801,\n .00000000000038529,\n .00000000000001539,\n -.00000000000004151,\n -.00000000000000954,\n .00000000000000382,\n .00000000000000176,\n -.00000000000000034,\n -.00000000000000027,\n .00000000000000003\n};\nstatic cheb_series ai02_cs = {\n ai02_data,\n 21,\n -1, 1,\n 11\n};\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint gsl_sf_bessel_I0_scaled_e(const double x, gsl_sf_result * result)\n{\n double y = fabs(x);\n\n /* CHECK_POINTER(result) */\n\n if(y < 2.0 * GSL_SQRT_DBL_EPSILON) {\n result->val = 1.0 - y;\n result->err = 0.5*y*y;\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(&bi0_cs, y*y/4.5-1.0, &c);\n result->val = ey * (2.75 + c.val);\n result->err = GSL_DBL_EPSILON * fabs(result->val) + ey * c.err;\n return GSL_SUCCESS;\n }\n else if(y <= 8.0) {\n const double sy = sqrt(y);\n gsl_sf_result c;\n cheb_eval_e(&ai0_cs, (48.0/y-11.0)/5.0, &c);\n result->val = (0.375 + c.val) / sy;\n result->err = 2.0 * GSL_DBL_EPSILON * (0.375 + fabs(c.val)) / sy;\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 cheb_eval_e(&ai02_cs, 16.0/y-1.0, &c);\n result->val = (0.375 + c.val) / sy;\n result->err = 2.0 * GSL_DBL_EPSILON * (0.375 + fabs(c.val)) / sy;\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_I0_e(const double x, gsl_sf_result * result)\n{\n double y = fabs(x);\n\n /* CHECK_POINTER(result) */\n\n if(y < 2.0 * GSL_SQRT_DBL_EPSILON) {\n result->val = 1.0;\n result->err = 0.5*y*y;\n return GSL_SUCCESS;\n }\n else if(y <= 3.0) {\n gsl_sf_result c;\n cheb_eval_e(&bi0_cs, y*y/4.5-1.0, &c);\n result->val = 2.75 + c.val;\n result->err = GSL_DBL_EPSILON * (2.75 + fabs(c.val));\n result->err += 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 - 1.0) {\n const double ey = exp(y);\n gsl_sf_result b_scaled;\n gsl_sf_bessel_I0_scaled_e(x, &b_scaled);\n result->val = ey * b_scaled.val;\n result->err = ey * b_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_I0_scaled(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_I0_scaled_e(x, &result); ) \n}\n\ndouble gsl_sf_bessel_I0(const double x)\n{\n EVAL_RESULT(gsl_sf_bessel_I0_e(x, &result); ) \n}\n", "meta": {"hexsha": "3fe0c64f94896a96584cc3039f6418c0d72fcc0a", "size": 5868, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/specfunc/bessel_I0.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_I0.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_I0.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.1845493562, "max_line_length": 76, "alphanum_fraction": 0.6489434219, "num_tokens": 2024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.28294054989865397}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nvoid init_MCMC(MCMC_info * MCMC,\n const char *problem_name,\n void * params,\n int (*f)(double *, MCMC_info *, double **),\n int n_P,\n double *P_init,\n char ** P_names,\n double *P_limit_min,\n double *P_limit_max,\n int n_arrays,\n ...) {\n int i_P;\n int i_array;\n int i;\n FILE * ft, *ft_restart;\n char test_dir[256], test_restart[256];\n va_list vargs;\n va_start(vargs, n_arrays);\n\n SID_log(\"Initializing MCMC structure...\", SID_LOG_OPEN);\n\n // Set defaults to bare minimums\n MCMC->n_avg = 100;\n MCMC->n_iterations_burn = 4;\n MCMC->n_iterations = 8;\n MCMC->n_thin = 1;\n MCMC->coverage_size = 100;\n MCMC->flag_autocor_on = GBP_FALSE;\n MCMC->flag_integrate_on = GBP_FALSE;\n MCMC->flag_analysis_on = GBP_TRUE;\n MCMC->first_map_call = GBP_TRUE;\n MCMC->first_link_call = GBP_TRUE;\n MCMC->flag_init_chain = GBP_TRUE;\n MCMC->first_chain_call = GBP_TRUE;\n MCMC->first_parameter_call = GBP_TRUE;\n MCMC->first_likelihood_call = GBP_TRUE;\n MCMC->ln_likelihood_last = 0.;\n MCMC->ln_likelihood_new = 0.;\n MCMC->ln_likelihood_chain = 0.;\n MCMC->P_init = NULL;\n MCMC->P_new = NULL;\n MCMC->P_last = NULL;\n MCMC->P_chain = NULL;\n MCMC->P_limit_min = NULL;\n MCMC->P_limit_max = NULL;\n MCMC->P_min = NULL;\n MCMC->P_max = NULL;\n MCMC->P_avg = NULL;\n MCMC->dP_avg = NULL;\n MCMC->P_best = NULL;\n MCMC->P_peak = NULL;\n MCMC->P_lo_68 = NULL;\n MCMC->P_hi_68 = NULL;\n MCMC->P_lo_95 = NULL;\n MCMC->P_hi_95 = NULL;\n MCMC->n_M = NULL;\n MCMC->M_new = NULL;\n MCMC->M_last = NULL;\n MCMC->DS = NULL;\n MCMC->last = NULL;\n MCMC->V = NULL;\n MCMC->m = NULL;\n MCMC->b = NULL;\n MCMC->RNG = NULL;\n MCMC->params = NULL;\n MCMC->temperature = 1.0;\n MCMC->n_DS = 0;\n MCMC->n_M_total = 0;\n MCMC->n_fail = 0;\n MCMC->n_success = 0;\n MCMC->n_propositions = 0;\n MCMC->n_map_calls = 0;\n\n // Process the passed arguments\n MCMC->map_P_to_M = f;\n MCMC->compute_MCMC_ln_likelihood = compute_MCMC_ln_likelihood_default;\n MCMC->params = params;\n MCMC->n_P = n_P;\n sprintf(MCMC->problem_name, \"%s\", problem_name);\n MCMC->P_names = (char **)SID_malloc(sizeof(char *) * MCMC->n_P);\n MCMC->P_name_length = 0;\n for(i_P = 0; i_P < n_P; i_P++) {\n MCMC->P_names[i_P] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE);\n sprintf(MCMC->P_names[i_P], \"%s\", P_names[i_P]);\n MCMC->P_name_length = GBP_MAX((size_t)(MCMC->P_name_length), strlen(MCMC->P_names[i_P]));\n }\n sprintf(MCMC->P_name_format, \"%%-%ds\", MCMC->P_name_length);\n\n // Initialize the MCMC mode and set things associated with it\n set_MCMC_mode(MCMC, MCMC_MODE_DEFAULT); // MCMC->my_chain is set here\n\n // Set parameter arrays and limits\n MCMC->P_init = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n MCMC->P_new = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n MCMC->P_last = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n MCMC->P_chain = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n MCMC->P_limit_min = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n MCMC->P_limit_max = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n if(P_limit_min == NULL) {\n for(i_P = 0; i_P < n_P; i_P++)\n MCMC->P_limit_min[i_P] = -DBL_MAX * 1e-3;\n } else {\n for(i_P = 0; i_P < n_P; i_P++)\n MCMC->P_limit_min[i_P] = P_limit_min[i_P];\n }\n if(P_limit_max == NULL) {\n for(i_P = 0; i_P < n_P; i_P++)\n MCMC->P_limit_max[i_P] = DBL_MAX * 1e-3;\n } else {\n for(i_P = 0; i_P < n_P; i_P++)\n MCMC->P_limit_max[i_P] = P_limit_max[i_P];\n }\n\n // Set parameter initial values\n memcpy(MCMC->P_init, P_init, (size_t)MCMC->n_P * sizeof(double));\n memcpy(MCMC->P_new, P_init, (size_t)MCMC->n_P * sizeof(double));\n memcpy(MCMC->P_last, P_init, (size_t)MCMC->n_P * sizeof(double));\n memcpy(MCMC->P_chain, P_init, (size_t)MCMC->n_P * sizeof(double));\n\n // Set arrays\n MCMC->n_arrays = n_arrays;\n if(n_arrays > 0) {\n MCMC->array = (double **)SID_malloc(sizeof(double *) * MCMC->n_arrays);\n MCMC->array_name = (char **)SID_malloc(sizeof(char *) * MCMC->n_arrays);\n for(i_array = 0; i_array < n_arrays; i_array++) {\n MCMC->array[i_array] = (double *)SID_malloc(sizeof(double) * MCMC->n_P);\n MCMC->array_name[i_array] = (char *)SID_malloc(sizeof(char) * MCMC_NAME_SIZE);\n memcpy(MCMC->array[i_array], (double *)va_arg(vargs, double *), (size_t)(MCMC->n_P) * sizeof(double));\n sprintf(MCMC->array_name[i_array], \"%s\", (char *)va_arg(vargs, char *));\n }\n } else\n MCMC->array = NULL;\n\n // Set autotune defaults (if needed)\n if(SID_CHECK_BITFIELD_SWITCH(MCMC->mode, MCMC_MODE_AUTOTUNE))\n set_MCMC_autotune(MCMC, -1., -1., -1., -1, -1, -1, -1); // Negatives mean use defaults (set in gbpMCMC.h)\n\n // Initialize Communicator\n SID_Comm_init(&(MCMC->comm));\n SID_Comm_split(SID_COMM_WORLD, MCMC->my_chain, SID.My_rank, MCMC->comm);\n\n // Set the base output directory\n if(MCMC->my_chain == SID.My_rank) {\n // Generate directory and stop filenames\n sprintf(test_dir, \"./%s_MCMC/\", SID.My_binary);\n sprintf(test_restart, \"./%s_MCMC/stop\", SID.My_binary);\n\n // analyze_MCMC() needs to know what the filename root is. We also need to strip trailing '/'s.\n strcpy(MCMC->filename_output_root, test_dir);\n int i_char;\n int flag_continue;\n for(i_char = strlen(MCMC->filename_output_root) - 1, flag_continue = GBP_TRUE; i_char >= 0 && flag_continue; i_char--) {\n if(MCMC->filename_output_root[i_char] != '/')\n flag_continue = GBP_FALSE;\n else\n MCMC->filename_output_root[i_char] = '\\0';\n }\n\n i = 0;\n // Try to open them ...\n ft = fopen(test_dir, \"r\");\n ft_restart = fopen(test_restart, \"r\");\n // If the directory exists & there is no stop file in it then...\n if((ft != NULL) && (ft_restart == NULL)) {\n // Increment the directory suffix until we don't find a directory,\n // whilst always ensuring we don't come across a stop file (which indicates\n // the previous run was stopped prematurely and we want restart the run).\n do {\n fclose(ft);\n i++;\n sprintf(test_dir, \"./%s_MCMC.%d/\", SID.My_binary, i);\n ft = fopen(test_dir, \"r\");\n sprintf(test_restart, \"./%s_MCMC.%d/stop\", SID.My_binary, i);\n ft_restart = fopen(test_restart, \"r\");\n } while((ft != NULL) && (ft_restart == NULL));\n }\n // Finally, if we did find a stop file then close it and remove it.\n if(ft_restart != NULL) {\n fclose(ft_restart);\n remove(test_restart);\n }\n // Copy the directory name we settled on to the MCMC structure\n strcpy(MCMC->filename_output_dir, test_dir);\n SID_log(\"ouput_dir set to: %s\", SID_LOG_COMMENT, MCMC->filename_output_dir);\n }\n // Broadcast the output directory to all the other cores.\n SID_Bcast(MCMC->filename_output_dir, SID_MAX_FILENAME_LENGTH, SID_CHAR, MCMC->my_chain, MCMC->comm);\n\n // Initilize the random number generator\n MCMC->RNG = (RNG_info *)SID_malloc(sizeof(RNG_info));\n init_seed_from_clock(&(MCMC->seed));\n SID_Bcast(&(MCMC->seed), 1, SID_INT, SID_MASTER_RANK, MCMC->comm);\n init_RNG(&(MCMC->seed), MCMC->RNG, RNG_DEFAULT);\n\n SID_log(\"Done.\", SID_LOG_CLOSE);\n\n va_end(vargs);\n}\n", "meta": {"hexsha": "762c8b634dcd1ebfbb205d83e352e17192ca2ef4", "size": 8698, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gbpMath/gbpMCMC/init_MCMC.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/init_MCMC.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/init_MCMC.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": 41.419047619, "max_line_length": 128, "alphanum_fraction": 0.5510462175, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804478040617, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2828672623461958}} {"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\"\n#define KSTEST 1\n#define KSFLAT 2\n#define KSSIN 3\n#define KSFLAT_WITH_MINMAX 4\n#define CORREL 20\n#define PEARSON 21\n#define MOMENTS 30\n#define MEDIAN 31\n#define CHI2TEST_HIST 50\n#define CHI2TEST_CDF 51\nint main(int argc, char **argv)\n{\n psrsalsaApplication application;\n long i, j;\n int file1_column1, file1_column2, file1_column3, file2_column1, file2_column2, file2_column3, typetest, read_log, output_idx, skiplines;\n double threshold1, threshold2, threshold3, ksflat_min, ksflat_max;\n initApplication(&application, \"pstat\", \"[options] inputfile(s)\");\n application.switch_libversions = 1;\n application.switch_verbose = 1;\n application.switch_debug = 1;\n file1_column1 = 0;\n file1_column2 = 0;\n file1_column3 = 0;\n file2_column1 = 0;\n file2_column2 = 0;\n file2_column3 = 0;\n typetest = 0;\n read_log = 0;\n threshold1 = 0;\n threshold2 = 0;\n threshold3 = 0;\n output_idx = 0;\n skiplines = 0;\n if(argc < 2) {\n printf(\"Program to perform various statistical tests on input data. One or two input\\n\");\n printf(\"files are required depending on the statistical test to be performed. The input\\n\");\n printf(\"files should be ascii files with each line having an equal number of columns.\\n\");\n printf(\"Lines starting with a # will be ignored. Usage:\\n\\n\");\n printApplicationHelp(&application);\n printf(\"Input/Output options:\\n\");\n printf(\"-col \\\"c1 c2 c3\\\" Specify one, two or three column numbers (counting from 1) to\\n\");\n printf(\" be read in from the first input file. Some statistical tests\\n\");\n printf(\" require only one input column, others two or more.\\n\");\n printf(\"-col1 Equivalent to -col\\n\");\n printf(\"-col2 Like -col1, but for second input file.\\n\");\n printf(\"-log The base 10 log of the input values is used.\\n\");\n printf(\"-output Specify output filename to use rather than the stdout.\\n\");\n printf(\"-skiplines nr Specify number of lines that should be skipped from start file(s).\\n\");\n printf(\"\\nStatistical tests:\\n\");\n printf(\"-chi2hist \\\"t1 t2 t3\\\" Input should be two files, each being a histogram and\\n\");\n printf(\" having two (or three, see below) columns: bin location and\\n\");\n printf(\" the height. The histograms should have equal bin widths,\\n\");\n printf(\" overlap at least partially and have aligned bins. Only bins\\n\");\n printf(\" in the 1st input file with a height >= t1 are considered (so if\\n\");\n printf(\" negative, everything should be included. t2 is the theshold for\\n\");\n printf(\" the 2nd file, while t3 is that for the sum of heights of the\\n\");\n printf(\" two histograms. Specifying t2 and t3 is optional. The optional\\n\");\n printf(\" 3rd column is the std. dev. on each bin, which is set to zero\\n\");\n printf(\" for bins outside the covered range of the histograms, and the\\n\");\n printf(\" height is set to zero as well. With only two columns, the\\n\");\n printf(\" chi-square test is unweighted, i.e. each bin has an equal\\n\");\n printf(\" weight (set to 1) regardless of the height of the bin(s).\\n\");\n printf(\" Examples: \\n\");\n printf(\" pstat -chi2hist \\\"-1 -1 0.1\\\" -col1 \\\"1 2\\\" -col2 \\\"1 2\\\" file1 file2\\n\");\n printf(\" pstat -chi2hist -1 -col1 \\\"1 2 3\\\" -col2 \\\"1 2 3\\\" file1 file2\\n\");\n printf(\"-chi2cdf This test is similar to -chi2hist, except that the inputs are\\n\");\n printf(\" not histograms, but the distribution of points itself (i.e. one\\n\");\n printf(\" column). This test therefore does not depend on binning. The\\n\");\n printf(\" vertical difference in their CDF is quantified with an non-\\n\");\n printf(\" weighted chi-square test (weights are set to 1). This is done\\n\");\n printf(\" for each point in the CDF of the shortest distribution and\\n\");\n printf(\" using a linear interpolation of the other. This test can be\\n\");\n printf(\" useful to decide which model distribution fits an observed\\n\");\n printf(\" distribution best, but the chi square itself is not immediately\\n\");\n printf(\" meaningful. Example: pstat -chi2cdf file1 file2\\n\");\n printf(\"-correl Produces the cross correlation function (as function of lag)\\n\");\n printf(\" calculated in the Fourier domain assuming equal sampling.\\n\");\n printf(\" Examples: pstat -correl -col1 1 -col2 1 file1 file2\\n\");\n printf(\" or: pstat -correl -col \\\"1 2\\\" file1\\n\");\n printf(\"-ks Kolmogorov-Smirnov test: Assess difference between two\\n\");\n printf(\" distributions of points. The made approximations are similar to\\n\");\n printf(\" the implementation in Numerical Recipes in C, 2nd edition and.\\n\");\n printf(\" does not depend on any binning.\\n\");\n printf(\" Examples: pstat -ks -col1 1 -col2 1 file1 file2\\n\");\n printf(\" or: pstat -ks -col \\\"1 2\\\" file1\\n\");\n printf(\"-ksflat Like -ks, but compare single input distribution with a flat\\n\");\n printf(\" distribution covering the range of input values.\\n\");\n printf(\" Example: pstat -ksflat -col 1 file1\\n\");\n printf(\"-ksflat2 \\\"min max\\\" Like -ksflat, but set the range to the specified values.\\n\");\n printf(\" Example: pstat -ksflat2 \\\"0 1\\\" -col 1 file1\\n\");\n printf(\"-kssin Like -ks, but compare single input distribution with a\\n\");\n printf(\" sinusoidal distribution between 0 and 90 deg.\\n\");\n printf(\" Example: pstat -kssin -col 1 file1\\n\");\n printf(\"-median Compute the median of the distribution.\\n\");\n printf(\" Example: pstat -median -col 1 file1\\n\");\n printf(\"-moments Compute different moments of the distribution (mean, variance\\n\");\n printf(\" etc.)\\n\");\n printf(\" Example: pstat -moments -col 1 file1\\n\");\n printf(\"-pearson Pearson product-moment correlation coefficient:\\n\");\n printf(\" Measures the linear correlation between two variables.\\n\");\n printf(\" Examples: pstat -pearson -col1 1 -col2 1 file1 file2\\n\");\n printf(\" or: pstat -pearson -col \\\"1 2\\\" file1\\n\");\n printf(\"\\n\");\n printCitationInfo();\n terminateApplication(&application);\n return 0;\n }else {\n for(i = 1; i < argc; i++) {\n int index;\n index = i;\n if(processCommandLine(&application, argc, argv, &index)) {\n i = index;\n }else if(strcmp(argv[i], \"-col\") == 0 || strcmp(argv[i], \"-col1\") == 0) {\n int ret;\n ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, \"%d %d %d\", &file1_column1, &file1_column2, &file1_column3, NULL);\n if(ret == 1) {\n file1_column2 = 0;\n file1_column3 = 0;\n }else if(ret == 2) {\n file1_column3 = 0;\n }else if(ret != 3) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot parse '%s' option, 1, 2 or 3 values.\", argv[i]);\n return 0;\n }\n i++;\n }else if(strcmp(argv[i], \"-col2\") == 0) {\n int ret;\n ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, \"%d %d %d\", &file2_column1, &file2_column2, &file2_column3, NULL);\n if(ret == 1) {\n file2_column2 = 0;\n file2_column3 = 0;\n }else if(ret == 2) {\n file2_column3 = 0;\n }else if(ret != 3) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot parse '%s' option, 1, 2 or 3 values.\", argv[i]);\n return 0;\n }\n i++;\n }else if(strcmp(argv[i], \"-skiplines\") == 0) {\n int ret;\n ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, \"%d\", &skiplines, NULL);\n if(ret != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot parse '%s' option, 1 integer value was expected.\", argv[i]);\n return 0;\n }\n i++;\n }else if(strcmp(argv[i], \"-output\") == 0) {\n output_idx = i+1;\n i++;\n }else if(strcmp(argv[i], \"-correl\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = CORREL;\n }else if(strcasecmp(argv[i], \"-pearson\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = PEARSON;\n }else if(strcmp(argv[i], \"-ks\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = KSTEST;\n }else if(strcmp(argv[i], \"-ksflat\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = KSFLAT;\n }else if(strcmp(argv[i], \"-ksflat2\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n int ret;\n ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, \"%lf %lf\", &ksflat_min, &ksflat_max, NULL);\n if(ret != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot parse '%s' option, 2 values were expected.\", argv[i]);\n return 0;\n }\n typetest = KSFLAT_WITH_MINMAX;\n i++;\n }else if(strcmp(argv[i], \"-moments\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = MOMENTS;\n }else if(strcmp(argv[i], \"-median\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = MEDIAN;\n }else if(strcmp(argv[i], \"-kssin\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = KSSIN;\n }else if(strcmp(argv[i], \"-chi2hist\") == 0) {\n int ret;\n ret = parse_command_string(application.verbose_state, argc, argv, i+1, 0, 1, \"%lf %lf %lf\", &threshold1, &threshold2, &threshold3, NULL);\n if(ret == 1) {\n threshold2 = threshold3 = -1;\n }else if(ret == 2) {\n threshold3 = -1;\n }else if(ret != 3) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot parse '%s' option, 1, 2 or 3 values.\", argv[i]);\n return 0;\n }\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = CHI2TEST_HIST;\n i++;\n }else if(strcmp(argv[i], \"-chi2cdf\") == 0) {\n if(typetest != 0) {\n printerror(application.verbose_state.debug, \"pstat: Cannot specify more than one type of statistical test at the time\");\n return 0;\n }\n typetest = CHI2TEST_CDF;\n }else if(strcmp(argv[i], \"-log\") == 0) {\n read_log = 1;\n }else {\n if(argv[i][0] == '-') {\n printerror(application.verbose_state.debug, \"pstat: Unknown option: %s\\n\\nRun pstat without command line arguments to show help\", argv[i]);\n terminateApplication(&application);\n return 0;\n }else {\n if(applicationAddFilename(i, application.verbose_state) == 0)\n return 0;\n }\n }\n }\n }\n if(applicationFilenameList_checkConsecutive(argv, application.verbose_state) == 0) {\n return 0;\n }\n {\n int nrInputFiles;\n int nrInputColumns;\n nrInputFiles = numberInApplicationFilenameList(&application, argv, application.verbose_state);\n if(nrInputFiles < 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: No files specified\");\n return 0;\n }\n if(nrInputFiles > 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot specify more than two input files. %d input files are currently specified.\", nrInputFiles);\n if(application.verbose_state.debug) {\n printerror(0, \" These are:\");\n char *filename_ptr;\n for(i = 0; i < nrInputFiles; i++) {\n filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state);\n if(filename_ptr != NULL) {\n printerror(0, \" %s\", filename_ptr);\n }\n }\n }\n return 0;\n }\n if(file1_column1 == 0) {\n {\n printwarning(application.verbose_state.debug, \"WARNING pstat: No -col1 option. Using the default (-col1 1).\");\n file1_column1 = 1;\n file1_column2 = 0;\n file1_column3 = 0;\n }\n }\n if(nrInputFiles == 2 && file2_column1 == 0) {\n {\n printwarning(application.verbose_state.debug, \"WARNING pstat: No -col2 option, while there are two input files. Default is -col2 1.\");\n file2_column1 = 1;\n file2_column2 = 0;\n file2_column3 = 0;\n }\n }\n if(file2_column1 && nrInputFiles != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: -col2 option suggest that there should be two input files, but there is only %d defined on command line.\", nrInputFiles);\n return 0;\n }\n nrInputColumns = 0;\n if(file1_column1)\n nrInputColumns++;\n if(file1_column2)\n nrInputColumns++;\n if(file1_column3)\n nrInputColumns++;\n if(file2_column1)\n nrInputColumns++;\n if(file2_column2)\n nrInputColumns++;\n if(file2_column3)\n nrInputColumns++;\n if(typetest == KSTEST) {\n if(nrInputColumns != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test requires two columns of data to be read in. Example: pstat -ks -col1 1 -col2 1 file1 file2 or pstat -ks -col \\\"1 2\\\" file1\");\n return 0;\n }\n }else if(typetest == CORREL) {\n if(nrInputColumns != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Correlation requires two columns of data to be read in. Example: pstat -correl -col1 1 -col2 1 file1 file2 or pstat -correl -col \\\"1 2\\\" file1\");\n return 0;\n }\n }else if(typetest == PEARSON) {\n if(nrInputColumns != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Correlation requires two columns of data to be read in. Example: pstat -pearson -col1 1 -col2 1 file1 file2 or pstat -pearson -col \\\"1 2\\\" file1\");\n return 0;\n }\n }else if(typetest == MOMENTS) {\n if(nrInputColumns != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Computation of the moments of a distribution requires one columns of data to be read in. Example: pstat -moments -col 1 file1\");\n return 0;\n }\n }else if(typetest == MEDIAN) {\n if(nrInputColumns != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Computation of the median of a distribution requires one columns of data to be read in. Example: pstat -median -col 1 file1\");\n return 0;\n }\n }else if(typetest == KSFLAT) {\n if(nrInputColumns != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test comparison with a flat distribution requires one columns of data to be read in. Example: pstat -ksflat -col 1 file1\");\n return 0;\n }\n }else if(typetest == KSFLAT_WITH_MINMAX) {\n if(nrInputColumns != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test comparison with a flat distribution requires one columns of data to be read in. Example: pstat -ksflat2 \\\"0 1\\\" -col 1 file1\");\n return 0;\n }\n }else if(typetest == KSSIN) {\n if(nrInputColumns != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test comparison with a sinusoidal distribution requires one columns of data to be read in. Example: pstat -kssin -col 1 file1\");\n return 0;\n }\n }else if(typetest == CHI2TEST_HIST) {\n if(nrInputColumns != 4 && nrInputColumns != 6) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The chi-square histogram test requires four or six columns of data to be read in. Examples: pstat -chi2hist -1 -col1 \\\"1 2\\\" -col2 \\\"1 2\\\" file1 file2 or pstat -chi2hist -1 -col1 \\\"1 2 3\\\" -col2 \\\"1 2 3\\\" file1 file2\");\n return 0;\n }\n }else if(typetest == CHI2TEST_CDF) {\n if(nrInputColumns != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The chi-square CDF test requires two columns of data to be read in. Examples: pstat -chi2cdf -col1 1 -col2 1 file1 file2 or pstat -chi2cdf -col1 \\\"1 2\\\" file1\");\n return 0;\n }\n }else {\n printerror(application.verbose_state.debug, \"ERROR pstat: No statistical test has been specified, nothing to do.\");\n return 0;\n }\n }\n char *filename_ptr;\n double *input_array[6];\n long number_values[6];\n int number_input_arrays;\n number_input_arrays = 0;\n number_values[0] = 0;\n filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state);\n if(filename_ptr == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Bug!\");\n return 0;\n }\n if(file1_column1) {\n double min_x, max_x, avrg;\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file1_column1, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: cannot load file.\\n\");\n return 0;\n }\n number_input_arrays++;\n }\n if(file1_column2) {\n double min_x, max_x, avrg;\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file1_column2, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: cannot load file.\\n\");\n return 0;\n }\n number_input_arrays++;\n }\n if(file1_column3) {\n double min_x, max_x, avrg;\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file1_column3, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: cannot load file.\\n\");\n return 0;\n }\n number_input_arrays++;\n }\n if(file2_column1 || file2_column2 || file2_column3) {\n filename_ptr = getNextFilenameFromList(&application, argv, application.verbose_state);\n if(filename_ptr == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Bug!\");\n return 0;\n }\n }\n if(file2_column1) {\n double min_x, max_x, avrg;\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file2_column1, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: cannot load file.\\n\");\n return 0;\n }\n number_input_arrays++;\n }\n if(file2_column2) {\n double min_x, max_x, avrg;\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file2_column2, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: cannot load file.\\n\");\n return 0;\n }\n number_input_arrays++;\n }\n if(file2_column3) {\n double min_x, max_x, avrg;\n if(read_ascii_column_double(filename_ptr, skiplines, '#', -1, 1, &number_values[number_input_arrays], file2_column3, 1.0, read_log, &input_array[number_input_arrays], &min_x, &max_x, &avrg, application.verbose_state, 0) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: cannot load file.\\n\");\n return 0;\n }\n number_input_arrays++;\n }\n FILE *fout;\n if(output_idx) {\n fout = fopen(argv[output_idx], \"w\");\n if(fout == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cannot open %s\", argv[output_idx]);\n return 0;\n }\n }else {\n fout = stdout;\n }\n if(typetest == KSTEST) {\n double max_diff, prob;\n if(number_input_arrays != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test requires two input arrays to be specified\");\n return 0;\n }\n kstest(input_array[0], number_values[0], input_array[1], number_values[1], 0, 0, 0, NULL, &max_diff, &prob, application.verbose_state);\n if(application.verbose_state.verbose == 0) {\n fprintf(fout, \"probability = %e\\n\", prob);\n }\n }else if(typetest == KSFLAT) {\n double max_diff, prob;\n if(number_input_arrays != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test comparison with a flat distribution requires one input array to be specified\");\n return 0;\n }\n kstest(input_array[0], number_values[0], NULL, 0, 1, 0, 0, NULL, &max_diff, &prob, application.verbose_state);\n if(application.verbose_state.verbose == 0) {\n fprintf(fout, \"probability = %e\\n\", prob);\n }\n }else if(typetest == KSFLAT_WITH_MINMAX) {\n double max_diff, prob;\n if(number_input_arrays != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test comparison with a flat distribution requires one input array to be specified\");\n return 0;\n }\n kstest(input_array[0], number_values[0], NULL, 0, 3, ksflat_min, ksflat_max, NULL, &max_diff, &prob, application.verbose_state);\n if(application.verbose_state.verbose == 0) {\n fprintf(fout, \"probability = %e\\n\", prob);\n }\n }else if(typetest == KSSIN) {\n double max_diff, prob;\n if(number_input_arrays != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: KS-test comparison with a sinusoidal distribution requires one input array to be specified\");\n return 0;\n }\n kstest(input_array[0], number_values[0], NULL, 0, 2, 0, 0, NULL, &max_diff, &prob, application.verbose_state);\n if(application.verbose_state.verbose == 0) {\n fprintf(fout, \"probability = %e\\n\", prob);\n }\n }else if(typetest == MOMENTS) {\n double mean, variance, skew, kurt;\n if(number_input_arrays != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Computation of the moments of a distribution requires one columns of data to be read in.\");\n return 0;\n }\n mean = gsl_stats_mean(input_array[0], 1, number_values[0]);\n fprintf(fout, \"Mean = %e\\n\", mean);\n variance = gsl_stats_variance_m(input_array[0], 1, number_values[0], mean);\n fprintf(fout, \"Variance = %e (unbiased, normalised by 1/(N-1))\\n\", variance);\n fprintf(fout, \"Standard deviation = %e (unbiased, normalised by 1/(N-1))\\n\", sqrt(variance));\n variance *= (number_values[0]-1.0)/(double)number_values[0];\n fprintf(fout, \"Variance = %e (normalised by 1/N)\\n\", variance);\n fprintf(fout, \"Standard deviation = %e (normalised by 1/N)\\n\", sqrt(variance));\n skew = gsl_stats_skew(input_array[0], 1, number_values[0]);\n fprintf(fout, \"Skewness = %e\\n\", skew);\n kurt = gsl_stats_kurtosis(input_array[0], 1, number_values[0]);\n fprintf(fout, \"Kurtosis = %e\\n\", kurt);\n }else if(typetest == MEDIAN) {\n double median;\n if(number_input_arrays != 1) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Computation of the moments of a distribution requires one columns of data to be read in.\");\n return 0;\n }\n gsl_sort(input_array[0], 1, number_values[0]);\n median = gsl_stats_median_from_sorted_data(input_array[0], 1, number_values[0]);\n fprintf(fout, \"Median = %e\\n\", median);\n }else if(typetest == PEARSON) {\n double cc;\n if(number_input_arrays != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Correlation requires two input arrays to be specified\");\n return 0;\n }\n if(number_values[0] != number_values[1]) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Correlation requires two input arrays of equal length\");\n return 0;\n }\n#if GSL_VERSION_NUMBER >= 110\n cc = gsl_stats_correlation(input_array[0], 1, input_array[1], 1, number_values[0]);\n fprintf(fout, \"Pearson correlation coefficient = %e\\n\", cc);\n#else\n printerror(application.verbose_state.debug, \"ERROR pstat: Pearson correlation coefficient cannot be calculated if GSL < 1.10\");\n return 0;\n#endif\n }else if(typetest == CORREL) {\n if(number_input_arrays != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Correlation requires two input arrays to be specified\");\n return 0;\n }\n if(number_values[0] != number_values[1]) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Correlation requires two input arrays of equal length\");\n return 0;\n }\n if(number_values[0] > 2147483646) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Input array too long.\");\n return 0;\n }\n float *x1, *y1;\n x1 = malloc(number_values[0]*sizeof(float));\n y1 = malloc(number_values[1]*sizeof(float));\n if(x1 == NULL || y1 == NULL) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Memory allocation error\");\n return 0;\n }\n for(i = 0; i < number_values[0]; i++)\n x1[i] = (input_array[0])[i];\n for(i = 0; i < number_values[1]; i++)\n y1[i] = (input_array[1])[i];\n int extrazeropad, cc_length;\n float *ans;\n extrazeropad = 0;\n if(crosscorrelation_fft_padding(x1, y1, number_values[0], extrazeropad, &ans, &cc_length, application.verbose_state) == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Cross correlation failed.\");\n return 0;\n }\n free(x1);\n free(y1);\n int lagoutput;\n lagoutput = 1;\n if(lagoutput == 0) {\n for(i = 0; i < cc_length; i++)\n fprintf(fout, \"%ld %e\\n\", i, ans[i]);\n }else {\n for(i = cc_length/2; i <= cc_length-1; i++)\n fprintf(fout, \"%ld %e\\n\", i-cc_length, ans[i]);\n for(i = 0; i < cc_length/2; i++)\n fprintf(fout, \"%ld %e\\n\", i, ans[i]);\n }\n free(ans);\n }else if(typetest == CHI2TEST_HIST) {\n double binwidth, ratio, offset, chi2;\n long offset_binnr, file2_x_col, dof, i2, nr_overlapping_bins;\n if(number_input_arrays != 4 && number_input_arrays != 6) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The chi-square histogram test requires four or six columns of data to be specified.\");\n return 0;\n }\n if(number_input_arrays == 4) {\n file2_x_col = 2;\n printwarning(application.verbose_state.debug, \"WARNING pstat: Since no column numbers with error-bars are provided, uniform weighting of the different bins is assumed with sigma=1. This is unlikely to be correct.\");\n }else {\n file2_x_col = 3;\n }\n binwidth = (input_array[0])[1] - (input_array[0])[0];\n ratio = binwidth/((input_array[file2_x_col])[1] - (input_array[file2_x_col])[0]);\n if(application.verbose_state.verbose) {\n printf(\"Ratio bin widths of two histograms is %lf (should be very close to 1)\\n\", binwidth);\n }\n if(ratio < 0.999 || ratio > 1.001) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The binwidths of the two histograms appear to be different (%e != %e).\", (input_array[0])[1] - (input_array[0])[0], (input_array[file2_x_col])[1] - (input_array[file2_x_col])[0]);\n return 0;\n }\n offset = (input_array[file2_x_col])[0];\n offset -= (input_array[0])[0];\n offset /= binwidth;\n if(application.verbose_state.verbose) {\n printf(\"Offset between two histograms is %lf bins (should be very close to an integer value)\\n\", offset);\n }\n offset_binnr = round(offset);\n offset = fabs(offset - offset_binnr);\n if(offset > 0.001) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The bins of the two histograms do not appear to be aligned, but have an offset of %lf.\", offset);\n return 0;\n }\n double height1, height2;\n height1 = 0;\n height2 = 0;\n for(i = 0; i < number_values[0]; i++)\n height1 += (input_array[1])[i];\n for(i = 0; i < number_values[file2_x_col]; i++)\n height2 += (input_array[file2_x_col+1])[i];\n if(application.verbose_state.verbose) {\n printf(\"Ratio of integrals of two histograms is %lf (should be very close to 1)\\n\", height1/height2);\n }\n if(height1/height2 > 1.001 || height2/height1 > 1.001) {\n printwarning(application.verbose_state.debug, \"WARNING pstat: The two histograms appear to be normalised differently, so the derived numbers are unlikely to give useful results.\");\n }\n chi2 = 0;\n dof = 0;\n nr_overlapping_bins = 0;\n for(i = -labs(offset_binnr)-10; i < number_values[0]+labs(offset_binnr)+10; i++) {\n int hist1_exist, hist2_exist;\n hist1_exist = hist2_exist = 0;\n if(i >= 0 && i < number_values[0]) {\n height1 = (input_array[1])[i];\n hist1_exist = 1;\n }else {\n height1 = 0;\n }\n i2 = i - offset_binnr;\n if(i2 >= 0 && i2 < number_values[file2_x_col]) {\n height2 = (input_array[file2_x_col+1])[i2];\n hist2_exist = 1;\n if(hist1_exist) {\n offset = (input_array[file2_x_col])[i2];\n offset -= (input_array[0])[i];\n offset /= binwidth;\n if(fabs(offset) > 0.001) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The bins of the two histograms do not appear to be aligned, but bins %ld and %ld have an offset of %lf.\", i+1, i2+1, offset);\n return 0;\n }\n nr_overlapping_bins++;\n }\n }else {\n height2 = 0;\n }\n if(hist1_exist || hist2_exist) {\n if(height1 >= threshold1 && height2 >= threshold2 && (height1+height2) >= threshold3) {\n double delta_y, var;\n delta_y = height2 - height1;\n if(number_input_arrays == 4) {\n chi2 += delta_y*delta_y;\n dof++;\n }else {\n var = 0;\n if(hist1_exist)\n var += (input_array[2])[i] * (input_array[2])[i];\n if(hist2_exist)\n var += (input_array[file2_x_col+2])[i2] * (input_array[file2_x_col+2])[i2];\n chi2 += delta_y*delta_y/var;\n dof++;\n }\n }\n }\n }\n if(nr_overlapping_bins == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: There appears to be no overlap between the two histograms.\");\n return 0;\n }\n if(application.verbose_state.verbose) {\n printf(\"Number of overlapping bins between two distributions: %ld\\n\", nr_overlapping_bins);\n printf(\"Total number of bins considered with specified threshold: %ld\\n\", dof);\n }\n if(number_input_arrays != 6)\n fprintf(fout, \"Total non-weighted chi square: %f = %e\\n\", chi2, chi2);\n else if(application.verbose_state.verbose)\n fprintf(fout, \"Total chi square: %f = %e\\n\", chi2, chi2);\n if(number_input_arrays == 6) {\n fprintf(fout, \"Reduced chi square: %f = %e\\n\", chi2/(double)dof, chi2/(double)dof);\n }\n }else if(typetest == CHI2TEST_CDF) {\n double x1, cdf1, cdf2, chi2;\n long start2, dof;\n if(number_input_arrays != 2) {\n printerror(application.verbose_state.debug, \"ERROR pstat: The chi-square CDF test requires two columns of data to be specified.\");\n return 0;\n }\n if(number_values[0] > number_values[1]) {\n i = number_values[0];\n number_values[0] = number_values[1];\n number_values[1] = i;\n input_array[2] = input_array[0];\n input_array[0] = input_array[1];\n input_array[1] = input_array[2];\n }\n gsl_sort(input_array[0], 1, number_values[0]);\n gsl_sort(input_array[1], 1, number_values[1]);\n start2 = 0;\n chi2 = 0;\n dof = 0;\n for(i = 0; i < number_values[0] - 1; i++) {\n cdf1 = (i+1)/(double)number_values[0];\n x1 = (input_array[0])[i] + 0.5*((input_array[0])[i+1]-(input_array[0])[i]);\n if(application.verbose_state.debug)\n printf(\"Going to find chi2 of observation distribution cdf point: (%e, %e)\\n\", x1, cdf1);\n if(x1 <= (input_array[1])[0]) {\n if(application.verbose_state.debug)\n printf(\" model cdf starts after point of interest\\n\");\n cdf2 = 0;\n if(x1 == (input_array[1])[0]) {\n cdf2 = (j+0.5)/(double)number_values[1];\n }\n }else if(x1 >= (input_array[1])[number_values[1]-1]) {\n if(application.verbose_state.debug)\n printf(\" model cdf ends before point of interest\\n\");\n cdf2 = 1;\n if(x1 == (input_array[1])[number_values[1]-1]) {\n cdf2 = (number_values[1]-1 +0.5)/(double)number_values[1];\n }\n }else {\n for(j = start2; j < number_values[1]; j++) {\n if((input_array[1])[j] >= x1) {\n if(application.verbose_state.debug)\n printf(\" First model cdf point after point of interest: (%e %e)\\n\", (input_array[1])[j], (j+1)/(double)number_values[1]);\n long index1, index2;\n index1 = j-1;\n index2 = j;\n if(j == 0) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Bug!\\n\");\n return 0;\n }\n while((input_array[1])[index2] == (input_array[1])[index1]) {\n if(index2 < number_values[1] - 1) {\n index2++;\n }else if(index1 > 1) {\n index1--;\n }else {\n printerror(application.verbose_state.debug, \"ERROR pstat: Something is wrong with the second input distribution, as all input values appear to be identical.\\n\");\n return 0;\n }\n }\n if(application.verbose_state.debug)\n printf(\" Going to interpolate following model points: (%e %e) and (%e %e)\\n\", (input_array[1])[index1], (index1+1-0.5)/(double)number_values[1], (input_array[1])[index2], (index2+1-0.5)/(double)number_values[1]);\n if(index1 < 0 || index2 >= number_values[1]) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Interpolation failed - trying to access second array out of limits (index1=%ld, index2=%ld).\\n\", index1, index2);\n return 0;\n }\n cdf2 = ((index2+1-0.5)/(double)number_values[1] - (index1+1-0.5)/(double)number_values[1]) * (x1 - (input_array[1])[index1]) / ((input_array[1])[index2] - (input_array[1])[index1]) + (index1+1-0.5)/(double)number_values[1];\n if(!isfinite(cdf2)) {\n printerror(application.verbose_state.debug, \"ERROR pstat: Interpolation failed: i=%ld, j=%ld (array2=[%e, %e, %e]), \\n\", i, j, (input_array[1])[j-1], (input_array[1])[j], (input_array[1])[j+1]);\n return 0;\n }\n start2 = j - 2;\n if(start2 < 0)\n start2 = 0;\n break;\n }\n }\n }\n chi2 += (cdf2-cdf1)*(cdf2-cdf1);\n dof++;\n if(application.verbose_state.debug) {\n printf(\" cdf2=%e, cdf1=%e, diff=%e\\n\", cdf2, cdf1, (cdf2-cdf1));\n printf(\" new chi2 = %e\\n\", chi2);\n }\n }\n if(application.verbose_state.verbose) {\n printf(\"\\nTotal number of bins considered: %ld\\n\", dof);\n }\n fprintf(fout, \"Non-weighted total chi square = %f = %e\\n\", chi2, chi2);\n }else {\n printerror(application.verbose_state.debug, \"ERROR pstat: Bug!\");\n return 0;\n }\n if(output_idx) {\n fclose(fout);\n }\n for(i = 0; i < number_input_arrays; i++) {\n free(input_array[i]);\n }\n terminateApplication(&application);\n return 0;\n}\n", "meta": {"hexsha": "e9b2fa25a05b1083c2d649bf7e63b97b95b48e83", "size": 36717, "ext": "c", "lang": "C", "max_stars_repo_path": "src/prog/pstat.c", "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/prog/pstat.c", "max_issues_repo_name": "David-McKenna/psrsalsa", "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/prog/pstat.c", "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2430730479, "max_line_length": 755, "alphanum_fraction": 0.6525587602, "num_tokens": 10155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.2821662430492542}} {"text": "#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#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/GRS.c\"\n#include \"like_grs.c\"\n\n\ndouble log_like_wrapper(input_cosmo_params ic, input_nuisance_params_grs in);\n\ndouble log_like_wrapper(input_cosmo_params ic, input_nuisance_params_grs in)\n{\n\t// printf(\"%le %le %le %le %le %le %le\\n\",ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0);\n\t// printf(\"%le %le %le %le %le %le %le\\n\",in.grsbias[0], in.grsbias[1], in.grsbias[2], in.grsbias[3],in.grsbias[4], in.grsbias[5], in.grsbias[6]);\n\t//printf(\"%le %le %le %le %le %le %le %le %le %le\\n\",in.grssigmap[0], in.grssigmap[1], in.grssigmap[2], in.grssigmap[3], in.grssigmap[4], in.grssigmap[5], in.grssigmap[6],in.grssigmaz, in.grspshot, in.grskstar);\n double like = log_like_GRS(ic.omega_m, ic.sigma_8, ic.n_s, ic.w0, ic.wa, ic.omega_b, ic.h0, ic.MGSigma, ic.MGmu,in.grsbias[0], in.grsbias[1], in.grsbias[2], in.grsbias[3],in.grsbias[4], in.grsbias[5], in.grsbias[6], in.grssigmap[0], in.grssigmap[1], in.grssigmap[2], in.grssigmap[3], in.grssigmap[4], in.grssigmap[5], in.grssigmap[6],in.grssigmaz, in.grspshot, in.grskstar);\n \n return like;\n}\n\nint main(void){\n\tdouble res;\n\tinit_GRS();\n\tres=log_like_GRS(0.3156,0.831,0.9645,-1.0,0.0,0.0491685,0.6727,0.0,0.0,1.538026692020565,1.862707210288686,2.213131761595241,2.617023657038295,2.975011712138650,3.376705680190931,3.725882076395691,290.,290.,290.,290.,290.,290.,290.,0.001,0.0,0.24);\n\tprintf(\"loglike=%le\\n\",res);\n\tres=log_like_GRS(0.2325384451023471,1.0310887691615935,0.8595022066924793, -1.137588053600136, 0.14993639190238117, 0.05165678142188447, 0.8247432633482439,0.0,0.0,1.538026692020565,1.862707210288686,2.213131761595241,2.617023657038295,2.975011712138650,3.376705680190931,3.725882076395691,290.,290.,290.,290.,290.,290.,290.,0.001,0.0,0.24);\n\tprintf(\"loglike=%le\\n\",res);\nreturn 0;\n}\t\n\n//\tdouble log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, \n//\tdouble B1, double B2, double B3, double B4, double B5, double B6, double B7, \n//\t double SIGMAP1, double SIGMAP2, double SIGMAP3, double SIGMAP4, double SIGMAP5, double SIGMAP6, double SIGMAP7,\n//\t double SIGMAZ, double PSHOT, double KSTAR)\n\n// \tlog_multi_like(0.315,0.831,0.965,-1.0,0.0,0.049,0.673,1.19,1.30,1.44,1.57,1.70,1.82,1.93,290.,290.,290.,290.,290.,290.,290.,0.001,0.0,0.094);\n// \tdouble dk, dmu, *k, *mu, *data, *variance;\n// \tint i;\n// \tk = create_double_vector(0,GRS.N_k-1);\n// \tmu = create_double_vector(0,GRS.N_mu-1);\n// \tdata = create_double_vector(0,GRS.N_z*GRS.N_k*GRS.N_mu-1);\n// \tvariance = create_double_vector(0,GRS.N_z*GRS.N_k*GRS.N_mu-1);\n// \tdk = (GRS.k_max-GRS.k_min)/GRS.N_k;\n// \tdmu= 1./GRS.N_mu;\n// \tfor (i =0; i < GRS.N_k; i++){\n// \t\t// use linear spacing in k!\n// \t\tk[i] = GRS.k_min +(i+0.5)*dk;\n// \t}\n// \tfor (i =0; i < GRS.N_mu; i++){\n// \t\t// use linear spacing in mu!\n// \t\tmu[i] = (i+0.5)*dmu;\n// \t}\n// \tset_data_GRS(k,mu,data);\n// \tset_variance_GRS(k,mu, dk, dmu, variance);\n// \treturn 0;\n// }\n\n/*int main(void){\n\tset_cosmological_parameters_to_Planck_WP();\n\tinit_GRS_single_zbin(0.16,0.4);\n\tdouble z;\n\tGRS_gal.b_g[0] = 1.0;\n\tfor (z = 0.1; z < 2.5; z+=0.05){\n\t\tGRS.z[0] = z;\n\t\tprintf(\"%.3f %e %e %e\\n\", z, 1./P_obs(0.14,0.6,0), 1./P_obs(0.5,0.6,0),1./P_obs(1.0,0.6,0));\n\t}\n\treturn 0;\n}\n*/", "meta": {"hexsha": "b86062c013fe3cca64eca84f4604c1e09cb08144", "size": 4512, "ext": "c", "lang": "C", "max_stars_repo_path": "like_grs_only.c", "max_stars_repo_name": "CosmoLike/WFIRST_forecasts", "max_stars_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-21T00:36:40.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-21T00:36:40.000Z", "max_issues_repo_path": "like_grs_only.c", "max_issues_repo_name": "CosmoLike/WFIRST_forecasts", "max_issues_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "like_grs_only.c", "max_forks_repo_name": "CosmoLike/WFIRST_forecasts", "max_forks_repo_head_hexsha": "aa65774dc1870450723b0a13449681e37d0f979c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5660377358, "max_line_length": 376, "alphanum_fraction": 0.6981382979, "num_tokens": 1802, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6926419704455589, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.28213620883610224}} {"text": "static char help[] = \"Example ablateCore Client using incompressible flow\";\n\n/** Example Argumetns\n -dm_plex_separate_marker -dm_refine 0 \\\n -vel_petscspace_degree 2 -pres_petscspace_degree 1 -temp_petscspace_degree 1 \\\n -dmts_check .001 -ts_max_steps 4 -ts_dt 0.1 \\\n -ksp_type fgmres -ksp_gmres_restart 10 -ksp_rtol 1.0e-9 -ksp_error_if_not_converged \\\n -pc_type fieldsplit -pc_fieldsplit_0_fields 0,2 -pc_fieldsplit_1_fields 1 -pc_fieldsplit_type schur -pc_fieldsplit_schur_factorization_type full \\\n -fieldsplit_0_pc_type lu \\\n -fieldsplit_pressure_ksp_rtol 1e-10 -fieldsplit_pressure_pc_type jacobi\n */\n\n#include \n#include \"flow.h\"\n#include \"incompressibleFlow.h\"\n#include \"mesh.h\"\n\ntypedef PetscErrorCode (*ExactFunction)(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);\n\ntypedef void (*IntegrandTestFunction)(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt *uOff, const PetscInt *uOff_x, const PetscScalar *u, const PetscScalar *u_t, const PetscScalar *u_x,\n const PetscInt *aOff, const PetscInt *aOff_x, const PetscScalar *a, const PetscScalar *a_t, const PetscScalar *a_x, PetscReal t, const PetscReal *X,\n PetscInt numConstants, const PetscScalar *constants, PetscScalar *f0);\n\n#define SourceFunction(FUNC) \\\n FUNC(PetscInt dim, \\\n PetscInt Nf, \\\n PetscInt NfAux, \\\n const PetscInt uOff[], \\\n const PetscInt uOff_x[], \\\n const PetscScalar u[], \\\n const PetscScalar u_t[], \\\n const PetscScalar u_x[], \\\n const PetscInt aOff[], \\\n const PetscInt aOff_x[], \\\n const PetscScalar a[], \\\n const PetscScalar a_t[], \\\n const PetscScalar a_x[], \\\n PetscReal t, \\\n const PetscReal X[], \\\n PetscInt numConstants, \\\n const PetscScalar constants[], \\\n PetscScalar f0[])\n\n// store the pointer to the provided test function from the solver\nstatic IntegrandTestFunction f0_v_original;\nstatic IntegrandTestFunction f0_w_original;\nstatic IntegrandTestFunction f0_q_original;\n\nstatic PetscErrorCode SetInitialConditions(TS ts, Vec u) {\n DM dm;\n PetscReal t;\n PetscErrorCode ierr;\n\n PetscFunctionBegin;\n ierr = TSGetDM(ts, &dm);\n CHKERRQ(ierr);\n ierr = TSGetTime(ts, &t);\n CHKERRQ(ierr);\n\n // This function Tags the u vector as the exact solution. We need to copy the values to prevent this.\n Vec e;\n ierr = VecDuplicate(u, &e);\n CHKERRQ(ierr);\n ierr = DMComputeExactSolution(dm, t, e, NULL);\n CHKERRQ(ierr);\n ierr = VecCopy(e, u);\n CHKERRQ(ierr);\n ierr = VecDestroy(&e);\n CHKERRQ(ierr);\n\n // get the flow to apply the completeFlowInitialization method\n ierr = IncompressibleFlow_CompleteFlowInitialization(dm, u);\n CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\nstatic PetscErrorCode MonitorError(TS ts, PetscInt step, PetscReal crtime, Vec u, void *ctx) {\n PetscErrorCode (*exactFuncs[3])(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);\n void *ctxs[3];\n DM dm;\n PetscDS ds;\n Vec v;\n PetscReal ferrors[3];\n PetscInt f;\n PetscErrorCode ierr;\n\n PetscFunctionBeginUser;\n ierr = TSGetDM(ts, &dm);\n CHKERRQ(ierr);\n ierr = DMGetDS(dm, &ds);\n CHKERRQ(ierr);\n\n ierr = VecViewFromOptions(u, NULL, \"-vec_view_monitor\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n for (f = 0; f < 3; ++f) {\n ierr = PetscDSGetExactSolution(ds, f, &exactFuncs[f], &ctxs[f]);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n }\n ierr = DMComputeL2FieldDiff(dm, crtime, exactFuncs, ctxs, u, ferrors);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscPrintf(PETSC_COMM_WORLD, \"Timestep: %04d time = %-8.4g \\t L_2 Error: [%2.3g, %2.3g, %2.3g]\\n\", (int)step, (double)crtime, (double)ferrors[0], (double)ferrors[1], (double)ferrors[2]);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n ierr = DMGetGlobalVector(dm, &u);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n // ierr = TSGetSolution(ts, &u);CHKERRABORT(PETSC_COMM_WORLD, ierr);\n // ierr = PetscObjectSetName((PetscObject)u, \"Numerical Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = DMRestoreGlobalVector(dm, &u);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n ierr = DMGetGlobalVector(dm, &v);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n // ierr = VecSet(v, 0.0);CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = DMProjectFunction(dm, 0.0, exactFuncs, ctxs, INSERT_ALL_VALUES, v);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscObjectSetName((PetscObject)v, \"Exact Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = VecViewFromOptions(v, NULL, \"-exact_vec_view\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = DMRestoreGlobalVector(dm, &v);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n PetscFunctionReturn(0);\n}\n\n// helper functions for generated code\nstatic PetscReal Power(PetscReal x, PetscInt exp) { return PetscPowReal(x, exp); }\nstatic PetscReal Cos(PetscReal x) { return PetscCosReal(x); }\nstatic PetscReal Sin(PetscReal x) { return PetscSinReal(x); }\n\n/*\n CASE: incompressible quadratic\n In 2D we use exact solution:\n\n u = t + x^2 + y^2\n v = t + 2x^2 - 2xy\n p = x + y - 1\n T = t + x + y\n so that\n\n \\nabla \\cdot u = 2x - 2x = 0\n\n see docs/content/formulations/incompressibleFlow/solutions/Incompressible_2D_Quadratic_MMS.nb\n*/\nstatic PetscErrorCode incompressible_quadratic_u(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) {\n u[0] = time + X[0] * X[0] + X[1] * X[1];\n u[1] = time + 2.0 * X[0] * X[0] - 2.0 * X[0] * X[1];\n return 0;\n}\nstatic PetscErrorCode incompressible_quadratic_u_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *u, void *ctx) {\n u[0] = 1.0;\n u[1] = 1.0;\n return 0;\n}\n\nstatic PetscErrorCode incompressible_quadratic_p(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *p, void *ctx) {\n p[0] = X[0] + X[1] - 1.0;\n return 0;\n}\n\nstatic PetscErrorCode incompressible_quadratic_T(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) {\n T[0] = time + X[0] + X[1];\n return 0;\n}\nstatic PetscErrorCode incompressible_quadratic_T_t(PetscInt Dim, PetscReal time, const PetscReal *X, PetscInt Nf, PetscScalar *T, void *ctx) {\n T[0] = 1.0;\n return 0;\n}\n\n/* f0_v = du/dt - f */\nstatic void SourceFunction(f0_incompressible_quadratic_v) {\n f0_v_original(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, a_t, a_x, t, X, numConstants, constants, f0);\n const PetscReal rho = 1.0;\n const PetscReal S = constants[STROUHAL];\n const PetscReal mu = constants[MU];\n const PetscReal R = constants[REYNOLDS];\n const PetscReal x = X[0];\n const PetscReal y = X[1];\n\n f0[0] -= 1 - (4. * mu) / R + rho * S + 2 * rho * y * (t + 2 * Power(x, 2) - 2 * x * y) + 2 * rho * x * (t + Power(x, 2) + Power(y, 2));\n f0[1] -= 1 - (4. * mu) / R + rho * S - 2 * rho * x * (t + 2 * Power(x, 2) - 2 * x * y) + rho * (4 * x - 2 * y) * (t + Power(x, 2) + Power(y, 2));\n}\n\n/* f0_w = dT/dt + u.grad(T) - Q */\nstatic void SourceFunction(f0_incompressible_quadratic_w) {\n f0_w_original(dim, Nf, NfAux, uOff, uOff_x, u, u_t, u_x, aOff, aOff_x, a, a_t, a_x, t, X, numConstants, constants, f0);\n\n const PetscReal rho = 1.0;\n const PetscReal S = constants[STROUHAL];\n const PetscReal Cp = constants[CP];\n const PetscReal x = X[0];\n const PetscReal y = X[1];\n\n f0[0] -= Cp * rho * (S + 2 * t + 3 * Power(x, 2) - 2 * x * y + Power(y, 2));\n}\n\nint main(int argc, char *argv[]) {\n DM dm; /* problem definition */\n TS ts; /* timestepper */\n PetscBag parameterBag; /* constant flow parameters */\n FlowData flowData; /* store some of the flow data*/\n PetscReal t;\n PetscErrorCode ierr;\n\n // initialize petsc and mpi\n PetscInitialize(&argc, &argv, NULL, help);\n\n // setup the ts\n ierr = TSCreate(PETSC_COMM_WORLD, &ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = CreateMesh(PETSC_COMM_WORLD, &dm, PETSC_TRUE, 2);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSSetDM(ts, dm);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSSetExactFinalTime(ts, TS_EXACTFINALTIME_MATCHSTEP);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Setup the flow data\n ierr = FlowCreate(&flowData);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // setup problem\n ierr = IncompressibleFlow_SetupDiscretization(flowData, dm);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // get the flow parameters from options\n IncompressibleFlowParameters *flowParameters;\n ierr = IncompressibleFlow_ParametersFromPETScOptions(¶meterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscBagGetData(parameterBag, (void **)&flowParameters);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Start the problem setup\n PetscScalar constants[TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS];\n ierr = IncompressibleFlow_PackParameters(flowParameters, constants);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = IncompressibleFlow_StartProblemSetup(flowData, TOTAL_INCOMPRESSIBLE_FLOW_PARAMETERS, constants);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Override problem with source terms, boundary, and set the exact solution\n {\n PetscDS prob;\n ierr = DMGetDS(dm, &prob);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // V, W Test Function\n IntegrandTestFunction tempFunctionPointer;\n ierr = PetscDSGetResidual(prob, VTEST, &f0_v_original, &tempFunctionPointer);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetResidual(prob, VTEST, f0_incompressible_quadratic_v, tempFunctionPointer);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n ierr = PetscDSGetResidual(prob, WTEST, &f0_w_original, &tempFunctionPointer);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetResidual(prob, WTEST, f0_incompressible_quadratic_w, tempFunctionPointer);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n /* Setup Boundary Conditions */\n PetscInt id;\n id = 3;\n ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"top wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 1;\n ierr =\n PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"bottom wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 2;\n ierr =\n PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"right wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 4;\n ierr =\n PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"left wall velocity\", \"marker\", VEL, 0, NULL, (void (*)(void))incompressible_quadratic_u, (void (*)(void))incompressible_quadratic_u_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 3;\n ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"top wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 1;\n ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"bottom wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 2;\n ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"right wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n id = 4;\n ierr = PetscDSAddBoundary(prob, DM_BC_ESSENTIAL, \"left wall temp\", \"marker\", TEMP, 0, NULL, (void (*)(void))incompressible_quadratic_T, (void (*)(void))incompressible_quadratic_T_t, 1, &id, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Set the exact solution\n ierr = PetscDSSetExactSolution(prob, VEL, incompressible_quadratic_u, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetExactSolution(prob, PRES, incompressible_quadratic_p, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetExactSolution(prob, TEMP, incompressible_quadratic_T, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetExactSolutionTimeDerivative(prob, VEL, incompressible_quadratic_u_t, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetExactSolutionTimeDerivative(prob, PRES, NULL, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscDSSetExactSolutionTimeDerivative(prob, TEMP, incompressible_quadratic_T_t, parameterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n }\n ierr = IncompressibleFlow_CompleteProblemSetup(flowData, ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Name the flow field\n ierr = PetscObjectSetName(((PetscObject)flowData->flowField), \"Numerical Solution\");\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Setup the TS\n ierr = TSSetFromOptions(ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Set initial conditions from the exact solution\n ierr = TSSetComputeInitialCondition(ts, SetInitialConditions);\n CHKERRABORT(PETSC_COMM_WORLD, ierr); /* Must come after SetFromOptions() */\n ierr = SetInitialConditions(ts, flowData->flowField);\n\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSGetTime(ts, &t);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = DMSetOutputSequenceNumber(dm, 0, t);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = DMTSCheckFromOptions(ts, flowData->flowField);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSMonitorSet(ts, MonitorError, NULL, NULL);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n ierr = TSSolve(ts, flowData->flowField);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Compare the actual vs expected values\n ierr = DMTSCheckFromOptions(ts, flowData->flowField);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n\n // Cleanup\n ierr = FlowDestroy(&flowData);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = DMDestroy(&dm);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = TSDestroy(&ts);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n ierr = PetscBagDestroy(¶meterBag);\n CHKERRABORT(PETSC_COMM_WORLD, ierr);\n return PetscFinalize();\n}", "meta": {"hexsha": "cfd4409a18b2d797b4e53b3248b5377a7a4e225b", "size": 15150, "ext": "c", "lang": "C", "max_stars_repo_path": "ablateCoreClient.c", "max_stars_repo_name": "pakserep/ablateClient", "max_stars_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ablateCoreClient.c", "max_issues_repo_name": "pakserep/ablateClient", "max_issues_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ablateCoreClient.c", "max_forks_repo_name": "pakserep/ablateClient", "max_forks_repo_head_hexsha": "c7bb7cf4a4ec706170efd7c06bf8589e30ece47b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.4097421203, "max_line_length": 214, "alphanum_fraction": 0.6755775578, "num_tokens": 4508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.28202905051303323}} {"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_GEMV_H\n#define SRC_RUNTIME_LOCAL_KERNELS_GEMV_H\n\n#include \n#include \n#include \n\n#include \n\n// ****************************************************************************\n// Struct for partial template specialization\n// ****************************************************************************\n\ntemplate\nstruct Gemv {\n static void apply(DTRes *& res, const DTMat * mat, const DTVec * vec, DCTX(ctx)) = delete;\n};\n\n// ****************************************************************************\n// Convenience function\n// ****************************************************************************\n\ntemplate\nvoid gemv(DTRes *& res, const DTMat * mat, const DTVec * vec, DCTX(ctx)) {\n Gemv::apply(res, mat, vec, ctx);\n}\n\n// ****************************************************************************\n// (Partial) template specializations for different data/value types\n// ****************************************************************************\n\n// ----------------------------------------------------------------------------\n// DenseMatrix <- DenseMatrix\n// ----------------------------------------------------------------------------\n\ntemplate<>\nstruct Gemv, DenseMatrix, DenseMatrix> {\n static void apply(DenseMatrix *& res, const DenseMatrix * mat, const DenseMatrix * vec, DCTX(ctx)) {\n const size_t numRows = mat->getNumRows();\n const size_t numCols = mat->getNumCols();\n\n if(res == nullptr)\n res = DataObjectFactory::create>(numCols, 1, false);\n\n cblas_dgemv(CblasRowMajor,\n CblasTrans,\n numRows,\n numCols,\n 1.0,\n mat->getValues(),\n mat->getRowSkip(),\n vec->getValues(),\n vec->getRowSkip(),\n 0.0,\n res->getValues(),\n res->getRowSkip()\n );\n }\n};\n\ntemplate<>\nstruct Gemv, DenseMatrix, DenseMatrix> {\n static void apply(DenseMatrix *& res, const DenseMatrix * mat, const DenseMatrix * vec, DCTX(ctx)) {\n const size_t numRows = mat->getNumRows();\n const size_t numCols = mat->getNumCols();\n\n if(res == nullptr)\n res = DataObjectFactory::create>(numCols, 1, false);\n\n cblas_sgemv(CblasRowMajor,\n CblasTrans,\n numRows,\n numCols,\n 1.0,\n mat->getValues(),\n mat->getRowSkip(),\n vec->getValues(),\n vec->getRowSkip(),\n 0.0,\n res->getValues(),\n res->getRowSkip()\n );\n }\n};\n\n#endif //SRC_RUNTIME_LOCAL_KERNELS_GEMV_H", "meta": {"hexsha": "6ae6c080f3b7adca1c7fe17ef55293e15692166f", "size": 3603, "ext": "h", "lang": "C", "max_stars_repo_path": "src/runtime/local/kernels/Gemv.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/Gemv.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/Gemv.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.3235294118, "max_line_length": 128, "alphanum_fraction": 0.5292811546, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2808657166546231}} {"text": "#include \"../include/paralleltt.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nvoid SSTT_sketch_to_train(sketch* s, tensor_train* tt, int train_ind)\n{\n int head = 0;\n MPI_tensor* ten = s->ten;\n MPI_Comm comm = ten->comm;\n int iscol = s->iscol;\n int flattening = s->flattening;\n\n flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);\n\n // train stuff\n int d = ten->d;\n int n = tt->n[train_ind];\n int r1 = tt->r[train_ind];\n int r2 = tt->r[train_ind + 1];\n double* train = tt->trains[train_ind];\n matrix_tt* train_mat = matrix_tt_wrap(r1 * n, r2, train);\n matrix_tt_fill_zeros(train_mat);\n\n int* op = s->owner_partition;\n int rank = ten->rank;\n\n matrix_tt* train_submat = submatrix(train_mat, 0, 0, 0, 0);\n for (int ii = op[rank]; ii < op[rank+1]; ++ii){\n matrix_tt* X_submat = own_submatrix(s, ii, 0);\n matrix_tt* X_subsubmat = submatrix(X_submat, 0, 0, 0, 0);\n\n flattening_info_f_update(fi, ten, ii);\n\n int i0_train = fi->f_t_index[0];\n int sz = fi->f_t_sizes[0];\n\n int jj_max = 1;\n if (train_ind != 0){\n i0_train = i0_train + r1 * fi->f_t_index[1];\n jj_max = fi->f_t_sizes[1];\n }\n\n for (int jj = 0; jj < jj_max; ++jj){\n submatrix_update(train_submat, i0_train + jj*r1, i0_train + sz + jj*r1, 0, r2);\n submatrix_update(X_subsubmat, jj*sz, (jj+1)*sz, 0, r2);\n matrix_tt_copy_data(train_submat, X_subsubmat);\n }\n\n free(X_submat); X_submat = NULL;\n free(X_subsubmat); X_subsubmat = NULL;\n }\n free(train_submat); train_submat = NULL;\n\n matrix_tt_reshape(r1*n*r2, 1, train_mat); // Reshape so MPI_Allreduce is only called once\n matrix_tt_allreduce(comm, train_mat);\n\n\n flattening_info_free(fi);\n free(train_mat);\n return;\n}\n\nMPI_tensor* SSTT_next_ten_init(MPI_tensor* prev_ten, tensor_train* tt, int train_ind)\n{\n int r2 = tt->r[train_ind + 1];\n\n MPI_Comm comm = prev_ten->comm;\n int rank = prev_ten->rank;\n int size = prev_ten->comm_size;\n int is_first = (train_ind == 0);\n\n int d = (is_first) ? prev_ten->d : prev_ten->d - 1;\n int prev_offset = (is_first) ? 0 : 1;\n int* n = (int*) calloc(d, sizeof(int));\n int* nps = (int*) calloc(d, sizeof(int));\n int Nblocks = 1;\n n[0] = r2;\n nps[0] = 1;\n\n int** partitions = (int**) malloc(d * sizeof(int*));\n partitions[0] = (int*) calloc(2, sizeof(int));\n partitions[0][1] = r2;\n for (int ii = 1; ii < d; ++ii){\n n[ii] = prev_ten->n[prev_offset + ii];\n nps[ii] = prev_ten->nps[prev_offset + ii];\n Nblocks = Nblocks * nps[ii];\n\n partitions[ii] = (int*) calloc(nps[ii]+1, sizeof(int));\n int* partition_ii = partitions[ii];\n int* prev_partition_ii = prev_ten->partitions[prev_offset + ii];\n for (int jj = 0; jj < nps[ii]+1; ++jj){\n partition_ii[jj] = prev_partition_ii[jj];\n }\n }\n\n int** schedule = (int**) calloc(size, sizeof(int*));\n int n_schedule = get_schedule(schedule, nps, d, size);\n int* inverse_schedule = (int*) calloc(Nblocks, sizeof(int));\n for (int ii = 0; ii < size; ++ii){\n int* schedule_ii = schedule[ii];\n for (int jj = 0; jj < n_schedule; ++jj){\n if (schedule_ii[jj] != -1){\n inverse_schedule[schedule_ii[jj]] = ii*n_schedule + jj;\n }\n }\n }\n\n\n long* subtensor_sizes = (long*) malloc(n_schedule * sizeof(long));\n int* t_t_block = (int*) malloc(d*sizeof(int));\n long X_size = 0;\n for (int jj = 0; jj < n_schedule; ++jj){\n\n int t_v_block = schedule[rank][jj];\n\n if (t_v_block != -1){\n subtensor_sizes[jj] = 1;\n to_tensor_ind(t_t_block, t_v_block, nps, d);\n\n for (int kk = 0; kk < d; ++kk){\n subtensor_sizes[jj] = subtensor_sizes[jj] * (partitions[kk][t_t_block[kk]+1] - partitions[kk][t_t_block[kk]]);\n }\n X_size = X_size + subtensor_sizes[jj];\n }\n else{\n subtensor_sizes[jj] = 0;\n }\n }\n free(t_t_block);\n double* X = (double*) calloc(X_size, sizeof(double)); // callocing here, because I will probably need it to start at 0\n\n\n double* X_subtensor = X;\n double** subtensors = (double**) malloc(n_schedule * sizeof(double*));\n for (int jj = 0; jj < n_schedule; ++jj){\n subtensors[jj] = X_subtensor;\n X_subtensor = X_subtensor + subtensor_sizes[jj];\n }\n int flattening = d;\n void* parameters = p_static_init(subtensors);\n\n free(subtensor_sizes);\n\n\n\n\n // Assigning fields\n MPI_tensor* next_ten = (MPI_tensor*) malloc(sizeof(MPI_tensor));\n\n next_ten->d = d;\n next_ten->n = n;\n\n next_ten->comm = comm;\n next_ten->rank = rank;\n next_ten->comm_size = size;\n\n next_ten->schedule = schedule;\n next_ten->n_schedule = n_schedule;\n next_ten->inverse_schedule = inverse_schedule;\n\n next_ten->partitions = partitions;\n next_ten->nps = nps;\n\n next_ten->current_part = -1;\n\n next_ten->f_ten = NULL;\n next_ten->parameters = parameters;\n\n next_ten->X_size = X_size;\n next_ten->X = X;\n\n next_ten->ind1 = (int*) malloc(d * sizeof(int));\n next_ten->ind2 = (int*) malloc(d * sizeof(int));\n next_ten->tensor_part = (int*) malloc(d * sizeof(int));\n next_ten->group_ranks = (int*) malloc(size * sizeof(int));\n next_ten->t_kk = (int*) malloc(d * sizeof(int));\n\n return next_ten;\n}\n\n\nMPI_tensor* SSTT_next_ten(MPI_tensor* prev_ten, tensor_train* tt, int train_ind)\n{\n // Get the train matrix. This is what we multiply prev_ten by!\n int n0 = tt->n[train_ind];\n int r1 = tt->r[train_ind];\n int r2 = tt->r[train_ind + 1];\n double* train = tt->trains[train_ind];\n matrix_tt* train_mat = matrix_tt_wrap(r1 * n0, r2, train);\n\n // Allocate memory for next_ten\n MPI_tensor* next_ten = SSTT_next_ten_init(prev_ten, tt, train_ind);\n\n // Allocate scratch memory\n long scratch_size = 1;\n for (int ii = 0; ii < next_ten->d; ++ii){\n int* partition_ii = next_ten->partitions[ii];\n int size_ii = 0;\n for (int jj = 0; jj < next_ten->nps[ii]; ++jj){\n int tmp = partition_ii[jj+1] - partition_ii[jj];\n size_ii = (size_ii > tmp) ? size_ii : tmp;\n }\n scratch_size = scratch_size * size_ii;\n }\n double* scratch = (double*) malloc(scratch_size * sizeof(double));\n\n // Get some indexing stuff\n int iscol = 1;\n int prev_flattening = (train_ind == 0) ? 1 : 2;\n flattening_info* prev_fi = flattening_info_init(prev_ten, prev_flattening, iscol, 0);\n flattening_info* prev_fi_tmp = flattening_info_init(prev_ten, prev_flattening, iscol, 0);\n\n int next_flattening = 1;\n flattening_info* next_fi = flattening_info_init(next_ten, next_flattening, iscol, 0);\n flattening_info* next_fi_tmp = flattening_info_init(next_ten, next_flattening, iscol, 0);\n\n // Streaming loop\n int rank = prev_ten->rank;\n int size = prev_ten->comm_size;\n int* prev_schedule_rank = prev_ten->schedule[rank];\n int* next_schedule_rank = next_ten->schedule[rank];\n\n MPI_Group world_group;\n MPI_Comm_group(next_ten->comm, &world_group);\n\n matrix_tt* prev_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));\n matrix_tt* next_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));\n matrix_tt* share_mat = (matrix_tt*) calloc(1, sizeof(matrix_tt));\n\n long buf_size = 1;\n for (int ii = 0; ii < next_ten->d; ++ii){\n int sz_ii = 0;\n int* partition_ii = next_ten->partitions[ii];\n for (int jj = 0; jj < next_ten->nps[ii]; ++jj){\n int sz_ii_jj = partition_ii[jj+1] - partition_ii[jj];\n sz_ii = (sz_ii > sz_ii_jj) ? sz_ii : sz_ii_jj;\n }\n buf_size *= sz_ii;\n }\n matrix_tt* buf = matrix_tt_init(buf_size, 1);\n\n for (int ii = 0; ii < prev_ten->n_schedule; ++ii){\n // Some initialization - figuring out who owns and needs what\n int prev_block_rank = prev_schedule_rank[ii];\n\n int* next_t_v_blocks = (int*) malloc(size*sizeof(int));\n for (int jj = 0; jj < size; ++jj){\n int prev_block_jj = prev_ten->schedule[jj][ii];\n\n if (prev_block_jj != -1){\n flattening_info_update(prev_fi_tmp, prev_ten, prev_block_jj);\n int* next_t_t_block = (prev_fi_tmp->t_t_block) + prev_flattening;\n int* next_nps = (next_fi->t_nps) + 1;\n next_t_v_blocks[jj] = to_vec_ind(next_t_t_block, next_nps, next_fi->t_d - 1);\n }\n else{\n next_t_v_blocks[jj] = -1;\n }\n }\n\n if (prev_block_rank != -1){\n // Get prev_mat\n stream(prev_ten, prev_block_rank);\n flattening_info_update(prev_fi, prev_ten, prev_block_rank);\n matrix_tt_wrap_update(prev_mat, prev_fi->f_N, prev_fi->s_N, get_X(prev_ten));\n\n // Get next_mat\n int next_t_v_block = next_t_v_blocks[rank];\n flattening_info_update(next_fi, next_ten, next_t_v_block);\n\n int next_owner;\n int next_epoch;\n MPI_tensor_get_owner(next_ten, next_t_v_block, &next_owner, &next_epoch);\n\n double beta;\n\n if (next_owner == rank){\n beta = 1.0;\n stream(next_ten, next_schedule_rank[next_epoch]);\n matrix_tt_wrap_update(next_mat, next_fi->f_N, next_fi->s_N, get_X(next_ten));\n }\n else{\n beta = 0.0;\n matrix_tt_wrap_update(next_mat, next_fi->f_N, next_fi->s_N, scratch);\n }\n\n // Get train submat\n int i0 = r1 * prev_fi->f_t_index[prev_flattening - 1];\n int i1 = i0 + r1 * prev_fi->f_t_sizes[prev_flattening - 1];\n submatrix_update(train_mat, i0, i1, 0, r2);\n train_mat->transpose = 1;\n\n // Multiply\n matrix_tt_dgemm(train_mat, prev_mat, next_mat, 1.0, beta);\n }\n\n\n // Share\n int* already_shared = (int*) calloc(size, sizeof(int));\n int* group_ranks = prev_ten->group_ranks;\n// printf(\"Starting share\\n\");\n for (int jj = 0; jj < size; ++jj){\n int group_size = 0;\n int t_v_block_jj = next_t_v_blocks[jj];\n int owner_jj;\n int epoch_jj;\n MPI_tensor_get_owner(next_ten, t_v_block_jj, &owner_jj, &epoch_jj);\n if (owner_jj == jj){\n already_shared[jj] = 1;\n }\n else if (t_v_block_jj == -1){\n already_shared[jj] = 1;\n }\n else if(already_shared[jj] == 0){\n int owner_ind;\n int rank_ind;\n for (int kk = 0; kk < size; ++kk){\n if (kk == rank){\n rank_ind = group_size;\n }\n\n if (kk == owner_jj){\n group_ranks[group_size] = kk;\n group_size = group_size + 1;\n }\n else if (next_t_v_blocks[kk] == t_v_block_jj){\n already_shared[kk] = 1;\n group_ranks[group_size] = kk;\n group_size = group_size + 1;\n }\n }\n\n matrix_tt* reduce_mat = NULL;\n if (owner_jj == rank){\n flattening_info_update(next_fi_tmp, next_ten, t_v_block_jj);\n stream(next_ten, t_v_block_jj);\n matrix_tt_wrap_update(share_mat, next_fi_tmp->t_N, 1, get_X(next_ten));\n reduce_mat = share_mat;\n }\n else{\n matrix_tt_reshape(next_mat->n * next_mat->m, 1, next_mat);\n reduce_mat = next_mat;\n }\n\n matrix_tt_reshape(reduce_mat->m, reduce_mat->n, buf);\n matrix_tt_group_reduce(next_ten->comm, rank, reduce_mat, buf, owner_jj, group_ranks, group_size);\n }\n }\n\n\n free(next_t_v_blocks);\n free(already_shared);\n }\n free(prev_mat);\n free(next_mat);\n free(share_mat);\n matrix_tt_free(buf);\n\n\n free(train_mat);\n free(scratch);\n\n flattening_info_free(prev_fi);\n flattening_info_free(prev_fi_tmp);\n flattening_info_free(next_fi);\n flattening_info_free(next_fi_tmp);\n\n MPI_Group_free(&world_group);\n return next_ten;\n}\n\nvoid SSTT_copy_final_train(MPI_tensor* ten, tensor_train* tt)\n{\n int r1 = tt->r[tt->d - 1];\n int n = tt->n[tt->d - 1];\n matrix_tt* train_mat = matrix_tt_wrap(r1, n, tt->trains[tt->d - 1]);\n\n int rank = ten->rank;\n MPI_Comm comm = ten->comm;\n int size = ten->comm_size;\n\n int flattening = 1;\n int iscol = 0;\n flattening_info* fi = flattening_info_init(ten, flattening, iscol, 0);\n\n int Nblocks = ten->nps[1];\n int head = 0;\n for (int ii = 0; ii < Nblocks; ++ii){\n int rank_ii;\n int epoch_ii;\n MPI_tensor_get_owner(ten, ii, &rank_ii, &epoch_ii);\n\n flattening_info_update(fi, ten, ii);\n matrix_tt* train_submat = submatrix(train_mat, 0, r1, fi->f_t_index[0], fi->f_t_index[0] + fi->f_N);\n\n if (rank_ii == rank){\n stream(ten, ii);\n matrix_tt* ten_mat = matrix_tt_wrap(train_submat->m, train_submat->n, get_X(ten));\n if (rank == head){\n matrix_tt_copy_data(train_submat, ten_mat);\n }\n else{\n matrix_tt_send(comm, ten_mat, head);\n }\n free(ten_mat);\n }\n else if (rank == head){\n matrix_tt_recv(comm, train_submat, rank_ii);\n }\n\n free(train_submat);\n }\n\n\n free(train_mat);\n flattening_info_free(fi);\n}\n\n\n// This frees ten. So just be careful\nvoid SSTT(tensor_train* tt, MPI_tensor* ten){\n int d = ten->d;\n int buf = 2;\n int iscol = 1;\n\n for (int ii = 0; ii < d-1; ++ii){\n int flattening = (ii == 0) ? 1 : 2;\n sketch* s = sketch_init(ten, flattening, tt->r[ii+1], buf, iscol); // Initialize sketch\n\n perform_sketch(s); // Sketch\n\n sketch_qr(s); // QR\n\n SSTT_sketch_to_train(s, tt, ii); // Get the train\n\n MPI_tensor* prev_ten = ten;\n ten = SSTT_next_ten(prev_ten, tt, ii); // Perform train^T * ten\n\n sketch_free(s);\n MPI_tensor_free(prev_ten); prev_ten = NULL;\n }\n SSTT_copy_final_train(ten, tt); // copy ten into trains[d-1]\n\n MPI_tensor_free(ten);\n}", "meta": {"hexsha": "71bb3e1a1980a30b9d47d8aa5e13a4db9d0c4c6d", "size": 14562, "ext": "c", "lang": "C", "max_stars_repo_path": "src/SSTT.c", "max_stars_repo_name": "SidShi/Parallel_TT_sketching", "max_stars_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/SSTT.c", "max_issues_repo_name": "SidShi/Parallel_TT_sketching", "max_issues_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SSTT.c", "max_forks_repo_name": "SidShi/Parallel_TT_sketching", "max_forks_repo_head_hexsha": "e2c00c289d75d3ac1df32ed2b95af579a517fcbf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4320712695, "max_line_length": 126, "alphanum_fraction": 0.572723527, "num_tokens": 4102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.603931819468636, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2807688518733584}} {"text": "/**\n *\n * @file core_zgetrf_reclap.c\n *\n * PLASMA core_blas kernel\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.8.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Piotr Luszczek\n * @date 2009-11-15\n *\n * @precisions normal z -> c d s\n *\n **/\n\n#include \n#include \n#include \n#include \"common.h\"\n\nstruct CORE_zgetrf_data_s {\n volatile PLASMA_Complex64_t *CORE_zamax;\n volatile int *CORE_zstep;\n};\n\nstatic inline void\nCORE_zgetrf_reclap_update(CORE_zgetrf_data_t *data,\n int M, int column, int n1, int n2,\n PLASMA_Complex64_t *A, int LDA, int *IPIV,\n int thidx, int thcnt);\nstatic inline void\nCORE_zgetrf_reclap_rec(CORE_zgetrf_data_t *data,\n int M, int N,\n PLASMA_Complex64_t *A, int LDA,\n int *IPIV, int *info,\n int thidx, int thcnt, int column);\n\n/***************************************************************************//**\n *\n * @ingroup dplasma_cores_complex64\n *\n * CORE_zgetrf_reclap computes a LU factorization of a general M-by-N\n * matrix A stored in CCRB layout using partial pivoting with row\n * interchanges.\n *\n * The factorization has the form\n *\n * A = P * L * U\n *\n * where P is a permutation matrix, L is lower triangular with unit\n * diagonal elements (lower trapezoidal if m > n), and U is upper\n * triangular (upper trapezoidal if m < n).\n *\n * This is the recursive version of the algorithm applied on column\n * major layout.\n *\n * WARNINGS:\n * - The function CORE_zgetrf_reclap_init has to be called prior\n * to any call to this function.\n * - You cannot call this kernel on different matrices at the same\n * time.\n * - The matrix A cannot be more than one tile wide.\n * - The number of threads calling this function has to be excatly\n * the number defined by info[2] with each one of them a different\n * index between 0 included and info[2] excluded.\n *\n *******************************************************************************\n *\n * @param[in] data\n * Common data structure to all threads initialized by\n * CORE_zgetrf_reclap_init() that contains information for thread\n * synchronization and maximum reductions. All threads working on a\n * given matrix A must provide the same data structure.\n *\n * @param[in] M\n * The number of rows of the matrix A. M >= 0.\n *\n * @param[in] N\n * The number of columns of the matrix A. N >= 0.\n *\n * @param[in,out] A\n * On entry, the M-by-N matrix to be factorized.\n * On exit, the factors L and U from the factorization\n * A = P*L*U; the unit diagonal elements of L are not stored.\n *\n * @param[in] LDA\n * The leading dimension of the array A. LDA >= max(1,M).\n *\n * @param[out] IPIV\n * The pivot indices; for 1 <= i <= min(M,N), row i of the\n * matrix was interchanged with row IPIV(i).\n * 1 <= IPIV[i] <= M.\n *\n * @param[in,out] info\n * Array of 3 integers\n * - info[0], see returned value\n * - info[1], is the thread index 0 <= info[0] < info[2]\n * - info[2], on entry is the number of threads trying to\n * participate to the factorization,\n * on exit is the real number of threads used to\n * perform the factorization.\n * Info[2] threads, and exactly info[2], have to call this function\n * to avoid dead lock.\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval -k, the k-th argument had an illegal value\n * \\retval k if U(k,k) is exactly zero. The factorization\n * has been completed, but the factor U is exactly\n * singular, and division by zero will occur if it is used\n * to solve a system of equations.\n *\n */\n#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zgetrf_reclap = PCORE_zgetrf_reclap\n#define CORE_zgetrf_reclap PCORE_zgetrf_reclap\n#endif\nint CORE_zgetrf_reclap(CORE_zgetrf_data_t *data,\n int M, int N,\n PLASMA_Complex64_t *A, int LDA,\n int *IPIV, int *info)\n{\n int thidx = info[1];\n int divmn = M / N;\n int thcnt = min( info[2], ((divmn == 0) && (M != 0))? 1 : divmn );\n int minMN = min(M, N);\n\n info[0] = 0;\n info[2] = thcnt;\n\n if( M < 0 ) {\n coreblas_error(1, \"illegal value of M\");\n return -1;\n }\n if( N < 0 ) {\n coreblas_error(2, \"illegal value of N\");\n return -2;\n }\n if( LDA < max(1, M) ) {\n coreblas_error(5, \"illegal value of LDA\");\n return -5;\n }\n\n /*\n * Quick return\n */\n if ( (M == 0) || (N == 0) || (thidx >= thcnt) ){\n return PLASMA_SUCCESS;\n }\n\n *info = 0;\n CORE_zgetrf_reclap_rec( data, M, minMN, A, LDA, IPIV, info,\n thidx, thcnt, 0 );\n\n if ( N > minMN ) {\n CORE_zgetrf_reclap_update(data, M, 0, minMN, N-minMN,\n A, LDA, IPIV,\n thidx, thcnt);\n }\n\n return info[0];\n}\n\n/*******************************************************************\n * Additional routines\n */\nstatic double sfmin = 0.;\n\nCORE_zgetrf_data_t *\nCORE_zgetrf_reclap_init(int nbthrd)\n{\n int i;\n CORE_zgetrf_data_t *data;\n\n data = (CORE_zgetrf_data_t*)malloc( nbthrd * (sizeof(PLASMA_Complex64_t)+sizeof(int))\n + 2 * sizeof(void*) );\n data->CORE_zamax = (PLASMA_Complex64_t*)((char*)data + 2 * sizeof(void*));\n data->CORE_zstep = (int*)((char*)data + 2 * sizeof(void*) + nbthrd * sizeof(PLASMA_Complex64_t));\n\n for (i = 0; i < nbthrd; ++i) {\n data->CORE_zamax[i] = 0.;\n data->CORE_zstep[i] = -1;\n }\n if ( sfmin == 0. ) {\n sfmin = LAPACKE_dlamch_work('S');\n }\n return data;\n}\n\nstatic inline void\npsplit(int n, int pidx, int pcnt, int *poff_p, int *psiz_p)\n{\n int q = n / pcnt, r = n % pcnt;\n\n if (pidx < r) {\n q++;\n *psiz_p = q;\n *poff_p = pidx * q;\n } else {\n *psiz_p = q;\n *poff_p = r * (q + 1) + (pidx - r) * q;\n }\n}\n\nstatic inline void\nCORE_zamax1_thread(CORE_zgetrf_data_t *data,\n PLASMA_Complex64_t localamx,\n int thidx, int thcnt, int *thwinner,\n PLASMA_Complex64_t *globalamx,\n int pividx, int *ipiv)\n{\n volatile PLASMA_Complex64_t *CORE_zamax = data->CORE_zamax;\n volatile int *CORE_zstep = data->CORE_zstep;\n\n if (thidx == 0) {\n int i, j = 0;\n PLASMA_Complex64_t curval = localamx, tmp;\n double curamx = cabs(localamx);\n\n /* make sure everybody filled in their value */\n for (i = 1; i < thcnt; ++i) {\n while (CORE_zstep[i] == -1) { /* wait for thread i to store its value */\n }\n }\n\n /* better not fuse the loop above and below to make sure data is sync'd */\n\n for (i = 1; i < thcnt; ++i) {\n tmp = CORE_zamax[i];\n if (cabs(tmp) > curamx) {\n curamx = cabs(tmp);\n curval = tmp;\n j = i;\n }\n }\n\n if (0 == j)\n ipiv[0] = pividx;\n\n /* make sure everybody knows the amax value */\n for (i = 1; i < thcnt; ++i)\n CORE_zamax[ i ] = curval;\n\n CORE_zstep[0] = -j - 2; /* set the index of the winning thread */\n\n *thwinner = j;\n *globalamx = curval;\n\n for (i = 1; i < thcnt; ++i)\n CORE_zstep[i] = -3;\n\n /* make sure everybody read the max value */\n for (i = 1; i < thcnt; ++i) {\n while (CORE_zstep[i] != -1) {\n }\n }\n\n CORE_zstep[0] = -1;\n } else {\n CORE_zamax[thidx] = localamx;\n CORE_zstep[thidx] = -2; /* announce to thread 0 that local amax was stored */\n while (CORE_zstep[0] == -1) { /* wait for thread 0 to finish calculating the global amax */\n }\n while (CORE_zstep[thidx] != -3) { /* wait for thread 0 to store amax */\n }\n *thwinner = -CORE_zstep[0] - 2;\n *globalamx = CORE_zamax[thidx]; /* read the amax from the location adjacent to the one in the above loop */\n CORE_zstep[thidx] = -1; /* signal thread 0 that this thread is done reading */\n\n if (thidx == *thwinner)\n ipiv[0] = pividx;\n\n while (CORE_zstep[0] != -1) { /* wait for thread 0 to finish */\n }\n }\n}\n\nstatic inline void\nCORE_zbarrier_thread(CORE_zgetrf_data_t *data,\n int thidx, int thcnt)\n{\n int idum1, idum2;\n PLASMA_Complex64_t ddum2 = 0.;\n /* it's probably faster to implement a dedicated barrier */\n CORE_zamax1_thread( data, 1.0, thidx, thcnt, &idum1, &ddum2, 0, &idum2 );\n}\n\nstatic inline void\nCORE_zlaswap1(int ncol, PLASMA_Complex64_t *a, int lda,\n int idxStart, int idxMax, const int *piv)\n{\n int i, j;\n PLASMA_Complex64_t tmp;\n\n for (j = 0; j < ncol; ++j) {\n for (i = idxStart; i < idxMax; ++i) {\n tmp = a[j*lda + piv[i] - 1];\n a[j*lda + piv[i] - 1] = a[i + j*lda];\n a[i + j*lda] = tmp;\n }\n }\n}\n\nstatic inline void\nCORE_zgetrf_reclap_update(CORE_zgetrf_data_t *data,\n int M, int column, int n1, int n2,\n PLASMA_Complex64_t *A, int LDA, int *IPIV,\n int thidx, int thcnt)\n{\n static PLASMA_Complex64_t posone = 1.0;\n static PLASMA_Complex64_t negone = -1.0;\n PLASMA_Complex64_t *Atop = A + column*LDA;\n PLASMA_Complex64_t *Atop2 = Atop + n1 *LDA;\n int coff, ccnt, lm, loff;\n\n CORE_zbarrier_thread( data, thidx, thcnt );\n\n psplit( n2, thidx, thcnt, &coff, &ccnt );\n\n if (ccnt > 0) {\n CORE_zlaswap1( ccnt, Atop2 + coff*LDA, LDA, column, n1 + column, IPIV ); /* swap to the right */\n\n cblas_ztrsm( CblasColMajor, CblasLeft, CblasLower, CblasNoTrans, CblasUnit,\n n1, ccnt, CBLAS_SADDR(posone), Atop + column, LDA, Atop2 + coff*LDA + column, LDA );\n }\n\n /* __sync_synchronize(); */ /* hopefully we will not need memory fences */\n\n /* need to wait for pivoting and triangular solve to finish */\n CORE_zbarrier_thread( data, thidx, thcnt );\n\n psplit( M, thidx, thcnt, &loff, &lm );\n if (thidx == 0) {\n loff = column + n1;\n lm -= column + n1;\n };\n\n cblas_zgemm( CblasColMajor, CblasNoTrans, CblasNoTrans, lm, n2, n1,\n CBLAS_SADDR(negone), Atop+loff, LDA, Atop2 + column, LDA, CBLAS_SADDR(posone), Atop2+loff, LDA );\n}\n\nstatic void\nCORE_zgetrf_reclap_rec(CORE_zgetrf_data_t *data, int M, int N,\n PLASMA_Complex64_t *A, int LDA,\n int *IPIV, int *info,\n int thidx, int thcnt, int column)\n{\n int jp, n1, n2, lm, loff;\n PLASMA_Complex64_t tmp1, tmp2, tmp3;\n PLASMA_Complex64_t *Atop = A + column*LDA;\n\n /* Assumption: N = min( M, N ); */\n if (N > 1) {\n int coff, ccnt;\n\n n1 = N / 2;\n n2 = N - n1;\n\n CORE_zgetrf_reclap_rec( data, M, n1, A, LDA, IPIV, info,\n thidx, thcnt, column );\n if ( *info != 0 )\n return;\n\n CORE_zgetrf_reclap_update(data, M, column, n1, n2,\n A, LDA, IPIV,\n thidx, thcnt);\n\n CORE_zgetrf_reclap_rec( data, M, n2, A, LDA, IPIV, info,\n thidx, thcnt, column + n1 );\n if ( *info != 0 )\n return;\n\n psplit( n1, thidx, thcnt, &coff, &ccnt );\n\n if (ccnt > 0) {\n CORE_zlaswap1( ccnt, Atop+coff*LDA, LDA, n1 + column, N + column, IPIV ); /* swap to the left */\n }\n\n } else {\n int thrd;\n\n CORE_zbarrier_thread( data, thidx, thcnt );\n\n psplit( M, thidx, thcnt, &loff, &lm );\n\n if (thidx == 0) {\n loff = column;\n lm -= column;\n }\n\n tmp2 = Atop[column]; /* all threads read the pivot element in case they need it */\n\n jp = cblas_izamax( lm, Atop + loff, 1 );\n tmp1 = Atop[loff + jp];\n\n CORE_zamax1_thread( data, tmp1, thidx, thcnt, &thrd,\n &tmp3, loff + jp + 1, IPIV + column );\n\n Atop[column] = tmp3; /* all threads set the pivot element: no need for synchronization */\n\n if ( tmp3 != 0.0 ) {\n if ( cabs(tmp3) >= sfmin ) {\n PLASMA_Complex64_t tmp = (PLASMA_Complex64_t)1.0 / tmp3;\n n1 = (thidx == 0) ? 1 : 0;\n cblas_zscal( lm - n1, CBLAS_SADDR(tmp), Atop + loff + n1, 1 );\n } else {\n int i;\n PLASMA_Complex64_t *Atop2;\n n1 = (thidx == 0) ? 1 : 0;\n Atop2 = Atop + loff + n1;\n\n for( i=0; i < lm-n1; i++, Atop2++)\n *Atop2 = *Atop2 / tmp3;\n }\n\n if (thrd == thidx) { /* the thread that owns the best pivot */\n if (loff + jp != column) /* if there is a need to exchange the pivot */\n Atop[loff + jp] = tmp2 / tmp3;\n }\n\n } else {\n *info = column + 1;\n return;\n }\n\n CORE_zbarrier_thread( data, thidx, thcnt );\n }\n}\n", "meta": {"hexsha": "8883762f5ec0b1e8f16507e543602ecd81e943e6", "size": 13650, "ext": "c", "lang": "C", "max_stars_repo_path": "src/cores/core_zgetrf_reclap.c", "max_stars_repo_name": "therault/dplasma", "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_issues_repo_path": "src/cores/core_zgetrf_reclap.c", "max_issues_repo_name": "therault/dplasma", "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_forks_repo_path": "src/cores/core_zgetrf_reclap.c", "max_forks_repo_name": "therault/dplasma", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "avg_line_length": 31.4516129032, "max_line_length": 119, "alphanum_fraction": 0.5226373626, "num_tokens": 4061, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6825737344123242, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2806134812692976}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef SUBFIND\n\n#include \"fof.h\"\n\n#include \"allvars.h\"\n#include \"proto.h\"\n#include \"domain.h\"\n#include \"subfind.h\"\n\nstatic struct id_list\n{\n MyIDType ID;\n int GrNr;\n int SubNr;\n float BindingEgy;\n\n#ifdef SUBFIND_SAVE_PARTICLELISTS\n float Pos[3];\n float Vel[3];\n int Type;\n#ifdef STELLARAGE\n float Mass;\n float StellarAge;\n#endif\n#endif\n}\n *ID_list;\n\nstatic int Nids;\n\n\nvoid subfind(int num)\n{\n double t0, t1, tstart, tend;\n int i, gr, nlocid, offset, limit, ncount;\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n struct unbind_data *d;\n int j, n, count[6], countall[6];\n double a3inv, dmax1, dmax2;\n#endif\n\n if(ThisTask == 0)\n printf(\"\\nWe now execute a parallel version of SUBFIND.\\n\");\n\n tstart = second();\n\n#ifndef ONLY_PRODUCE_HSML_FILES\n if(!All.ComovingIntegrationOn)\n {\n if(ThisTask == 0)\n\tprintf(\"works only for comoving integration.\\n\");\n endrun(0);\n }\n#endif\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n a3inv = 1 / (All.Time * All.Time * All.Time);\n\n for(j = 0; j < 6; j++)\n count[j] = 0;\n\n /* let's count number of particles of selected species */\n for(i = 0; i < NumPart; i++)\n count[P[i].Type]++;\n\n MPI_Allreduce(count, countall, 6, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n /* do first loop: basically just defining the hsml for different species */\n for(j = 0; j < 6; j++)\n {\n if((1 << j) & (DENSITY_SPLIT_BY_TYPE))\n\t{\n#ifdef BLACK_HOLES\n\t if(j == 5)\n\t countall[j] = 0;\t/* this will prevent that the black holes are treated separately */\n#endif\n\n\t force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);\n\n\t if(countall[j] > All.DesNumNgb)\n\t {\n\t /* build index list of particles of selectes species */\n\t d = (struct unbind_data *) mymalloc(count[j] * sizeof(struct unbind_data));\n\t for(i = 0, n = 0; i < NumPart; i++)\n\t\tif(P[i].Type == j)\n\t\t d[n++].index = i;\n\n\t t0 = second();\n\t if(ThisTask == 0)\n\t\tprintf(\"Tree construction for species %d (%d).\\n\", j, countall[j]);\n\n\t CPU_Step[CPU_FOF] += measure_time();\n\n\t force_treebuild(count[j], d);\n\n\t myfree(d);\n\n\t t1 = second();\n\t if(ThisTask == 0)\n\t\tprintf(\"tree build for species %d took %g sec\\n\", j, timediff(t0, t1));\n\t }\n\t else\n\t {\n\t t0 = second();\n\t if(ThisTask == 0)\n\t\tprintf(\"Tree construction.\\n\");\n\n\t CPU_Step[CPU_FOF] += measure_time();\n\n\t force_treebuild(NumPart, NULL);\n\n\t t1 = second();\n\t if(ThisTask == 0)\n\t\tprintf(\"tree build took %g sec\\n\", timediff(t0, t1));\n\t }\n\n\n\t /* let's determine the local densities */\n\t t0 = second();\n\t subfind_setup_smoothinglengths(j);\n\t subfind_density(j);\n\t t1 = second();\n\t if(ThisTask == 0)\n\t printf(\"density and smoothing length for species %d took %g sec\\n\", j, timediff(t0, t1));\n\n\t force_treefree();\n\n\t /* let's save density contribution of own species */\n\t for(i = 0; i < NumPart; i++)\n\t if(P[i].Type == j)\n\t P[i].w.density_sum = P[i].u.DM_Density;\n\n\t}\n }\n\n /* do second loop: now calculate all density contributions */\n for(j = 0; j < 6; j++)\n {\n if((1 << j) & (DENSITY_SPLIT_BY_TYPE))\n\t{\n\t force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);\n\n\t /* build index list of particles of selectes species */\n\t d = (struct unbind_data *) mymalloc(count[j] * sizeof(struct unbind_data));\n\t for(i = 0, n = 0; i < NumPart; i++)\n\t if(P[i].Type == j)\n\t d[n++].index = i;\n\n\t t0 = second();\n\t if(ThisTask == 0)\n\t printf(\"Tree construction for species %d (%d).\\n\", j, countall[j]);\n\n\t CPU_Step[CPU_FOF] += measure_time();\n\n\t force_treebuild(count[j], d);\n\n\t myfree(d);\n\n\t t1 = second();\n\t if(ThisTask == 0)\n\t printf(\"tree build for species %d took %g sec\\n\", j, timediff(t0, t1));\n\n\t /* let's determine the local densities */\n\t t0 = second();\n\t for(i = 0; i < 6; i++)\n\t if((1 << i) & (DENSITY_SPLIT_BY_TYPE))\n\t if(j != i)\n\t\t{\n\t\t if(countall[i] > All.DesNumNgb)\n\t\t {\n\t\t if(ThisTask == 0)\n\t\t\tprintf(\"calculating density contribution of species %d to species %d\\n\", j, i);\n\t\t subfind_density(-(i + 1));\n\t\t }\n\t\t}\n\t t1 = second();\n\t if(ThisTask == 0)\n\t printf(\"density() of species %d took %g sec\\n\", j, timediff(t0, t1));\n\n\t force_treefree();\n\n\t /* let's sum up density contribution */\n\t for(i = 0; i < NumPart; i++)\n\t if((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE))\n\t if(j != P[i].Type)\n\t\tif(countall[P[i].Type] > All.DesNumNgb)\n\t\t P[i].w.density_sum += P[i].u.DM_Density;\n\t}\n }\n\n\n for(i = 0; i < NumPart; i++)\n {\n P[i].u.DM_Density = P[i].w.density_sum;\n\n if(P[i].Type == 0)\n\tP[i].w.int_energy = DMAX(All.MinEgySpec,\n\t\t\t\t SphP[i].Entropy / GAMMA_MINUS1 * pow(SphP[i].d.Density * a3inv,\n\t\t\t\t\t\t\t\t GAMMA_MINUS1));\n else\n\tP[i].w.int_energy = 0;\n\n }\n#else\n force_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);\n\n t0 = second();\n if(ThisTask == 0)\n printf(\"Tree construction.\\n\");\n\n CPU_Step[CPU_FOF] += measure_time();\n\n force_treebuild(NumPart, NULL);\n\n t1 = second();\n if(ThisTask == 0)\n printf(\"tree build took %g sec\\n\", timediff(t0, t1));\n\n\n /* let's determine the local dark matter densities */\n t0 = second();\n subfind_setup_smoothinglengths();\n subfind_density();\n t1 = second();\n if(ThisTask == 0)\n printf(\"dark matter density() took %g sec\\n\", timediff(t0, t1));\n\n force_treefree();\n#endif /* DENSITY_SPLIT_BY_TYPE */\n\n if(DumpFlag)\n {\n /* let's save the densities to a file (for making images) */\n t0 = second();\n subfind_save_densities(num);\n t1 = second();\n if(ThisTask == 0)\n\tprintf(\"saving densities took %g sec\\n\", timediff(t0, t1));\n }\n\n#ifdef ONLY_PRODUCE_HSML_FILES\n return;\n#endif\n\n /* count how many groups we have that should be done collectively */\n limit = 0.6 * All.TotNumPart / NTask;\n\n\n for(i = 0, ncount = 0; i < Ngroups; i++)\n if(Group[i].Len >= limit)\n ncount++;\n MPI_Allreduce(&ncount, &Ncollective, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n if(ThisTask == 0)\n {\n printf(\"\\nNumber of FOF halos treated with collective SubFind code = %d\\n\", Ncollective);\n printf(\"(the adopted size-limit for the collective algorithm was %d particles.)\\n\", limit);\n printf(\"the other %d FOF halos are treated in parallel with serial code\\n\\n\", TotNgroups - Ncollective);\n }\n\n /* to decide on which task a group should be:\n * if GrNr <= Ncollective: collective groupfinding.\n * the task where the group info is put is TaskNr = (GrNr - 1) % NTask\n */\n\n /* now we distribute the particles such that small groups are assigned in\n * total to certain CPUs, and big groups are left where they are \n */\n\n t0 = second();\n\n for(i = 0; i < NumPart; i++)\n {\n if(P[i].GrNr > Ncollective && P[i].GrNr <= TotNgroups)\t/* particle is in small group */\n\tP[i].targettask = (P[i].GrNr - 1) % NTask;\n else\n\tP[i].targettask = ThisTask;\n }\n\n subfind_exchange();\t\t/* distributes gas particles as well if needed */\n\n t1 = second();\n if(ThisTask == 0)\n printf(\"subfind_exchange()() took %g sec\\n\", timediff(t0, t1));\n\n subfind_distribute_groups();\n\n qsort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_GrNr);\n\n\n for(i = 0; i < NumPart; i++)\n if(P[i].GrNr > Ncollective && P[i].GrNr <= TotNgroups)\n if(((P[i].GrNr - 1) % NTask) != ThisTask)\n\t{\n\t printf(\"i=%d %d task=%d\\n\", i, P[i].GrNr, ThisTask);\n\t endrun(87);\n\t}\n\n /* lets estimate the maximum number of substructures we need to store on the local CPU */\n for(i = 0, nlocid = 0; i < Ngroups; i++)\n nlocid += Group[i].Len;\n\n MaxNsubgroups = nlocid / All.DesLinkNgb;\t/* this is a quite conservative upper limit */\n Nsubgroups = 0;\n SubGroup = (struct subgroup_properties *) mymalloc(MaxNsubgroups * sizeof(struct subgroup_properties));\n\n for(i = 0; i < NumPart; i++)\n P[i].SubNr = (1 << 30);\t/* default */\n\n /* we begin by applying the collective version of subfind to distributed groups */\n t0 = second();\n for(GrNr = 1; GrNr <= Ncollective; GrNr++)\n subfind_process_group_collectively(num);\n t1 = second();\n if(ThisTask == 0)\n printf(\"processing of collective halos took %g sec\\n\", timediff(t0, t1));\n\n#ifdef SUBFIND_COLLECTIVE_STAGE1\n if(ThisTask == 0)\n printf(\"stage 1 ended\\n\");\n endrun(0);\n#endif\n\n for(i = 0; i < NumPart; i++)\n {\n P[i].origindex = i;\n P[i].origintask = ThisTask;\n }\n\n t0 = second();\n qsort(P, NumPart, sizeof(struct particle_data), subfind_compare_P_GrNr_DM_Density);\n t1 = second();\n if(ThisTask == 0)\n printf(\"sort of local particles()() took %g sec\\n\", timediff(t0, t1));\n\n\n /* now we have the particles of groups consecutively, but SPH particles are\n not aligned. They can however be accessed via SphP[P[i].originindex] */\n\n\n /* let's count how many local particles we have in small groups */\n for(i = 0, nlocid = 0; i < NumPart; i++)\n if(P[i].GrNr > Ncollective && P[i].GrNr <= Ngroups)\t/* particle is in small group */\n nlocid++;\n\n if(ThisTask == 0)\n printf(\"contructing tree for serial subfind of local groups\\n\");\n\n subfind_loctree_treeallocate((int) (All.TreeAllocFactor * All.MaxPart) + NTopnodes, All.MaxPart);\n\n if(ThisTask == 0)\n printf(\"Start to do local groups with serial subfind algorithm\\n\");\n\n t0 = second();\n\n /* we now apply a serial version of subfind to the local groups */\n for(gr = 0, offset = 0; gr < Ngroups; gr++)\n {\n if(Group[gr].GrNr > Ncollective)\n\t{\n\t if(((Group[gr].GrNr - 1) % NTask) == ThisTask)\n\t offset = subfind_process_group_serial(gr, offset);\n\t}\n }\n\n t1 = second();\n if(ThisTask == 0)\n printf(\"processing of local groups took took %g sec\\n\", timediff(t0, t1));\n\n\n subfind_loctree_treefree();\n\n\n /* bringing back particles in original positions, such that gas particles are aligned */\n t0 = second();\n qsort(P, NumPart, sizeof(struct particle_data), subfind_compare_P_origindex);\n t1 = second();\n if(ThisTask == 0)\n printf(\"unsorting of local particles()() took %g sec\\n\", timediff(t0, t1));\n\n\n GrNr = -1;\t\t\t/* to ensure that domain decomposition acts normally again */\n\n /* now determine the remaining spherical overdensity values for the non-local groups */\n\n domain_free_trick();\n\n CPU_Step[CPU_FOF] += measure_time();\n\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n printf(\"Task %d: testing particles ...\\n\", ThisTask);\n for(i = 0; i < NumPart; i++)\n {\n if(P[i].origintask != ThisTask)\n\tprintf(\"Task %d: Holding particle of task %d !\\n\", ThisTask, P[i].origintask);\n if(P[i].origindex != i)\n\tprintf(\"Task %d: Particles is in wrong position (is=%d, was=%d) !\\n\", ThisTask, i, P[i].origindex);\n }\n#endif\n\n All.DoDynamicUpdate = 0;\n domain_Decomposition();\n\n force_treebuild(NumPart, NULL);\n\n\n /* compute spherical overdensities for FOF groups */\n t0 = second();\n\n subfind_overdensity();\n\n t1 = second();\n if(ThisTask == 0)\n printf(\"determining spherical overdensity masses took %g sec\\n\", timediff(t0, t1));\n\n\n /* determine which halos are contaminated by boundary particles */\n t0 = second();\n\n subfind_contamination();\n\n t1 = second();\n if(ThisTask == 0)\n printf(\"determining contamination of halos took %g sec\\n\", timediff(t0, t1));\n\n\n force_treefree();\n domain_free();\n\n domain_allocate_trick();\n\n /* now assemble final output */\n subfind_save_final(num);\n\n tend = second();\n\n if(ThisTask == 0)\n printf(\"\\nFinished with SUBFIND. (total time=%g sec)\\n\\n\", timediff(tstart, tend));\n\n myfree(SubGroup);\n\n CPU_Step[CPU_FOF] += measure_time();\n}\n\n\n\n\nvoid subfind_save_final(int num)\n{\n int i, j, totsubs, masterTask, groupTask, nprocgroup;\n char buf[1000];\n double t0, t1;\n\n /* prepare list of ids with assigned group numbers */\n\n parallel_sort(Group, Ngroups, sizeof(struct group_properties), fof_compare_Group_GrNr);\n parallel_sort(SubGroup, Nsubgroups, sizeof(struct subgroup_properties),\n\t\tsubfind_compare_SubGroup_GrNr_SubNr);\n\n ID_list = mymalloc(sizeof(struct id_list) * NumPart);\n\n for(i = 0, Nids = 0; i < NumPart; i++)\n {\n if(P[i].GrNr <= TotNgroups)\n\t{\n\t ID_list[Nids].GrNr = P[i].GrNr;\n\t ID_list[Nids].SubNr = P[i].SubNr;\n\t ID_list[Nids].BindingEgy = P[i].v.DM_BindingEnergy;\n\t ID_list[Nids].ID = P[i].ID;\n#ifdef SUBFIND_SAVE_PARTICLELISTS\n\t for(j = 0; j < 3; j++)\n\t {\n\t ID_list[Nids].Pos[j] = P[i].Pos[j];\n\t ID_list[Nids].Vel[j] = P[i].Vel[j];\n\t }\n\t ID_list[Nids].Type = P[i].Type;\n#ifdef STELLARAGE\n ID_list[Nids].Mass = P[i].Mass;\n if(P[i].Type == 4)\n ID_list[Nids].StellarAge = P[i].StellarAge;\n else\n ID_list[Nids].StellarAge = 0;\n#endif\n#endif\n\t Nids++;\n\t}\n }\n\n parallel_sort(ID_list, Nids, sizeof(struct id_list), subfind_compare_ID_list);\n\n\n MPI_Allreduce(&Nsubgroups, &TotNsubgroups, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\n\n /* fill in the FirstSub-values */\n for(i = 0, totsubs = 0; i < Ngroups; i++)\n {\n if(i > 0)\n\tGroup[i].FirstSub = Group[i - 1].FirstSub + Group[i - 1].Nsubs;\n else\n\tGroup[i].FirstSub = 0;\n totsubs += Group[i].Nsubs;\n }\n\n MPI_Allgather(&totsubs, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);\n for(j = 1, Send_offset[0] = 0; j < NTask; j++)\n Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\n for(i = 0; i < Ngroups; i++)\n Group[i].FirstSub += Send_offset[ThisTask];\n\n\n\n\n MPI_Allgather(&Nids, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);\n for(j = 1, Send_offset[0] = 0; j < NTask; j++)\n Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\n if(ThisTask == 0)\n {\n sprintf(buf, \"%s/groups_%03d\", All.OutputDir, num);\n mkdir(buf, 02755);\n }\n MPI_Barrier(MPI_COMM_WORLD);\n\n\n if(NTask < All.NumFilesWrittenInParallel)\n {\n printf\n\t(\"Fatal error.\\nNumber of processors must be a smaller or equal than `NumFilesWrittenInParallel'.\\n\");\n endrun(241931);\n }\n\n t0 = second();\n\n nprocgroup = NTask / All.NumFilesWrittenInParallel;\n if((NTask % All.NumFilesWrittenInParallel))\n nprocgroup++;\n masterTask = (ThisTask / nprocgroup) * nprocgroup;\n for(groupTask = 0; groupTask < nprocgroup; groupTask++)\n {\n if(ThisTask == (masterTask + groupTask))\t/* ok, it's this processor's turn */\n\tsubfind_save_local_catalogue(num);\n MPI_Barrier(MPI_COMM_WORLD);\t/* wait inside the group */\n }\n\n t1 = second();\n\n if(ThisTask == 0)\n {\n printf(\"Subgroup catalogues saved. took = %g sec\\n\", timediff(t0, t1));\n fflush(stdout);\n }\n\n myfree(ID_list);\n}\n\n\nvoid subfind_save_local_catalogue(int num)\n{\n FILE *fd;\n char buf[500], fname[500];\n float *mass, *pos, *vel, *spin;\n\n#ifdef SAVE_MASS_TAB\n float *masstab;\n#endif\n int i, j, *len;\n MyIDType *ids;\n\n sprintf(fname, \"%s/groups_%03d/%s_%03d.%d\", All.OutputDir, num, \"subhalo_tab\", num, ThisTask);\n strcpy(buf, fname);\n if(!(fd = fopen(buf, \"w\")))\n {\n printf(\"can't open file `%s`\\n\", buf);\n endrun(1183);\n }\n\n my_fwrite(&Ngroups, sizeof(int), 1, fd);\n my_fwrite(&TotNgroups, sizeof(int), 1, fd);\n my_fwrite(&Nids, sizeof(int), 1, fd);\n my_fwrite(&TotNids, sizeof(long long), 1, fd);\n my_fwrite(&NTask, sizeof(int), 1, fd);\n my_fwrite(&Nsubgroups, sizeof(int), 1, fd);\n my_fwrite(&TotNsubgroups, sizeof(int), 1, fd);\n\n /* group len */\n len = mymalloc(Ngroups * sizeof(int));\n for(i = 0; i < Ngroups; i++)\n len[i] = Group[i].Len;\n my_fwrite(len, Ngroups, sizeof(int), fd);\n myfree(len);\n\n /* offset into id-list */\n len = mymalloc(Ngroups * sizeof(int));\n for(i = 0; i < Ngroups; i++)\n len[i] = Group[i].Offset;\n my_fwrite(len, Ngroups, sizeof(int), fd);\n myfree(len);\n\n /* mass */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].Mass;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* location (potential minimum) */\n pos = mymalloc(Ngroups * 3 * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n for(j = 0; j < 3; j++)\n pos[i * 3 + j] = Group[i].Pos[j];\n my_fwrite(pos, Ngroups, 3 * sizeof(float), fd);\n myfree(pos);\n\n /* M_Mean200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].M_Mean200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* R_Mean200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].R_Mean200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* M_Crit200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].M_Crit200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* R_Crit200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].R_Crit200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* M_TopHat200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].M_TopHat200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* R_TopHat200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].R_TopHat200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n#ifdef SO_VEL_DISPERSIONS\n /* VelDisp_Mean200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].VelDisp_Mean200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* VelDisp_Crit200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].VelDisp_Crit200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* VelDisp_TopHat200 */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].VelDisp_TopHat200;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n#endif\n\n /* contamination particle count */\n len = mymalloc(Ngroups * sizeof(int));\n for(i = 0; i < Ngroups; i++)\n len[i] = Group[i].ContaminationLen;\n my_fwrite(len, Ngroups, sizeof(int), fd);\n myfree(len);\n\n /* contamination mass */\n mass = mymalloc(Ngroups * sizeof(float));\n for(i = 0; i < Ngroups; i++)\n mass[i] = Group[i].ContaminationMass;\n my_fwrite(mass, Ngroups, sizeof(float), fd);\n myfree(mass);\n\n /* number of substructures in FOF group */\n len = mymalloc(Ngroups * sizeof(int));\n for(i = 0; i < Ngroups; i++)\n len[i] = Group[i].Nsubs;\n my_fwrite(len, Ngroups, sizeof(int), fd);\n myfree(len);\n\n /* first substructure in FOF group */\n len = mymalloc(Ngroups * sizeof(int));\n for(i = 0; i < Ngroups; i++)\n len[i] = Group[i].FirstSub;\n my_fwrite(len, Ngroups, sizeof(int), fd);\n myfree(len);\n\n /* ------------------------------ */\n\n /* Len of substructure */\n len = mymalloc(Nsubgroups * sizeof(int));\n for(i = 0; i < Nsubgroups; i++)\n len[i] = SubGroup[i].Len;\n my_fwrite(len, Nsubgroups, sizeof(int), fd);\n myfree(len);\n\n /* offset of substructure */\n len = mymalloc(Nsubgroups * sizeof(int));\n for(i = 0; i < Nsubgroups; i++)\n len[i] = SubGroup[i].Offset;\n my_fwrite(len, Nsubgroups, sizeof(int), fd);\n myfree(len);\n\n /* parent of substructure */\n len = mymalloc(Nsubgroups * sizeof(int));\n for(i = 0; i < Nsubgroups; i++)\n len[i] = SubGroup[i].SubParent;\n my_fwrite(len, Nsubgroups, sizeof(int), fd);\n myfree(len);\n\n /* Mass of substructure */\n mass = mymalloc(Nsubgroups * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n mass[i] = SubGroup[i].Mass;\n my_fwrite(mass, Nsubgroups, sizeof(float), fd);\n myfree(mass);\n\n /* Pos of substructure */\n pos = mymalloc(Nsubgroups * 3 * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n for(j = 0; j < 3; j++)\n pos[i * 3 + j] = SubGroup[i].Pos[j];\n my_fwrite(pos, Nsubgroups, 3 * sizeof(float), fd);\n myfree(pos);\n\n /* Vel of substructure */\n vel = mymalloc(Nsubgroups * 3 * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n for(j = 0; j < 3; j++)\n vel[i * 3 + j] = SubGroup[i].Vel[j];\n my_fwrite(vel, Nsubgroups, 3 * sizeof(float), fd);\n myfree(vel);\n\n /* Center of mass of substructure */\n pos = mymalloc(Nsubgroups * 3 * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n for(j = 0; j < 3; j++)\n pos[i * 3 + j] = SubGroup[i].CM[j];\n my_fwrite(pos, Nsubgroups, 3 * sizeof(float), fd);\n myfree(pos);\n\n /* Spin of substructure */\n spin = mymalloc(Nsubgroups * 3 * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n for(j = 0; j < 3; j++)\n spin[i * 3 + j] = SubGroup[i].Spin[j];\n my_fwrite(spin, Nsubgroups, 3 * sizeof(float), fd);\n myfree(spin);\n\n /* velocity dispesion */\n mass = mymalloc(Nsubgroups * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n mass[i] = SubGroup[i].SubVelDisp;\n my_fwrite(mass, Nsubgroups, sizeof(float), fd);\n myfree(mass);\n\n /* maximum circular velocity */\n mass = mymalloc(Nsubgroups * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n mass[i] = SubGroup[i].SubVmax;\n my_fwrite(mass, Nsubgroups, sizeof(float), fd);\n myfree(mass);\n\n /* radius of maximum circular velocity */\n mass = mymalloc(Nsubgroups * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n mass[i] = SubGroup[i].SubVmaxRad;\n my_fwrite(mass, Nsubgroups, sizeof(float), fd);\n myfree(mass);\n\n /* radius of half the mass */\n mass = mymalloc(Nsubgroups * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n mass[i] = SubGroup[i].SubHalfMass;\n my_fwrite(mass, Nsubgroups, sizeof(float), fd);\n myfree(mass);\n\n /* ID of most bound particle */\n ids = mymalloc(Nsubgroups * sizeof(MyIDType));\n for(i = 0; i < Nsubgroups; i++)\n ids[i] = SubGroup[i].SubMostBoundID;\n my_fwrite(ids, Nsubgroups, sizeof(MyIDType), fd);\n myfree(ids);\n\n /* GrNr of substructure */\n len = mymalloc(Nsubgroups * sizeof(int));\n for(i = 0; i < Nsubgroups; i++)\n len[i] = SubGroup[i].GrNr;\n my_fwrite(len, Nsubgroups, sizeof(int), fd);\n myfree(len);\n\n /* Masstab of substructure */\n#ifdef SAVE_MASS_TAB\n masstab = mymalloc(Nsubgroups * 6 * sizeof(float));\n for(i = 0; i < Nsubgroups; i++)\n for(j = 0; j < 6; j++)\n masstab[i * 6 + j] = SubGroup[i].MassTab[j];\n my_fwrite(masstab, Nsubgroups, 6 * sizeof(float), fd);\n myfree(masstab);\n#endif\n\n fclose(fd);\n\n\n#ifdef SUBFIND_SAVE_PARTICLELISTS\n sprintf(buf, \"%s/groups_%03d/%s_%03d.%d\", All.OutputDir, num, \"subhalo_posvel\", num, ThisTask);\n if(!(fd = fopen(buf, \"w\")))\n {\n printf(\"can't open file `%s`\\n\", buf);\n endrun(1184);\n }\n\n my_fwrite(&Ngroups, sizeof(int), 1, fd);\n my_fwrite(&TotNgroups, sizeof(int), 1, fd);\n my_fwrite(&Nids, sizeof(int), 1, fd);\n my_fwrite(&TotNids, sizeof(long long), 1, fd);\n my_fwrite(&NTask, sizeof(int), 1, fd);\n my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd);\n my_fwrite(&All.Time, sizeof(double), 1, fd);\n\n float *posdata;\n double a3inv;\n char *types;\n\n if(All.ComovingIntegrationOn)\n a3inv = 1.0 / (All.Time * All.Time * All.Time);\n else\n a3inv = 1.0;\n\n posdata = (float *) mymalloc(3 * Nids * sizeof(float));\n\n for(i = 0; i < Nids; i++)\n for(j = 0; j < 3; j++)\n posdata[i * 3 + j] = ID_list[i].Pos[j];\n\n my_fwrite(posdata, 3 * sizeof(float), Nids, fd);\n\n for(i = 0; i < Nids; i++)\n for(j = 0; j < 3; j++)\n posdata[i * 3 + j] = ID_list[i].Vel[j] * sqrt(a3inv);\n\n my_fwrite(posdata, 3 * sizeof(float), Nids, fd);\n\n types = (char *) posdata;\n\n for(i = 0; i < Nids; i++)\n types[i] = ID_list[i].Type;\n\n my_fwrite(types, sizeof(char), Nids, fd);\n\n\n#ifdef STELLARAGE\n for(i = 0; i < Nids; i++)\n posdata[i] = ID_list[i].Mass;\n\n my_fwrite(posdata, sizeof(float), Nids, fd);\n\n for(i = 0; i < Nids; i++)\n posdata[i] = ID_list[i].StellarAge;\n\n my_fwrite(posdata, sizeof(float), Nids, fd);\n#endif\n\n\n myfree(posdata);\n\n fclose(fd);\n#endif\n\n\n\n ids = (MyIDType *) ID_list;\n\n for(i = 0; i < Nids; i++)\n ids[i] = ID_list[i].ID;\n\n sprintf(buf, \"%s/groups_%03d/%s_%03d.%d\", All.OutputDir, num, \"subhalo_ids\", num, ThisTask);\n if(!(fd = fopen(buf, \"w\")))\n {\n printf(\"can't open file `%s`\\n\", buf);\n endrun(1184);\n }\n\n my_fwrite(&Ngroups, sizeof(int), 1, fd);\n my_fwrite(&TotNgroups, sizeof(int), 1, fd);\n my_fwrite(&Nids, sizeof(int), 1, fd);\n my_fwrite(&TotNids, sizeof(long long), 1, fd);\n my_fwrite(&NTask, sizeof(int), 1, fd);\n my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd);\n my_fwrite(ids, sizeof(MyIDType), Nids, fd);\n\n fclose(fd);\n}\n\nint subfind_compare_ID_list(const void *a, const void *b)\n{\n if(((struct id_list *) a)->GrNr < ((struct id_list *) b)->GrNr)\n return -1;\n\n if(((struct id_list *) a)->GrNr > ((struct id_list *) b)->GrNr)\n return +1;\n\n if(((struct id_list *) a)->SubNr < ((struct id_list *) b)->SubNr)\n return -1;\n\n if(((struct id_list *) a)->SubNr > ((struct id_list *) b)->SubNr)\n return +1;\n\n if(((struct id_list *) a)->BindingEgy < ((struct id_list *) b)->BindingEgy)\n return -1;\n\n if(((struct id_list *) a)->BindingEgy > ((struct id_list *) b)->BindingEgy)\n return +1;\n\n return 0;\n}\n\nint subfind_compare_SubGroup_GrNr_SubNr(const void *a, const void *b)\n{\n if(((struct subgroup_properties *) a)->GrNr < ((struct subgroup_properties *) b)->GrNr)\n return -1;\n\n if(((struct subgroup_properties *) a)->GrNr > ((struct subgroup_properties *) b)->GrNr)\n return +1;\n\n if(((struct subgroup_properties *) a)->SubNr < ((struct subgroup_properties *) b)->SubNr)\n return -1;\n\n if(((struct subgroup_properties *) a)->SubNr > ((struct subgroup_properties *) b)->SubNr)\n return +1;\n\n return 0;\n}\n\n\nint subfind_compare_P_GrNr_DM_Density(const void *a, const void *b)\n{\n if(((struct particle_data *) a)->GrNr < (((struct particle_data *) b)->GrNr))\n return -1;\n\n if(((struct particle_data *) a)->GrNr > (((struct particle_data *) b)->GrNr))\n return +1;\n\n if(((struct particle_data *) a)->u.DM_Density > (((struct particle_data *) b)->u.DM_Density))\n return -1;\n\n if(((struct particle_data *) a)->u.DM_Density < (((struct particle_data *) b)->u.DM_Density))\n return +1;\n\n return 0;\n}\n\n\nint subfind_compare_P_origindex(const void *a, const void *b)\n{\n if(((struct particle_data *) a)->origindex < (((struct particle_data *) b)->origindex))\n return -1;\n\n if(((struct particle_data *) a)->origindex > (((struct particle_data *) b)->origindex))\n return +1;\n\n return 0;\n}\n\n\n#endif\n", "meta": {"hexsha": "938b93e7d74b8d378222ef6fac0d25b1f5273ecd", "size": 26420, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind.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/subfind.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/subfind.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": 26.42, "max_line_length": 110, "alphanum_fraction": 0.6187736563, "num_tokens": 8399, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.27986073794693384}} {"text": "#include \"quantum_gates.h\"\n#include \"quac_p.h\"\n#include \n#include \n#include \n#include \n#include \"qasm_parser.h\"\n#include \"error_correction.h\"\n#include \"dm_utilities.h\"\n#include \n\nvoid quil_read(char filename[],PetscInt *num_qubits,circuit *circ){\n FILE *fp;\n int ch = 0,lines=0,finished_allocate=0,num_pragma=0,this_qubit,max_qubit=-1;\n char *line = NULL;\n size_t len = 0;\n ssize_t read;\n PetscReal time=1.0;\n\n fp = fopen(filename,\"r\");\n\n if (fp == NULL){\n if (nid==0){\n printf(\"ERROR! File not found in projectq_qasm_read!\\n\");\n }\n }\n\n //Count number of lines\n while(!feof(fp)){\n ch = fgetc(fp);\n if(ch == '\\n'){\n lines++;\n }\n }\n //Rewind file\n rewind(fp);\n\n *num_qubits = 0;\n num_pragma = 0;\n this_qubit = -1;\n while ((read = getline(&line, &len, fp)) != -1){\n if (strstr(line,\"PRAGMA\")){\n //We will skip pragma lines\n num_pragma = num_pragma + 1;\n } else {\n this_qubit = line[strlen(line) - 2] - '0';\n if (this_qubit>max_qubit){\n max_qubit = this_qubit;\n }\n }\n }\n *num_qubits = max_qubit+1;\n\n lines = lines - num_pragma;\n\n create_circuit(circ,lines);\n rewind(fp); //Rewind the file (again)\n\n while ((read = getline(&line, &len, fp)) != -1){\n if (strstr(line,\"PRAGMA\")){\n //We will skip pragma lines\n } else if (strlen(line)>1){\n _quil_add_gate(line,circ,time);\n time = time + 1.0;\n }\n }\n\n fclose(fp);\n if (line) free(line);\n return;\n}\n\nvoid _quil_get_angle_pi(char angle_pi[32],PetscReal *angle){\n char numerator[32],denominator[32];\n int found_denom=1,i_n,i_d,i,denom,numer,factor;\n //Gate was printed with 'pi' or 'pi/2'\n angle_pi[strlen(angle_pi)-1] = 0;\n factor = 1;\n //Search for digits\n i_d = 0; i_n = 0;\n denom = 1; numer = 1;\n for (i=0;angle_pi[i] != '\\0'; i++){\n if (angle_pi[i]=='-'){\n //Found negative sign\n factor = -1;\n } else if (angle_pi[i]==\"/\") {\n // Found division; all digits after this\n // belong to the denominator\n found_denom = 1;\n } if (isdigit(angle_pi[i])){\n if (found_denom==0){\n //Numerator\n numerator[i_n] = angle_pi[i];\n i_n = i_n + 1;\n } else {\n //Denominator\n denominator[i_n] = angle_pi[i];\n i_d = i_d + 1;\n }\n }\n }\n if (i_d>0){\n denom = atoi(denominator);\n }\n if (i_n>0){\n numer = atoi(numerator);\n }\n *angle = factor * numer * PETSC_PI / denom;\n return;\n}\n\n\nvoid _quil_add_gate(char *line,circuit *circ,PetscReal time){\n char *token=NULL,*ptr=NULL;\n const char s[2] = \" \";\n char angle_pi[32];\n int qubit1=-1,qubit2=-1;\n PetscReal angle;\n gate_type my_gate_type;\n // Split string on \" \" to separate the gate and the qubits\n while (token=strsep(&line,\" \")) {\n size_t i, j;\n for (i=0, j=0; token[j]=token[i]; j+=!isspace(token[i++]));\n //FIXME: Not exhaustive\n if (isdigit(token[0])){\n // check qubit numbers\n if (qubit1<0){\n qubit1 = atoi(token);\n } else {\n qubit2 = atoi(token);\n }\n } else {\n // gate types\n if (strcmp(token,\"CNOT\")==0){\n my_gate_type = CNOT;\n } else if (strcmp(token,\"I\")==0){\n my_gate_type = EYE;\n } else if (strcmp(token,\"CZ\")==0){\n my_gate_type = CZ;;\n } else if (strcmp(token,\"H\")==0) {\n my_gate_type = HADAMARD;\n } else if (strcmp(token,\"Z\")==0) {\n my_gate_type = SIGMAZ;\n } else if (strcmp(token,\"X\")==0) {\n my_gate_type = SIGMAX;\n } else if (strcmp(token,\"Y\")==0) {\n my_gate_type = SIGMAY;\n } else if (strstr(token,\"RX\")) {\n my_gate_type = RX;\n if (strstr(token,\"pi\")){\n sscanf(token,\"RX(%s)\",&angle_pi);\n _quil_get_angle_pi(angle_pi,&angle);\n } else {\n //Not sure if quil prints like this\n sscanf(token,\"RX(%lf)\",&angle);\n }\n } else if (strstr(token,\"RY\")) {\n my_gate_type = RY;\n if (strstr(token,\"pi\")){\n sscanf(token,\"RY(%s)\",&angle_pi);\n _quil_get_angle_pi(angle_pi,&angle);\n } else {\n //Not sure if quil prints like this\n sscanf(token,\"RY(%lf)\",&angle);\n }\n } else if (strstr(token,\"RZ\")) {\n if (strstr(token,\"pi\")){\n sscanf(token,\"RZ(%s)\",&angle_pi);\n _quil_get_angle_pi(angle_pi,&angle);\n } else {\n //Not sure if quil prints like this\n sscanf(token,\"RZ(%lf)\",&angle);\n }\n my_gate_type = RZ;\n }\n }\n }\n\n if (qubit2>0){\n //Multiqubit gate\n add_gate_to_circuit(circ,time,my_gate_type,qubit1,qubit2);\n } else {\n //Single qubit gate\n if (my_gate_type==6||my_gate_type==7||my_gate_type==8){\n //Rotation gate\n add_gate_to_circuit(circ,time,my_gate_type,qubit1,angle);\n } else {\n add_gate_to_circuit(circ,time,my_gate_type,qubit1);\n }\n }\n return;\n}\n\nvoid projectq_qasm_read(char filename[],PetscInt *num_qubits,circuit *circ){\n FILE *fp;\n int ch = 0,lines=0,finished_allocate=0;\n char *line = NULL;\n size_t len = 0;\n ssize_t read;\n PetscReal time=1.0;\n\n fp = fopen(filename,\"r\");\n\n if (fp == NULL){\n if (nid==0){\n printf(\"ERROR! File not found in projectq_qasm_read!\\n\");\n }\n }\n\n //Count number of lines\n while(!feof(fp)){\n ch = fgetc(fp);\n if(ch == '\\n')\n {\n lines++;\n }\n }\n //Rewind file\n rewind(fp);\n\n *num_qubits = 0;\n while ((read = getline(&line, &len, fp)) != -1){\n if (!finished_allocate){\n if (strstr(line,\"Allocate\")){\n //Get number of qubits by reading number of lines with 'Allocate'\n *num_qubits = *num_qubits+1;\n } else {\n /*Subtract off the allocate lines to get the total number\n * of gates.\n * Factor of 2 because the end has DEALLOCATE statements\n * WARNING! Comments will be included, too - not too big of a problem,\n * just will overallocate a bit */\n lines = lines - 2*(*num_qubits);\n //Allocate the circuit\n create_circuit(circ,lines);\n finished_allocate = 1;\n //Add the first gate to list\n _projectq_qasm_add_gate(line,circ,time);\n time = time + 1.0;\n // gate_list[0]\n }\n } else if (strstr(line,\"Deallocate\")){\n //Breakout since we've finished going through the circuit\n break;\n } else {\n _projectq_qasm_add_gate(line,circ,time);\n time = time + 1.0;\n }\n\n }\n\n fclose(fp);\n if (line) free(line);\n return;\n}\n\n\nvoid _projectq_qasm_add_gate(char *line,circuit *circ,PetscReal time){\n char *token=NULL;\n int qubit1,qubit2;\n PetscReal angle;\n gate_type my_gate_type;\n // Split string on | to separate gate type and qubits\n while (token=strsep(&line,\"|\")) {\n //Strip whitespace\n size_t i, j;\n for (i=0, j=0; token[j]=token[i]; j+=!isspace(token[i++]));\n //Do direct strcmp for some, strstr for others\n //FIXME: Not exhaustive\n if (strstr(token,\"Qureg\")){\n // qubit numbers\n if (my_gate_type<0){\n //Multiqubit gate\n sscanf(token,\"(Qureg[%d],Qureg[%d])\",&qubit1,&qubit2);\n add_gate_to_circuit(circ,time,my_gate_type,qubit1,qubit2);\n } else {\n //Single qubit gate\n sscanf(token,\"Qureg[%d]\",&qubit1);\n if (my_gate_type==6||my_gate_type==7||my_gate_type==8){\n //Rotation gate\n add_gate_to_circuit(circ,time,my_gate_type,qubit1,angle);\n } else {\n add_gate_to_circuit(circ,time,my_gate_type,qubit1);\n }\n }\n } else {\n // gate types\n if (strcmp(token,\"CX\")==0){\n my_gate_type = CNOT;\n } else if (strcmp(token,\"H\")==0) {\n my_gate_type = HADAMARD;\n } else if (strcmp(token,\"Z\")==0) {\n my_gate_type = SIGMAZ;\n } else if (strcmp(token,\"X\")==0) {\n my_gate_type = SIGMAX;\n } else if (strcmp(token,\"Y\")==0) {\n my_gate_type = SIGMAY;\n } else if (strstr(token,\"Rx\")) {\n my_gate_type = RX;\n sscanf(token,\"Rx(%lf)\",&angle);\n } else if (strstr(token,\"Ry\")) {\n my_gate_type = RY;\n sscanf(token,\"Ry(%lf)\",&angle);\n } else if (strstr(token,\"Rz\")) {\n sscanf(token,\"Rz(%lf)\",&angle);\n my_gate_type = RZ;\n }\n }\n }\n}\n\nvoid projectq_vqe_get_expectation(char filename[],Vec rho,PetscScalar *trace_val){\n FILE *fp;\n char *token=NULL,*token2=NULL;\n char *line = NULL,gate_char;\n size_t len = 0;\n ssize_t read;\n int token_number,num_ops,qubit_number;\n operator ops[100];\n PetscReal scalar_multiply;\n PetscScalar temp_trace_val;\n fp = fopen(filename,\"r\");\n *trace_val = 0.0;\n if (fp == NULL){\n if (nid==0){\n printf(\"ERROR! File not found in projectq_vqe_get_expectation!\\n\");\n }\n }\n\n while ((read = getline(&line, &len, fp)) != -1){\n token_number = 0;\n while (token=strsep(&line,\"[\")) {\n if(token_number==0){\n //Strip whitespace\n size_t i, j;\n for (i=0, j=0; token[j]=token[i]; j+=!isspace(token[i++]));\n scalar_multiply = atof(token);\n token_number = 1;\n } else {\n token2=strsep(&token,\"]\");\n num_ops = 0;\n while (token=strsep(&token2,\" \")) {\n if (strcmp(token,\"\")==0){\n *trace_val = *trace_val + scalar_multiply;\n } else {\n //Assume qubit number in file is global system number\n //FIXME: Put logical->physical qubit mapping here\n sscanf(token,\"%c%d\",&gate_char,&qubit_number);\n if (gate_char=='X'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_x;\n } else if (gate_char=='Y'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_y;\n } else if (gate_char=='Z'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_z;\n }\n num_ops = num_ops + 1;\n }\n }\n if (num_ops!=0){\n //This is a hack where I pass many ops, even though many of them\n //may not exist or be valid; they won't be accessed, at least.\n //Consider passing the array instead, and iterating inside?\n get_expectation_value(rho,&temp_trace_val,num_ops,\n ops[0],ops[1],ops[2],ops[3],\n ops[4],ops[5],ops[6],ops[7],\n ops[8],ops[9],ops[10],ops[11],\n ops[12],ops[13],ops[14],ops[15],\n ops[16],ops[17],ops[18],ops[19]);\n temp_trace_val = temp_trace_val * scalar_multiply;\n *trace_val = *trace_val + temp_trace_val;\n }\n }\n }\n }\n return;\n}\n\nvoid projectq_vqe_get_expectation_squared(char filename[],Vec rho,PetscScalar *trace_val){\n FILE *fp;\n char *token=NULL,*token2=NULL;\n char *line = NULL,gate_char;\n size_t len = 0;\n ssize_t read;\n int token_number,num_ops,qubit_number;\n operator ops[100];\n PetscReal scalar_multiply;\n PetscScalar temp_trace_val;\n fp = fopen(filename,\"r\");\n *trace_val = 0.0;\n if (fp == NULL){\n if (nid==0){\n printf(\"ERROR! File not found in projectq_vqe_get_expectation!\\n\");\n }\n }\n\n while ((read = getline(&line, &len, fp)) != -1){\n token_number = 0;\n while (token=strsep(&line,\"[\")) {\n if(token_number==0){\n //Strip whitespace\n size_t i, j;\n for (i=0, j=0; token[j]=token[i]; j+=!isspace(token[i++]));\n scalar_multiply = atof(token);\n token_number = 1;\n } else {\n token2=strsep(&token,\"]\");\n num_ops = 0;\n while (token=strsep(&token2,\" \")) {\n if (strcmp(token,\"\")==0){\n *trace_val = *trace_val + scalar_multiply;\n } else {\n //Assume qubit number in file is global system number\n //FIXME: Put logical->physical qubit mapping here\n sscanf(token,\"%c%d\",&gate_char,&qubit_number);\n if (gate_char=='X'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_x;\n } else if (gate_char=='Y'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_y;\n } else if (gate_char=='Z'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_z;\n }\n num_ops = num_ops + 1;\n }\n }\n if (num_ops!=0){\n //This is a hack where I pass many ops, even though many of them\n //may not exist or be valid; they won't be accessed, at least.\n //Consider passing the array instead, and iterating inside?\n get_expectation_value(rho,&temp_trace_val,num_ops,\n ops[0],ops[1],ops[2],ops[3],\n ops[4],ops[5],ops[6],ops[7],\n ops[8],ops[9],ops[10],ops[11],\n ops[12],ops[13],ops[14],ops[15],\n ops[16],ops[17],ops[18],ops[19]);\n temp_trace_val = temp_trace_val * scalar_multiply;\n *trace_val = *trace_val + temp_trace_val;\n }\n }\n }\n }\n return;\n}\n\nvoid projectq_vqe_get_expectation_encoded(char filename[],Vec rho,PetscScalar *trace_val,\n PetscInt num_encoders,...){\n FILE *fp;\n char *token=NULL,*token2=NULL;\n char *line = NULL,gate_char;\n size_t len = 0;\n ssize_t read;\n int token_number,num_ops,qubit_number;\n va_list ap;\n operator ops[100];\n PetscInt i;\n PetscReal scalar_multiply;\n PetscScalar temp_trace_val;\n encoded_qubit encoders[50]; //50 is more systems than we will be able to do\n\n va_start(ap,num_encoders);\n for (i=0;iphysical qubit mapping here\n sscanf(token,\"%c%d\",&gate_char,&qubit_number);\n qubit_number = encoders[qubit_number].qubits[0];\n if (gate_char=='X'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_x;\n } else if (gate_char=='Y'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_y;\n } else if (gate_char=='Z'){\n ops[num_ops] = subsystem_list[qubit_number]->sig_z;\n }\n num_ops = num_ops + 1;\n }\n }\n if (num_ops!=0){\n if (num_ops>4){\n if (nid==0) {\n printf(\"ERROR! vqe_get_expectation only supports 4 ops for now\\n\");\n exit(0);\n }\n }\n get_expectation_value(rho,&temp_trace_val,num_ops,ops[0],ops[1],ops[2],ops[3]);\n temp_trace_val = temp_trace_val * scalar_multiply;\n *trace_val = *trace_val + temp_trace_val;\n }\n }\n }\n }\n return;\n}\n", "meta": {"hexsha": "4e63553cb0f12fd0af6ff1bb8d82140676f26cac", "size": 15377, "ext": "c", "lang": "C", "max_stars_repo_path": "src/qasm_parser.c", "max_stars_repo_name": "bcwu/QuaC", "max_stars_repo_head_hexsha": "b5a71cb8c34ebffd1c980380862dcd59c2ef69c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/qasm_parser.c", "max_issues_repo_name": "bcwu/QuaC", "max_issues_repo_head_hexsha": "b5a71cb8c34ebffd1c980380862dcd59c2ef69c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/qasm_parser.c", "max_forks_repo_name": "bcwu/QuaC", "max_forks_repo_head_hexsha": "b5a71cb8c34ebffd1c980380862dcd59c2ef69c2", "max_forks_repo_licenses": ["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.6853281853, "max_line_length": 90, "alphanum_fraction": 0.5553749106, "num_tokens": 4335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.27972725365827134}} {"text": "#include \"imd.h\"\n#include \n#include \n#include \n\n\n// #define USEFLOAT // hauptsächlich in der funktion genexptint. Profiling zeigte, dass\n // hier die meiste zeit verbraucht wird -> float verdoppelt performance\n\n#ifdef USEFLOAT\ntypedef float Real;\n#define REALTYPE MPI_FLOAT\n#else\ntypedef double Real;\n#define REALTYPE MPI_DOUBLE\n#endif\n\n#ifdef USEFLOAT\n #define EXPR expf //exp zu floaten ist eine ganz mieeese idee\n #define SQRTR sqrtf\n #define POWR powf\n #define LOGR logf\n#else\n #define EXPR exp\n #define SQRTR sqrt\n #define POWR pow\n#define LOGR log\n#endif\n\n\n// *********************************************************\n// PHYSICAL CONSTANTS\n// *********************************************************\n// const double eV2J=1.6021766E-19;\nconst Real eV2H=0.03674932; //eV to Hartree\nconst Real colrad_reltol=1e-5;\nconst Real colrad_abstol=10.0;\n\n// const Real J2eV=6.2415091E18;\nconst Real planck=6.62607004E-34; // J/s\nconst Real bohr_radius=0.52917721067E-10; // m\nconst Real bohr_radius_sq=2.800285202924816e-21;\nconst Real hbar_cub=1.172812163789953e-102; //hbar^3 \nconst Real double_emass_pow_3_2 = 2.459112949719466e-45; // (2*emass)^3/2\nconst int MAXLINE = 255;\nconst Real pi=3.141592653589793;\nconst Real pi_sq=9.869604401089358;\nconst Real E_ion_H=13.6; // eV\nconst Real E_ion_H_J=2.178960176000000e-18; // J\nconst Real E_ion_H_sq_J=4.747867448593952e-36;\n\nconst Real colrad_tequi=1e-12;//TEST// 1e-12; //bei initial equi ohne Temperatur-variation erst einmal \n //die Saha-besetzungsdichten equilibrieren\n\n//const double LIGHTSPEED=2.997925458e8; // m/s\nReal LASERFREQ;\n\n\n\n\nint colrad_ydot(double t, N_Vector u, N_Vector udot, void *user_data);\nvoid do_Saha(Real Te,Real totalc,Real ne,N_Vector y);\nint colrad_GetCoeffs(N_Vector y,Real It, void * user_data);\n\n// Die Zwei müssen nach Prototypes.h\n// void do_colrad(double dt);\n// void colrad_init(void);\n\nvoid colrad_read_states(void);\nvoid colrad_Saha_init(int i,int j,int k);\n\n\n\n\n// ******************************************************************************\n// * CROSS SECTION INTEGRATION STUFF\n// ******************************************************************************\n\ngsl_integration_workspace * winteg_inner=NULL;\ngsl_integration_workspace * winteg_outer=NULL;\ngsl_integration_workspace * winteg_fermi=NULL;\ngsl_integration_workspace * winteg_exc=NULL; //excitation\n\ngsl_integration_romberg_workspace * winteg_rb_inner=NULL;\ngsl_integration_romberg_workspace * winteg_rb_outer=NULL;\n\n\nstruct my_f_params { Real ne; Real T;Real mu; Real E;Real DeltaE; int allowed;};\n// struct my_f_params fparams_inner; //For inner integrand\n// struct my_f_params fparams_outer; //outer integrand\n// struct my_f_params fparams_fermi; \n// struct my_f_params fparams_exc; \n\ndouble inner_integrand_ionization(double x, void *p); // integrate along E'\ndouble outer_integrand_ionization(double x,void *p); // integrate along E\n\n\nReal double_integral_ionization(Real ne,Real T, Real mu, Real DeltaE); //evaluates double integral\n\n\ndouble inner_integrand_recombination(double x, void *p);\ndouble outer_integrand_recombination(double x,void *p);\nReal double_integral_recombination(Real ne,Real T, Real mu, Real DeltaE);\n\ndouble integrand_excitation(double x,void *p);\nReal eval_excitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed); \n\nReal eval_dexcitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed);\ndouble integrand_deexcitation(double x,void *p);\n\n\ndouble fermi_integrand(double x, void *p);\nReal eval_fermi_integrand(Real ne,Real T, Real mu);\n\n\ndouble integrand_excitation_debug(double x,void *p);\n\n\ndouble outer_integrand_ionization2(double x,struct my_f_params* p);\nReal double_integral_ionization2(Real ne,Real T, Real mu, Real DeltaE); //evaluates double integral\ndouble inner_integrand_ionization2(double x, struct my_f_params* p);\n\n// **********************************************************************************************\n// * PAR INTEGRAL STUFF\n// **********************************************************************************************\nint terminate_gkq;\nint terminate_gkq_outer;\nint terminate_gkq_inner;\nint terminate_serial;\nint gkq_iter_serial; // nr of iterations\n\nconst double gkq_alpha=0.816496580927726;\nconst double gkq_beta=0.447213595499958; \nstatic const double xgkq[12] = \n{\n 0.0,\n -0.942882415695480,\n -0.816496580927726,\n -0.641853342345781,\n -0.447213595499958,\n -0.236383199662150,\n 0.0,\n 0.236383199662150,\n 0.447213595499958,\n 0.641853342345781,\n 0.816496580927726,\n 0.942882415695480\n};\n\n\nReal integral_simpson(Real (*f)(Real, void*), Real a, Real b,int n,void* p);\n\nint simpson_error;\nconst Real tolmax=1e-20;\nconst Real simpson_itermax=120;\n#define INITIAL_STACK_SIZE 128 /* initial size of new stacks */\n\n\n\n\n/* the stack structure */\nstruct stack_s{ \n int el_count; /* count of elements on stack */ \n int el_size; /* size of an element */\n int mem_reserve; /* allocated memory for stack */\n void* elements; /* pointer to begin of stack */\n};\n\ntypedef struct _work_t{\n double a;\n double b;\n double tol;\n double S;\n double fa;\n double fb;\n double fm;\n double rec;\n int iter;\n struct my_f_params * p; //pointer auf params\n} work_t;\n\ntypedef struct _work_t_gkq{\n double a;\n double b;\n double toler;\n double I_13;\n double I_prev;\n double fa;\n double fb;\n struct my_f_params * p; //pointer auf params\n shortint iter;\n} work_gkq;\n\n\ntypedef struct stack_s* stack_t;\ndouble integral_simpson_par(double (*f)(double, struct my_f_params*), stack_t stack);\n\ndouble gkq_adapt_OMP(double (*f)(double, struct my_f_params*), stack_t stack);\ndouble gkq_OMP(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p,stack_t stack);\n\ndouble gkq_serial(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p);\ndouble gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, \n double fa,double fb, double toler,double I_13, struct my_f_params* p);\n\n// void create_stack(stack_t* stack, int element_size);\n// int empty_stack(stack_t stack);\n// void push_stack(stack_t stack, void* element);\n// void pop_stack(stack_t stack, void* element);\n\n\n\n\n\n/******************************************\n * create new stack\n ******************************************/\nvoid create_stack(\n stack_t* stack, /* stack to create */\n int element_size) /* size of a stack element */\n{\n int initial_size = INITIAL_STACK_SIZE;\n\n /* allocate memory for new stack struct */\n (*stack) = (stack_t) malloc(sizeof(struct stack_s));\n if (!(*stack)){\n char errstr[255];\n sprintf(errstr, \"error: could not allocate memory for stack.. Abort.\\n\"); \n error(errstr);\n // exit(1);\n } \n\n /* allocate memory for stack elements */\n (*stack)->elements = (void*) malloc(element_size * initial_size);\n (*stack)->mem_reserve = initial_size; \n if (!(*stack)->elements){\n char errstr[255];\n sprintf(errstr, \"error: could not allocate memory for stack.. Abort.\\n\");\n error(errstr);\n }\n\n (*stack)->el_size = element_size;\n (*stack)->el_count = 0;\n\n}\n\n/*****************************************\n * check if the stack is empty \n *****************************************/\nint empty_stack(stack_t stack)\n{\n return stack->el_count <= 0;\n}\n\n\n/*****************************************\n * push a element on stack\n *****************************************/\nvoid push_stack(stack_t stack, /* target stack */\n void* element) /* element to push */\n{\n int i, new_reserve;\n int log2_count;\n\n /* check if we need more memory for stack */ \n if (stack->el_count >= stack->mem_reserve)\n {\n\n /* calculate new size for the stack\n it should be a power of two */\n for (i = stack->el_count, log2_count = 0; \n i > 0; \n i>>1, log2_count++);\n new_reserve = 1 << log2_count;\n \n /* reallocate memory for phase thread tables \n and nullify new values */\n stack->elements = (void *) realloc(stack->elements, \n stack->el_size * new_reserve);\n if (!stack->elements){\n char errstr [255];\n sprintf(errstr, \"error: can't reallocate stack.. Aborting\\n\");\n error(errstr);\n // exit(1);\n }\n\n stack->mem_reserve = new_reserve;\n }\n \n /* now push the element on top of the stack */\n memcpy((char*)stack->elements + stack->el_count*stack->el_size, \n element, stack->el_size);\n stack->el_count++;\n\n}\n\n\n/*****************************************\n * pop an element from stack\n *****************************************/\nvoid pop_stack(\n stack_t stack, /* target stack */\n void* element) /* where poped el. should be stored */\n{\n if (stack->el_count <= 0){\n char errstr[255];\n sprintf(errstr, \"error: trying to pop from empty stack.\\n\");\n error(errstr);\n // exit(2);\n }\n\n stack->el_count--;\n memcpy(element, \n (char*)stack->elements + stack->el_count*stack->el_size, \n stack->el_size);\n\n}\n\n\n\n// ***************************************************************************\n// * Gauss-kronard quadrature, parallel\n// ***************************************************************************\ndouble gkq_OMP(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p,stack_t stack)\n{\n //1st integration\n double result=0.0;\n// ********************************************* \n\n double m=0.5*(a+b);\n double h=0.5*(b-a);\n double y[13];\n double fa=y[0]=f(a,p);\n double fb=y[12]=f(b,p);\n int i;\n for(i=1;i<12;i++)\n y[i]=f(m+xgkq[i]*h,p);\n\n double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto\n double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod\n 625.0*(y[4]+y[8])+672.0*y[6]);\n\n double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+\n 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+\n 0.242611071901408*y[6]); //13-point Kronrod\n\n \n double Err1=fabs(I_7-I_13);\n double Err2=fabs(I_4-I_13);\n\n double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;\n double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; \n\n if(I_13 == 0)\n I_13=b-a;\n I_13=fabs(I_13);\n\n \n //Prepare work and push onto stack\n work_gkq work;\n\n work.a = a;\n work.b = b;\n work.toler = toler;\n work.I_13=I_13;\n work.fa=fa;\n work.fb=fb;\n work.p=p;\n work.I_prev=I_7;\n\n //ANTI-FOLGENDES:\n //OUT OF TOLERANCE !!!, mll:3.0162e-18, a:3.0162e-18, b:3.0162e-18, mrr:3.0162e-18,I_7-I_4:0.0000e+00, tol:1.6002e-315,I_13:7.0585e-313\n if(I_13 < 1e-150) \n return 0;\n\n push_stack(stack, &work); \n result=gkq_adapt(f,stack);\n return result;\n}\n\ndouble gkq_serial(double (*f)(double, struct my_f_params*), double a, double b, double TOL, struct my_f_params* p)\n{\n //1st integration\n\n double result=0.0;\n gkq_iter_serial=0;\n// ********************************************* \n\n double m=0.5*(a+b);\n double h=0.5*(b-a);\n double y[13];\n double fa=y[0]=f(a,p);\n double fb=y[12]=f(b,p);\n int i;\n for(i=1;i<12;i++)\n y[i]=f(m+xgkq[i]*h,p);\n\n double I_4= (h/6.0)*(y[0]+y[12]+5.0*(y[4]+y[8])); // 4-point gauss-lobatto\n double I_7= (h/1470.0)*(77.0*(y[0]+y[12])+432.0*(y[2]+y[10])+ // 7-point kronrod\n 625.0*(y[4]+y[8])+672.0*y[6]);\n\n double I_13= h*(0.0158271919734802*(y[0]+y[12])+0.0942738402188500*(y[1]+y[11])+0.155071987336585*(y[2]+y[10])+\n 0.188821573960182*(y[3]+y[9])+0.199773405226859*(y[4]+y[8])+0.224926465333340*(y[5]+y[7])+\n 0.242611071901408*y[6]); //13-point Kronrod\n\n \n double Err1=fabs(I_7-I_13);\n double Err2=fabs(I_4-I_13);\n\n double r=(Err2 != 0.0) ? Err1/Err2 : 1.0;\n double toler=(r > 0.0 && r < 1.0) ? TOL/r : TOL; \n\n if(I_13 == 0)\n I_13=b-a;\n I_13=fabs(I_13);\n\n\n result=gkq_adapt_serial(f,a,b,fa,fb,toler,I_13, p); \n\n return result;\n}\n\n\n// ***********************************************\n// * RECURSIVE ADAPTION ROUTINE FOR PARALLEL-GK-QUADRATURE \n// **********************************************\ndouble gkq_adapt_OMP(double (*f)(double, struct my_f_params*), stack_t stack)\n{\n work_gkq work;\n work.iter=0;\n int ready, idle, busy;\n double integral_result = 0.0; \n\n busy = 0;\n terminate_gkq=0;\n\n#pragma omp parallel default(none) \\\n shared(stack, integral_result,f,busy,terminate_gkq,myid) \\\n private(work, idle, ready)\n { \n// printf(\"me:%d, err:%d\\n\",omp_get_thread_num(),simpson_error); \n\n ready = 0;\n idle = 1;\n\n while(!ready) // && !terminate_gkq)// && !simpson_error) //<-- so NICHT!\n {\n #pragma omp critical (stack)\n {\n if (!empty_stack(stack))\n {\n /* we have new work */ \n pop_stack(stack, &work);\n if (idle)\n {\n /* say others i'm busy */\n busy += 1;\n idle = 0;\n }\n }\n else\n {\n /* no new work on stack */\n if (!idle){\n busy -= 1;\n idle = 1;\n }\n\n /* nobody has anything to do; let us leave the loop */\n if (busy == 0)\n {\n ready = 1; \n }\n }\n } /* end critical(stack) */\n\n if (idle)\n continue; //if ready==1 --> leave loop\ndouble I_prev=work.I_prev;\n\n double a = work.a;\n double b = work.b; \n double toler = work.toler; \n double I_13=work.I_13; \n double fa=work.fa;\n double fb=work.fb;\n int iter=work.iter;\n // double *y= work.y; // brauch ich nicht!\n struct my_f_params * p = work.p;\n \n double m = (a+b)/2;\n double h = (b -a)/2;\n double mll=m-gkq_alpha*h;\n double ml=m-gkq_beta*h;\n double mr=m+gkq_beta*h;\n double mrr=m+gkq_alpha*h;\n\n double fmll=f(mll,p);\n double fml=f(ml,p);\n double fm=f(m,p);\n double fmr=f(mr,p);\n double fmrr=f(mrr,p);\n double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.\n double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);\n \n// if(myid==1)\n// printf(\"I_7:%.4e, I_13:%.4e,I_4:%.4e, minus:%.4e, to:%.4e\\n\",I_7,I_13,I_4,I_7-I_4, toler*I_13);\nint maxiter=50; //max. subdivisions\ndouble abstol=1e-30;\nwork.I_prev=I_7; // für abstolcheck in nächster recursion\n\n if (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr || iter > maxiter || fabs(I_7-I_prev) < abstol ) \n {\n if ((mll <= a || b <= mrr)) //Error\n {\n // out_of_tolerance=true; // Interval contains no more machine numbers\n // printf(\"OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e,I_7-I_4:%.4e, tol:%.4e,I_13:%.4e\\n\", \n // mll,b,b,mrr,I_7-I_4, toler*I_13,I_13);\n terminate_gkq=1; \n }\n #pragma omp critical (integral_result) \n {\n integral_result += I_7; //Terminate recursion. \n } \n// printf(\"me ok:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f,ubteg;%.4e\\n\", omp_get_thread_num(), a,b,toler,I_4,I_7,integral_result); \n\n }\n else //subdivide interval and push new work on stack\n {\n #pragma omp critical (stack)\n {\n\n // printf(\"me NOOOO:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\\n\", omp_get_thread_num(), a,b,toler,I_4,I_7);\n\n work.iter=iter+1;\n\n work.a=a;\n work.b=mll;\n work.fa=fa;\n work.fb=fmll;\n push_stack(stack, &work); \n\n work.a=mll;\n work.b=ml;\n work.fa=fmll;\n work.fb=fml;\n push_stack(stack, &work); \n\n work.a=ml;\n work.b=m;\n work.fa=fml;\n work.fb=fm;\n push_stack(stack, &work); \n\n work.a=m;\n work.b=mr;\n work.fa=fm;\n work.fb=fmr;\n push_stack(stack, &work); \n\n work.a=mr;\n work.b=mrr;\n work.fa=fmr;\n work.fb=fmrr;\n push_stack(stack, &work); \n\n work.a=mrr;\n work.b=b;\n work.fa=fmrr;\n work.fb=fb;\n push_stack(stack, &work); \n\n } // pragma critical stack\n } // else ..non-acceptable error\n } // while\n } /* end omp parallel */\n return integral_result; \n}\n\n\ndouble gkq_adapt_serial(double (*f)(double, struct my_f_params*), double a, double b, double fa,\n double fb, double toler,double I_13, struct my_f_params* p)\n{\n double m = (a+b)/2;\n double h = (b -a)/2;\n double mll=m-gkq_alpha*h;\n double ml=m-gkq_beta*h;\n double mr=m+gkq_beta*h;\n double mrr=m+gkq_alpha*h;\n\n double fmll=f(mll,p);\n double fml=f(ml,p);\n double fm=f(m,p);\n double fmr=f(mr,p);\n double fmrr=f(mrr,p);\n double I_4=h/6.0*(fa+fb+5.0*(fml+fmr)); // 4-point Gauss-Lobatto formula.\n double I_7=h/1470.0*(77.0*(fa+fb)+432.0*(fmll+fmrr)+625.0*(fml+fmr)+672.0*fm);\n \n gkq_iter_serial++;\n\n\n if ( (fabs(I_7-I_4) <= toler*I_13 || mll <= a || b <= mrr) && gkq_iter_serial) \n {\n if ((mll <= a || b <= mrr) && !terminate_serial) //Error\n {\n // out_of_tolerance=true; // Interval contains no more machine numbers\n printf(\"OUT OF TOLERANCE !!!, mll:%.4e, a:%.4e, b:%.4e, mrr:%.4e\\n\", mll,b,b,mrr);\n terminate_serial=1; \n }\n\n// printf(\"me ok:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\\n\", omp_get_thread_num(), a,b,toler,I_4,I_7); \n return I_7;\n }\n else\n {\n\n // printf(\"me NOOOO:%d, a:%f,b:%f, tler:%.5e,I_4:%f,I_7:%f\\n\", omp_get_thread_num(), a,b,toler,I_4,I_7);\n\n return gkq_adapt_serial(f, a,mll,fa,fmll,toler,I_13,p) +\n gkq_adapt_serial(f, mll,ml,fmll,fml,toler,I_13,p) +\n gkq_adapt_serial(f, ml,m,fml,fm,toler,I_13,p) +\n gkq_adapt_serial(f, m,mr,fm,fmr,toler,I_13,p) +\n gkq_adapt_serial(f, mr,mrr,fmr,fmrr,toler,I_13,p) +\n gkq_adapt_serial(f, mrr,b,fmrr,fb,toler,I_13,p);\n }\n\n\n}", "meta": {"hexsha": "3b0f212278c8120ec4b14091fbe8454a2202a2a6", "size": 18302, "ext": "h", "lang": "C", "max_stars_repo_path": "imd_colrad.h", "max_stars_repo_name": "fmqeisfeld/IMD", "max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z", "max_issues_repo_path": "imd_colrad.h", "max_issues_repo_name": "fmqeisfeld/IMD", "max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imd_colrad.h", "max_forks_repo_name": "fmqeisfeld/IMD", "max_forks_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_forks_repo_licenses": ["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.1897926635, "max_line_length": 137, "alphanum_fraction": 0.5735985138, "num_tokens": 5658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7122321720225278, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.27943491271435317}} {"text": "/* specfunc/airy.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#include \"check.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval_mode.c\"\n\n/*-*-*-*-*-*-*-*-*-*-*-* Private Section *-*-*-*-*-*-*-*-*-*-*-*/\n\n\n/* chebyshev expansions for Airy modulus and phase\n based on SLATEC r9aimp()\n\n Series for AM21 on the interval -1.25000D-01 to 0.\n with weighted error 2.89E-17\n log weighted error 16.54\n significant figures required 14.15\n decimal places required 17.34\n\n Series for ATH1 on the interval -1.25000D-01 to 0.\n with weighted error 2.53E-17\n log weighted error 16.60\n significant figures required 15.15\n decimal places required 17.38\n\n Series for AM22 on the interval -1.00000D+00 to -1.25000D-01\n with weighted error 2.99E-17\n log weighted error 16.52\n significant figures required 14.57\n decimal places required 17.28\n\n Series for ATH2 on the interval -1.00000D+00 to -1.25000D-01\n with weighted error 2.57E-17\n log weighted error 16.59\n significant figures required 15.07\n decimal places required 17.34\n*/\n\nstatic double am21_data[37] = {\n 0.0065809191761485,\n 0.0023675984685722,\n 0.0001324741670371,\n 0.0000157600904043,\n 0.0000027529702663,\n 0.0000006102679017,\n 0.0000001595088468,\n 0.0000000471033947,\n 0.0000000152933871,\n 0.0000000053590722,\n 0.0000000020000910,\n 0.0000000007872292,\n 0.0000000003243103,\n 0.0000000001390106,\n 0.0000000000617011,\n 0.0000000000282491,\n 0.0000000000132979,\n 0.0000000000064188,\n 0.0000000000031697,\n 0.0000000000015981,\n 0.0000000000008213,\n 0.0000000000004296,\n 0.0000000000002284,\n 0.0000000000001232,\n 0.0000000000000675,\n 0.0000000000000374,\n 0.0000000000000210,\n 0.0000000000000119,\n 0.0000000000000068,\n 0.0000000000000039,\n 0.0000000000000023,\n 0.0000000000000013,\n 0.0000000000000008,\n 0.0000000000000005,\n 0.0000000000000003,\n 0.0000000000000001,\n 0.0000000000000001\n};\nstatic cheb_series am21_cs = {\n am21_data,\n 36,\n -1, 1,\n 20\n};\n\nstatic double ath1_data[36] = {\n -0.07125837815669365,\n -0.00590471979831451,\n -0.00012114544069499,\n -0.00000988608542270,\n -0.00000138084097352,\n -0.00000026142640172,\n -0.00000006050432589,\n -0.00000001618436223,\n -0.00000000483464911,\n -0.00000000157655272,\n -0.00000000055231518,\n -0.00000000020545441,\n -0.00000000008043412,\n -0.00000000003291252,\n -0.00000000001399875,\n -0.00000000000616151,\n -0.00000000000279614,\n -0.00000000000130428,\n -0.00000000000062373,\n -0.00000000000030512,\n -0.00000000000015239,\n -0.00000000000007758,\n -0.00000000000004020,\n -0.00000000000002117,\n -0.00000000000001132,\n -0.00000000000000614,\n -0.00000000000000337,\n -0.00000000000000188,\n -0.00000000000000105,\n -0.00000000000000060,\n -0.00000000000000034,\n -0.00000000000000020,\n -0.00000000000000011,\n -0.00000000000000007,\n -0.00000000000000004,\n -0.00000000000000002\n};\nstatic cheb_series ath1_cs = {\n ath1_data,\n 35,\n -1, 1,\n 15\n};\n\nstatic double am22_data[33] = {\n -0.01562844480625341,\n 0.00778336445239681,\n 0.00086705777047718,\n 0.00015696627315611,\n 0.00003563962571432,\n 0.00000924598335425,\n 0.00000262110161850,\n 0.00000079188221651,\n 0.00000025104152792,\n 0.00000008265223206,\n 0.00000002805711662,\n 0.00000000976821090,\n 0.00000000347407923,\n 0.00000000125828132,\n 0.00000000046298826,\n 0.00000000017272825,\n 0.00000000006523192,\n 0.00000000002490471,\n 0.00000000000960156,\n 0.00000000000373448,\n 0.00000000000146417,\n 0.00000000000057826,\n 0.00000000000022991,\n 0.00000000000009197,\n 0.00000000000003700,\n 0.00000000000001496,\n 0.00000000000000608,\n 0.00000000000000248,\n 0.00000000000000101,\n 0.00000000000000041,\n 0.00000000000000017,\n 0.00000000000000007,\n 0.00000000000000002\n};\nstatic cheb_series am22_cs = {\n am22_data,\n 32,\n -1, 1,\n 15\n};\n\nstatic double ath2_data[32] = {\n 0.00440527345871877,\n -0.03042919452318455,\n -0.00138565328377179,\n -0.00018044439089549,\n -0.00003380847108327,\n -0.00000767818353522,\n -0.00000196783944371,\n -0.00000054837271158,\n -0.00000016254615505,\n -0.00000005053049981,\n -0.00000001631580701,\n -0.00000000543420411,\n -0.00000000185739855,\n -0.00000000064895120,\n -0.00000000023105948,\n -0.00000000008363282,\n -0.00000000003071196,\n -0.00000000001142367,\n -0.00000000000429811,\n -0.00000000000163389,\n -0.00000000000062693,\n -0.00000000000024260,\n -0.00000000000009461,\n -0.00000000000003716,\n -0.00000000000001469,\n -0.00000000000000584,\n -0.00000000000000233,\n -0.00000000000000093,\n -0.00000000000000037,\n -0.00000000000000015,\n -0.00000000000000006,\n -0.00000000000000002\n};\nstatic cheb_series ath2_cs = {\n ath2_data,\n 31,\n -1, 1,\n 16\n};\n\n\n/* Airy modulus and phase for x < -1 */\nstatic\nint\nairy_mod_phase(const double x, gsl_mode_t mode, gsl_sf_result * mod, gsl_sf_result * phase)\n{\n gsl_sf_result result_m;\n gsl_sf_result result_p;\n double m, p;\n double sqx;\n\n if(x < -2.0) {\n double z = 16.0/(x*x*x) + 1.0;\n cheb_eval_mode_e(&am21_cs, z, mode, &result_m);\n cheb_eval_mode_e(&ath1_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(&am22_cs, z, mode, &result_m);\n cheb_eval_mode_e(&ath2_cs, z, mode, &result_p);\n }\n else {\n mod->val = 0.0;\n mod->err = 0.0;\n phase->val = 0.0;\n phase->err = 0.0;\n GSL_ERROR (\"x is greater than 1.0\", GSL_EDOM);\n }\n\n m = 0.3125 + result_m.val;\n p = -0.625 + result_p.val;\n\n sqx = sqrt(-x);\n\n mod->val = sqrt(m/sqx);\n mod->err = fabs(mod->val) * (GSL_DBL_EPSILON + fabs(result_m.err/result_m.val));\n phase->val = M_PI_4 - x*sqx * p;\n phase->err = fabs(phase->val) * (GSL_DBL_EPSILON + fabs(result_p.err/result_p.val));\n\n return GSL_SUCCESS;\n}\n\n\n\n/* Chebyshev series for Ai(x) with x in [-1,1]\n based on SLATEC ai(x)\n\n series for aif on the interval -1.00000d+00 to 1.00000d+00\n with weighted error 1.09e-19\n log weighted error 18.96\n significant figures required 17.76\n decimal places required 19.44\n\n series for aig on the interval -1.00000d+00 to 1.00000d+00\n with weighted error 1.51e-17\n log weighted error 16.82\n significant figures required 15.19\n decimal places required 17.27\n */\nstatic double ai_data_f[9] = {\n -0.03797135849666999750,\n 0.05919188853726363857,\n 0.00098629280577279975,\n 0.00000684884381907656,\n 0.00000002594202596219,\n 0.00000000006176612774,\n 0.00000000000010092454,\n 0.00000000000000012014,\n 0.00000000000000000010\n};\nstatic cheb_series aif_cs = {\n ai_data_f,\n 8,\n -1, 1,\n 8\n};\n\nstatic double ai_data_g[8] = {\n 0.01815236558116127,\n 0.02157256316601076,\n 0.00025678356987483,\n 0.00000142652141197,\n 0.00000000457211492,\n 0.00000000000952517,\n 0.00000000000001392,\n 0.00000000000000001\n};\nstatic cheb_series aig_cs = {\n ai_data_g,\n 7,\n -1, 1,\n 7\n};\n\n\n/* Chebvyshev series for Bi(x) with x in [-1,1]\n based on SLATEC bi(x)\n\n series for bif on the interval -1.00000d+00 to 1.00000d+00\n with weighted error 1.88e-19\n log weighted error 18.72\n significant figures required 17.74\n decimal places required 19.20\n\n series for big on the interval -1.00000d+00 to 1.00000d+00\n with weighted error 2.61e-17\n log weighted error 16.58\n significant figures required 15.17\n decimal places required 17.03\n */\nstatic double data_bif[9] = {\n -0.01673021647198664948,\n 0.10252335834249445610,\n 0.00170830925073815165,\n 0.00001186254546774468,\n 0.00000004493290701779,\n 0.00000000010698207143,\n 0.00000000000017480643,\n 0.00000000000000020810,\n 0.00000000000000000018\n};\nstatic cheb_series bif_cs = {\n data_bif,\n 8,\n -1, 1,\n 8\n};\n\nstatic double data_big[8] = {\n 0.02246622324857452,\n 0.03736477545301955,\n 0.00044476218957212,\n 0.00000247080756363,\n 0.00000000791913533,\n 0.00000000001649807,\n 0.00000000000002411,\n 0.00000000000000002\n};\nstatic cheb_series big_cs = {\n data_big,\n 7,\n -1, 1,\n 7\n};\n\n\n/* Chebyshev series for Bi(x) with x in [1,8]\n based on SLATEC bi(x)\n */\nstatic double data_bif2[10] = {\n 0.0998457269381604100,\n 0.4786249778630055380,\n 0.0251552119604330118,\n 0.0005820693885232645,\n 0.0000074997659644377,\n 0.0000000613460287034,\n 0.0000000003462753885,\n 0.0000000000014288910,\n 0.0000000000000044962,\n 0.0000000000000000111\n};\nstatic cheb_series bif2_cs = {\n data_bif2,\n 9,\n -1, 1,\n 9\n};\n\nstatic double data_big2[10] = {\n 0.033305662145514340,\n 0.161309215123197068,\n 0.0063190073096134286,\n 0.0001187904568162517,\n 0.0000013045345886200,\n 0.0000000093741259955,\n 0.0000000000474580188,\n 0.0000000000001783107,\n 0.0000000000000005167,\n 0.0000000000000000011\n};\nstatic cheb_series big2_cs = {\n data_big2,\n 9,\n -1, 1,\n 9\n};\n\n\n/* chebyshev for Ai(x) asymptotic factor \n based on SLATEC aie()\n\n Series for AIP on the interval 0. to 1.00000D+00\n with weighted error 5.10E-17\n log weighted error 16.29\n significant figures required 14.41\n decimal places required 17.06\n \n [GJ] Sun Apr 19 18:14:31 EDT 1998\n There was something wrong with these coefficients. I was getting\n errors after 3 or 4 digits. So I recomputed this table. Now I get\n double precision agreement with Mathematica. But it does not seem\n possible that the small differences here would account for the\n original discrepancy. There must have been something wrong with my\n original usage...\n*/\nstatic double data_aip[36] = {\n -0.0187519297793867540198,\n -0.0091443848250055004725,\n 0.0009010457337825074652,\n -0.0001394184127221491507,\n 0.0000273815815785209370,\n -0.0000062750421119959424,\n 0.0000016064844184831521,\n -0.0000004476392158510354,\n 0.0000001334635874651668,\n -0.0000000420735334263215,\n 0.0000000139021990246364,\n -0.0000000047831848068048,\n 0.0000000017047897907465,\n -0.0000000006268389576018,\n 0.0000000002369824276612,\n -0.0000000000918641139267,\n 0.0000000000364278543037,\n -0.0000000000147475551725,\n 0.0000000000060851006556,\n -0.0000000000025552772234,\n 0.0000000000010906187250,\n -0.0000000000004725870319,\n 0.0000000000002076969064,\n -0.0000000000000924976214,\n 0.0000000000000417096723,\n -0.0000000000000190299093,\n 0.0000000000000087790676,\n -0.0000000000000040927557,\n 0.0000000000000019271068,\n -0.0000000000000009160199,\n 0.0000000000000004393567,\n -0.0000000000000002125503,\n 0.0000000000000001036735,\n -0.0000000000000000509642,\n 0.0000000000000000252377,\n -0.0000000000000000125793\n/*\n -.0187519297793868\n -.0091443848250055,\n .0009010457337825,\n -.0001394184127221,\n .0000273815815785,\n -.0000062750421119,\n .0000016064844184,\n -.0000004476392158,\n .0000001334635874,\n -.0000000420735334,\n .0000000139021990,\n -.0000000047831848,\n .0000000017047897,\n -.0000000006268389,\n .0000000002369824,\n -.0000000000918641,\n .0000000000364278,\n -.0000000000147475,\n .0000000000060851,\n -.0000000000025552,\n .0000000000010906,\n -.0000000000004725,\n .0000000000002076,\n -.0000000000000924,\n .0000000000000417,\n -.0000000000000190,\n .0000000000000087,\n -.0000000000000040,\n .0000000000000019,\n -.0000000000000009,\n .0000000000000004,\n -.0000000000000002,\n .0000000000000001,\n -.0000000000000000\n*/\n};\nstatic cheb_series aip_cs = {\n data_aip,\n 35,\n -1, 1,\n 17\n};\n\n\n/* chebyshev for Bi(x) asymptotic factor \n based on SLATEC bie()\n\n Series for BIP on the interval 1.25000D-01 to 3.53553D-01\n with weighted error 1.91E-17\n log weighted error 16.72\n significant figures required 15.35\n decimal places required 17.41\n\n Series for BIP2 on the interval 0. to 1.25000D-01\n with weighted error 1.05E-18\n log weighted error 17.98\n significant figures required 16.74\n decimal places required 18.71\n*/\nstatic double data_bip[24] = {\n -0.08322047477943447,\n 0.01146118927371174,\n 0.00042896440718911,\n -0.00014906639379950,\n -0.00001307659726787,\n 0.00000632759839610,\n -0.00000042226696982,\n -0.00000019147186298,\n 0.00000006453106284,\n -0.00000000784485467,\n -0.00000000096077216,\n 0.00000000070004713,\n -0.00000000017731789,\n 0.00000000002272089,\n 0.00000000000165404,\n -0.00000000000185171,\n 0.00000000000059576,\n -0.00000000000012194,\n 0.00000000000001334,\n 0.00000000000000172,\n -0.00000000000000145,\n 0.00000000000000049,\n -0.00000000000000011,\n 0.00000000000000001\n};\nstatic cheb_series bip_cs = {\n data_bip,\n 23,\n -1, 1,\n 14\n};\n\nstatic double data_bip2[29] = { \n -0.113596737585988679,\n 0.0041381473947881595,\n 0.0001353470622119332,\n 0.0000104273166530153,\n 0.0000013474954767849,\n 0.0000001696537405438,\n -0.0000000100965008656,\n -0.0000000167291194937,\n -0.0000000045815364485,\n 0.0000000003736681366,\n 0.0000000005766930320,\n 0.0000000000621812650,\n -0.0000000000632941202,\n -0.0000000000149150479,\n 0.0000000000078896213,\n 0.0000000000024960513,\n -0.0000000000012130075,\n -0.0000000000003740493,\n 0.0000000000002237727,\n 0.0000000000000474902,\n -0.0000000000000452616,\n -0.0000000000000030172,\n 0.0000000000000091058,\n -0.0000000000000009814,\n -0.0000000000000016429,\n 0.0000000000000005533,\n 0.0000000000000002175,\n -0.0000000000000001737,\n -0.0000000000000000010\n};\nstatic cheb_series bip2_cs = {\n data_bip2,\n 28,\n -1, 1,\n 10\n};\n\n\n/* assumes x >= 1.0 */\ninline static int \nairy_aie(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n double sqx = sqrt(x);\n double z = 2.0/(x*sqx) - 1.0;\n double y = sqrt(sqx);\n gsl_sf_result result_c;\n cheb_eval_mode_e(&aip_cs, z, mode, &result_c);\n result->val = (0.28125 + result_c.val)/y;\n result->err = result_c.err/y + GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n}\n\n/* assumes x >= 2.0 */\nstatic int airy_bie(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n const double ATR = 8.7506905708484345;\n const double BTR = -2.0938363213560543;\n\n if(x < 4.0) {\n double sqx = sqrt(x);\n double z = ATR/(x*sqx) + BTR;\n double y = sqrt(sqx);\n gsl_sf_result result_c;\n cheb_eval_mode_e(&bip_cs, z, mode, &result_c);\n result->val = (0.625 + result_c.val)/y;\n result->err = result_c.err/y + GSL_DBL_EPSILON * fabs(result->val);\n }\n else {\n double sqx = sqrt(x);\n double z = 16.0/(x*sqx) - 1.0;\n double y = sqrt(sqx);\n gsl_sf_result result_c;\n cheb_eval_mode_e(&bip2_cs, z, mode, &result_c);\n result->val = (0.625 + result_c.val)/y;\n result->err = result_c.err/y + GSL_DBL_EPSILON * fabs(result->val);\n }\n\n return GSL_SUCCESS;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_airy_Ai_e(const double x, const gsl_mode_t mode, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n\n if(x < -1.0) {\n gsl_sf_result mod;\n gsl_sf_result theta;\n gsl_sf_result cos_result;\n int stat_mp = airy_mod_phase(x, mode, &mod, &theta);\n int stat_cos = gsl_sf_cos_err_e(theta.val, theta.err, &cos_result);\n result->val = mod.val * cos_result.val;\n result->err = fabs(mod.val * cos_result.err) + fabs(cos_result.val * mod.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_mp, stat_cos);\n }\n else if(x <= 1.0) {\n const double z = x*x*x;\n gsl_sf_result result_c0;\n gsl_sf_result result_c1;\n cheb_eval_mode_e(&aif_cs, z, mode, &result_c0);\n cheb_eval_mode_e(&aig_cs, z, mode, &result_c1);\n result->val = 0.375 + (result_c0.val - x*(0.25 + result_c1.val));\n result->err = result_c0.err + fabs(x*result_c1.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n double x32 = x * sqrt(x);\n double s = exp(-2.0*x32/3.0);\n gsl_sf_result result_aie;\n int stat_aie = airy_aie(x, mode, &result_aie);\n result->val = result_aie.val * s;\n result->err = result_aie.err * s + result->val * x32 * GSL_DBL_EPSILON;\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n CHECK_UNDERFLOW(result);\n return stat_aie;\n }\n}\n\n\nint\ngsl_sf_airy_Ai_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 mod;\n gsl_sf_result theta;\n gsl_sf_result cos_result;\n int stat_mp = airy_mod_phase(x, mode, &mod, &theta);\n int stat_cos = gsl_sf_cos_err_e(theta.val, theta.err, &cos_result);\n result->val = mod.val * cos_result.val;\n result->err = fabs(mod.val * cos_result.err) + fabs(cos_result.val * mod.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_mp, stat_cos);\n }\n else if(x <= 1.0) {\n const double z = x*x*x;\n gsl_sf_result result_c0;\n gsl_sf_result result_c1;\n cheb_eval_mode_e(&aif_cs, z, mode, &result_c0);\n cheb_eval_mode_e(&aig_cs, z, mode, &result_c1);\n result->val = 0.375 + (result_c0.val - x*(0.25 + result_c1.val));\n result->err = result_c0.err + fabs(x*result_c1.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n\n if(x > 0.0) {\n const double scale = exp(2.0/3.0 * sqrt(z));\n result->val *= scale;\n result->err *= scale;\n }\n\n return GSL_SUCCESS;\n }\n else {\n return airy_aie(x, mode, result);\n }\n}\n\n\nint gsl_sf_airy_Bi_e(const double x, gsl_mode_t mode, gsl_sf_result * result)\n{\n /* CHECK_POINTER(result) */\n if(x < -1.0) {\n gsl_sf_result mod;\n gsl_sf_result theta;\n gsl_sf_result sin_result;\n int stat_mp = airy_mod_phase(x, mode, &mod, &theta);\n int stat_sin = gsl_sf_sin_err_e(theta.val, theta.err, &sin_result);\n result->val = mod.val * sin_result.val;\n result->err = fabs(mod.val * sin_result.err) + fabs(sin_result.val * mod.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_mp, stat_sin);\n }\n else if(x < 1.0) {\n const double z = x*x*x;\n gsl_sf_result result_c0;\n gsl_sf_result result_c1;\n cheb_eval_mode_e(&bif_cs, z, mode, &result_c0);\n cheb_eval_mode_e(&big_cs, z, mode, &result_c1);\n result->val = 0.625 + result_c0.val + x*(0.4375 + result_c1.val);\n result->err = result_c0.err + fabs(x * result_c1.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_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 = 1.125 + result_c0.val + x*(0.625 + result_c1.val);\n result->err = result_c0.err + fabs(x * result_c1.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n const double y = 2.0*x*sqrt(x)/3.0;\n const double s = exp(y);\n\n if(y > GSL_LOG_DBL_MAX - 1.0) {\n OVERFLOW_ERROR(result);\n }\n else {\n gsl_sf_result result_bie;\n int stat_bie = airy_bie(x, mode, &result_bie);\n result->val = result_bie.val * s;\n result->err = result_bie.err * s + fabs(1.5*y * (GSL_DBL_EPSILON * result->val));\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return stat_bie;\n }\n }\n}\n\n\nint\ngsl_sf_airy_Bi_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 mod;\n gsl_sf_result theta;\n gsl_sf_result sin_result;\n int stat_mp = airy_mod_phase(x, mode, &mod, &theta);\n int stat_sin = gsl_sf_sin_err_e(theta.val, theta.err, &sin_result);\n result->val = mod.val * sin_result.val;\n result->err = fabs(mod.val * sin_result.err) + fabs(sin_result.val * mod.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_ERROR_SELECT_2(stat_mp, stat_sin);\n }\n else if(x < 1.0) {\n const double z = x*x*x;\n gsl_sf_result result_c0;\n gsl_sf_result result_c1;\n cheb_eval_mode_e(&bif_cs, z, mode, &result_c0);\n cheb_eval_mode_e(&big_cs, z, mode, &result_c1);\n result->val = 0.625 + result_c0.val + x*(0.4375 + result_c1.val);\n result->err = result_c0.err + fabs(x * result_c1.err);\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n if(x > 0.0) {\n const double scale = exp(-2.0/3.0 * sqrt(z));\n result->val *= scale;\n result->err *= scale;\n }\n return GSL_SUCCESS;\n }\n else if(x <= 2.0) {\n const double x3 = x*x*x;\n const double z = (2.0*x3 - 9.0)/7.0;\n const double s = exp(-2.0/3.0 * sqrt(x3));\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 * (1.125 + result_c0.val + x*(0.625 + result_c1.val));\n result->err = s * (result_c0.err + fabs(x * result_c1.err));\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else {\n return airy_bie(x, mode, result);\n }\n}\n\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_airy_Ai(const double x, gsl_mode_t mode)\n{\n EVAL_RESULT(gsl_sf_airy_Ai_e(x, mode, &result));\n}\n\ndouble gsl_sf_airy_Ai_scaled(const double x, gsl_mode_t mode)\n{\n EVAL_RESULT(gsl_sf_airy_Ai_scaled_e(x, mode, &result));\n}\n\ndouble gsl_sf_airy_Bi(const double x, gsl_mode_t mode)\n{\n EVAL_RESULT(gsl_sf_airy_Bi_e(x, mode, &result));\n}\n\ndouble gsl_sf_airy_Bi_scaled(const double x, gsl_mode_t mode)\n{\n EVAL_RESULT(gsl_sf_airy_Bi_scaled_e(x, mode, &result));\n}\n\n\n", "meta": {"hexsha": "18b78107aa8de1608d93e7e45126db2c29774a0e", "size": 23546, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/airy.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/airy.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.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.0643678161, "max_line_length": 91, "alphanum_fraction": 0.6553979444, "num_tokens": 8392, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7185944046238982, "lm_q2_score": 0.3886180267058489, "lm_q1q2_score": 0.27925873952680363}} {"text": "/* DomSelfAdaptFWD.c\n\nForward-in-time simulation of an adaptive alleles with dominance and selfing, with linked neutral fragment.\n\nThis is the BATCH version - to be used on cluster machine to produce many simulation replicates at once.\n\nReps program: Reads in pre-calculated tables and introduces neutral mutations based on them. See README for more information.\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\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\n/* Function prototypes */\nvoid Wait();\nvoid fitness(unsigned int N, double h, double s, unsigned int *inpop, double *outfit, double *outcf, double *fitsum);\ndouble sumT_UI(unsigned int *Tin, unsigned int nrow);\nunsigned int parchoose(unsigned int N, double *culfit, double *fitsum, const gsl_rng *r);\nunsigned int bitswitch(unsigned int x);\nvoid rec_sort(double *index, unsigned int nrow);\nvoid generation(unsigned int N, double self, double R, unsigned int *nums, unsigned int *selin, unsigned int *selout, unsigned int **neutin, unsigned int **neutout, double *culfit, double *fitsum, unsigned int npoly, double *polypos, const gsl_rng *r);\nvoid addpoly(unsigned int N, unsigned int **neutin, double *polyloc, unsigned int *npoly, double theta, unsigned int maxsize, const gsl_rng *r);\nvoid reassign(unsigned int **neutin, unsigned int **neutout, unsigned int *selin, unsigned int *selout, unsigned int npoly, unsigned int N);\nvoid reassign2(unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int N);\nvoid polyprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N);\nvoid ptrim(unsigned int size, unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int *npolyT, double *avpi);\nvoid mutsamp(unsigned int N, unsigned int samps, unsigned int *selin, double *polypos, unsigned int **neutin, unsigned int *nums2, unsigned int npoly, unsigned int ei, unsigned int rep, const gsl_rng *r);\nvoid popread(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N, unsigned int ei, unsigned int suffix);\n\nvoid Wait(){\n\tprintf(\"Press Enter to Continue\");\n\twhile( getchar() != '\\n' );\n\tprintf(\"\\n\");\t\n}\n\n/* Fitness calculation routine */\nvoid fitness(unsigned int N, double h, double s, unsigned int *inpop, double *outfit, double *outcf, double *fitsum){\n\tunsigned int i;\t\t\t\t/* Pop counter */\n\tunsigned int ac = 0;\t\t/* Allele copies in indv */\n\t\n\t/* Calculating new fitnesses */\n *fitsum = 0;\n\tfor(i = 0; i < N; i++){\n\t\tac = 0;\n\t\tac = (*(inpop + 2*i)) + (*(inpop + 2*i + 1));\n\t\tif(ac == 0){\n\t\t\t*(outfit + i) = 1;\n\t\t}else if(ac == 1){\n\t\t\t*(outfit + i) = 1 + h*s;\n\t\t}else if(ac == 2){\n\t\t\t*(outfit + i) = 1 + s;\n\t\t}\n\t\t*fitsum += *(outfit + i);\n\t\t*(outcf + i) = *fitsum;\n }\n}\t/* End of fitness routine */\n\n/* Summing entire table (unsigned int) */\ndouble sumT_UI(unsigned int *Tin, unsigned int nrow){\n\tunsigned int i;\n\tdouble res = 0;\n\tfor(i = 0; i < nrow; i++){\n\t\tres += (*(Tin + i));\n\t}\n\treturn res;\n}\n\n/* Parent choosing */\nunsigned int parchoose(unsigned int N, double *culfit, double *fitsum, const gsl_rng *r){\n\t\t\n\tdouble a;\t\t\t\t\t/* Random number */\n\tunsigned int done = 0;\t\t/* Signal to determine whether selection complete */\n\tunsigned int cases = 0;\t\t/* Determines whether one should add up or decrease */\n\tunsigned int choose1 = 0;\t/* Chromosome to be selected */\n\tunsigned int firstgo = 0;\t/* First try at choosing progeny */\n\t\n\tdone = 0;\n\tcases = 0;\n\tchoose1 = 0;\n\ta = gsl_ran_flat(r,0.0,1.0);\n\tfirstgo = (int)N*a;\n\t\n\t/* Choosing case */\n\tif (((*(culfit + firstgo)/(*(fitsum))) >= a) && firstgo == 0){\n\t\tcases = 3;\n\t} else if (((*(culfit + firstgo)/(*(fitsum))) >= a) && firstgo != 0){\n\t\tcases = 2;\n\t} else {\n\t\tcases = 1;\n\t}\n\t\n\tswitch(cases)\n\t{\n\t\tcase 1:\n\t\t\twhile(done != 1){\n\t\t\t\tfirstgo++;\n\t\t\t\tif((*(culfit + firstgo)/(*(fitsum))) >= a){\n\t\t\t\t\tchoose1 = firstgo;\n\t\t\t\t\tdone = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\twhile(done != 1){\n\t\t\t\tfirstgo--;\n\t\t\t\tif((*(culfit + firstgo)/(*(fitsum))) < a || firstgo == 0){\n\t\t\t\t\tchoose1 = (firstgo + 1);\n\t\t\t\t\tdone = 1;\n\t\t\t\t}\n\t\t\t}\n\t\tbreak;\n\t\tcase 3:\n\t\t\tchoose1 = 0;\n\t\t\tbreak;\n\t}\n\t\n\treturn choose1;\n}\n\n/* Bit-switching routine */\nunsigned int bitswitch(unsigned int x){\n\tunsigned int ret;\n\tswitch(x)\n\t{\n\t\tcase 0:\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tret = 0;\n\t\t\tbreak;\t\t\n\t\tdefault:\t/* If none of these cases chosen, exit with error message */\n\t\t\tfprintf(stderr,\"Error in bitswitch: input is not 0 or 1.\\n\");\n\t\t\texit(1);\n break;\n\t}\n\treturn ret;\n}\n\n/* Sorting rec events after choosing them */\nvoid rec_sort(double *index, unsigned int nrow){\n\tunsigned int j, i;\t\t/* Sorting indices */\n\tdouble temp0;\t\t/* For swapping */\n\t\n\tfor(j = 1; j < nrow; j++){\n\t\ti = j;\n\t\twhile( (i > 0) && ( *(index + (i - 1) ) > *(index + i) )){\n\t\t\t/* Swapping entries */\n\t\t\ttemp0 = *(index + (i - 1));\n\t\t\t*(index + (i - 1)) = *(index + (i));\n\t\t\t*(index + (i)) = temp0;\t\t\t\n\t\t\ti--;\n\t\t}\n\t}\n\t\n}\n\n/* Reproduction routine */\nvoid generation(unsigned int N, double self, double R, unsigned int *nums, unsigned int *selin, unsigned int *selout, unsigned int **neutin, unsigned int **neutout, double *culfit, double *fitsum, unsigned int npoly, double *polypos, const gsl_rng *r){\n\tunsigned int i, j, k;\t\t/* Pop counter, neutral marker counter, rec event counter */\n\tunsigned int isself = 0;\t/* Is this a selfing reproduction? */\n\tunsigned int choose1 = 0;\t/* Chromosome to be selected */\n\tunsigned int choose2 = 0;\t/* Chromosome to be selected (2nd with outcrossing) */\n\tunsigned int wc1 = 0;\t\t/* Which chrom (parent 1) */\n\tunsigned int wc2 = 0;\t\t/* Which chrom (parent 2) */\n\tunsigned int index1 = 0;\t/* Index of chosen sample 1 */\n\tunsigned int index2 = 0;\t/* Index of chosen sample 2 */\n\tunsigned int nself = 0;\t\t/* Number of selfing events */\n\tunsigned int selfix = 0;\t/* Selfing index */\n\tunsigned int recix1 = 0;\t/* Rec index chr 1 */\n\tunsigned int recix2 = 0;\t/* Rec index chr 2 */\n\tunsigned int nrec1 = 0;\t\t/* Number rec events chr 1 */\n\tunsigned int nrec2 = 0;\t\t/* Number rec events chr 2 */\n\t\n\t/* First deciding number of selfing events; creating vector of events + choosing */\n\tnself = gsl_ran_binomial(r, self, N);\n\tunsigned int *selfev = calloc(nself,sizeof(unsigned int));\n\tgsl_ran_choose(r, selfev, nself, nums, N, sizeof(unsigned int));\n\t\t\n\tfor(i = 0; i < N; i++){\t\t/* Regenerating population */\n \t\n \t/* Choosing first parent, and relevant chromosomes */\n\t\tchoose1 = parchoose(N, culfit, fitsum, r);\n\t\twc1 = gsl_ran_bernoulli(r,0.5);\n\t\twc2 = gsl_ran_bernoulli(r,0.5);\n\t\tindex1 = 2*choose1 + wc1;\n\t\t\n\t\t/* Copying over selected sites, first checking if selfing occurs */\n\t\tisself = 0;\n\t\tif(nself != 0){\n\t\t\tif(*(selfev + selfix) == i){\n\t\t\t\tisself = 1;\n\t\t\t\tselfix++;\n\t\t\t}\n\t\t}\n\t\tif(isself == 1){\n\t\t\tindex2 = 2*choose1 + wc2;\n\t\t}else if(isself == 0){\n\t\t\tchoose2 = parchoose(N, culfit, fitsum, r);\n\t\t\tindex2 = 2*choose2 + wc2;\n\t\t}\n\t\t(*(selout + 2*i)) = (*(selin + index1));\n\t\t(*(selout + 2*i + 1)) = (*(selin + index2));\n\t\t\n\t\t/* Now copying over neutral fragment, accounting for recombination */\n\t\tif(R != 0){\n\t\t\t/* Choosing number of recombination events on arms 1, 2 */\n\t\t\trecix1 = 0;\n\t\t\trecix2 = 0;\n\t\t\tnrec1 = gsl_ran_poisson(r,R);\n\t\t\tnrec2 = gsl_ran_poisson(r,R);\n\t\t\tdouble *recev1 = calloc(nrec1 + 1,sizeof(double));\n\t\t\tdouble *recev2 = calloc(nrec2 + 1,sizeof(double));\n\t\t\tfor(k = 0; k < nrec1; k++){\n\t\t\t\t*(recev1 + k) = gsl_ran_flat(r,0,1);\n\t\t\t}\n\t\t\tfor(k = 0; k < nrec2; k++){\n\t\t\t\t*(recev2 + k) = gsl_ran_flat(r,0,1);\n\t\t\t}\n\t\t\t*(recev1 + nrec1) = 1.01;\n\t\t\t*(recev2 + nrec2) = 1.01;\t\t\t\n\t\t\trec_sort(recev1,nrec1 + 1);\n\t\t\trec_sort(recev2,nrec2 + 1);\n\t\t\t\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\tif( (*(polypos + j)) >= *(recev1 + recix1)){\n\t\t\t\t\twc1 = bitswitch(wc1);\n\t\t\t\t\tindex1 = 2*choose1 + wc1;\n\t\t\t\t\trecix1++;\n\t\t\t\t}\n\t\t\t\tif( (*(polypos + j)) >= *(recev2 + recix2)){\n\t\t\t\t\twc2 = bitswitch(wc2);\n\t\t\t\t\tif(isself == 1){\n\t\t\t\t\t\tindex2 = 2*choose1 + wc2;\n\t\t\t\t\t}else if(isself == 0){\n\t\t\t\t\t\tindex2 = 2*choose2 + wc2;\n\t\t\t\t\t}\n\t\t\t\t\trecix2++;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t*((*(neutout + 2*i)) + j) = *((*(neutin + index1)) + j);\n\t\t\t\t*((*(neutout + 2*i + 1)) + j) = *((*(neutin + index2)) + j);\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tfree(recev1);\n\t\t\tfree(recev2);\n\t\t\t\n\t\t}else if (R == 0){\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\t*((*(neutout + 2*i)) + j) = *((*(neutin + index1)) + j);\n\t\t\t\t*((*(neutout + 2*i + 1)) + j) = *((*(neutin + index2)) + j);\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfree(selfev);\n\t\n}\t/* End of reproduction routine */\n\n/* Adding neutral polymorphism routine */\nvoid addpoly(unsigned int N, unsigned int **neutin, double *polyloc, unsigned int *npoly, double theta, unsigned int maxsize, const gsl_rng *r){\n\tunsigned int i, j;\n\tint k;\n\tunsigned int newpoly = 0;\t\t\t/* Number of new polymorphisms added */\n\tunsigned int pchr = 0;\t\t\t\t/* Chromosome of appearance */\n\tunsigned int pfound = 0;\t\t\t/* Flag to denote if right index found */\n\tdouble ploc = 0;\t\t\t\t\t/* Location of polymorphism */\n/*\tFILE *ofp_poly;\t\t\t\t Pointer for polymorphisms output */\t\n\t\n\tnewpoly = gsl_ran_poisson(r,(0.5*theta));\n/*\tprintf(\"Add %d new polymorphisms\\n\",newpoly);*/\n\t\n\tfor(j = 0; j < newpoly; j++){\n\t\tploc = gsl_ran_flat(r,0.0,1.0);\n/*\t\tprintf(\"ploc is %lf\\n\",ploc);\t\t*/\n\t\tpchr = gsl_rng_uniform_int(r,2*N);\n/*\t\tprintf(\"pchr is %d\\n\",pchr);\t\t*/\n\t\t\n\t\t/* Inserting new polymorphism */\n\t\tif(*(npoly) == 0){\n/*\t\t\tprintf(\"zero entry here\\n\");\t*/\n\t\t\t*(polyloc + 0) = ploc;\n\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t*((*(neutin + i)) + 0) = 0;\n\t\t\t\t}\n\t\t\t*((*(neutin + pchr)) + 0) = 1;\n\t\t}else if(*(npoly) > 0){\n/*\t\t\tprintf(\"non-zero entry here\\n\");\t\t*/\n\t\t\tpfound = 0;\n\t\t\tfor(k = (*(npoly) - 1); k >= 0; k--){\n/*\t\t\t\tprintf(\"k is %d\\n\",k);*/\n\t\t\t\tif(*(polyloc + k) > ploc){\t\n/*\t\t\t\t\tprintf(\"is here 1\\n\");*/\n\t\t\t\t\t*(polyloc + k + 1) = *(polyloc + k);\n\t\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t\t*((*(neutin + i)) + k + 1) = *((*(neutin + i)) + k);\n\t\t\t\t\t}\n\t\t\t\t}else if(*(polyloc + k) <= ploc){\n/*\t\t\t\t\tprintf(\"is here 2\\n\");\t\t\t\t*/\n\t\t\t\t\tpfound = 1;\n\t\t\t\t\t*(polyloc + k + 1) = ploc;\n\t\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t\t*((*(neutin + i)) + k + 1) = 0;\n\t\t\t\t\t}\n\t\t\t\t\t*((*(neutin + pchr)) + k + 1) = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\n\t\t\t}\n\n\t\t\tif(pfound == 0){\t\t/* In this case polymorphism is inserted at the start */\n\t\t\t\t*(polyloc + 0) = ploc;\n\t\t\t\tfor(i = 0; i < 2*N; i++){\n\t\t\t\t\t*((*(neutin + i)) + 0) = 0;\n\t\t\t\t}\n\t\t\t\t*((*(neutin + pchr)) + 0) = 1;\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\t*(npoly) += 1;\n/*\t\tprintf(\"n poly is %d\\n\",*(npoly));\t\t\t*/\n\t\tif(*(npoly) == maxsize){\n\t\t\tfprintf(stderr,\"Too many neutral polymorphisms.\\n\");\n\t\t\texit(1);\n\t\t}\n\t\t\n\t}\n}\n\n/* Reassigning new population routine */\nvoid reassign(unsigned int **neutin, unsigned int **neutout, unsigned int *selin, unsigned int *selout, unsigned int npoly, unsigned int N){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\t\n\tfor(i = 0; i < 2*N; i++){\n\t\t*(selout + i) = *(selin + i);\n\t\tfor(j = 0; j < npoly; j++){\n\t\t\t*((*(neutout + i)) + j) = *((*(neutin + i)) + j);\n\t\t}\n\t}\n\t\n}\t/* End of reassignment routine */\n\n/* Reassigning new population routine (after trimming) */\nvoid reassign2(unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int N){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\t\n\tfor(i = 0; i < 2*N; i++){\n\t\tfor(j = 0; j < npoly; j++){\n\t\t\t*((*(neutout + i)) + j) = *((*(neutin + i)) + j);\n\t\t\tif(i == 0){\n\t\t\t\t*(posout + j) = *(posin + j);\n\t\t\t}\n\t\t}\n\t}\n\t\n}\t/* End of reassignment routine */\n\n/* Printing polymorphism routines */\nvoid polyprint(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\t\n\tfor(j = 0; j < npoly; j++){\n\t\tprintf(\"%lf \",*(posin + j));\n\t\tfor(i = 0; i < 2*N; i++){\n\t\t\tprintf(\"%d \",*((*(neutin + i)) + j));\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tWait();\n\t\n}\t/* End of reassignment routine */\n\n/* Cutting out non-polymorphic sites */\nvoid ptrim(unsigned int size, unsigned int **neutin, unsigned int **neutout, double *posin, double *posout, unsigned int npoly, unsigned int *npolyT, double *avpi){\n\tunsigned int i, j;\n\tunsigned int newp = 0;\t\t/* New number of polymorphisms */\n\tunsigned int count = 0;\t\t/* Polymorphism count */\n\tdouble cumpi = 0;\t\t\t/* Cumulative pi (diversity) */\n\n/*\tprintf(\"Trimming routine activated\\n\");\t*/\n\tfor(j = 0; j < npoly; j++){\n\t\tcount = 0;\n\t\t*(posout + newp) = *(posin + j);\n\t\tfor(i = 0; i < size; i++){\n\t\t\t*((*(neutout + i)) + newp) = *((*(neutin + i)) + j);\n\t\t\tcount += *((*(neutin + i)) + j);\n\t\t}\n/*\t\tprintf(\"For poly %d, count is %d\\n\",j,count);*/\n\t\tif((count > 0) && (count < size)){\n/*\t\t\tprintf(\"Keeping poly %d\\n\",j);\t*/\n\t\t\tnewp++;\n\t\t\tcumpi += ((count*(size-count))/(1.0*size*size));\n/*\t\t\tprintf(\"Count is %d, freq is %lf, cumulative value is %lf\\n\",count,count/(1.0*size),cumpi);\t*/\n\t\t}\n\t}\n\t\n\t*npolyT = newp;\n\t*avpi = (cumpi/(1.0*newp));\n}\n\n/* Producing mutational samples */\nvoid mutsamp(unsigned int N, unsigned int samps, unsigned int *selin, double *polypos, unsigned int **neutin, unsigned int *nums2, unsigned int npoly, unsigned int ei, unsigned int rep, const gsl_rng *r){\n\n\tunsigned int a, j, x;\n\tunsigned int currsamp;\n\tunsigned int npolyT;\n\tdouble avpi;\n\tchar Mout[32];\t\t\t\t /* String to hold filename in (Mutations) */\n\tFILE *ofp_mut = NULL;\t\t /* Pointer for data output */\n\t\n\tfor(x = 0; x < rep; x++){\n\t\n\t\tdouble *polyposF = calloc(npoly,sizeof(double));\t\t\t\t\t\t/* Position of neutral mutations (final for polymorphism sampling) */\n\t\tunsigned int *selsamp = calloc(samps,sizeof(unsigned int *));\t\t\t/* State of selected locus after sim stops */\n\t\tunsigned int **nsamp = calloc(samps,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (final for sampling) */\n\t\tunsigned int **nsampT = calloc(samps,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (final for sampling) AFTER TRIMMING */\n\t\tfor(a = 0; a < samps; a++){\n\t\t\tnsamp[a] = calloc(npoly,sizeof(unsigned int));\t\n\t\t\tnsampT[a] = calloc(npoly,sizeof(unsigned int));\t\t\t\t\n\t\t}\n\t\t\n\t\tnpolyT = npoly;\n\t\n\t\t/* Choosing which haplotypes to sample */\n\t\tunsigned int *thesamp = calloc(samps,sizeof(unsigned int));\n\t\tgsl_ran_choose(r, thesamp, samps, nums2, 2*N, sizeof(unsigned int));\n\t\n\t\tfor(a = 0; a < samps; a++){\n\t\t\tcurrsamp = *(thesamp + a);\n\t\t\t*(selsamp + a) = *(selin + currsamp);\n\t\t\tfor(j = 0; j < npoly; j++){\n\t\t\t\t*((*(nsamp + a)) + j) = *((*(neutin + currsamp)) + j);\n\t\t\t}\n\t\t}\n\t\t\n\t\t/* Check, then include code to ONLY print out polymorphic sites in table? */\n\t\tptrim(samps, nsamp, nsampT, polypos, polyposF, npoly, &npolyT, &avpi);\n\t\t\n\t\t/* Printing out sample table */\n\t\tsprintf(Mout,\"Mutations/Muts_%d.dat\",ei*rep + x);\n\t\tofp_mut = fopen(Mout,\"w\");\n\t\t\n\t\t/* State of selected site */\n\t\tfprintf(ofp_mut,\"0 \");\n\t\tfor(a = 0; a < samps; a++){\n\t\t\tfprintf(ofp_mut,\"%d \",*(selsamp + a));\n\t\t}\n\t\tfprintf(ofp_mut,\"\\n\");\n\t\t\n\t\tfor(j = 0; j < npolyT; j++){\n\t\t\tfprintf(ofp_mut,\"%lf \",*(polyposF + j));\n\t\t\tfor(a = 0; a < samps; a++){\n\t\t\t\tfprintf(ofp_mut,\"%d \",*((*(nsampT + a)) + j));\n\t\t\t}\n\t\t\tfprintf(ofp_mut,\"\\n\");\n\t\t}\n\t\tfclose(ofp_mut);\n\t\n\t\tfor(a = 0; a < samps; a++){\n\t\t\tfree(nsampT[a]);\t\t\n\t\t\tfree(nsamp[a]);\n\t\t}\n\t\tfree(nsampT);\t\t\n\t\tfree(nsamp);\n\t\tfree(thesamp);\n\t\tfree(selsamp);\t\t\n\t\tfree(polyposF);\n\t\n\t}\n}\n\n/* Reading population state from file */\nvoid popread(unsigned int **neutin, double *posin, unsigned int npoly, unsigned int N, unsigned int ei, unsigned int suffix){\n\tunsigned int i, j;\t\t/* pop counter, poly counter */\n\tchar Pin[32];\t\t\t\t /* String to hold filename in (Mutations) */\n\tFILE *ifp_poly = NULL;\t\t /* Pointer for data output */\n\t\n\t/* Printing out polymorphism table */\n\tsprintf(Pin,\"Pop_%d.dat\",ei + suffix);\n\tifp_poly = fopen(Pin,\"r\");\n\tfor(j = 0; j < npoly; j++){\n\t\t/* Is this the right way of reading in the first column of file? */\n\t\tfor(i = 0; i < (2*N + 1); i++){\n\t\t\tif(i == 0){\n\t\t\t\tfscanf(ifp_poly,\"%lf\",&(posin[j]));\n\t\t\t}else if(i > 0){\n\t\t\t\tfscanf(ifp_poly,\"%d\",&(neutin[(i-1)][j]));\n\t\t\t}\n\t\t}\n\t\tfprintf(ifp_poly,\"\\n\");\n\t}\n\tfclose(ifp_poly);\n\t\t\n}\t/* End of population reading routine */\n\n/* Main program */\nint main(int argc, char *argv[]){\n\n\t/* Declare variables here */\n\tunsigned int a, i, x;\t\t/* Counters */\n\tunsigned int N = 0;\t\t\t/* Population Size */\n\tunsigned int initp = 0;\t\t/* Initial location of mutant (individual) */\n\tunsigned int done = 0;\t\t/* Is simulation done or not? */\n\tunsigned int dcopies = 0;\t/* Number of copies of derived allele */\n\tunsigned int afix = 0;\t\t/* Has allele fixed? */\n\tunsigned int npoly = 0;\t\t/* Number of neutral alleles */\n\tunsigned int npolyB = 0;\t/* BASELINE number of neutral alleles at simulation initiation */\t\n\tunsigned int npolyT = 0;\t/* Number of neutral alleles (after cutting out fixed sites) */\t\n\tunsigned int nowsel = 0;\t/* If derived allele selected for? */\n\tunsigned int samps = 0;\t\t/* Number of samples to take */\n\tunsigned int suffix = 0;\t/* Number of times to subsample from population */\n\tunsigned int base = 0;\t\t/* Number of baseline forward-in-time simulations */\n\tunsigned int rps = 0;\t\t/* Samples taken per baseline simulation */\n\tunsigned int INITTS = 0;\t/* Initial size of mutation array */\n/*\tunsigned int n = 0;\t\t\tsprintf counter */\n\tdouble s = 0;\t\t\t\t/* Strength of selection */\n\tdouble h = 0;\t\t\t\t/* Dominance level */\n\tdouble self = 0;\t\t\t/* Selfing rate */\n\tdouble Rin = 0;\t\t\t\t/* Recombination rate (input) */\n\tdouble R = 0;\t\t\t\t/* Recombination rate (at a time) */\t\n\tdouble x0 = 0;\t\t\t\t/* Initial allele frequency */\n\tdouble xfix = 0;\t\t\t/* Final allele frequency (i.e. stop when allele reaches this frequency) */\n\tdouble theta = 0;\t\t\t/* Rate of neutral mutation */\n\tdouble fitsum = 0;\t\t\t/* Summed Fitness */\n\tdouble scurr = 0;\t\t\t/* Current fitness of mutant (to account for initial neutrality) */\n\tdouble avpi = 0;\n\tchar Pout[32];\t\t\t\t/* String to hold filename in (Mutations) */\t\n\tchar Sout[32];\t\t\t\t/* String to hold filename in (Seed) */\t\t\n\tFILE *ofp_sd;\t\t\t\t/* Pointer for seed output */\n\tFILE *ofp_poly;\t\t\t\t/* Pointer for polymorphisms output */\n\t\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\tif(argc != 14){\n\t\tfprintf(stderr,\"Not enough inputs (need: N s h self R x0 xfix theta basereps reps-per-sim samples suffix npoly).\\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\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\tself = strtod(argv[4],NULL);\n\tif(self < 0 || self > 1){\n\t\tfprintf(stderr,\"Selfing rate must lie between 0 and 1 (inclusive).\\n\");\n\t\texit(1);\n\t}\n\t\t\n\tRin = strtod(argv[5],NULL);\n\tif(Rin < 0){\n\t\tfprintf(stderr,\"Recombination rate must be positive or zero.\\n\");\n\t\texit(1);\n\t}\n\tRin /= 2.0*N;\n\t\n\tx0 = strtod(argv[6],NULL);\n\tif(x0 < (1.0/(2.0*N)) || x0 > 1.0-(1.0/(2.0*N)) ){\n\t\tfprintf(stderr,\"Initial mutant frequency must lie between 1/2N and 1-1/2N.\\n\");\n\t\texit(1);\n\t}\n\t\n\txfix = strtod(argv[7],NULL);\n\tif(xfix < 0 || xfix > 1.0 ){\n\t\tfprintf(stderr,\"Final mutant frequency must lie between 0 and 1.\\n\");\n\t\texit(1);\n\t}\n\tif(xfix <= x0){\n\t\tfprintf(stderr,\"Final mutant frequency must be greater than initial mutant frequency.\\n\");\n\t\texit(1);\n\t}\n\t\n\ttheta = strtod(argv[8],NULL);\n\tif(theta <= 0){\n\t\tfprintf(stderr,\"Mutation rate must be a positive value.\\n\");\n\t\texit(1);\n\t}\n\t\n\tbase = atoi(argv[9]);\n\tif(base <= 0){\n\t\tfprintf(stderr,\"Number of baseline simulations must be greater than zero.\\n\");\n\t\texit(1);\n\t}\n\t\n\trps = atoi(argv[10]);\n\tif(rps <= 0){\n\t\tfprintf(stderr,\"Number of reps per simulation must be > 0.\\n\");\n\t\texit(1);\n\t}\n\t\n\tsamps = atoi(argv[11]);\n\tif(samps <= 0){\n\t\tfprintf(stderr,\"Number of samples taken must be > 0.\\n\");\n\t\texit(1);\n\t}\n\t\n\tsuffix = atoi(argv[12]);\n\tif(argv[12] < 0){\n\t\tfprintf(stderr,\"File index must be greater than or equal to zero.\\n\");\n\t\texit(1);\n\t}\n\t\n\tnpolyB = atoi(argv[13]);\n\tINITTS = 2*npolyB;\n\n\t/* create a generator chosen by the \n environment variable GSL_RNG_TYPE */\n \n mkdir(\"SeedsRep/\", 0777); \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\tsprintf(Sout,\"SeedsRep/Seed_%d.dat\",suffix);\n\tofp_sd = fopen(Sout,\"w\");\n\tfprintf(ofp_sd,\"%lu\\n\",gsl_rng_default_seed);\n\tfclose(ofp_sd);\n\n\tmkdir(\"Polymorphisms/\", 0777);\t\t\n\tmkdir(\"Mutations/\", 0777);\n\t\n\t/* Vector of 0 to (N-1) for sampling random numbers */\n\tunsigned int *nums = calloc(N,sizeof(unsigned int));\n\tunsigned int *nums2 = calloc(2*N,sizeof(unsigned int));\n\tfor(a = 0; a < 2*N; a++){\n\t\t*(nums2 + a) = a;\n\t\tif(a < N){\n\t\t\t*(nums + a) = a;\n\t\t}\n\t}\n\t\n\t/* Executing simulation */\n\tfor(i = 0; i < base; i++){\n\n/*\t\tprintf(\"Starting run %d\\n\",i);*/\n\t\n\t\tafix = 0;\n\t\tR = Rin;\n\t\twhile(afix != 1){\n\t\n\t\t\t/* Setting up selection, neutral tables per individual */\n\t\t\tdouble *fit = calloc(N,sizeof(double));\t\t\t\t\t\t\t\t\t/* Fitness of each individual */\n\t\t\tdouble *cumfit = calloc(N,sizeof(double));\t\t\t\t\t\t\t\t/* Cumulative fitness of each individual */\n\t\t\tdouble *polypos = calloc(INITTS,sizeof(double));\t\t\t\t\t\t/* Position of neutral mutations */\n\t\t\tdouble *polyposF = calloc(INITTS,sizeof(double));\t\t\t\t\t\t/* Position of neutral mutations (final for polymorphism sampling) */\n\t\t\tunsigned int *selindvP = calloc(2*N,sizeof(unsigned int));\t\t\t\t/* Table of derived allele states per individual (parents) */\n\t\t\tunsigned int *selindvO = calloc(2*N,sizeof(unsigned int));\t\t\t\t/* Table of derived allele states per individual (offspring) */\n\t\t\tunsigned int **neutindvP = calloc(2*N,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (parents) */\n\t\t\tunsigned int **neutindvO = calloc(2*N,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (offspring) */\n\t\t\tunsigned int **neutindvF = calloc(2*N,sizeof(unsigned int *));\t\t\t/* Table of neutral markers per individual (final for sampling) */\n\t\t\tfor(a = 0; a < 2*N; a++){\n\t\t\t\tneutindvP[a] = calloc(INITTS,sizeof(unsigned int));\t\n\t\t\t\tneutindvO[a] = calloc(INITTS,sizeof(unsigned int));\n\t\t\t\tneutindvF[a] = calloc(INITTS,sizeof(unsigned int));\t\t\t\n\t\t\t}\n\n\t\t\t/* Reassigning ancestral polymorphism state */\n\t\t\tnpoly = npolyB;\n\t\t\tpopread(neutindvP, polypos, npoly, N, i, suffix);\t\t\t\n/*\n\t\t\tpolyprint(neutindvP, polypos, npoly, N);\n\t\t\texit(1);\n*/\n\t\t\t/* Assigning initial mutant, calculating fitness */\n\t\t\tinitp = gsl_rng_uniform_int(r,2*N);\n\t\t\t*(selindvP + initp) = 1;\n\t\t\n\t\t\tif(x0 == 1.0/(2.0*N)){\n\t\t\t\tscurr = s;\n\t\t\t\tnowsel = 1;\n\t\t\t}else if(x0 > 1.0/(2.0*N)){\n\t\t\t\tscurr = 0;\n\t\t\t\tnowsel = 0;\n\t\t\t}\n\t/*\t\tprintf(\"scurr is %lf\\n\",scurr);\t*/\n\t\t\tfitness(N, h, scurr, selindvP, fit, cumfit, &fitsum);\n\t\n\t\t\tdone = 0;\n\t\t\twhile(done != 1){\n\t\t\t\t\t\t\n\t\t\t\t/* Generating new population */\n\t\t\t\tgeneration(N,self,R,nums,selindvP,selindvO,neutindvP,neutindvO,cumfit,&fitsum,npoly,polypos,r);\n\t\t\n\t\t\t\t/* Neutral Mutation phase */\n\t\t\t\taddpoly(N, neutindvO, polypos, &npoly, theta, INITTS, r);\n\t\t\t\n\t\t\t\t/* Reassigning matrices */\n\t\t\t\treassign(neutindvO, neutindvP, selindvO, selindvP, npoly, N);\n\t\t\t\t\n\t\t\t\t/* Garbage collection of non-polymorphic sites */\n\t\t\t\tptrim(2*N, neutindvP, neutindvF, polypos, polyposF, npoly, &npolyT,&avpi);\n\t\t\t\tnpoly = npolyT;\n\t\t\t\treassign2(neutindvF, neutindvP, polyposF, polypos, npoly, N);\n\t\t\t\t\t\t\t\t\n\t\t\t\t/* Checking derived allele copies and whether it has fixed or lost */\n\t\t\t\tdcopies = sumT_UI(selindvP, 2.0*N);\n\t\t\t\t/*\n\t\t\t\tprintf(\"Dcopies are %d\\n\",dcopies);\t\t\t\t\n\t\t\t\tprintf(\"copies are %d, npoly are %d\\n\",dcopies,npoly);\n\t\t\t\t*/\n\t\t\t\tif(dcopies == 0){\n\t\t\t\t\tdone = 1;\n/*\t\t\t\t\tprintf(\"Selected allele lost\\n\");*/\n\t\t\t\t}\n\t\t\t\tif(dcopies >= (int)(2.0*N*xfix)){\n\t\t\t\t\tdone = 1;\n\t\t\t\t\tafix = 1;\n\t\t\t\t}\n\t\t\t\n\t\t\t\t/* Deciding if derived allele becomes selected for, then updating fitness */\n\t\t\t\tif(((dcopies/(2.0*N)) >= x0) && nowsel == 0){\n\t\t\t\t\tnowsel = 1;\n\t\t\t\t\tscurr = s;\n/*\t\t\t\t\tprintf(\"scurr is %lf\\n\",scurr);\t*/\n\t\t\t\t}\n\t\t\t\tfitness(N, h, scurr, selindvP, fit, cumfit, &fitsum);\n\t\t\t}\n\t\t\n\t\t\t/* Routine to print out polymorphisms if allele fixed */\n\t\t\tif(afix == 1){\n\t\t\t\n\t\t\t\tprintf(\"Selected allele fixed\\n\");\n\t\t\t\n\t\t\t\t/* First, remove non-polymorphic sites */\n\t\t\t\tptrim(2*N, neutindvP, neutindvF, polypos, polyposF, npoly, &npolyT,&avpi);\n\t\t\t\tnpoly = npolyT;\n\t\t\n\t\t\t\t/* Printing out polymorphism table */\n\t\t\t\tsprintf(Pout,\"Polymorphisms/Poly_%d.dat\",i + suffix);\n\t\t\t\tofp_poly = fopen(Pout,\"w\");\n\t\t\t\t\n\t\t\t\t/* State of selected site */\n\t\t\t\tfprintf(ofp_poly,\"0 \");\n\t\t\t\tfor(x = 0; x < 2*N; x++){\n\t\t\t\t\tfprintf(ofp_poly,\"%d \",*(selindvP + x));\n\t\t\t\t}\n\t\t\t\tfprintf(ofp_poly,\"\\n\");\n\t\t\t\t\n\t\t\t\t/* State of neutral sites */\n\t\t\t\tfor(a = 0; a < npoly; a++){\n\t\t\t\t\tfprintf(ofp_poly,\"%lf \",*(polyposF + a));\n\t\t\t\t\tfor(x = 0; x < 2*N; x++){\n\t\t\t\t\t\tfprintf(ofp_poly,\"%d \",*((*(neutindvF + x)) + a));\n\t\t\t\t\t}\n\t\t\t\t\tfprintf(ofp_poly,\"\\n\");\n\t\t\t\t}\n\t\t\t\tfclose(ofp_poly);\n\t\t\n\t\t\t\t/* Then, sample from this table to produce pseudo-coalescent results */\n\t\t\t\tmutsamp(N, samps, selindvP, polyposF, neutindvF, nums2, npoly, i + suffix, rps, r);\n\t\t\t\n\t\t\t}\n\t\t\n\t\t\t/* End of run; freeing memory */\n\t\t\tfor(a = 0; a < 2*N; a++){\n\t\t\t\tfree(neutindvF[a]);\t\t\n\t\t\t\tfree(neutindvO[a]);\n\t\t\t\tfree(neutindvP[a]);\n\t\t\t}\t\n\t\t\tfree(neutindvF);\n\t\t\tfree(neutindvO);\n\t\t\tfree(neutindvP);\n\t\t\tfree(selindvO);\n\t\t\tfree(selindvP);\n\t\t\tfree(polyposF);\n\t\t\tfree(polypos);\n\t\t\tfree(cumfit);\t\t\n\t\t\tfree(fit);\n\t\t}\n\t\n\t}\n\n\tfree(nums2);\t\n\tfree(nums);\n\tgsl_rng_free(r);\t\n\treturn 0;\n\t\n}\t/* End of main program */\n\n/* End of File */", "meta": {"hexsha": "f438adb58c2744d86162cefb023e0875a94c6941", "size": 25694, "ext": "c", "lang": "C", "max_stars_repo_path": "DomSelfAdaptFWD_RepsRec.c", "max_stars_repo_name": "MattHartfield/DomSelfAdapt", "max_stars_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "DomSelfAdaptFWD_RepsRec.c", "max_issues_repo_name": "MattHartfield/DomSelfAdapt", "max_issues_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "DomSelfAdaptFWD_RepsRec.c", "max_forks_repo_name": "MattHartfield/DomSelfAdapt", "max_forks_repo_head_hexsha": "73cde4d7936bb6645397f9931dade99a818e4c49", "max_forks_repo_licenses": ["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.6818742293, "max_line_length": 252, "alphanum_fraction": 0.6072623959, "num_tokens": 8387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2792177400426444}} {"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/*\n * Spline the linear power spectrum for mu-Sigma MG cosmologies.\n * @param cosmo Cosmological parameters\n ^ @param psp The linear power spectrum to spline.\n * @param status, integer indicating the status\n */\nvoid ccl_rescale_musigma_s8(ccl_cosmology* cosmo, ccl_f2d_t *psp,\n int mg_rescale, int* status) {\n\n int do_mg = mg_rescale && (fabs(cosmo->params.mu_0) > 1e-14);\n int do_s8 = isfinite(cosmo->params.sigma8) && (!isfinite(cosmo->params.A_s));\n\n if (!do_mg && !do_s8)\n return;\n\n size_t na;\n double *aa;\n double rescale_extra_musig = 1;\n double *rescale_factor = NULL;\n\n if (*status == 0) {\n // Get array of scale factors\n if(psp->fa != NULL) {\n na = psp->fa->size;\n aa = psp->fa->x;\n }\n else if(psp->fka != NULL) {\n na = psp->fka->interp_object.ysize;\n aa = psp->fka->yarr;\n }\n else {\n *status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"input pk2d has no splines.\\n\");\n }\n }\n\n // Alloc rescale_factor\n if(*status == 0) {\n rescale_factor = malloc(na * sizeof(double));\n if(rescale_factor == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): memory allocation\\n\");\n }\n }\n\n // set to 1 by default\n if(*status == 0) {\n for(int i=0; iparams.N_nu_mass; i=i+1)\n mnu_list[i] = cosmo->params.m_nu[i];\n\n if (isfinite(cosmo->params.A_s)) {\n norm_pk = cosmo->params.A_s;\n }\n else if (isfinite(cosmo->params.sigma8)) {\n norm_pk = cosmo->params.sigma8;\n }\n else {\n *status = CCL_ERROR_PARAMETERS;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"neither A_s nor sigma8 defined.\\n\");\n }\n\n if (*status == 0) {\n params_GR = ccl_parameters_create(\n cosmo->params.Omega_c, cosmo->params.Omega_b, cosmo->params.Omega_k,\n cosmo->params.Neff, mnu_list, cosmo->params.N_nu_mass,\n cosmo->params.w0, cosmo->params.wa, cosmo->params.h,\n norm_pk, cosmo->params.n_s,\n cosmo->params.bcm_log10Mc, cosmo->params.bcm_etab,\n cosmo->params.bcm_ks, 0., 0., cosmo->params.nz_mgrowth,\n cosmo->params.z_mgrowth, cosmo->params.df_mgrowth, status);\n\n if (*status) {\n *status = CCL_ERROR_PARAMETERS;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"could not make MG params.\\n\");\n }\n }\n\n if (*status == 0) {\n cosmo_GR = ccl_cosmology_create(params_GR, cosmo->config);\n\n if (cosmo_GR == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"error initializing cosmology\\n\");\n }\n }\n\n if (*status == 0) {\n ccl_cosmology_compute_growth(cosmo_GR, status);\n\n if (*status) {\n *status = CCL_ERROR_PARAMETERS;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"could not init GR growth.\\n\");\n }\n }\n\n // Populate rescale_factor\n if (*status == 0) {\n for (int i=0; iparams.sigma8/ccl_sigma8(cosmo, psp, status);\n renorm *= renorm;\n renorm /= rescale_extra_musig;\n\n for (int i=0; ifka != NULL)\n nk=psp->fka->interp_object.xsize;\n\n // Rescale\n for (int i=0; ifa != NULL) {\n if(psp->is_log)\n psp->fa->y[i] += log(rescale_factor[i]);\n else\n psp->fa->y[i] *= rescale_factor[i];\n }\n else {\n for(int j=0; jis_log)\n psp->fka->zarr[i*nk+j] += log(rescale_factor[i]);\n else\n psp->fka->zarr[i*nk+j] *= rescale_factor[i];\n }\n }\n }\n\n //Respline\n if(psp->fa != NULL) {\n gsl_spline *fa = gsl_spline_alloc(gsl_interp_cspline,\n psp->fa->size);\n if(fa == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"memory allocation\\n\");\n }\n if(*status==0) {\n int spstatus = gsl_spline_init(fa, psp->fa->x,\n psp->fa->y, psp->fa->size);\n if(spstatus) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"Error initializing spline\\n\");\n }\n }\n if(*status==0) {\n gsl_spline_free(psp->fa);\n psp->fa=fa;\n }\n }\n else {\n gsl_spline2d *fka = gsl_spline2d_alloc(gsl_interp2d_bicubic,\n psp->fka->interp_object.xsize,\n psp->fka->interp_object.ysize); \n if(fka == NULL) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"memory allocation\\n\");\n }\n if(*status==0) {\n int spstatus = gsl_spline2d_init(fka, psp->fka->xarr,\n psp->fka->yarr, psp->fka->zarr,\n psp->fka->interp_object.xsize,\n psp->fka->interp_object.ysize);\n if(spstatus) {\n *status = CCL_ERROR_MEMORY;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_musigma.c: ccl_rescale_musigma_s8(): \"\n \"Error initializing spline\\n\");\n }\n }\n if(*status==0) {\n gsl_spline2d_free(psp->fka);\n psp->fka=fka;\n }\n }\n }\n\n free(rescale_factor);\n}\n", "meta": {"hexsha": "5c36cb56e3f31f087deb53bf5722eda4896ab5a9", "size": 7800, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_musigma.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_musigma.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_musigma.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": 30.9523809524, "max_line_length": 86, "alphanum_fraction": 0.5519230769, "num_tokens": 2234, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.665410558746814, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2786053443999316}} {"text": "/**\n *\n * @file core_zpemv.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 Dulceneia Becker\n * @date 2011-06-29\n * @precisions normal z -> c d s\n *\n **/\n#include \n#include \n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_PLASMA_Complex64_t\n *\n * CORE_zpemv performs one of the matrix-vector operations\n *\n * y = alpha*op( A )*x + beta*y\n *\n * where op( A ) is one of\n *\n * op( A ) = A or op( A ) = A**T or op( A ) = A**H,\n *\n * alpha and beta are scalars, x and y are vectors and A is a\n * pentagonal matrix (see further details).\n *\n *\n * Arguments\n * ==========\n *\n * @param[in] storev\n *\n * @arg PlasmaColumnwise : array A stored columwise\n * @arg PlasmaRowwise : array A stored rowwise\n *\n * @param[in] trans\n *\n * @arg PlasmaNoTrans : y := alpha*A*x + beta*y.\n * @arg PlasmaTrans : y := alpha*A**T*x + beta*y.\n * @arg PlasmaConjTrans : y := alpha*A**H*x + beta*y.\n *\n * @param[in] M\n * Number of rows of the matrix A.\n * M must be at least zero.\n *\n * @param[in] N\n * Number of columns of the matrix A.\n * N must be at least zero.\n *\n * @param[in] L\n * Order of triangle within the matrix A (L specifies the shape\n * of the matrix A; see further details).\n *\n * @param[in] ALPHA\n * Scalar alpha.\n *\n * @param[in] A\n * Array of size LDA-by-N. On entry, the leading M by N part\n * of the array A must contain the matrix of coefficients.\n *\n * @param[in] LDA\n * Leading dimension of array A.\n *\n * @param[in] X\n * On entry, the incremented array X must contain the vector x.\n *\n * @param[in] INCX\n * Increment for the elements of X. INCX must not be zero.\n *\n * @param[in] BETA\n * Scalar beta.\n *\n * @param[in,out] Y\n * On entry, the incremented array Y must contain the vector y.\n *\n * @param[out] INCY\n * Increment for the elements of Y. INCY must not be zero.\n *\n * @param[out] WORK\n * Workspace array of size at least L.\n *\n * Further Details\n * ===============\n *\n * | N |\n * _ ___________ _\n * | |\n * A: | |\n * M-L | |\n * | | M\n * _ |..... |\n * \\ : |\n * L \\ : |\n * _ \\:_____| _\n *\n * | L | N-L |\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#if defined(PLASMA_HAVE_WEAK)\n#pragma weak CORE_zpemv = PCORE_zpemv\n#define CORE_zpemv PCORE_zpemv\n#endif\nint CORE_zpemv(PLASMA_enum trans, int storev,\n int M, int N, int L,\n PLASMA_Complex64_t ALPHA,\n const PLASMA_Complex64_t *A, int LDA,\n const PLASMA_Complex64_t *X, int INCX,\n PLASMA_Complex64_t BETA,\n PLASMA_Complex64_t *Y, int INCY,\n PLASMA_Complex64_t *WORK)\n{\n\n /*\n * y = alpha * op(A) * x + beta * y\n */\n\n int K;\n static PLASMA_Complex64_t zzero = 0.0;\n\n\n /* Check input arguments */\n if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans) && (trans != PlasmaConjTrans)) {\n coreblas_error(1, \"Illegal value of trans\");\n return -1;\n }\n if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) {\n coreblas_error(2, \"Illegal value of storev\");\n return -2;\n }\n if (!( ((storev == PlasmaColumnwise) && (trans != PlasmaNoTrans)) ||\n ((storev == PlasmaRowwise) && (trans == PlasmaNoTrans)) )) {\n coreblas_error(2, \"Illegal values of trans/storev\");\n return -2;\n }\n if (M < 0) {\n coreblas_error(3, \"Illegal value of M\");\n return -3;\n }\n if (N < 0) {\n coreblas_error(4, \"Illegal value of N\");\n return -4;\n }\n if (L > min(M ,N)) {\n coreblas_error(5, \"Illegal value of L\");\n return -5;\n }\n if (LDA < max(1,M)) {\n coreblas_error(8, \"Illegal value of LDA\");\n return -8;\n }\n if (INCX < 1) {\n coreblas_error(10, \"Illegal value of INCX\");\n return -10;\n }\n if (INCY < 1) {\n coreblas_error(13, \"Illegal value of INCY\");\n return -13;\n }\n\n /* Quick return */\n if ((M == 0) || (N == 0))\n return PLASMA_SUCCESS;\n if ((ALPHA == zzero) && (BETA == zzero))\n return PLASMA_SUCCESS;\n\n /* If L < 2, there is no triangular part */\n if (L == 1) L = 0;\n\n /* Columnwise */\n if (storev == PlasmaColumnwise) {\n /*\n * ______________\n * | | | A1: A[ 0 ]\n * | | | A2: A[ M-L ]\n * | A1 | | A3: A[ (N-L) * LDA ]\n * | | |\n * |______| A3 |\n * \\ | |\n * \\ A2 | |\n * \\ | |\n * \\|_____|\n *\n */\n\n\n /* Columnwise / NoTrans */\n if (trans == PlasmaNoTrans) {\n coreblas_error(1, \"The case PlasmaNoTrans / PlasmaColumnwise is not yet implemented\");\n return -1;\n }\n /* Columnwise / [Conj]Trans */\n else {\n\n /* L top rows of y */\n if (L > 0) {\n\n /* w = A_2' * x_2 */\n cblas_zcopy(\n L, &X[INCX*(M-L)], INCX, WORK, 1);\n cblas_ztrmv(\n CblasColMajor, (CBLAS_UPLO)PlasmaUpper,\n (CBLAS_TRANSPOSE)trans,\n (CBLAS_DIAG)PlasmaNonUnit,\n L, &A[M-L], LDA, WORK, 1);\n\n if (M > L) {\n\n /* y_1 = beta * y_1 [ + alpha * A_1 * x_1 ] */\n cblas_zgemv(\n CblasColMajor, (CBLAS_TRANSPOSE)trans,\n M-L, L, CBLAS_SADDR(ALPHA), A, LDA,\n X, INCX, CBLAS_SADDR(BETA), Y, INCY);\n\n /* y_1 = y_1 + alpha * w */\n cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);\n\n } else {\n\n /* y_1 = y_1 + alpha * w */\n if (BETA == zzero) {\n cblas_zscal(L, CBLAS_SADDR(ALPHA), WORK, 1);\n cblas_zcopy(L, WORK, 1, Y, INCY);\n } else {\n cblas_zscal(L, CBLAS_SADDR(BETA), Y, INCY);\n cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);\n }\n }\n }\n\n /* N-L bottom rows of Y */\n if (N > L) {\n K = N - L;\n cblas_zgemv(\n CblasColMajor, (CBLAS_TRANSPOSE)trans,\n M, K, CBLAS_SADDR(ALPHA), &A[LDA*L], LDA,\n X, INCX, CBLAS_SADDR(BETA), &Y[INCY*L], INCY);\n }\n }\n }\n /* Rowwise */\n else {\n /*\n * --------------\n * | | \\ A1: A[ 0 ]\n * | A1 | \\ A2: A[ (N-L) * LDA ]\n * | | A2 \\ A3: A[ L ]\n * |--------------------\\\n * | A3 |\n * ----------------------\n *\n */\n\n /* Rowwise / NoTrans */\n if (trans == PlasmaNoTrans) {\n /* L top rows of A and y */\n if (L > 0) {\n\n /* w = A_2 * x_2 */\n cblas_zcopy(\n L, &X[INCX*(N-L)], INCX, WORK, 1);\n cblas_ztrmv(\n CblasColMajor, (CBLAS_UPLO)PlasmaLower,\n (CBLAS_TRANSPOSE)PlasmaNoTrans,\n (CBLAS_DIAG)PlasmaNonUnit,\n L, &A[LDA*(N-L)], LDA, WORK, 1);\n\n if (N > L) {\n\n /* y_1 = beta * y_1 [ + alpha * A_1 * x_1 ] */\n cblas_zgemv(\n CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans,\n L, N-L, CBLAS_SADDR(ALPHA), A, LDA,\n X, INCX, CBLAS_SADDR(BETA), Y, INCY);\n\n /* y_1 = y_1 + alpha * w */\n cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);\n\n } else {\n\n /* y_1 = y_1 + alpha * w */\n if (BETA == zzero) {\n cblas_zscal(L, CBLAS_SADDR(ALPHA), WORK, 1);\n cblas_zcopy(L, WORK, 1, Y, INCY);\n } else {\n cblas_zscal(L, CBLAS_SADDR(BETA), Y, INCY);\n cblas_zaxpy(L, CBLAS_SADDR(ALPHA), WORK, 1, Y, INCY);\n }\n }\n }\n\n /* M-L bottom rows of Y */\n if (M > L) {\n cblas_zgemv(\n CblasColMajor, (CBLAS_TRANSPOSE)PlasmaNoTrans,\n M-L, N, CBLAS_SADDR(ALPHA), &A[L], LDA,\n X, INCX, CBLAS_SADDR(BETA), &Y[INCY*L], INCY);\n }\n }\n /* Rowwise / [Conj]Trans */\n else {\n coreblas_error(1, \"The case Plasma[Conj]Trans / PlasmaRowwise is not yet implemented\");\n return -1;\n }\n }\n\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "9cc2320c19affb70f62486dcdd95a42451c5bbdc", "size": 9805, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_zpemv.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_zpemv.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_zpemv.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3560371517, "max_line_length": 99, "alphanum_fraction": 0.4142784294, "num_tokens": 2701, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.27825224486071365}} {"text": "/* specfunc/transport.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\n#include \"error.h\"\n#include \"check.h\"\n\n#include \"chebyshev.h\"\n#include \"cheb_eval.c\"\n\nstatic double transport2_data[18] = {\n 1.671760446434538503,\n -0.147735359946794490,\n 0.148213819946936338e-01,\n -0.14195330326305613e-02,\n 0.1306541324415708e-03,\n -0.117155795867579e-04,\n 0.10333498445756e-05,\n -0.901911304223e-07,\n 0.78177169833e-08,\n -0.6744565684e-09,\n 0.579946394e-10,\n -0.49747619e-11,\n 0.425961e-12,\n -0.36422e-13,\n 0.3111e-14,\n -0.265e-15,\n 0.23e-16,\n -0.19e-17\n};\nstatic cheb_series transport2_cs = {\n transport2_data,\n 17,\n -1, 1,\n 9\n};\n\nstatic double transport3_data[18] = {\n 0.762012543243872007,\n -0.105674387705058533,\n 0.119778084819657810e-01,\n -0.12144015203698307e-02,\n 0.1155099769392855e-03,\n -0.105815992124423e-04,\n 0.9474663385302e-06,\n -0.836221212858e-07,\n 0.73109099278e-08,\n -0.6350594779e-09,\n 0.549118282e-10,\n -0.47321395e-11,\n 0.4067695e-12,\n -0.348971e-13,\n 0.29892e-14,\n -0.256e-15,\n 0.219e-16,\n -0.19e-17\n};\nstatic cheb_series transport3_cs = {\n transport3_data,\n 17,\n -1, 1,\n 9\n};\n\n\nstatic double transport4_data[18] = {\n 0.4807570994615110579,\n -0.8175378810321083956e-01,\n 0.1002700665975162973e-01,\n -0.10599339359820151e-02,\n 0.1034506245030405e-03,\n -0.96442705485899e-05,\n 0.8745544408515e-06,\n -0.779321207981e-07,\n 0.68649886141e-08,\n -0.5999571076e-09,\n 0.521366241e-10,\n -0.45118382e-11,\n 0.3892159e-12,\n -0.334936e-13,\n 0.28767e-14,\n -0.2467e-15,\n 0.211e-16,\n -0.18e-17\n};\nstatic cheb_series transport4_cs = {\n transport4_data,\n 17,\n -1, 1,\n 9\n};\n\n\nstatic double transport5_data[18] = {\n 0.347777777133910789,\n -0.66456988976050428e-01,\n 0.8611072656883309e-02,\n -0.9396682223755538e-03,\n 0.936324806081513e-04,\n -0.88571319340833e-05,\n 0.811914989145e-06,\n -0.72957654233e-07,\n 0.646971455e-08,\n -0.568490283e-09,\n 0.49625598e-10,\n -0.4310940e-11,\n 0.373100e-12,\n -0.32198e-13,\n 0.2772e-14,\n -0.238e-15,\n 0.21e-16,\n -0.18e-17\n};\nstatic cheb_series transport5_cs = {\n transport5_data,\n 17,\n -1, 1,\n 9\n};\n\n\nstatic\ndouble\ntransport_sumexp(const int numexp, const int order, const double t, double x)\n{\n double rk = (double)numexp;\n double sumexp = 0.0;\n int k;\n for(k=1; k<=numexp; k++) {\n double sum2 = 1.0;\n double xk = 1.0/(rk*x);\n double xk1 = 1.0;\n int j;\n for(j=1; j<=order; j++) {\n sum2 = sum2*xk1*xk + 1.0;\n xk1 += 1.0;\n }\n sumexp *= t;\n sumexp += sum2;\n rk -= 1.0;\n }\n return sumexp;\n}\n\n\n/*-*-*-*-*-*-*-*-*-*-*-* Functions with Error Codes *-*-*-*-*-*-*-*-*-*-*-*/\n\nint\ngsl_sf_transport_2_e(const double x, gsl_sf_result * result)\n{\n const double val_infinity = 3.289868133696452873;\n\n /* CHECK_POINTER(result) */\n\n if(x < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x < 3.0*GSL_SQRT_DBL_EPSILON) {\n result->val = x;\n result->err = GSL_DBL_EPSILON*fabs(x) + x*x/2.0;\n return GSL_SUCCESS;\n }\n else if(x <= 4.0) {\n double t = (x*x/8.0 - 0.5) - 0.5;\n gsl_sf_result result_c;\n cheb_eval_e(&transport2_cs, t, &result_c);\n result->val = x * result_c.val;\n result->err = x * result_c.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x < -GSL_LOG_DBL_EPSILON) {\n const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1;\n const double sumexp = transport_sumexp(numexp, 2, exp(-x), x);\n const double t = 2.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + fabs(t) * et);\n }\n return GSL_SUCCESS;\n }\n else if(x < 2.0/GSL_DBL_EPSILON) {\n const int numexp = 1;\n const double sumexp = transport_sumexp(numexp, 2, 1.0, x);\n const double t = 2.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n else {\n const double t = 2.0 * log(x) - x;\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_transport_3_e(const double x, gsl_sf_result * result)\n{ \n const double val_infinity = 7.212341418957565712;\n\n /* CHECK_POINTER(result) */\n\n if(x < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x < 3.0*GSL_SQRT_DBL_EPSILON) {\n result->val = 0.5*x*x;\n result->err = 2.0 * GSL_DBL_EPSILON * result->val;\n CHECK_UNDERFLOW(result);\n return GSL_SUCCESS;\n }\n else if(x <= 4.0) {\n const double x2 = x*x;\n const double t = (x2/8.0 - 0.5) - 0.5;\n gsl_sf_result result_c;\n cheb_eval_e(&transport3_cs, t, &result_c);\n result->val = x2 * result_c.val;\n result->err = x2 * result_c.err;\n result->err += GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x < -GSL_LOG_DBL_EPSILON) {\n const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1;\n const double sumexp = transport_sumexp(numexp, 3, exp(-x), x);\n const double t = 3.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + fabs(t) * et);\n }\n return GSL_SUCCESS;\n }\n else if(x < 3.0/GSL_DBL_EPSILON) {\n const int numexp = 1;\n const double sumexp = transport_sumexp(numexp, 3, 1.0, x);\n const double t = 3.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n else {\n const double t = 3.0 * log(x) - x;\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_transport_4_e(const double x, gsl_sf_result * result)\n{\n const double val_infinity = 25.97575760906731660;\n\n /* CHECK_POINTER(result) */\n\n if(x < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x < 3.0*GSL_SQRT_DBL_EPSILON) {\n result->val = x*x*x/3.0;\n result->err = 3.0 * GSL_DBL_EPSILON * result->val;\n CHECK_UNDERFLOW(result);\n return GSL_SUCCESS;\n }\n else if(x <= 4.0) {\n const double x2 = x*x;\n const double t = (x2/8.0 - 0.5) - 0.5;\n gsl_sf_result result_c;\n cheb_eval_e(&transport4_cs, t, &result_c);\n result->val = x2*x * result_c.val;\n result->err = x2*x * result_c.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x < -GSL_LOG_DBL_EPSILON) {\n const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1;\n const double sumexp = transport_sumexp(numexp, 4, exp(-x), x);\n const double t = 4.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n else if(x < 3.0/GSL_DBL_EPSILON) {\n const int numexp = 1;\n const double sumexp = transport_sumexp(numexp, 4, 1.0, x);\n const double t = 4.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n else {\n const double t = 4.0 * log(x) - x;\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n}\n\n\nint\ngsl_sf_transport_5_e(const double x, gsl_sf_result * result)\n{\n const double val_infinity = 124.4313306172043912;\n\n /* CHECK_POINTER(result) */\n\n if(x < 0.0) {\n DOMAIN_ERROR(result);\n }\n else if(x == 0.0) {\n result->val = 0.0;\n result->err = 0.0;\n return GSL_SUCCESS;\n }\n else if(x < 3.0*GSL_SQRT_DBL_EPSILON) {\n result->val = x*x*x*x/4.0;\n result->err = 4.0 * GSL_DBL_EPSILON * result->val;\n CHECK_UNDERFLOW(result);\n return GSL_SUCCESS;\n }\n else if(x <= 4.0) {\n const double x2 = x*x;\n const double t = (x2/8.0 - 0.5) - 0.5;\n gsl_sf_result result_c;\n cheb_eval_e(&transport5_cs, t, &result_c);\n result->val = x2*x2 * result_c.val;\n result->err = x2*x2 * result_c.err;\n result->err += 2.0 * GSL_DBL_EPSILON * fabs(result->val);\n return GSL_SUCCESS;\n }\n else if(x < -GSL_LOG_DBL_EPSILON) {\n const int numexp = (int)((-GSL_LOG_DBL_EPSILON)/x) + 1;\n const double sumexp = transport_sumexp(numexp, 5, exp(-x), x);\n const double t = 5.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n else if(x < 3.0/GSL_DBL_EPSILON) {\n const int numexp = 1;\n const double sumexp = transport_sumexp(numexp, 5, 1.0, x);\n const double t = 5.0 * log(x) - x + log(sumexp);\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n else {\n const double t = 5.0 * log(x) - x;\n if(t < GSL_LOG_DBL_EPSILON) {\n result->val = val_infinity;\n result->err = 2.0 * GSL_DBL_EPSILON * val_infinity;\n }\n else {\n const double et = exp(t);\n result->val = val_infinity - et;\n result->err = 2.0 * GSL_DBL_EPSILON * (val_infinity + (fabs(t)+1.0) * et);\n }\n return GSL_SUCCESS;\n }\n}\n\n/*-*-*-*-*-*-*-*-*-* Functions w/ Natural Prototypes *-*-*-*-*-*-*-*-*-*-*/\n\n#include \"eval.h\"\n\ndouble gsl_sf_transport_2(const double x)\n{\n EVAL_RESULT(gsl_sf_transport_2_e(x, &result));\n}\n\ndouble gsl_sf_transport_3(const double x)\n{\n EVAL_RESULT(gsl_sf_transport_3_e(x, &result));\n}\n\ndouble gsl_sf_transport_4(const double x)\n{\n EVAL_RESULT(gsl_sf_transport_4_e(x, &result));\n}\n\ndouble gsl_sf_transport_5(const double x)\n{\n EVAL_RESULT(gsl_sf_transport_5_e(x, &result));\n}\n", "meta": {"hexsha": "c55c13c10090e6f4ad37eeb5cc1f2dd4106324a9", "size": 12834, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/specfunc/transport.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/transport.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/transport.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.0324543611, "max_line_length": 81, "alphanum_fraction": 0.6178899797, "num_tokens": 4628, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.27807536927539545}} {"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\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\n/* This file was automatically generated --- DO NOT EDIT */\n/* Generated on Sun Nov 7 20:44:26 EST 1999 */\n\n#include \n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2real 15 */\n\n/*\n * This function contains 64 FP additions, 31 FP multiplications,\n * (or, 47 additions, 14 multiplications, 17 fused multiply/add),\n * 36 stack variables, and 30 memory accesses\n */\nstatic const fftw_real K1_118033988 = FFTW_KONST(+1.118033988749894848204586834365638117720309180);\nstatic const fftw_real K1_902113032 = FFTW_KONST(+1.902113032590307144232878666758764286811397268);\nstatic const fftw_real K1_175570504 = FFTW_KONST(+1.175570504584946258337411909278145537195304875);\nstatic const fftw_real K500000000 = FFTW_KONST(+0.500000000000000000000000000000000000000000000);\nstatic const fftw_real K866025403 = FFTW_KONST(+0.866025403784438646763723170752936183471402627);\nstatic const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);\nstatic const fftw_real K1_732050807 = FFTW_KONST(+1.732050807568877293527446341505872366942805254);\n\n/*\n * Generator Id's : \n * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $\n * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $\n * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $\n */\n\nvoid fftw_hc2real_15(const fftw_real *real_input, const fftw_real *imag_input, fftw_real *output, int real_istride, int imag_istride, int ostride)\n{\n fftw_real tmp3;\n fftw_real tmp30;\n fftw_real tmp18;\n fftw_real tmp37;\n fftw_real tmp61;\n fftw_real tmp62;\n fftw_real tmp45;\n fftw_real tmp40;\n fftw_real tmp23;\n fftw_real tmp31;\n fftw_real tmp42;\n fftw_real tmp28;\n fftw_real tmp32;\n fftw_real tmp8;\n fftw_real tmp13;\n fftw_real tmp14;\n ASSERT_ALIGNED_DOUBLE;\n {\n\t fftw_real tmp17;\n\t fftw_real tmp1;\n\t fftw_real tmp2;\n\t fftw_real tmp15;\n\t fftw_real tmp16;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp16 = imag_input[5 * imag_istride];\n\t tmp17 = K1_732050807 * tmp16;\n\t tmp1 = real_input[0];\n\t tmp2 = real_input[5 * real_istride];\n\t tmp15 = tmp1 - tmp2;\n\t tmp3 = tmp1 + (K2_000000000 * tmp2);\n\t tmp30 = tmp15 - tmp17;\n\t tmp18 = tmp15 + tmp17;\n }\n {\n\t fftw_real tmp4;\n\t fftw_real tmp39;\n\t fftw_real tmp5;\n\t fftw_real tmp6;\n\t fftw_real tmp7;\n\t fftw_real tmp22;\n\t fftw_real tmp38;\n\t fftw_real tmp9;\n\t fftw_real tmp44;\n\t fftw_real tmp10;\n\t fftw_real tmp11;\n\t fftw_real tmp12;\n\t fftw_real tmp27;\n\t fftw_real tmp43;\n\t fftw_real tmp19;\n\t fftw_real tmp24;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp20;\n\t fftw_real tmp21;\n\t fftw_real tmp25;\n\t fftw_real tmp26;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp4 = real_input[3 * real_istride];\n\t tmp39 = imag_input[3 * imag_istride];\n\t tmp5 = real_input[7 * real_istride];\n\t tmp6 = real_input[2 * real_istride];\n\t tmp7 = tmp5 + tmp6;\n\t tmp20 = imag_input[7 * imag_istride];\n\t tmp21 = imag_input[2 * imag_istride];\n\t tmp22 = K866025403 * (tmp20 - tmp21);\n\t tmp38 = tmp20 + tmp21;\n\t tmp9 = real_input[6 * real_istride];\n\t tmp44 = imag_input[6 * imag_istride];\n\t tmp10 = real_input[4 * real_istride];\n\t tmp11 = real_input[real_istride];\n\t tmp12 = tmp10 + tmp11;\n\t tmp25 = imag_input[4 * imag_istride];\n\t tmp26 = imag_input[imag_istride];\n\t tmp27 = K866025403 * (tmp25 + tmp26);\n\t tmp43 = tmp25 - tmp26;\n\t }\n\t tmp37 = K866025403 * (tmp5 - tmp6);\n\t tmp61 = tmp39 - tmp38;\n\t tmp62 = tmp44 - tmp43;\n\t tmp45 = (K500000000 * tmp43) + tmp44;\n\t tmp40 = (K500000000 * tmp38) + tmp39;\n\t tmp19 = tmp4 - (K500000000 * tmp7);\n\t tmp23 = tmp19 - tmp22;\n\t tmp31 = tmp19 + tmp22;\n\t tmp42 = K866025403 * (tmp10 - tmp11);\n\t tmp24 = tmp9 - (K500000000 * tmp12);\n\t tmp28 = tmp24 - tmp27;\n\t tmp32 = tmp24 + tmp27;\n\t tmp8 = tmp4 + tmp7;\n\t tmp13 = tmp9 + tmp12;\n\t tmp14 = tmp8 + tmp13;\n }\n output[0] = tmp3 + (K2_000000000 * tmp14);\n {\n\t fftw_real tmp63;\n\t fftw_real tmp65;\n\t fftw_real tmp60;\n\t fftw_real tmp64;\n\t fftw_real tmp58;\n\t fftw_real tmp59;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp63 = (K1_175570504 * tmp61) - (K1_902113032 * tmp62);\n\t tmp65 = (K1_902113032 * tmp61) + (K1_175570504 * tmp62);\n\t tmp58 = tmp3 - (K500000000 * tmp14);\n\t tmp59 = K1_118033988 * (tmp8 - tmp13);\n\t tmp60 = tmp58 - tmp59;\n\t tmp64 = tmp59 + tmp58;\n\t output[12 * ostride] = tmp60 - tmp63;\n\t output[3 * ostride] = tmp60 + tmp63;\n\t output[6 * ostride] = tmp64 - tmp65;\n\t output[9 * ostride] = tmp64 + tmp65;\n }\n {\n\t fftw_real tmp51;\n\t fftw_real tmp29;\n\t fftw_real tmp50;\n\t fftw_real tmp55;\n\t fftw_real tmp57;\n\t fftw_real tmp53;\n\t fftw_real tmp54;\n\t fftw_real tmp56;\n\t fftw_real tmp52;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp51 = K1_118033988 * (tmp23 - tmp28);\n\t tmp29 = tmp23 + tmp28;\n\t tmp50 = tmp18 - (K500000000 * tmp29);\n\t tmp53 = tmp40 - tmp37;\n\t tmp54 = tmp45 - tmp42;\n\t tmp55 = (K1_175570504 * tmp53) - (K1_902113032 * tmp54);\n\t tmp57 = (K1_902113032 * tmp53) + (K1_175570504 * tmp54);\n\t output[5 * ostride] = tmp18 + (K2_000000000 * tmp29);\n\t tmp56 = tmp51 + tmp50;\n\t output[11 * ostride] = tmp56 - tmp57;\n\t output[14 * ostride] = tmp56 + tmp57;\n\t tmp52 = tmp50 - tmp51;\n\t output[2 * ostride] = tmp52 - tmp55;\n\t output[8 * ostride] = tmp52 + tmp55;\n }\n {\n\t fftw_real tmp35;\n\t fftw_real tmp33;\n\t fftw_real tmp34;\n\t fftw_real tmp47;\n\t fftw_real tmp49;\n\t fftw_real tmp41;\n\t fftw_real tmp46;\n\t fftw_real tmp48;\n\t fftw_real tmp36;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp35 = K1_118033988 * (tmp31 - tmp32);\n\t tmp33 = tmp31 + tmp32;\n\t tmp34 = tmp30 - (K500000000 * tmp33);\n\t tmp41 = tmp37 + tmp40;\n\t tmp46 = tmp42 + tmp45;\n\t tmp47 = (K1_175570504 * tmp41) - (K1_902113032 * tmp46);\n\t tmp49 = (K1_902113032 * tmp41) + (K1_175570504 * tmp46);\n\t output[10 * ostride] = tmp30 + (K2_000000000 * tmp33);\n\t tmp48 = tmp35 + tmp34;\n\t output[ostride] = tmp48 - tmp49;\n\t output[4 * ostride] = tmp48 + tmp49;\n\t tmp36 = tmp34 - tmp35;\n\t output[7 * ostride] = tmp36 - tmp47;\n\t output[13 * ostride] = tmp36 + tmp47;\n }\n}\n\nfftw_codelet_desc fftw_hc2real_15_desc =\n{\n \"fftw_hc2real_15\",\n (void (*)()) fftw_hc2real_15,\n 15,\n FFTW_BACKWARD,\n FFTW_HC2REAL,\n 345,\n 0,\n (const int *) 0,\n};\n", "meta": {"hexsha": "6cc9acb7c1099ef690ba91a0883a336b3d21acb0", "size": 7141, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fcr_15.c", "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fcr_15.c", "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fcr_15.c", "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "avg_line_length": 31.4581497797, "max_line_length": 146, "alphanum_fraction": 0.6657330906, "num_tokens": 2447, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6513548511303336, "lm_q2_score": 0.42632159254749025, "lm_q1q2_score": 0.2776866374474173}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"pmpfft.h\"\n\nvoid\nfastpm_powerspectrum_init(FastPMPowerSpectrum * ps, const size_t size)\n{\n fastpm_funck_init(&ps->base, size);\n ps->pm = NULL;\n ps->edges = malloc(sizeof(ps->edges[0]) * (ps->base.size + 1));\n ps->Nmodes = malloc(sizeof(ps->Nmodes[0]) * ps->base.size);\n}\n\nvoid\nfastpm_powerspectrum_init_from(FastPMPowerSpectrum * ps, const FastPMPowerSpectrum * other)\n{\n fastpm_powerspectrum_init(ps, other->base.size);\n memcpy(ps->base.k, other->base.k, sizeof(ps->base.k[0]) * ps->base.size);\n memcpy(ps->base.f, other->base.f, sizeof(ps->base.f[0]) * ps->base.size);\n memcpy(ps->edges, other->edges, sizeof(ps->edges[0]) * (ps->base.size + 1));\n memcpy(ps->Nmodes, other->Nmodes, sizeof(ps->Nmodes[0]) * ps->base.size);\n}\n\nvoid\nfastpm_powerspectrum_init_from_delta(FastPMPowerSpectrum * ps, PM * pm, const FastPMFloat * delta1_k, const FastPMFloat * delta2_k)\n{\n /* This function measures powerspectrum from two overdensity or 1+overdensity fields */\n /* normalize them with fastpm_apply_normalize_transfer if needed before using this function.*/\n /* N is used to store metadata -- the shot-noise level. */\n fastpm_powerspectrum_init(ps, pm_nmesh(pm)[0] / 2);\n\n ps->pm = pm;\n double Volume = 1.0;\n int d;\n double k0 = 2 * M_PI / pm_boxsize(ps->pm)[0];\n for (d = 0; d < 3; d ++) {\n Volume *= pm_boxsize(pm)[d];\n }\n ps->Volume = Volume;\n ps->k0 = k0;\n\n memset(ps->base.f, 0, sizeof(ps->base.f[0]) * ps->base.size);\n memset(ps->base.k, 0, sizeof(ps->base.k[0]) * ps->base.size);\n memset(ps->edges, 0, sizeof(ps->edges[0]) * (ps->base.size + 1));\n memset(ps->Nmodes, 0, sizeof(ps->Nmodes[0]) * ps->base.size);\n\n int i;\n for(i = 0; i < ps->base.size + 1; i ++) {\n ps->edges[i] = i * k0;\n }\n\n#pragma omp parallel\n {\n PMKIter kiter;\n for(pm_kiter_init(ps->pm, &kiter);\n !pm_kiter_stop(&kiter);\n pm_kiter_next(&kiter)) {\n int d;\n ptrdiff_t kk = 0.;\n for(d = 0; d < 3; d++) {\n double ik = kiter.iabs[d];\n if(ik > pm->Nmesh[d] / 2) ik -= pm->Nmesh[d];\n kk += ik * ik;\n }\n\n ptrdiff_t ind = kiter.ind;\n\n ptrdiff_t bin = ((ptrdiff_t)floor(sqrt(kk))) - 2;\n if(bin < 0) bin = 0;\n while((bin + 1) * (bin + 1) <= kk) {\n bin ++;\n }\n\n double k = sqrt(kk) * k0;\n\n if(bin >= 0 && bin < ps->base.size) {\n double real1 = delta1_k[ind + 0];\n double imag1 = delta1_k[ind + 1];\n double real2 = delta2_k[ind + 0];\n double imag2 = delta2_k[ind + 1];\n double value = real1 * real2 + imag1 * imag2;\n int w = 2;\n\n if(kiter.i[2] == 0 || kiter.i[2] == pm->Nmesh[2] / 2) w = 1;\n\n if(kiter.iabs[0] == 0 &&\n kiter.iabs[1] == 0 &&\n kiter.iabs[2] == 0) {\n\n } else {\n #pragma omp atomic\n ps->Nmodes[bin] += w;\n #pragma omp atomic\n ps->base.f[bin] += w * value; /// cic;\n #pragma omp atomic\n ps->base.k[bin] += w * k;\n }\n }\n }\n }\n\n\n MPI_Allreduce(MPI_IN_PLACE, ps->base.f, ps->base.size, MPI_DOUBLE, MPI_SUM, ps->pm->Comm2D);\n MPI_Allreduce(MPI_IN_PLACE, ps->Nmodes, ps->base.size, MPI_DOUBLE, MPI_SUM, ps->pm->Comm2D);\n MPI_Allreduce(MPI_IN_PLACE, ps->base.k, ps->base.size, MPI_DOUBLE, MPI_SUM, ps->pm->Comm2D);\n\n ptrdiff_t ind;\n for(ind = 0; ind < ps->base.size; ind++) {\n if(ps->Nmodes[ind] == 0) continue;\n ps->base.k[ind] /= ps->Nmodes[ind];\n ps->base.f[ind] /= ps->Nmodes[ind];\n ps->base.f[ind] *= ps->Volume;\n }\n}\n\nvoid\nfastpm_transferfunction_init(FastPMPowerSpectrum * ps, PM * pm, FastPMFloat * src_k, FastPMFloat * dest_k)\n{\n FastPMPowerSpectrum * ps2 = alloca(sizeof(*ps2));\n\n fastpm_powerspectrum_init_from_delta(ps, pm, src_k, src_k);\n fastpm_powerspectrum_init_from_delta(ps2, pm, dest_k, dest_k);\n\n ptrdiff_t i;\n for(i = 0; i < ps->base.size; i ++) {\n ps->base.f[i] = sqrt(ps2->base.f[i] / ps->base.f[i]);\n }\n\n fastpm_powerspectrum_destroy(ps2);\n}\n\nvoid\nfastpm_powerspectrum_destroy(FastPMPowerSpectrum * ps) {\n free(ps->edges);\n free(ps->Nmodes);\n fastpm_funck_destroy(&ps->base);\n}\n\nvoid\nfastpm_powerspectrum_write(FastPMPowerSpectrum * ps, char * filename, double N)\n{\n FILE * fp = fopen(filename, \"w\");\n int i;\n fprintf(fp, \"# k p N \\n\");\n for(i = 0; i < ps->base.size; i ++) {\n fprintf(fp, \"%g %g %g\\n\", ps->base.k[i], ps->base.f[i], ps->Nmodes[i]);\n }\n double * BoxSize = pm_boxsize(ps->pm);\n fprintf(fp, \"# metadata 7\\n\");\n fprintf(fp, \"# volume %g float64\\n\", ps->Volume);\n fprintf(fp, \"# shotnoise %g float64\\n\", ps->Volume / N);\n fprintf(fp, \"# N1 %g int\\n\", N);\n fprintf(fp, \"# N2 %g int\\n\", N);\n fprintf(fp, \"# Lz %g float64\\n\", BoxSize[2]);\n fprintf(fp, \"# Lx %g float64\\n\", BoxSize[0]);\n fprintf(fp, \"# Ly %g float64\\n\", BoxSize[1]);\n fclose(fp);\n}\n\ndouble\nfastpm_powerspectrum_large_scale(FastPMPowerSpectrum * ps, int Nmax)\n{\n double kmax = Nmax * ps->k0;\n ptrdiff_t i;\n double Plin = 0;\n double Nmodes = 0;\n /* ignore zero mode ! */\n for(i = 0; (i == 0) || (i < ps->base.size && ps->base.k[i] <= kmax); i ++) {\n Plin += ps->base.f[i] * ps->Nmodes[i];\n Nmodes += ps->Nmodes[i];\n }\n Plin /= Nmodes;\n return Plin;\n}\n\n/* inverted calling signature for callbacks */\ndouble\nfastpm_powerspectrum_eval2(double k, FastPMPowerSpectrum * ps)\n{\n return fastpm_powerspectrum_eval(ps, k);\n}\n\ndouble\nfastpm_powerspectrum_eval(FastPMPowerSpectrum * ps, double k)\n{\n return fastpm_funck_eval(&ps->base, k);\n}\n\ndouble\nfastpm_powerspectrum_get(FastPMPowerSpectrum * ps, double k)\n{\n if(k == 0) return 1;\n\n /* ignore the 0 mode */\n\n int l = 0;\n int r = ps->base.size;\n\n while(r - l > 1) {\n int m = (r + l) / 2;\n /* if we are on the exact k, return value from there.*/\n if(k <= ps->edges[m])\n r = m;\n else\n l = m;\n }\n\n return ps->base.f[l];\n}\n\ndouble\nfastpm_powerspectrum_get2(double k, FastPMPowerSpectrum * ps)\n{\n return fastpm_powerspectrum_get(ps, k);\n}\n\nstruct sigma2_int {\n FastPMPowerSpectrum * ps;\n double R;\n};\nstatic\ndouble sigma2_int(double k, struct sigma2_int * param)\n{\n double kr, kr3, kr2, w, x;\n double r_tophat = param->R;\n\n kr = r_tophat * k;\n kr2 = kr * kr;\n kr3 = kr2 * kr;\n\n if(kr < 1e-8)\n return 0;\n\n w = 3 * (sin(kr) / kr3 - cos(kr) / kr2);\n x = 4 * M_PI * k * k * w * w * fastpm_powerspectrum_eval(param->ps, k);\n\n return x / pow(2 * M_PI, 3);\n}\n\ndouble\nfastpm_powerspectrum_sigma(FastPMPowerSpectrum * ps, double R)\n{\n const int WORKSIZE = 81920;\n\n double result, abserr;\n gsl_integration_workspace *workspace;\n gsl_function F;\n\n struct sigma2_int param;\n param.ps = ps;\n param.R = R;\n\n workspace = gsl_integration_workspace_alloc(WORKSIZE);\n\n F.function = (void*) &sigma2_int;\n F.params = ¶m;\n\n void * handler = gsl_set_error_handler_off ();\n //\n // note: 500/R is here chosen as (effectively) infinity integration boundary\n gsl_integration_qag(&F, 0, 500.0 * 1 / R,\n 0, 1.0e-4, WORKSIZE, GSL_INTEG_GAUSS41, workspace, &result, &abserr);\n\n // high precision caused error\n gsl_integration_workspace_free(workspace);\n gsl_set_error_handler (handler);\n\n return sqrt(result);\n}\n\nvoid\nfastpm_powerspectrum_scale(FastPMPowerSpectrum * ps, double factor)\n{\n ptrdiff_t i;\n /* neglect the zero mode */\n for(i = 1; i < ps->base.size; i ++) {\n ps->base.f[i] *= factor;\n }\n}\n\nvoid\nfastpm_powerspectrum_rebin(FastPMPowerSpectrum * ps, size_t newsize)\n{\n /* this doesn't work */\n double * k1 = malloc(newsize * sizeof(k1[0]));\n double * p1 = malloc(newsize * sizeof(p1[0]));\n double * Nmodes1 = malloc(newsize * sizeof(Nmodes1[0]));\n double * edges1 = malloc((newsize + 1) * sizeof(edges1[0]));\n\n ptrdiff_t i;\n\n for(i = 0; i < newsize; i ++) {\n ptrdiff_t j1 = (i ) * ps->base.size / newsize;\n ptrdiff_t j2 = (i + 1) * ps->base.size / newsize;\n ptrdiff_t j;\n k1[i] = 0;\n p1[i] = 0;\n Nmodes1[i] = 0;\n edges1[i] = ps->edges[j1];\n edges1[i + 1] = ps->edges[j2];\n for(j = j1; j < j2; j ++) {\n k1[i] += ps->base.k[j] * ps->Nmodes[j];\n p1[i] += ps->base.f[j] * ps->Nmodes[j];\n Nmodes1[i] += ps->Nmodes[j];\n }\n if(Nmodes1[i] > 0) {\n k1[i] /= Nmodes1[i];\n p1[i] /= Nmodes1[i];\n }\n }\n free(ps->base.k);\n free(ps->base.f);\n free(ps->Nmodes);\n free(ps->edges);\n ps->base.k = k1;\n ps->base.f = p1;\n ps->Nmodes = Nmodes1;\n ps->edges = edges1;\n ps->base.size = newsize;\n}\n\nint\nfastpm_powerspectrum_init_from_string(FastPMPowerSpectrum * ps, const char * string)\n{\n int r = fastpm_funck_init_from_string(&ps->base, string);\n ps->edges = malloc(sizeof(ps->edges[0]) * (ps->base.size + 1));\n ps->Nmodes = malloc(sizeof(ps->Nmodes[0]) * ps->base.size);\n return r;\n}\n\nvoid\nfastpm_funck_init(FastPMFuncK * fk, const size_t size)\n{\n fk->size = size;\n fk->k = malloc(sizeof(fk->k[0]) * fk->size);\n fk->f = malloc(sizeof(fk->f[0]) * fk->size);\n}\n\nint\nfastpm_funck_init_from_string(FastPMFuncK * fk, const char * string)\n{\n char ** list = fastpm_strsplit(string, \"\\n\");\n char ** line;\n ptrdiff_t i;\n int pass = 0;\n /* two pass parsing, first pass for counting */\n /* second pass for assignment */\n while(pass < 2) {\n i = 0;\n for (line = list; *line; line++) {\n double k, f;\n if(2 == sscanf(*line, \"%lg\\t%lg\", &k, &f)) { // note tab. Could make more general?\n if(pass == 1) {\n fk->k[i] = k;\n fk->f[i] = f;\n }\n i ++;\n }\n }\n if(pass == 0) {\n fastpm_funck_init(fk, i);\n }\n pass ++;\n }\n\n free(list);\n if(fk->size == 0) {\n /* Nothing is savagable in the file.*/\n return 0;\n }\n return 0;\n}\n\n/* inverted calling signature for callbacks */\ndouble\nfastpm_funck_eval2(double k, FastPMFuncK * fk)\n{\n return fastpm_funck_eval(fk, k);\n}\n\ndouble\nfastpm_funck_eval(FastPMFuncK * fk, double k)\n{\n\n /* ignore the 0 mode */\n if(k == 0) return 1;\n\n int l = 0;\n int r = fk->size - 1;\n\n /* determine the right and left values around k */\n while(r - l > 1) {\n int m = (r + l) / 2;\n if(k < fk->k[m])\n r = m;\n else\n l = m;\n }\n double k2 = fk->k[r],\n k1 = fk->k[l];\n double f2 = fk->f[r],\n f1 = fk->f[l];\n\n if(l == r) {\n return fk->f[l];\n }\n\n if(f1 <= 0 || f2 <= 0 || k1 == 0 || k2 == 0) {\n /* if any of the f is zero, or negative, use linear interpolation */\n double f = (k - k1) * f2 + (k2 - k) * f1;\n f /= (k2 - k1);\n return f;\n } else {\n k = log(k);\n f1 = log(f1);\n f2 = log(f2);\n k1 = log(k1);\n k2 = log(k2);\n double f = (k - k1) * f2 + (k2 - k) * f1;\n f /= (k2 - k1);\n return exp(f);\n }\n}\n\nvoid\nfastpm_funck_destroy(FastPMFuncK * fk)\n{\n free(fk->f);\n free(fk->k);\n}\n", "meta": {"hexsha": "49e95c017d27aa637bee778585f52d3bfe9e331b", "size": 11831, "ext": "c", "lang": "C", "max_stars_repo_path": "fastpm/libfastpm/powerspectrum.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/powerspectrum.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/powerspectrum.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": 26.8276643991, "max_line_length": 131, "alphanum_fraction": 0.5427267348, "num_tokens": 3739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.42632159254749036, "lm_q1q2_score": 0.27617036792676997}} {"text": "#ifndef UTILS_H\r\n#define UTILS_H\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\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\nusing namespace std;\r\n\r\ndouble log_sum(double log_a, double log_b);\r\ndouble log_normalize(double * array, int nlen);\r\ndouble log_normalize(vector & vec, int nlen);\r\ndouble log_subtract(double log_a, double log_b);\r\ndouble log_factorial(int n, double a);\r\ndouble similarity(const int* v1, const int* v2, int n);\r\n\r\nbool file_exists(const char * filename);\r\nbool dir_exists(const char * directory);\r\n\r\ntemplate void free_vec_ptr(vector & v)\r\n{\r\n int size = v.size();\r\n T* p = NULL;\r\n for (int i = 0; i < size; i ++)\r\n {\r\n p = v[i];\r\n delete [] p;\r\n }\r\n v.clear();\r\n}\r\n\r\n// find the max and argmax in an array\r\ntemplate T max(const T * x, int n, int* argmax)\r\n{\r\n *argmax = 0;\r\n T max_val = x[0];\r\n for (int i = 1; i < n; i++)\r\n if (x[i] > max_val)\r\n {\r\n max_val = x[i];\r\n *argmax = i;\r\n }\r\n return max_val;\r\n}\r\n\r\n// find the max and argmax in an vector\r\ntemplate T max_vec(vector & v, int n, int* argmax)\r\n{\r\n *argmax = 0;\r\n T max_val = v[0];\r\n for (int i = 1; i < n; i++)\r\n if (v[i] > max_val)\r\n {\r\n max_val = v[i];\r\n *argmax = i;\r\n }\r\n return max_val;\r\n}\r\n\r\n// set a value to the entire array\r\ntemplate void set_array(T * array, int size, T value)\r\n{\r\n for (int i = 0; i < size; i++) array[i] = value;\r\n}\r\n\r\n// swap two elements in an array\r\ntemplate < typename T > void swap_array_element(T * array, int i, int j)\r\n{\r\n if (i == j) return;\r\n T a = array[i];\r\n array[i] = array[j];\r\n array[j] = a;\r\n}\r\n\r\n// set a value to a entrie vector\r\ntemplate void set_vector(vector & v, T value)\r\n{\r\n int size = v.size();\r\n for (int i = 0; i < size; i++) v[i] = value;\r\n}\r\n\r\n// swap two elements in vector\r\ntemplate < typename T > void swap_vec_element(vector & v, int i, int j)\r\n{\r\n if (i == j) return; // no need to swap\r\n T a = v[i];\r\n v[i] = v[j];\r\n v[j] = a;\r\n}\r\n\r\n\r\n/// gsl_wrappers\r\n//double lgamma(double x); // linux has this\r\nunsigned int rmultinomial(const double* p, int n, double tot_p=-1);\r\ndouble rgamma(double a, double b);\r\ndouble rbeta(double a, double b);\r\nunsigned int rbernoulli(double p);\r\ndouble runiform();\r\nvoid rshuffle (void* base, size_t n, size_t size);\r\nunsigned long int runiform_int(unsigned long int n);\r\n\r\n\r\n#endif\r\n", "meta": {"hexsha": "9bccd57b40c41a7c64cb4d0fc9bbf98ae3954eb6", "size": 2803, "ext": "h", "lang": "C", "max_stars_repo_path": "topicmodelling/hdp/utils.h", "max_stars_repo_name": "marziehf/Topic-Sensitive-Embeddings", "max_stars_repo_head_hexsha": "d013f5b90024620ee79a72e85aa5e5761c3cd8dc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-01-12T18:50:16.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T10:33:51.000Z", "max_issues_repo_path": "run/hdp-wsi/topicmodelling/hdp/utils.h", "max_issues_repo_name": "osmanbaskaya/mapping-impact", "max_issues_repo_head_hexsha": "8024dd3b916ac2dfc336221dd32faba4c0a98442", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-09-03T11:57:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-03T12:06:35.000Z", "max_forks_repo_path": "run/hdp-wsi/topicmodelling/hdp/utils.h", "max_forks_repo_name": "osmanbaskaya/mapping-impact", "max_forks_repo_head_hexsha": "8024dd3b916ac2dfc336221dd32faba4c0a98442", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-04-14T10:00:32.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-17T07:16:52.000Z", "avg_line_length": 23.9572649573, "max_line_length": 75, "alphanum_fraction": 0.5858009276, "num_tokens": 805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.27590740667197156}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n#ifdef COSMIC_RAYS\n#include \"cosmic_rays.h\"\n#endif\n#ifdef CS_MODEL\n#include \"cs_metals.h\"\n#endif\n\n\n/*! Structure for communication during the density computation. Holds data that is sent to other processors.\n */\nstatic struct densdata_in\n{\n MyDouble Pos[3];\n MyFloat Vel[3];\n MyFloat Hsml;\n#ifdef VOLUME_CORRECTION\n MyFloat DensityOld;\n#endif\n#ifdef WINDS\n MyFloat DelayTime;\n#endif\n int NodeList[NODELISTLENGTH];\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB)\n MyFloat BPred[3];\n#endif\n#ifdef EULERPOTENTIALS\n MyFloat EulerA, EulerB;\n#endif\n#ifdef CS_MODEL\n MyFloat DensityOld, Entropy;\n#endif\n}\n *DensDataIn, *DensDataGet;\n\n\nstatic struct densdata_out\n{\n MyLongDouble Rho;\n MyLongDouble DhsmlDensity;\n MyLongDouble Ngb;\n#ifndef NAVIERSTOKES\n MyLongDouble Div, Rot[3];\n#else\n MyFloat DV[3][3];\n#endif\n#ifdef MAGNETIC\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n MyFloat RotB[3];\n#endif\n#ifdef TRACEDIVB\n MyFloat divB;\n#endif\n#endif\n\n#ifdef RADTRANSFER_FLUXLIMITER\n MyFloat Grad_ngamma[3];\n#endif\n\n#if defined(BLACK_HOLES)\n MyLongDouble SmoothedEntr;\n#endif\n#ifdef CONDUCTION_SATURATION\n MyFloat GradEntr[3];\n#endif\n\n#ifdef BLACK_HOLES\n MyLongDouble GasVel[3];\n#endif\n\n#ifdef HYDRO_COST_FACTOR\n int Ninteractions;\n#endif\n\n#ifdef VOLUME_CORRECTION\n MyFloat DensityStd;\n#endif\n\n#ifdef EULERPOTENTIALS\n MyFloat dEulerA[3], dEulerB[3];\n#endif\n\n}\n *DensDataResult, *DensDataOut;\n\n\n/*! \\file density.c \n * \\brief SPH density computation and smoothing length determination\n *\n * This file contains the \"first SPH loop\", where the SPH densities and some\n * auxiliary quantities are computed. There is also functionality that\n * corrects the smoothing length if needed.\n */\n\n\n/*! This function computes the local density for each active SPH particle, the\n * number of neighbours in the current smoothing radius, and the divergence\n * and rotation of the velocity field. The pressure is updated as well. If a\n * particle with its smoothing region is fully inside the local domain, it is\n * not exported to the other processors. The function also detects particles\n * that have a number of neighbours outside the allowed tolerance range. For\n * these particles, the smoothing length is adjusted accordingly, and the\n * density() computation is called again. Note that the smoothing length is\n * not allowed to fall below the lower bound set by MinGasHsml (this may mean\n * that one has to deal with substantially more than normal number of\n * neighbours.)\n */\nvoid density(void)\n{\n MyFloat *Left, *Right;\n int i, j, ndone, ndone_flag, npleft, dt_step, dummy, iter = 0;\n int ngrp, sendTask, recvTask, place, nexport, nimport;\n long long ntot;\n double dmax1, dmax2, fac;\n double timeall = 0, timecomp1 = 0, timecomp2 = 0, timecommsumm1 = 0, timecommsumm2 = 0, timewait1 =\n 0, timewait2 = 0;\n double timecomp, timecomm, timewait;\n double dt_entr, tstart, tend, t0, t1;\n double desnumngb;\n\n#ifdef COSMIC_RAYS\n int CRpop;\n#endif\n\n#if defined(NAVIERSTOKES)\n int k;\n#endif\n#ifdef NAVIERSTOKES\n double dvel[3][3];\n double rotx, roty, rotz;\n#endif\n\n#if defined(SOFTEREQS)\n double a3inv;\n\n if(All.ComovingIntegrationOn)\n a3inv = 1 / (All.Time * All.Time * All.Time);\n else\n a3inv = 1;\n#endif\n\n#ifdef EULERPOTENTIALS\n double efak;\n\n if(All.ComovingIntegrationOn)\n efak = 1. / All.Time / All.HubbleParam;\n else\n efak = 1;\n#endif\n\n CPU_Step[CPU_DENSMISC] += measure_time();\n\n Left = (MyFloat *) mymalloc(NumPart * sizeof(MyFloat));\n Right = (MyFloat *) mymalloc(NumPart * sizeof(MyFloat));\n\n for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i])\n {\n if(density_isactive(i))\n\t{\n\t Left[i] = Right[i] = 0;\n\n#ifdef BLACK_HOLES\n\t P[i].SwallowID = 0;\n#endif\n#if defined(BLACK_HOLES) && defined(FLTROUNDOFFREDUCTION)\n\t if(P[i].Type == 0)\n\t SphP[i].i.dInjected_BH_Energy = SphP[i].i.Injected_BH_Energy;\n#endif\n\t}\n }\n\n /* allocate buffers to arrange communication */\n\n\n Ngblist = (int *) mymalloc(NumPart * sizeof(int));\n\n All.BunchSize =\n (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +\n\t\t\t\t\t sizeof(struct densdata_in) + sizeof(struct densdata_out) +\n\t\t\t\t\t sizemax(sizeof(struct densdata_in),\n\t\t\t\t\t\t sizeof(struct densdata_out))));\n DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));\n DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));\n\n t0 = second();\n\n desnumngb = All.DesNumNgb;\n\n /* we will repeat the whole thing for those particles where we didn't find enough neighbours */\n do\n {\n i = FirstActiveParticle;\t/* begin with this index */\n\n do\n\t{\n\t for(j = 0; j < NTask; j++)\n\t {\n\t Send_count[j] = 0;\n\t Exportflag[j] = -1;\n\t }\n\n\t /* do local particles and prepare export list */\n\t tstart = second();\n\t for(nexport = 0; i >= 0; i = NextActiveParticle[i])\n\t {\n\t if(density_isactive(i))\n\t\t{\n\t\t if(density_evaluate(i, 0, &nexport, Send_count) < 0)\n\t\t break;\n\t\t}\n\t }\n\t tend = second();\n\t timecomp1 += timediff(tstart, tend);\n\n#ifdef MYSORT\n\t mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n#else\n\t qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n#endif\n\n\t tstart = second();\n\n\t MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);\n\n\t tend = second();\n\t timewait1 += timediff(tstart, tend);\n\n\t for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)\n\t {\n\t Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];\n\t nimport += Recv_count[j];\n\n\t if(j > 0)\n\t\t{\n\t\t Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\t\t Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];\n\t\t}\n\t }\n\n\t DensDataGet = (struct densdata_in *) mymalloc(nimport * sizeof(struct densdata_in));\n\t DensDataIn = (struct densdata_in *) mymalloc(nexport * sizeof(struct densdata_in));\n\n\t /* prepare particle data for export */\n\t for(j = 0; j < nexport; j++)\n\t {\n\t place = DataIndexTable[j].Index;\n\n\t DensDataIn[j].Pos[0] = P[place].Pos[0];\n\t DensDataIn[j].Pos[1] = P[place].Pos[1];\n\t DensDataIn[j].Pos[2] = P[place].Pos[2];\n\t DensDataIn[j].Hsml = PPP[place].Hsml;\n\n#ifdef CS_MODEL\n\t DensDataIn[j].DensityOld = SphP[place].DensityOld;\n\t DensDataIn[j].Entropy = SphP[place].Entropy;\n#endif\n\t memcpy(DensDataIn[j].NodeList,\n\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\n#if defined(BLACK_HOLES)\n\t if(P[place].Type != 0)\n\t\t{\n\t\t DensDataIn[j].Vel[0] = 0;\n\t\t DensDataIn[j].Vel[1] = 0;\n\t\t DensDataIn[j].Vel[2] = 0;\n\t\t}\n\t else\n#endif\n\t\t{\n\t\t DensDataIn[j].Vel[0] = SphP[place].VelPred[0];\n\t\t DensDataIn[j].Vel[1] = SphP[place].VelPred[1];\n\t\t DensDataIn[j].Vel[2] = SphP[place].VelPred[2];\n\t\t}\n#ifdef VOLUME_CORRECTION\n\t DensDataIn[j].DensityOld = SphP[place].DensityOld;\n#endif\n\n#ifdef EULERPOTENTIALS\n\t DensDataIn[j].EulerA = SphP[place].EulerA;\n\t DensDataIn[j].EulerB = SphP[place].EulerB;\n#endif\n\n#ifdef WINDS\n\t DensDataIn[j].DelayTime = SphP[place].DelayTime;\n#endif\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB)\n\t DensDataIn[j].BPred[0] = SphP[place].BPred[0];\n\t DensDataIn[j].BPred[1] = SphP[place].BPred[1];\n\t DensDataIn[j].BPred[2] = SphP[place].BPred[2];\n#endif\n\t }\n\t /* exchange particle data */\n\t tstart = second();\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t {\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t {\n\t\t /* get the particles */\n\t\t MPI_Sendrecv(&DensDataIn[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct densdata_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A,\n\t\t\t\t &DensDataGet[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct densdata_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t }\n\t\t}\n\t }\n\t tend = second();\n\t timecommsumm1 += timediff(tstart, tend);\n\n\t myfree(DensDataIn);\n\t DensDataResult = (struct densdata_out *) mymalloc(nimport * sizeof(struct densdata_out));\n\t DensDataOut = (struct densdata_out *) mymalloc(nexport * sizeof(struct densdata_out));\n\n\n\t /* now do the particles that were sent to us */\n\n\t tstart = second();\n\t for(j = 0; j < nimport; j++)\n\t density_evaluate(j, 1, &dummy, &dummy);\n\t tend = second();\n\t timecomp2 += timediff(tstart, tend);\n\n\t if(i < 0)\n\t ndone_flag = 1;\n\t else\n\t ndone_flag = 0;\n\n\t tstart = second();\n\t MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n\t tend = second();\n\t timewait2 += timediff(tstart, tend);\n\n\n\t /* get the result */\n\t tstart = second();\n\t for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t {\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t {\n\t\t /* send the results */\n\t\t MPI_Sendrecv(&DensDataResult[Recv_offset[recvTask]],\n\t\t\t\t Recv_count[recvTask] * sizeof(struct densdata_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B,\n\t\t\t\t &DensDataOut[Send_offset[recvTask]],\n\t\t\t\t Send_count[recvTask] * sizeof(struct densdata_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t }\n\t\t}\n\n\t }\n\t tend = second();\n\t timecommsumm2 += timediff(tstart, tend);\n\n\n\t /* add the result to the local particles */\n\t tstart = second();\n\t for(j = 0; j < nexport; j++)\n\t {\n\t place = DataIndexTable[j].Index;\n\n\t PPP[place].n.dNumNgb += DensDataOut[j].Ngb;\n#ifdef HYDRO_COST_FACTOR\n\t P[place].GravCost += HYDRO_COST_FACTOR * DensDataOut[j].Ninteractions;\n#endif\n\n\t if(P[place].Type == 0)\n\t\t{\n\t\t SphP[place].d.dDensity += DensDataOut[j].Rho;\n\t\t SphP[place].h.dDhsmlDensityFactor += DensDataOut[j].DhsmlDensity;\n\n#ifndef NAVIERSTOKES\n\t\t SphP[place].v.dDivVel += DensDataOut[j].Div;\n\t\t SphP[place].r.dRot[0] += DensDataOut[j].Rot[0];\n\t\t SphP[place].r.dRot[1] += DensDataOut[j].Rot[1];\n\t\t SphP[place].r.dRot[2] += DensDataOut[j].Rot[2];\n#else\n\t\t for(k = 0; k < 3; k++)\n\t\t {\n\t\t SphP[place].u.DV[k][0] += DensDataOut[j].DV[k][0];\n\t\t SphP[place].u.DV[k][1] += DensDataOut[j].DV[k][1];\n\t\t SphP[place].u.DV[k][2] += DensDataOut[j].DV[k][2];\n\t\t }\n#endif\n\n#ifdef VOLUME_CORRECTION\n\t\t SphP[place].DensityStd += DensDataOut[j].DensityStd;\n#endif\n\n#ifdef CONDUCTION_SATURATION\n\t\t SphP[place].GradEntr[0] += DensDataOut[j].GradEntr[0];\n\t\t SphP[place].GradEntr[1] += DensDataOut[j].GradEntr[1];\n\t\t SphP[place].GradEntr[2] += DensDataOut[j].GradEntr[2];\n#endif\n\n#ifdef RADTRANSFER_FLUXLIMITER\n\t\t SphP[place].Grad_ngamma[0] += DensDataOut[j].Grad_ngamma[0];\n\t\t SphP[place].Grad_ngamma[1] += DensDataOut[j].Grad_ngamma[1];\n\t\t SphP[place].Grad_ngamma[2] += DensDataOut[j].Grad_ngamma[2];\n#endif\n\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n\t\t SphP[place].RotB[0] += DensDataOut[j].RotB[0];\n\t\t SphP[place].RotB[1] += DensDataOut[j].RotB[1];\n\t\t SphP[place].RotB[2] += DensDataOut[j].RotB[2];\n#endif\n\n#ifdef TRACEDIVB\n\t\t SphP[place].divB += DensDataOut[j].divB;\n#endif\n\n#ifdef EULERPOTENTIALS\n\t\t SphP[place].dEulerA[0] += DensDataOut[j].dEulerA[0];\n\t\t SphP[place].dEulerA[1] += DensDataOut[j].dEulerA[1];\n\t\t SphP[place].dEulerA[2] += DensDataOut[j].dEulerA[2];\n\t\t SphP[place].dEulerB[0] += DensDataOut[j].dEulerB[0];\n\t\t SphP[place].dEulerB[1] += DensDataOut[j].dEulerB[1];\n\t\t SphP[place].dEulerB[2] += DensDataOut[j].dEulerB[2];\n#endif\n\t\t}\n\n#if defined(RADTRANSFER) || defined(SNIA_HEATING)\n\t if(P[place].Type == 4)\n\t\tP[place].DensAroundStar += DensDataOut[j].Rho;\n#endif\n\n\n#ifdef BLACK_HOLES\n\t if(P[place].Type == 5)\n\t\t{\n\t\t P[place].b1.dBH_Density += DensDataOut[j].Rho;\n\t\t P[place].b2.dBH_Entropy += DensDataOut[j].SmoothedEntr;\n\t\t P[place].b3.dBH_SurroundingGasVel[0] += DensDataOut[j].GasVel[0];\n\t\t P[place].b3.dBH_SurroundingGasVel[1] += DensDataOut[j].GasVel[1];\n\t\t P[place].b3.dBH_SurroundingGasVel[2] += DensDataOut[j].GasVel[2];\n\t\t}\n#endif\n\t }\n\t tend = second();\n\t timecomp1 += timediff(tstart, tend);\n\n\n\t myfree(DensDataOut);\n\t myfree(DensDataResult);\n\t myfree(DensDataGet);\n\t}\n while(ndone < NTask);\n\n#ifdef FLTROUNDOFFREDUCTION\n for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i])\n\tif(density_isactive(i))\n\t {\n\t PPP[i].n.NumNgb = FLT(PPP[i].n.dNumNgb);\n\n\t if(P[i].Type == 0)\n\t {\n\t\tSphP[i].d.Density = FLT(SphP[i].d.dDensity);\n\t\tSphP[i].h.DhsmlDensityFactor = FLT(SphP[i].h.dDhsmlDensityFactor);\n\t\tSphP[i].v.DivVel = FLT(SphP[i].v.dDivVel);\n\t\tfor(j = 0; j < 3; j++)\n\t\t SphP[i].r.Rot[j] = FLT(SphP[i].r.dRot[j]);\n\t }\n\n#ifdef BLACK_HOLES\n\t if(P[i].Type == 5)\n\t {\n\t\tP[i].b1.BH_Density = FLT(P[i].b1.dBH_Density);\n\t\tP[i].b2.BH_Entropy = FLT(P[i].b2.dBH_Entropy);\n\t\tfor(j = 0; j < 3; j++)\n\t\t P[i].b3.BH_SurroundingGasVel[j] = FLT(P[i].b3.dBH_SurroundingGasVel[j]);\n\t }\n#endif\n\t }\n#endif\n\n\n /* do final operations on results */\n tstart = second();\n for(i = FirstActiveParticle, npleft = 0; i >= 0; i = NextActiveParticle[i])\n\t{\n\t if(density_isactive(i))\n\t {\n\t if(P[i].Type == 0)\n\t\t{\n\t\t if(SphP[i].d.Density > 0)\n\t\t {\n#ifdef VOLUME_CORRECTION\n\t\t SphP[i].DensityOld = SphP[i].DensityStd;\n#endif\n\t\t SphP[i].h.DhsmlDensityFactor *= PPP[i].Hsml / (NUMDIMS * SphP[i].d.Density);\n\t\t if(SphP[i].h.DhsmlDensityFactor > -0.9)\t/* note: this would be -1 if only a single particle at zero lag is found */\n\t\t\tSphP[i].h.DhsmlDensityFactor = 1 / (1 + SphP[i].h.DhsmlDensityFactor);\n\t\t else\n\t\t\tSphP[i].h.DhsmlDensityFactor = 1;\n#ifndef NAVIERSTOKES\n\t\t SphP[i].r.CurlVel = sqrt(SphP[i].r.Rot[0] * SphP[i].r.Rot[0] +\n\t\t\t\t\t SphP[i].r.Rot[1] * SphP[i].r.Rot[1] +\n\t\t\t\t\t SphP[i].r.Rot[2] * SphP[i].r.Rot[2]) / SphP[i].d.Density;\n\n\t\t SphP[i].v.DivVel /= SphP[i].d.Density;\n#else\n\t\t for(k = 0; k < 3; k++)\n\t\t\t{\n\t\t\t dvel[k][0] = SphP[i].u.DV[k][0] / SphP[i].d.Density;\n\t\t\t dvel[k][1] = SphP[i].u.DV[k][1] / SphP[i].d.Density;\n\t\t\t dvel[k][2] = SphP[i].u.DV[k][2] / SphP[i].d.Density;\n\t\t\t}\n\t\t SphP[i].u.s.DivVel = dvel[0][0] + dvel[1][1] + dvel[2][2];\n\n\t\t SphP[i].u.s.StressDiag[0] = 2 * dvel[0][0] - 2.0 / 3 * SphP[i].u.s.DivVel;\n\t\t SphP[i].u.s.StressDiag[1] = 2 * dvel[1][1] - 2.0 / 3 * SphP[i].u.s.DivVel;\n\t\t SphP[i].u.s.StressDiag[2] = 2 * dvel[2][2] - 2.0 / 3 * SphP[i].u.s.DivVel;\n\n\t\t SphP[i].u.s.StressOffDiag[0] = dvel[0][1] + dvel[1][0];\t/* xy */\n\t\t SphP[i].u.s.StressOffDiag[1] = dvel[0][2] + dvel[2][0];\t/* xz */\n\t\t SphP[i].u.s.StressOffDiag[2] = dvel[1][2] + dvel[2][1];\t/* yz */\n\n#ifdef NAVIERSTOKES_BULK\n\t\t SphP[i].u.s.StressBulk = All.NavierStokes_BulkViscosity * SphP[i].u.s.DivVel;\n#endif\n\t\t rotx = dvel[1][2] - dvel[2][1];\n\t\t roty = dvel[2][0] - dvel[0][2];\n\t\t rotz = dvel[0][1] - dvel[1][0];\n\t\t SphP[i].u.s.CurlVel = sqrt(rotx * rotx + roty * roty + rotz * rotz);\n#endif\n\n\n#ifdef CONDUCTION_SATURATION\n\t\t SphP[i].GradEntr[0] /= SphP[i].d.Density;\n\t\t SphP[i].GradEntr[1] /= SphP[i].d.Density;\n\t\t SphP[i].GradEntr[2] /= SphP[i].d.Density;\n#endif\n\n\n#ifdef RADTRANSFER_FLUXLIMITER\n\t\t SphP[i].Grad_ngamma[0] /= SphP[i].d.Density;\n\t\t SphP[i].Grad_ngamma[1] /= SphP[i].d.Density;\n\t\t SphP[i].Grad_ngamma[2] /= SphP[i].d.Density;\n#endif\n\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n\t\t SphP[i].RotB[0] /= SphP[i].d.Density;\n\t\t SphP[i].RotB[1] /= SphP[i].d.Density;\n\t\t SphP[i].RotB[2] /= SphP[i].d.Density;\n#endif\n\n#ifdef TRACEDIVB\n\t\t SphP[i].divB /= SphP[i].d.Density;\n#endif\n\n#ifdef EULERPOTENTIALS\n\t\t SphP[i].dEulerA[0] *= efak / SphP[i].d.Density;\n\t\t SphP[i].dEulerA[1] *= efak / SphP[i].d.Density;\n\t\t SphP[i].dEulerA[2] *= efak / SphP[i].d.Density;\n\t\t SphP[i].dEulerB[0] *= efak / SphP[i].d.Density;\n\t\t SphP[i].dEulerB[1] *= efak / SphP[i].d.Density;\n\t\t SphP[i].dEulerB[2] *= efak / SphP[i].d.Density;\n#ifdef\tPERIODIC\n\t\t SphP[i].dEulerB[2] = 1.0;\n#endif\n\t\t SphP[i].BPred[0] =\n\t\t\tSphP[i].dEulerA[1] * SphP[i].dEulerB[2] - SphP[i].dEulerA[2] * SphP[i].dEulerB[1];\n\t\t SphP[i].BPred[1] =\n\t\t\tSphP[i].dEulerA[2] * SphP[i].dEulerB[0] - SphP[i].dEulerA[0] * SphP[i].dEulerB[2];\n\t\t SphP[i].BPred[2] =\n\t\t\tSphP[i].dEulerA[0] * SphP[i].dEulerB[1] - SphP[i].dEulerA[1] * SphP[i].dEulerB[0];\n#endif\n\t\t }\n\n#ifndef WAKEUP\n\t\t dt_step = (P[i].TimeBin ? (1 << P[i].TimeBin) : 0);\n#else\n\t\t dt_step = P[i].dt_step;\n#endif\n\t\t dt_entr = (All.Ti_Current - (P[i].Ti_begstep + dt_step / 2)) * All.Timebase_interval;\n\n#ifndef EOS_DEGENERATE\n#ifndef MHM\n#ifndef SOFTEREQS\n\t\t SphP[i].Pressure =\n\t\t (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA);\n#else\n\t\t /* use an intermediate EQS, between isothermal and the full multiphase model */\n\t\t if(SphP[i].d.Density * a3inv >= All.PhysDensThresh)\n\t\t SphP[i].Pressure = All.FactorForSofterEQS *\n\t\t (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA) +\n\t\t (1 - All.FactorForSofterEQS) * GAMMA_MINUS1 * SphP[i].d.Density * All.InitGasU;\n\t\t else\n\t\t SphP[i].Pressure =\n\t\t (SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr) * pow(SphP[i].d.Density, GAMMA);\n#endif\n#else\n\t\t /* Here we use an isothermal equation of state */\n\t\t SphP[i].Pressure = GAMMA_MINUS1 * SphP[i].d.Density * All.InitGasU;\n\t\t SphP[i].Entropy = SphP[i].Pressure / pow(SphP[i].d.Density, GAMMA);\n#endif\n#else\n\t\t /* call tabulated eos with physical units */\n#ifdef EOS_ENERGY\n\t\t eos_calc_egiven2(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc,\n\t\t\t\t SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr * All.UnitTime_in_s,\n\t\t\t\t &SphP[i].temp, &SphP[i].Pressure);\n\t\t SphP[i].Pressure /= All.UnitPressure_in_cgs;\n#else\n\t\t eos_calc_sgiven(SphP[i].d.Density * All.UnitDensity_in_cgs, SphP[i].xnuc,\n\t\t\t\t SphP[i].Entropy + SphP[i].e.DtEntropy * dt_entr * All.UnitTime_in_s,\n\t\t\t\t &SphP[i].temp, &SphP[i].Pressure, &SphP[i].u);\n\t\t SphP[i].Pressure /= All.UnitPressure_in_cgs;\n#endif\n#endif\n\n#ifdef COSMIC_RAYS\n\t\t for(CRpop = 0; CRpop < NUMCRPOP; CRpop++)\n\t\t {\n\t\t CR_Particle_Update(SphP + i, CRpop);\n#ifndef CR_NOPRESSURE\n\t\t SphP[i].Pressure += CR_Comoving_Pressure(SphP + i, CRpop);\n#endif\n\t\t }\n#endif\n\t\t}\n\n#ifdef BLACK_HOLES\n\t if(P[i].Type == 5)\n\t\t{\n\t\t if(P[i].b1.BH_Density > 0)\n\t\t {\n\t\t P[i].b2.BH_Entropy /= P[i].b1.BH_Density;\n\t\t P[i].b3.BH_SurroundingGasVel[0] /= P[i].b1.BH_Density;\n\t\t P[i].b3.BH_SurroundingGasVel[1] /= P[i].b1.BH_Density;\n\t\t P[i].b3.BH_SurroundingGasVel[2] /= P[i].b1.BH_Density;\n\t\t }\n\t\t}\n#endif\n\n\t /* now check whether we had enough neighbours */\n\n\t desnumngb = All.DesNumNgb;\n\n#ifdef BLACK_HOLES\n\t if(P[i].Type == 5)\n\t\tdesnumngb = All.DesNumNgb * All.BlackHoleNgbFactor;\n#endif\n\n#ifdef RADTRANSFER\n\t if(P[i].Type == 4)\n\t\tdesnumngb = 64;//NORM_COEFF * KERNEL_COEFF_1;\t/* will assign the stellar luminosity to very few (one actually) gas particles */\n#endif\n\n\t if(PPP[i].n.NumNgb < (desnumngb - All.MaxNumNgbDeviation) ||\n\t\t (PPP[i].n.NumNgb > (desnumngb + All.MaxNumNgbDeviation)\n\t\t && PPP[i].Hsml > (1.01 * All.MinGasHsml)))\n\t\t{\n\t\t /* need to redo this particle */\n\t\t npleft++;\n\n\t\t if(Left[i] > 0 && Right[i] > 0)\n\t\t if((Right[i] - Left[i]) < 1.0e-3 * Left[i])\n\t\t {\n\t\t\t/* this one should be ok */\n\t\t\tnpleft--;\n\t\t\tP[i].TimeBin = -P[i].TimeBin - 1;\t/* Mark as inactive */\n\t\t\tcontinue;\n\t\t }\n\n\t\t if(PPP[i].n.NumNgb < (desnumngb - All.MaxNumNgbDeviation))\n\t\t Left[i] = DMAX(PPP[i].Hsml, Left[i]);\n\t\t else\n\t\t {\n\t\t if(Right[i] != 0)\n\t\t\t{\n\t\t\t if(PPP[i].Hsml < Right[i])\n\t\t\t Right[i] = PPP[i].Hsml;\n\t\t\t}\n\t\t else\n\t\t\tRight[i] = PPP[i].Hsml;\n\t\t }\n\n\t\t if(iter >= MAXITER - 10)\n\t\t {\n\t\t printf\n\t\t\t(\"i=%d task=%d ID=%d Hsml=%g Left=%g Right=%g Ngbs=%g Right-Left=%g\\n pos=(%g|%g|%g)\\n\",\n\t\t\t i, ThisTask, (int) P[i].ID, PPP[i].Hsml, Left[i], Right[i],\n\t\t\t (float) PPP[i].n.NumNgb, Right[i] - Left[i], P[i].Pos[0], P[i].Pos[1], P[i].Pos[2]);\n\t\t fflush(stdout);\n\t\t }\n\n\t\t if(Right[i] > 0 && Left[i] > 0)\n\t\t PPP[i].Hsml = pow(0.5 * (pow(Left[i], 3) + pow(Right[i], 3)), 1.0 / 3);\n\t\t else\n\t\t {\n\t\t if(Right[i] == 0 && Left[i] == 0)\n\t\t\tendrun(8188);\t/* can't occur */\n\n\t\t if(Right[i] == 0 && Left[i] > 0)\n\t\t\t{\n\t\t\t if(P[i].Type == 0 && fabs(PPP[i].n.NumNgb - desnumngb) < 0.5 * desnumngb)\n\t\t\t {\n\t\t\t fac = 1 - (PPP[i].n.NumNgb -\n\t\t\t\t\t desnumngb) / (NUMDIMS * PPP[i].n.NumNgb) *\n\t\t\t\tSphP[i].h.DhsmlDensityFactor;\n\n\t\t\t if(fac < 1.26)\n\t\t\t\tPPP[i].Hsml *= fac;\n\t\t\t else\n\t\t\t\tPPP[i].Hsml *= 1.26;\n\t\t\t }\n\t\t\t else\n\t\t\t PPP[i].Hsml *= 1.26;\n\t\t\t}\n\n\t\t if(Right[i] > 0 && Left[i] == 0)\n\t\t\t{\n\t\t\t if(P[i].Type == 0 && fabs(PPP[i].n.NumNgb - desnumngb) < 0.5 * desnumngb)\n\t\t\t {\n\t\t\t fac = 1 - (PPP[i].n.NumNgb -\n\t\t\t\t\t desnumngb) / (NUMDIMS * PPP[i].n.NumNgb) *\n\t\t\t\tSphP[i].h.DhsmlDensityFactor;\n\n\t\t\t if(fac > 1 / 1.26)\n\t\t\t\tPPP[i].Hsml *= fac;\n\t\t\t else\n\t\t\t\tPPP[i].Hsml /= 1.26;\n\t\t\t }\n\t\t\t else\n\t\t\t PPP[i].Hsml /= 1.26;\n\t\t\t}\n\t\t }\n\n\t\t if(PPP[i].Hsml < All.MinGasHsml)\n\t\t PPP[i].Hsml = All.MinGasHsml;\n\n#ifdef BLACK_HOLES\n\t\t if(P[i].Type == 5)\n\t\t if(Left[i] > All.BlackHoleMaxAccretionRadius)\n\t\t {\n\t\t\t/* this will stop the search for a new BH smoothing length in the next iteration */\n\t\t\tPPP[i].Hsml = Left[i] = Right[i] = All.BlackHoleMaxAccretionRadius;\n\t\t }\n#endif\n\t\t}\n\t else\n\t\tP[i].TimeBin = -P[i].TimeBin - 1;\t/* Mark as inactive */\n\t }\n\t}\n tend = second();\n timecomp1 += timediff(tstart, tend);\n\n sumup_large_ints(1, &npleft, &ntot);\n\n if(ntot > 0)\n\t{\n\t iter++;\n\n\t if(iter > 0 && ThisTask == 0)\n\t {\n\t printf(\"ngb iteration %d: need to repeat for %d%09d particles.\\n\", iter,\n\t\t (int) (ntot / 1000000000), (int) (ntot % 1000000000));\n\t fflush(stdout);\n\t }\n\n\t if(iter > MAXITER)\n\t {\n\t printf(\"failed to converge in neighbour iteration in density()\\n\");\n\t fflush(stdout);\n\t endrun(1155);\n\t }\n\t}\n }\n while(ntot > 0);\n\n\n myfree(DataNodeList);\n myfree(DataIndexTable);\n myfree(Ngblist);\n myfree(Right);\n myfree(Left);\n\n\n\n#if defined(CS_MODEL) && defined(CS_FEEDBACK)\n double xhyd, yhel, ne, mu, energy, temp, a3inv;\n\n for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i])\n {\n if(P[i].Type == 0 && P[i].EnergySN < 0)\t/* only gas particles should enter here */\n\t{\n\n\t printf(\"prom 2i=%d type=%d energySN%g\\n\", i, P[i].Type, P[i].EnergySN);\n\t fflush(0);\n\n\t P[i].EnergySN = 0;\n\n\t}\n\n if(All.ComovingIntegrationOn)\n\ta3inv = 1 / (All.Time * All.Time * All.Time);\n else\n\ta3inv = 1;\n\n if(P[i].Type == 0 && (SphP[i].TempPromotion > 0 || SphP[i].DensPromotion > 0))\n\t{\n\t xhyd = P[i].Zm[6] / P[i].Mass;\n\t yhel = (1 - xhyd) / (4. * xhyd);\n\t ne = SphP[i].Ne;\n\t mu = (1 + 4 * yhel) / (1 + yhel + ne);\n\t energy = SphP[i].Entropy * P[i].Mass / GAMMA_MINUS1 * pow(SphP[i].d.Density * a3inv, GAMMA_MINUS1);\t/* Total Energys */\n\t temp = GAMMA_MINUS1 / BOLTZMANN * energy / P[i].Mass * PROTONMASS * mu;\n\t temp *= All.UnitEnergy_in_cgs / All.UnitMass_in_g;\t/* Temperature in Kelvin */\n\n\t fprintf(FdPromotion, \"%g %d %g %g %g %g %g %g\\n\", All.Time, P[i].ID, SphP[i].DensPromotion,\n\t\t SphP[i].TempPromotion, SphP[i].d.Density, temp, SphP[i].da.DensityAvg,\n\t\t SphP[i].ea.EntropyAvg);\n\t fflush(FdPromotion);\n\t}\n }\n#endif\n\n /* mark as active again */\n for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i])\n if(P[i].TimeBin < 0)\n P[i].TimeBin = -P[i].TimeBin - 1;\n\n /* collect some timing information */\n\n t1 = WallclockTime = second();\n timeall += timediff(t0, t1);\n\n timecomp = timecomp1 + timecomp2;\n timewait = timewait1 + timewait2;\n timecomm = timecommsumm1 + timecommsumm2;\n\n CPU_Step[CPU_DENSCOMPUTE] += timecomp;\n CPU_Step[CPU_DENSWAIT] += timewait;\n CPU_Step[CPU_DENSCOMM] += timecomm;\n CPU_Step[CPU_DENSMISC] += timeall - (timecomp + timewait + timecomm);\n}\n\n\n/*! This function represents the core of the SPH density computation. The\n * target particle may either be local, or reside in the communication\n * buffer.\n */\nint density_evaluate(int target, int mode, int *nexport, int *nsend_local)\n{\n int j, n;\n int startnode, numngb, numngb_inbox, listindex = 0;\n double h, h2, fac, hinv, hinv3, hinv4;\n MyLongDouble rho;\n double wk, dwk;\n double dx, dy, dz, r, r2, u, mass_j;\n double dvx, dvy, dvz;\n MyLongDouble weighted_numngb;\n MyLongDouble dhsmlrho;\n\n#ifdef HYDRO_COST_FACTOR\n int ninteractions = 0;\n#endif\n\n#ifdef CS_MODEL\n double densityold, entropy = 0;\n#endif\n#ifdef BLACK_HOLES\n MyLongDouble gasvel[3];\n#endif\n#ifndef NAVIERSTOKES\n MyLongDouble divv, rotv[3];\n#else\n int k;\n double dvel[3][3];\n#endif\n\n MyDouble *pos;\n MyFloat *vel;\n static MyFloat veldummy[3] = { 0, 0, 0 };\n\n#ifdef EULERPOTENTIALS\n MyDouble deulera[3], deulerb[3], eulera, eulerb, dea, deb;\n\n deulera[0] = deulera[1] = deulera[2] = deulerb[0] = deulerb[1] = deulerb[2] = 0;\n#endif\n\n#if defined(BLACK_HOLES)\n MyLongDouble smoothentr;\n\n smoothentr = 0;\n#endif\n\n#ifdef WINDS\n double delaytime;\n#endif\n\n#ifdef VOLUME_CORRECTION\n double densityold, densitystd = 0;\n#endif\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB)\n MyFloat *bflt;\n MyDouble dbx, dby, dbz;\n#endif\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n MyDouble rotb[3];\n#endif\n\n#ifdef TRACEDIVB\n double divB = 0;\n#endif\n\n#ifdef CONDUCTION_SATURATION\n double gradentr[3];\n\n gradentr[0] = gradentr[1] = gradentr[2] = 0;\n#endif\n\n#ifdef RADTRANSFER_FLUXLIMITER\n double grad_ngamma[3];\n\n grad_ngamma[0] = grad_ngamma[1] = grad_ngamma[2] = 0;\n#endif\n\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n rotb[0] = rotb[1] = rotb[2] = 0;\n#endif\n\n#ifndef NAVIERSTOKES\n divv = rotv[0] = rotv[1] = rotv[2] = 0;\n#else\n for(k = 0; k < 3; k++)\n dvel[k][0] = dvel[k][1] = dvel[k][2] = 0;\n#endif\n#ifdef BLACK_HOLES\n gasvel[0] = gasvel[1] = gasvel[2] = 0;\n#endif\n rho = weighted_numngb = dhsmlrho = 0;\n\n if(mode == 0)\n {\n pos = P[target].Pos;\n h = PPP[target].Hsml;\n#ifdef VOLUME_CORRECTION\n densityold = SphP[target].DensityOld;\n#endif\n if(P[target].Type == 0)\n\t{\n\t vel = SphP[target].VelPred;\n#ifdef WINDS\n\t delaytime = SphP[target].DelayTime;\n#endif\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB)\n\t bflt = SphP[target].BPred;\n#endif\n#ifdef EULERPOTENTIALS\n\t eulera = SphP[target].EulerA;\n\t eulerb = SphP[target].EulerB;\n#endif\n\t}\n else\n\tvel = veldummy;\n#ifdef CS_MODEL\n if(P[target].Type == 0)\n\t{\n\t densityold = SphP[target].DensityOld;\n\t entropy = SphP[target].Entropy;\n\t}\n else\n\tdensityold = 0;\n#endif\n }\n else\n {\n pos = DensDataGet[target].Pos;\n vel = DensDataGet[target].Vel;\n h = DensDataGet[target].Hsml;\n#ifdef WINDS\n delaytime = DensDataGet[target].DelayTime;\n#endif\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB)\n bflt = DensDataGet[target].BPred;\n#endif\n#ifdef VOLUME_CORRECTION\n densityold = DensDataGet[target].DensityOld;\n#endif\n#ifdef EULERPOTENTIALS\n eulera = DensDataGet[target].EulerA;\n eulerb = DensDataGet[target].EulerB;\n#endif\n#ifdef CS_MODEL\n densityold = DensDataGet[target].DensityOld;\n entropy = DensDataGet[target].Entropy;\n#endif\n }\n\n\n h2 = h * h;\n hinv = 1.0 / h;\n#ifndef TWODIMS\n hinv3 = hinv * hinv * hinv;\n#else\n hinv3 = hinv * hinv / boxSize_Z;\n#endif\n hinv4 = hinv3 * hinv;\n\n\n if(mode == 0)\n {\n startnode = All.MaxPart;\t/* root node */\n }\n else\n {\n startnode = DensDataGet[target].NodeList[0];\n startnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n }\n\n numngb = 0;\n\n while(startnode >= 0)\n {\n while(startnode >= 0)\n\t{\n#ifdef CS_MODEL\n\t numngb_inbox = cs_ngb_treefind_variable_decoupling(&pos[0], h, target, &startnode,\n\t\t\t\t\t\t\t densityold, entropy, &vel[0], mode, nexport,\n\t\t\t\t\t\t\t nsend_local);\n#else\n\t numngb_inbox = ngb_treefind_variable(pos, h, target, &startnode, mode, nexport, nsend_local);\n#endif\n\n\t if(numngb_inbox < 0)\n\t return -1;\n\n\t for(n = 0; n < numngb_inbox; n++)\n\t {\n#ifdef HYDRO_COST_FACTOR\n\t ninteractions++;\n#endif\n\t j = Ngblist[n];\n#ifdef WINDS\n\t if(SphP[j].DelayTime > 0)\t/* partner is a wind particle */\n\t\tif(!(delaytime > 0))\t/* if I'm not wind, then ignore the wind particle */\n\t\t continue;\n#endif\n#ifdef BLACK_HOLES\n\t if(P[j].Mass == 0)\n\t\tcontinue;\n#endif\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 < h2)\n\t\t{\n\t\t numngb++;\n\n\t\t r = sqrt(r2);\n\n\t\t u = r * hinv;\n\n\t\t if(u < 0.5)\n\t\t {\n\t\t wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);\n\t\t dwk = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);\n\t\t }\n\t\t else\n\t\t {\n\t\t wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);\n\t\t dwk = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);\n\t\t }\n\n\t\t mass_j = P[j].Mass;\n\n#ifdef VOLUME_CORRECTION\n\t\t rho += FLT(mass_j * wk * pow(densityold / SphP[j].DensityOld, VOLUME_CORRECTION));\n\t\t densitystd += FLT(mass_j * wk);\n#else\n\t\t rho += FLT(mass_j * wk);\n#endif\n\n\t\t weighted_numngb += FLT(NORM_COEFF * wk / hinv3);\t/* 4.0/3 * PI = 4.188790204786 */\n\n\t\t dhsmlrho += FLT(-mass_j * (NUMDIMS * hinv * wk + u * dwk));\n\n\n#ifdef BLACK_HOLES\n\t\t smoothentr += FLT(mass_j * wk * SphP[j].Entropy);\n\t\t gasvel[0] += FLT(mass_j * wk * SphP[j].VelPred[0]);\n\t\t gasvel[1] += FLT(mass_j * wk * SphP[j].VelPred[1]);\n\t\t gasvel[2] += FLT(mass_j * wk * SphP[j].VelPred[2]);\n#endif\n\n#ifdef CONDUCTION_SATURATION\n\t\t if(r > 0)\n\t\t {\n\t\t gradentr[0] += mass_j * dwk * dx / r * SphP[j].Entropy;\n\t\t gradentr[1] += mass_j * dwk * dy / r * SphP[j].Entropy;\n\t\t gradentr[2] += mass_j * dwk * dz / r * SphP[j].Entropy;\n\t\t }\n#endif\n\n\n#ifdef RADTRANSFER_FLUXLIMITER\n\t\t if(r > 0)\n\t\t {\n\t\t grad_ngamma[0] += mass_j * dwk * dx / r * SphP[j].n_gamma;\n\t\t grad_ngamma[1] += mass_j * dwk * dy / r * SphP[j].n_gamma;\n\t\t grad_ngamma[2] += mass_j * dwk * dz / r * SphP[j].n_gamma;\n\t\t }\n#endif\n\n\n\t\t if(r > 0)\n\t\t {\n\t\t fac = mass_j * dwk / r;\n\n\t\t dvx = vel[0] - SphP[j].VelPred[0];\n\t\t dvy = vel[1] - SphP[j].VelPred[1];\n\t\t dvz = vel[2] - SphP[j].VelPred[2];\n\n#ifndef NAVIERSTOKES\n\t\t divv += FLT(-fac * (dx * dvx + dy * dvy + dz * dvz));\n\n\t\t rotv[0] += FLT(fac * (dz * dvy - dy * dvz));\n\t\t rotv[1] += FLT(fac * (dx * dvz - dz * dvx));\n\t\t rotv[2] += FLT(fac * (dy * dvx - dx * dvy));\n#else\n\t\t dvel[0][0] -= fac * dx * dvx;\n\t\t dvel[0][1] -= fac * dx * dvy;\n\t\t dvel[0][2] -= fac * dx * dvz;\n\t\t dvel[1][0] -= fac * dy * dvx;\n\t\t dvel[1][1] -= fac * dy * dvy;\n\t\t dvel[1][2] -= fac * dy * dvz;\n\t\t dvel[2][0] -= fac * dz * dvx;\n\t\t dvel[2][1] -= fac * dz * dvy;\n\t\t dvel[2][2] -= fac * dz * dvz;\n#endif\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS) || defined(TRACEDIVB)\n\t\t dbx = bflt[0] - SphP[j].BPred[0];\n\t\t dby = bflt[1] - SphP[j].BPred[1];\n\t\t dbz = bflt[2] - SphP[j].BPred[2];\n#endif\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n\t\t rotb[0] += FLT(fac * (dz * dby - dy * dbz));\n\t\t rotb[1] += FLT(fac * (dx * dbz - dz * dbx));\n\t\t rotb[2] += FLT(fac * (dy * dbx - dx * dby));\n#endif\n#ifdef TRACEDIVB\n\t\t divB += fac * (dbx * dx + dby * dy + dbz * dz);\n#endif\n#ifdef EULERPOTENTIALS\n\t\t dea = eulera - SphP[j].EulerA;\n\t\t deb = eulerb - SphP[j].EulerB;\n\t\t deulera[0] -= fac * dx * dea;\n\t\t deulera[1] -= fac * dy * dea;\n\t\t deulera[2] -= fac * dz * dea;\n\t\t deulerb[0] -= fac * dx * deb;\n\t\t deulerb[1] -= fac * dy * deb;\n\t\t deulerb[2] -= fac * dz * deb;\n#endif\n\t\t }\n\t\t}\n\t }\n\t}\n\n if(mode == 1)\n\t{\n\t listindex++;\n\t if(listindex < NODELISTLENGTH)\n\t {\n\t startnode = DensDataGet[target].NodeList[listindex];\n\t if(startnode >= 0)\n\t\tstartnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n\t }\n\t}\n }\n\n if(mode == 0)\n {\n PPP[target].n.dNumNgb = weighted_numngb;\n#ifdef HYDRO_COST_FACTOR\n P[target].GravCost += HYDRO_COST_FACTOR * ninteractions;\n#endif\n if(P[target].Type == 0)\n\t{\n\t SphP[target].d.dDensity = rho;\n#ifdef VOLUME_CORRECTION\n\t SphP[target].DensityStd = densitystd;\n#endif\n\t SphP[target].h.dDhsmlDensityFactor = dhsmlrho;\n#ifndef NAVIERSTOKES\n\t SphP[target].v.dDivVel = divv;\n\t SphP[target].r.dRot[0] = rotv[0];\n\t SphP[target].r.dRot[1] = rotv[1];\n\t SphP[target].r.dRot[2] = rotv[2];\n#else\n\t for(k = 0; k < 3; k++)\n\t {\n\t SphP[target].u.DV[k][0] = dvel[k][0];\n\t SphP[target].u.DV[k][1] = dvel[k][1];\n\t SphP[target].u.DV[k][2] = dvel[k][2];\n\t }\n#endif\n\n#ifdef CONDUCTION_SATURATION\n\t SphP[target].GradEntr[0] = gradentr[0];\n\t SphP[target].GradEntr[1] = gradentr[1];\n\t SphP[target].GradEntr[2] = gradentr[2];\n#endif\n\n#ifdef RADTRANSFER_FLUXLIMITER\n\t SphP[target].Grad_ngamma[0] = grad_ngamma[0];\n\t SphP[target].Grad_ngamma[1] = grad_ngamma[1];\n\t SphP[target].Grad_ngamma[2] = grad_ngamma[2];\n#endif\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n\t SphP[target].RotB[0] = rotb[0];\n\t SphP[target].RotB[1] = rotb[1];\n\t SphP[target].RotB[2] = rotb[2];\n#endif\n#ifdef TRACEDIVB\n\t SphP[target].divB = divB;\n#endif\n#ifdef EULERPOTENTIALS\n\t SphP[target].dEulerA[0] = deulera[0];\n\t SphP[target].dEulerA[1] = deulera[1];\n\t SphP[target].dEulerA[2] = deulera[2];\n\t SphP[target].dEulerB[0] = deulerb[0];\n\t SphP[target].dEulerB[1] = deulerb[1];\n\t SphP[target].dEulerB[2] = deulerb[2];\n#endif\n\t}\n#ifdef BLACK_HOLES\n P[target].b1.dBH_Density = rho;\n P[target].b2.dBH_Entropy = smoothentr;\n P[target].b3.dBH_SurroundingGasVel[0] = gasvel[0];\n P[target].b3.dBH_SurroundingGasVel[1] = gasvel[1];\n P[target].b3.dBH_SurroundingGasVel[2] = gasvel[2];\n#endif\n#if defined(RADTRANSFER) || defined(SNIA_HEATING)\n if(P[target].Type == 4)\n\tP[target].DensAroundStar = rho;\n#endif\n }\n else\n {\n#ifdef HYDRO_COST_FACTOR\n DensDataResult[target].Ninteractions = ninteractions;\n#endif\n DensDataResult[target].Rho = rho;\n#ifdef VOLUME_CORRECTION\n DensDataResult[target].DensityStd = densitystd;\n#endif\n DensDataResult[target].Ngb = weighted_numngb;\n DensDataResult[target].DhsmlDensity = dhsmlrho;\n#ifndef NAVIERSTOKES\n DensDataResult[target].Div = divv;\n DensDataResult[target].Rot[0] = rotv[0];\n DensDataResult[target].Rot[1] = rotv[1];\n DensDataResult[target].Rot[2] = rotv[2];\n#else\n for(k = 0; k < 3; k++)\n\t{\n\t DensDataResult[target].DV[k][0] = dvel[k][0];\n\t DensDataResult[target].DV[k][1] = dvel[k][1];\n\t DensDataResult[target].DV[k][2] = dvel[k][2];\n\t}\n#endif\n\n#if defined(BLACK_HOLES)\n DensDataResult[target].SmoothedEntr = smoothentr;\n#endif\n#ifdef CONDUCTION_SATURATION\n DensDataResult[target].GradEntr[0] = gradentr[0];\n DensDataResult[target].GradEntr[1] = gradentr[1];\n DensDataResult[target].GradEntr[2] = gradentr[2];\n#endif\n\n#ifdef RADTRANSFER_FLUXLIMITER\n DensDataResult[target].Grad_ngamma[0] = grad_ngamma[0];\n DensDataResult[target].Grad_ngamma[1] = grad_ngamma[1];\n DensDataResult[target].Grad_ngamma[2] = grad_ngamma[2];\n#endif\n\n#if defined(MAGNETIC_DIFFUSION) || defined(ROT_IN_MAG_DIS)\n DensDataResult[target].RotB[0] = rotb[0];\n DensDataResult[target].RotB[1] = rotb[1];\n DensDataResult[target].RotB[2] = rotb[2];\n#endif\n#ifdef TRACEDIVB\n DensDataResult[target].divB = divB;\n#endif\n#ifdef BLACK_HOLES\n DensDataResult[target].GasVel[0] = gasvel[0];\n DensDataResult[target].GasVel[1] = gasvel[1];\n DensDataResult[target].GasVel[2] = gasvel[2];\n#endif\n\n#ifdef EULERPOTENTIALS\n DensDataResult[target].dEulerA[0] = deulera[0];\n DensDataResult[target].dEulerA[1] = deulera[1];\n DensDataResult[target].dEulerA[2] = deulera[2];\n DensDataResult[target].dEulerB[0] = deulerb[0];\n DensDataResult[target].dEulerB[1] = deulerb[1];\n DensDataResult[target].dEulerB[2] = deulerb[2];\n#endif\n }\n\n return 0;\n}\n\n\n\n\n\nint density_isactive(int n)\n{\n if(P[n].TimeBin < 0)\n return 0;\n\n#if defined(RADTRANSFER) || defined(SNIA_HEATING)\n if(P[n].Type == 4)\n return 1;\n#endif\n\n#ifdef BLACK_HOLES\n if(P[n].Type == 5)\n return 1;\n#endif\n\n if(P[n].Type == 0)\n return 1;\n\n return 0;\n}\n\n\n#ifdef NAVIERSTOKES\ndouble get_shear_viscosity(int i)\n{\n return All.NavierStokes_ShearViscosity;\n}\n#endif\n", "meta": {"hexsha": "b29cf80dee7b271782e43c20b6492467ff3b98cd", "size": 37303, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/density.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/density.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/density.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": 27.0311594203, "max_line_length": 129, "alphanum_fraction": 0.6163847412, "num_tokens": 13406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6688802603710085, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2749839452533641}} {"text": "#ifndef __COYOTE_H\n#define __COYOTE_H\n\n\n\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"errorlist.h\"\n#include \"maths.h\"\n\n\n/* Error codes */\n#define coyote_base -2200\n#define coyote_h -1 + coyote_base\n#define coyote_flat -2 + coyote_base\n#define coyote_range -3 + coyote_base\n\n\n/* =============================================== *\n * From other header files which have been removed *\n * Constants which are used also outside of Coyote *\n * (e.g. in cosmo.c) \t\t\t\t *\n * =============================================== */\n\n/* Coyote I */\n\n/* Number of k values */\n#define nsim 1995\nconst double ksim[nsim];\n\n/* Coyote II */\n\n#define fr_nsim 582\n#define fr_rs 11\nconst double fr_ksim[fr_nsim];\n\n\n\n/* v1: Functions from hubble.c and emu.c */\ndouble getH0fromCMB(double omega_m, double omega_b, double w0_de, int physical);\nvoid fill_xstar_wo_z(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de, double xstar[]);\ndouble P_NL_coyote5(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de,\n\t\t double h_100, double a, double k, error **err);\nvoid emu(double *xstar, double *ystar, error **err);\n\n/* v2: Functions from fr_emu.c */\ndouble P_NL_coyote6(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de,\n\t\t double h_100, double a, double k, double **ystar_allz, error **err);\nvoid fr_check_range(const double *xstar, error **err);\nvoid fr_fill_ystar_allz(double *ystar_allz, const double *xstar, error **err);\nvoid fr_emu(const double *xstar, double *ystar, const double *ystar_allz, error **err);\nvoid fill_xstar6_wo_z(double omega_m, double omega_b, double n_spec, double sigma_8, double w0_de, double h_100,\n double xstar[]);\n\n\n#endif\n", "meta": {"hexsha": "6ff6c2427668f0923cf60dbc1dbd93be0e6fec2b", "size": 1938, "ext": "h", "lang": "C", "max_stars_repo_path": "src/nicaea_2.5/Coyote/include/coyote.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/Coyote/include/coyote.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/Coyote/include/coyote.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": 28.9253731343, "max_line_length": 114, "alphanum_fraction": 0.6811145511, "num_tokens": 550, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.27434326303852985}} {"text": "#ifndef _PS_\n#define _PS_\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 \"../Parameter_files/Variables.h\"\n\n/* New in v1.1 */\n#define ERFC_NPTS (int) 75\n#define ERFC_PARAM_DELTA (float) 0.1\nstatic double log_erfc_table[ERFC_NPTS], erfc_params[ERFC_NPTS];\nstatic gsl_interp_accel *erfc_acc;\nstatic gsl_spline *erfc_spline;\n\n#define NR_END 1\n#define FREE_ARG char*\n\n#define MM 7\n#define NSTACK 50\n\n#define FUNC(x,y,z,xx,yy) ((*func)(x,y,z,xx,yy))\n#define FUNC2(x1,x2,x3,x4,x5,x6) ((*func)(x1,x2,x3,x4,x5,x6))\n#define EPS2 3.0e-11\n\n#define SWAP(a,b) tempr=(a);(a)=(b);(b)=tempr\n\n#define NGaussLegendre 40 //defines the number of points in the Gauss-Legendre quadrature integration\n\n#define SPLINE_NPTS (int) 250\n#define NGLhigh 100\n#define NGLlow 100\n\n#define Nhigh 200\n#define Nlow 100\n#define NMass 200\n\nstatic double log_MFspline_table[SPLINE_NPTS], MFspline_params[SPLINE_NPTS];\nstatic double log_MFspline_table_densgtr1[SPLINE_NPTS], MFspline_params_densgtr1[SPLINE_NPTS];\nstatic gsl_interp_accel *MFspline_acc, *MFspline_densgtr1_acc;\nstatic gsl_spline *MF_spline, *MF_spline_densgtr1;\n\nstatic double Fcoll_spline_params[SPLINE_NPTS], log_Fcoll_spline_table[SPLINE_NPTS];\nstatic gsl_interp_accel *Fcoll_spline_acc;\nstatic gsl_spline *Fcoll_spline;\n\nstruct parameters_gsl_int_{\n double z_obs;\n double Mval;\n double M_Feed;\n double alpha_pl;\n double del_traj_1;\n double del_traj_2;\n};\n\nstruct parameters_gsl_ST_int_{\n double z_obs;\n double M_Feed;\n double alpha_pl;\n};\n\nunsigned long *lvector(long nl, long nh);\nvoid free_lvector(unsigned long *v, long nl, long nh);\n\nfloat *vector(long nl, long nh);\nvoid free_vector(float *v, long nl, long nh);\n\nvoid spline(float x[], float y[], int n, float yp1, float ypn, float y2[]);\nvoid splint(float xa[], float ya[], float y2a[], int n, float x, float *y);\n\nvoid gauleg(float x1, float x2, float x[], float w[], int n);\n\ndouble FgtrlnM_general(double lnM, void *params);\ndouble FgtrM_general(float z, float M1, float M_Max, float M2, float MFeedback, float alpha, float delta1, float delta2);\n\nfloat FgtrConditionalM_second(float z, float M1, float M2, float MFeedback, float alpha, float delta1, float delta2);\nfloat dNdM_conditional_second(float z, float M1, float M2, float delta1, float delta2);\n\nfloat FgtrConditionallnM(float M1, struct parameters_gsl_int_ parameters_gsl_int);\nfloat GaussLegengreQuad_Fcoll(int n, float z, float M2, float MFeedback, float alpha, float delta1, float delta2);\n\nfloat *Overdense_spline_gsl,*Overdense_spline_GL_high,*Fcoll_spline_gsl,*Fcoll_spline_GL_high,*xi_low,*xi_high,*wi_high,*wi_low;\nfloat *second_derivs_low_GL,*second_derivs_high_GL,*Overdense_spline_GL_low,*Fcoll_spline_GL_low;\n\nfloat *Mass_Spline, *Sigma_Spline, *dSigmadm_Spline, *second_derivs_sigma, *second_derivs_dsigma;\n\nvoid initialiseSplinedSigmaM(float M_Min, float M_Max);\nvoid initialiseGL_Fcoll(int n_low, int n_high, float M_Min, float M_Max);\nvoid initialiseGL_FcollDblPl(int n_low, int n_high, float M_Min, float M_feedback, float M_Max);\nvoid initialiseFcoll_spline(float z, float Mmin, float Mmax, float Mval, float MFeedback, float alphapl);\n\ndouble dFdlnM_st_PL (double lnM, void *params);\ndouble FgtrM_st_PL(double z, double Mmin, double MFeedback, double alpha_pl);\n\ndouble sigma_norm, R, theta_cmb, omhh, z_equality, y_d, sound_horizon, alpha_nu, f_nu, f_baryon, beta_c, d2fact, R_CUTOFF, DEL_CURR, SIG_CURR;\n\n\n/***** FUNCTION PROTOTYPES *****/\ndouble init_ps(); /* initialize global variables, MUST CALL THIS FIRST!!! returns R_CUTOFF */\nvoid free_ps(); /* deallocates the gsl structures from init_ps */\ndouble splined_erfc(double); /* returns erfc for x>=0, using cubic spline in logy-x space */\ndouble deltolindel(float del, float z); /* converts a non-linear overdensity, del, at z to a linear overdensity at z=0 */\ndouble lindeltodel(float lindel, float z); /* converts a linear overdensity, del, at z=0 to a non-linear overdensity at redshift z */\ndouble power_in_k(double k); /* Returns the value of the linear power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */\n\ndouble power_in_vcb(double k); /*JBM: Returns the value of the DM-b relative velocity power spectrum density (i.e. <|delta_k|^2>/V) at a given k mode at z=0 */\n\n\ndouble RtoM(double); /* R in Mpc, M in Msun */\ndouble MtoR(double); /* R in Mpc, M in Msun */\ndouble M_J_WDM(); /* returns the \"effective Jeans mass\" corresponding to the gas analog of WDM ; eq. 10 in BHO 2001 */\ndouble sheth_delc(double del, double sig);\ndouble dNdM_st(double z, double M);\ndouble dNdM(double z, double M);\ndouble dnbiasdM(double M, float z, double M_o, float del_o); /* dnbiasdM */\ndouble FgtrM(double z, double M); //calculates the fraction of mass contained in haloes with mass > M at redshift z\ndouble FgtrM_st(double z, double M); //calculates the fraction of mass contained in haloes with mass > M at redshift z, with Sheth-Tormen correction\ndouble FgtrM_bias(double z, double M, double del_bias, double sig_bias); //calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias\ndouble sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias);/* Uses sigma parameters instead of Mass for scale */\n\ndouble FgtrM_bias_BL08(double z, double M, double del_bias, double sig_bias); // as above, but this version uses the hybrid perscription of Barkana & Loeb 2004 (specifically the separate integral version of eq. 2 in Barkana & Loeb 2008)\ndouble dicke(double z); //calculates the dicke growth function at redshift z\ndouble ddickedz(double z); /* Redshift derivative of the growth function at z */\ndouble ddickedt(double z); /* Time derivative of the growth function at z */\ndouble sigma_z0(double M); //calculates sigma at z=0 (no dicke)\ndouble dsigmasqdm_z0(double M); //calculates d(sigma^2)/dm at z=0 (i.e. does not include dicke growth)\ndouble TFmdm(double k); //Eisenstien & Hu power spectrum transfer function\nvoid TFset_parameters();\nfloat get_R_c(); // returns R_CUTOFF\ndouble get_M_min_ion(float z);\n/***************************************/\n\n/* Returns the minimum source mass for ionizing sources, according to user specifications */\ndouble get_M_min_ion(float z){\n double MMIN;\n\n if (ION_M_MIN < 0){ // use the virial temperature for Mmin\n if (ION_Tvir_MIN < 9.99999e3) // neutral IGM\n MMIN = TtoM(z, ION_Tvir_MIN, 1.22);\n else // ionized IGM\n MMIN = TtoM(z, ION_Tvir_MIN, 0.6);\n }\n else if (ION_Tvir_MIN < 0){ // use the mass\n MMIN = ION_M_MIN;\n }\n else{\n fprintf(stderr, \"You have to \\\"turn-off\\\" either the ION_M_MIN or \\\n the ION_Tvir_MIN option in ANAL_PARAMS.H\\nAborting...\\n\");\n return -1;\n }\n // check for WDM\n if (P_CUTOFF && ( MMIN < M_J_WDM()))\n MMIN = M_J_WDM();\n // printf(\"Mmin is %e\\n\", MMIN);\n return MMIN;\n}\n\n/* Returns the minimum source mass for x-ray sources, according to user specifications */\ndouble get_M_min_xray(float z){\n double MMIN;\n if (X_RAY_Tvir_MIN < 9.99999e3) //neutral IGM\n MMIN = TtoM(z, X_RAY_Tvir_MIN, 1.22);\n else // ionized IGM\n MMIN = TtoM(z, X_RAY_Tvir_MIN, 0.6);\n\n // check for WDM\n if (P_CUTOFF && ( MMIN < M_J_WDM()))\n MMIN = M_J_WDM();\n // printf(\"Mmin is %e\\n\", MMIN);\n return MMIN;\n}\n\n\n/* returns the \"effective Jeans mass\" in Msun\n corresponding to the gas analog of WDM ; eq. 10 in Barkana+ 2001 */\ndouble M_J_WDM(){\n double z_eq, fudge=60;\n if (!P_CUTOFF)\n return 0;\n z_eq = 3600*(OMm-OMb)*hlittle*hlittle/0.15;\n return fudge*3.06e8 * (1.5/g_x) * sqrt((OMm-OMb)*hlittle*hlittle/0.15) * pow(M_WDM, -4) * pow(z_eq/3000.0, 1.5);\n}\n\n\n/* converts a non-linear overdensity, del, at z to a linear overdensity at z=0 */\ndouble deltolindel(float del, float z){\n float onepdel = 1.0+del;\n return ( 1.68647 - 1.35*pow(onepdel,-2/3.0) + 0.78785*pow(onepdel,-0.58661) - 1.12431*pow(onepdel,-0.5) )/dicke(z);\n}\n\n/* converts a linear overdensity, del, at z=0 to a non-linear overdensity at redshift z */\ndouble lindeltodel(float lindel, float z){\n float prev_lindelguess, delcrit, delguess;\n float lindelguess, delmin, delmax, epsilon = 1.0e-7;\n\n // set the critical density corresponding to virialization\n // this will be maximum allowed del\n delcrit = Deltac_nonlinear(z)*rho_critz(z)/(OMm*RHOcrit*pow(1+z, 3)) - 1;\n\n delmin = -1;\n delmax = 500;\n prev_lindelguess = -1e10;\n while (1){\n delguess = 0.5*(delmax+delmin);\n lindelguess = deltolindel(delguess, z);\n //fprintf(stderr, \"%e\\t%e\\n\", delmin, delmax);\n\t // fprintf(stderr, \"%e\\t%e\\t%e\\n\\n\", delguess, lindelguess, lindel);\n if ((fabs((lindelguess-lindel)/lindel) < epsilon ) ||\n\t(fabs(lindelguess-lindel) < epsilon ) ||\n\t(fabs(prev_lindelguess - lindelguess) < TINY ))// close enough, or resolution loop\n return delguess;\n\n if (lindelguess > lindel)\n delmax = delguess;\n else\n delmin = delguess;\n\n // check if we are above delcrit (see above)\n if (delmin > delcrit){\n // printf(\"exced max at lindel=%e\\n\", lindel);\n return delcrit;\n }\n\n prev_lindelguess = lindelguess;\n }\n}\n\n\n/* R in Mpc, M in Msun */\ndouble RtoM(double R){\n // set M according to M<->R conversion defined by the filter type in ../Parameter_files/COSMOLOGY.H\n if (FILTER == 0) //top hat M = (4/3) PI R^3\n return (4.0/3.0)*PI*pow(R,3)*(OMm*RHOcrit);\n else if (FILTER == 1) //gaussian: M = (2PI)^1.5 R^3\n return pow(2*PI, 1.5) * OMm*RHOcrit * pow(R, 3);\n else // filter not defined\n fprintf(stderr, \"No such filter = %i.\\nResults are bogus.\\n\", FILTER);\n return -1;\n}\n\n/* R in Mpc, M in Msun */\ndouble MtoR(double M){\n // set R according to M<->R conversion defined by the filter type in ../Parameter_files/COSMOLOGY.H\n if (FILTER == 0) //top hat M = (4/3) PI R^3\n return pow(3*M/(4*PI*OMm*RHOcrit), 1.0/3.0);\n else if (FILTER == 1) //gaussian: M = (2PI)^1.5 R^3\n return pow( M/(pow(2*PI, 1.5) * OMm * RHOcrit), 1.0/3.0 );\n else // filter not defined\n fprintf(stderr, \"No such filter = %i.\\nResults are bogus.\\n\", FILTER);\n return -1;\n}\n\n\n/* equation (5) from jenkis et al. (2001) */\ndouble f_jenkins(float del, double sigsq){\n if (del < 0){ fprintf(stderr, \"ERROR: In function f_jenkins del_o must be less than del_1 = del_crit/dicke(z)!\\nAborting...\\n\"); return 0; }\n\n // fprintf(stderr, \"%f\\t%f\\n\", del, sqrt(sigsq));\n return sqrt(2/PI) * del/sqrt(sigsq) * pow(E, -0.5*del*del/sigsq);\n}\n\n\nfloat get_R_c(){\n return R_CUTOFF;\n}\n\n/* sheth correction to delta crit */\ndouble sheth_delc(double del, double sig){\n return sqrt(SHETH_a)*del*(1 + SHETH_b*pow(sig*sig/(SHETH_a*del*del), SHETH_c));\n}\n\n\n/* dnbiasdM */\ndouble dnbiasdM(double M, float z, double M_o, float del_o){\n double sigsq, del, sig_one, sig_o;\n\n if ((M_o-M) < TINY){\n fprintf(stderr, \"WARNING: In function dnbiasdM: M must be less than M_o!\\nAborting...\\n\");\n return -1;\n }\n del = Deltac/dicke(z) - del_o;\n if (del < 0){ fprintf(stderr, \"ERROR: In function dnbiasdM: del_o must be less than del_1 = del_crit/dicke(z)!\\nAborting...\\n\"); return 0; }\n sig_o = sigma_z0(M_o);\n sig_one = sigma_z0(M);\n sigsq = sig_one*sig_one - sig_o*sig_o;\n return -(RHOcrit*OMm)/M /sqrt(2*PI) *del*pow(sigsq,-1.5)*pow(E, -0.5*del*del/sigsq)*dsigmasqdm_z0(M);\n}\n\n\n/*\n FUNCTION dNdM(z, M)\n Computes the Press_schechter mass function with Sheth-Torman correction for ellipsoidal collapse at\n redshift z, and dark matter halo mass M (in solar masses).\n\n The return value is the number density per unit mass of halos in the mass range M to M+dM in units of:\n comoving Mpc^-3 Msun^-1\n\n Reference: Sheth, Mo, Torman 2001\n*/\ndouble dNdM_st(double z, double M){\n double sigma, dsigmadm, nuhat, dicke_growth;\n\n dicke_growth = dicke(z);\n sigma = sigma_z0(M) * dicke_growth;\n dsigmadm = dsigmasqdm_z0(M) * dicke_growth*dicke_growth/(2.0*sigma);\n// sigma = 1.0 * dicke_growth;\n// dsigmadm = 1.0 * dicke_growth*dicke_growth/(2.0*sigma);\n nuhat = sqrt(SHETH_a) * Deltac / sigma;\n\n return (-OMm*RHOcrit/M) * (dsigmadm/sigma) * sqrt(2/PI)*SHETH_A * (1+ pow(nuhat, -2*SHETH_p)) * nuhat * pow(E, -nuhat*nuhat/2.0);\n}\n\n\n\n/*\n FUNCTION dNdM(z, M)\n Computes the Press_schechter mass function at\n redshift z, and dark matter halo mass M (in solar masses).\n\n The return value is the number density per unit mass of halos in the mass range M to M+dM in units of:\n comoving Mpc^-3 Msun^-1\n\n Reference: Padmanabhan, pg. 214\n*/\ndouble dNdM(double z, double M){\n double sigma, dsigmadm, dicke_growth;\n\n dicke_growth = dicke(z);\n sigma = sigma_z0(M) * dicke_growth;\n dsigmadm = dsigmasqdm_z0(M) * (dicke_growth*dicke_growth/(2*sigma));\n\n return (-OMm*RHOcrit/M) * sqrt(2/PI) * (Deltac/(sigma*sigma)) * dsigmadm * pow(E, -(Deltac*Deltac)/(2*sigma*sigma));\n}\n\n\n/*\n FUNCTION FgtrM_st(z, M)\n Computes the fraction of mass contained in haloes with mass > M at redshift z\n Uses Sheth-Torman correction\n*/\ndouble dFdlnM_st (double lnM, void *params){\n double z = *(double *)params;\n double M = exp(lnM);\n return dNdM_st(z, M) * M * M;\n}\ndouble FgtrM_st(double z, double M){\n\n// printf(\"Calculating ST coll fraction: M=%.2le, z=%.2le \\n\",M,z);\n\n\n double result, error, lower_limit, upper_limit;\n gsl_function F;\n// double rel_tol = 0.001; //<- relative tolerance\n double rel_tol = 0.01; //<- relative tolerance\n gsl_integration_workspace * w\n = gsl_integration_workspace_alloc (1000);\n\n F.function = &dFdlnM_st;\n F.params = &z;\n lower_limit = log(M);\n upper_limit = log(FMAX(1e16, M*100));\n\n\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error);\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS51, w, &result, &error);\n gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS41, w, &result, &error);\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS31, w, &result, &error);\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS21, w, &result, &error);\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS15, w, &result, &error);\n gsl_integration_workspace_free (w);\n\n return result / (OMm*RHOcrit);\n}\n\n\n/*\n FUNCTION FgtrM(z, M)\n Computes the fraction of mass contained in haloes with mass > M at redshift z\n*/\ndouble FgtrM(double z, double M){\n double del, sig;\n\n del = Deltac/dicke(z); //regular spherical collapse delta\n sig = sigma_z0(M);\n\n return splined_erfc(del / (sqrt(2)*sig));\n}\n\n\n/*\n calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias\n */\ndouble FgtrM_bias(double z, double M, double del_bias, double sig_bias){\n double del, sig, sigsmallR;\n\n sigsmallR = sigma_z0(M);\n\n if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo!\n// fprintf(stderr, \"FgtrM_bias: Biased region is smaller than halo!\\nResult is bogus.\\n\");\n// return 0;\n return 0.000001;\n }\n\n del = Deltac/dicke(z) - del_bias;\n sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias);\n\n return splined_erfc(del / (sqrt(2)*sig));\n}\n\n\n/* Uses sigma parameters instead of Mass for scale */\ndouble sigmaparam_FgtrM_bias(float z, float sigsmallR, float del_bias, float sig_bias){\n double del, sig;\n\n if (!(sig_bias < sigsmallR)){ // biased region is smaller that halo!\n// fprintf(stderr, \"local_FgtrM_bias: Biased region is smaller than halo!\\nResult is bogus.\\n\");\n// return 0;\n return 0.000001;\n }\n\n del = Deltac/dicke(z) - del_bias;\n sig = sqrt(sigsmallR*sigsmallR - sig_bias*sig_bias);\n\n return splined_erfc(del / (sqrt(2)*sig));\n}\n\n\n/*\n Calculates the fraction of mass contained in haloes with mass > M at redshift z, in regions with a linear overdensity of del_bias, and standard deviation sig_bias.\n This version uses the hybrid perscription of Barkana & Loeb 2004 (specifically the separate\n integral version of eq. 2 in Barkana & Loeb 2008)\n */\ndouble FgtrM_bias_BL08(double z, double M, double del_bias, double sig_bias){\n return FgtrM_st(z, M) / FgtrM(z, M) * FgtrM_bias(z, M, del_bias, sig_bias);\n}\n\n\n/*\n FUNCTION dicke(z)\n Computes the dicke growth function at redshift z, i.e. the z dependance part of sigma\n\n References: Peebles, \"Large-Scale...\", pg.53 (eq. 11.16). Includes omega<=1\n Nonzero Lambda case from Liddle et al, astro-ph/9512102, eqs. 6-8.\n and quintessence case from Wang et al, astro-ph/9804015\n\n Normalized to dicke(z=0)=1\n*/\ndouble dicke(double z){\n double omegaM_z, dick_z, dick_0, x, x_0;\n double tiny = 1e-4;\n\n if (fabs(OMm-1.0) < tiny){ //OMm = 1 (Einstein de-Sitter)\n return 1.0/(1.0+z);\n }\n else if ( (OMl > (-tiny)) && (fabs(OMl+OMm+OMr-1.0) < 0.01) && (fabs(wl+1.0) < tiny) ){\n //this is a flat, cosmological CONSTANT universe, with only lambda, matter and radiation\n //it is taken from liddle et al.\n omegaM_z = OMm*pow(1+z,3) / ( OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4) );\n dick_z = 2.5*omegaM_z / ( 1.0/70.0 + omegaM_z*(209-omegaM_z)/140.0 + pow(omegaM_z, 4.0/7.0) );\n dick_0 = 2.5*OMm / ( 1.0/70.0 + OMm*(209-OMm)/140.0 + pow(OMm, 4.0/7.0) );\n return dick_z / (dick_0 * (1.0+z));\n }\n else if ( (OMtot < (1+tiny)) && (fabs(OMl) < tiny) ){ //open, zero lambda case (peebles, pg. 53)\n x_0 = 1.0/(OMm+0.0) - 1.0;\n dick_0 = 1 + 3.0/x_0 + 3*log(sqrt(1+x_0)-sqrt(x_0))*sqrt(1+x_0)/pow(x_0,1.5);\n x = fabs(1.0/(OMm+0.0) - 1.0) / (1+z);\n dick_z = 1 + 3.0/x + 3*log(sqrt(1+x)-sqrt(x))*sqrt(1+x)/pow(x,1.5);\n return dick_z/dick_0;\n }\n else if ( (OMl > (-tiny)) && (fabs(OMtot-1.0) < tiny) && (fabs(wl+1) > tiny) ){\n fprintf(stderr, \"IN WANG\\n\");\n return -1;\n }\n\n fprintf(stderr, \"No growth function!!! Output will be fucked up.\");\n return -1;\n}\n\n\n/* redshift derivative of the growth function at z */\ndouble ddicke_dz(double z){\n float dz = 1e-10;\n double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz;\n\n return (dicke(z+dz)-dicke(z))/dz;\n}\n\n/* Time derivative of the growth function at z */\ndouble ddickedt(double z){\n float dz = 1e-10;\n double omegaM_z, ddickdz, dick_0, x, x_0, domegaMdz;\n double tiny = 1e-4;\n\n return (dicke(z+dz)-dicke(z))/dz/dtdz(z); // lazy non-analytic form getting\n\n if (fabs(OMm-1.0) < tiny){ //OMm = 1 (Einstein de-Sitter)\n return -pow(1+z,-2)/dtdz(z);\n }\n else if ( (OMl > (-tiny)) && (fabs(OMl+OMm+OMr-1.0) < 0.01) && (fabs(wl+1.0) < tiny) ){\n //this is a flat, cosmological CONSTANT universe, with only lambda, matter and radiation\n //it is taken from liddle et al.\n omegaM_z = OMm*pow(1+z,3) / ( OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4) );\n domegaMdz = omegaM_z*3/(1+z) - OMm*pow(1+z,3)*pow(OMl + OMm*pow(1+z,3) + OMr*pow(1+z,4), -2) * (3*OMm*(1+z)*(1+z) + 4*OMr*pow(1+z,3));\n dick_0 = OMm / ( 1.0/70.0 + OMm*(209-OMm)/140.0 + pow(OMm, 4.0/7.0) );\n\n ddickdz = (domegaMdz/(1+z)) * (1.0/70.0*pow(omegaM_z,-2) + 1.0/140.0 + 3.0/7.0*pow(omegaM_z, -10.0/3.0)) * pow(1.0/70.0/omegaM_z + (209.0-omegaM_z)/140.0 + pow(omegaM_z, -3.0/7.0) , -2);\n ddickdz -= pow(1+z,-2)/(1.0/70.0/omegaM_z + (209.0-omegaM_z)/140.0 + pow(omegaM_z, -3.0/7.0));\n\n return ddickdz / dick_0 / dtdz(z);\n }\n\n fprintf(stderr, \"No growth function!!! Output will be fucked up.\");\n return -1;\n}\n\n\n\n/*\n JBM:\n this function reads the z=0 matter (CDM+baryons) transfer function from CLASS\n\tflag = 0 to initialize interpolator, flag = -1 to free memory, flag = else to interpolate.\n\tsimilar to built-in function \"double T_RECFAST(float z, int flag)\"\n*/\n\ndouble TFm_CLASS(double k, int flag)\n{\n static double kclass[CLASS_LENGTH], Tmclass[CLASS_LENGTH];\n static gsl_interp_accel *acc_class;\n static gsl_spline *spline_class;\n float trash, currk, currTm;\n double ans;\n int i;\n FILE *F;\n\n\n\n if (flag == 0) {// Initialize vectors and read file\n if ( !(F=fopen(CLASS_FILENAME, \"r\")) ){\n fprintf(stderr, \"TFm_CLASS: Unable to open file: %s for reading\\nAborting\\n\", CLASS_FILENAME);\n return -1;\n }\n\n// for (i=(CLASS_LENGTH-1);i>=0;i--) {\n for (i=0;i0){\n \tprintf(\"WARNING, Tk table not ordered \\n\");\n \tprintf(\"k=%.1le kprev=%.1le \\n\\n\",kclass[i],kclass[i-1]);\n }\n }\n fclose(F);\n\n // Set up spline table\n acc_class = gsl_interp_accel_alloc ();\n spline_class = gsl_spline_alloc (gsl_interp_cspline, CLASS_LENGTH);\n gsl_spline_init(spline_class, kclass, Tmclass, CLASS_LENGTH);\n\n return 0;\n }\n\n if (flag == -1) {\n gsl_spline_free (spline_class);\n gsl_interp_accel_free(acc_class);\n return 0;\n }\n\n\n\n if (k > kclass[CLASS_LENGTH-1]) { // k>kmax\n fprintf(stderr, \"Called TFm_CLASS with k=%f, larger than kmax!\\n\", k);\n return (Tmclass[CLASS_LENGTH]/kclass[CLASS_LENGTH-1]/kclass[CLASS_LENGTH-1]);\n //JBM:we just set it to the last value, since sometimes it wants large k for R<=0;i--) {\n for (i=0;i0){\n \tprintf(\"WARNING, T_vcb table not ordered \\n\");\n }\n }\n fclose(F);\n\n // Set up spline table\n acc_vcb = gsl_interp_accel_alloc ();\n spline_vcb = gsl_spline_alloc (gsl_interp_cspline, CLASS_LENGTH);\n gsl_spline_init(spline_vcb, kclass_vcb, Tvclass_vcb, CLASS_LENGTH);\n\n return 0;\n }\n\n if (flag == -1) {\n gsl_spline_free (spline_vcb);\n gsl_interp_accel_free(acc_vcb);\n return 0;\n }\n\n if (k > kclass_vcb[CLASS_LENGTH-1]) { // k>kmax\n fprintf(stderr, \"Called TFvcb_CLASS with k=%f, bailing out!\\n\", k);\n return 0;\n }\n else { // Do spline\n ans = gsl_spline_eval (spline_vcb, k, acc_vcb);\n// printf(\"k=%.3le, T=%.1le \\n\", k, ans);\n }\n\n return ans/k/k;\n//JBM:we have to divide by k^2 to agree with the old-fashioned convention.\n\n}\n\n\n/*\n FUNCTION sigma_z0(M)\n Returns the standard deviation of the normalized, density excess (delta(x)) field,\n smoothed on the comoving scale of M (see filter definitions for M<->R conversion).\n The sigma is evaluated at z=0, with the time evolution contained in the dicke(z) factor,\n i.e. sigma(M,z) = sigma_z0(m) * dicke(z)\n\n normalized so that sigma_z0(M->8/h Mpc) = SIGMA8 in ../Parameter_files/COSMOLOGY.H\n\n NOTE: volume is normalized to = 1, so this is equvalent to the mass standard deviation\n\n M is in solar masses\n\n References: Padmanabhan, pg. 210, eq. 5.107\n*/\ndouble dsigma_dk(double k, void *params){\n double p, w, T, gamma, q, aa, bb, cc, kR;\n\n // get the power spectrum.. choice of 5:\n if (POWER_SPECTRUM == 0){ // Eisenstein & Hu\n T = TFmdm(k);\n // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function\n if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v);\n p = pow(k, POWER_INDEX) * T * T;\n }\n else if (POWER_SPECTRUM == 1){ // BBKS\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n q = k / (hlittle*gamma);\n T = (log(1.0+2.34*q)/(2.34*q)) *\n pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25);\n p = pow(k, POWER_INDEX) * T * T;\n }\n else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992)\n gamma = 0.25;\n aa = 6.4/(hlittle*gamma);\n bb = 3.0/(hlittle*gamma);\n cc = 1.7/(hlittle*gamma);\n p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 );\n }\n else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n aa = 8.0 / (hlittle*gamma);\n bb = 4.7 / pow(hlittle*gamma, 2);\n p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2);\n }\n else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n aa = 1.7/(hlittle*gamma);\n bb = 9.0/pow(hlittle*gamma, 1.5);\n cc = 1.0/pow(hlittle*gamma, 2);\n p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2);\n }\n else if (POWER_SPECTRUM == 5){ // JBM: CLASS\n\n T = TFm_CLASS(k, 1); //read from z=0 output of CLASS\n//JBM: flag = 1 here always, since now we have to have initialized the interpolator for CLASS\n \tp = pow(k, POWER_INDEX) * T * T;\n }\n else{\n fprintf(stderr, \"No such power spectrum defined: %i\\nOutput is bogus.\\n\", POWER_SPECTRUM);\n p = 0;\n }\n\n\n // now get the value of the window function\n // NOTE: only use top hat for SIGMA8 normalization\n kR = k*R;\n if ( (FILTER == 0) || (sigma_norm < 0) ){ // top hat\n if ( (kR) < 1.0e-4 ){ w = 1.0;} // w converges to 1 as (kR) -> 0\n else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));}\n }\n else if (FILTER == 1){ // gaussian of width 1/R\n w = pow(E, -kR*kR/2.0);\n }\n else {\n fprintf(stderr, \"No such filter: %i\\nOutput is bogus.\\n\", FILTER);\n w=0;\n }\n\n return k*k*p*w*w;\n}\n\n\n\n\ndouble sigma_z0(double M){\n double result, error, lower_limit, upper_limit;\n gsl_function F;\n//OLD: double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance\n double rel_tol = 0.01; //<- relative tolerance\n gsl_integration_workspace * w\n = gsl_integration_workspace_alloc (1000);\n double kstart, kend;\n\n R = MtoR(M);\n\n// printf(\"sigmaz0 -> R=%.2le, from M=%.2le \\n\",R, M);\n\n // now lets do the integral for sigma and scale it with sigma_norm\n kstart = FMAX(1.0e-99/R,KBOT);\n //JBM:we stablish a maximum k of 10^3 Mpc-1, since the CLASS transfer function has a max!\n kend = FMIN(350.0/R, KTOP);\n lower_limit = kstart;//log(kstart);\n upper_limit = kend;//log(kend);\n\n\n F.function = &dsigma_dk;\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error);\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS41, w, &result, &error);\n gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS15, w, &result, &error);\n gsl_integration_workspace_free (w);\n\n return sigma_norm * sqrt(result);\n}\n\n\n\n\n\n/*\n Returns the value of the linear power spectrum DENSITY (i.e. <|delta_k|^2>/V)\n at a given k mode linearly extrapolated to z=0\n*/\ndouble power_in_k(double k){\n double p, T, gamma, q, aa, bb, cc;\n\n\n // get the power spectrum.. choice of 5:\n if (POWER_SPECTRUM == 0){ // Eisenstein & Hu\n T = TFmdm(k);\n // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function\n if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v);\n p = pow(k, POWER_INDEX) * T * T;\n //p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05\n }\n else if (POWER_SPECTRUM == 1){ // BBKS\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n q = k / (hlittle*gamma);\n T = (log(1.0+2.34*q)/(2.34*q)) *\n pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25);\n p = pow(k, POWER_INDEX) * T * T;\n }\n else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992)\n gamma = 0.25;\n aa = 6.4/(hlittle*gamma);\n bb = 3.0/(hlittle*gamma);\n cc = 1.7/(hlittle*gamma);\n p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 );\n }\n else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n aa = 8.0 / (hlittle*gamma);\n bb = 4.7 / pow(hlittle*gamma, 2);\n p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2);\n }\n else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n aa = 1.7/(hlittle*gamma);\n bb = 9.0/pow(hlittle*gamma, 1.5);\n cc = 1.0/pow(hlittle*gamma, 2);\n p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + bb*pow(k, 1.5) + cc*k*k, 2);\n }\n else if (POWER_SPECTRUM == 5){ // JBM: CLASS\n T = TFm_CLASS(k, 1); //read from z=0 output of CLASS\n//JBM: flag = 1 here always, since now we have to have initialized the interpolator for CLASS\n \tp = pow(k, POWER_INDEX) * T * T;\n }\n else{\n fprintf(stderr, \"No such power spectrum defined: %i\\nOutput is bogus.\\n\", POWER_SPECTRUM);\n p = 0;\n }\n\n return p*TWOPI*PI*sigma_norm*sigma_norm;\n}\n\n\n/*\n JBM: Returns the value of the linear power spectrum of the DM-b relative velocity\n at kinematic decoupling (which we set at zkin=1010)\n*/\ndouble power_in_vcb(double k){\n double p, T, gamma, q, aa, bb, cc;\n\n\n //only works if using CLASS\n if (POWER_SPECTRUM == 5){ // CLASS\n T = TFvcb_CLASS(k, 1.0); //read from CLASS file. flag=1 since we have initialized before\n\tp = pow(k, POWER_INDEX) * T * T;\n }\n else{\n fprintf(stderr, \"Cannot get P_cb unless using CLASS: %i\\n Set USE_RELATIVE_VELOCITIES 0 or use CLASS.\\n\", POWER_SPECTRUM);\n p = 0;\n }\n\n\n return p*TWOPI*PI*sigma_norm*sigma_norm;\n}\n\n\n/*\n FUNCTION dsigmasqdm_z0(M)\n returns d/dm (sigma^2) (see function sigma), in units of Msun^-1\n*/\ndouble dsigmasq_dm(double k, void *params){\n double p, w, T, gamma, q, aa, bb, cc, dwdr, drdm, kR;\n\n // get the power spectrum.. choice of 5:\n if (POWER_SPECTRUM == 0){ // Eisenstein & Hu ApJ, 1999, 511, 5\n T = TFmdm(k);\n // check if we should cuttoff power spectrum according to Bode et al. 2000 transfer function\n if (P_CUTOFF) T *= pow(1 + pow(BODE_e*k*R_CUTOFF, 2*BODE_v), -BODE_n/BODE_v);\n p = pow(k, POWER_INDEX) * T * T;\n //p = pow(k, POWER_INDEX - 0.05*log(k/0.05)) * T * T; //running, alpha=0.05\n }\n else if (POWER_SPECTRUM == 1){ // BBKS\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n q = k / (hlittle*gamma);\n T = (log(1.0+2.34*q)/(2.34*q)) *\n pow( 1.0+3.89*q + pow(16.1*q, 2) + pow( 5.46*q, 3) + pow(6.71*q, 4), -0.25);\n p = pow(k, POWER_INDEX) * T * T;\n }\n else if (POWER_SPECTRUM == 2){ // Efstathiou,G., Bond,J.R., and White,S.D.M., MNRAS,258,1P (1992)\n gamma = 0.25;\n aa = 6.4/(hlittle*gamma);\n bb = 3.0/(hlittle*gamma);\n cc = 1.7/(hlittle*gamma);\n p = pow(k, POWER_INDEX) / pow( 1+pow( aa*k + pow(bb*k, 1.5) + pow(cc*k,2), 1.13), 2.0/1.13 );\n }\n else if (POWER_SPECTRUM == 3){ // Peebles, pg. 626\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n aa = 8.0 / (hlittle*gamma);\n bb = 4.7 / (hlittle*gamma);\n p = pow(k, POWER_INDEX) / pow(1 + aa*k + bb*k*k, 2);\n }\n else if (POWER_SPECTRUM == 4){ // White, SDM and Frenk, CS, 1991, 379, 52\n gamma = OMm * hlittle * pow(E, -OMb - OMb/OMm);\n aa = 1.7/(hlittle*gamma);\n bb = 9.0/pow(hlittle*gamma, 1.5);\n cc = 1.0/pow(hlittle*gamma, 2);\n p = pow(k, POWER_INDEX) * 19400.0 / pow(1 + aa*k + pow(bb*k, 1.5) + cc*k*k, 2);\n }\n\telse if (POWER_SPECTRUM == 5){ // JBM: CLASS\n\n T = TFm_CLASS(k, 1); //read from z=0 output of CLASS\n\t//JBM: flag = 1 here always, since now we have to have initialized the interpolator for CLASS\n\tp = pow(k, POWER_INDEX) * T * T;\n\t}\n else{\n fprintf(stderr, \"No such power spectrum defined: %i\\nOutput is bogus.\\n\", POWER_SPECTRUM);\n p = 0;\n }\n\n\n // now get the value of the window function\n kR = k * R;\n if (FILTER == 0){ // top hat\n if ( (kR) < 1.0e-4 ){ w = 1.0; }// w converges to 1 as (kR) -> 0\n else { w = 3.0 * (sin(kR)/pow(kR, 3) - cos(kR)/pow(kR, 2));}\n\n // now do d(w^2)/dm = 2 w dw/dr dr/dm\n if ( (kR) < 1.0e-10 ){ dwdr = 0;}\n else{ dwdr = 9*cos(kR)*k/pow(kR,3) + 3*sin(kR)*(1 - 3/(kR*kR))/(kR*R);}\n\t //3*k*( 3*cos(kR)/pow(kR,3) + sin(kR)*(-3*pow(kR, -4) + 1/(kR*kR)) );}\n // dwdr = -1e8 * k / (R*1e3);\n drdm = 1.0 / (4.0*PI * OMm*RHOcrit * R*R);\n }\n else if (FILTER == 1){ // gaussian of width 1/R\n w = pow(E, -kR*kR/2.0);\n dwdr = - k*kR * w;\n drdm = 1.0 / (pow(2*PI, 1.5) * OMm*RHOcrit * 3*R*R);\n }\n else {\n fprintf(stderr, \"No such filter: %i\\nOutput is bogus.\\n\", FILTER);\n w=0;\n }\n\n // printf(\"%e\\t%e\\t%e\\t%e\\t%e\\t%e\\t%e\\n\", k, R, p, w, dwdr, drdm, dsigmadk[1]);\n // printf(\"k=%.1e and R=%.1e -> P=%.1e W(KR)=%.1e \\n\", k, R, p, w);\n return k*k*p*2*w*dwdr*drdm * d2fact;\n}\n\ndouble dsigmasqdm_z0(double M){\n double result, error, lower_limit, upper_limit;\n gsl_function F;\n//OLD: double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance\n double rel_tol = 0.01; //<- relative tolerance\n gsl_integration_workspace * w\n = gsl_integration_workspace_alloc (3000);\n double kstart, kend;\n\n R = MtoR(M);\n\n // now lets do the integral for sigma and scale it with sigma_norm\n kstart = FMAX(1.0e-99/R,KBOT);\n kend = FMIN(350.0/R, KTOP);\n lower_limit = kstart;//log(kstart);\n upper_limit = kend;//log(kend);\n //OLD: d2fact = M*10000/sigma_z0(M);\n d2fact = 1.0;\n //JBM:This is an irrelevant scaling to make te integral converge that was in 21cmmc originally, but it can be set to one and it works better.\n\n //printf(\"dsigma/dm -> R=%.2le, from M=%.2le \\n\",R, M);\n\n long unsigned int trash;\n\n\n F.function = &dsigmasq_dm;\n// gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS61, w, &result, &error);\n//OLD: gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,1000, GSL_INTEG_GAUSS15, w, &result, &error);\n gsl_integration_qng (&F, lower_limit, upper_limit, 3000, rel_tol, &result, &error, &trash);\n gsl_integration_workspace_free (w);\n\n\n return sigma_norm * sigma_norm * result /d2fact;\n}\n\n\n\n/*\n FUNCTION TFmdm is the power spectrum transfer function from Eisenstein & Hu ApJ, 1999, 511, 5\n*/\ndouble TFmdm(double k){\n double q, gamma_eff, q_eff, TF_m, q_nu;\n\n q = k*pow(theta_cmb,2)/omhh;\n gamma_eff=sqrt(alpha_nu) + (1.0-sqrt(alpha_nu))/(1.0+pow(0.43*k*sound_horizon, 4));\n q_eff = q/gamma_eff;\n TF_m= log(E+1.84*beta_c*sqrt(alpha_nu)*q_eff);\n TF_m /= TF_m + pow(q_eff,2) * (14.4 + 325.0/(1.0+60.5*pow(q_eff,1.11)));\n q_nu = 3.92*q/sqrt(f_nu/N_nu);\n TF_m *= 1.0 + (1.2*pow(f_nu,0.64)*pow(N_nu,0.3+0.6*f_nu)) /\n (pow(q_nu,-1.6)+pow(q_nu,0.8));\n\n // printf(\"%f %e %f %f %f %f\\n\",omhh,f_nu,f_baryon,N_nu,y_d,alpha_nu);\n // printf(\"%f %f %f %f\\n\", beta_c,sound_horizon,theta_cmb,z_equality);\n //printf(\"%f %e %f %f %f\\n\\n\",q, k, gamma_eff, q_nu, TF_m);\n\n\n return TF_m;\n}\n\n\n\n\n\n\nvoid TFset_parameters(){\n double z_drag, R_drag, R_equality, p_c, p_cb, f_c, f_cb, f_nub, k_equality;\n\n z_equality = 25000*omhh*pow(theta_cmb, -4) - 1.0;\n k_equality = 0.0746*omhh/(theta_cmb*theta_cmb);\n\n z_drag = 0.313*pow(omhh,-0.419) * (1 + 0.607*pow(omhh, 0.674));\n z_drag = 1 + z_drag*pow(OMb*hlittle*hlittle, 0.238*pow(omhh, 0.223));\n z_drag *= 1291 * pow(omhh, 0.251) / (1 + 0.659*pow(omhh, 0.828));\n\n y_d = (1 + z_equality) / (1.0 + z_drag);\n\n R_drag = 31.5 * OMb*hlittle*hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_drag);\n R_equality = 31.5 * OMb*hlittle*hlittle * pow(theta_cmb, -4) * 1000 / (1.0 + z_equality);\n\n sound_horizon = 2.0/3.0/k_equality * sqrt(6.0/R_equality) *\n log( (sqrt(1+R_drag) + sqrt(R_drag+R_equality)) / (1.0 + sqrt(R_equality)) );\n\n p_c = -(5 - sqrt(1 + 24*(1 - f_nu-f_baryon)))/4.0;\n p_cb = -(5 - sqrt(1 + 24*(1 - f_nu)))/4.0;\n f_c = 1 - f_nu - f_baryon;\n f_cb = 1 - f_nu;\n f_nub = f_nu+f_baryon;\n\n alpha_nu = (f_c/f_cb) * (2*(p_c+p_cb)+5)/(4*p_cb+5.0);\n alpha_nu *= 1 - 0.553*f_nub+0.126*pow(f_nub,3);\n alpha_nu /= 1-0.193*sqrt(f_nu)+0.169*f_nu;\n alpha_nu *= pow(1+y_d, p_c-p_cb);\n alpha_nu *= 1+ (p_cb-p_c)/2.0 * (1.0+1.0/(4.0*p_c+3.0)/(4.0*p_cb+7.0))/(1.0+y_d);\n beta_c = 1.0/(1.0-0.949*f_nub);\n}\n\n\n\n\ndouble init_ps(){\n double result, error, lower_limit, upper_limit;\n gsl_function F;\n// double rel_tol = FRACT_FLOAT_ERR*10; //<- relative tolerance\n double rel_tol = 0.01; //<- relative tolerance\n gsl_integration_workspace * w\n = gsl_integration_workspace_alloc (1000);\n double kstart, kend;\n int i;\n double x;\n\n //JBM: we start the interpolator if using CLASS:\n\tdouble temp_var;\n\tif (POWER_SPECTRUM == 5){\n\t\ttemp_var = TFm_CLASS(1.0, 0);\n\t\ttemp_var = TFvcb_CLASS(1.0, 0);\n\t}\n\n // Set cuttoff scale for WDM (eq. 4 in Barkana et al. 2001) in comoving Mpc\n R_CUTOFF = 0.201*pow((OMm-OMb)*hlittle*hlittle/0.15, 0.15)*pow(g_x/1.5, -0.29)*pow(M_WDM, -1.15);\n\n// fprintf(stderr, \"For M_DM = %.2e keV, R_CUTOFF is: %.2e comoving Mpc\\n\", M_WDM, R_CUTOFF);\n if (!P_CUTOFF)\n// fprintf(stderr, \"But you have selected CDM, so this is ignored\\n\");\n\n omhh = OMm*hlittle*hlittle;\n theta_cmb = T_cmb / 2.7;\n\n // Translate Parameters into forms GLOBALVARIABLES form\n f_nu = OMn/OMm;\n f_baryon = OMb/OMm;\n if (f_nu < TINY) f_nu = 1e-10;\n if (f_baryon < TINY) f_baryon = 1e-10;\n\n\n TFset_parameters();\n\n sigma_norm = -1;\n\n R = 8.0/hlittle;\n kstart = FMAX(1.0e-99/R, KBOT);\n kend = FMIN(350.0/R, KTOP);\n\n lower_limit = kstart;//log(kstart);\n upper_limit = kend;//log(kend);\n\n F.function = &dsigma_dk;\n\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 sigma_norm = SIGMA8/sqrt(result); //takes care of volume factor\n\n\n /* initialize the lookup table for erfc */\n /*\n for (i=0; i<=ERFC_NPTS; i++){\n erfc_params[i] = i*ERFC_PARAM_DELTA;\n log_erfc_table[i] = log(erfcc(erfc_params[i]));\n }\n // Set up spline table\n erfc_acc = gsl_interp_accel_alloc ();\n erfc_spline = gsl_spline_alloc (gsl_interp_cspline, ERFC_NPTS);\n gsl_spline_init(erfc_spline, erfc_params, log_erfc_table, ERFC_NPTS);\n */\n\n return R_CUTOFF;\n}\n\nvoid free_ps(){\n /* gsl_spline_free (erfc_spline);\n gsl_interp_accel_free(erfc_acc);\n */\n\n\tdouble temp_var;\n\t//JBM: we free the interpolator if using CLASS:\n\t\tif (POWER_SPECTRUM == 5){\n\t\t\ttemp_var = TFm_CLASS(1.0, -1);\n\t\t\ttemp_var = TFvcb_CLASS(1.0, -1);\n\t\t}\n\n return;\n}\n\ndouble splined_erfc(double x){\n if (x < 0){\n // fprintf(stderr, \"WARNING: Negative value %e passed to splined_erfc. Returning 1\\n\", x);\n return 1;\n }\n return erfcc(x); // the interpolation below doesn't seem to be stable in Ts.c\n if (x > ERFC_PARAM_DELTA*(ERFC_NPTS-1))\n return erfcc(x);\n else\n return exp(gsl_spline_eval(erfc_spline, x, erfc_acc));\n}\n\nfloat FgtrConditionalM_second(float z, float M1, float M2, float MFeedback, float alpha, float delta1, float delta2) {\n\n return exp(M1)*pow(exp(M1)/MFeedback,alpha)*dNdM_conditional_second(z,M1,M2,delta1,delta2)/sqrt(2.*PI);\n}\n\nfloat dNdM_conditional_second(float z, float M1, float M2, float delta1, float delta2){\n\n float sigma1, sigma2, dsigmadm, dicke_growth,dsigma_val;\n\n M1 = exp(M1);\n M2 = exp(M2);\n\n dicke_growth = dicke(z);\n\n splint(Mass_Spline-1,Sigma_Spline-1,second_derivs_sigma-1,(int)NMass,M1,&(sigma1));\n splint(Mass_Spline-1,Sigma_Spline-1,second_derivs_sigma-1,(int)NMass,M2,&(sigma2));\n\n sigma1 = sigma1*sigma1;\n sigma2 = sigma2*sigma2;\n\n splint(Mass_Spline-1,dSigmadm_Spline-1,second_derivs_dsigma-1,(int)NMass,M1,&(dsigma_val));\n\n dsigmadm = -pow(10.,dsigma_val)/(2.0*sigma1); // This is actually sigma1^{2} as calculated above, however, it should just be sigma1. It cancels with the same factor below. Why I have decided to write it like that I don't know!\n\n if((sigma1 > sigma2)) {\n\n return -(( delta1 - delta2 )/dicke_growth)*( 2.*sigma1*dsigmadm )*( exp( - ( delta1 - delta2 )*( delta1 - delta2 )/( 2.*dicke_growth*dicke_growth*( sigma1 - sigma2 ) ) ) )/(pow( sigma1 - sigma2, 1.5));\n }\n else if(sigma1==sigma2) {\n\n return -(( delta1 - delta2 )/dicke_growth)*( 2.*sigma1*dsigmadm )*( exp( - ( delta1 - delta2 )*( delta1 - delta2 )/( 2.*dicke_growth*dicke_growth*( 1.e-6 ) ) ) )/(pow( 1.e-6, 1.5));\n\n }\n else {\n return 0.;\n }\n}\n\nvoid gauleg(float x1, float x2, float x[], float w[], int n)\n//Given the lower and upper limits of integration x1 and x2, and given n, this routine returns arrays x[1..n] and w[1..n] of length n,\n//containing the abscissas and weights of the Gauss- Legendre n-point quadrature formula.\n{\n\n int m,j,i;\n double z1,z,xm,xl,pp,p3,p2,p1;\n\n m=(n+1)/2;\n xm=0.5*(x2+x1);\n xl=0.5*(x2-x1);\n for (i=1;i<=m;i++) {\n //High precision is a good idea for this routine.\n //The roots are symmetric in the interval, so we only have to find half of them.\n //Loop over the desired roots.\n\n z=cos(3.141592654*(i-0.25)/(n+0.5));\n\n //Starting with the above approximation to the ith root, we enter the main loop of refinement by Newton’s method.\n do {\n p1=1.0;\n p2=0.0;\n for (j=1;j<=n;j++) {\n //Loop up the recurrence relation to get the Legendre polynomial evaluated at z.\n p3=p2;\n p2=p1;\n p1=((2.0*j-1.0)*z*p2-(j-1.0)*p3)/j;\n }\n //p1 is now the desired Legendre polynomial. We next compute pp, its derivative, by a standard relation involving also p2,\n //the polynomial of one lower order.\n pp=n*(z*p1-p2)/(z*z-1.0);\n z1=z;\n z=z1-p1/pp;\n } while (fabs(z-z1) > EPS2);\n x[i]=xm-xl*z;\n x[n+1-i]=xm+xl*z;\n w[i]=2.0*xl/((1.0-z*z)*pp*pp);\n w[n+1-i]=w[i];\n }\n}\n\nvoid nrerror(char error_text[])\n{\n fprintf(stderr,\"Numerical Recipes run-time error...\\n\");\n fprintf(stderr,\"%s\\n\",error_text);\n fprintf(stderr,\"...now exiting to system...\\n\");\n exit(1);\n}\n\nfloat *vector(long nl, long nh)\n/* allocate a float vector with subscript range v[nl..nh] */\n{\n float *v;\n v = (float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));\n if(!v) nrerror(\"allocation failure in vector()\");\n return v - nl + NR_END;\n}\n\nvoid free_vector(float *v, long nl, long nh)\n/* free a float vector allocated with vector() */\n{\n free((FREE_ARG) (v+nl-NR_END));\n}\n\nvoid spline(float x[], float y[], int n, float yp1, float ypn, float y2[])\n/*Given arrays x[1..n] and y[1..n] containing a tabulated function, i.e., yi = f(xi), with\n x1 0.99e30) // The lower boundary condition is set either to be \"natural\"\n y2[1]=u[1]=0.0;\n else { // or else to have a specified first derivative.\n y2[1] = -0.5;\n u[1]=(3.0/(x[2]-x[1]))*((y[2]-y[1])/(x[2]-x[1])-yp1);\n }\n for (i=2;i<=n-1;i++) { //This is the decomposition loop of the tridiagonal algorithm.\n sig=(x[i]-x[i-1])/(x[i+1]-x[i-1]); //y2 and u are used for temporary\n na = 1;\n nb = 1;\n check = 0;\n while(((float)(x[i+na*1]-x[i-nb*1])==(float)0.0)) {\n check = check + 1;\n if(check%2==0) {\n na = na + 1;\n }\n else {\n nb = nb + 1;\n }\n sig=(x[i]-x[i-1])/(x[i+na*1]-x[i-nb*1]);\n }\n p=sig*y2[i-1]+2.0; //storage of the decomposed\n y2[i]=(sig-1.0)/p; // factors.\n u[i]=(y[i+1]-y[i])/(x[i+1]-x[i]) - (y[i]-y[i-1])/(x[i]-x[i-1]);\n u[i]=(6.0*u[i]/(x[i+1]-x[i-1])-sig*u[i-1])/p;\n\n if(((float)(x[i+1]-x[i])==(float)0.0) || ((float)(x[i]-x[i-1])==(float)0.0)) {\n na = 0;\n nb = 0;\n check = 0;\n while((float)(x[i+na*1]-x[i-nb])==(float)(0.0) || ((float)(x[i+na]-x[i-nb*1])==(float)0.0)) {\n check = check + 1;\n if(check%2==0) {\n na = na + 1;\n }\n else {\n nb = nb + 1;\n }\n }\n u[i]=(y[i+1]-y[i])/(x[i+na*1]-x[i-nb]) - (y[i]-y[i-1])/(x[i+na]-x[i-nb*1]);\n\n u[i]=(6.0*u[i]/(x[i+na*1]-x[i-nb*1])-sig*u[i-1])/p;\n\n }\n }\n if (ypn > 0.99e30) //The upper boundary condition is set either to be \"natural\"\n qn=un=0.0;\n else { //or else to have a specified first derivative.\n qn=0.5;\n un=(3.0/(x[n]-x[n-1]))*(ypn-(y[n]-y[n-1])/(x[n]-x[n-1]));\n }\n y2[n]=(un-qn*u[n-1])/(qn*y2[n-1]+1.0);\n\n for (k=n-1;k>=1;k--) { //This is the backsubstitution loop of the tridiagonal\n y2[k]=y2[k]*y2[k+1]+u[k]; //algorithm.\n }\n free_vector(u,1,n-1);\n}\n\n\nvoid splint(float xa[], float ya[], float y2a[], int n, float x, float *y)\n/*Given the arrays xa[1..n] and ya[1..n], which tabulate a function (with the xai's in order),\n and given the array y2a[1..n], which is the output from spline above, and given a value of\n x, this routine returns a cubic-spline interpolated value y.*/\n{\n void nrerror(char error_text[]);\n int klo,khi,k;\n float h,b,a;\n klo=1; // We will find the right place in the table by means of\n khi=n; //bisection. This is optimal if sequential calls to this\n while (khi-klo > 1) { //routine are at random values of x. If sequential calls\n k=(khi+klo) >> 1; //are in order, and closely spaced, one would do better\n if (xa[k] > x) khi=k; //to store previous values of klo and khi and test if\n else klo=k; //they remain appropriate on the next call.\n } // klo and khi now bracket the input value of x.\n h=xa[khi]-xa[klo];\n if (h == 0.0) nrerror(\"Bad xa input to routine splint\"); //The xa's must be distinct.\n a=(xa[khi]-x)/h;\n b=(x-xa[klo])/h; //Cubic spline polynomial is now evaluated.\n *y=a*ya[klo]+b*ya[khi]+((a*a*a-a)*y2a[klo]+(b*b*b-b)*y2a[khi])*(h*h)/6.0;\n}\n\nunsigned long *lvector(long nl, long nh)\n/* allocate an unsigned long vector with subscript range v[nl..nh] */\n{\n unsigned long *v;\n v = (unsigned long *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(long)));\n if(!v) nrerror(\"allocation failure in lvector()\");\n return v - nl + NR_END;\n}\n\nvoid free_lvector(unsigned long *v, long nl, long nh)\n/* free an unsigned long vector allocated with lvector() */\n{\n free((FREE_ARG) (v+nl-NR_END));\n}\n\ndouble FgtrlnM_general(double lnM, void *params) {\n\n struct parameters_gsl_int_ vals = *(struct parameters_gsl_int_ *)params;\n\n float z = vals.z_obs;\n float M2 = vals.Mval;\n float MFeedback = vals.M_Feed;\n float alpha = vals.alpha_pl;\n float delta1 = vals.del_traj_1;\n float delta2 = vals.del_traj_2;\n\n return FgtrConditionalM_second(z,lnM,M2,MFeedback,alpha,delta1,delta2);\n}\ndouble FgtrM_general(float z, float M1, float M_Max, float M2, float MFeedback, float alpha, float delta1, float delta2) {\n\n double result, error, lower_limit, upper_limit;\n\n double rel_tol = 0.01;\n\n int size;\n size = 1000;\n\n // printf(\"delta1 = %e Deltac = %e\\n\",delta1,Deltac);\n\n if((float)delta1==(float)Deltac) {\n\n gsl_function Fx;\n\n gsl_integration_workspace * w = gsl_integration_workspace_alloc (size);\n\n Fx.function = &FgtrlnM_general;\n\n struct parameters_gsl_int_ parameters_gsl_int = {\n .z_obs = z,\n .Mval = M2,\n .M_Feed = MFeedback,\n .alpha_pl = alpha,\n .del_traj_1 = delta1,\n .del_traj_2 = delta2\n };\n\n Fx.params = ¶meters_gsl_int;\n\n lower_limit = M1;\n upper_limit = M_Max;\n\n// gsl_integration_qag (&Fx, lower_limit, upper_limit, 0, rel_tol, size, GSL_INTEG_GAUSS15, w, &result, &error);\n gsl_integration_qag (&Fx, lower_limit, upper_limit, 0, rel_tol, size, GSL_INTEG_GAUSS61, w, &result, &error);\n gsl_integration_workspace_free (w);\n\n if(delta2 > delta1) {\n return 1.;\n }\n else {\n return result;\n }\n }\n}\n\nfloat FgtrConditionallnM(float M1, struct parameters_gsl_int_ parameters_gsl_int) {\n\n float z = parameters_gsl_int.z_obs;\n float M2 = parameters_gsl_int.Mval;\n float MFeedback = parameters_gsl_int.M_Feed;\n float alpha = parameters_gsl_int.alpha_pl;\n float delta1 = parameters_gsl_int.del_traj_1;\n float delta2 = parameters_gsl_int.del_traj_2;\n\n return exp(M1)*pow(exp(M1)/MFeedback,alpha)*dNdM_conditional_second(z,M1,M2,delta1,delta2)/sqrt(2.*PI);\n}\n\nfloat GaussLegengreQuad_Fcoll(int n, float z, float M2, float MFeedback, float alpha, float delta1, float delta2)\n{\n //Performs the Gauss-Legendre quadrature.\n int i;\n\n float integrand,x;\n integrand = 0.0;\n\n struct parameters_gsl_int_ parameters_gsl_int = {\n .z_obs = z,\n .Mval = M2,\n .M_Feed = MFeedback,\n .alpha_pl = alpha,\n .del_traj_1 = delta1,\n .del_traj_2 = delta2\n };\n\n if(delta2>delta1) {\n return 1.;\n }\n else {\n for(i=1;i<(n+1);i++) {\n x = xi_low[i];\n integrand += wi_low[i]*FgtrConditionallnM(x,parameters_gsl_int);\n }\n return integrand;\n }\n}\n\n/*\n FUNCTION FgtrM_st(z, M)\n Computes the fraction of mass contained in haloes with mass > M at redshift z\n Uses Sheth-Torman correction\n */\ndouble dFdlnM_st_PL (double lnM, void *params){\n\n struct parameters_gsl_ST_int_ vals = *(struct parameters_gsl_ST_int_ *)params;\n\n double M = exp(lnM);\n float z = vals.z_obs;\n float MFeedback = vals.M_Feed;\n float alpha = vals.alpha_pl;\n\n return dNdM_st(z, M) * M * M * pow((M/MFeedback),alpha);\n}\ndouble FgtrM_st_PL(double z, double Mmin, double MFeedback, double alpha_pl){\n\n double result_lower, result_upper, error, lower_limit, upper_limit;\n gsl_function F;\n double rel_tol = 0.01; //<- relative tolerance\n gsl_integration_workspace * w_lower\n = gsl_integration_workspace_alloc (1000);\n gsl_integration_workspace * w_upper\n = gsl_integration_workspace_alloc (1000);\n\n struct parameters_gsl_ST_int_ parameters_gsl_ST_lower = {\n .z_obs = z,\n .M_Feed = MFeedback,\n .alpha_pl = alpha_pl,\n };\n\n F.function = &dFdlnM_st_PL;\n F.params = ¶meters_gsl_ST_lower;\n lower_limit = log(Mmin);\n upper_limit = log(1e16);\n\n gsl_integration_qag (&F, lower_limit, upper_limit, 0, rel_tol,\n 1000, GSL_INTEG_GAUSS61, w_lower, &result_lower, &error);\n gsl_integration_workspace_free (w_lower);\n\n return (result_lower) / (OMm*RHOcrit);\n}\n\nvoid initialiseSplinedSigmaM(float M_Min, float M_Max)\n{\n int i;\n float Mass;\n\n Mass_Spline = calloc(NMass,sizeof(float));\n Sigma_Spline = calloc(NMass,sizeof(float));\n dSigmadm_Spline = calloc(NMass,sizeof(float));\n second_derivs_sigma = calloc(NMass,sizeof(float));\n second_derivs_dsigma = calloc(NMass,sizeof(float));\n\n printf(\"Initializing mass spline \\n\");\n\n for(i=0;i\n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n#if (defined(SMOOTH_PHI) || defined(SMOOTH_ROTB) || defined(BSMOOTH))\n\n/*! Structure for communication during the density computation. Holds data that is sent to other processors.\n */\nstatic struct smoothdata_in\n{\n MyDouble Pos[3];\n MyFloat Hsml;\n int NodeList[NODELISTLENGTH];\n}\n *SmoothDataIn, *SmoothDataGet;\n\n\nstatic struct smoothdata_out\n{\n#ifdef SMOOTH_PHI\n MyFloat SmoothPhi;\n MyFloat SmoothDivB;\n#endif\n#ifdef SMOOTH_ROTB\n MyFloat SmoothRotB[3];\n#endif\n#ifdef BSMOOTH\n MyFloat BSmooth[3];\n#endif\n#if defined(BLACK_HOLES)\n MyLongDouble SmoothedEntr;\n#endif\n MyFloat DensityNorm;\n}\n *SmoothDataResult, *SmoothDataOut;\n\n\n\n\n\nvoid smoothed_values(void)\n{\n int ngrp, sendTask, recvTask, place, nexport, nimport;\n int i, j, ndone, ndone_flag, dummy;\n double timeall = 0, timecomp1 = 0, timecomp2 = 0, timecommsumm1 = 0, timecommsumm2 = 0, timewait1 =\n 0, timewait2 = 0;\n double timecomp, timecomm, timewait;\n double tstart, tend, t0, t1;\n\n#ifdef BSMOOTH\n int Smooth_Flag = 0;\n double dB[3];\n#endif\n\n /* Display information message that this step is executed on Task 0 ... */\n if(ThisTask == 0)\n {\n printf(\"Updating SPH interpolants for:\"\n#ifdef SMOOTH_PHI\n\t \" (divB and Phi(Dedner)\"\n#endif /* SMOOTH_PHI */\n#ifdef SMOOTH_ROTB\n\t \" (rotB)\"\n#endif /* SMOOTH_ROTB */\n#ifdef BSMOOTH\n\t \" (B)\"\n#endif /* BSMOOTH */\n\t \"\\n\");\n#ifdef BSMOOTH\n printf(\"Flag_FullStep = %d, Main TimestepCounts = %d\\n\", Flag_FullStep, All.MainTimestepCounts);\n#endif\n }\n#ifdef BSMOOTH\n if(Flag_FullStep == 1)\n {\n if((All.MainTimestepCounts % All.BSmoothInt == 0) && (All.BSmoothInt >= 0))\n\t{\n\t Smooth_Flag = 1;\n\t if(ThisTask == 0)\n\t printf(\"Smoothing B %d, %f\\n\", All.BSmoothInt, All.BSmoothFrac);\n\t}\n All.MainTimestepCounts++;\n }\n#endif\n\n Ngblist = (int *) mymalloc(NumPart * sizeof(int));\n\n All.BunchSize =\n (int) ((All.BufferSize * 1024 * 1024) / (sizeof(struct data_index) + sizeof(struct data_nodelist) +\n\t\t\t\t\t sizeof(struct smoothdata_in) + sizeof(struct smoothdata_out) +\n\t\t\t\t\t sizemax(sizeof(struct smoothdata_in),\n\t\t\t\t\t\t sizeof(struct smoothdata_out))));\n DataIndexTable = (struct data_index *) mymalloc(All.BunchSize * sizeof(struct data_index));\n DataNodeList = (struct data_nodelist *) mymalloc(All.BunchSize * sizeof(struct data_nodelist));\n\n CPU_Step[CPU_SMTHMISC] += measure_time();\n t0 = second();\n\n i = FirstActiveParticle;\t/* begin with this index */\n\n do\n {\n for(j = 0; j < NTask; j++)\n\t{\n\t Send_count[j] = 0;\n\t Exportflag[j] = -1;\n\t}\n\n /* do local particles and prepare export list */\n tstart = second();\n for(nexport = 0; i >= 0; i = NextActiveParticle[i])\n\t{\n\t if(density_isactive(i))\n\t {\n\t if(smoothed_evaluate(i, 0, &nexport, Send_count) < 0)\n\t\tbreak;\n\t }\n\t}\n tend = second();\n timecomp1 += timediff(tstart, tend);\n\n#ifdef MYSORT\n mysort_dataindex(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n#else\n qsort(DataIndexTable, nexport, sizeof(struct data_index), data_index_compare);\n#endif\n\n tstart = second();\n\n MPI_Allgather(Send_count, NTask, MPI_INT, Sendcount_matrix, NTask, MPI_INT, MPI_COMM_WORLD);\n\n tend = second();\n timewait1 += timediff(tstart, tend);\n\n for(j = 0, nimport = 0, Recv_offset[0] = 0, Send_offset[0] = 0; j < NTask; j++)\n\t{\n\t Recv_count[j] = Sendcount_matrix[j * NTask + ThisTask];\n\t nimport += Recv_count[j];\n\n\t if(j > 0)\n\t {\n\t Send_offset[j] = Send_offset[j - 1] + Send_count[j - 1];\n\t Recv_offset[j] = Recv_offset[j - 1] + Recv_count[j - 1];\n\t }\n\t}\n\n SmoothDataGet = (struct smoothdata_in *) mymalloc(nimport * sizeof(struct smoothdata_in));\n SmoothDataIn = (struct smoothdata_in *) mymalloc(nexport * sizeof(struct smoothdata_in));\n\n /* prepare particle data for export */\n for(j = 0; j < nexport; j++)\n\t{\n\t place = DataIndexTable[j].Index;\n\n\t SmoothDataIn[j].Pos[0] = P[place].Pos[0];\n\t SmoothDataIn[j].Pos[1] = P[place].Pos[1];\n\t SmoothDataIn[j].Pos[2] = P[place].Pos[2];\n\t SmoothDataIn[j].Hsml = PPP[place].Hsml;\n\n\t memcpy(SmoothDataIn[j].NodeList,\n\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\t}\n\n /* exchange particle data */\n tstart = second();\n for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t{\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t {\n\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t{\n\t\t /* get the particles */\n\t\t MPI_Sendrecv(&SmoothDataIn[Send_offset[recvTask]],\n\t\t\t Send_count[recvTask] * sizeof(struct smoothdata_in), MPI_BYTE,\n\t\t\t recvTask, TAG_SMOOTH_A,\n\t\t\t &SmoothDataGet[Recv_offset[recvTask]],\n\t\t\t Recv_count[recvTask] * sizeof(struct smoothdata_in), MPI_BYTE,\n\t\t\t recvTask, TAG_SMOOTH_A, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t}\n\t }\n\t}\n tend = second();\n timecommsumm1 += timediff(tstart, tend);\n\n myfree(SmoothDataIn);\n SmoothDataResult = (struct smoothdata_out *) mymalloc(nimport * sizeof(struct smoothdata_out));\n SmoothDataOut = (struct smoothdata_out *) mymalloc(nexport * sizeof(struct smoothdata_out));\n\n\n /* now do the particles that were sent to us */\n\n tstart = second();\n for(j = 0; j < nimport; j++)\n\tsmoothed_evaluate(j, 1, &dummy, &dummy);\n tend = second();\n timecomp2 += timediff(tstart, tend);\n\n if(i < 0)\n\tndone_flag = 1;\n else\n\tndone_flag = 0;\n\n tstart = second();\n MPI_Allreduce(&ndone_flag, &ndone, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);\n tend = second();\n timewait2 += timediff(tstart, tend);\n\n\n /* get the result */\n tstart = second();\n for(ngrp = 1; ngrp < (1 << PTask); ngrp++)\n\t{\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\t if(recvTask < NTask)\n\t {\n\t if(Send_count[recvTask] > 0 || Recv_count[recvTask] > 0)\n\t\t{\n\t\t /* send the results */\n\t\t MPI_Sendrecv(&SmoothDataResult[Recv_offset[recvTask]],\n\t\t\t Recv_count[recvTask] * sizeof(struct smoothdata_out),\n\t\t\t MPI_BYTE, recvTask, TAG_SMOOTH_B,\n\t\t\t &SmoothDataOut[Send_offset[recvTask]],\n\t\t\t Send_count[recvTask] * sizeof(struct smoothdata_out),\n\t\t\t MPI_BYTE, recvTask, TAG_SMOOTH_B, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n\t\t}\n\t }\n\t}\n tend = second();\n timecommsumm2 += timediff(tstart, tend);\n\n\n /* add the result to the local particles */\n tstart = second();\n for(j = 0; j < nexport; j++)\n\t{\n\t place = DataIndexTable[j].Index;\n\n\t if(P[place].Type == 0)\n\t {\n#ifdef SMOOTH_PHI\n\t SphP[place].SmoothPhi += SmoothDataOut[j].SmoothPhi;\n\t SphP[place].SmoothDivB += SmoothDataOut[j].SmoothDivB;\n#endif /* SMOOTH_PHI */\n\n#ifdef SMOOTH_ROTB\n\t SphP[place].SmoothedRotB[0] += SmoothDataOut[j].SmoothRotB[0];\n\t SphP[place].SmoothedRotB[1] += SmoothDataOut[j].SmoothRotB[1];\n\t SphP[place].SmoothedRotB[2] += SmoothDataOut[j].SmoothRotB[2];\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n\t SphP[place].BSmooth[0] += SmoothDataOut[j].BSmooth[0];\n\t SphP[place].BSmooth[1] += SmoothDataOut[j].BSmooth[1];\n\t SphP[place].BSmooth[2] += SmoothDataOut[j].BSmooth[2];\n#endif /* BSMOOTH */\n\n\t SphP[place].DensityNorm += SmoothDataOut[j].DensityNorm;\n\t }\n\t}\n tend = second();\n timecomp1 += timediff(tstart, tend);\n\n\n myfree(SmoothDataOut);\n myfree(SmoothDataResult);\n myfree(SmoothDataGet);\n }\n while(ndone < NTask);\n\n myfree(DataNodeList);\n myfree(DataIndexTable);\n myfree(Ngblist);\n\n\n\n /* do final operations on results */\n tstart = second();\n for(i = FirstActiveParticle; i >= 0; i = NextActiveParticle[i])\n {\n if(density_isactive(i))\n\tif(P[i].Type == 0)\n\t {\n#ifdef SMOOTH_PHI\n\t SphP[i].SmoothPhi /= SphP[i].DensityNorm;\n\t SphP[i].SmoothDivB /= SphP[i].DensityNorm;\n#endif /* SMOOTH_PHI */\n\n#ifdef SMOOTH_ROTB\n\t SphP[i].SmoothedRotB[0] /= SphP[i].DensityNorm;\n\t SphP[i].SmoothedRotB[1] /= SphP[i].DensityNorm;\n\t SphP[i].SmoothedRotB[2] /= SphP[i].DensityNorm;\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n\t SphP[i].BSmooth[0] /= SphP[i].DensityNorm;\n\t SphP[i].BSmooth[1] /= SphP[i].DensityNorm;\n\t SphP[i].BSmooth[2] /= SphP[i].DensityNorm;\n\n\t if(Smooth_Flag == 1)\n\t {\n\t\tdB[0] = All.BSmoothFrac * (SphP[i].BSmooth[0] - SphP[i].BPred[0]);\n\t\tdB[1] = All.BSmoothFrac * (SphP[i].BSmooth[1] - SphP[i].BPred[1]);\n\t\tdB[2] = All.BSmoothFrac * (SphP[i].BSmooth[2] - SphP[i].BPred[2]);\n\t\tSphP[i].BPred[0] += dB[0];\n\t\tSphP[i].BPred[1] += dB[1];\n\t\tSphP[i].BPred[2] += dB[2];\n#ifndef EULERPOTENTIALS\n\t\tSphP[i].B[0] += dB[0];\n\t\tSphP[i].B[1] += dB[1];\n\t\tSphP[i].B[2] += dB[2];\n#endif\n\t }\n#endif /* BSMOOTH */\n\t }\n }\n tend = second();\n timecomp1 += timediff(tstart, tend);\n\n /* collect some timing information */\n\n t1 = WallclockTime = second();\n timeall += timediff(t0, t1);\n\n timecomp = timecomp1 + timecomp2;\n timewait = timewait1 + timewait2;\n timecomm = timecommsumm1 + timecommsumm2;\n\n CPU_Step[CPU_SMTHCOMPUTE] += timecomp;\n CPU_Step[CPU_SMTHWAIT] += timewait;\n CPU_Step[CPU_SMTHCOMM] += timecomm;\n CPU_Step[CPU_SMTHMISC] += timeall - (timecomp + timewait + timecomm);\n}\n\n\n\n/*! This function represents the core of the SPH density computation. The\n* target particle may either be local, or reside in the communication\n* buffer.\n*/\nint smoothed_evaluate(int target, int mode, int *nexport, int *nsend_local)\n{\n int j, n, listindex = 0;\n int startnode, numngb_inbox;\n double h, h2, hinv, hinv3, hinv4;\n double wk, dwk;\n double dx, dy, dz, r, r2, u, mass_j;\n MyFloat *pos;\n double DensityNorm = 0;\n\n#ifdef SMOOTH_PHI\n double SmoothPhi = 0.0;\n double SmoothDivB = 0.0;\n#endif /* SMOOTH_PHI */\n\n#ifdef SMOOTH_ROTB\n double smoothrotb[3];\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n double BSmooth[3];\n#endif /* BSMOOTH */\n\n\n#ifdef SMOOTH_ROTB\n smoothrotb[0] = smoothrotb[1] = smoothrotb[2] = 0;\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n BSmooth[0] = BSmooth[1] = BSmooth[2] = 0;\n#endif /* BSMOOTH */\n\n if(mode == 0)\n {\n pos = P[target].Pos;\n h = PPP[target].Hsml;\n }\n else\n {\n pos = SmoothDataGet[target].Pos;\n h = SmoothDataGet[target].Hsml;\n }\n\n\n h2 = h * h;\n hinv = 1.0 / h;\n#ifndef TWODIMS\n hinv3 = hinv * hinv * hinv;\n#else\n hinv3 = hinv * hinv / boxSize_Z;\n#endif\n hinv4 = hinv3 * hinv;\n\n\n\n if(mode == 0)\n {\n startnode = All.MaxPart;\t/* root node */\n }\n else\n {\n startnode = SmoothDataGet[target].NodeList[0];\n startnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n }\n\n while(startnode >= 0)\n {\n while(startnode >= 0)\n\t{\n\t numngb_inbox = ngb_treefind_variable(&pos[0], h, target, &startnode, mode, nexport, nsend_local);\n\n\t if(numngb_inbox < 0)\n\t return -1;\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 < h2)\n\t\t{\n\t\t r = sqrt(r2);\n\n\t\t u = r * hinv;\n\n\t\t if(u < 0.5)\n\t\t {\n\t\t wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);\n\t\t dwk = hinv4 * u * (KERNEL_COEFF_3 * u - KERNEL_COEFF_4);\n\t\t }\n\t\t else\n\t\t {\n\t\t wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);\n\t\t dwk = hinv4 * KERNEL_COEFF_6 * (1.0 - u) * (1.0 - u);\n\t\t }\n\n\t\t mass_j = P[j].Mass;\n\t\t wk /= SphP[j].d.Density;\n\n#ifdef SMOOTH_PHI\n\t\t SmoothPhi += mass_j * wk * SphP[j].PhiPred;\n\t\t SmoothDivB += mass_j * wk * SphP[j].divB;\n#endif /* SMOOTH_PHI */\n\n#ifdef SMOOTH_ROTB\n\t\t smoothrotb[0] += mass_j * wk * SphP[j].RotB[0];\n\t\t smoothrotb[1] += mass_j * wk * SphP[j].RotB[1];\n\t\t smoothrotb[2] += mass_j * wk * SphP[j].RotB[2];\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n\t\t BSmooth[0] += mass_j * wk * SphP[j].BPred[0];\n\t\t BSmooth[1] += mass_j * wk * SphP[j].BPred[1];\n\t\t BSmooth[2] += mass_j * wk * SphP[j].BPred[2];\n#endif /* BSMOOTH */\n\n\t\t DensityNorm += mass_j * wk;\n\t\t}\n\t }\n\t}\n if(mode == 1)\n\t{\n\t listindex++;\n\t if(listindex < NODELISTLENGTH)\n\t {\n\t startnode = SmoothDataGet[target].NodeList[listindex];\n\t if(startnode >= 0)\n\t\tstartnode = Nodes[startnode].u.d.nextnode;\t/* open it */\n\t }\n\t}\n }\n\n\n if(mode == 0)\n {\n#ifdef SMOOTH_PHI\n SphP[target].SmoothPhi = SmoothPhi;\n SphP[target].SmoothDivB = SmoothDivB;\n#endif /* SMOOTH_PHI */\n\n#ifdef SMOOTH_ROTB\n SphP[target].SmoothedRotB[0] = smoothrotb[0];\n SphP[target].SmoothedRotB[1] = smoothrotb[1];\n SphP[target].SmoothedRotB[2] = smoothrotb[2];\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n SphP[target].BSmooth[0] = BSmooth[0];\n SphP[target].BSmooth[1] = BSmooth[1];\n SphP[target].BSmooth[2] = BSmooth[2];\n#endif /* BSMOOTH */\n SphP[target].DensityNorm = DensityNorm;\n }\n else\n {\n#ifdef SMOOTH_PHI\n SmoothDataResult[target].SmoothPhi = SmoothPhi;\n SmoothDataResult[target].SmoothDivB = SmoothDivB;\n#endif /* SMOOTH_PHI */\n\n#ifdef SMOOTH_ROTB\n SmoothDataResult[target].SmoothRotB[0] = smoothrotb[0];\n SmoothDataResult[target].SmoothRotB[1] = smoothrotb[1];\n SmoothDataResult[target].SmoothRotB[2] = smoothrotb[2];\n#endif /* SMOOTH_ROTB */\n\n#ifdef BSMOOTH\n SmoothDataResult[target].BSmooth[0] = BSmooth[0];\n SmoothDataResult[target].BSmooth[1] = BSmooth[1];\n SmoothDataResult[target].BSmooth[2] = BSmooth[2];\n#endif /* BSMOOTH */\n SmoothDataResult[target].DensityNorm = DensityNorm;\n }\n\n return 0;\n}\n\n\n#endif\n", "meta": {"hexsha": "cc606fa734470c2cc5dfc836a24e5dc3f446dfe7", "size": 14007, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/smooth_simple.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/smooth_simple.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/smooth_simple.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.5602189781, "max_line_length": 108, "alphanum_fraction": 0.6215463697, "num_tokens": 4612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.2742505719377324}} {"text": "///\n/// @file\n///\n/// @brief This file contains math functions that are shared among all\n/// components of the library.\n///\n/// @author Mirko Myllykoski (mirkom@cs.umu.se), Umeå University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Umeå Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n/// this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n/// this list of conditions and the following disclaimer in the documentation\n/// and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n/// contributors may be used to endorse or promote products derived from this\n/// software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include \n#include \n#include \"math.h\"\n#include \"common.h\"\n#include \"sanity.h\"\n#include \n#include \n#include \n\nint starneig_largers_factor(int a, int b)\n{\n while (b != 0) {\n int t = b;\n b = a % b;\n a = t;\n }\n return a;\n}\n\nvoid starneig_init_local_q(int n, size_t ldA, double *A)\n{\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n A[i*ldA+j] = 0.0;\n\n for (int i = 0; i < n; i++)\n A[i*ldA+i] = 1.0;\n}\n\nvoid starneig_small_left_gemm_update(int rbegin, int rend, int cbegin, int cend,\n size_t ldQ, size_t ldA, size_t ldT, double const *Q, double *A, double *T) {\n\n STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, \"A (in)\");\n STARNEIG_SANITY_CHECK_INF(0, rend-rbegin, 0, rend-rbegin, ldQ, Q, \"Q\");\n\n int m = rend-rbegin;\n int n = cend-cbegin;\n int k = rend-rbegin;\n\n if (m == 0 || n == 0)\n return;\n\n starneig_copy_matrix(\n k, n, ldA, ldT, sizeof(double), A+cbegin*ldA+rbegin, T);\n\n cblas_dgemm(\n CblasColMajor, CblasTrans, CblasNoTrans, m, n, k, 1.0, Q, ldQ, T, ldT,\n 0.0, A+cbegin*ldA+rbegin, ldA);\n\n STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, \"A (out)\");\n}\n\nvoid starneig_small_right_gemm_update(\n int rbegin, int rend, int cbegin, int cend,\n size_t ldQ, size_t ldA, size_t ldT, double const *Q, double *A, double *T) {\n\n STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, \"A (in)\");\n STARNEIG_SANITY_CHECK_INF(0, cend-cbegin, 0, cend-cbegin, ldQ, Q, \"Q\");\n\n int m = rend-rbegin;\n int n = cend-cbegin;\n int k = cend-cbegin;\n\n if (m == 0 || n == 0)\n return;\n\n starneig_copy_matrix(\n m, k, ldA, ldT, sizeof(double), A+cbegin*ldA+rbegin, T);\n\n cblas_dgemm(\n CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1.0, T, ldT, Q, ldQ,\n 0.0, A+cbegin*ldA+rbegin, ldA);\n\n STARNEIG_SANITY_CHECK_INF(rbegin, rend, cbegin, cend, ldA, A, \"A (out)\");\n}\n\nvoid starneig_small_gemm_updates(\n int begin, int end, int n, size_t ldlQ, size_t ldlZ, size_t ldQ, size_t ldZ,\n size_t ldA, size_t ldB, size_t ldhT, size_t ldvT, double const *lQ,\n double const *lZ, double *Q, double *Z, double *A, double *B,\n double *hT, double *vT)\n{\n // apply the local transformation matrices lQ and lZ to Q and Z\n if (Q != NULL)\n starneig_small_right_gemm_update(\n 0, n, begin, end, ldlQ, ldQ, ldvT, lQ, Q, vT);\n if (Z != NULL && Z != Q)\n starneig_small_right_gemm_update(\n 0, n, begin, end, ldlZ, ldZ, ldvT, lZ, Z, vT);\n\n // apply the local transformation matrices lQ and lZ to A\n if (A != NULL) {\n starneig_small_right_gemm_update(\n 0, begin, begin, end, ldlZ, ldA, ldvT, lZ, A, vT);\n starneig_small_left_gemm_update(\n begin, end, end, n, ldlQ, ldA, ldhT, lQ, A, hT);\n }\n\n // apply the local transformation matrices lQ and lZ to B\n if (B != NULL) {\n starneig_small_right_gemm_update(\n 0, begin, begin, end, ldlZ, ldB, ldvT, lZ, B, vT);\n starneig_small_left_gemm_update(\n begin, end, end, n, ldlQ, ldB, ldhT, lQ, B, hT);\n }\n}\n\nvoid starneig_compute_complex_eigenvalue(\n int ldA, int ldB, double const *A, double const *B,\n double *real1, double *imag1, double *real2, double *imag2,\n double *beta1, double *beta2)\n{\n if (B != NULL) {\n extern void dlag2_(double const *, int const *, double const *,\n int const *, double const *, double*, double *, double *, double *,\n double *);\n\n extern double dlamch_(char const *);\n const double safmin = dlamch_(\"S\");\n\n double _real1, _real2, _beta1, _beta2, wi;\n dlag2_(\n A, &ldA, B, &ldB, &safmin, &_beta1, &_beta2, &_real1, &_real2, &wi);\n\n if (beta1) {\n *real1 = _real1;\n *real2 = _real2;\n *imag1 = wi;\n *imag2 = -wi;\n *beta1 = _beta1;\n *beta2 = _beta2;\n }\n else {\n *real1 = _real1/_beta1;\n *real2 = _real2/_beta2;\n *imag1 = wi/_beta1;\n *imag2 = -wi/_beta2;\n }\n }\n else {\n extern void dlanv2_(\n double *, double *, double *, double *, double *,\n double *, double *, double *, double *, double *);\n\n double a[] = { A[0], A[1], A[ldA], A[ldA+1] };\n double cs, ss;\n\n dlanv2_(\n &a[0], &a[2], &a[1], &a[3], real1, imag1, real2, imag2, &cs, &ss);\n\n if (beta1) {\n *beta1 = 1.0;\n *beta2 = 1.0;\n }\n }\n}\n", "meta": {"hexsha": "16b4ee0ffbd54ced451064ad875366d3bd32e65e", "size": 6487, "ext": "c", "lang": "C", "max_stars_repo_path": "src/common/math.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/common/math.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common/math.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 33.0969387755, "max_line_length": 80, "alphanum_fraction": 0.6115307538, "num_tokens": 2002, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.523420348936324, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.27396886168062323}} {"text": "#pragma once\n\n#include \n#include \n#include \n\nnamespace rev {\n\nstruct Segment {\n glm::vec3 start;\n glm::vec3 end;\n};\n\nstruct Ray {\n glm::vec3 origin;\n glm::vec3 direction;\n};\n\nstruct Sphere {\n glm::vec3 center;\n float radius;\n};\n\ntemplate \nvoid iteratePolygonVertices(const VertexRange& vertices, SegmentVisitor&& visitor)\n{\n Expects(vertices.size() >= 3);\n auto begin = std::begin(vertices);\n auto end = std::end(vertices);\n\n auto segmentStart = begin;\n auto segmentEnd = begin + 1;\n\n while (segmentStart != end) {\n if (segmentEnd == end) {\n segmentEnd = begin;\n }\n\n visitor(Segment{ *segmentStart, *segmentEnd });\n segmentStart++;\n segmentEnd++;\n }\n}\n\nclass NullPolygonBuilder {\npublic:\n void addVertex(const glm::vec3& vertex) {}\n};\n\ntemplate \nclass OutputIteratorPolygonBuilder {\npublic:\n OutputIteratorPolygonBuilder(IteratorType iterator)\n : _iter(iterator)\n {\n }\n\n void addVertex(const glm::vec3& vertex)\n {\n *_iter = vertex;\n _iter++;\n }\n\n IteratorType getIterator() const { return _iter; }\n\nprivate:\n IteratorType _iter;\n};\n\nstruct AxisAlignedPlane {\n struct Hit {\n glm::vec3 intersectionPoint;\n float t;\n };\n\n Hit intersect(const Ray& ray) const\n {\n float boundaryDelta = boundary - ray.origin[dimensionIndex];\n float t = boundaryDelta / ray.direction[dimensionIndex];\n\n glm::vec3 intersectPoint = ray.origin + (t * ray.direction);\n\n // Avoid floating point error along the boundary dimension.\n intersectPoint[dimensionIndex] = boundary;\n return { intersectPoint, t };\n }\n\n glm::vec3 intersect(const Segment& segment) const\n {\n glm::vec3 direction = segment.end - segment.start;\n auto [intersectionPoint, t] = intersect(Ray{ segment.start, direction });\n if (!(t > 0.0f)) {\n return segment.start;\n } else if (!(t < 1.0f)) {\n return segment.end;\n }\n\n for (size_t k = 0; k < 3; k++) {\n if (segment.start[k] == segment.end[k]) {\n intersectionPoint[k] = segment.start[k];\n }\n }\n return intersectionPoint;\n }\n\n template \n void splitConvexPolygon(const InputVertexRange& inputVertices, LeftBuilder&& leftBuilder,\n RightBuilder&& rightBuilder) const\n {\n iteratePolygonVertices(\n inputVertices, [this, &leftBuilder, &rightBuilder](const Segment& segment) {\n float startPosition = segment.start[dimensionIndex];\n float endPosition = segment.end[dimensionIndex];\n\n bool emitIntersection = false;\n if (startPosition < boundary) {\n leftBuilder.addVertex(segment.start);\n if (endPosition > boundary) {\n emitIntersection = true;\n }\n } else if (startPosition > boundary) {\n rightBuilder.addVertex(segment.start);\n if (endPosition < boundary) {\n emitIntersection = true;\n }\n } else {\n // Right on the boundary.\n leftBuilder.addVertex(segment.start);\n rightBuilder.addVertex(segment.start);\n }\n\n if (emitIntersection) {\n auto intersection = intersect(segment);\n leftBuilder.addVertex(intersection);\n rightBuilder.addVertex(intersection);\n }\n });\n }\n\n uint8_t dimensionIndex;\n float boundary;\n};\n\nstruct AxisAlignedBoundingBox {\n void expandToVertex(const glm::vec3& vertex)\n {\n for (int k = 0; k < 3; k++) {\n if (vertex[k] < minimum[k]) {\n minimum[k] = vertex[k];\n }\n if (vertex[k] > maximum[k]) {\n maximum[k] = vertex[k];\n }\n }\n }\n\n void expandToBox(const AxisAlignedBoundingBox& other)\n {\n for (int k = 0; k < 3; k++) {\n if (other.minimum[k] < minimum[k]) {\n minimum[k] = other.minimum[k];\n }\n if (other.maximum[k] > maximum[k]) {\n maximum[k] = other.maximum[k];\n }\n }\n }\n\n void reduceToBox(const AxisAlignedBoundingBox& other)\n {\n for (int k = 0; k < 3; k++) {\n if (other.minimum[k] > minimum[k]) {\n minimum[k] = other.minimum[k];\n }\n if (other.maximum[k] < maximum[k]) {\n maximum[k] = other.maximum[k];\n }\n Expects(!(minimum[k] > maximum[k]));\n }\n }\n\n float getSurfaceArea() const\n {\n glm::vec3 diagonal = maximum - minimum;\n float surfaceArea = 0.0f;\n surfaceArea += diagonal.x * diagonal.y;\n surfaceArea += diagonal.y * diagonal.z;\n surfaceArea += diagonal.z * diagonal.z;\n\n return 2.0f * surfaceArea;\n }\n\n float getVolume() const\n {\n glm::vec3 diagonal = maximum - minimum;\n return diagonal.x * diagonal.y * diagonal.z;\n }\n\n std::array split(const AxisAlignedPlane& plane) const\n {\n Expects(!(plane.boundary < minimum[plane.dimensionIndex]));\n Expects(!(plane.boundary > maximum[plane.dimensionIndex]));\n\n std::array splitBoxes{ *this, *this };\n splitBoxes[0].maximum[plane.dimensionIndex] = plane.boundary;\n splitBoxes[1].minimum[plane.dimensionIndex] = plane.boundary;\n\n return splitBoxes;\n }\n\n struct Hit {\n glm::vec3 intersectionPoint;\n float t;\n uint8_t planeDimension;\n };\n\n bool containsPoint(const glm::vec3& point) const\n {\n for (int k = 0; k < 3; k++) {\n if (point[k] < minimum[k]) {\n return false;\n }\n if (point[k] > maximum[k]) {\n return false;\n }\n }\n\n return true;\n }\n\n bool intersectsSphere(const Sphere& sphere) const\n {\n float r2 = sphere.radius * sphere.radius;\n for (size_t k = 0; k < 3; k++) {\n if (sphere.center[k] < minimum[k]) {\n float diff = minimum[k] - sphere.center[k];\n r2 -= diff * diff;\n } else if (sphere.center[k] > maximum[k]) {\n float diff = sphere.center[k] - maximum[k];\n r2 -= diff * diff;\n }\n }\n return r2 > 0.0f;\n }\n\n std::optional castExternalRay(const Ray& ray) const\n {\n for (uint8_t k = 0; k < 3; k++) {\n float d = ray.direction[k];\n if (d < 0.0f) {\n float boundary = maximum[k];\n if (ray.origin[k] > boundary) {\n auto intersection = AxisAlignedPlane{ k, boundary }.intersect(ray);\n if (containsPoint(intersection.intersectionPoint)) {\n return Hit{ intersection.intersectionPoint, intersection.t, k };\n }\n }\n } else if (d > 0.0f) {\n float boundary = minimum[k];\n if (ray.origin[k] < boundary) {\n auto intersection = AxisAlignedPlane{ k, boundary }.intersect(ray);\n if (containsPoint(intersection.intersectionPoint)) {\n return Hit{ intersection.intersectionPoint, intersection.t, k };\n }\n }\n }\n }\n return std::nullopt;\n }\n\n Hit castInternalRay(const Ray& ray) const\n {\n for (uint8_t k = 0; k < 3; k++) {\n float d = ray.direction[k];\n\n float boundary;\n if (d < 0.0f) {\n boundary = minimum[k];\n } else if (d > 0.0f) {\n boundary = maximum[k];\n } else {\n continue;\n }\n\n auto intersection = AxisAlignedPlane{ k, boundary }.intersect(ray);\n if (containsPoint(intersection.intersectionPoint)) {\n return Hit{ intersection.intersectionPoint, intersection.t, k };\n }\n }\n throw std::runtime_error(\"Internal ray intersection not found.\");\n }\n\n glm::vec3 minimum{ std::numeric_limits::infinity() };\n glm::vec3 maximum{ -std::numeric_limits::infinity() };\n};\n\ntemplate \nAxisAlignedBoundingBox smallestBoxContainingVertices(const VertexRange& range)\n{\n AxisAlignedBoundingBox box;\n for (const auto& vertex : range) {\n box.expandToVertex(vertex);\n }\n return box;\n}\n\n}", "meta": {"hexsha": "362ae7a4a995f603449732efbbcaf712c98d1b12", "size": 8877, "ext": "h", "lang": "C", "max_stars_repo_path": "engine/include/rev/geometry/Tools.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/Tools.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/Tools.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": 28.9153094463, "max_line_length": 93, "alphanum_fraction": 0.5358792385, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2731529165032717}} {"text": "/**\n *\n * @file core_dssssm.c\n *\n * PLASMA core_blas kernel\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Hatem Ltaief\n * @author Mathieu Faverge\n * @author Jakub Kurzak\n * @date 2010-11-15\n * @generated d Tue Jan 7 11:44:45 2014\n *\n **/\n#include \n#include \"common.h\"\n\n/***************************************************************************//**\n *\n * @ingroup CORE_double\n *\n * CORE_dssssm applies the LU factorization update from a complex\n * matrix formed by a lower triangular IB-by-K tile L1 on top of a\n * M2-by-K tile L2 to a second complex matrix formed by a M1-by-N1\n * tile A1 on top of a M2-by-N2 tile A2 (N1 == N2).\n *\n * This is the right-looking Level 2.5 BLAS version of the algorithm.\n *\n *******************************************************************************\n *\n * @param[in] M1\n * The number of rows of the tile A1. M1 >= 0.\n *\n * @param[in] N1\n * The number of columns of the tile A1. N1 >= 0.\n *\n * @param[in] M2\n * The number of rows of the tile A2 and of the tile L2.\n * M2 >= 0.\n *\n * @param[in] N2\n * The number of columns of the tile A2. N2 >= 0.\n *\n * @param[in] K\n * The number of columns of the tiles L1 and L2. K >= 0.\n *\n * @param[in] IB\n * The inner-blocking size. IB >= 0.\n *\n * @param[in,out] A1\n * On entry, the M1-by-N1 tile A1.\n * On exit, A1 is updated by the application of L (L1 L2).\n *\n * @param[in] LDA1\n * The leading dimension of the array A1. LDA1 >= max(1,M1).\n *\n * @param[in,out] A2\n * On entry, the M2-by-N2 tile A2.\n * On exit, A2 is updated by the application of L (L1 L2).\n *\n * @param[in] LDA2\n * The leading dimension of the array A2. LDA2 >= max(1,M2).\n *\n * @param[in] L1\n * The IB-by-K lower triangular tile as returned by\n * CORE_dtstrf.\n *\n * @param[in] LDL1\n * The leading dimension of the array L1. LDL1 >= max(1,IB).\n *\n * @param[in] L2\n * The M2-by-K tile as returned by CORE_dtstrf.\n *\n * @param[in] LDL2\n * The leading dimension of the array L2. LDL2 >= max(1,M2).\n *\n * @param[in] IPIV\n * The pivot indices array of size K as returned by\n * CORE_dtstrf.\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_dssssm = PCORE_dssssm\n#define CORE_dssssm PCORE_dssssm\n#endif\nint CORE_dssssm(int M1, int N1, int M2, int N2, int K, int IB,\n double *A1, int LDA1,\n double *A2, int LDA2,\n const double *L1, int LDL1,\n const double *L2, int LDL2,\n const int *IPIV)\n{\n static double zone = 1.0;\n static double mzone =-1.0;\n\n int i, ii, sb;\n int im, ip;\n\n /* Check input arguments */\n if (M1 < 0) {\n coreblas_error(1, \"Illegal value of M1\");\n return -1;\n }\n if (N1 < 0) {\n coreblas_error(2, \"Illegal value of N1\");\n return -2;\n }\n if (M2 < 0) {\n coreblas_error(3, \"Illegal value of M2\");\n return -3;\n }\n if (N2 < 0) {\n coreblas_error(4, \"Illegal value of N2\");\n return -4;\n }\n if (K < 0) {\n coreblas_error(5, \"Illegal value of K\");\n return -5;\n }\n if (IB < 0) {\n coreblas_error(6, \"Illegal value of IB\");\n return -6;\n }\n if (LDA1 < max(1,M1)) {\n coreblas_error(8, \"Illegal value of LDA1\");\n return -8;\n }\n if (LDA2 < max(1,M2)) {\n coreblas_error(10, \"Illegal value of LDA2\");\n return -10;\n }\n if (LDL1 < max(1,IB)) {\n coreblas_error(12, \"Illegal value of LDL1\");\n return -12;\n }\n if (LDL2 < max(1,M2)) {\n coreblas_error(14, \"Illegal value of LDL2\");\n return -14;\n }\n\n /* Quick return */\n if ((M1 == 0) || (N1 == 0) || (M2 == 0) || (N2 == 0) || (K == 0) || (IB == 0))\n return PLASMA_SUCCESS;\n\n ip = 0;\n\n for(ii = 0; ii < K; ii += IB) {\n sb = min(K-ii, IB);\n\n for(i = 0; i < sb; i++) {\n im = IPIV[ip]-1;\n\n if (im != (ii+i)) {\n im = im - M1;\n cblas_dswap(N1, &A1[ii+i], LDA1, &A2[im], LDA2);\n }\n ip = ip + 1;\n }\n\n cblas_dtrsm(\n CblasColMajor, CblasLeft, CblasLower,\n CblasNoTrans, CblasUnit,\n sb, N1, (zone),\n &L1[LDL1*ii], LDL1,\n &A1[ii], LDA1);\n\n cblas_dgemm(\n CblasColMajor, CblasNoTrans, CblasNoTrans,\n M2, N2, sb,\n (mzone), &L2[LDL2*ii], LDL2,\n &A1[ii], LDA1,\n (zone), A2, LDA2);\n }\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "367b1c5015a39e04207a6c35177712993ad2a3c5", "size": 5011, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_dssssm.c", "max_stars_repo_name": "zhuangsc/Plasma-ompss1", "max_stars_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "core_blas/core_dssssm.c", "max_issues_repo_name": "zhuangsc/Plasma-ompss1", "max_issues_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core_blas/core_dssssm.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2336956522, "max_line_length": 82, "alphanum_fraction": 0.4929155857, "num_tokens": 1565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.2730500831720349}} {"text": "#include \n#include \n#include \n#include \n#define LOOPY_CALL_WITH_INTEGER_TYPES(MACRO_NAME) \\\n MACRO_NAME(int8, char) \\\n MACRO_NAME(int16, short) \\\n MACRO_NAME(int32, int) \\\n MACRO_NAME(int64, long)\n#define LOOPY_DEFINE_FLOOR_DIV_POS_B(SUFFIX, TYPE) \\\n static inline TYPE loopy_floor_div_pos_b_##SUFFIX(TYPE a, TYPE b) \\\n { \\\n if (a<0) \\\n a = a - (b-1); \\\n return a/b; \\\n }\nLOOPY_CALL_WITH_INTEGER_TYPES(LOOPY_DEFINE_FLOOR_DIV_POS_B)\n#undef LOOPY_DEFINE_FLOOR_DIV_POS_B\n#undef LOOPY_CALL_WITH_INTEGER_TYPES\n#define BYTES8 (8*8)\ntypedef double double8 __attribute__ ((vector_size (BYTES8)));\n#define BYTES4 (8*4)\ntypedef int int8 __attribute__ ((vector_size (BYTES4)));\n\nvoid wrap_form0_cell_integral_otherwise(int const start, int const end, double *__restrict__ dat2, double const *__restrict__ dat1, double const *__restrict__ glob0, double const *__restrict__ dat0, int const *__restrict__ map0, int const *__restrict__ map1)\n{\n double8 form_form0_cell_integral_otherwise __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_0 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_1 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_10 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_11 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_12 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_13 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_14 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_15 __attribute__ ((aligned (64)));\n double const form_form0_cell_integral_otherwise_16[4] __attribute__ ((aligned (64))) = { 0.041666666666666664, 0.041666666666666664, 0.041666666666666664, 0.041666666666666664 };\n double const form_form0_cell_integral_otherwise_17[4 * 4] __attribute__ ((aligned (64))) = { 0.13819660112500914, 0.585410196624969, 0.138196601125011, 0.13819660112501098, 0.13819660112500912, 0.13819660112501092, 0.585410196624969, 0.13819660112501098, 0.13819660112500914, 0.13819660112501095, 0.138196601125011, 0.585410196624969, 0.5854101966249672, 0.13819660112501092, 0.138196601125011, 0.13819660112501098 };\n double8 form_form0_cell_integral_otherwise_18 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_19 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_2 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_20 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_21 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_22[4] __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_23 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_24 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_25 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_26 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_27 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_28 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_29 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_3 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_30 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_31 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_32 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_33 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_34 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_35 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_36 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_37 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_38 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_39 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_4 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_40 __attribute__ ((aligned (64)));\n double const form_form0_cell_integral_otherwise_41[4] __attribute__ ((aligned (64))) = { -1.0, 0.0, 0.0, 1.0 };\n double8 form_form0_cell_integral_otherwise_42 __attribute__ ((aligned (64)));\n double const form_form0_cell_integral_otherwise_43[4] __attribute__ ((aligned (64))) = { -1.0, 0.0, 1.0, 0.0 };\n double8 form_form0_cell_integral_otherwise_44 __attribute__ ((aligned (64)));\n double const form_form0_cell_integral_otherwise_45[4] __attribute__ ((aligned (64))) = { -1.0, 1.0, 0.0, 0.0 };\n double8 form_form0_cell_integral_otherwise_5 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_6 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_7 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_8 __attribute__ ((aligned (64)));\n double8 form_form0_cell_integral_otherwise_9 __attribute__ ((aligned (64)));\n double8 t0[4] __attribute__ ((aligned (64)));\n double8 t1[4 * 3] __attribute__ ((aligned (64)));\n double8 t2[4] __attribute__ ((aligned (64)));\n double8 const zero_vec_float64 = { 0.0 };\n\n {\n /* initial slab for 'n_outer' */\n /* */\n }\n {\n int const n_outer = start + -1 * ((7 + 7 * start) / 8);\n\n if (-1 + end + -1 * start >= 0)\n {\n for (int i2 = 0; i2 <= 3; ++i2)\n t2[i2] = zero_vec_float64;\n for (int i0 = 0; i0 <= 3; ++i0)\n {\n for (int i1 = 0; i1 <= 2; ++i1)\n for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)\n t1[(3 * i0 + i1)][n_batch] = dat1[3 * map1[32 * n_outer + 4 * n_batch + i0] + i1];\n for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)\n t0[i0][n_batch] = dat0[map0[32 * n_outer + 4 * n_batch + i0]];\n }\n for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)\n {\n /* no-op (insn=form__start) */\n /* */\n }\n form_form0_cell_integral_otherwise_20 = zero_vec_float64;\n form_form0_cell_integral_otherwise = -1.0 * t1[0];\n form_form0_cell_integral_otherwise_0 = form_form0_cell_integral_otherwise + t1[3];\n form_form0_cell_integral_otherwise_1 = -1.0 * t1[1];\n form_form0_cell_integral_otherwise_2 = form_form0_cell_integral_otherwise_1 + t1[7];\n form_form0_cell_integral_otherwise_3 = -1.0 * t1[2];\n form_form0_cell_integral_otherwise_4 = form_form0_cell_integral_otherwise_3 + t1[11];\n form_form0_cell_integral_otherwise_5 = form_form0_cell_integral_otherwise_1 + t1[10];\n form_form0_cell_integral_otherwise_6 = form_form0_cell_integral_otherwise_3 + t1[8];\n form_form0_cell_integral_otherwise_7 = form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_4 + -1.0 * form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_6;\n form_form0_cell_integral_otherwise_8 = form_form0_cell_integral_otherwise + t1[6];\n form_form0_cell_integral_otherwise_9 = form_form0_cell_integral_otherwise_3 + t1[5];\n form_form0_cell_integral_otherwise_10 = form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_9;\n form_form0_cell_integral_otherwise_11 = form_form0_cell_integral_otherwise_1 + t1[4];\n form_form0_cell_integral_otherwise_12 = form_form0_cell_integral_otherwise + t1[9];\n form_form0_cell_integral_otherwise_13 = form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_6 + -1.0 * form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_9;\n form_form0_cell_integral_otherwise_14 = form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_13 + form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_7 + form_form0_cell_integral_otherwise_8 * (form_form0_cell_integral_otherwise_10 + -1.0 * form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_4);\n #pragma omp simd\n for (int n_batch_simd = start + -8 * n_outer; n_batch_simd <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch_simd)\n form_form0_cell_integral_otherwise_15[n_batch_simd] = fabs(form_form0_cell_integral_otherwise_14[n_batch_simd]);\n for (int form_j = 0; form_j <= 3; ++form_j)\n form_form0_cell_integral_otherwise_22[form_j] = zero_vec_float64;\n for (int form_ip = 0; form_ip <= 3; ++form_ip)\n {\n form_form0_cell_integral_otherwise_18 = zero_vec_float64;\n for (int form_i = 0; form_i <= 3; ++form_i)\n form_form0_cell_integral_otherwise_18 = form_form0_cell_integral_otherwise_18 + form_form0_cell_integral_otherwise_17[4 * form_ip + form_i] * t0[form_i];\n form_form0_cell_integral_otherwise_19 = form_form0_cell_integral_otherwise_16[form_ip] * form_form0_cell_integral_otherwise_15;\n form_form0_cell_integral_otherwise_20 = form_form0_cell_integral_otherwise_20 + form_form0_cell_integral_otherwise_19;\n form_form0_cell_integral_otherwise_21 = form_form0_cell_integral_otherwise_19 * glob0[0] * form_form0_cell_integral_otherwise_18;\n for (int form_j_0 = 0; form_j_0 <= 3; ++form_j_0)\n form_form0_cell_integral_otherwise_22[form_j_0] = form_form0_cell_integral_otherwise_22[form_j_0] + form_form0_cell_integral_otherwise_17[4 * form_ip + form_j_0] * form_form0_cell_integral_otherwise_21;\n }\n form_form0_cell_integral_otherwise_23 = 1.0 / form_form0_cell_integral_otherwise_14;\n form_form0_cell_integral_otherwise_24 = form_form0_cell_integral_otherwise_7 * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_25 = -1.0 * t0[0];\n form_form0_cell_integral_otherwise_26 = form_form0_cell_integral_otherwise_25 + t0[1];\n form_form0_cell_integral_otherwise_27 = (form_form0_cell_integral_otherwise_10 + form_form0_cell_integral_otherwise_11 * -1.0 * form_form0_cell_integral_otherwise_4) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_28 = form_form0_cell_integral_otherwise_25 + t0[2];\n form_form0_cell_integral_otherwise_29 = form_form0_cell_integral_otherwise_13 * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_30 = form_form0_cell_integral_otherwise_25 + t0[3];\n form_form0_cell_integral_otherwise_31 = form_form0_cell_integral_otherwise_29 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_24 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_27 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_32 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_6 + form_form0_cell_integral_otherwise_4 * -1.0 * form_form0_cell_integral_otherwise_8) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_33 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_4 + form_form0_cell_integral_otherwise_9 * -1.0 * form_form0_cell_integral_otherwise_12) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_34 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_9 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_6) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_35 = form_form0_cell_integral_otherwise_34 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_32 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_33 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_36 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_5 + -1.0 * form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_2) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_37 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_11 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_5) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_38 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_2 + -1.0 * form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_11) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_39 = form_form0_cell_integral_otherwise_38 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_36 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_37 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_40 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_38 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_29 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_34) * form_form0_cell_integral_otherwise_20;\n form_form0_cell_integral_otherwise_42 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_37 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_27 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_33) * form_form0_cell_integral_otherwise_20;\n form_form0_cell_integral_otherwise_44 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_36 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_24 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_32) * form_form0_cell_integral_otherwise_20;\n for (int form_j_1 = 0; form_j_1 <= 3; ++form_j_1)\n t2[form_j_1] = t2[form_j_1] + form_form0_cell_integral_otherwise_41[form_j_1] * form_form0_cell_integral_otherwise_40 + form_form0_cell_integral_otherwise_43[form_j_1] * form_form0_cell_integral_otherwise_42 + form_form0_cell_integral_otherwise_22[form_j_1] + form_form0_cell_integral_otherwise_45[form_j_1] * form_form0_cell_integral_otherwise_44;\n for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)\n {\n /* no-op (insn=statement4) */\n /* */\n }\n for (int i3 = 0; i3 <= 3; ++i3)\n for (int n_batch = start + -8 * n_outer; n_batch <= (-8 + end + -8 * n_outer >= 0 ? 7 : -1 + end + -8 * n_outer); ++n_batch)\n dat2[map0[32 * n_outer + 4 * n_batch + i3]] = dat2[map0[32 * n_outer + 4 * n_batch + i3]] + t2[i3][n_batch];\n }\n }\n {\n /* bulk slab for 'n_outer' */\n /* */\n }\n for (int n_outer = 1 + start + -1 * ((7 + 7 * start) / 8); n_outer <= -2 + (7 + end) / 8; ++n_outer)\n {\n for (int i2 = 0; i2 <= 3; ++i2)\n t2[i2] = zero_vec_float64;\n for (int i0 = 0; i0 <= 3; ++i0)\n {\n for (int i1 = 0; i1 <= 2; ++i1)\n for (int n_batch = 0; n_batch <= 7; ++n_batch)\n t1[(3 * i0 + i1)][n_batch] = dat1[3 * map1[32 * n_outer + 4 * n_batch + i0] + i1];\n for (int n_batch = 0; n_batch <= 7; ++n_batch)\n t0[i0][n_batch] = dat0[map0[32 * n_outer + 4 * n_batch + i0]];\n }\n for (int n_batch = 0; n_batch <= 7; ++n_batch)\n {\n /* no-op (insn=form__start) */\n /* */\n }\n form_form0_cell_integral_otherwise_20 = zero_vec_float64;\n form_form0_cell_integral_otherwise = -1.0 * t1[0];\n form_form0_cell_integral_otherwise_0 = form_form0_cell_integral_otherwise + t1[3];\n form_form0_cell_integral_otherwise_1 = -1.0 * t1[1];\n form_form0_cell_integral_otherwise_2 = form_form0_cell_integral_otherwise_1 + t1[7];\n form_form0_cell_integral_otherwise_3 = -1.0 * t1[2];\n form_form0_cell_integral_otherwise_4 = form_form0_cell_integral_otherwise_3 + t1[11];\n form_form0_cell_integral_otherwise_5 = form_form0_cell_integral_otherwise_1 + t1[10];\n form_form0_cell_integral_otherwise_6 = form_form0_cell_integral_otherwise_3 + t1[8];\n form_form0_cell_integral_otherwise_7 = form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_4 + -1.0 * form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_6;\n form_form0_cell_integral_otherwise_8 = form_form0_cell_integral_otherwise + t1[6];\n form_form0_cell_integral_otherwise_9 = form_form0_cell_integral_otherwise_3 + t1[5];\n form_form0_cell_integral_otherwise_10 = form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_9;\n form_form0_cell_integral_otherwise_11 = form_form0_cell_integral_otherwise_1 + t1[4];\n form_form0_cell_integral_otherwise_12 = form_form0_cell_integral_otherwise + t1[9];\n form_form0_cell_integral_otherwise_13 = form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_6 + -1.0 * form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_9;\n form_form0_cell_integral_otherwise_14 = form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_13 + form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_7 + form_form0_cell_integral_otherwise_8 * (form_form0_cell_integral_otherwise_10 + -1.0 * form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_4);\n #pragma omp simd\n for (int n_batch_simd = 0; n_batch_simd <= 7; ++n_batch_simd)\n form_form0_cell_integral_otherwise_15[n_batch_simd] = fabs(form_form0_cell_integral_otherwise_14[n_batch_simd]);\n for (int form_j = 0; form_j <= 3; ++form_j)\n form_form0_cell_integral_otherwise_22[form_j] = zero_vec_float64;\n for (int form_ip = 0; form_ip <= 3; ++form_ip)\n {\n form_form0_cell_integral_otherwise_18 = zero_vec_float64;\n for (int form_i = 0; form_i <= 3; ++form_i)\n form_form0_cell_integral_otherwise_18 = form_form0_cell_integral_otherwise_18 + form_form0_cell_integral_otherwise_17[4 * form_ip + form_i] * t0[form_i];\n form_form0_cell_integral_otherwise_19 = form_form0_cell_integral_otherwise_16[form_ip] * form_form0_cell_integral_otherwise_15;\n form_form0_cell_integral_otherwise_20 = form_form0_cell_integral_otherwise_20 + form_form0_cell_integral_otherwise_19;\n form_form0_cell_integral_otherwise_21 = form_form0_cell_integral_otherwise_19 * glob0[0] * form_form0_cell_integral_otherwise_18;\n for (int form_j_0 = 0; form_j_0 <= 3; ++form_j_0)\n form_form0_cell_integral_otherwise_22[form_j_0] = form_form0_cell_integral_otherwise_22[form_j_0] + form_form0_cell_integral_otherwise_17[4 * form_ip + form_j_0] * form_form0_cell_integral_otherwise_21;\n }\n form_form0_cell_integral_otherwise_23 = 1.0 / form_form0_cell_integral_otherwise_14;\n form_form0_cell_integral_otherwise_24 = form_form0_cell_integral_otherwise_7 * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_25 = -1.0 * t0[0];\n form_form0_cell_integral_otherwise_26 = form_form0_cell_integral_otherwise_25 + t0[1];\n form_form0_cell_integral_otherwise_27 = (form_form0_cell_integral_otherwise_10 + form_form0_cell_integral_otherwise_11 * -1.0 * form_form0_cell_integral_otherwise_4) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_28 = form_form0_cell_integral_otherwise_25 + t0[2];\n form_form0_cell_integral_otherwise_29 = form_form0_cell_integral_otherwise_13 * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_30 = form_form0_cell_integral_otherwise_25 + t0[3];\n form_form0_cell_integral_otherwise_31 = form_form0_cell_integral_otherwise_29 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_24 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_27 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_32 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_6 + form_form0_cell_integral_otherwise_4 * -1.0 * form_form0_cell_integral_otherwise_8) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_33 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_4 + form_form0_cell_integral_otherwise_9 * -1.0 * form_form0_cell_integral_otherwise_12) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_34 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_9 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_6) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_35 = form_form0_cell_integral_otherwise_34 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_32 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_33 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_36 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_5 + -1.0 * form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_2) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_37 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_11 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_5) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_38 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_2 + -1.0 * form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_11) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_39 = form_form0_cell_integral_otherwise_38 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_36 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_37 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_40 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_38 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_29 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_34) * form_form0_cell_integral_otherwise_20;\n form_form0_cell_integral_otherwise_42 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_37 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_27 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_33) * form_form0_cell_integral_otherwise_20;\n form_form0_cell_integral_otherwise_44 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_36 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_24 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_32) * form_form0_cell_integral_otherwise_20;\n for (int form_j_1 = 0; form_j_1 <= 3; ++form_j_1)\n t2[form_j_1] = t2[form_j_1] + form_form0_cell_integral_otherwise_41[form_j_1] * form_form0_cell_integral_otherwise_40 + form_form0_cell_integral_otherwise_43[form_j_1] * form_form0_cell_integral_otherwise_42 + form_form0_cell_integral_otherwise_22[form_j_1] + form_form0_cell_integral_otherwise_45[form_j_1] * form_form0_cell_integral_otherwise_44;\n for (int n_batch = 0; n_batch <= 7; ++n_batch)\n {\n /* no-op (insn=statement4) */\n /* */\n }\n for (int i3 = 0; i3 <= 3; ++i3)\n for (int n_batch = 0; n_batch <= 7; ++n_batch)\n dat2[map0[32 * n_outer + 4 * n_batch + i3]] = dat2[map0[32 * n_outer + 4 * n_batch + i3]] + t2[i3][n_batch];\n }\n {\n /* final slab for 'n_outer' */\n /* */\n }\n {\n int const n_outer = loopy_floor_div_pos_b_int32(-1 + end, 8);\n\n if (-1 + 8 * n_outer + -1 * start >= 0)\n {\n for (int i2 = 0; i2 <= 3; ++i2)\n t2[i2] = zero_vec_float64;\n for (int i0 = 0; i0 <= 3; ++i0)\n {\n for (int i1 = 0; i1 <= 2; ++i1)\n for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)\n t1[(3 * i0 + i1)][n_batch] = dat1[3 * map1[32 * n_outer + 4 * n_batch + i0] + i1];\n for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)\n t0[i0][n_batch] = dat0[map0[32 * n_outer + 4 * n_batch + i0]];\n }\n for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)\n {\n /* no-op (insn=form__start) */\n /* */\n }\n form_form0_cell_integral_otherwise_20 = zero_vec_float64;\n form_form0_cell_integral_otherwise = -1.0 * t1[0];\n form_form0_cell_integral_otherwise_0 = form_form0_cell_integral_otherwise + t1[3];\n form_form0_cell_integral_otherwise_1 = -1.0 * t1[1];\n form_form0_cell_integral_otherwise_2 = form_form0_cell_integral_otherwise_1 + t1[7];\n form_form0_cell_integral_otherwise_3 = -1.0 * t1[2];\n form_form0_cell_integral_otherwise_4 = form_form0_cell_integral_otherwise_3 + t1[11];\n form_form0_cell_integral_otherwise_5 = form_form0_cell_integral_otherwise_1 + t1[10];\n form_form0_cell_integral_otherwise_6 = form_form0_cell_integral_otherwise_3 + t1[8];\n form_form0_cell_integral_otherwise_7 = form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_4 + -1.0 * form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_6;\n form_form0_cell_integral_otherwise_8 = form_form0_cell_integral_otherwise + t1[6];\n form_form0_cell_integral_otherwise_9 = form_form0_cell_integral_otherwise_3 + t1[5];\n form_form0_cell_integral_otherwise_10 = form_form0_cell_integral_otherwise_5 * form_form0_cell_integral_otherwise_9;\n form_form0_cell_integral_otherwise_11 = form_form0_cell_integral_otherwise_1 + t1[4];\n form_form0_cell_integral_otherwise_12 = form_form0_cell_integral_otherwise + t1[9];\n form_form0_cell_integral_otherwise_13 = form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_6 + -1.0 * form_form0_cell_integral_otherwise_2 * form_form0_cell_integral_otherwise_9;\n form_form0_cell_integral_otherwise_14 = form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_13 + form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_7 + form_form0_cell_integral_otherwise_8 * (form_form0_cell_integral_otherwise_10 + -1.0 * form_form0_cell_integral_otherwise_11 * form_form0_cell_integral_otherwise_4);\n #pragma omp simd\n for (int n_batch_simd = 0; n_batch_simd <= -1 + end + -8 * n_outer; ++n_batch_simd)\n form_form0_cell_integral_otherwise_15[n_batch_simd] = fabs(form_form0_cell_integral_otherwise_14[n_batch_simd]);\n for (int form_j = 0; form_j <= 3; ++form_j)\n form_form0_cell_integral_otherwise_22[form_j] = zero_vec_float64;\n for (int form_ip = 0; form_ip <= 3; ++form_ip)\n {\n form_form0_cell_integral_otherwise_18 = zero_vec_float64;\n for (int form_i = 0; form_i <= 3; ++form_i)\n form_form0_cell_integral_otherwise_18 = form_form0_cell_integral_otherwise_18 + form_form0_cell_integral_otherwise_17[4 * form_ip + form_i] * t0[form_i];\n form_form0_cell_integral_otherwise_19 = form_form0_cell_integral_otherwise_16[form_ip] * form_form0_cell_integral_otherwise_15;\n form_form0_cell_integral_otherwise_20 = form_form0_cell_integral_otherwise_20 + form_form0_cell_integral_otherwise_19;\n form_form0_cell_integral_otherwise_21 = form_form0_cell_integral_otherwise_19 * glob0[0] * form_form0_cell_integral_otherwise_18;\n for (int form_j_0 = 0; form_j_0 <= 3; ++form_j_0)\n form_form0_cell_integral_otherwise_22[form_j_0] = form_form0_cell_integral_otherwise_22[form_j_0] + form_form0_cell_integral_otherwise_17[4 * form_ip + form_j_0] * form_form0_cell_integral_otherwise_21;\n }\n form_form0_cell_integral_otherwise_23 = 1.0 / form_form0_cell_integral_otherwise_14;\n form_form0_cell_integral_otherwise_24 = form_form0_cell_integral_otherwise_7 * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_25 = -1.0 * t0[0];\n form_form0_cell_integral_otherwise_26 = form_form0_cell_integral_otherwise_25 + t0[1];\n form_form0_cell_integral_otherwise_27 = (form_form0_cell_integral_otherwise_10 + form_form0_cell_integral_otherwise_11 * -1.0 * form_form0_cell_integral_otherwise_4) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_28 = form_form0_cell_integral_otherwise_25 + t0[2];\n form_form0_cell_integral_otherwise_29 = form_form0_cell_integral_otherwise_13 * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_30 = form_form0_cell_integral_otherwise_25 + t0[3];\n form_form0_cell_integral_otherwise_31 = form_form0_cell_integral_otherwise_29 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_24 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_27 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_32 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_6 + form_form0_cell_integral_otherwise_4 * -1.0 * form_form0_cell_integral_otherwise_8) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_33 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_4 + form_form0_cell_integral_otherwise_9 * -1.0 * form_form0_cell_integral_otherwise_12) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_34 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_9 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_6) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_35 = form_form0_cell_integral_otherwise_34 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_32 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_33 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_36 = (form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_5 + -1.0 * form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_2) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_37 = (form_form0_cell_integral_otherwise_12 * form_form0_cell_integral_otherwise_11 + -1.0 * form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_5) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_38 = (form_form0_cell_integral_otherwise_0 * form_form0_cell_integral_otherwise_2 + -1.0 * form_form0_cell_integral_otherwise_8 * form_form0_cell_integral_otherwise_11) * form_form0_cell_integral_otherwise_23;\n form_form0_cell_integral_otherwise_39 = form_form0_cell_integral_otherwise_38 * form_form0_cell_integral_otherwise_30 + form_form0_cell_integral_otherwise_36 * form_form0_cell_integral_otherwise_26 + form_form0_cell_integral_otherwise_37 * form_form0_cell_integral_otherwise_28;\n form_form0_cell_integral_otherwise_40 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_38 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_29 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_34) * form_form0_cell_integral_otherwise_20;\n form_form0_cell_integral_otherwise_42 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_37 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_27 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_33) * form_form0_cell_integral_otherwise_20;\n form_form0_cell_integral_otherwise_44 = (form_form0_cell_integral_otherwise_39 * form_form0_cell_integral_otherwise_36 + form_form0_cell_integral_otherwise_31 * form_form0_cell_integral_otherwise_24 + form_form0_cell_integral_otherwise_35 * form_form0_cell_integral_otherwise_32) * form_form0_cell_integral_otherwise_20;\n for (int form_j_1 = 0; form_j_1 <= 3; ++form_j_1)\n t2[form_j_1] = t2[form_j_1] + form_form0_cell_integral_otherwise_41[form_j_1] * form_form0_cell_integral_otherwise_40 + form_form0_cell_integral_otherwise_43[form_j_1] * form_form0_cell_integral_otherwise_42 + form_form0_cell_integral_otherwise_22[form_j_1] + form_form0_cell_integral_otherwise_45[form_j_1] * form_form0_cell_integral_otherwise_44;\n for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)\n {\n /* no-op (insn=statement4) */\n /* */\n }\n for (int i3 = 0; i3 <= 3; ++i3)\n for (int n_batch = 0; n_batch <= -1 + end + -8 * n_outer; ++n_batch)\n dat2[map0[32 * n_outer + 4 * n_batch + i3]] = dat2[map0[32 * n_outer + 4 * n_batch + i3]] + t2[i3][n_batch];\n }\n }\n}", "meta": {"hexsha": "9357e02b06cfd14e0c2267158a3906e2ed043ad4", "size": 33100, "ext": "c", "lang": "C", "max_stars_repo_path": "cached_kernels/0ee8f4736d289edd2859eaf7303628_p10082.c", "max_stars_repo_name": "sv2518/Vect-Firedrake-Likwid", "max_stars_repo_head_hexsha": "45af935843217475f45a22f69d7f19965422c923", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cached_kernels/0ee8f4736d289edd2859eaf7303628_p10082.c", "max_issues_repo_name": "sv2518/Vect-Firedrake-Likwid", "max_issues_repo_head_hexsha": "45af935843217475f45a22f69d7f19965422c923", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cached_kernels/0ee8f4736d289edd2859eaf7303628_p10082.c", "max_forks_repo_name": "sv2518/Vect-Firedrake-Likwid", "max_forks_repo_head_hexsha": "45af935843217475f45a22f69d7f19965422c923", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 96.783625731, "max_line_length": 419, "alphanum_fraction": 0.7987915408, "num_tokens": 9673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191214879991, "lm_q2_score": 0.38491214448393357, "lm_q1q2_score": 0.27291007053206034}} {"text": "\n/*\n* -----------------------------------------------------------------\n* pmsr_lib.c\n* Pairwise Mixing Stirred Reactor Library\n* Version: 2.0\n* Last Update: Oct 1, 2019\n* \n* This is a computational library with routines to implement\n* a Pairwise Mixing Stirred Reactor (PMSR) model.\n* ----------------------------------------------------------------- \n* Programmer: Americo Barbosa da Cunha Junior\n* americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n* Copyright (c) 2019 by Americo Barbosa da Cunha Junior\n* -----------------------------------------------------------------\n*/\n\n\n\n\n#include \n#include \n#include \n#include \n\n#include \"../include/pmsr_lib.h\"\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_title\n*\n* This function prints the program title on the screen.\n*\n* last update: Oct 20, 2009\n* -----------------------------------------------------------------\n*/\n\nvoid pmsr_title()\n{\n time_t curtime = time (NULL);\n struct tm *loctime = localtime (&curtime);\n \n printf(\"\\n\");\n printf(\"=============================================\");\n printf(\"\\n Pairwise Mixing Stirred Reactor --- PMSR\\n\");\n printf(\"\\n by\");\n printf(\"\\n Americo Barbosa da Cunha Junior\");\n printf(\"\\n americo.cunhajr@gmail.com\\n\");\n printf(\"\\n Date:\");\n printf(\"\\n %s\", asctime(loctime) );\n printf(\"=============================================\");\n printf(\"\\n\");\n \n return;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_input\n*\n* This function receives PMSR parameters from user\n* and returns GSL_SUCCESS if there is no error.\n*\n* Input:\n* seed - RNG seed\n* Np - # of particles\n* Ndt - # of time steps\n* t0 - initial time\n* delta_t - time step\n* tau_res - residence time\n* tau_mix - mixture time\n* tau_pair - pairwise time\n*\n* Output:\n* success or error\n*\n* last update: Oct 1, 2019\n* -----------------------------------------------------------------\n*/\n\nint pmsr_input(unsigned long int *seed,unsigned int *Np,unsigned int *Ndt,\n\t double *t0,double *delta_t,double *tau_res,double *tau_mix,\n\t double *tau_pair,double *Tmax,double *Tmin,\n double *atol,double *rtol)\n{\n printf(\"\\n Input PMSR parameters:\\n\");\n\n printf(\"\\n RNG seed:\");\n scanf(\"%lu\", seed);\n printf(\"\\n %lu\\n\", *seed);\n if( *seed <= 0 )\n\t*seed = time(NULL);\n \n printf(\"\\n # of particles:\");\n scanf(\"%d\", Np);\n printf(\"\\n %d\\n\", *Np);\n if( *Np <= 0 || *Np % 2 != 0 )\n\tGSL_ERROR(\" Np must be a positive even integer\",GSL_EINVAL);\n \n printf(\"\\n # of time steps:\");\n scanf(\"%d\", Ndt);\n printf(\"\\n %d\\n\", *Ndt);\n if( *Ndt <= 0 )\n\tGSL_ERROR(\" Ndt must be a positive integer\",GSL_EINVAL);\n\n printf(\"\\n initial time:\");\n scanf(\"%lf\", t0);\n printf(\"\\n %+.1e\\n\", *t0);\n if( *t0 < 0.0 )\n\tGSL_ERROR(\" t0 must be a grather than zero\",GSL_EINVAL);\n \n printf(\"\\n time step:\");\n scanf(\"%lf\", delta_t);\n printf(\"\\n %+.1e\\n\", *delta_t);\n if( *delta_t <= 0.0 )\n\tGSL_ERROR(\" delta_t must be a grather than zero\",GSL_EINVAL);\n\n printf(\"\\n residence time:\");\n scanf(\"%lf\", tau_res);\n printf(\"\\n %+.1e\\n\", *tau_res);\n if( *tau_res <= 0.0 )\n\tGSL_ERROR(\" tau_res must be a grather than zero\",GSL_EINVAL);\n \n printf(\"\\n mixture time:\");\n scanf(\"%lf\", tau_mix);\n printf(\"\\n %+.1e\\n\", *tau_mix);\n if( *tau_mix <= 0.0 )\n\tGSL_ERROR(\" tau_mix must be a grather than zero\",GSL_EINVAL);\n \n printf(\"\\n pairwise time:\");\n scanf(\"%lf\", tau_pair);\n printf(\"\\n %+.1e\\n\", *tau_pair);\n if( *tau_pair <= 0.0 )\n\tGSL_ERROR(\" tau_pair must be a grather than zero\",GSL_EINVAL);\n \n printf(\"\\n temperature upper bound:\");\n scanf(\"%lf\", Tmax);\n printf(\"\\n %+.1e\\n\", *Tmax);\n if( *Tmax <= 0.0 )\n\tGSL_ERROR(\" Tmax must be a grather than zero\",GSL_EINVAL);\n \n printf(\"\\n temperature lower bound:\");\n scanf(\"%lf\", Tmin);\n printf(\"\\n %+.1e\\n\", *Tmin);\n if( *Tmin < 0.0 || *Tmin > *Tmax )\n\tGSL_ERROR(\" Tmin must be less than Tmax and a grather than zero\",GSL_EINVAL);\n\n printf(\"\\n absolute tolerance:\");\n scanf(\"%lf\", atol);\n printf(\"\\n %+.1e\\n\", *atol);\n if( *atol <= 0.0 )\n\tGSL_ERROR(\" atol must be a grather than zero\",GSL_EINVAL);\n\n printf(\"\\n relative tolerance:\");\n scanf(\"%lf\", rtol);\n printf(\"\\n %+.1e\\n\", *rtol);\n if( *rtol <= 0.0 )\n\tGSL_ERROR(\" rtol must be a grather than zero\",GSL_EINVAL);\n \n return GSL_SUCCESS;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_alloc\n*\n* This function allocates an internal memory block for\n* pmsr workspace struct. If successful, returns a pointer to\n* pmsr_wrk. If a startup error occurs returns NULL.\n*\n* last update: Nov 5, 2009\n* -----------------------------------------------------------------\n*/\n\npmsr_wrk *pmsr_alloc()\n{\n pmsr_wrk *pmsr = NULL;\n \n /* memory allocation for pmsr struct */\n pmsr = (pmsr_wrk *) malloc(sizeof(pmsr_wrk));\n if ( pmsr == NULL )\n return NULL;\n \n /* setting pmsr_wrk elements */\n pmsr->pmsr_idx = NULL;\n pmsr->pmsr_ps = NULL;\n \n return pmsr;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_init\n*\n* This function initiates the system of particles\n* with an initial composition phi.\n*\n* Input:\n* Np - # of particles\n* Neq - # of equations\n* pmsr - pointer to a struct pmsr\n*\n* Output:\n* success or error\n*\n* last update: Sep 22, 2009\n* -----------------------------------------------------------------\n*/\n\nint pmsr_init(int Np,int Neq,pmsr_wrk *pmsr)\n{\n int i;\n \n /* checking if pmsr is NULL */\n if ( pmsr == NULL )\n return GSL_EINVAL;\n \n /* memory allocation for the system of particles */\n pmsr->pmsr_ps = (gsl_vector **) malloc(Np*sizeof(gsl_vector *));\n if ( pmsr->pmsr_ps == NULL )\n\treturn GSL_ENOMEM;\n \n for ( i = 0; i < Np; i++ )\n pmsr->pmsr_ps[i] = gsl_vector_calloc(Neq);\n \n /* memory allocation for the vector of indices */\n pmsr->pmsr_idx = (int *) malloc(Np*sizeof(int));\n if ( pmsr->pmsr_idx == NULL )\n {\n\tfor ( i = 0; i < Np; i++ )\n\t{\n\t gsl_vector_free(pmsr->pmsr_ps[i]);\n\t pmsr->pmsr_ps[i] = NULL;\n\t}\n\t\n free(pmsr->pmsr_ps);\n\tpmsr->pmsr_ps = NULL;\n \n\treturn GSL_ENOMEM;\n }\n \n /* initial configuration of particles pairwise */\n for ( i = 0; i < Np; i++ )\n pmsr->pmsr_idx[i] = i;\n \n return GSL_SUCCESS;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_free\n*\n* This routine frees the memory allocated by pmsr_alloc.\n*\n* Input:\n* pmsr - pointer to a struct pmsr\n*\n* Output:\n* void\n*\n* last update: May 10, 2009\n* -----------------------------------------------------------------\n*/\n\nvoid pmsr_free(int Np,void **pmsr_bl)\n{\n int i;\n pmsr_wrk *pmsr = NULL;\n \n /* checking if pmsr_bl is NULL */\n if ( *pmsr_bl == NULL )\n return;\n \n /* checking if Np is positive */\n if ( Np <= 0 )\n return;\n \n pmsr = (pmsr_wrk *) (*pmsr_bl);\n \n /* releasing pmsr elements */\n if ( pmsr->pmsr_ps != NULL )\n {\n\tfor ( i = 0; i < Np; i++ )\n\t if ( pmsr->pmsr_ps[i] != NULL )\n\t {\n\t gsl_vector_free(pmsr->pmsr_ps[i]);\n\t pmsr->pmsr_ps[i] = NULL;\n\t }\n\t/* releasing pmsr struct */\n\tfree(pmsr->pmsr_ps);\n\tpmsr->pmsr_ps = NULL;\n }\n \n if ( pmsr->pmsr_idx != NULL )\n {\n\tfree(pmsr->pmsr_idx);\n\tpmsr->pmsr_idx = NULL;\n }\n \n free(*pmsr_bl);\n *pmsr_bl = NULL;\n \n return;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_set_all\n*\n* This function sets the system of particles with a given\n* composition phi.\n*\n* Input:\n* pmsr - pointer to a struct pmsr\n* phi - composition\n*\n* Output:\n* success or error\n*\n* last update: Mar 2, 2010\n* -----------------------------------------------------------------\n*/\n\nvoid pmsr_set_all(int Np,gsl_vector *phi,pmsr_wrk *pmsr)\n{\n int i;\n \n /* setting all particles with an initial phi */\n for ( i = 0; i < Np; i++ )\n gsl_vector_memcpy(pmsr->pmsr_ps[i],phi);\n \n return;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_Nexc\n*\n* This function computes the number of particles to be exchanged,\n* Nexc, corresponding to outflow/inflow particles.\n*\n* Nexc = ceil( 1/2 Np delta_t/taus_res )\n*\n* Input:\n* Np - # of particles\n* delta_t - time step\n* tau_res - residence time\n*\n* Output:\n* Nexc - # of particles to be exchanged\n*\n* last update: Feb 12, 2009\n* -----------------------------------------------------------------\n*/\n\nint pmsr_Nexc(int Np,double delta_t,double tau_res)\n{ \n return ceil( (Np/2)*(delta_t/tau_res) );\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_Npair\n*\n* This function computes the number of particles to be pairwised,\n* Npair, corresponding to pairing particles.\n*\n* Npair = ceil( 1/2 Np delta_t/taus_pair )\n*\n* Input:\n* Np - # of particles\n* delta_t - time step\n* tau_pair - pairwise time\n*\n* Output:\n* Npair - # of particles to be pairwised\n*\n* last update: Feb 12, 2009\n* -----------------------------------------------------------------\n*/\n\nint pmsr_Npair(int Np,double delta_t,double tau_pair)\n{ \n return ceil( (Np/2)*(delta_t/tau_pair) );\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_meanvar\n*\n* This function computes the mean and the variance\n* of a particular property in a system of particles\n* using the algorithm of Knuth/Welford.\n*\n* Ref.:\n* D. E. Knuth (1998)\n* The Art of Computer Programming,\n* volume 2: Seminumerical Algorithms\n* 3rd ed., Addison-Wesley.\n* \n* B. P. Welford (1962).\n* \"Note on a method for calculating corrected sums\n* of squares and products\". Technometrics 4(3):419–420\n*\n* Input:\n* Np - # of particles\n* k - property index\n* ps - system of particle\n*\n* Output:\n* mean - propertie mean value\n* var - propertie variance\n*\n* last update: Mar 4, 2010\n* -----------------------------------------------------------------\n*/\n\nvoid pmsr_meanvar(int Np,int k,gsl_vector **ps,double *mean,double *var)\n{\n int i;\n double M = 0.0;\n double S = 0.0;\n double delta = 0.0;\n\n for ( i = 0; i < Np; i++ )\n {\n delta = ps[i]->data[k] - M;\n\tM += delta/(double) (i+1);\n S += delta*(ps[i]->data[k] - M);\n }\n\n /* mean */\n *mean = M;\n \n /* variance */\n *var = S/(double) (i-1);\n \n return;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_mixture\n*\n* This function computes the mixture step in PMSR model.\n*\n* Input:\n* Np - # of particles\n* Neq - # of equations\n* delta_t - time step\n* tau_mix - mixture time\n* idx - particles index vector\n*\n* Output:\n* ps - system of particles\n*\n* last update: Mar 9, 2009\n* -----------------------------------------------------------------\n*/\n\nvoid pmsr_mixture(int Np,int Neq,double delta_t,double tau_mix,\n\t\t\t\t\t int *idx,gsl_vector **ps)\n{\n int k, i;\n double sum, dif;\n \n /* particle index */\n k = 0;\n \n /* mixture of the Np particles */\n while( k < Np/2 )\n {\n /* mixture of two particles */\n for ( i = 0; i < Neq; i++ )\n {\n /* sum = 1/2(phi_p0 + phi_q0) */\n sum = 0.5*( ps[idx[2*k]]->data[i] + ps[idx[2*k+1]]->data[i] );\n \n /* dif = 1/2(phi_p0 - phi_q0) */\n dif = 0.5*( ps[idx[2*k]]->data[i] - ps[idx[2*k+1]]->data[i] );\n \n /* phi_p = dif.exp(-2/tau delta_t) + sum */\n ps[idx[2*k]]->data[i] =\n dif*exp(-(2.0/tau_mix)*delta_t) + sum;\n \n /* phi_q = -dif.exp(-2/tau delta_t) + sum */\n ps[idx[2*k+1]]->data[i] =\n -dif*exp(-(2.0/tau_mix)*delta_t) + sum;\n }\n k++;\n }\n \n return;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* pmsr_iops\n*\n* This function executes the inflow/outflow,\n* pairwise and shuflle steps.\n*\n* Input:\n* Np - # of particles\n* Nexc - # of particles to be exchanged\n* Npair - # of particles to be pairwised\n* rand - rng workspace\n* phi - inflow composition\n*\n* Output:\n* p - system of particles\n* pairs - pairs of particles index\n*\n* last update: Mar 1, 2010\n* -----------------------------------------------------------------\n*/\n\nvoid pmsr_iops(int Np,int Nexc,int Npair,gsl_rng *rand,\n\t\t\t\t gsl_vector *phi,pmsr_wrk *pmsr)\n{\n int i;\n int idx1[Nexc+Npair];\n int idx2[2*(Nexc+Npair)];\n int *aux = NULL;\n \n /* memory allocation */\n aux = (int *) malloc((Np/2)*sizeof(int));\n \n /* setting aux vector with integers from 0 to Np/2-1 */\n for ( i = 0; i < Np/2; i++ )\n aux[i] = i;\n \n /* selecting Nexc + Npair pairs at random */\n gsl_ran_choose(rand,idx1,Nexc+Npair,aux,Np/2,sizeof(int));\n for ( i = 0; i < Nexc + Npair; i++ )\n {\n idx2[2*i ] = pmsr->pmsr_idx[2*idx1[i] ];\n idx2[2*i+1] = pmsr->pmsr_idx[2*idx1[i]+1];\n }\n \n \n /* changing composition of Nexc pairs (inflow / outflow) */\n for ( i = 0; i < Nexc; i++ )\n {\n gsl_vector_memcpy(pmsr->pmsr_ps[idx2[2*i] ],phi);\n gsl_vector_memcpy(pmsr->pmsr_ps[idx2[2*i+1]],phi);\n }\n \n /* shuffling the selected pairs */\n gsl_ran_shuffle(rand,idx2,2*(Nexc+Npair),sizeof(int));\n \n /* setting the new partners in the system */\n for ( i = 0; i < Nexc + Npair; i++ )\n {\n pmsr->pmsr_idx[2*idx1[i] ] = idx2[2*i ];\n pmsr->pmsr_idx[2*idx1[i]+1] = idx2[2*i+1];\n }\n \n /* releasing allocated memory */\n free(aux);\n aux = NULL;\n \n return;\n}\n/*----------------------------------------------------------------*/\n\n", "meta": {"hexsha": "dbc1d75578e5591b2872a36617f0ce49e5236732", "size": 14831, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/src/pmsr_lib.c", "max_stars_repo_name": "americocunhajr/CRFlowLib", "max_stars_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-29T12:56:14.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-29T12:56:14.000Z", "max_issues_repo_path": "CRFlowLib-2.0/src/pmsr_lib.c", "max_issues_repo_name": "americocunhajr/CRFlowLib", "max_issues_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CRFlowLib-2.0/src/pmsr_lib.c", "max_forks_repo_name": "americocunhajr/CRFlowLib", "max_forks_repo_head_hexsha": "35b67f798c1c33118c028691f42b98ba06220eeb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-15T03:57:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T01:44:13.000Z", "avg_line_length": 24.2733224223, "max_line_length": 78, "alphanum_fraction": 0.4623423909, "num_tokens": 4157, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.49218813572079556, "lm_q1q2_score": 0.2729037844611154}} {"text": "/**\n * @file zheevd.c\n *\n * PLASMA computational routines\n * Release Date: November, 15th 2009\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 * @author Hatem Ltaief\n * @date 2010-11-15\n * @precisions normal z -> s d c\n *\n **/\n#include \n#include \"common.h\"\n/***************************************************************************//**\n *\n * @ingroup PLASMA_Complex64_t\n *\n * PLASMA_zheevd - Computes all eigenvalues and, optionally,\n * eigenvectors of a complex Hermitian matrix A. The matrix A is\n * preliminary reduced to tridiagonal form using a two-stage\n * approach:\n * First stage: reduction to band tridiagonal form;\n * Second stage: reduction from band to tridiagonal form.\n *\n *******************************************************************************\n *\n * @param[in] jobz\n * Intended usage:\n * = PlasmaNoVec: computes eigenvalues only;\n * = PlasmaVec: computes eigenvalues and eigenvectors.\n *\n * @param[in] uplo\n * Specifies whether the matrix A is upper triangular or\n * lower triangular:\n * = PlasmaUpper: Upper triangle of A is stored;\n * = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in] N\n * The order of the matrix A. N >= 0.\n *\n * @param[in,out] A\n * On entry, the symmetric (or Hermitian) matrix A.\n * If uplo = PlasmaUpper, the leading N-by-N upper triangular\n * part of A contains the upper triangular part of the matrix\n * A, and the strictly lower triangular part of A is not\n * referenced.\n * If uplo = PlasmaLower, the leading N-by-N lower triangular\n * part of A contains the lower triangular part of the matrix\n * A, and the strictly upper triangular part of A is not\n * referenced.\n * On exit, the lower triangle (if uplo = PlasmaLower) or the\n * upper triangle (if uplo = PlasmaUpper) of A, including the\n * diagonal, is destroyed.\n *\n * @param[in] LDA\n * The leading dimension of the array A. LDA >= max(1,N).\n *\n * @param[out] W\n * On exit, if info = 0, the eigenvalues.\n *\n * @param[in, out] descT\n * On entry, descriptor as return by PLASMA_Alloc_Workspace_zheevd\n * On exit, contains auxiliary factorization data.\n *\n * @param[out] Q\n * On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.\n *\n * @param[in] LDQ\n * The leading dimension of the array Q. LDQ >= max(1,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 * \\retval >0 if INFO = i, the algorithm failed to converge; i\n * off-diagonal elements of an intermediate tridiagonal\n * form did not converge to zero.\n *\n *******************************************************************************\n *\n * @sa PLASMA_zheevd_Tile\n * @sa PLASMA_zheevd_Tile_Async\n * @sa PLASMA_cheevd\n * @sa PLASMA_dsyev\n * @sa PLASMA_ssyev\n *\n ******************************************************************************/\nint PLASMA_zheevd(PLASMA_enum jobz, PLASMA_enum uplo, int N,\n PLASMA_Complex64_t *A, int LDA,\n double *W,\n PLASMA_desc *descT,\n PLASMA_Complex64_t *Q, int LDQ)\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_error(\"PLASMA_zheevd\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n\n /* Check input arguments */\n if (jobz != PlasmaNoVec && jobz != PlasmaVec) {\n plasma_error(\"PLASMA_zheevd\", \"illegal value of jobz\");\n return -1;\n }\n if (uplo != PlasmaLower && uplo != PlasmaUpper) {\n plasma_error(\"PLASMA_zheevd\", \"illegal value of uplo\");\n return -2;\n }\n if (N < 0) {\n plasma_error(\"PLASMA_zheevd\", \"illegal value of N\");\n return -3;\n }\n if (LDA < max(1, N)) {\n plasma_error(\"PLASMA_zheevd\", \"illegal value of LDA\");\n return -5;\n }\n if (LDQ < max(1, N)) {\n plasma_error(\"PLASMA_zheevd\", \"illegal value of LDQ\");\n return -9;\n }\n\n /* Quick return */\n if (N == 0)\n return PLASMA_SUCCESS;\n\n /* Tune NB & IB depending on N; Set NBNB */\n status = plasma_tune(PLASMA_FUNC_ZHEEVD, N, N, 0);\n if (status != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_zheevd\", \"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_zooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request,\n plasma_desc_mat_free(&(descA)) );\n } else {\n plasma_ziplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N,\n sequence, &request);\n }\n\n /* Call the tile interface */\n PLASMA_zheevd_Tile_Async(jobz, uplo, &descA, W, descT, Q, LDQ, sequence, &request);\n\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooptile2lap( descA, A, NB, NB, LDA, N, sequence, &request);\n plasma_dynamic_sync();\n plasma_desc_mat_free(&descA);\n } else {\n plasma_ziptile2lap( 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 * @ingroup PLASMA_Complex64_t_Tile\n *\n * PLASMA_zheevd_Tile - Computes all eigenvalues and, optionally, eigenvectors of a\n * complex Hermitian matrix A using a two-stage approach:\n * First stage: reduction to band tridiagonal form;\n * Second stage: reduction from band to tridiagonal form.\n *\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] jobz\n * Intended usage:\n * = PlasmaNoVec: computes eigenvalues only;\n * = PlasmaVec: computes eigenvalues and eigenvectors.\n *\n * @param[in] uplo\n * Specifies whether the matrix A is upper triangular or\n * lower triangular:\n * = PlasmaUpper: Upper triangle of A is stored;\n * = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in,out] A\n * On entry, the symmetric (or Hermitian) matrix A.\n * If uplo = PlasmaUpper, the leading N-by-N upper triangular\n * part of A contains the upper triangular part of the matrix\n * A, and the strictly lower triangular part of A is not\n * referenced.\n * If UPLO = 'L', the leading N-by-N lower triangular part of\n * A contains the lower triangular part of the matrix A, and\n * the strictly upper triangular part of A is not referenced.\n * On exit, if jobz = PlasmaVec, then if return value = 0, A\n * contains the orthonormal eigenvectors of the matrix A.\n * If jobz = PlasmaNoVec, then on exit the lower triangle (if\n * uplo = PlasmaLower) or the upper triangle (if uplo =\n * PlasmaUpper) of A, including the diagonal, is destroyed.*\n *\n * @param[out] W\n * On exit, if info = 0, the eigenvalues.\n *\n * @param[in,out] T\n * On entry, descriptor as return by\n * PLASMA_Alloc_Workspace_zheevd\n * On exit, contains auxiliary factorization data.\n *\n * @param[out] Q\n * On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.\n *\n * @param[in] LDQ\n * The leading dimention of the eigenvectors matrix Q. LDQ >= max(1,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 * \\retval >0 if INFO = i, the algorithm failed to converge; i\n * off-diagonal elements of an intermediate tridiagonal\n * form did not converge to zero.\n *\n *******************************************************************************\n *\n * @sa PLASMA_zheevd_Tile\n * @sa PLASMA_zheevd_Tile_Async\n * @sa PLASMA_cheevd\n * @sa PLASMA_dsyev\n * @sa PLASMA_ssyev\n *\n ******************************************************************************/\nint PLASMA_zheevd_Tile(PLASMA_enum jobz, PLASMA_enum uplo,\n PLASMA_desc *A, double *W,\n PLASMA_desc *T, PLASMA_Complex64_t *Q, int LDQ)\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_zheevd_Tile\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n plasma_sequence_create(plasma, &sequence);\n PLASMA_zheevd_Tile_Async(jobz, uplo, A, W, T, Q, LDQ, 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 PLASMA_Complex64_t_Tile_Async\n *\n * PLASMA_zheevd_Tile_Async - Computes all eigenvalues and,\n * optionally, eigenvectors of a complex Hermitian matrix A using a\n * two-stage approach:\n * First stage: reduction to band tridiagonal form;\n * Second stage: reduction from band to tridiagonal form.\n *\n * May return before the computation is finished.\n * Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] jobz\n * Intended usage:\n * = PlasmaNoVec: computes eigenvalues only;\n * = PlasmaVec: computes eigenvalues and eigenvectors.\n *\n * @param[in] uplo\n * Specifies whether the matrix A is upper triangular or\n * lower triangular:\n * = PlasmaUpper: Upper triangle of A is stored;\n * = PlasmaLower: Lower triangle of A is stored.\n *\n * @param[in,out] A\n * On entry, the symmetric (or Hermitian) matrix A.\n * If uplo = PlasmaUpper, the leading N-by-N upper triangular\n * part of A contains the upper triangular part of the matrix\n * A, and the strictly lower triangular part of A is not\n * referenced.\n * If UPLO = 'L', the leading N-by-N lower triangular part of\n * A contains the lower triangular part of the matrix A, and\n * the strictly upper triangular part of A is not referenced.\n * On exit, if jobz = PlasmaVec, then if return value = 0, A\n * contains the orthonormal eigenvectors of the matrix A.\n * If jobz = PlasmaNoVec, then on exit the lower triangle (if\n * uplo = PlasmaLower) or the upper triangle (if uplo =\n * PlasmaUpper) of A, including the diagonal, is destroyed.*\n *\n * @param[out] W\n * On exit, if info = 0, the eigenvalues.\n *\n * @param[in,out] T\n * On entry, descriptor as return by\n * PLASMA_Alloc_Workspace_zheevd\n * On exit, contains auxiliary factorization data.\n *\n * @param[out] Q\n * On exit, if jobz = PlasmaVec and info = 0, the eigenvectors.\n *\n * @param[in] LDQ\n * The leading dimention of the eigenvectors matrix Q. LDQ >= max(1,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_zheevd\n * @sa PLASMA_zheevd_Tile\n * @sa PLASMA_cheevd_Tile_Async\n * @sa PLASMA_dsyev_Tile_Async\n * @sa PLASMA_ssyev_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_zheevd_Tile_Async(PLASMA_enum jobz, PLASMA_enum uplo,\n PLASMA_desc *A,\n double *W,\n PLASMA_desc *T,\n PLASMA_Complex64_t *Q, int LDQ,\n PLASMA_sequence *sequence, PLASMA_request *request)\n{\n plasma_context_t *plasma;\n PLASMA_desc descA;\n PLASMA_desc descT;\n PLASMA_desc descQ;\n PLASMA_Complex64_t *AB;\n double *E;\n int N;\n int NB;\n int LDAB;\n int status;\n\n plasma = plasma_context_self();\n if (plasma == NULL) {\n plasma_fatal_error(\"PLASMA_zheevd_Tile_Async\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n if (sequence == NULL) {\n plasma_fatal_error(\"PLASMA_zheevd_Tile_Async\", \"NULL sequence\");\n return PLASMA_ERR_UNALLOCATED;\n }\n if (request == NULL) {\n plasma_fatal_error(\"PLASMA_zheevd_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_zheevd_Tile_Async\", \"invalid 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_zheevd_Tile_Async\", \"invalid descriptor\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n } else {\n descT = *T;\n }\n /* Check input arguments */\n if (jobz != PlasmaNoVec && jobz != PlasmaVec) {\n plasma_error(\"PLASMA_zheevd_Tile_Async\", \"illegal value of jobz\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n if (uplo != PlasmaLower && uplo != PlasmaUpper) {\n plasma_error(\"PLASMA_zheevd_Tile_Async\", \"illegal value of uplo\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n if (descA.m != descA.n) {\n plasma_error(\"PLASMA_zheevd_Tile_Async\", \"matrix need to be square\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n if (descA.nb != descA.mb) {\n plasma_error(\"PLASMA_zheevd_Tile_Async\", \"only square tiles supported\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n\n N = descA.m;\n NB = min(descA.mb,descA.m);\n LDAB = 2*NB+1;\n\n /* Allocate workspace for band storage of the band matrix A and for the off diagonal after tridiagonalisation */\n AB = (PLASMA_Complex64_t *)plasma_shared_alloc(plasma, LDAB*N, PlasmaComplexDouble);\n memset( AB, 0, LDAB * N * sizeof(PLASMA_Complex64_t) );\n if (AB == NULL) {\n plasma_error(\"PLASMA_zheevd_Tile_Async\", \"plasma_shared_alloc(AB) failed\");\n plasma_shared_free(plasma, AB);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n E = (double *)plasma_shared_alloc(plasma, N, PlasmaRealDouble);\n if (E == NULL) {\n plasma_error(\"PLASMA_zheevd_Tile_Async\", \"plasma_shared_alloc(E) failed\");\n plasma_shared_free(plasma, E);\n return PLASMA_ERR_OUT_OF_RESOURCES;\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 timeB = PLASMA_Wtime();\n #endif\n /* Reduction to tridiagonal form\n * with a two-stage approach.\n */\n /*=======================================\n * calling Reduction to BAND\n * then convert matrix to band form\n *=======================================*/\n plasma_dynamic_call_5(plasma_pzhetrd_he2hb,\n PLASMA_enum, uplo,\n PLASMA_desc, descA,\n PLASMA_desc, descT,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n plasma_dynamic_call_6( plasma_pzhbcpy_t2bl,\n PLASMA_enum, uplo,\n PLASMA_desc, descA,\n PLASMA_Complex64_t*, AB,\n int, LDAB,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n\n plasma_dynamic_sync();\n\n status = sequence->status;\n if (status != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_zheevd\",\"pzhetrd_he2hb+pzcopy\");\n return status;\n }\n /*=======================================\n * END of calling Reduction to BAND\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 * calling bulge chasing\n *=======================================*/\n PLASMA_Complex64_t *TAU2 = NULL;\n PLASMA_Complex64_t *V2 = NULL;\n PLASMA_Complex64_t *T2 = NULL;\n int Vblksiz, blkcnt, LDT, LDV;\n int WANTZ = 0;\n int blguplo = PlasmaLower;\n /* int NE = N; // for later use when a portion of the eigenvectors are requested*/\n if( jobz == PlasmaNoVec )\n WANTZ=0;\n else\n WANTZ=2;\n /* Vblksiz correspond to the blocking used when applying V2 to the matrix Q\n * it is similar to IB in LAPACK ZUNMQR.\n * blkcnt is the number of losange 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 losange in a tile storage meaning\n * that V2_1 is stored then V2_2,..., V2_blkcnt.\n * blkcnt is the number of losange.\n * */\n Vblksiz = min(NB,48);\n LDT = Vblksiz;\n if( jobz == PlasmaVec ) {\n findVTsiz(N, NB, Vblksiz, &blkcnt, &LDV);\n TAU2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, blkcnt*Vblksiz, PlasmaComplexDouble);\n V2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDV*blkcnt*Vblksiz, PlasmaComplexDouble);\n T2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, LDT*blkcnt*Vblksiz, PlasmaComplexDouble);\n if ( (TAU2 == NULL) || (V2 == NULL) || (T2 == NULL) ) {\n plasma_error(\"PLASMA_zheevd\", \"plasma_shared_alloc() failed\");\n plasma_shared_free(plasma, TAU2);\n plasma_shared_free(plasma, V2);\n plasma_shared_free(plasma, T2);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n memset(TAU2, 0, blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n memset(V2, 0, LDV*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n memset(T2, 0, LDT*blkcnt*Vblksiz*sizeof(PLASMA_Complex64_t));\n }\n else {\n TAU2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*N, PlasmaComplexDouble);\n V2 = (PLASMA_Complex64_t *) plasma_shared_alloc(plasma, 2*N, PlasmaComplexDouble);\n if ( (TAU2 == NULL) || (V2 == NULL) ) {\n plasma_error(\"PLASMA_zheevd\", \"plasma_shared_alloc() failed\");\n plasma_shared_free(plasma, TAU2);\n plasma_shared_free(plasma, V2);\n return PLASMA_ERR_OUT_OF_RESOURCES;\n }\n memset(TAU2, 0, 2*N*sizeof(PLASMA_Complex64_t));\n memset(V2, 0, 2*N*sizeof(PLASMA_Complex64_t));\n }\n #if defined(ENABLE_TIMER)\n timeblg = PLASMA_Wtime();\n #endif\n plasma_static_call_13(plasma_pzhetrd_hb2st_v1,\n PLASMA_enum, blguplo,\n int, N,\n int, NB,\n int, Vblksiz,\n PLASMA_Complex64_t*, AB,\n int, LDAB,\n PLASMA_Complex64_t*, V2,\n PLASMA_Complex64_t*, TAU2,\n double*, W,\n double*, E,\n int, WANTZ,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n /* WARNING: If plasma_pzhetrd_hb2st is implemented through a dynamic call, don't\n * forget to synchronize */\n plasma_dynamic_sync();\n /*=======================================\n * END of calling bulge chasing\n *=======================================*/\n #if defined(ENABLE_TIMER)\n timeblg = PLASMA_Wtime()-timeblg;\n printf(\" Finish Bulge timing= %lf \\n\" ,timeblg);\n timelpk = PLASMA_Wtime();\n #endif\n /*=======================================\n * calling eigensolver\n *=======================================*/\n /* call eigensolver using lapack routine for our resulting tridiag [D E] */\n plasma_setlapack_multithreads(plasma->world_size);\n /*\n status = LAPACKE_zstevd( LAPACK_COL_MAJOR, lapack_const(jobz), N, W, E, Q, LDQ );\n */\n if(jobz == PlasmaNoVec){\n status = LAPACKE_zstedc( LAPACK_COL_MAJOR, lapack_const(PlasmaNoVec),\n N, W, E, Q, LDQ );\n } else {\n status = LAPACKE_zstedc( LAPACK_COL_MAJOR, lapack_const(PlasmaIvec),\n N, W, E, Q, LDQ );\n }\n\n if(status != 0){\n plasma_error(\"PLASMA_zstedc\",\"ZSTEDC\");\n return status;\n }\n sequence->status = status;\n plasma_setlapack_sequential(plasma);\n /*=======================================\n * END of calling eigensolver\n *=======================================*/\n #if defined(ENABLE_TIMER)\n timelpk = PLASMA_Wtime()-timelpk;\n printf(\" Finish Eigensolver timing= %lf WANTZ %d threads %d\\n\" ,timelpk, WANTZ, plasma->world_size);\n #endif\n if (jobz == PlasmaVec){\n /*=======================================\n * apply Q2 from the bulge\n *=======================================*/\n /* compute T2 */\n #if defined(ENABLE_TIMER)\n timeT = PLASMA_Wtime();\n #endif\n plasma_static_call_8(plasma_pzlarft_blgtrd,\n int, N,\n int, NB,\n int, Vblksiz,\n PLASMA_Complex64_t*, V2,\n PLASMA_Complex64_t*, T2,\n PLASMA_Complex64_t*, TAU2,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeT = PLASMA_Wtime()-timeT;\n printf(\" Finish compute T2 timing= %lf \\n\" ,timeT);\n timeaplQ2 = PLASMA_Wtime();\n #endif\n /* apply Q2 from Left */\n plasma_static_call_14(plasma_pzunmqr_blgtrd,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaNoTrans,\n int, N,\n int, NB,\n int, N,\n int, Vblksiz,\n int, WANTZ,\n PLASMA_Complex64_t*, V2,\n PLASMA_Complex64_t*, T2,\n PLASMA_Complex64_t*, TAU2,\n PLASMA_Complex64_t*, Q,\n int, LDQ,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeaplQ2 = PLASMA_Wtime()-timeaplQ2;\n printf(\" Finish compute Q2 timing= %lf \\n\" ,timeaplQ2);\n #endif\n /*=======================================\n * apply Q1 from the reduction to band\n *=======================================*/\n /* CASE NB>N, Q1 doesn't need to be applied, only bulge chasing has been done */\n if( NB < N ){\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeconv1 = PLASMA_Wtime();\n #endif\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooplap2tile( descQ, Q, NB, NB, LDQ, N, 0, 0, N, N, sequence, request, plasma_desc_mat_free(&(descQ)) );\n }else {\n plasma_ziplap2tile( descQ, Q, NB, NB, LDQ, 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(uplo==PlasmaLower){\n plasma_dynamic_call_7(plasma_pzunmqr,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaNoTrans,\n PLASMA_desc, plasma_desc_submatrix(descA, descA.mb, 0, descA.m-descA.mb, descA.n-descA.nb),\n PLASMA_desc, plasma_desc_submatrix(descQ, descQ.mb, 0, descQ.m-descQ.mb, descQ.n),\n PLASMA_desc, plasma_desc_submatrix(descT, descT.mb, 0, descT.m-descT.mb, descT.n-descT.nb),\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n\n }\n else {\n plasma_dynamic_call_7(plasma_pzunmlq,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaConjTrans,\n PLASMA_desc, plasma_desc_submatrix(descA, 0, descA.nb, descA.m-descA.mb, descA.n-descA.nb),\n PLASMA_desc, plasma_desc_submatrix(descQ, descQ.mb, 0, descQ.m-descQ.mb, descQ.n ),\n PLASMA_desc, plasma_desc_submatrix(descT, 0, descT.nb, descT.m-descT.mb, descT.n-descT.nb),\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n }\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeaplQ1 = PLASMA_Wtime()-timeaplQ1;\n printf(\" Finish compute Q1 timing= %lf \\n\" ,timeaplQ1);\n timeconv2 = PLASMA_Wtime();\n #endif\n if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) {\n plasma_zooptile2lap( descQ, Q, NB, NB, LDQ, N, sequence, request );\n plasma_dynamic_sync();\n plasma_desc_mat_free(&descQ);\n } else {\n plasma_ziptile2lap( descQ, Q, NB, NB, LDQ, N, sequence, request );\n plasma_dynamic_sync();\n }\n #if defined(ENABLE_TIMER)\n plasma_dynamic_sync();\n timeconv2 = PLASMA_Wtime()-timeconv2;\n printf(\" Finish convert timing= %lf \\n\" ,timeconv1+timeconv2);\n #endif\n } /* END of ( NB < N ) */\n }\n #if defined(ENABLE_TIMER)\n timeall = PLASMA_Wtime()-timeall;\n printf(\" Finish full eigenproblem threads %d N %d timeall= %lf \\n\", plasma->world_size, N, timeall);\n #endif\n\n\n if( jobz == PlasmaVec )\n plasma_shared_free(plasma, T2);\n plasma_shared_free(plasma, V2);\n plasma_shared_free(plasma, TAU2);\n plasma_shared_free(plasma, E);\n plasma_shared_free(plasma, AB);\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "fd9cacd5b0a8e0b795b1c05539eba3d989074546", "size": 27217, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/zheevd.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/zheevd.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/zheevd.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.1048850575, "max_line_length": 127, "alphanum_fraction": 0.5664106992, "num_tokens": 7185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621765008857982, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.2723071008776031}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"ccl.h\"\n\n\nccl_a_finder *ccl_a_finder_new(int na, double *a_arr)\n{\n if(na<=0)\n return NULL;\n\n ccl_a_finder *finda=malloc(sizeof(ccl_a_finder));\n if(finda == NULL)\n return NULL;\n\n finda->ia_last=0;\n finda->amin = a_arr[0];\n finda->amax = a_arr[na-1];\n finda->na = na;\n finda->a_arr = malloc(na*sizeof(double));\n if(finda->a_arr==NULL) {\n free(finda);\n return NULL;\n }\n\n memcpy(finda->a_arr, a_arr, na*sizeof(double));\n\n return finda;\n}\n\nvoid ccl_a_finder_free(ccl_a_finder *finda)\n{\n if(finda!=NULL) {\n if(finda->na>0)\n free(finda->a_arr);\n free(finda);\n }\n}\n \nint ccl_find_a_index(ccl_a_finder *finda, double a)\n{\n int ia_0;\n\n if(a>=finda->amax)\n ia_0=finda->na-1;\n else if(a<=finda->amin)\n ia_0=0;\n else {\n int gotit=0;\n ia_0=finda->ia_last;\n while(!gotit) {\n if(ia_0==0) {\n if(aa_arr[1])\n gotit=1;\n else\n ia_0++;\n }\n else if(ia_0==finda->na-1) {\n if(a>=finda->a_arr[ia_0-1])\n gotit=1;\n ia_0--;\n }\n else {\n if(aa_arr[ia_0])\n ia_0--;\n else {\n if(a>=finda->a_arr[ia_0+1])\n ia_0++;\n else\n gotit=1;\n }\n }\n }\n }\n\n finda->ia_last = ia_0;\n return ia_0;\n}\n\nccl_f3d_t *ccl_f3d_t_copy(ccl_f3d_t *f3d_o, int *status)\n{\n int ia, s2dstatus=0;\n ccl_f3d_t *f3d = malloc(sizeof(ccl_f3d_t));\n if (f3d == NULL)\n *status = CCL_ERROR_MEMORY;\n\n if(*status==0) {\n f3d->lkmin = f3d_o->lkmin;\n f3d->lkmax = f3d_o->lkmax;\n f3d->na = f3d_o->na;\n f3d->is_product = f3d_o->is_product;\n f3d->extrap_linear_growth = f3d_o->extrap_linear_growth;\n f3d->extrap_order_lok = f3d_o->extrap_order_lok;\n f3d->extrap_order_hik = f3d_o->extrap_order_hik;\n f3d->is_log = f3d_o->is_log;\n f3d->growth_factor_0 = f3d_o->growth_factor_0;\n f3d->growth_exponent = f3d_o->growth_exponent;\n\n f3d->a_arr = malloc(f3d->na*sizeof(double));\n if(f3d->a_arr == NULL)\n *status = CCL_ERROR_MEMORY;\n }\n\n if(*status==0) {\n memcpy(f3d->a_arr, f3d_o->a_arr, f3d->na*sizeof(double));\n\n if(f3d_o->fka_1 != NULL)\n f3d->fka_1 = ccl_f2d_t_copy(f3d_o->fka_1, status);\n else\n f3d->fka_1 = NULL;\n }\n\n if(*status==0) {\n if(f3d_o->fka_2 != NULL)\n f3d->fka_2 = ccl_f2d_t_copy(f3d_o->fka_2, status);\n else\n f3d->fka_2 = NULL;\n }\n\n if(*status==0) {\n if(f3d_o->tkka != NULL) {\n f3d->tkka = malloc(f3d->na*sizeof(gsl_spline2d));\n if (f3d->tkka == NULL)\n *status = CCL_ERROR_MEMORY;\n\n if(*status == 0) {\n s2dstatus = 0;\n for(ia=0; iana; ia++) {\n f3d->tkka[ia] = gsl_spline2d_alloc(gsl_interp2d_bicubic,\n f3d_o->tkka[ia]->interp_object.xsize,\n f3d_o->tkka[ia]->interp_object.ysize);\n if(f3d->tkka[ia] == NULL)\n *status = CCL_ERROR_MEMORY;\n\n if(*status==0) {\n s2dstatus |= gsl_spline2d_init(f3d->tkka[ia],\n f3d_o->tkka[ia]->xarr,\n f3d_o->tkka[ia]->yarr,\n f3d_o->tkka[ia]->zarr,\n f3d_o->tkka[ia]->interp_object.xsize,\n f3d_o->tkka[ia]->interp_object.ysize);\n if(s2dstatus)\n *status = CCL_ERROR_SPLINE;\n }\n }\n }\n }\n else\n f3d->tkka = NULL;\n }\n\n return f3d;\n}\n \nccl_f3d_t *ccl_f3d_t_new(int na,double *a_arr,\n int nk,double *lk_arr,\n double *tkka_arr,\n double *fka1_arr,\n double *fka2_arr,\n int is_product,\n int extrap_order_lok,\n int extrap_order_hik,\n ccl_f2d_extrap_growth_t extrap_linear_growth,\n int is_tkka_log,\n double growth_factor_0,\n int growth_exponent,\n ccl_f2d_interp_t interp_type,\n int *status) {\n int ia, s2dstatus;\n ccl_f3d_t *f3d = malloc(sizeof(ccl_f3d_t));\n if (f3d == NULL)\n *status = CCL_ERROR_MEMORY;\n\n if (*status == 0) {\n is_product = is_product || (tkka_arr == NULL);\n f3d->is_product = is_product;\n f3d->extrap_order_lok = extrap_order_lok;\n f3d->extrap_order_hik = extrap_order_hik;\n f3d->extrap_linear_growth = extrap_linear_growth;\n f3d->is_log = is_tkka_log;\n f3d->growth_factor_0 = growth_factor_0;\n f3d->growth_exponent = growth_exponent;\n f3d->fka_1 = NULL;\n f3d->fka_2 = NULL;\n f3d->tkka = NULL;\n\n f3d->lkmin = lk_arr[0];\n f3d->lkmax = lk_arr[nk-1];\n f3d->na = na;\n f3d->a_arr = malloc(na*sizeof(double));\n if(f3d->a_arr == NULL)\n *status = CCL_ERROR_MEMORY;\n }\n\n if (*status == 0)\n memcpy(f3d->a_arr, a_arr, na*sizeof(double));\n\n if ((extrap_order_lok > 1) || (extrap_order_lok < 0) ||\n (extrap_order_hik > 1) || (extrap_order_hik < 0))\n *status = CCL_ERROR_INCONSISTENT;\n\n if ((extrap_linear_growth != ccl_f2d_cclgrowth) &&\n (extrap_linear_growth != ccl_f2d_constantgrowth) &&\n (extrap_linear_growth != ccl_f2d_no_extrapol))\n *status = CCL_ERROR_INCONSISTENT;\n\n if (f3d->is_product) {\n if ((fka1_arr == NULL) || (fka2_arr == NULL))\n *status = CCL_ERROR_INCONSISTENT;\n }\n else {\n if (tkka_arr == NULL)\n *status = CCL_ERROR_INCONSISTENT;\n }\n \n if(*status == 0) {\n if (f3d->is_product) {\n f3d->fka_1 = ccl_f2d_t_new(na, a_arr,\n nk, lk_arr,\n fka1_arr, NULL, NULL, 0,\n extrap_order_lok, extrap_order_hik,\n extrap_linear_growth,\n is_tkka_log,\n growth_factor_0, growth_exponent/2,\n interp_type, status);\n f3d->fka_2 = ccl_f2d_t_new(na, a_arr,\n nk, lk_arr,\n fka2_arr, NULL, NULL, 0,\n extrap_order_lok, extrap_order_hik,\n extrap_linear_growth,\n is_tkka_log,\n growth_factor_0, growth_exponent/2,\n interp_type, status);\n }\n else {\n switch(interp_type) {\n case(ccl_f2d_3):\n f3d->tkka = malloc(na*sizeof(gsl_spline2d));\n if (f3d->tkka == NULL)\n *status = CCL_ERROR_MEMORY;\n if(*status == 0) {\n for(ia=0; iatkka[ia] = gsl_spline2d_alloc(gsl_interp2d_bicubic, nk, nk);\n if (f3d->tkka[ia] == NULL) {\n *status = CCL_ERROR_MEMORY;\n break;\n }\n s2dstatus = gsl_spline2d_init(f3d->tkka[ia],\n lk_arr, lk_arr, tkk, nk, nk);\n if (s2dstatus) {\n *status = CCL_ERROR_SPLINE;\n break;\n }\n }\n }\n break;\n default:\n f3d->tkka = NULL;\n }\n }\n }\n\n return f3d;\n}\n\ndouble ccl_f3d_t_eval(ccl_f3d_t *f3d,double lk1,double lk2,double a,ccl_a_finder *finda,\n void *cosmo, int *status) {\n double tkka_post;\n\n double a_ev = a;\n int is_hiz = a < f3d->a_arr[0];\n int is_loz = a > f3d->a_arr[f3d->na-1];\n if (is_loz) { // Are we above the interpolation range in a?\n if (f3d->extrap_linear_growth == ccl_f2d_no_extrapol) {\n *status=CCL_ERROR_SPLINE_EV;\n return NAN;\n }\n a_ev = f3d->a_arr[f3d->na-1];\n }\n else if (is_hiz) { // Are we below the interpolation range in a?\n if (f3d->extrap_linear_growth == ccl_f2d_no_extrapol) {\n *status=CCL_ERROR_SPLINE_EV;\n return NAN;\n }\n a_ev = f3d->a_arr[0];\n }\n\n if (f3d->is_product) {\n double fka1 = ccl_f2d_t_eval(f3d->fka_1, lk1, a_ev, cosmo, status);\n double fka2 = ccl_f2d_t_eval(f3d->fka_2, lk2, a_ev, cosmo, status);\n if(*status != 0)\n return NAN;\n tkka_post = fka1*fka2;\n }\n else {\n double lk1_ev = lk1;\n int is_hik1 = lk1 > f3d->lkmax;\n int is_lok1 = lk1 < f3d->lkmin;\n int extrap_k1 = (is_hik1 & (f3d->extrap_order_hik > 0)) || (is_lok1 & (f3d->extrap_order_lok > 0));\n if (is_hik1) // Are we above the interpolation range in k?\n lk1_ev = f3d->lkmax;\n else if (is_lok1) // Are we below the interpolation range in k?\n lk1_ev = f3d->lkmin;\n\n double lk2_ev = lk2;\n int is_hik2 = lk2 > f3d->lkmax;\n int is_lok2 = lk2 < f3d->lkmin;\n int extrap_k2 = (is_hik2 & (f3d->extrap_order_hik > 0)) || (is_lok2 & (f3d->extrap_order_lok > 0));\n if (is_hik2) // Are we above the interpolation range in k?\n lk2_ev = f3d->lkmax;\n else if (is_lok2) // Are we below the interpolation range in k?\n lk2_ev = f3d->lkmin;\n\n int ia = ccl_find_a_index(finda, a_ev);\n\n if(*status == 0) {\n int spstatus = 0;\n double tkka, dtkka1, dtkka2;\n spstatus |= gsl_spline2d_eval_e(f3d->tkka[ia], lk1_ev, lk2_ev,\n NULL, NULL, &tkka);\n if(extrap_k1)\n spstatus |= gsl_spline2d_eval_deriv_x_e(f3d->tkka[ia], lk1_ev, lk2_ev,\n NULL, NULL, &dtkka1);\n if(extrap_k2)\n spstatus |= gsl_spline2d_eval_deriv_y_e(f3d->tkka[ia], lk1_ev, lk2_ev,\n NULL, NULL, &dtkka2);\n if(ia < f3d->na-1) {\n double tkka_p1, dtkka1_p1, dtkka2_p1;\n double h = (a_ev-f3d->a_arr[ia])/(f3d->a_arr[ia+1]-f3d->a_arr[ia]);\n\n spstatus |= gsl_spline2d_eval_e(f3d->tkka[ia+1], lk1_ev, lk2_ev,\n NULL, NULL, &tkka_p1);\n if(!spstatus)\n tkka = tkka*(1-h) + tkka_p1*h;\n\n if(extrap_k1) {\n spstatus |= gsl_spline2d_eval_deriv_x_e(f3d->tkka[ia+1], lk1_ev, lk2_ev,\n NULL, NULL, &dtkka1_p1);\n if(!spstatus)\n dtkka1 = dtkka1*(1-h) + dtkka1_p1*h;\n }\n\n if(extrap_k2) {\n spstatus |= gsl_spline2d_eval_deriv_y_e(f3d->tkka[ia+1], lk1_ev, lk2_ev,\n NULL, NULL, &dtkka2_p1);\n if(!spstatus)\n dtkka2 = dtkka2*(1-h) + dtkka2_p1*h;\n }\n }\n if(spstatus) {\n *status = CCL_ERROR_SPLINE_EV;\n return NAN;\n }\n\n // Extrapolate if needed\n if(extrap_k1)\n tkka += dtkka1 * (lk1 - lk1_ev);\n if(extrap_k2)\n tkka += dtkka2 * (lk2 - lk2_ev);\n tkka_post = tkka;\n }\n\n // Exponentiate if needed\n if (f3d->is_log)\n tkka_post = exp(tkka_post);\n }\n\n // Extrapolate in a if needed\n if (is_hiz) {\n double gz;\n if (f3d->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_f3d.c: ccl_f3d_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 // Use constant growth factor\n gz = f3d->growth_factor_0;\n\n tkka_post *= pow(gz, f3d->growth_exponent);\n }\n\n return tkka_post;\n}\n\nvoid ccl_f3d_t_free(ccl_f3d_t *f3d)\n{\n if(f3d != NULL) {\n if(f3d->fka_1 != NULL)\n ccl_f2d_t_free(f3d->fka_1);\n if(f3d->fka_2 != NULL)\n ccl_f2d_t_free(f3d->fka_2);\n if(f3d->tkka != NULL) {\n int ia;\n for(ia=0; iana; ia++)\n gsl_spline2d_free(f3d->tkka[ia]);\n free(f3d->tkka);\n }\n if(f3d->na > 0)\n free(f3d->a_arr);\n free(f3d);\n }\n}\n\nccl_a_finder *ccl_a_finder_new_from_f3d(ccl_f3d_t *f3d)\n{\n return ccl_a_finder_new(f3d->na, f3d->a_arr);\n}\n", "meta": {"hexsha": "0eee82eeb3999f70d8a36a0b753e963e51987459", "size": 12317, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_f3d.c", "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": "src/ccl_f3d.c", "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": "src/ccl_f3d.c", "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": 29.1182033097, "max_line_length": 104, "alphanum_fraction": 0.5317853373, "num_tokens": 4088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.27172933061375243}} {"text": "#include \n#include \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(dstarr->data.db, srcarr->data.db, mat_size_bytes(srcarr));\n}\n\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(dst->data.db != src1->data.db);\n\tassert(dst->data.db != src2->data.db);\n\n\tcblas_dgemm(CblasRowMajor, (tABC & CV_GEMM_A_T) ? CblasTrans : CblasNoTrans,\n\t\t\t\t(tABC & CV_GEMM_B_T) ? CblasTrans : CblasNoTrans, dst->rows, dst->cols, cols1, alpha, src1->data.db,\n\t\t\t\tlda, src2->data.db, ldb, beta, dst->data.db, dst->cols);\n}\n\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 = dst->rows;\n\tassert(drows == 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_dgemm(CblasRowMajor, isAT ? CblasTrans : CblasNoTrans, isBT ? CblasTrans : CblasNoTrans, cols, dstCols, rows,\n\t\t\t\tscale, src->data.db, cols, src->data.db, cols, beta, dst->data.db, 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\nSURVIVE_LOCAL_ONLY CvMat *cvCreateMatHeader(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\tCvMat *arr = (CvMat *)cvAlloc(sizeof(*arr));\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\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\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\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\tdouble *a = dstarr->data.db;\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 = malloc(sizeof(lapack_int) * MIN(srcarr->rows, srcarr->cols));\n\t\tinf = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, rows, cols, a, lda, ipiv);\n\t\tassert(inf == 0);\n\n\t\tinf = LAPACKE_dgetri(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\tfree(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\tCvMat *w = cvCreateMat(1, MIN(dstarr->rows, dstarr->cols), dstarr->type);\n\t\tCvMat *u = cvCreateMat(dstarr->cols, dstarr->cols, dstarr->type);\n\t\tCvMat *v = cvCreateMat(dstarr->rows, dstarr->rows, dstarr->type);\n\t\tCvMat *um = cvCreateMat(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->data.db[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\tcvReleaseMat(&w);\n\t\tcvReleaseMat(&u);\n\t\tcvReleaseMat(&v);\n\t\tcvReleaseMat(&um);\n\t}\n\treturn 0;\n}\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\tCvMat *a_ws = cvCloneMat(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 = malloc(sizeof(lapack_int) * MIN(Aarr->rows, Aarr->cols));\n\n\t\tinf = LAPACKE_dgetrf(LAPACK_ROW_MAJOR, arows, acols, a_ws->data.db, 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\tprint_mat(a_ws);\n\t\tprint_mat(Barr);\n#endif\n\n\t\tinf =\n\t\t\tLAPACKE_dgetrs(LAPACK_ROW_MAJOR, CblasNoTrans, arows, bcols, a_ws->data.db, lda, ipiv, Barr->data.db, ldb);\n\t\tassert(inf == 0);\n\n\t\tfree(ipiv);\n\t\tcvReleaseMat(&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\txCpy = cvCloneMat(xarr);\n\t\t} else {\n\t\t\txCpy = Barr;\n\t\t\tmemcpy(Barr->data.db, xarr->data.db, mat_size_bytes(xarr));\n\t\t}\n\n\t\tCvMat *aCpy = cvCloneMat(Aarr);\n\n\t\tdouble *S = malloc(sizeof(double) * MIN(arows, acols));\n\t\tdouble rcond = -1;\n\t\tlapack_int *rank = malloc(sizeof(lapack_int) * MIN(arows, acols));\n\t\tlapack_int inf = LAPACKE_dgelss(LAPACK_ROW_MAJOR, arows, acols, xcols, aCpy->data.db, acols, xCpy->data.db,\n\t\t\t\t\t\t\t\t\t\txcols, S, rcond, rank);\n\t\tfree(rank);\n\t\tfree(S);\n\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\tcvReleaseMat(&xCpy);\n\t\t}\n\n\t\tcvReleaseMat(&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 || M->data.db == dst->data.db;\n\tdouble *src = M->data.db;\n\n\tCvMat *tmp = 0;\n\tif (inPlace) {\n\t\ttmp = cvCloneMat(dst);\n\t\tsrc = tmp->data.db;\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\tdst->data.db[j * M->rows + i] = src[i * M->cols + j];\n\t\t}\n\t}\n\n\tif (inPlace) {\n\t\tcvReleaseMat(&tmp);\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\tdouble *pw, *pu, *pv;\n\tlapack_int arows = aarr->rows, acols = aarr->cols;\n\n\tpw = warr ? warr->data.db : (double *)alloca(sizeof(double) * arows * acols);\n\tpu = uarr ? uarr->data.db : (double *)alloca(sizeof(double) * arows * arows);\n\tpv = varr ? varr->data.db : (double *)alloca(sizeof(double) * acols * acols);\n\n\tlapack_int ulda = uarr ? uarr->cols : acols;\n\tlapack_int plda = varr ? varr->cols : acols;\n\n\tdouble *superb = malloc(sizeof(double) * MIN(arows, acols));\n\tinf = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, jobu, jobvt, arows, acols, aarr->data.db, acols, pw, pu, ulda, pv, plda,\n\t\t\t\t\t\t superb);\n\n\tfree(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\tarr->data.db[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\tarr->data.db[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\tassert(CV_64F == CV_MAT_TYPE(M->type) && \"cvDet unimplemented for float\");\n\tdouble *m = M->data.db;\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\tdouble m00 = m[0], m01 = m[1], m02 = m[2], m10 = m[3], m11 = m[4], m12 = m[5], m20 = m[6], m21 = m[7],\n\t\t\t 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": "6559be01d5c1afbfaa14547fd7ed1043d1f644da", "size": 11880, "ext": "c", "lang": "C", "max_stars_repo_path": "redist/minimal_opencv.c", "max_stars_repo_name": "a1batross/libsurvive", "max_stars_repo_head_hexsha": "2e1c2576299035c38ca9b0ea51620530742ea208", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-06T05:34:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-06T05:34:37.000Z", "max_issues_repo_path": "redist/minimal_opencv.c", "max_issues_repo_name": "ChristophHaag/libsurvive", "max_issues_repo_head_hexsha": "457a0a53c49a656424c51898b1150d0753c39673", "max_issues_repo_licenses": ["MIT"], "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": "ChristophHaag/libsurvive", "max_forks_repo_head_hexsha": "457a0a53c49a656424c51898b1150d0753c39673", "max_forks_repo_licenses": ["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.8778280543, "max_line_length": 116, "alphanum_fraction": 0.6452020202, "num_tokens": 4185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832354982647, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.2715969781793041}} {"text": "#ifndef __INTEGRATOR_H\n#define __INTEGRATOR_H\n\n#include \"autoparams.h\"\n#include \n#include \n#include \nnamespace integrator \n{\n\ndouble infty = 1000;\n\nclass WorkspaceHandle;\n\nclass Workspaces\n{\npublic:\n static const size_t WORKSPACE_SIZE = 1000000;\n static const size_t NUM_INITIAL_WORKSPACES = 4;\n\n static WorkspaceHandle get_workspace_handle();\n \n virtual ~Workspaces()\n {\n while (!workspace_stack_.empty()) \n {\n gsl_integration_workspace_free(workspace_stack_.top());\n workspace_stack_.pop();\n }\n }\nprivate:\n Workspaces(): // private constructor\n workspace_stack_()\n {\n for (int i = 0; i < NUM_INITIAL_WORKSPACES; i++)\n workspace_stack_.push(\n gsl_integration_workspace_alloc(WORKSPACE_SIZE));\n }\n Workspaces(Workspaces const& copy); // not impl\n Workspaces& operator=(Workspaces const& copy); // not impl\n std::stack workspace_stack_;\n};\n\nclass WorkspaceHandle\n{\npublic:\n WorkspaceHandle(std::stack* workspaces):\n workspaces_(workspaces), ws_(0)\n {\n if (!workspaces->empty())\n {\n ws_ = workspaces_->top();\n workspaces_->pop();\n }\n else ws_ = gsl_integration_workspace_alloc(Workspaces::WORKSPACE_SIZE);\n \n }\n\n virtual ~WorkspaceHandle()\n {\n workspaces_->push(ws_);\n }\n\n gsl_integration_workspace* get()\n {\n return ws_;\n }\nprivate:\n std::stack* workspaces_;\n gsl_integration_workspace* ws_;\n};\n\nWorkspaceHandle Workspaces::get_workspace_handle()\n{\n static Workspaces workspaces;\n return WorkspaceHandle(&workspaces.workspace_stack_);\n} \n\n\nstruct WrapperInfo\n{\n double l;\n double r;\n double ts;\n gsl_function fu;\n};\n\ndouble wrapper_func(const double x, const void* p)\n{\n const WrapperInfo* wi = static_cast(p);\n const double l = wi->l;\n const double r = wi->r;\n const double ts = wi->ts;\n return (r-l)/2 * 1./atan(ts) * 1./(1.+x*x) * \n wi->fu.function((r-l)/2*atan(x)/atan(ts)+(l+r)/2, wi->fu.params);\n}\n\n\ntypedef double (*func_with_nonconst_args)(double, void*);\n\ndouble integrate(double (*func)(const double, const void*), const double a, const double b,\n const double eps, const void* const p=0) \n{\n WorkspaceHandle w = Workspaces::get_workspace_handle();\n double result = 0;\n double error = 0;\n gsl_function fu = {(func_with_nonconst_args)func, const_cast(p)};\n gsl_integration_qags(&fu, a, b, params::integ_epsabs, eps, Workspaces::WORKSPACE_SIZE, \n w.get(), &result, &error);\n return result;\n}\n\ndouble integrate_inf(double (*func)(double, const void*),\n const double eps, const void* const p=0)\n{\n WorkspaceHandle w = Workspaces::get_workspace_handle();\n double result = 0;\n double error = 0;\n gsl_function fu = {(func_with_nonconst_args)func, const_cast(p)};\n gsl_integration_qagi(&fu, params::integ_epsabs, eps, Workspaces::WORKSPACE_SIZE, \n w.get(), &result, &error);\n return result;\n}\n\ndouble integrate_infu(double (*func)(double, const void*), const double a, \n const double eps, const void* const p=0)\n{\n WorkspaceHandle w = Workspaces::get_workspace_handle();\n double result = 0;\n double error = 0;\n gsl_function fu = {(func_with_nonconst_args)func, const_cast(p)};\n gsl_integration_qagiu(&fu, a, params::integ_epsabs, eps, Workspaces::WORKSPACE_SIZE, \n w.get(), &result, &error);\n return result;\n}\n\ndouble integrate_infl(double (*func)(double, const void*), const double b,\n const double eps, const void* const p=0)\n{\n WorkspaceHandle w = Workspaces::get_workspace_handle();\n double result = 0;\n double error = 0;\n gsl_function fu = {(func_with_nonconst_args)func, const_cast(p)};\n gsl_integration_qagil(&fu, b, params::integ_epsabs, eps, Workspaces::WORKSPACE_SIZE, \n w.get(), &result, &error);\n return result;\n}\n\n\ndouble edge_emph_integrate(double (*func)(double, const void*), const double l, \n const double r, const double ts, const double a, const double b, \n const double eps, const void* const p=0)\n{\n WorkspaceHandle w = Workspaces::get_workspace_handle();\n double result = 0;\n double error = 0;\n gsl_function fu = {(func_with_nonconst_args)func, const_cast(p)};\n WrapperInfo wi = {l, r, ts, fu};\n gsl_function wra_fu = {(func_with_nonconst_args)wrapper_func, &wi};\n gsl_integration_qags(&wra_fu, \n tan(2./(r-l)*(a-(l+r)/2)*atan(ts)), \n tan(2./(r-l)*(b-(l+r)/2)*atan(ts)), \n params::integ_epsabs, eps, Workspaces::WORKSPACE_SIZE,\n //GSL_INTEG_GAUSS21, \n w.get(), &result, &error);\n\n\n return result;\n}\n\n\n};\n\n#endif // __INTEGRATOR_H\n", "meta": {"hexsha": "5178ac2a2c6408a18fb5baf4298dd148b2c89530", "size": 4971, "ext": "h", "lang": "C", "max_stars_repo_path": "simulation/integrator.h", "max_stars_repo_name": "ModelDBRepository/228604", "max_stars_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulation/integrator.h", "max_issues_repo_name": "ModelDBRepository/228604", "max_issues_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simulation/integrator.h", "max_forks_repo_name": "ModelDBRepository/228604", "max_forks_repo_head_hexsha": "8f641f73bcac2700b476663fe656fcad7d63470d", "max_forks_repo_licenses": ["BSD-3-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.4057142857, "max_line_length": 91, "alphanum_fraction": 0.6491651579, "num_tokens": 1266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259584, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.27140251779524166}} {"text": "/*\n * Copyright (c) 2011-2020 The University of Tennessee and The University\n * of Tennessee Research Foundation. All rights\n * reserved.\n * Copyright (c) 2013 Inria. All rights reserved.\n *\n * @precisions normal z -> c d s\n *\n */\n\n#include \"dplasma.h\"\n#include \"dplasma/types.h\"\n#include \"dplasmaaux.h\"\n#include \"parsec/data_dist/matrix/two_dim_rectangle_cyclic.h\"\n#include \"parsec/data_dist/matrix/vector_two_dim_cyclic.h\"\n#include \"cores/core_blas.h\"\n\n#include \"zpltmg_chebvand.h\"\n#include \"zpltmg_fiedler.h\"\n#include \"zpltmg_hankel.h\"\n#include \"zpltmg_toeppd.h\"\n\n#include \n#include \n\n/**\n *******************************************************************************\n *\n * Generic case\n *\n *******************************************************************************\n */\nstruct zpltmg_args_s {\n dplasma_enum_t mtxtype;\n unsigned long long int seed;\n dplasma_complex64_t *W;\n};\ntypedef struct zpltmg_args_s zpltmg_args_t;\n\nstatic int\ndplasma_zpltmg_generic_operator( parsec_execution_stream_t *es,\n const parsec_tiled_matrix_t *descA,\n void *_A,\n dplasma_enum_t uplo, int m, int n,\n void *op_data )\n{\n int tempmm, tempnn, ldam;\n zpltmg_args_t *args = (zpltmg_args_t*)op_data;\n dplasma_complex64_t *A = (dplasma_complex64_t*)_A;\n (void)es;\n (void)uplo;\n\n tempmm = (m == (descA->mt-1)) ? (descA->m - m * descA->mb) : descA->mb;\n tempnn = (n == (descA->nt-1)) ? (descA->n - n * descA->nb) : descA->nb;\n ldam = BLKLDD( descA, m );\n\n if ( args->mtxtype == dplasmaMatrixCircul ) {\n return CORE_zpltmg_circul(\n tempmm, tempnn, A, ldam,\n descA->m, m*descA->mb, n*descA->nb, args->W );\n } else {\n return CORE_zpltmg(\n args->mtxtype, tempmm, tempnn, A, ldam,\n descA->m, descA->n, m*descA->mb, n*descA->nb, args->seed );\n }\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_generic - Generic wrapper for cases that are based on the map\n * function. This is the default for many test matrices generation.\n *\n * See parsec_apply() for further information.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in] mtxtype\n * Type of matrix to be generated.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[out] W\n * Workspace required by some generators.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_genvect\n * @sa dplasma_dpltmg_genvect\n * @sa dplasma_spltmg_genvect\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_generic( parsec_context_t *parsec,\n dplasma_enum_t mtxtype,\n parsec_tiled_matrix_t *A,\n dplasma_complex64_t *W,\n unsigned long long int seed)\n{\n parsec_taskpool_t *parsec_zpltmg = NULL;\n zpltmg_args_t *params = (zpltmg_args_t*)malloc(sizeof(zpltmg_args_t));\n\n params->mtxtype = mtxtype;\n params->seed = seed;\n params->W = W;\n\n parsec_zpltmg = parsec_apply_New( dplasmaUpperLower, A, dplasma_zpltmg_generic_operator, params );\n if ( parsec_zpltmg != NULL )\n {\n parsec_context_add_taskpool(parsec, (parsec_taskpool_t*)parsec_zpltmg);\n dplasma_wait_until_completion(parsec);\n parsec_apply_Destruct( parsec_zpltmg );\n return 0;\n }\n return -101;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_genvect - Generic wrapper for cases that are using two\n * datatypes: the default one, and one describing a vector.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in] mtxtype\n * Type of matrix to be generated.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_genvect\n * @sa dplasma_dpltmg_genvect\n * @sa dplasma_spltmg_genvect\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_genvect( parsec_context_t *parsec,\n dplasma_enum_t mtxtype,\n parsec_tiled_matrix_t *A,\n unsigned long long int seed )\n{\n size_t vectorsize = 0;\n parsec_taskpool_t* tp;\n\n switch( mtxtype ) {\n case dplasmaMatrixChebvand:\n tp = (parsec_taskpool_t*)parsec_zpltmg_chebvand_new( seed,\n A );\n vectorsize = 2 * A->nb * sizeof(dplasma_complex64_t);\n break;\n\n case dplasmaMatrixFiedler:\n tp = (parsec_taskpool_t*)parsec_zpltmg_fiedler_new( seed,\n A );\n vectorsize = A->mb * sizeof(dplasma_complex64_t);\n break;\n\n case dplasmaMatrixHankel:\n tp = (parsec_taskpool_t*)parsec_zpltmg_hankel_new( seed,\n A );\n vectorsize = A->mb * sizeof(dplasma_complex64_t);\n break;\n\n case dplasmaMatrixToeppd:\n tp = (parsec_taskpool_t*)parsec_zpltmg_toeppd_new( seed,\n A );\n vectorsize = 2 * A->mb * sizeof(dplasma_complex64_t);\n break;\n\n default:\n return -2;\n }\n\n if (tp != NULL) {\n parsec_zpltmg_hankel_taskpool_t *zpltmg_tp = (parsec_zpltmg_hankel_taskpool_t*)tp;\n\n /* Default type */\n dplasma_add2arena_tile( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_DEFAULT_ADT_IDX],\n A->mb*A->nb*sizeof(dplasma_complex64_t),\n PARSEC_ARENA_ALIGNMENT_SSE,\n parsec_datatype_double_complex_t, A->mb );\n\n /* Vector type */\n dplasma_add2arena_tile( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_VECTOR_ADT_IDX],\n vectorsize,\n PARSEC_ARENA_ALIGNMENT_SSE,\n parsec_datatype_double_complex_t, A->mb );\n\n\n parsec_context_add_taskpool(parsec, tp);\n dplasma_wait_until_completion(parsec);\n\n dplasma_matrix_del2arena( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_DEFAULT_ADT_IDX] );\n dplasma_matrix_del2arena( &zpltmg_tp->arenas_datatypes[PARSEC_zpltmg_hankel_VECTOR_ADT_IDX ] );\n parsec_taskpool_free(tp);\n return 0;\n }\n return -101;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_circul - Generates a Circulant test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_circul\n * @sa dplasma_dpltmg_circul\n * @sa dplasma_spltmg_circul\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_circul( parsec_context_t *parsec,\n parsec_tiled_matrix_t *A,\n unsigned long long int seed )\n{\n int info;\n dplasma_complex64_t *V = (dplasma_complex64_t*) malloc( A->m * sizeof(dplasma_complex64_t) );\n\n CORE_zplrnt( A->m, 1, V, A->m, A->m, 0, 0, seed );\n\n info = dplasma_zpltmg_generic(parsec, dplasmaMatrixCircul, A, V, seed);\n\n free(V);\n return info;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_internal\n *\n * dplasma_zpltmg_condex - Generates a Condex test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_condex\n * @sa dplasma_dpltmg_condex\n * @sa dplasma_spltmg_condex\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_condex( parsec_context_t *parsec,\n parsec_tiled_matrix_t *A )\n{\n /* gallery('condex', A->m, 4, 100.) */\n dplasma_complex64_t theta = 100.;\n parsec_matrix_block_cyclic_t *twodA = (parsec_matrix_block_cyclic_t *)A;\n parsec_matrix_block_cyclic_t Q;\n parsec_matrix_block_cyclic_init( &Q, PARSEC_MATRIX_COMPLEX_DOUBLE, PARSEC_MATRIX_TILE,\n A->super.myrank,\n A->mb, A->nb, A->mb*A->mt, 3, 0, 0, A->m, 3, 1, 1, twodA->grid.krows, twodA->grid.kcols, twodA->grid.ip, twodA->grid.jq );\n Q.mat = parsec_data_allocate((size_t)Q.super.nb_local_tiles *\n (size_t)Q.super.bsiz *\n (size_t)parsec_datadist_getsizeoftype(Q.super.mtype));\n parsec_data_collection_set_key((parsec_data_collection_t*)&Q, \"Q\");\n\n if (A->super.myrank == 0) {\n dplasma_complex64_t *Qmat;\n\n Qmat = (dplasma_complex64_t*)(Q.mat);\n\n /* Initialize the Q matrix */\n CORE_zpltmg_condexq( A->m, A->n, Qmat, Q.super.lm );\n\n /*\n * Conversion to tile layout\n */\n {\n dplasma_complex64_t *W = (dplasma_complex64_t*) malloc (A->mb * sizeof(dplasma_complex64_t) );\n int *leaders = NULL;\n int i, nleaders;\n\n /* Get all the cycles leaders and length\n * They are the same for each independent problem (each panel) */\n GKK_getLeaderNbr( Q.super.lmt, A->nb, &nleaders, &leaders );\n\n /* shift cycles. */\n for(i=0; imb, A->mb * sizeof(dplasma_complex64_t) );\n CORE_zshiftw(leaders[i*3], leaders[i*3+1], A->mt, A->nb, A->mb, Qmat, W);\n }\n\n free(leaders); free(W);\n }\n }\n\n dplasma_zlaset( parsec, dplasmaUpperLower, 0., 1. + theta, A );\n dplasma_zgemm( parsec, dplasmaNoTrans, dplasmaConjTrans,\n -theta, (parsec_tiled_matrix_t*)&Q,\n (parsec_tiled_matrix_t*)&Q,\n 1., A );\n\n parsec_data_free(Q.mat);\n parsec_tiled_matrix_destroy((parsec_tiled_matrix_t*)&Q);\n return 0;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_house - Generates a Householder test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_house\n * @sa dplasma_dpltmg_house\n * @sa dplasma_spltmg_house\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_house( parsec_context_t *parsec,\n parsec_tiled_matrix_t *A,\n unsigned long long int seed )\n{\n /* gallery('house', random, 0 ) */\n parsec_vector_two_dim_cyclic_t V;\n dplasma_complex64_t *Vmat, tau;\n\n parsec_vector_two_dim_cyclic_init( &V, PARSEC_MATRIX_COMPLEX_DOUBLE, PARSEC_VECTOR_DISTRIB_DIAG,\n A->super.myrank,\n A->mb, A->m, 0, A->m, 1, 1 );\n V.mat = parsec_data_allocate((size_t)V.super.nb_local_tiles *\n (size_t)V.super.bsiz *\n (size_t)parsec_datadist_getsizeoftype(V.super.mtype));\n parsec_data_collection_set_key((parsec_data_collection_t*)&V, \"V\");\n Vmat = (dplasma_complex64_t*)(V.mat);\n\n /* Initialize Householder vector */\n if (A->super.myrank == 0) {\n CORE_zplrnt( A->m, 1, Vmat, A->m, A->m, 0, 0, seed );\n LAPACKE_zlarfg_work( A->m, Vmat, Vmat+1, 1, &tau );\n Vmat[0] = 1.;\n }\n\n#if defined(PARSEC_HAVE_MPI)\n /* If we don't need to broadcast, don't do it, this way we don't require MPI to be initialized */\n if( A->super.nodes > 1 )\n MPI_Bcast( &tau, 1, parsec_datatype_double_complex_t, 0, *(MPI_Comm*)dplasma_pcomm );\n#endif\n\n /* Compute the Householder matrix I - tau v * v' */\n dplasma_zlaset( parsec, dplasmaUpperLower, 0., 1., A);\n dplasma_zgerc( parsec, -tau,\n (parsec_tiled_matrix_t*)&V,\n (parsec_tiled_matrix_t*)&V,\n A );\n\n parsec_data_free(V.mat);\n parsec_tiled_matrix_destroy((parsec_tiled_matrix_t*)&V);\n\n return 0;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg - Generates a special test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in] mtxtype\n * See PLASMA_zpltmg() for possible values and information on generated\n * matrices.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n * On exit, the matrix A generated.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg\n * @sa dplasma_dpltmg\n * @sa dplasma_spltmg\n *\n ******************************************************************************/\nint\ndplasma_zpltmg( parsec_context_t *parsec,\n dplasma_enum_t mtxtype,\n parsec_tiled_matrix_t *A,\n unsigned long long int seed)\n{\n\n switch( mtxtype ) {\n case dplasmaMatrixCircul:\n return dplasma_zpltmg_circul(parsec, A, seed);\n break;\n\n case dplasmaMatrixChebvand:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case dplasmaMatrixCondex:\n return dplasma_zpltmg_condex(parsec, A);\n break;\n\n case dplasmaMatrixFiedler:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case dplasmaMatrixHankel:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case dplasmaMatrixHouse:\n return dplasma_zpltmg_house(parsec, A, seed);\n break;\n\n case dplasmaMatrixToeppd:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case dplasmaMatrixCauchy:\n case dplasmaMatrixCompan:\n case dplasmaMatrixDemmel:\n case dplasmaMatrixDorr:\n case dplasmaMatrixFoster:\n case dplasmaMatrixHadamard:\n case dplasmaMatrixHilb:\n case dplasmaMatrixInvhess:\n case dplasmaMatrixKms:\n case dplasmaMatrixLangou:\n case dplasmaMatrixLehmer:\n case dplasmaMatrixLotkin:\n case dplasmaMatrixMinij:\n case dplasmaMatrixMoler:\n case dplasmaMatrixOrthog:\n case dplasmaMatrixParter:\n case dplasmaMatrixRandom:\n case dplasmaMatrixRiemann:\n case dplasmaMatrixRis:\n case dplasmaMatrixWilkinson:\n case dplasmaMatrixWright:\n return dplasma_zpltmg_generic(parsec, mtxtype, A, NULL, seed);\n break;\n default:\n return -2;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "3597dd2a08a6c18eaa5395718dc136e700a2f84c", "size": 18363, "ext": "c", "lang": "C", "max_stars_repo_path": "src/zpltmg_wrapper.c", "max_stars_repo_name": "therault/dplasma", "max_stars_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-17T19:36:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-17T19:36:41.000Z", "max_issues_repo_path": "src/zpltmg_wrapper.c", "max_issues_repo_name": "therault/dplasma", "max_issues_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2022-03-02T21:42:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T15:22:21.000Z", "max_forks_repo_path": "src/zpltmg_wrapper.c", "max_forks_repo_name": "therault/dplasma", "max_forks_repo_head_hexsha": "fa687f0ceec07f03249217b93e8a707aa9fd8ef3", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2022-02-28T21:24:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T01:53:32.000Z", "avg_line_length": 33.2061482821, "max_line_length": 153, "alphanum_fraction": 0.5162555138, "num_tokens": 4415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.2709296636763177}} {"text": "#include \n#include \n#include \"advanceCN.h\"\n#include \"advanceBE.h\"\n#include \"checkpoint.h\"\n#include \"driver.h\"\n#include \"setup.h\"\n#include \"userFunc.h\"\n\n/**************************************************************************/\n/* Driver routine */\n/**************************************************************************/\n\ndouble \ndriver(\n /* Time parameters */\n const double tStart,\n const double tEnd,\n /* Equation of state parameters */\n const bool eos_func,\n const double gamma_val, \n const double delta_val,\n /* Dimensionless viscosity parameters */\n const bool alpha_func,\n const double alpha_val,\n /* Inner boundary condition parameters */\n const pres_bc_type ibc_pres,\n const enth_bc_type ibc_enth,\n const bool ibc_func,\n const double ibc_pres_val, \n const double ibc_enth_val,\n /* Outer boundary condition parameters */\n const pres_bc_type obc_pres,\n const enth_bc_type obc_enth,\n const bool obc_func,\n const double obc_pres_val, \n const double obc_enth_val,\n /* Source function parameters */\n const bool massSrc_func,\n const double massSrc_val,\n const bool intEnSrc_func,\n const double intEnSrc_val,\n /* Control and method parameters */\n const double dtStart,\n const double dtMin, \n const double dtTol, \n const double errTol,\n const double maxDtIncrease,\n const unsigned long maxIter,\n const unsigned long interpOrder,\n const unsigned long maxStep,\n const bool useBE,\n const bool preTimestep_func,\n const bool postTimestep_func,\n const unsigned long verbosity,\n /* Output control parameters */\n const unsigned long nSave,\n const double *tSave,\n const unsigned long nUserOut,\n const bool *userOutCum,\n const bool *writeCheckpoint,\n const char *checkname,\n const bool userWriteCheckpoint,\n const bool writeFirstStep,\n const unsigned long checknum,\n /* Computational grid and workspace */\n const grid *grd,\n const wksp *w, \n /* Input data */\n double *col,\n double *pres,\n double *eInt,\n /* User-defined extra parameters */\n void *params,\n /* Diagnostic outputs */\n unsigned long *nStep,\n unsigned long *nIter,\n unsigned long *nFail,\n /* Storage for outputs */\n unsigned long *nOut,\n double *tOut,\n double *colOut,\n double *presOut,\n double *eIntOut,\n double *mBndOut,\n double *eBndOut,\n double *mSrcOut,\n double *eSrcOut,\n double *userOut\n#ifdef TESTING_MODE\n /* Parameters used in code tests */\n , double *residSum, unsigned long *iterStep,\n double *driverTime, double *advanceTime,\n double *nextIterTime, double *userTime\n#endif\n ) {\n;\n status stat = RUNNING;\n double t = tStart;\n double dt = dtStart;\n bool writeOut = writeFirstStep;\n unsigned long savePtr = 0, chkPtr = checknum;\n double dtNew;\n unsigned long i, j;\n unsigned long nIterTmp, nreduce;\n#ifdef TESTING_MODE\n unsigned long *residType;\n clock_t start_t, end_t;\n\n /* Start the clocks */\n start_t = clock();\n *advanceTime = *nextIterTime = *userTime = 0.0;\n\n /* In testing mode, allocate memory for diagnostic array */\n if (!(residType = calloc(maxIter, sizeof(unsigned long)))) {\n fprintf(stderr, \"Error: unable to allocate memory for diagnostic arrays!\\n\");\n exit(1);\n }\n\n /* In testing mode, initialize sum of residuals and iteration\n counter arrays */\n for (i=0; i 1) {\n printf(\"Step %ld, t = %e, dt = %e\\n\", *nStep, t, dt);\n } else if (verbosity > 0) {\n if (*nStep % 100 == 0) {\n\tprintf(\"Step %ld, t = %e, dt = %e\\n\", *nStep, t, dt);\n }\n }\n\n /* Call user work function */\n if (preTimestep_func) {\n\t\t\n userPreTimestep(t, dt, grd, col, pres, eInt, mBndOut+2*(*nOut),\n\t\t eBndOut+2*(*nOut), mSrcOut+grd->nr*(*nOut),\n\t\t eSrcOut+grd->nr*(*nOut), params, nUserOut,\n\t\t userOut+nUserOut*grd->nr*(*nOut));\n }\n\n /* Try to advance */\n dtNew = -1.0;\n nreduce = 0;\n while (dtNew < 0) {\n if (useBE == 0) { \n\n\tdtNew = advanceCN(t, dt, grd, col, pres, eInt, \n\t\t\t mBndOut+2*(*nOut),\n\t\t\t eBndOut+2*(*nOut),\n\t\t\t mSrcOut+grd->nr*(*nOut),\n\t\t\t eSrcOut+grd->nr*(*nOut),\n\t\t\t eos_func, gamma_val, delta_val,\n\t\t\t alpha_func, alpha_val, \n\t\t\t ibc_pres, ibc_enth,\n\t\t\t ibc_func, ibc_pres_val, ibc_enth_val,\n\t\t\t obc_pres, obc_enth,\n\t\t\t obc_func, obc_pres_val, obc_enth_val,\n\t\t\t massSrc_func, massSrc_val,\n\t\t\t intEnSrc_func, intEnSrc_val,\n\t\t\t errTol, dtTol, maxIter,\n\t\t\t interpOrder, false, verbosity > 2, w, params,\n\t\t\t &nIterTmp\n#ifdef TESTING_MODE\n\t\t\t , residSum, residType,\n\t\t\t advanceTime, nextIterTime, userTime\n#endif\n\t\t\t );\n } else { \n\tdtNew = advanceBE(t, dt, grd, col, pres, eInt, \n\t\t\t mBndOut+2*(*nOut),\n\t\t\t eBndOut+2*(*nOut),\n\t\t\t mSrcOut+grd->nr*(*nOut),\n\t\t\t eSrcOut+grd->nr*(*nOut),\n\t\t\t eos_func, gamma_val, delta_val,\n\t\t\t alpha_func, alpha_val, \n\t\t\t ibc_pres, ibc_enth,\n\t\t\t ibc_func, ibc_pres_val, ibc_enth_val,\n\t\t\t obc_pres, obc_enth,\n\t\t\t obc_func, obc_pres_val, obc_enth_val,\n\t\t\t massSrc_func, massSrc_val,\n\t\t\t intEnSrc_func, intEnSrc_val,\n\t\t\t errTol, dtTol, maxIter,\n\t\t\t interpOrder, false, verbosity > 2, w, params,\n\t\t\t &nIterTmp\n#ifdef TESTING_MODE\n\t\t\t , residSum, residType,\n\t\t\t advanceTime, nextIterTime, userTime\n#endif\n\t\t\t );\n }\n\n /* Upate iteration count. We do it here to ensure that we count\n\t iterations even if they fail to converge. */\n *nIter += nIterTmp;\n#ifdef TESTING_MODE\n iterStep[*nStep-1] += nIterTmp;\n#endif\n if (dtNew < 0) {\n\twriteOut = false;\n\tdt = dt/2.0;\n\tnreduce++;\n\t(*nFail)++;\n\tif (verbosity > 1)\n\t printf(\" Iterative solver non-convergence! Reducing dt to %e.\\n\", dt);\n\tif (dt < dtMin*(tEnd - tStart)) {\n\t stat = ZENO_ERROR;\n\t dtNew = dt;\n\t break;\n\t}\n }\n }\n for (i=0; inr*(*nOut),\n\t\t eSrcOut+grd->nr*(*nOut), params, nUserOut,\n\t\t userOut+nUserOut*grd->nr*(*nOut));\n }\n\n /* If requested, scale back the next time step */\n if (dtNew/dt > maxDtIncrease) dtNew = maxDtIncrease * dt;\n\n /* Store state */\n if (writeOut) {\n if (verbosity > 0)\n\tprintf(\"Storing output %lu at step %lu, time %e\\n\", (*nOut)+1,\n\t (*nStep)-1, t);\n tOut[(*nOut)] = t;\n for (i=0; inr; i++) {\n\tcolOut[i + (*nOut)*grd->nr] = col[i];\n\tpresOut[i + (*nOut)*grd->nr] = pres[i];\n\tif (eos_func) eIntOut[i + (*nOut)*grd->nr] = eInt[i];\n }\n /* Boundary and source values are cumulative, so just copy the\n final value during this output interval into the slot for the\n next interval */\n if (savePtrnr; i++) {\n\t mSrcOut[((*nOut)+1)*grd->nr+i] = mSrcOut[(*nOut)*grd->nr+i];\n\t eSrcOut[((*nOut)+1)*grd->nr+i] = eSrcOut[(*nOut)*grd->nr+i];\n\t }\n\t} else if (intEnSrc_func == 1) {\n\t for (i=0; inr; i++) {\n\t eSrcOut[((*nOut)+1)*grd->nr+i] = eSrcOut[(*nOut)*grd->nr+i];\n\t }\n\t}\n\t/* Handle any user-defined cumulative outputs in the same way;\n\t note that user outputs are a 3D array, with the dimensions\n\t being (output time, output variable number, cell number),\n\t where cell number is the fastest varying index and output\n\t time is the slowest varying index in memory */\n\tfor (j=0; jnr; i++)\n\t\tuserOut[((*nOut)+1)*nUserOut*grd->nr + j*grd->nr + i] =\n\t\t userOut[(*nOut)*nUserOut*grd->nr + j*grd->nr + i];\n\t }\n\t }\n\t}\n }\n\n /* Write checkpoint if requested */\n if (0&&writeCheckpoint) {\n\tif (writeCheckpoint[savePtr]) {\n\t saveCheckpoint(checkname, chkPtr,\n\t\t\t eos_func, massSrc_func, intEnSrc_func,\n\t\t\t nUserOut, t, dtNew, *nStep, *nIter, *nFail, grd,\n\t\t\t *nOut+1, tOut, colOut, presOut, eIntOut,\n\t\t\t mBndOut, eBndOut, mSrcOut, eSrcOut, userOut,\n#if AA_M > 0\n\t\t\t w->constraint,\n#endif\n\t\t\t params, userWriteCheckpoint, verbosity);\n\t /* Update checkpoint counter */\n\t chkPtr++;\n\t}\n }\n\n /* Update counters and flags */\n (*nOut)++;\n savePtr++;\n writeOut = false;\n }\n\n /* Check termination conditions */\n if ((*nStep > maxStep) && (maxStep > 0)) stat = TOO_MANY_STEPS;\n if (dtNew < dtMin*(tEnd-tStart)) stat = ZENO_ERROR;\n if (t >= tEnd) stat = NORMAL_EXIT;\n\n /* If necessary, reduce next time step to hit the next output\n time or the end time */\n if (savePtr < nSave) {\n if (t + dtNew > tSave[savePtr]) {\n\tdtNew = tSave[savePtr] - t;\n\twriteOut = true;\n }\n }\n if (t + dtNew >= tEnd) dtNew = (1.0+1.0e-10)*(tEnd - t);\n dt = dtNew;\n\n } /* Main loop end */\n \n#ifdef TESTING_MODE\n /* In testing mode, free memory for diagnostic array */\n free(residType);\n#endif\n\n /* On early exit, store final state in last output */\n if (stat != NORMAL_EXIT) {\n if (savePtr < nSave) {\n tOut[(*nOut)] = t;\n for (i=0; inr; i++) {\n\tcolOut[i + (*nOut)*grd->nr] = col[i];\n\tpresOut[i + (*nOut)*grd->nr] = pres[i];\n\tif (eos_func) eIntOut[i + (*nOut)*grd->nr] = eInt[i];\n }\n (*nOut)++;\n }\n }\n\n /* Print final status and return */\n if (verbosity > 0) {\n *nStep = *nStep-1;\n if (stat == NORMAL_EXIT)\n printf(\"Finished computation in %ld steps, t = %e\\n\", *nStep, t);\n else if (stat == TOO_MANY_STEPS)\n printf(\"Reached maximum number of steps = %ld, t = %e\\n\", *nStep, t);\n else if (stat == ZENO_ERROR)\n printf(\"Time step too small after %ld steps, t = %e, dt = %e\\n\",\n\t *nStep, t, dt);\n }\n#ifdef TESTING_MODE\n end_t = clock();\n *driverTime = (double) (end_t - start_t) / CLOCKS_PER_SEC;\n#endif\n return(t);\n}\n\n\n", "meta": {"hexsha": "b3e4b0dff41239d34f71a1fe3086e4fb24c443dd", "size": 10523, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/driver.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/driver.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/driver.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": 29.3938547486, "max_line_length": 81, "alphanum_fraction": 0.585479426, "num_tokens": 3215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7690802264851919, "lm_q2_score": 0.35220178204788966, "lm_q1q2_score": 0.2708714263058792}} {"text": "/* GPC: A library for the solution of General Point Correspondence problems.\n Copyright (C) 2006 Andrea Censi (andrea at censi dot org)\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU General Public License\n as published by the Free Software Foundation; either version 2\n of the License, or (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n*/\n\n#include \n#include \n#include \"gpc.h\"\n#include \"gpc_utils.h\"\n\n/* Note that we use static values here so we don't need to evaluate that all the time */\n#define M(matrix, rows, col) static gsl_matrix*matrix=0; if(!matrix) matrix = gsl_matrix_alloc(rows,col);\n#define MF(matrix) /*gsl_matrix_free(matrix)*/\n\n\nint gpc_solve(int K, const struct gpc_corr*c,\n\tconst double*x0, const double *cov_x0,\n\tdouble *x_out) \n{\n\tM(bigM, 4,4); M(g, 4,1); M(bigM_k,2,4);\n\tM(bigM_k_t,4,2); M(C_k,2,2); M(q_k, 2,1);\n\tM(temp41, 4,1); M(temp22,2,2);\tM(temp22b,2,2);\n\tM(temp42, 4,2); M(temp44,4,4);\tM(temp21, 2,1);\n\tM(temp22c, 2,2); M(temp12,1,2);\n\t\n\tgsl_matrix_set_zero(bigM);\n\tgsl_matrix_set_zero(g);\n\tgsl_matrix_set_zero(temp42);\n\t\n\tdouble d_bigM[4][4] = { {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}};\n\tdouble d_g[4] = {0, 0, 0, 0};\n\tint k;\n\tfor(k=0;k= 0) && (trace>0);\n\t\tif(!is_semidef_pos) {\n\t\t\tfprintf(stderr, \"k=%d; I expect the matrix to be semidef positive (det>=0 and trace>0), det = %.20f trace= %.10f C = [%.15f,%.15f;%.15f %.15f]\\n\",\n\t\t\t\tk, det, trace,\tC00,C01,C10,C11);\n\t\t\treturn 0;\n\t\t}\n#endif\n\t\t\n\t\tdouble qx = c[k].q[0];\n\t\tdouble qy = c[k].q[1];\n\t\tdouble px = c[k].p[0];\n\t\tdouble py = c[k].p[1];\n\t\t\n\t\t/* [ C00, c01, px C00 + c01 py , c01 px - py C00 ] */\n\t\td_bigM[0][0] += C00;\n\t\td_bigM[0][1] += C01;\n\t\td_bigM[0][2] += +px * C00 + py * C01;\n\t\td_bigM[0][3] += -py * C00 + px * C01;\n\t\n\t\t/* [ C10 , C11 , py C11 + px C10 , px C11 - py C10 ] */\n\t\td_bigM[1][0] += C10;\n\t\td_bigM[1][1] += C11;\n\t\td_bigM[1][2] += +px * C10 + py * C11;\n\t\td_bigM[1][3] += +px * C11 - py * C10;\n\t\t\n\t\t/*Col 1 = [ py C10 + px C00 ] \n\t\t Col 2 = [ py C11 + c01 px ]\n\t\t Col 3 = [ py (py C11 + px C10) + px (px C00 + c01 py) ]\n\t\t Col 4 = [ py (px C11 - py C10) + px (c01 px - py C00) ]\n\t\t*/\n\t\td_bigM[2][0] += px * C00 + py * C10;\n\t\td_bigM[2][1] += px * C01 + py * C11;\n\t\td_bigM[2][2] += (px*px)*(+C00) + (px*py)*(+C10+C01) + (py*py)*(+C11);\n\t\td_bigM[2][3] += (px*px)*(+C01) + (px*py)*(-C00+C11) + (py*py)*(-C10);\n\n\t\t/*Col 1 = [ px C10 - py C00 ] \n\t\t Col 2 = [ px C11 - c01 py ]\n\t\t Col 3 = [ px (py C11 + px C10) - py (px C00 + c01 py) ]\n\t\t Col 4 = [ px (px C11 - py C10) - py (c01 px - py C00) ]*/\n\t\td_bigM[3][0] += -py * C00 + px * C10;\n\t\td_bigM[3][1] += -py * C01 + px * C11;\n\t\td_bigM[3][2] += (px*px)*(+C10) + (px*py)*(-C00+C11) + (py*py)*(-C01);\n\t\td_bigM[3][3] += (px*px)*(+C11) + (px*py)*(-C10-C01) + (py*py)*(+C00);\n\t\t\n\t\td_g[0] += C00*qx+C10*qy;\n\t\td_g[1] += C01*qx+C11*qy;\n\t\td_g[2] += qx * (C00*px+C01*py) + qy * (C10*px+C11*py);\n\t\td_g[3] += qx * (C00*(-py)+C01*px) + qy * (C10*(-py)+C11*px);\n\n\t}\n\n\t{\n\tunsigned int a,b;\n\t for(a=0;a<4;a++) \n\t\t\t*gsl_matrix_ptr(g, a, 0) = -2 * d_g[a];\n\t for(a=0;a<4;a++) \n\t\tfor(b=0;b<4;b++)\n\t\tgsl_matrix_set(bigM, a, b, 2 * d_bigM[a][b]);\n\t}\n\n\t\n\tM(mA,2,2); gms(mA,0,0, gmg(bigM,0,0)); gms(mA,0,1, gmg(bigM,0,1));\n\t gms(mA,1,0, gmg(bigM,1,0)); gms(mA,1,1, gmg(bigM,1,1));\n\tM(mB,2,2); gms(mB,0,0, gmg(bigM,0,2)); gms(mB,0,1, gmg(bigM,0,3));\n\t gms(mB,1,0, gmg(bigM,1,2)); gms(mB,1,1, gmg(bigM,1,3));\n\tM(mD,2,2); gms(mD,0,0, gmg(bigM,2,2)); gms(mD,0,1, gmg(bigM,2,3));\n\t gms(mD,1,0, gmg(bigM,3,2)); gms(mD,1,1, gmg(bigM,3,3));\n\n\tM(mS,2,2); M(mSa,2,2);\n\n\t \n\t/*\tmS = mD - mB.trans * mA.inv * mB;\n\t temp22b = inv(A) */\n\tm_inv(mA, temp22b); \n\t/* temp22c = inv(A) * mB */\n\tm_mult(temp22b, mB, temp22c);\n\t/* temp22 = mB' */\n\tm_trans(mB, temp22); \n\tm_mult(temp22, temp22c, temp22b); \n\tm_scale(-1.0,temp22b);\n\tm_add(mD,temp22b,mS);\n\t\n\t/* mSa = mS.inv * mS.det; */\n\tm_inv(mS, mSa);\n\tm_scale(m_det(mS), mSa);\n\t\n\tif(TRACE_ALGO) {\n\t\tm_display(\"mA\",mA);\n\t\tm_display(\"mB\",mB);\n\t\tm_display(\"mD\",mD);\n\t\tm_display(\"mS\",mS);\n\t\tm_display(\"mSa\",mSa);\n\t}\n\n\tM(g1,2,1);\tM(g2,2,1);\n\tM(g1t,1,2);\tM(g2t,1,2);\n\tM(mAi,2,2);\tM(mBt,2,2);\n\t\n\tgms(g1,0,0,gmg(g,0,0));\n\tgms(g1,1,0,gmg(g,1,0));\n\tgms(g2,0,0,gmg(g,2,0));\n\tgms(g2,1,0,gmg(g,3,0));\n\tm_trans(g1, g1t);\n\tm_trans(g2, g2t);\n\tm_trans(mB, mBt);\n\tm_inv(mA, mAi);\n\n\tM(m1t,1,2);\tM(m1,2,1);\n\tM(m2t,1,2);\tM(m2,2,1);\n\tM(m3t,1,2);\tM(m3,2,1);\n\n\t/* m1t = g1t*mAi*mB */\n\tm_mult(g1t,mAi,temp12);\n\tm_mult(temp12,mB,m1t);\n\n\tm_trans(m1t,m1);\n\t/* m2t = m1t*mSa */\n\tm_mult(m1t,mSa,m2t);\n\tm_trans(m2t,m2);\n\t/* m3t = g2t*mSa */\n\tm_mult(g2t,mSa,m3t); \n\tm_trans(m3t,m3);\n\t\n\tdouble p[3] = {\n\t\t m_dot(m2t,m2) - 2*m_dot(m2t,m3) + m_dot(m3t,m3),\n\t\t4*m_dot(m2t,m1) - 8*m_dot(m2t,g2) + 4*m_dot(g2t,m3),\n\t\t4*m_dot(m1t,m1) - 8*m_dot(m1t,g2) + 4*m_dot(g2t,g2)};\n\n\tdouble l[3] = {m_det(mS), 2*gmg(mS,0,0)+2*gmg(mS,1,1), 4};\n\t\n\t/* q = p - l^2 */\n\tdouble q[5] = {p[0]-(l[0]*l[0]), p[1]-(2*l[1]*l[0]), \n\t\tp[2]-(l[1]*l[1]+2*l[0]*l[2]), -(2*l[2]*l[1]), -(l[2]*l[2])};\n\t\n\tif(TRACE_ALGO) {\n\t\tfprintf(stderr, \"p = %f %f %f \\n\", p[2], p[1], p[0]);\n\t\tfprintf(stderr, \"l = %f %f %f \\n\", l[2], l[1], l[0]);\n\t\tfprintf(stderr, \"q = %f %f %f %f %f \\n\", q[4], q[3], q[2], q[1], q[0]);\n\t}\n\n\t/*\n\tdouble lambdas[4];\n\tif(!poly_real_roots(5, q, lambdas)) {\n\t\tfprintf(stderr, \"Cannot solve polynomial.\\n\");\n\t\treturn 0;\n\t}\n\n\tdouble lambdas_error[4];\n\tdouble lambdas_pose[4][3];\n\t\n\tfor(int i=0;i<4;i++) {\n\t\tdouble lambda = lambdas[i];\n\t\t\n\t\tif(TRACE_ALGO) {\n\t\t\tfprintf(stderr, \"lambda = %f \\n\", lambda);\n\t\t}\t\n\t\n\t\tM(W,4,4); gsl_matrix_set_zero(W); gms(W,2,2,1.0); gms(W,3,3,1.0);\n\t\tM(x,4,1);\n\t\n\t\tm_scale(2*lambda, W);\n\t\tgsl_matrix_add(bigM,W);\n\t\tm_inv(bigM, temp44);\n\t\tm_mult(temp44, g, x);\n\t\tm_scale(-1.0, x);\n\t\n\t\tlambdas_pose[i][0] = gmg(x,0,0);\n\t\tlambdas_pose[i][1] = gmg(x,1,0);\n\t\tlambdas_pose[i][2] = atan2(gmg(x,3,0),gmg(x,2,0));\n\t\t\n\t\tlambdas_error[i] = gpc_total_error(c, K, lambdas_pose[i]);\n\t}\n\t\n\tint lowest_error = 0;\n\tfor(int i=0;i<4;i++) {\n\t\tprintf(\"#%d lambda=%lf error=%lf\\n\",i,lambdas[i],lambdas_error[i]);\n\t\tif(lambdas_error[i] < lambdas_error[lowest_error])\n\t\t\tlowest_error = i;\n\t}\n\t\n\tdouble lr;\n\tpoly_greatest_real_root(5,q,&lr);\n\tprintf(\"Choose %d: lambda = %lf bigger real root = %lf \\n\",lowest_error,lambdas[lowest_error],lr);\n\t\n\tx_out[0]=lambdas_pose[lowest_error][0];\n\tx_out[1]=lambdas_pose[lowest_error][1];\n\tx_out[2]=lambdas_pose[lowest_error][2];\n\t*/\n\t\n\tdouble lambda;\n\tif(!poly_greatest_real_root(5, q, &lambda)) return 0;\n\t\n\tM(W,4,4); gsl_matrix_set_zero(W); gms(W,2,2,1.0); gms(W,3,3,1.0);\n\tM(x,4,1);\n\n\tm_scale(2*lambda, W);\n\tgsl_matrix_add(bigM,W);\n\tm_inv(bigM, temp44);\n\tm_mult(temp44, g, x);\n\tm_scale(-1.0, x);\n\n\tx_out[0] = gmg(x,0,0);\n\tx_out[1] = gmg(x,1,0);\n\tx_out[2] = atan2(gmg(x,3,0),gmg(x,2,0));\n\n\tif(TRACE_ALGO) {\n\t\tfprintf(stderr, \"x = %f %f %f deg\\n\", x_out[0], x_out[1],x_out[2]*180/M_PI);\n\t}\n\t\n\tMF(mA); MF(mB); MF(mD); MF(mS); MF(mSa);\n\tMF(m1t);\tMF(m1);\tMF(m2t);\tMF(m2);\n\tMF(m3t);\tMF(m3);\tMF(W); \tMF(x);\n\tMF(bigM); MF(g); MF(bigM_k);\n\tMF(bigM_k_t); MF(C_k); MF(q_k);\n\tMF(temp42); MF(temp44);\tMF(temp21);\n\tMF(temp41); MF(temp22);\tMF(temp22b);\n\tMF(temp22c); MF(temp12);\n\tMF(g1);\tMF(g2);\n\tMF(g1t);\tMF(g2t);\n\tMF(mAi);\tMF(mBt);\n\treturn 1;\n}\n\n\ndouble gpc_error(const struct gpc_corr*co, const double*x) {\n\tdouble c = cos(x[2]);\n\tdouble s = sin(x[2]);\n\tdouble e[2];\n\te[0] = c*(co->p[0]) -s*(co->p[1]) + x[0] - co->q[0];\n\te[1] = s*(co->p[0]) +c*(co->p[1]) + x[1] - co->q[1];\n\tdouble this_error = e[0]*e[0]*co->C[0][0]+2*e[0]*e[1]*co->C[0][1]+e[1]*e[1]*co->C[1][1];\n\t\n\tif(0) /* due to limited numerical precision, error might be negative */\n\tif(this_error < 0) {\n\t\tfprintf(stderr, \"Something fishy: error = %lf e = [%lf %lf] C = [%lf,%lf;%lf,%lf]\\n\", this_error,\n\t\t\te[0],e[1],co->C[0][0],co->C[0][1],co->C[1][0],co->C[1][1]);\n\t}\n\treturn this_error;\n}\n\ndouble gpc_total_error(const struct gpc_corr*co, int n, const double*x){\n\tdouble error = 0;\n\tfor(int i=0;i\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n//! Enum class for deciding on Bose-Einstein, Fermi-Dirac or Botlzmann particle dsitribution\nenum class EParticleType : int { kBoson = 1, kFermion = -1, kBoltzman = 0 };\nenum class EFjIndex : int { \n kFeq1 = 0,\n kFeq2 = 1,\n kFshear1 = 2,\n kFshear2 = 3,\n kFshear3 = 4,\n kFbulk1 = 5,\n kFbulk2 = 6,\n kFtemp1 = 7,\n kFtemp2 = 8,\n kFvel1 = 9,\n kFvel2 = 10,\n kFvel3 = 11 };\n\n\n\n//! Particle class with basic properties and universal decay spectra components\nclass TParticle {\n protected:\n //! Particle properties\n std::string fParticleName; // particle name\n std::string fDescription; // particle name\n std::string fDescriptionHeader; // particle name\n std::string fHeader = \"1:pbar [GeV]\\t2:m [GeV]\";\n std::vector fComponentNames = {\"Feq 1\", \"Feq 2\",\"Fshear 1\",\"Fshear 2\",\"Fshear 3\",\"Fbulk 1\",\"Fbulk 2\",\"Ftemp 1\",\"Ftemp 2\",\"Fvel 1\",\"Fvel 2\",\"Fvel 3\"};\n //std::string fHeader = \"1:pbar [GeV]\\t2:m [GeV]\\t3:feq 1\\t4:feq 2\\t5:fshear 1\\t6:fshear 2\\t7:fshear 3\\t8:fbulk 1\\t9:fbulk 2\\t10:ftemperature 1\\t11:ftemperature 2\\t12:fvelocity 1\\t13:fvelocity 2\\t14:fvelocity 3\";\n \n // particle name\n double fMass; // [GeV] resonance mass\n double fGamma; // [GeV] resonance width (currently not used)\n double fIsospin; // isospin J |J,m>\n int fPDGCode; // number code according to PDG\n int fNu; // degeneracy of a particle\n double fQB; // baryon charge\n double fQS; // strange charge\n double fQC; // charme charge\n EParticleType fParticleType; // particle statistic (bose-einstein, fermi-dirac, boltzmann)\n\n double fTfo;\n double fNtotal; //integrated particle number\n double fNtotal_buffer;\n\n //! Grid and interpolator for decay spectra components\n const gsl_interp_type *fSpline_type = gsl_interp_cspline;\n double fPbar_arr[grid_params::fNpbar]; // array of fluid restframe momentum\n double fFj_arr[grid_params::fNf][grid_params::fNpbar]; // array of scalar functions Fj\n double fFj_arr_buffer[grid_params::fNf][grid_params::fNpbar]; // buffer array of scalar functions Fj \n gsl_spline *fSpline_Fj[grid_params::fNf] ;\n gsl_interp_accel *fPbar_acc;\n //! Bool variables to control data read in/out-put\n bool fIsLocked = false; //if true, prevent modifying fFj_arr data\n bool fIsModified[grid_params::fNf]; //if true, require initilization of interpolator\n //! After any update of the grid, don't forget to reinitialized the interpolator!\n //! initiliazes the interpolator\n void init_grid(std::string comps=\"Feq Fshear Fbulk Ftemp Fvel\");\n void init(int j);\n public:\n\n std::vector fComponents;\n //! Contructor with particle properties\n ~TParticle() ;\n //! return parameters about the particle\n std::string getName() {return fParticleName;};\n double getM() {return fMass;};\n double getGamma() {return fGamma;};\n double getQB() {return fQB;};\n double getQS() {return fQS;};\n double getQC() {return fQC;};\n double getIsospin() {return fIsospin;};\n double getN() {return fNtotal;};\n int getNu() {return fNu;};\n int getPDG() {return fPDGCode;};\n EParticleType getType() {return fParticleType;};\n\n //! increment integrated particle number\n void addN(double n) {\n if (fIsLocked){\n std::cerr << \"\\033[1mTParticle.h\\033[0m : \\033[1;31merror\\033[0m : attemped to modify locked \"<< fParticleName <<\" data\" << std::endl;\n exit(EXIT_FAILURE);}\n else { fNtotal+=n; fNtotal_buffer+=n; }};\n //! set initial thermal temperature\n void setTfo(double Tfo) {fTfo=Tfo;};\n //! set lock on data modification\n void lock() {fIsLocked=true;};\n bool hasdecayed() {return fIsLocked;};\n //! clean the buffer\n void clean_buffer() { \n for(int i = 0; i \n\t\t\tstatic void Add(MemoryBuffer&, const MemoryBuffer&, const MemoryBuffer&, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void AddEqual(MemoryBuffer&, const MemoryBuffer&, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void AddEqualMatrix(MemoryTile&, const MemoryTile&, const MatrixOperation, const MatrixOperation, const double, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void Scale(MemoryBuffer&, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ScaleColumns(MemoryTile&, const MemoryBuffer&)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ElementwiseProduct(MemoryBuffer&, const MemoryBuffer&, const MemoryBuffer&, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void SubMultiply(MemoryTile&, const MemoryTile&, const MemoryTile&, const unsigned, const unsigned, const unsigned, const MatrixOperation, const MatrixOperation, const double, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void BatchedMultiply(MemoryCube&, const MemoryCube&, const MemoryCube&, const unsigned, const unsigned, const MatrixOperation, const MatrixOperation, const double, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void Dot(MemoryBuffer&, const MemoryTile&, const MemoryBuffer&, const MatrixOperation, const double, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void KroneckerProduct(MemoryTile&, const MemoryBuffer&, const MemoryBuffer&, const double)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void Solve(const MemoryTile&, MemoryTile&, const MatrixOperation, const LinearSystemSolverType)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ArgAbsMin(int&, const MemoryBuffer&)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ColumnWiseArgAbsMin(MemoryBuffer&, const MemoryTile&)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ArgAbsMax(int&, const MemoryBuffer&)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ColumnWiseArgAbsMax(MemoryBuffer&, const MemoryTile&)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\n\t\t\t// norm = ||x||_2\n\t\t\ttemplate\n\t\t\tstatic void EuclideanNorm(double&, const MemoryBuffer&)\n\t\t\t{\n\t\t\t\tthrow NotImplementedException();\n\t\t\t}\n\t\t}\n\t}\t // namespace routines\n}\t // namespace cl\n\n#else\n\n\t#include \n\t#include \n\nBLAS_NAMESPACE\n{\n\t#include \n\t#include \n}\n\nnamespace cl\n{\n\tnamespace routines\n\t{\n\t\tROUTINES_NAMESPACE\n\t\t{\n\t\t\tstatic constexpr GENERIC_API_NAMESPACE::CBLAS_ORDER columnMajorLayout = { GENERIC_API_NAMESPACE::CBLAS_ORDER::CblasColMajor };\n\t\t\tstatic constexpr std::array operationsEnum = { GENERIC_API_NAMESPACE::CBLAS_TRANSPOSE::CblasNoTrans, GENERIC_API_NAMESPACE::CBLAS_TRANSPOSE::CblasTrans };\n\n\t\t\ttemplate\n\t\t\tstatic void Add(MemoryBuffer & z, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha);\n\n\t\t\ttemplate<>\n\t\t\tinline void Add(MemoryBuffer & z, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)\n\t\t\t{\n\t\t\t\tCopy(z, y);\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_saxpy(static_cast(z.size), static_cast(alpha), reinterpret_cast(x.pointer), 1, reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void Add(MemoryBuffer & z, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)\n\t\t\t{\n\t\t\t\tCopy(z, y);\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_daxpy(static_cast(z.size), alpha, reinterpret_cast(x.pointer), 1, reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void AddEqual(MemoryBuffer & z, const MemoryBuffer& x, const double alpha);\n\n\t\t\ttemplate<>\n\t\t\tinline void AddEqual(MemoryBuffer & z, const MemoryBuffer& x, const double alpha)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_saxpy(static_cast(z.size), static_cast(alpha), reinterpret_cast(x.pointer), 1, reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void AddEqual(MemoryBuffer & z, const MemoryBuffer& x, const double alpha)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_daxpy(static_cast(z.size), alpha, reinterpret_cast(x.pointer), 1, reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void AddEqualMatrix(MemoryTile & A, const MemoryTile& B, const MatrixOperation aOperation, const MatrixOperation bOperation, const double alpha, const double beta);\n\n\t\t\ttemplate<>\n\t\t\tinline void AddEqualMatrix(MemoryTile & A, const MemoryTile& B, const MatrixOperation aOperation, const MatrixOperation bOperation, const double alpha, const double beta)\n\t\t\t{\n\t\t\t\tif (aOperation != MatrixOperation::None)\n\t\t\t\t\tthrow NotImplementedException();\n\t\t\t\tif (bOperation != MatrixOperation::None)\n\t\t\t\t\tthrow NotImplementedException();\n\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_sgeadd(columnMajorLayout, static_cast(A.nRows), static_cast(A.nCols), static_cast(beta), reinterpret_cast(B.pointer), static_cast(B.leadingDimension), static_cast(alpha), reinterpret_cast(A.pointer), static_cast(A.leadingDimension));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void AddEqualMatrix(MemoryTile & A, const MemoryTile& B, const MatrixOperation aOperation, const MatrixOperation bOperation, const double alpha, const double beta)\n\t\t\t{\n\t\t\t\tif (aOperation != MatrixOperation::None)\n\t\t\t\t\tthrow NotImplementedException();\n\t\t\t\tif (bOperation != MatrixOperation::None)\n\t\t\t\t\tthrow NotImplementedException();\n\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_dgeadd(columnMajorLayout, static_cast(A.nRows), static_cast(A.nCols), beta, reinterpret_cast(B.pointer), static_cast(B.leadingDimension), alpha, reinterpret_cast(A.pointer), static_cast(A.leadingDimension));\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void Scale(MemoryBuffer & z, const double alpha);\n\n\t\t\ttemplate<>\n\t\t\tinline void Scale(MemoryBuffer & z, const double alpha)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_sscal(static_cast(z.size), static_cast(alpha), reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void Scale(MemoryBuffer & z, const double alpha)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_dscal(static_cast(z.size), alpha, reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ScaleColumns(MemoryTile & z, const MemoryBuffer& alpha);\n\n\t\t\ttemplate<>\n\t\t\tinline void ScaleColumns(MemoryTile & z, const MemoryBuffer& alpha)\n\t\t\t{\n\t\t\t\tfor (size_t i = 0; i < z.nCols; ++i)\n\t\t\t\t\tGENERIC_API_NAMESPACE::cblas_sscal(static_cast(z.nRows), *reinterpret_cast(alpha.pointer + i * alpha.ElementarySize()), reinterpret_cast(z.pointer + i * z.nRows * z.ElementarySize()), 1);\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void ScaleColumns(MemoryTile & z, const MemoryBuffer& alpha)\n\t\t\t{\n\t\t\t\tfor (size_t i = 0; i < z.nCols; ++i)\n\t\t\t\t\tGENERIC_API_NAMESPACE::cblas_dscal(static_cast(z.nRows), *reinterpret_cast(alpha.pointer + i * alpha.ElementarySize()), reinterpret_cast(z.pointer + i * z.nRows * z.ElementarySize()), 1);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void SubMultiply(MemoryTile & A, const MemoryTile& B, const MemoryTile& C, const unsigned nRowsB, const unsigned nColsB, const unsigned nColsC, const MatrixOperation bOperation, const MatrixOperation cOperation, const double alpha, const double beta);\n\n\t\t\ttemplate<>\n\t\t\tinline void SubMultiply(MemoryTile & A, const MemoryTile& B, const MemoryTile& C, const unsigned nRowsB, const unsigned nColsB, const unsigned nColsC, const MatrixOperation bOperation, const MatrixOperation cOperation, const double alpha, const double beta)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_sgemm(columnMajorLayout, operationsEnum[static_cast(bOperation)], operationsEnum[static_cast(cOperation)], static_cast(nRowsB), static_cast(nColsC), static_cast(nColsB), static_cast(alpha), reinterpret_cast(B.pointer), static_cast(B.leadingDimension), reinterpret_cast(C.pointer), static_cast(C.leadingDimension), static_cast(beta), reinterpret_cast(A.pointer), static_cast(A.leadingDimension));\n\t\t\t}\n\n\t\t\ttemplate<>\n\t\t\tinline void SubMultiply(MemoryTile & A, const MemoryTile& B, const MemoryTile& C, const unsigned nRowsB, const unsigned nColsB, const unsigned nColsC, const MatrixOperation bOperation, const MatrixOperation cOperation, const double alpha, const double beta)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_dgemm(columnMajorLayout, operationsEnum[static_cast(bOperation)], operationsEnum[static_cast(cOperation)], static_cast(nRowsB), static_cast(nColsC), static_cast(nColsB), alpha, reinterpret_cast(B.pointer), static_cast(B.leadingDimension), reinterpret_cast(C.pointer), static_cast(C.leadingDimension), beta, reinterpret_cast(A.pointer), static_cast(A.leadingDimension));\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void Dot(MemoryBuffer & y, const MemoryTile& A, const MemoryBuffer& x, const MatrixOperation aOperation, const double alpha = 1.0, const double beta = 0.0);\n\n\t\t\ttemplate<>\n\t\t\tinline void Dot(MemoryBuffer & y, const MemoryTile& A, const MemoryBuffer& x, const MatrixOperation aOperation, const double alpha, const double beta)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_sgemv(columnMajorLayout, operationsEnum[static_cast(aOperation)], static_cast(A.nRows), static_cast(A.nCols), static_cast(alpha), reinterpret_cast(A.pointer), static_cast(A.leadingDimension), reinterpret_cast(x.pointer), 1, static_cast(beta), reinterpret_cast(y.pointer), 1);\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void Dot(MemoryBuffer & y, const MemoryTile& A, const MemoryBuffer& x, const MatrixOperation aOperation, const double alpha, const double beta)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_dgemv(columnMajorLayout, operationsEnum[static_cast(aOperation)], static_cast(A.nRows), static_cast(A.nCols), alpha, reinterpret_cast(A.pointer), static_cast(A.leadingDimension), reinterpret_cast(x.pointer), 1, beta, reinterpret_cast(y.pointer), 1);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void KroneckerProduct(MemoryTile & A, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha);\n\n\t\t\ttemplate<>\n\t\t\tinline void KroneckerProduct(MemoryTile & A, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_sger(columnMajorLayout, static_cast(x.size), static_cast(y.size), static_cast(alpha), reinterpret_cast(x.pointer), 1, reinterpret_cast(y.pointer), 1, reinterpret_cast(A.pointer), static_cast(A.nRows));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void KroneckerProduct(MemoryTile & A, const MemoryBuffer& x, const MemoryBuffer& y, const double alpha)\n\t\t\t{\n\t\t\t\tGENERIC_API_NAMESPACE::cblas_dger(columnMajorLayout, static_cast(x.size), static_cast(y.size), alpha, reinterpret_cast(x.pointer), 1, reinterpret_cast(y.pointer), 1, reinterpret_cast(A.pointer), static_cast(A.nRows));\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void Solve(const MemoryTile& A, MemoryTile& B, const MatrixOperation aOperation, const LinearSystemSolverType solver);\n\n\t\t\ttemplate<>\n\t\t\tinline void Solve(const MemoryTile& A, MemoryTile& B, const MatrixOperation aOperation, const LinearSystemSolverType solver)\n\t\t\t{\n\t\t\t\t// Need to copy A, as it will be overwritten by its factorization\n\t\t\t\tMemoryTile aCopy(A);\n\t\t\t\tAlloc(aCopy);\n\t\t\t\tCopy(aCopy, A);\n\n\t\t\t\tconst auto nra = static_cast(A.nRows);\n\t\t\t\tconst auto lda = static_cast(A.leadingDimension);\n\t\t\t\tconst auto ncb = static_cast(B.nCols);\n\t\t\t\tconst auto ldb = static_cast(B.leadingDimension);\n\n\t\t\t\t// Initializes auxliary value for solver\n\t\t\t\tint info = 0;\n\n\t\t\t\tswitch (solver)\n\t\t\t\t{\n\t\t\t\t\tcase LinearSystemSolverType::Lu:\n\t\t\t\t\t{\n\t\t\t\t\t\t// allocate memory for pivoting\n\t\t\t\t\t\tMemoryBuffer pivot(0, A.nRows, A.memorySpace, MathDomain::Int);\n\t\t\t\t\t\tAlloc(pivot);\n\n\t\t\t\t\t\t// Factorize A (and overwrite it with L)\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_sgetrf(static_cast(columnMajorLayout), nra, nra, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(pivot.pointer));\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// Solve factorized system\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_sgetrs(static_cast(columnMajorLayout), openBlasOperation[static_cast(aOperation)], nra, ncb, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(pivot.pointer), reinterpret_cast(B.pointer), ldb);\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// free memory\n\t\t\t\t\t\tFree(pivot);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase LinearSystemSolverType::Qr:\n\t\t\t\t\t{\n\t\t\t\t\t\t// allocate memory for tau\n\t\t\t\t\t\tMemoryBuffer tau(0, A.nRows, A.memorySpace, MathDomain::Float);\n\t\t\t\t\t\tAlloc(tau);\n\n\t\t\t\t\t\t// A = Q * R\n\t\t\t\t\t\t/* int matrix_layout, lapack_int m, lapack_int n,\n\t\t\t\t\t\t\t\t float* a, lapack_int lda, float* tau */\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_sgeqrf(static_cast(columnMajorLayout), nra, nra, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(tau.pointer));\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// B = Q^T * B\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * int matrix_layout, char side, char trans,\n\t\t\t\t\t\t\t\t lapack_int m, lapack_int n, lapack_int k,\n\t\t\t\t\t\t\t\t const float* a, lapack_int lda, const float* tau,\n\t\t\t\t\t\t\t\t float* c, lapack_int ldc */\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_sormqr(static_cast(columnMajorLayout), 'L', 'T', nra, nra, ncb, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(tau.pointer), reinterpret_cast(B.pointer), ldb);\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// Solve (x = R \\ (Q^T * B))\n\t\t\t\t\t\tGENERIC_API_NAMESPACE::cblas_strsm(columnMajorLayout, GENERIC_API_NAMESPACE::CBLAS_SIDE::CblasLeft, GENERIC_API_NAMESPACE::CBLAS_UPLO::CblasUpper, operationsEnum[static_cast(aOperation)], GENERIC_API_NAMESPACE::CBLAS_DIAG::CblasNonUnit, nra, nra, 1.0, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(B.pointer), ldb);\n\n\t\t\t\t\t\t// free memory\n\t\t\t\t\t\tFree(tau);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow NotImplementedException();\n\t\t\t\t}\n\n\t\t\t\tFree(aCopy);\n\t\t\t}\n\n\t\t\ttemplate<>\n\t\t\tinline void Solve(const MemoryTile& A, MemoryTile& B, const MatrixOperation aOperation, const LinearSystemSolverType solver)\n\t\t\t{\n\t\t\t\t// Need to copy A, as it will be overwritten by its factorization\n\t\t\t\tMemoryTile aCopy(A);\n\t\t\t\tAlloc(aCopy);\n\t\t\t\tCopy(aCopy, A);\n\n\t\t\t\tconst auto nra = static_cast(A.nRows);\n\t\t\t\tconst auto lda = static_cast(A.leadingDimension);\n\t\t\t\tconst auto ncb = static_cast(B.nCols);\n\t\t\t\tconst auto ldb = static_cast(B.leadingDimension);\n\n\t\t\t\t// Initializes auxliary value for solver\n\t\t\t\tint info = 0;\n\n\t\t\t\tswitch (solver)\n\t\t\t\t{\n\t\t\t\t\tcase LinearSystemSolverType::Lu:\n\t\t\t\t\t{\n\t\t\t\t\t\t// allocate memory for pivoting\n\t\t\t\t\t\tMemoryBuffer pivot(0, A.nRows, A.memorySpace, MathDomain::Int);\n\t\t\t\t\t\tAlloc(pivot);\n\n\t\t\t\t\t\t// Factorize A (and overwrite it with L)\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_dgetrf(static_cast(columnMajorLayout), nra, nra, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(pivot.pointer));\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// Solve factorized system\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_dgetrs(static_cast(columnMajorLayout), openBlasOperation[static_cast(aOperation)], nra, ncb, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(pivot.pointer), reinterpret_cast(B.pointer), ldb);\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// free memory\n\t\t\t\t\t\tFree(pivot);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase LinearSystemSolverType::Qr:\n\t\t\t\t\t{\n\t\t\t\t\t\t// allocate memory for tau\n\t\t\t\t\t\tMemoryBuffer tau(0, A.nRows, A.memorySpace, MathDomain::Double);\n\t\t\t\t\t\tAlloc(tau);\n\n\t\t\t\t\t\t// A = Q * R\n\t\t\t\t\t\t/* int matrix_layout, lapack_int m, lapack_int n,\n\t\t\t\t\t\t\t\t double* a, lapack_int lda, double* tau */\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_dgeqrf(static_cast(columnMajorLayout), nra, nra, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(tau.pointer));\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// B = Q^T * B\n\t\t\t\t\t\t/*\n\t\t\t\t\t\t * int matrix_layout, char side, char trans,\n\t\t\t\t\t\t\t\t lapack_int m, lapack_int n, lapack_int k,\n\t\t\t\t\t\t\t\t const double* a, lapack_int lda, const double* tau,\n\t\t\t\t\t\t\t\t double* c, lapack_int ldc */\n\t\t\t\t\t\tinfo = GENERIC_API_NAMESPACE::LAPACKE_dormqr(static_cast(columnMajorLayout), 'L', 'T', nra, nra, ncb, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(tau.pointer), reinterpret_cast(B.pointer), ldb);\n\t\t\t\t\t\tif (info != 0)\n\t\t\t\t\t\t\tthrow OpenBlasException(__func__);\n\n\t\t\t\t\t\t// Solve (x = R \\ (Q^T * B))\n\t\t\t\t\t\tcblas_dtrsm(columnMajorLayout, GENERIC_API_NAMESPACE::CBLAS_SIDE::CblasLeft, GENERIC_API_NAMESPACE::CBLAS_UPLO::CblasUpper, operationsEnum[static_cast(aOperation)], GENERIC_API_NAMESPACE::CBLAS_DIAG::CblasNonUnit, nra, nra, 1.0, reinterpret_cast(aCopy.pointer), lda, reinterpret_cast(B.pointer), ldb);\n\n\t\t\t\t\t\t// free memory\n\t\t\t\t\t\tFree(tau);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow NotImplementedException();\n\t\t\t\t}\n\n\t\t\t\tFree(aCopy);\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ArgAbsMin(int& argMin, const MemoryBuffer& x);\n\n\t\t\ttemplate<>\n\t\t\tinline void ArgAbsMin(int&, const MemoryBuffer&)\n\t\t\t{\n\t\t\t\t// TODO: apparently there's isamax but not isamin??\n\t\t\t\t// argMin = static_cast(cblas_isamin(static_cast(x.size), reinterpret_cast(x.pointer), 1));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void ArgAbsMin(int&, const MemoryBuffer&)\n\t\t\t{\n\t\t\t\t// TODO: apparently there's isamax but not isamin??\n\t\t\t\t// argMin = static_cast(cblas_idamin(static_cast(x.size), reinterpret_cast(x.pointer), 1));\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ColumnWiseArgAbsMin(MemoryBuffer & argMin, const MemoryTile& A);\n\n\t\t\ttemplate<>\n\t\t\tinline void ColumnWiseArgAbsMin(MemoryBuffer&, const MemoryTile&)\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t\t//\t\tauto* argMinPtr = reinterpret_cast(argMin.pointer);\n\t\t\t\t//\t\t// 1 added for compatibility\n\t\t\t\t//\t\tfor (size_t j = 0; j < A.nCols; ++j)\n\t\t\t\t//\t\t\targMinPtr[j] = 1 + static_cast(cblas_isamin(static_cast(A.nRows), reinterpret_cast(A.pointer + j * A.nRows * A.ElementarySize()), 1));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void ColumnWiseArgAbsMin(MemoryBuffer&, const MemoryTile&)\n\t\t\t{\n\t\t\t\t// TODO\n\t\t\t\t//\t\t// 1 added for compatibility\n\t\t\t\t//\t\tauto* argMinPtr = reinterpret_cast(argMin.pointer);\n\t\t\t\t//\t\tfor (size_t j = 0; j < A.nCols; ++j)\n\t\t\t\t//\t\t\targMinPtr[j] = 1 + static_cast(cblas_idamin(static_cast(A.nRows), reinterpret_cast(A.pointer + j * A.nRows * A.ElementarySize()), 1));\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ArgAbsMax(int& argMax, const MemoryBuffer& x);\n\n\t\t\ttemplate<>\n\t\t\tinline void ArgAbsMax(int& argMax, const MemoryBuffer& x)\n\t\t\t{\n\t\t\t\targMax = static_cast(GENERIC_API_NAMESPACE::cblas_isamax(static_cast(x.size), reinterpret_cast(x.pointer), 1));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void ArgAbsMax(int& argMax, const MemoryBuffer& x)\n\t\t\t{\n\t\t\t\targMax = static_cast(GENERIC_API_NAMESPACE::cblas_idamax(static_cast(x.size), reinterpret_cast(x.pointer), 1));\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic void ColumnWiseArgAbsMax(MemoryBuffer & argMax, const MemoryTile& A);\n\n\t\t\ttemplate<>\n\t\t\tinline void ColumnWiseArgAbsMax(MemoryBuffer & argMax, const MemoryTile& A)\n\t\t\t{\n\t\t\t\t// 1 added for compatibility\n\t\t\t\tauto* argMaxPtr = reinterpret_cast(argMax.pointer);\n\t\t\t\tfor (size_t j = 0; j < A.nCols; ++j)\n\t\t\t\t\targMaxPtr[j] = 1 + static_cast(GENERIC_API_NAMESPACE::cblas_isamax(static_cast(A.nRows), reinterpret_cast(A.pointer + j * A.nRows * A.ElementarySize()), 1));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void ColumnWiseArgAbsMax(MemoryBuffer & argMax, const MemoryTile& A)\n\t\t\t{\n\t\t\t\t// 1 added for compatibility\n\t\t\t\tauto* argMaxPtr = reinterpret_cast(argMax.pointer);\n\t\t\t\tfor (size_t j = 0; j < A.nCols; ++j)\n\t\t\t\t\targMaxPtr[j] = 1 + static_cast(GENERIC_API_NAMESPACE::cblas_idamax(static_cast(A.nRows), reinterpret_cast(A.pointer + j * A.nRows * A.ElementarySize()), 1));\n\t\t\t}\n\n\t\t\t// norm = ||x||_2\n\t\t\ttemplate\n\t\t\tstatic void EuclideanNorm(double& norm, const MemoryBuffer& z);\n\n\t\t\ttemplate<>\n\t\t\tinline void EuclideanNorm(double& norm, const MemoryBuffer& z)\n\t\t\t{\n\t\t\t\tnorm = static_cast(GENERIC_API_NAMESPACE::cblas_snrm2(static_cast(z.size), reinterpret_cast(z.pointer), 1));\n\t\t\t}\n\t\t\ttemplate<>\n\t\t\tinline void EuclideanNorm(double& norm, const MemoryBuffer& z)\n\t\t\t{\n\t\t\t\tnorm = GENERIC_API_NAMESPACE::cblas_dnrm2(static_cast(z.size), reinterpret_cast(z.pointer), 1);\n\t\t\t}\n\t\t}\n\t}\t // namespace routines\n}\t // namespace cl\n\n#endif\n\n#undef GENERIC_API_DEFINE\n#undef GENERIC_API_NAMESPACE\n#undef GENERIC_API_ROUTINES_NAMESPACE\n#undef ROUTINES_NAMESPACE\n#undef BLAS_NAMESPACE\n", "meta": {"hexsha": "290a8cdda0fbbec94863989ea5a5983a3dcd14de", "size": 22751, "ext": "h", "lang": "C", "max_stars_repo_path": "HostRoutines/GenericBlasApiWrappers.h", "max_stars_repo_name": "pmontalb/CudaLight", "max_stars_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-25T17:54:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-30T23:34:21.000Z", "max_issues_repo_path": "HostRoutines/GenericBlasApiWrappers.h", "max_issues_repo_name": "pmontalb/CudaLight", "max_issues_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-03-04T22:26:42.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-13T12:57:46.000Z", "max_forks_repo_path": "HostRoutines/GenericBlasApiWrappers.h", "max_forks_repo_name": "pmontalb/CudaLight", "max_forks_repo_head_hexsha": "390efb41da88245b2f5909b84213fb5839d505cf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.5842911877, "max_line_length": 516, "alphanum_fraction": 0.7197046284, "num_tokens": 5849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.26993789687605746}} {"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#if 0\n/*\n\nPerforms y = ( G^T G )^{-1} ( G^T K G ) ( G^T G )^{-1} x\n\n\n*/\n\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"common-driver-utils.h\"\n\n#include \n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n #if (PETSC_VERSION_MINOR >=6)\n #include \"petsc/private/pcimpl.h\"\n #include \"petsc/private/kspimpl.h\"\n #else\n #include \"petsc-private/pcimpl.h\"\n #include \"petsc-private/kspimpl.h\"\n #endif\n#else\n #include \"private/pcimpl.h\"\n #include \"private/kspimpl.h\"\n#endif\n\n\n#include \"pc_ScaledGtKG.h\"\n\n#include \n#include \n\n#define PCTYPE_SCGtKG \"scgtkg\"\n\n\n/* private data */\n\ntypedef struct {\n\tMat B, Bt, F, C; /* Bt \\in [M x N], F \\in [M x M] */\n\tVec X1,X2, Y1,Y2; /* the scaling vectors */\n\tVec s,t,X; /* s \\in [M], t \\in [N], X \\in [M] */\n\tKSP ksp_BBt; /* The user MUST provide this operator */\n\tPetscTruth BBt_has_cnst_nullspace;\n\tPetscTruth monitor_activated;\n} _PC_SC_GtKG;\n\ntypedef _PC_SC_GtKG* PC_SC_GtKG;\n\n\n/* private prototypes */\nPetscErrorCode BSSCR_PCApply_ScGtKG( PC pc, Vec x, Vec y );\nPetscErrorCode BSSCR_PCApplyTranspose_ScGtKG( PC pc, Vec x, Vec y );\nPetscErrorCode BSSCR_PCSetUp_GtKG( PC pc );\n\n\nPetscErrorCode BSSCR_BSSCR_pc_error_ScGtKG( PC pc, const char func_name[] ) \n{\n\tconst PCType type;\n\tPCGetType( pc, &type );\n\t\n\tif( strcmp(type,PCTYPE_SCGtKG)!=0 ) {\n\t\tprintf(\"Error(%s): PC type (%s) should be scgtkg. \\n\",func_name, type );\n\t\tPetscFinalize();\n\t\texit(0);\n\t}\n\tPetscFunctionReturn(0);\n}\n\n\nvoid BSSCR_BSSCR_get_number_nonzeros_AIJ_ScGtKG( Mat A, PetscInt *nnz )\n{\n\tMatInfo info;\n\t\n\tMatGetInfo( A, MAT_GLOBAL_SUM, &info );\n\t*nnz = info.nz_used;\n\t\n}\n\nPetscErrorCode BSSCR_PCScGtKGBBtContainsConstantNullSpace( PC pc, PetscTruth *has_cnst_nullsp )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\tPetscInt N;\n\tPetscScalar sum;\n\tPetscReal nrm;\n\tVec l,r;\n\tMat BBt,A;\n\t\n\t\n\tStg_KSPGetOperators( ctx->ksp_BBt, &BBt, PETSC_NULL, PETSC_NULL );\n\tA = BBt;\n\t\n\tMatGetVecs( A, &r, &l ); // l = A r\n\t\n\t\n\tVecGetSize(r,&N);\n\tsum = 1.0/N;\n\tVecSet(r,sum);\n\t\n\t/* scale */\n\tVecPointwiseMult( r, r, ctx->Y2 );\n\t/* {l} = [A] {r} */\n\tMatMult( A,r, l );\n\t/* scale */\n\tVecPointwiseMult( l, l, ctx->X2 );\n\t\n\tVecNorm(l,NORM_2,&nrm);\n\tif (nrm < 1.e-7) {\n\t\t*has_cnst_nullsp = PETSC_TRUE;\n\t}\n\telse {\n\t\t*has_cnst_nullsp = PETSC_FALSE;\n\t}\n\t\n\tStg_VecDestroy(&l);\n\tStg_VecDestroy(&r);\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n/*\nI should not modify setup called!!\nThis is handled via petsc.\n*/\nPetscErrorCode BSSCR_PCSetUp_ScGtKG( PC pc )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tif( ctx->F == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, \"gtkg: F not set\" ); }\n\tif( ctx->Bt == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, \"gtkg: Bt not set\" ); }\n\t\n\tif(ctx->ksp_BBt==PETSC_NULL) {\n\t\tBSSCR_PCScGtKGUseStandardBBtOperator( pc ) ;\n\t}\n\t\n\tBSSCR_PCScGtKGBBtContainsConstantNullSpace( pc, &ctx->BBt_has_cnst_nullspace );\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t\tPetscPrintf( PETSC_COMM_WORLD, \"\\t* Detected prescence of constant nullspace in BBt-C\\n\" );\n\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCDestroy_ScGtKG( PC pc )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\t\n\tif( ctx == PETSC_NULL ) {\tPetscFunctionReturn(0); }\n\t\n\tif( ctx->ksp_BBt != PETSC_NULL ) {\tStg_KSPDestroy(&ctx->ksp_BBt );\t\t}\n\t\n\tif( ctx->s != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->s );\t\t}\n\tif( ctx->X != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->X );\t\t}\n\tif( ctx->t != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->t );\t\t}\n\t\n\tif( ctx->X1 != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->X1 );\t\t}\n\tif( ctx->X2 != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->X2 );\t\t}\n\tif( ctx->Y1 != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->Y1 );\t\t}\n\tif( ctx->Y2 != PETSC_NULL ) {\t\tStg_VecDestroy(&ctx->Y2 );\t\t}\n\t\n\tPetscFree( ctx );\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCView_ScGtKG( PC pc, PetscViewer viewer )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tPetscViewerASCIIPushTab(viewer); //1\n\t\n\t\n\tPetscViewerASCIIPrintf( viewer, \"gtkg-ksp \\n\" );\n\tPetscViewerASCIIPrintf(viewer,\"---------------------------------\\n\");\n\tPetscViewerASCIIPushTab(viewer);\n\t\tKSPView( ctx->ksp_BBt, viewer );\n\tPetscViewerASCIIPopTab(viewer);\n\tPetscViewerASCIIPrintf(viewer,\"---------------------------------\\n\");\n\t\n\tPetscViewerASCIIPopTab(viewer); //1\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCRBSSCR_Lp_monitor_ScGtKG( KSP ksp, PetscInt index )\n{\n\tPetscInt max_it;\n\tPetscReal rnorm;\n\tKSPConvergedReason reason;\n\t\n\t\n\tKSPGetIterationNumber( ksp, &max_it );\n\tKSPGetResidualNorm( ksp, &rnorm );\n\tKSPGetConvergedReason( ksp, &reason );\n\tif (reason >= 0) {\n\t\tPetscPrintf(((PetscObject)ksp)->comm,\"\\t: Linear solve converged. its.=%.4d ; |r|=%5.5e ; Reason=%s\\n\", \n\t\t\t\tindex, max_it, rnorm, KSPConvergedReasons[reason] );\n\t} else {\n\t\tPetscPrintf(((PetscObject)ksp)->comm,\"\\t: Linear solve did not converge. its.=%.4d ; |r|=%5.5e ; Residual reduction=%2.2e ; Reason=%s\\n\", \n\t\t\t\tindex, max_it, rnorm, (ksp->rnorm0/rnorm), KSPConvergedReasons[reason]);\n\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCScBFBTSubKSPMonitor( KSP ksp, PetscInt index, PetscLogDouble time )\n{\n\tPetscInt max_it;\n\tPetscReal rnorm;\n\tKSPConvergedReason reason;\n\t\n\tKSPGetIterationNumber( ksp, &max_it );\n\tKSPGetResidualNorm( ksp, &rnorm );\n\tKSPGetConvergedReason( ksp, &reason );\n\tPetscPrintf(((PetscObject)ksp)->comm,\" PCScBFBTSubKSP (%d): %D Residual norm; r0 %12.12e, r %12.12e: Reason %s: Time %5.5e \\n\", \n\t\t\tindex, max_it, ksp->rnorm0, rnorm, KSPConvergedReasons[reason], time );\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n/* \nPerforms y <- S*^{-1} x \n S*^{-1} = ( B' Bt' )^{-1} B' F' Bt' ( B' Bt' )^{-1}\nwhere \n F' = X1 F Y1\n Bt' = X1 Bt Y2\n B' = X2 B Y1\n\nThus, S*^{-1} = [ X2 B Y1 X1 Bt Y2 ]^{-1} . [ X2 B Y1 . X1 F Y1 . X1 Bt Y2 ] . [ X2 B Y1 X1 Bt Y2 ]^{-1}\n = Y2^{-1} ksp_BBt X2^{-1} . [ B' F' Bt' ] . Y2^{-1} ksp_BBt X2^{-1}\n = Y2^{-1} ksp_BBt . [ B Y1 . X1 F Y1 . X1 Bt ] . ksp_BBt X2^{-1}\n*/\nPetscErrorCode BSSCR_PCApply_ScGtKG( PC pc, Vec x, Vec y )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat F, Bt;\n\tVec s,t,X;\n\tPetscLogDouble t0,t1;\n\t\n\tksp = ctx->ksp_BBt;\n\tF = ctx->F;\n\tBt = ctx->Bt;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\t\n\t\n\t/* Apply scaled Poisson operator */\n\t/* scale x */ \n\t/* ======================================================== \n\t NOTE:\n\t I THINK TO OMIT THESE AS WE WANT TO UNSCALE THE \n\t PRECONDITIONER AS S IN THIS CASE IS NOT SCALED \n\t======================================================== */\n//\tVecPointwiseDivide( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */\n\t\n\t\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t BSSCR_VecRemoveConstNullspace( x, PETSC_NULL );\n\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, x, t ); /* t <- GtG_inv x */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\n\t\tBSSCR_PCScBFBTSubKSPMonitor(ksp,1,(t1-t0));\t\t\n\t}\n\t\n\t/* Apply Bt */\n\tMatMult( Bt, t, s ); /* s <- G t */\n\tVecPointwiseMult( s, s, ctx->X1 ); /* s <- s * X1 */\n\t\n\t\n\t/* Apply F */\n\tVecPointwiseMult( s, s, ctx->Y1 ); /* s <- s * Y1 */\n\tMatMult( F, s, X ); /* X <- K s */\n\tVecPointwiseMult( X, X, ctx->X1 ); /* X <- X * X1 */\n\t\n\t/* Apply B */\n\tVecPointwiseMult( X, X, ctx->Y1 ); /* X <- X * Y1 */\n\tMatMultTranspose( Bt, X, t ); /* t <- Gt X */\n\t\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t\tBSSCR_VecRemoveConstNullspace( t, PETSC_NULL );\n\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, t, y ); /* y <- GtG_inv t */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\n\t\tBSSCR_PCScBFBTSubKSPMonitor(ksp,2,(t1-t0));\n\t}\n\t\n\tVecPointwiseMult( y, y, ctx->Y2 ); /* y <- y/Y2 */ \n\t\n\t\n\t/* undo modification made to x on entry */\n//\tVecPointwiseMult( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n/* \nPerforms y <- S*^{-1} x \n S*^{-1} = ( B' Bt' )^{-1} B' F' Bt' - C' ( B' Bt' )^{-1}\nwhere \n F' = X1 F Y1\n Bt' = X1 Bt Y2\n B' = X2 B Y1\n C' = X2 C Y2\n\nThus, S*^{-1} = [ X2 B Y1 X1 Bt Y2 ]^{-1} . [ X2 B Y1 . X1 F Y1 . X1 Bt Y2 - X2 C Y2 ] . [ X2 B Y1 X1 Bt Y2 ]^{-1}\n = Y2^{-1} ksp_BBt X2^{-1} . [ B' F' Bt' - C' ] . Y2^{-1} ksp_BBt X2^{-1}\n = Y2^{-1} ksp_BBt . [ B Y1 . X1 F Y1 . X1 Bt - C ] . ksp_BBt X2^{-1}\n*/\nPetscErrorCode BSSCR_BSSCR_PCApply_ScGtKG_C( PC pc, Vec x, Vec y )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat F, Bt,C;\n\tVec s,t,X;\n\tPetscLogDouble t0,t1;\n\t\n\t\n\tksp = ctx->ksp_BBt;\n\tF = ctx->F;\n\tBt = ctx->Bt;\n\tC = ctx->C;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\t\n\t\n\t/* Apply scaled Poisson operator */\n\t/* scale x */ \n\t/* ======================================================== \n\t NOTE:\n\t I THINK TO OMIT THESE AS WE WANT TO UNSCALE THE \n\t PRECONDITIONER AS S IN THIS CASE IS NOT SCALED \n\t======================================================== */\n//\tVecPointwiseDivide( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */\n\t\n\t\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t\tBSSCR_VecRemoveConstNullspace( x, PETSC_NULL );\n\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, x, t ); /* t <- GtG_inv x */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\n\t\tBSSCR_PCScBFBTSubKSPMonitor(ksp,1,(t1-t0));\n\t}\n\t\n\t/* Apply Bt */\n\tMatMult( Bt, t, s ); /* s <- G t */\n\tVecPointwiseMult( s, s, ctx->X1 ); /* s <- s * X1 */\n\t\n\t\n\t/* Apply F */\n\tVecPointwiseMult( s, s, ctx->Y1 ); /* s <- s * Y1 */\n\tMatMult( F, s, X ); /* X <- K s */\n\tVecPointwiseMult( X, X, ctx->X1 ); /* X <- X * X1 */\n\t\n\t/* Apply B */\n\tVecPointwiseMult( X, X, ctx->Y1 ); /* X <- X * Y1 */\n\tMatMultTranspose( Bt, X, s ); /* s <- Gt X */\n\t\n\t/* s <- s - C t */\n\tVecScale( s, -1.0 );\n\tMatMultAdd( C, t, s, s );\n\tVecScale( s, -1.0 );\n\t\n\t\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t\tBSSCR_VecRemoveConstNullspace( s, PETSC_NULL );\n\t}\n\tPetscGetTime(&t0);\n\tKSPSolve( ksp, s, y ); /* y <- GtG_inv s */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\n\t\tBSSCR_PCScBFBTSubKSPMonitor(ksp,2,(t1-t0));\n\t}\n\t\n\tVecPointwiseMult( y, y, ctx->Y2 ); /* y <- y/Y2 */ \n\t\n\t\n\t/* undo modification made to x on entry */\n//\tVecPointwiseMult( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n/* Need to check this one if correct */\n/*\nS^{-1} = ( G^T G )^{-1} G^T K G ( G^T G )^{-1}\n = A C A\nS^{-T} = A^T (A C)^T\n = A^T C^T A^T, but A = G^T G which is symmetric\n = A C^T A\n = A G^T ( G^T K )^T A\n = A G^T K^T G A\n\n*/\nPetscErrorCode BSSCR_PCApplyTranspose_ScGtKG( PC pc, Vec x, Vec y )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tKSP ksp;\n\tMat F, Bt;\n\tVec s,t,X;\n\tPetscLogDouble t0,t1;\n\t\n\t\n\tksp = ctx->ksp_BBt;\n\tF = ctx->F;\n\tBt = ctx->Bt;\n\ts = ctx->s;\n\tt = ctx->t;\n\tX = ctx->X;\n\t\n\t\n\t\n\t/* Apply scaled Poisson operator */\n\t/* scale x */ \n\t/* ======================================================== \n\t NOTE:\n\t I THINK TO OMIT THESE AS WE WANT TO UNSCALE THE \n\t PRECONDITIONER AS S IN THIS CASE IS NOT SCALED \n\t======================================================== */\n//\tVecPointwiseDivide( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */\n\t\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t\tBSSCR_VecRemoveConstNullspace( x, PETSC_NULL );\n\t}\n\tPetscGetTime(&t0);\n\tKSPSolveTranspose( ksp, x, t ); /* t <- GtG_inv x */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\n\t\tBSSCR_PCScBFBTSubKSPMonitor(ksp,1,(t1-t0));\n\t}\n\t\n\t/* Apply Bt */\n\tMatMult( Bt, t, s ); /* s <- G t */\n\tVecPointwiseMult( s, s, ctx->X1 ); /* s <- s * X1 */\n\t\n\t\n\t/* Apply F */\n\tVecPointwiseMult( s, s, ctx->Y1 ); /* s <- s * Y1 */\n\tMatMultTranspose( F, s, X ); /* X <- K s */\n\tVecPointwiseMult( X, X, ctx->X1 ); /* X <- X * X1 */\n\t\n\t/* Apply B */\n\tVecPointwiseMult( X, X, ctx->Y1 ); /* X <- X * Y1 */\n\tMatMultTranspose( Bt, X, t ); /* t <- Gt X */\n\t\n\tif( ctx->BBt_has_cnst_nullspace == PETSC_TRUE ) {\n\t\tBSSCR_VecRemoveConstNullspace( t, PETSC_NULL );\n\t}\n\tPetscGetTime(&t0);\n\tKSPSolveTranspose( ksp, t, y ); /* y <- GtG_inv t */\n\tPetscGetTime(&t1);\n\tif (ctx->monitor_activated) {\n\t\tBSSCR_PCScBFBTSubKSPMonitor(ksp,2,(t1-t0));\n\t}\n\t\n\tVecPointwiseMult( y, y, ctx->Y2 ); /* y <- y/Y2 */ \n\t\n\t\n\t/* undo modification made to x on entry */\n//\tVecPointwiseMult( x, x, ctx->X2 ); /* x <- x/X2 */ /* NEED TO BE SURE */\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n/* \nPerforms y <- S^{-1} x \nS^{-1} = ( G^T Di G )^{-1} G^T Di K Di G ( G^T Di G )^{-1}\nwhere Di = diag(M)^{-1}\n*/\n\n\n\n/*\nOnly the options related to GtKG should be set here.\n*/\nPetscErrorCode BSSCR_PCSetFromOptions_ScGtKG( PC pc )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\tPetscTruth ivalue, flg;\n\t\n\tif(ctx->ksp_BBt!=PETSC_NULL) {\n\t\tPetscOptionsGetTruth( PETSC_NULL, \"-pc_gtkg_monitor\", &ivalue, &flg );\n\t\tBSSCR_PCScGtKGSetSubKSPMonitor( pc, ivalue );\n\t\t\n\t}\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n\n/* ---- Exposed functions ---- */\n\nPetscErrorCode BSSCR_PCCreate_ScGtKG( PC pc )\n{\n\tPC_SC_GtKG pc_data;\n\tPetscErrorCode ierr;\n\t\n\t/* create memory for ctx */\n\tierr = Stg_PetscNew( _PC_SC_GtKG,&pc_data);CHKERRQ(ierr);\n\t\n\t/* init ctx */\n\tpc_data->F = PETSC_NULL;\n\tpc_data->Bt = PETSC_NULL;\n\tpc_data->B = PETSC_NULL;\n\tpc_data->BBt_has_cnst_nullspace = PETSC_FALSE;\n\tpc_data->ksp_BBt = PETSC_NULL;\n\tpc_data->monitor_activated = PETSC_FALSE;\n\t\n\tpc_data->X1 = PETSC_NULL;\n\tpc_data->X2 = PETSC_NULL;\n\tpc_data->Y1 = PETSC_NULL;\n\tpc_data->Y2 = PETSC_NULL;\n\t\n\tpc_data->s = PETSC_NULL;\n\tpc_data->t = PETSC_NULL;\n\tpc_data->X = PETSC_NULL;\n\t\n\t\n\t\n\t/* set ctx onto pc */\n\tpc->data = (void*)pc_data;\n\t\n\tierr = PetscLogObjectMemory(pc,sizeof(_PC_SC_GtKG));CHKERRQ(ierr);\n\t\n\t/* define operations */\n\tpc->ops->setup = BSSCR_PCSetUp_ScGtKG;\n\tpc->ops->view = BSSCR_PCView_ScGtKG;\n\tpc->ops->destroy = BSSCR_PCDestroy_ScGtKG;\n\tpc->ops->setfromoptions = BSSCR_PCSetFromOptions_ScGtKG;\n\t\n\tpc->ops->apply = BSSCR_PCApply_ScGtKG;\n\tpc->ops->applytranspose = BSSCR_PCApplyTranspose_ScGtKG;\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_PCScGtKGGetScalings( PC pc, Vec *X1, Vec *X2, Vec *Y1, Vec *Y2 )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\tif( X1 != PETSC_NULL ) { *X1 = ctx->X1; }\n\tif( X2 != PETSC_NULL ) { *X2 = ctx->X2; }\n\t\n\tif( Y1 != PETSC_NULL ) { *Y1 = ctx->Y1; }\n\tif( Y2 != PETSC_NULL ) { *Y2 = ctx->Y2; }\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\n/*\nF & Bt must different to PETSC_NULL\nB may be PETSC_NULL\nC can be PETSC_NULL\n*/\nPetscErrorCode BSSCR_PCScGtKGSetOperators( PC pc, Mat F, Mat Bt, Mat B, Mat C )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\t\n\tctx->F = F;\n\tctx->Bt = Bt;\n\tctx->B = B;\n\tctx->C = C;\n\t\n\tif( C != PETSC_NULL ) {\n\t\tpc->ops->apply = BSSCR_BSSCR_PCApply_ScGtKG_C;\n\t\tpc->ops->applytranspose = PETSC_NULL;\n\t}\n\t\n\t/* Create vectors */\n\tif( ctx->s == PETSC_NULL ) { MatGetVecs( ctx->F, &ctx->s, PETSC_NULL ); }\n\tif( ctx->X == PETSC_NULL ) { MatGetVecs( ctx->F, PETSC_NULL, &ctx->X ); }\n\tif( ctx->t == PETSC_NULL ) { MatGetVecs( ctx->Bt, &ctx->t, PETSC_NULL ); }\n\t\n\tif( ctx->F == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, \"gtkg: F not set\" ); }\n\tif( ctx->Bt == PETSC_NULL ) { Stg_SETERRQ( PETSC_ERR_SUP, \"gtkg: Bt not set\" ); }\n\t\n\tif( ctx->X1 == PETSC_NULL ) { MatGetVecs( ctx->F, &ctx->X1, PETSC_NULL ); }\n\tif( ctx->Y1 == PETSC_NULL ) { MatGetVecs( ctx->F, &ctx->Y1, PETSC_NULL ); }\n\tif( ctx->X2 == PETSC_NULL ) { MatGetVecs( ctx->Bt, &ctx->X2, PETSC_NULL ); }\n\tif( ctx->Y2 == PETSC_NULL ) { MatGetVecs( ctx->Bt, &ctx->Y2, PETSC_NULL ); }\n\t\n\tVecSet( ctx->X1, 1.0 );\n\tVecSet( ctx->Y1, 1.0 );\n\tVecSet( ctx->X2, 1.0 );\n\tVecSet( ctx->Y2, 1.0 );\n\t\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_PCScGtKGAttachNullSpace( PC pc )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\tMatNullSpace nsp;\n\t\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\t/* Attach a null space */\n\tMatNullSpaceCreate( PETSC_COMM_WORLD, PETSC_TRUE, PETSC_NULL, PETSC_NULL, &nsp );\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR <6) )\n\tKSPSetNullSpace( ctx->ksp_BBt, nsp );\n#else\n Mat A;\n KSPGetOperators(ctx->ksp_BBt,&A,NULL);//Note: DOES NOT increase the reference counts of the matrix, so you should NOT destroy them. \n MatSetNullSpace( A, nsp);\n#endif\n\t/* \n\tNOTE: This does NOT destroy the memory for nsp, it just decrements the nsp->refct, so that\n\tthe next time MatNullSpaceDestroy() is called, the memory will be released. The next time this\n\tis called will be by KSPDestroy();\n\t*/\n\tMatNullSpaceDestroy( nsp );\n\t\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCScGtKGGetKSP( PC pc, KSP *ksp )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\t\n\tif( ksp != PETSC_NULL ) {\n\t\t(*ksp) = ctx->ksp_BBt;\n\t}\n\t\n\tPetscFunctionReturn(0);\n}\n\nPetscErrorCode BSSCR_PCScGtKGSetKSP( PC pc, KSP ksp )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\t\n\tif( ctx->ksp_BBt != PETSC_NULL ) {\n\t\tStg_KSPDestroy(&ctx->ksp_BBt);\n\t}\n\t\n\tPetscObjectReference( (PetscObject)ksp );\n\tctx->ksp_BBt = ksp;\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_PCScGtKGSetSubKSPMonitor( PC pc, PetscTruth flg )\n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\t\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\tctx->monitor_activated = flg;\n\t\n\tPetscFunctionReturn(0);\n}\n\n\nPetscErrorCode BSSCR_PCScGtKGUseStandardScaling( PC pc ) \n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\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\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\t\n\tL1 = ctx->X1;\n\tL2 = ctx->X2;\n\t\n\tR1 = ctx->Y1;\n\tR2 = ctx->Y2;\n\t\n\t\n\trA = L1;\n\trC = L2;\n\t\n\tK = ctx->F;\n\tG = ctx->Bt;\n\tD = ctx->B;\n\tC = ctx->C;\n\t\n\tVecDuplicate( rA, &rG );\n\t\n\t/* Get magnitude of K */ \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\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 );\n\t\n\tPetscFunctionReturn(0);\n}\n\n/*\nBuilds \n B Y1 X1 Bt \nand creates a ksp when C=0, otherwise it builds \n B Y1 X1 Bt - C\n*/\nPetscErrorCode BSSCR_PCScGtKGUseStandardBBtOperator( PC pc ) \n{\n\tPC_SC_GtKG ctx = (PC_SC_GtKG)pc->data;\n\tPetscReal fill;\n\tMat diag_mat,C;\n\tVec diag;\n\tPetscInt M,N, m,n;\n\tMPI_Comm comm;\n\tPetscInt nnz_I, nnz_G;\n\tMatType mtype;\n\tconst char *prefix;\n\tMat BBt;\n\tKSP ksp;\n\tPetscTruth ivalue, flg, has_cnst_nullsp;\n\t\n\t\n\tBSSCR_BSSCR_pc_error_ScGtKG( pc, __func__ );\n\t\n\t/* Assemble BBt */\n\tMatGetSize( ctx->Bt, &M, &N );\n\tMatGetLocalSize( ctx->Bt, &m, &n );\n\t\n\tMatGetVecs( ctx->Bt, PETSC_NULL, &diag );\n\t\n\t/* Define diagonal matrix Y1 X1 */\n\tVecPointwiseMult( diag, ctx->Y1, ctx->X1 );\n\t\n\tPetscObjectGetComm( (PetscObject)ctx->F, &comm ); \n\tMatCreate( comm, &diag_mat );\n\tMatSetSizes( diag_mat, m,m , M, M );\n#if (((PETSC_VERSION_MAJOR==3) && (PETSC_VERSION_MINOR>=3)) || (PETSC_VERSION_MAJOR>3) )\n MatSetUp(diag_mat);\n#endif\n\tMatGetType( ctx->Bt, &mtype );\n\tMatSetType( diag_mat, mtype );\n\t\n\tMatDiagonalSet( diag_mat, diag, INSERT_VALUES );\n\t\n\t/* Build operator B Y1 X1 Bt */\n\tBSSCR_BSSCR_get_number_nonzeros_AIJ_ScGtKG( diag_mat, &nnz_I );\n\tBSSCR_BSSCR_get_number_nonzeros_AIJ_ScGtKG( ctx->Bt, &nnz_G );\n\t/* \n\tNot sure the best way to estimate the fill factor.\n\tBBt is a laplacian on the pressure space. \n\tThis might tell us something useful...\n\t*/\n\tfill = (PetscReal)(nnz_G)/(PetscReal)( nnz_I );\n\tMatPtAP( diag_mat, ctx->Bt, MAT_INITIAL_MATRIX, fill, &BBt );\n\t\n\tStg_MatDestroy(&diag_mat );\n\tStg_VecDestroy(&diag );\n\t\n\t\n\tC = ctx->C;\n\tif( C !=PETSC_NULL ) {\n\t\tMatAXPY( BBt, -1.0, C, DIFFERENT_NONZERO_PATTERN );\n\t}\n\t\n\t\n\t/* Build the solver */\n\tKSPCreate( ((PetscObject)pc)->comm, &ksp );\n\t\n\tStg_KSPSetOperators( ksp, BBt, BBt, SAME_NONZERO_PATTERN );\n\t\n\tPCGetOptionsPrefix( pc,&prefix );\n\tKSPSetOptionsPrefix( ksp, prefix );\n\tKSPAppendOptionsPrefix( ksp, \"pc_gtkg_\" ); /* -pc_GtKG_ksp_type , -ksp_GtKG_pc_type */\n\t\n\tBSSCR_PCScGtKGSetKSP( pc, ksp );\n\t\n\tBSSCR_MatContainsConstNullSpace( BBt, NULL, &has_cnst_nullsp );\n\tif( has_cnst_nullsp == PETSC_TRUE ) {\n\t\tBSSCR_PCScGtKGAttachNullSpace( pc );\n\t}\n\t\n\tPetscOptionsGetTruth( PETSC_NULL, \"-pc_gtkg_monitor\", &ivalue, &flg );\n\tBSSCR_PCScGtKGSetSubKSPMonitor( pc, ivalue );\n\t\n\tStg_KSPDestroy(&ksp);\n\tStg_MatDestroy(&BBt);\n\t\n\tPetscFunctionReturn(0);\n}\n\n#endif\n\n", "meta": {"hexsha": "a340d405c50ef9e211278fa82e8199623cdfb402", "size": 21246, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/pc_ScaledGtKG.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/pc_ScaledGtKG.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/pc_ScaledGtKG.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.5902777778, "max_line_length": 148, "alphanum_fraction": 0.6039725125, "num_tokens": 8070, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526368038304, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.2693599255257554}} {"text": "/**\n */\n#include \"aXe_grism.h\"\n#include \n#include \n#include \n#include \n#include \"fringe_conf.h\"\n#include \"fringe_model.h\"\n#include \"fringe_utils.h\"\n\n#define MIN(x,y) (((x)<(y))?(x):(y))\n#define MAX(x,y) (((x)>(y))?(x):(y))\n\n\n/**\n * Function: fringe_correct_PET\n * Performs fringe corrections to PET pixel lists\n *\n * The main function to compute and perform the fringe\n * correction to a list of PET pixels. for every pixel in\n * the PET list the pixel throughput function is \n * computed, and the relevant information from\n * the fringing model is extracted. Then the fringe\n * amplitude is computed and the count value of the pixel\n * is corrected. Also the PET pixel list is simultaneously\n * parsed and corrected for the fringing.\n *\n * Parameters:\n * @param fconf - the fringe configuration file\n * @param act_beam - the beam aperture\n * @param obj_pet - the PET pixel\n * @param bck_pet - the PET pixel\n */\nvoid\nfringe_correct_PET(const fringe_conf *fconf, const beam act_beam,\n\t\t ap_pixel *obj_pet, ap_pixel *bck_pet)\n{\n ap_pixel *obj_pix=NULL;\n ap_pixel *bck_pix=NULL;\n\n //d_point angles;\n pixel_tput *p_tput ;\n gsl_vector **tput_vectors=NULL;\n\n //int ii=0;\n //int jj=0;\n int index;\n int pix_index;\n\n double lambda_mean;\n double pixel_ampl;\n double fringe_factor;\n double fringe_tot;\n\n optical_property *optprops;\n\n // allocate the pixel throughput structure\n p_tput = alloc_pixel_tput();\n\n // allocate memory for the optical property structure \n optprops = alloc_optprops_list(fconf);\n\n // compute the mean wavelength\n lambda_mean = (gsl_vector_get(fconf->fringe_range, 0) +\n (gsl_vector_get(fconf->fringe_range, 1)\n - gsl_vector_get(fconf->fringe_range, 0))/2.0)/1.0e+04;\n\n // initialize some values in the optical property list\n init_optprops_list(fconf, lambda_mean, optprops);\n\n // initialize the PET pixel storages\n obj_pix = obj_pet;\n bck_pix = bck_pet;\n\n fringe_tot = 0.0;\n pix_index = 0;\n // go over the whole PET list\n while (obj_pix->p_x != -1)\n {\n // check whether the pixel has to be fringe corrected\n // at all, based on boundaries given in the configuration\n if ( obj_pix->lambda < gsl_vector_get(fconf->fringe_range, 0)\n \t || obj_pix->lambda > gsl_vector_get(fconf->fringe_range, 1)\n \t || obj_pix->dlambda > fconf->max_dispersion)\n \t{\n\n \t // count up the object PET \n \t obj_pix++;\n\n \t // count up the background PET\n \t if (bck_pet)\n \t bck_pix++;\n \n \t // jump to the next PET pixel\n \t continue;\n \t}\n\n // determine the filter throughput values\n // tput_vectors = evaluate_pixel_throughput(fconf, act_beam, obj_pix);\n // for the ISR with the WFC value\n tput_vectors = get_gauss_throughput(fconf, obj_pix, 80.0);\n\n // fill the optical thickness of the layers\n // into the structure\n fill_optprops_thickness(fconf->opt_layers, obj_pix->p_x,\n\t\t\t obj_pix->p_y, optprops);\n\n pixel_ampl = 0.0;\n for (index=0; index < (int)tput_vectors[0]->size; index++)\n\t{\n\t // fill all information in the optical\n\t // property list\n\t fill_optprops_all(fconf->opt_layers,\n\t\t\t gsl_vector_get(tput_vectors[0],index),\n\t\t\t optprops);\n\t \n\t // compute and add the contribution at a wavelength\n\t pixel_ampl += gsl_vector_get(tput_vectors[1],index)*\n\t fringe_contrib_single(optprops, fconf);\n\t}\n\n //put together the fringe correction factor\n fringe_factor = fconf->fringe_amp * pixel_ampl + 1.0;\n#ifdef DEBUGFCONF\n fprintf(stderr, \"Wavelength: %f, dispersion: %f, fringe factor: %f, (x,y): (%i, %i)\\n\", \n\t obj_pix->lambda, obj_pix->dlambda, fringe_factor, obj_pix->p_x, obj_pix->p_y);\n#endif\n\n // correct the object PET\n obj_pix->count /= fringe_factor;\n //obj_pix->count = fringe_factor;\n //fprintf(stdout, \"%e \",obj_pix->count); \n\n fringe_tot += fringe_factor;\n pix_index++;\n\n\n // treat the background PET pixel\n if (bck_pet)\n\t{\n\t if (bck_pix->p_x != obj_pix->p_x || bck_pix->p_y != obj_pix->p_y)\n\t aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n\t\t\t \"aXe_FRINGECORR: The sequence of pixels\\n\"\n\t\t\t \"in the object PET and background PET differs.\\n\"\n\t\t\t \"Something must be wrong!\\n\");\n\n\t // correct also the background PET\n\t bck_pix->count /= fringe_factor;\n\n\t // count up the background PET\n\t bck_pix++;\n\t}\n\n // count up the object PET\n obj_pix++;\n // obj_pix->p_x = -1;\n }\n\n // if (pix_index)\n // fprintf(stdout,\"Mean fringe factor: %f\\n\", fringe_tot/(double)pix_index);\n\n if (tput_vectors)\n {\n // release the memory in the vectors\n gsl_vector_free(tput_vectors[0]);\n gsl_vector_free(tput_vectors[1]);\n free(tput_vectors);\n }\n\n // free the optical property structure\n free_optprops_list(optprops);\n\n // free the memory\n free_pixel_tput(p_tput);\n}\n\n\n/**\n * Function: evaluate_pixel_throughput\n * Computes the wavelength and filter throughputs for a PET pixel.\n *\n * The function computes and returns two vector, one with wavelength\n * steps and the second with the pixel throughputs at those wavelengths.\n * This data is computed to a single PET pixel according to the settings\n * in the fringe configuration file.\n * \n * Parameters:\n * @param fconf - the fringe configuration file\n * @param act_beam - the beam aperture\n * @param obj_pix - the PET pixel\n *\n * Returns:\n * @return double_vector - the wavelength and filter throughput steps\n */\ngsl_vector **\nevaluate_pixel_throughput(const fringe_conf *fconf,\n\t\t\t const beam act_beam, const ap_pixel *obj_pix)\n{\n pixel_tput *p_tput ;\n\n gsl_vector **double_vector;\n gsl_vector *lambda_values;\n gsl_vector *through_values;\n\n interpolator *interp;\n\n double stepsize;\n double lambda_act;\n double through_act;\n double through_tot;\n\n double abs_min;\n double abs_max;\n\n int index;\n\n // allocate the pixel throughput structure\n p_tput = alloc_pixel_tput();\n\n // allocate the space for the vectors\n lambda_values = gsl_vector_alloc(fconf->num_steps + 1);\n through_values = gsl_vector_alloc(fconf->num_steps + 1);\n\n // allocate space for the return vector\n double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *));\n\n compute_pixel_tput(act_beam, obj_pix, p_tput);\n#ifdef DEBUGFCONF\n print_pixel_tput(p_tput);\n#endif\n // convert the pixel throughput information\n // into an interplator \n interp = create_interp_tput(p_tput);\n\n abs_min = MAX(interp->xmin, gsl_vector_get(fconf->fringe_range, 0));\n abs_max = MIN(interp->xmax, gsl_vector_get(fconf->fringe_range, 1));\n \n // compute the steps in wavelength\n stepsize = (abs_max - abs_min)/(double)fconf->num_steps;\n\n // set the lower wavelength end\n lambda_act = abs_min;\n\n // loop over the wavelength\n through_tot = 0.0;\n for (index=0; index < fconf->num_steps; index++)\n {\n // set the wavelength value\n gsl_vector_set(lambda_values, index, lambda_act);\n\n // compute the throughput\n through_act = eval_interp(interp, lambda_act);\n\n // compute the total throughput\n through_tot += through_act;\n\n // set the thoughput value\n gsl_vector_set(through_values, index, through_act);\n\n lambda_act += stepsize;\n }\n\n // treat the last step separately, avoiding\n // to leave the allowed interpolation range\n // due to rounding errors \n gsl_vector_set(lambda_values, fconf->num_steps, abs_max);\n through_act = eval_interp(interp, abs_max);\n through_tot += through_act;\n gsl_vector_set(through_values, fconf->num_steps, through_act);\n\n for (index=0; index < (int)through_values->size; index++)\n {\n // normalize the filter throughput values\n gsl_vector_set(through_values, index,\n\t\t gsl_vector_get(through_values, index)/through_tot);\n\n // convert the wavelength from AA to micron\n gsl_vector_set(lambda_values, index,\n\t\t gsl_vector_get(lambda_values, index)*1.0e-04);\n }\n#ifdef DEBUGFCONF\n through_tot = 0.0;\n for (index=0; index < through_values->size; index++)\n {\n fprintf(stderr, \"Wavelength: %f, Throughput: %f\\n\",\n\t gsl_vector_get(lambda_values, index),\n\t gsl_vector_get(through_values, index));\n through_tot += gsl_vector_get(through_values, index);\n }\n fprintf(stderr, \"Total throughput: %f\\n\", through_tot);\n#endif\n \n // build up the output array\n double_vector[0] = lambda_values;\n double_vector[1] = through_values;\n\n \n // free the memory of the interpolator\n free_interp(interp);\n\n // free the memory of the pixel throughput\n free_pixel_tput(p_tput);\n\n // return the two gsl vectors\n return double_vector;\n}\n\n\n/**\n * Function: get_gauss_throughput\n *\n * Parameters:\n * @param fconf - the fringe configuration file\n * @param act_beam - the beam aperture\n * @param obj_pix - the PET pixel\n *\n * Returns:\n * @return double_vector - the wavelength and filter throughput steps\n */\ngsl_vector **\nget_gauss_throughput(const fringe_conf *fconf, const ap_pixel *obj_pix,\n\t\t const double fwhm)\n{\n pixel_tput *p_tput ;\n\n gsl_vector **double_vector;\n gsl_vector *lambda_values;\n gsl_vector *through_values;\n\n //interpolator *interp;\n\n double stepsize;\n double lambda_act;\n double through_act;\n double through_tot;\n\n double abs_min;\n double abs_max;\n\n double sigma;\n double arg;\n \n int index;\n\n // convert the FWHM into sigma\n sigma = fwhm / 2.35482;\n\n // allocate the pixel throughput structure\n p_tput = alloc_pixel_tput();\n\n // allocate the space for the vectors\n lambda_values = gsl_vector_alloc(fconf->num_steps + 1);\n through_values = gsl_vector_alloc(fconf->num_steps + 1);\n\n // allocate space for the return vector\n double_vector = (gsl_vector **)malloc(2*sizeof (gsl_vector *));\n\n // compute the minimum and maximum wavelength\n abs_min = MAX(obj_pix->lambda - 2.5 * fwhm,\n\t\tgsl_vector_get(fconf->fringe_range, 0));\n abs_max = MIN(obj_pix->lambda + 2.5 * fwhm,\n\t\tgsl_vector_get(fconf->fringe_range, 1));\n\n // compute the steps in wavelength\n stepsize = (abs_max - abs_min)/(double)fconf->num_steps;\n\n // set the lower wavelength end\n lambda_act = abs_min;\n\n // loop over the wavelength\n through_tot = 0.0;\n for (index=0; index < fconf->num_steps; index++)\n {\n // set the wavelength value\n gsl_vector_set(lambda_values, index, lambda_act);\n\n // z=(coord-g(2))/g(3)\n // sumgauss=sumgauss+DBLE(g(1)*EXP(-0.5*z**2))\n arg = (lambda_act - obj_pix->lambda) / sigma;\n\n // compute the throughput\n through_act = exp(-0.5*arg*arg);\n\n // compute the total throughput\n through_tot += through_act;\n\n // set the thoughput value\n gsl_vector_set(through_values, index, through_act);\n\n // increment the wavelength\n lambda_act += stepsize;\n }\n\n // treat the last step separately, avoiding\n // to leave the allowed interpolation range\n // due to rounding errors \n gsl_vector_set(lambda_values, fconf->num_steps, abs_max);\n arg = (abs_max - obj_pix->lambda) / sigma;\n through_act = exp(-0.5*arg*arg);\n through_tot += through_act;\n gsl_vector_set(through_values, fconf->num_steps, through_act);\n\n\n for (index=0; index < (int)through_values->size; index++)\n {\n // normalize the filter throughput values\n gsl_vector_set(through_values, index,\n\t\t gsl_vector_get(through_values, index)/through_tot);\n\n // convert the wavelength from AA to micron\n gsl_vector_set(lambda_values, index,\n\t\t gsl_vector_get(lambda_values, index)*1.0e-04);\n }\n\n#ifdef DEBUGFCONF\n through_tot = 0.0;\n for (index=0; index < through_values->size; index++)\n {\n fprintf(stderr, \"Wavelength: %f, Throughput: %f\\n\",\n\t gsl_vector_get(lambda_values, index),\n\t gsl_vector_get(through_values, index));\n through_tot += gsl_vector_get(through_values, index);\n }\n fprintf(stderr, \"Total throughput: %f\\n\", through_tot);\n#endif\n\n // build up the output array\n double_vector[0] = lambda_values;\n double_vector[1] = through_values;\n\n return double_vector;\n}\n\n\n/**\n * Function: create_interp_tput\n * The function creates and returns an interpolator\n * for a pixel throughput function. The interpolator\n * structure is allocated, data is filled in and\n * finally initialized.\n *\n * Parameters:\n * @param p_tput - the pixel throughput structure\n * \n * Returns:\n * @return interp - the new interpolator\n */\ninterpolator *\ncreate_interp_tput(const pixel_tput *p_tput)\n{\n interpolator *interp;\n\n double *xvals;\n double *yvals;\n\n // allocate memory for the independent values \n xvals = (double *) malloc(4 * sizeof(double));\n if (!xvals) { \n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n }\n\n // allocate memory for the dependent values \n yvals = (double *) malloc(4 * sizeof(double));\n if (!yvals) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n\t\t \"Memory allocation failed\");\n }\n\n // set the independent vector values \n xvals[0] = gsl_vector_get(p_tput->lambda_values, 0);\n xvals[1] = gsl_vector_get(p_tput->lambda_values, 1);\n xvals[2] = gsl_vector_get(p_tput->lambda_values, 2);\n xvals[3] = gsl_vector_get(p_tput->lambda_values, 3);\n\n // set the dependent vector values\n yvals[0] = 0.0;\n yvals[1] = p_tput->tp_max;\n yvals[2] = p_tput->tp_max;\n yvals[3] = 0.0;\n\n\n // create the interpolator\n interp = create_interp(4, FILTER_INTERP_TYPE, xvals, yvals);\n\n // return the interpolator\n return interp;\n}\n\n\n/**\n * Function: compute_pixel_tput\n * The function computes all relevant data to characterize\n * the pixel throughput function for an individual PET pixel.\n * The information is written into a pixel throughput structure.\n *\n * Parameters:\n * @param act_beam - the beam aperture\n * @param obj_pix - the PET pixel\n * @param p_tput - the pixel throughput structure\n */\nvoid\ncompute_pixel_tput(const beam act_beam, const ap_pixel *obj_pix,\n\t\t pixel_tput *p_tput)\n{\n d_point angles;\n\n double theta_2a;\n double theta_3a;\n\n double theta_1b;\n double theta_2b;\n\n double sin_theta_2a;\n double sin_theta_3a;\n\n double sin_theta_1b;\n double cos_theta_1b;\n double sin_theta_2b;\n\n double dist1;\n double dist2;\n\n // compute the anngles alpha and beta\n angles = compute_tput_angles(act_beam, obj_pix);\n\n // the computation of p_min-p3 in the\n // design document\n theta_1b = M_PI_2 + angles.x - angles.y;\n theta_2b = angles.y;\n\n // compute the sin's and cos's neede\n sin_theta_1b = sin(theta_1b);\n cos_theta_1b = cos(theta_1b);\n sin_theta_2b = sin(theta_2b);\n\n // compute one delta\n dist2 = obj_pix->dlambda * sin_theta_1b / sin_theta_2b;\n\n // the computation of p_h-p0 in the\n // design document\n theta_2a = M_PI - angles.y;\n theta_3a = angles.y - angles.x - M_PI_4;\n\n // next line due to sin(angle) = sin(180-angle)\n sin_theta_2a = sin_theta_2b;\n sin_theta_3a = sin(theta_3a);\n\n // compute the second delta \n dist1 = obj_pix->dlambda * M_SQRT1_2 * sin_theta_3a / sin_theta_2a;\n\n // determine the maximum throughput\n p_tput->tp_max = 1.0/MAX(fabs(sin_theta_1b), fabs(cos_theta_1b));\n\n // put together the distances, using\n // the deltas and the dispersion\n gsl_vector_set(p_tput->lambda_values, 0, obj_pix->lambda - dist1 - dist2);\n gsl_vector_set(p_tput->lambda_values, 1, obj_pix->lambda - dist1);\n gsl_vector_set(p_tput->lambda_values, 2, obj_pix->lambda + dist1);\n gsl_vector_set(p_tput->lambda_values, 3, obj_pix->lambda + dist1 + dist2);\n\n // sort the distances\n gsl_sort_vector(p_tput->lambda_values);\n}\n\n\n/**\n * Function: compute_tput_angles\n * The function computes the angles which characterize\n * a pixel in the lambda-cross dispersion plane.\n * In detail this is the angle between the lambda-axis\n * and the x-axis, and the angle between the lambda abd\n * the cross dispersion axis.\n * The two angles are computed from the basic pixel\n * and beam data.\n *\n *\n * Parameters:\n * @param act_beam - the beam aperture\n * @param act_pet - the PET pixel\n *\n * Returns:\n * @return angles - the relevant pixel angles\n */\nd_point\ncompute_tput_angles(const beam act_beam, const ap_pixel *act_pet)\n{\n d_point angles;\n\n // compute the angle 'alpha' between lambda-axis and\n // x-axis\n angles.x = -atan2(act_beam.spec_trace->deriv(act_pet->xi,\n\t\t\t\t\t act_beam.spec_trace->data),1.0);\n // compute the angle beta between lambda and cross dispersion axis\n angles.y = act_beam.orient + angles.x;\n\n // return the two angles\n return angles;\n}\n\n\n/**\n * Function: alloc_pixel_tput\n * The function allocates and returns memory\n * for a pixel throughput function\n *\n * Returns:\n * @return p_tput -the new allocated pixel throughput structure\n */\npixel_tput *\nalloc_pixel_tput()\n{\n pixel_tput *p_tput;\n\n // allcoate the pointer\n p_tput = (pixel_tput *) malloc(sizeof(pixel_tput));\n\n // allocate the vector in the structure\n p_tput->lambda_values = gsl_vector_alloc(4);\n\n // return the structure\n return p_tput;\n}\n\n/**\n * Function: print_pixel_tput\n * The function prints the content of a pixel throughput\n * structure onto the screen. \n *\n * Parameters:\n * @param p_tput - the pixel throughput structure\n */\nvoid\nprint_pixel_tput(pixel_tput *p_tput)\n{\n fprintf(stdout, \"l_min: %f, l_1: %f, l_2: %f, l_max: %f; tp_max: %f\\n\\n\",\n\t gsl_vector_get(p_tput->lambda_values,0),\n\t gsl_vector_get(p_tput->lambda_values,1),\n\t gsl_vector_get(p_tput->lambda_values,2),\n\t gsl_vector_get(p_tput->lambda_values,3),\n\t p_tput->tp_max);\n}\n\n\n/**\n * Function: free_pixel_tput\n * The function releases the memory allocated\n * in a pixel throughput function.\n *\n * Parameters:\n * @param p_tput - the pixel throughput structure\n */\nvoid\nfree_pixel_tput(pixel_tput *p_tput)\n{\n // free the gsl-vector\n gsl_vector_free(p_tput->lambda_values);\n\n // free everything\n free(p_tput);\n\n // set it to NULL\n p_tput = NULL;\n}\n\n", "meta": {"hexsha": "7864cd54dddb9eb694f0d47818aecff7f2c0945c", "size": 17788, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/fringe_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/fringe_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/fringe_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": 26.6686656672, "max_line_length": 94, "alphanum_fraction": 0.6940071959, "num_tokens": 4830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2692343413120742}} {"text": "\n#include \"imd_colrad.h\"\n\n// #include \n// #include \n// #include \n\n\n// ***************************************************\n// * TODO:\n// * mpi2 und mpi3 anpassen weil energies delE und kbTe in eV\n// * SPEEDUP pragma omp auch in ydot\n// * floats wo möglich\n// ****************************************************\n\n\n#ifdef LOADBALANCE\n#define node l1[i]\n#define node2 l2[i]\n#else\n#define node l1[i][j][k]\n#define node2 l2[i][j][k]\n#endif\n\n\n\n\n#define OMP\n#define LAPACK\n//#define MULTIPHOTON\n// #define SPONT //<-- spontante emission, Kaum effekt \n//#define STARK //<-- reabsorption via stark effect\n#define DOIPD //\n#define RHOMIN 50\n\n#ifdef OMP\n#include \n#endif\n\n#define TIMING //time-elapsed to stdout\n\n#define MAXLEVEL 4 // bis zu welchem Ionisationsgrad?\n\n// #ifdef USEFLOAT //Dieser Versuch ist fehlgeschlagen...\n// #define EXPR(x) expf(x) //floats an wichtigen stellen erschweren \n// #else //konvergenz für solver\n// #define EXPR(x) exp(x)\n// #endif\n\n\n\nconst int MAX_LINE_LENGTH=3000; //wird von colrad_read benuthzt\n //Hängt davon ab wieviele states betrachtet werden\n //sollte eigentlich besser dynamisch berechnet werden\n\n\n\n\n\nint num_threads;\n//const double EMASS=9.10938356e-31; // kg\n//const double ECONST=8.854187817e-12; // As/Vm\n//const double BOLTZMAN=1.38064852e-23; // J/K\n//const double ECHARGE=1.60217662e-19; // C\n//const double AMU=1.66053904020e-27; // atomic mass unit\n\n\nconst Real integ_reltol = 1e-6;\n\nconst Real integ_abstol = 1.0e-6; //1e-6; \nconst Real integ_abstol_ioniz= 1.0e-4; //-6; \nconst Real integ_abstol_recomb= 1.0e-4; //1e-6; \n\nconst int integ_meshdim =1500;\n\n// const Real alpha_i =0.3; //0.05; //0.3;\n// const Real beta_i =0.9; //4.0 ; //0.9;\n\nconst Real alpha_i =0.3; //0.05; //0.3;\nconst Real beta_i =0.9; //4.0 ; //0.9;\n\nconst Real ioniz_const = 1.573949440579906e+71; // konstanten zus. gefasst und aus dem doppelintegral gezogen\nconst Real recomb_const= 6.213703330335829e+72; // selbes für 3b-recomb.\n\n#define muINF (50*eV2J) //ACHTUNG: Unebdingt was sinnvolleres finden (mu wird kleiner mit Te)\n\n//wenn geschätzte max. ioniz.rate kleiner als das --> integrale garnicht erst berechnen \n//Schätzungen mit Hilfe von matlab-script DESCHAUD_TEST.m\n#define MINRATE 1e16 // in 1/s/m^3 --> alles unter 10 Ionisationsereignissen pro fs pro m^3 wird ignoriert\n // habe ich also eine ionenkonz. von 10^26/m^3 und eine rate von 10/m^3/fs\n // so ändert sich pro md-step die konz. um den Bruchteil 10/1E26 = 1E-25\n // -->wayne\n\n#define RATEIONIZMAX 1.5252e-13 // in m^3/s, das entspricht dem doppelintegral \n#define RATERECOMBMAX 6e-35 //6.1052e-42 // in m^6/s, das entspricht dem doppelintegral\n#define MINCONC 1e-60 //im Saha-init sollen zu kleine konzentrationen ignoriert werden\n\nReal k_EE_MAX, k_EI_MAX, k_EE_REV_MAX, k_EI_REV_MAX; //DEBUG PURPOSE\n\n\n\n\n// *********************************************************\n// CVODE-STRUCT FOR SOLVER PARAMS\n// *********************************************************\ntypedef struct {\n Real It; //Intesity\n Real IPD0,IPD1,IPD2,IPD3,IPD4;\n Real EF;\n Real P_EE,P_EI,P_MPI2,P_MPI3,P_RR;\n Real P_TOTAL; //komplette colrad-Leistungsdichte, für eng-filge\n Real dens; //weil cv F(dens,temp) \n Real ni; //für Z=ne/ni\n bool initial_equi;\n Real Tinit; //initial Temp. during equi must not change!\n Real Heatrate; //um temp.sprünge zu vermeiden //TEST!\n} *colrad_UserData;\ncolrad_UserData cdata;\n\n// *********************************************************\n// MAIN\n// *********************************************************\nvoid do_colrad(double dt)\n{\n\n k_EE_MAX= k_EI_MAX= k_EE_REV_MAX= k_EI_REV_MAX=0.0; \n\n int flag;\n\n double t;\n double tout=dt; //müssen beide double sein\n\n int i,j,k;\n N_Vector y;\n Real Te0,Ti0,rho0,ni0,ne0;\n colrad_ptotal=0.0;\n\n if(myid==0 && cdata->initial_equi)\n printf(\"COLRAD performs pre-equilibration of Saha-distribution\\nfor t=%.4e s...This may take some time.\\n\",colrad_tequi);\n\n#ifdef TIMING\n //if(myid==0)\n // {\n struct timeval start, end;\n gettimeofday(&start, NULL); \n // }\n#endif\n\n\n for(i=1;i irgendwas stimmt nicht!\n // node.ne=node2.ne=0.0;\n // node.Z=node2.Z=0.0;\n // node.P_EE=node2.P_EE=0.0;\n // node.P_EI=node2.P_EI=0.0;\n // node.P_MPI2=node2.P_MPI2=0.0;\n // node.P_MPI3=node2.P_MPI3=0.0;\n // node.P_RR=node2.P_RR=0.0;\n\n if(node.natoms < fd_min_atoms || node.dens < RHOMIN) continue;\n y=node.y;\n\n Te0=node.temp*11604.5;\n Ti0=node.md_temp*11604.5; \n rho0=node.dens;\n ni0=rho0/AMU/26.9185; //1e28; //1e26/m^3 entspricht etwa 1e-4/Angtrom^3 \n\n if(cdata->initial_equi==true) \n {\n Real Zmean=MeanCharge(Te0, rho0, atomic_charge, atomic_weight,i,j,k); \n ne0= Zmean* node.dens / (atomic_weight * AMU); \n node.ne=ne0; //Saha init greift darauf zu\n colrad_Saha_init(i, j, k); \n }\n else //NORMAL\n {\n ne0=node.ne; \n }\n\n double Told=Ith(y,0); //DEBUG //letzter step, checke wie groß temp.sprung\n Ith(y,0)=Told; //TEST//Te0;\n\n cdata->Tinit=Told;\n\n Ith(y,1)=Ti0;\n Ith(y,2)=ne0;\n\n flag = CVodeReInit(cvode_mem, 0.0, y); \n\n \n if(cdata->initial_equi==true)\n {\n// printf(\"myid:%d, RUNNNING INITIAL EQUI\\n\",myid);\n flag = CVode(cvode_mem, colrad_tequi, y, &t, CV_NORMAL); \n\n int i_global,j_global,k_global;\n\n#ifndef LOADBALANCE\n i_global = ((i - 1) + my_coord.x * (local_fd_dim.x - 2));\n j_global = ((j - 1) + my_coord.y * (local_fd_dim.y - 2));\n k_global = ((k-1) + my_coord.z*(local_fd_dim.z-2)); \n#else\n i_global = ((i - 1) + myid * (local_fd_dim.x - 2));\n j_global=k_global=1;\n#endif\nlong int nje;\nlong int nfe;\nlong int nsetups;\nlong int nni;\nlong int nst;\nlong int ncfn;\nlong int netf;\nCVodeGetNumJacEvals(cvode_mem, &nje);\nCVodeGetNumRhsEvals(cvode_mem, &nfe);\nCVodeGetNumLinSolvSetups(cvode_mem, &nsetups);\nCVodeGetNumNonlinSolvIters(cvode_mem, &nni);\nCVodeGetNumSteps(cvode_mem, &nst);\nCVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);\nCVodeGetNumErrTestFails(cvode_mem, &netf);\n\nprintf(\"myid:%d, COLRAD Cell %d was equilibrated, nfe:%ld, nje:%ld, nsetups:%ld, nni:%ld,nst:%ld,ncfn:%ld,netf:%ld\\n\",\n myid,i_global, nfe,nje,nsetups,nni,nst,ncfn,netf);\n\n\n } //initial equi\n else //NORMAL\n {\n cdata->dens=node.dens;\n cdata->Tinit=Te0; \n\n// printf(\"myid:%d, COLRAD Cell %d begin step, Te0:%f, ne0:%.2e\\n\", myid,(i - 1) + myid * (local_fd_dim.x - 2),Te0, ne0); \n cdata->Heatrate=(Te0-Told)/dt; //TEST\n\n flag = CVode(cvode_mem, tout, y, &t, CV_NORMAL);\n colrad_ptotal+=(fd_vol)*1e-30*cdata->P_TOTAL; // d.h. ptotal ist Gesamt-Leisung\n\n int i_global;\n#ifndef LOADBALANCE \n i_global = ((i - 1) + my_coord.x * (local_fd_dim.x - 2));\n#else\n i_global = ((i - 1) + myid * (local_fd_dim.x - 2)); \n#endif \n\nlong int nje;\nlong int nfe;\nlong int nsetups;\nlong int nni;\nlong int nst;\nlong int ncfn;\nlong int netf;\nCVodeGetNumJacEvals(cvode_mem, &nje);\nCVodeGetNumRhsEvals(cvode_mem, &nfe);\nCVodeGetNumLinSolvSetups(cvode_mem, &nsetups);\nCVodeGetNumNonlinSolvIters(cvode_mem, &nni);\nCVodeGetNumSteps(cvode_mem, &nst);\nCVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn);\nCVodeGetNumErrTestFails(cvode_mem, &netf);\nif(myid==1 && i_global==18) //DEBUG\nprintf(\"myid:%d, COLRAD Cell %d step done,HR:%.2e, Told:%f, T0:%f, T1:%f, ne0:%.2e, ne1:%.2e, nfe:%ld, nje:%ld, nsetups:%ld, nni:%ld,nst:%ld,ncfn:%ld,netf:%ld\\n\",\n myid,i_global, cdata->Heatrate, Told, node.temp*11604.5, Ith(y,0), node.ne, Ith(y,2),\n nfe,nje,nsetups,nni,nst,ncfn,netf);\n\n //ni0=cdata->ni;\n }\n \n\n //REASSIGN NEW TE AND NE\n node.temp=Ith(y,0)/11604.5;\n node.ne=Ith(y,2);\n node.Z=node.ne/ni0;\n node.P_EE=cdata->P_EE;\n node.P_EI=cdata->P_EI;\n node.P_MPI2=cdata->P_MPI2;\n node.P_MPI3=cdata->P_MPI3;\n node.P_RR=cdata->P_RR;\n\n node2.temp=node.temp; //auch in l2 speichern! wichtig!\n node2.ne=node.ne; //sonst geht alles im diffusion-step vor \n node2.Z=node.Z; //ttm-writeout verloren!\n node2.P_EE=node.P_EE;\n node2.P_EI=node.P_EI;\n node2.P_MPI2=node.P_MPI2;\n node2.P_MPI3=node.P_MPI3;\n node2.P_RR=node.P_RR;\n\n\n if(node.temp <0 || isnan(node.temp) !=0 ) \n {\n char errstr[255];\n sprintf(errstr,\"ERROR in COLRAD: Te became Nan or <0:%.4e\\n\",node.ne);\n error(errstr);\n }\n if(node.ne <0 || isnan(node.ne) !=0 ) \n {\n char errstr[255];\n sprintf(errstr,\"ERROR in COLRAD: ne became Nan or <0:%.4e\\n\",node.ne);\n error(errstr);\n }\n#ifndef LOADBALANCE\n } // for k\n } //for j\n#endif \n }\n if(cdata->initial_equi==true)\n {\n colrad_write(0);\n cdata->initial_equi=false;\n if(myid==0)\n printf(\"Initial equi done\\n\");\n }\n else if(steps % ttm_int ==0)\n {\n // colrad_write(steps);\n } \n\n #ifdef TIMING\n MPI_Barrier(cpugrid);\n // if(myid==0)\n // {\n\n gettimeofday(&end, NULL);\n Real delta = ((end.tv_sec - start.tv_sec) * 1000000u + \n end.tv_usec - start.tv_usec) / 1.e6;\n\n // if(myid==0)\n printf(\"myid:%d, telaps:%f, COLRAD STEP DONE, kee:%.4e,keeb:%.4e, kei:%.4e, k3b:%.4e\\n\",\n myid,delta, k_EE_MAX, k_EE_REV_MAX, k_EI_MAX, k_EI_REV_MAX);\n // }\n #endif\n \n}\n\n// *********************************************************\n// INIT FUNC\n// *********************************************************\nvoid colrad_init(void)\n{\n //Init gsl-integration stuff\n winteg_inner= gsl_integration_workspace_alloc (integ_meshdim); //Integration workspace allocation \n winteg_outer= gsl_integration_workspace_alloc (integ_meshdim); //Integration workspace allocation \n winteg_fermi= gsl_integration_workspace_alloc (integ_meshdim); //Integration workspace allocation \n winteg_exc= gsl_integration_workspace_alloc (integ_meshdim); \n\n winteg_rb_inner=gsl_integration_romberg_alloc(20);\n winteg_rb_outer=gsl_integration_romberg_alloc(20);\n\n\tHBAR=planck/2.0/pi;\n\tLASERFREQ=LIGHTSPEED/lambda;\n\tSUNMatrix A;\n\tN_Vector abstol;\t\n\tint i,j,k;\n\t\n\n\n\tif(myid==0)\n\t{\n printf(\"*****************************************\\n\");\n printf(\"* COLLISIONAL RADIATIVE MODEL *\\n\");\n printf(\"*****************************************\\n\");\n printf(\" READING ENERGY LEVELS \\n\");\t\n printf(\" reltol:%.4e\\n\",colrad_reltol);\n printf(\" abstol:%.4e\\n\",colrad_abstol);\n\t}\n\tcolrad_read_states();\n if(myid==0)\n {\n printf(\" Nr. of Equations:%d *\\n\",total_species+3); \n }\n\nMPI_Barrier(cpugrid);\n#ifdef OMP\n #pragma omp parallel\n {\n #pragma omp single\n {\n num_threads=omp_get_num_threads();\n printf(\"myid:%d, omp threads:%d\\n\",myid,num_threads);\n }\n }\n#endif \nif(myid==0)\n{ \n printf(\"*****************************************\\n\");\n}\n\n cdata=(colrad_UserData) malloc(sizeof *cdata); \n cdata->initial_equi=true;\n cdata->P_TOTAL=0.0;\n\n\t//total_species=z0_len+z1_len; //wird bereits in read-states reduced\n\tneq=total_species+3;\n\n\tfor(i=1;i BS\n\t//CVodeSetEpsLin(cvode_mem,0.01); //Default=0.05;\n\n CVodeSetMaxStepsBetweenJac(cvode_mem,50); //default 50 --> guter performance boost\n // CVodeSetMaxStepsBetweenJac(cvode_mem,50); //default 50 --> guter performance boost\n\t\n\t//N_VDestroy(dummy);\t\n\t\n/*\n N_VDestroy(y);\n SUNMatDestroy(A);\n SUNLinSolFree(LS);\n CVodeFree(&cvode_mem);\t\n*/\n \n //colrad_read(0);\n}\n\n\nvoid colrad_Saha_init(int i,int j,int k)\n{ \n // int i,j,k;\n // for(i=1;i 0)\n {\n alloc2darr(double, STATES_z0, z0_len, 6);\n for (i = 0; i < z0_len * 6; i += 6)\n {\n STATES_z0[i / 6][0] = buf[i];\n STATES_z0[i / 6][1] = buf[i + 1];\n STATES_z0[i / 6][2] = buf[i + 2];\n STATES_z0[i / 6][3] = buf[i + 3];\n STATES_z0[i / 6][4] = buf[i + 4];\n STATES_z0[i / 6][5] = buf[i + 5];\n\n\n }\n }\n free(buf);\n\n // ***********************************************\n //Read Al, Z=+1\n // **********************************************\n if (myid == 0)\n {\n lcnt = 1;\n fin = fopen(\"Al1_states.txt\", \"r\");\n if (fin == NULL)\n {\n char errstr[255];\n sprintf(errstr, \"ERROR in colrad_read_states: File %s not found\\n\", \"Al1_states.txt\");\n error(errstr);\n }\n while (1) {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n lcnt++;\n }\n\n alloc2darr(double, STATES_z1, lcnt, 6);\n\n lcnt = 0;\n rewind(fin);\n while (1)\n {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n sscanf(line, \"%lf\\t%lf\\t%lf\\t%lf\\t%lf\\t%lf\",\n &STATES_z1[lcnt][0], &STATES_z1[lcnt][1], &STATES_z1[lcnt][2],\n &STATES_z1[lcnt][3], &STATES_z1[lcnt][4], &STATES_z1[lcnt][5]);\n lcnt++;\n }\n z1_len = lcnt;\n fclose(fin);\n total_species += z1_len;\n\n }\n\n //NOW COMMUNICATE\n MPI_Bcast(&z1_len, 1, MPI_INT, 0, cpugrid);\n alloc1darr(Real, buf, z1_len * 6);\n if (myid == 0)\n {\n for (i = 0; i < z1_len * 6; i += 6) //fill 1d buff-array\n {\n buf[i] = (Real) STATES_z1[i / 6][0];\n buf[i + 1] = (Real) STATES_z1[i / 6][1];\n buf[i + 2] = (Real) STATES_z1[i / 6][2];\n buf[i + 3] = (Real) STATES_z1[i / 6][3];\n buf[i + 4] = (Real) STATES_z1[i / 6][4];\n buf[i + 5] = (Real) STATES_z1[i / 6][5];\n }\n }\n\n MPI_Bcast(buf, z1_len * 6, REALTYPE, 0, cpugrid);\n //NOW RECONSTRUCT on other procs\n if (myid > 0)\n {\n alloc2darr(double, STATES_z1, z1_len, 6);\n for (i = 0; i < z1_len * 6; i += 6)\n {\n STATES_z1[i / 6][0] = buf[i];\n STATES_z1[i / 6][1] = buf[i + 1];\n STATES_z1[i / 6][2] = buf[i + 2];\n STATES_z1[i / 6][3] = buf[i + 3];\n STATES_z1[i / 6][4] = buf[i + 4];\n STATES_z1[i / 6][5] = buf[i + 5];\n\n }\n }\n free(buf);\n\n\n // ***********************************************\n //Read Al, Z=+2\n // **********************************************\n #if MAXLEVEL > 1\n if (myid == 0)\n {\n lcnt = 1;\n fin = fopen(\"Al2_states.txt\", \"r\");\n if (fin == NULL)\n {\n char errstr[255];\n sprintf(errstr, \"ERROR in colrad_read_states: File %s not found\\n\", \"Al2_states.txt\");\n error(errstr);\n }\n while (1) {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n lcnt++;\n }\n\n alloc2darr(double, STATES_z2, lcnt, 6);\n\n lcnt = 0;\n rewind(fin);\n while (1)\n {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n sscanf(line, \"%lf\\t%lf\\t%lf\\t%lf\\t%lf\\t%lf\",\n &STATES_z2[lcnt][0], &STATES_z2[lcnt][1], &STATES_z2[lcnt][2],\n &STATES_z2[lcnt][3], &STATES_z2[lcnt][4], &STATES_z2[lcnt][5]);\n lcnt++;\n }\n z2_len = lcnt;\n fclose(fin);\n total_species += z2_len;\n }\n\n //NOW COMMUNICATE\n MPI_Bcast(&z2_len, 1, MPI_INT, 0, cpugrid);\n alloc1darr(Real, buf, z2_len * 6);\n if (myid == 0)\n {\n for (i = 0; i < z2_len * 6; i += 6) //fill 1d buff-array\n {\n buf[i] = (Real) STATES_z2[i / 6][0];\n buf[i + 1] = (Real) STATES_z2[i / 6][1];\n buf[i + 2] = (Real) STATES_z2[i / 6][2];\n buf[i + 3] = (Real) STATES_z2[i / 6][3];\n buf[i + 4] = (Real) STATES_z2[i / 6][4];\n buf[i + 5] = (Real) STATES_z2[i / 6][5];\n }\n }\n\n MPI_Bcast(buf, z2_len * 6, REALTYPE, 0, cpugrid);\n //NOW RECONSTRUCT on other procs\n if (myid > 0)\n {\n alloc2darr(double, STATES_z2, z2_len, 6);\n for (i = 0; i < z2_len * 6; i += 6)\n {\n STATES_z2[i / 6][0] = buf[i];\n STATES_z2[i / 6][1] = buf[i + 1];\n STATES_z2[i / 6][2] = buf[i + 2];\n STATES_z2[i / 6][3] = buf[i + 3];\n STATES_z2[i / 6][4] = buf[i + 4];\n STATES_z2[i / 6][5] = buf[i + 5];\n\n }\n }\n free(buf);\n #endif //MAXLEVEL > 1\n\n\n // ***********************************************\n //Read Al, Z=+3\n // **********************************************\n #if MAXLEVEL > 2\n if (myid == 0)\n {\n lcnt = 1;\n fin = fopen(\"Al3_states.txt\", \"r\");\n if (fin == NULL)\n {\n char errstr[255];\n sprintf(errstr, \"ERROR in colrad_read_states: File %s not found\\n\", \"Al3_states.txt\");\n error(errstr);\n }\n while (1) {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n lcnt++;\n }\n\n alloc2darr(double, STATES_z3, lcnt, 6);\n\n lcnt = 0;\n rewind(fin);\n while (1)\n {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n sscanf(line, \"%lf\\t%lf\\t%lf\\t%lf\\t%lf\\t%lf\",\n &STATES_z3[lcnt][0], &STATES_z3[lcnt][1], &STATES_z3[lcnt][2],\n &STATES_z3[lcnt][3], &STATES_z3[lcnt][4], &STATES_z3[lcnt][5]);\n\n\n\n lcnt++;\n\n }\n z3_len = lcnt;\n fclose(fin);\n total_species += z3_len;\n }\n\n //NOW COMMUNICATE\n MPI_Bcast(&z3_len, 1, MPI_INT, 0, cpugrid);\n alloc1darr(Real, buf, z3_len * 6);\n if (myid == 0)\n {\n for (i = 0; i < z3_len * 6; i += 6) //fill 1d buff-array\n {\n buf[i] = (Real) STATES_z3[i / 6][0];\n buf[i + 1] = (Real) STATES_z3[i / 6][1];\n buf[i + 2] = (Real) STATES_z3[i / 6][2];\n buf[i + 3] = (Real) STATES_z3[i / 6][3];\n buf[i + 4] = (Real) STATES_z3[i / 6][4];\n buf[i + 5] = (Real) STATES_z3[i / 6][5];\n }\n }\n\n MPI_Bcast(buf, z3_len * 6, REALTYPE, 0, cpugrid);\n //NOW RECONSTRUCT on other procs\n if (myid > 0)\n {\n alloc2darr(double, STATES_z3, z3_len, 6);\n for (i = 0; i < z3_len * 6; i += 6)\n {\n STATES_z3[i / 6][0] = buf[i];\n STATES_z3[i / 6][1] = buf[i + 1];\n STATES_z3[i / 6][2] = buf[i + 2];\n STATES_z3[i / 6][3] = buf[i + 3];\n STATES_z3[i / 6][4] = buf[i + 4];\n STATES_z3[i / 6][5] = buf[i + 5];\n\n }\n }\n free(buf);\n #endif //MAXLEVEL > 2\n\n // ***********************************************\n //Read Al, Z=+4\n // **********************************************\n #if MAXLEVEL > 3\n if (myid == 0)\n {\n lcnt = 1;\n fin = fopen(\"Al4_states.txt\", \"r\");\n if (fin == NULL)\n {\n char errstr[255];\n sprintf(errstr, \"ERROR in colrad_read_states: File %s not found\\n\", \"Al4_states.txt\");\n error(errstr);\n }\n while (1) {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n lcnt++;\n }\n\n alloc2darr(double, STATES_z4, lcnt, 6);\n\n lcnt = 0;\n rewind(fin);\n while (1)\n {\n if (fgets(line, MAXLINE, fin) == NULL) break;\n sscanf(line, \"%lf\\t%lf\\t%lf\\t%lf\\t%lf\\t%lf\",\n &STATES_z4[lcnt][0], &STATES_z4[lcnt][1], &STATES_z4[lcnt][2],\n &STATES_z4[lcnt][3], &STATES_z4[lcnt][4], &STATES_z4[lcnt][5]);\n lcnt++;\n }\n z4_len = lcnt;\n fclose(fin);\n total_species += z4_len;\n }\n\n //NOW COMMUNICATE\n MPI_Bcast(&z4_len, 1, MPI_INT, 0, cpugrid);\n alloc1darr(Real, buf, z4_len * 6);\n if (myid == 0)\n {\n for (i = 0; i < z4_len * 6; i += 6) //fill 1d buff-array\n {\n buf[i] = (Real) STATES_z4[i / 6][0];\n buf[i + 1] = (Real) STATES_z4[i / 6][1];\n buf[i + 2] = (Real) STATES_z4[i / 6][2];\n buf[i + 3] = (Real) STATES_z4[i / 6][3];\n buf[i + 4] = (Real) STATES_z4[i / 6][4];\n buf[i + 5] = (Real) STATES_z4[i / 6][5];\n }\n }\n\n MPI_Bcast(buf, z4_len * 6, REALTYPE, 0, cpugrid);\n //NOW RECONSTRUCT on other procs\n if (myid > 0)\n {\n alloc2darr(double, STATES_z4, z4_len, 6);\n for (i = 0; i < z4_len * 6; i += 6)\n {\n STATES_z4[i / 6][0] = buf[i];\n STATES_z4[i / 6][1] = buf[i + 1];\n STATES_z4[i / 6][2] = buf[i + 2];\n STATES_z4[i / 6][3] = buf[i + 3];\n STATES_z4[i / 6][4] = buf[i + 4];\n STATES_z4[i / 6][5] = buf[i + 5];\n\n }\n }\n free(buf);\n #endif //MAXLEVEL > 3\n\n // **********************************\n // * ALLOC ARRAYS\n // **********************************\n alloc2darr(double, k_EE_z0_z0, z0_len, z0_len);\n alloc2darr(double, k_EE_z0_z0_b, z0_len, z0_len);\n\n alloc2darr(double, k_EE_z1_z1, z1_len, z1_len);\n alloc2darr(double, k_EE_z1_z1_b, z1_len, z1_len);\n\n #if MAXLEVEL > 1\n alloc2darr(double, k_EE_z2_z2, z2_len, z2_len);\n alloc2darr(double, k_EE_z2_z2_b, z2_len, z2_len);\n #endif\n\n #if MAXLEVEL > 2\n alloc2darr(double, k_EE_z3_z3, z3_len, z3_len);\n alloc2darr(double, k_EE_z3_z3_b, z3_len, z3_len);\n #endif\n\n #if MAXLEVEL > 3\n alloc2darr(double, k_EE_z4_z4, z4_len, z4_len);\n alloc2darr(double, k_EE_z4_z4_b, z4_len, z4_len);\n #endif\n // **********************************************\n // Now Thermal Ionization and Recomb. rate coeff. arrays\n\n // z0->z1\n alloc2darr(double, k_EI_z0_z1, z0_len, z1_len);\n alloc2darr(double, k_EI_z1_z0, z0_len, z1_len);\n\n #if MAXLEVEL > 1\n //z1->z2\n alloc2darr(double, k_EI_z1_z2, z1_len, z2_len);\n alloc2darr(double, k_EI_z2_z1, z1_len, z2_len);\n #endif\n\n #if MAXLEVEL > 2\n //z2->z3\n alloc2darr(double, k_EI_z2_z3, z2_len, z3_len);\n alloc2darr(double, k_EI_z3_z2, z2_len, z3_len);\n #endif\n\n #if MAXLEVEL > 3\n //z3->z4\n alloc2darr(double, k_EI_z3_z4, z3_len, z4_len);\n alloc2darr(double, k_EI_z4_z3, z3_len, z4_len);\n #endif\n // k_MPI arrays\n //z0->z1\n alloc3darr(double, k_MPI_z0_z1, z0_len, z1_len, 2);\n alloc3darr(double, k_MPI_z1_z0, z0_len, z1_len, 2);\n\n //z1->z2\n #if MAXLEVEL > 1\n alloc3darr(double, k_MPI_z1_z2, z1_len, z2_len, 2);\n alloc3darr(double, k_MPI_z2_z1, z1_len, z2_len, 2);\n #endif\n\n //z2->z3\n #if MAXLEVEL > 2\n alloc3darr(double, k_MPI_z2_z3, z2_len, z3_len, 2);\n alloc3darr(double, k_MPI_z3_z2, z2_len, z3_len, 2);\n #endif\n\n\n //z3->z4\n #if MAXLEVEL > 3\n alloc3darr(double, k_MPI_z3_z4, z3_len, z4_len, 2);\n alloc3darr(double, k_MPI_z4_z3, z3_len, z4_len, 2);\n #endif\n\n MPI_Bcast(&total_species, 1, MPI_INT, 0, cpugrid);\n}\n\n\n\n\n\nvoid do_Saha(Real Te,Real totalc,Real ne,N_Vector y) //Bei init\n{\n double tmp;\n double Zav=ne/totalc;\n // double Ti=Te;\n\n double Q_z0,Q_z1,Q_z2,Q_z3,Q_z4,Q_z5; //partition functions\n // double IPD_SP=0.0; //Stewart and Pyatt =(POWR(1.0+a/Debye,2.0/3.0)-1.0)/2.0/(Zav+1.0);\n // double IPD_IS=0.0; //Ion-sphere model (high dens,low T) =3.0*1.0*ECHARGE*ECHARGE/2.0/a/BOLTZMAN/Te;\n // double IPD_DH=0.0; //Debye-Hückel (high T,low dens) = 1.0*ECHARGE*ECHARGE/Debye/BOLTZMAN/Te;\n double r10,r21,r32,r43,r54; //ratios of ion. conc.\n double DeltaE;\n double IPD=0.0;\n double n0,n1,n2,n3,n4,n5;\n double p; //probability\n\n\n int i;\n\n\n r10=r21=r32=r43=r54=0;\n\n\n Zav=ne/totalc;\n double EF=fermi_E(ne);\n double mu=chempot(ne,Te);\n //Debye=SQRTR(BOLTZMAN*Te/4.0/pi/ECHARGE/ECHARGE/ne/(Zav+1));\n tmp=POWR(2.0*pi*EMASS*BOLTZMAN*Te,1.5)/planck/planck/planck; //ACHTUNG: Das ist wieder thermal-de brogilie Lambda\n //Nutze richtiges chempot!!!!\n #ifdef DOIPD\n double IPD0,IPD1,IPD2,IPD3,IPD4;\n double z; //DOI after ionization (e.g.=1 for Al0)\n double r0; //Ion sphere radius\n r0=POWR(3.0/4.0/pi/totalc,1.0/3.0);\n double debye=SQRTR(BOLTZMAN*Te/4.0/pi/POWR(totalc+ne,2.0));\n // Atoms, solids, and plasmas in super-intense laser fields S.220\n IPD0=1.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD1=2.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD2=3.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD3=4.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST; \n IPD4=5.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST; \n #endif \n\n //compute partition functions\n Q_z0=0.0;\n Q_z1=0.0;\n Q_z2=0.0;\n Q_z3=0.0;\n Q_z4=0.0;\n Q_z5=0.0;\n for(i=0;i truncate partiation function \n qi=0;\n\n Q_z0+=qi; //Mit Energien, relativ zum Grundzustand (level=0) dieses Ions\n\n// if(myid==0)\n// printf(\"Z0, qi:%.4e, exp:%.4e, gi:%.4e,Q:%.4e\\n\", qi, \n// exp(-(STATES_z0[i][2]-0.0)*eV2J/BOLTZMAN/Te),\n// STATES_z0[i][3], Q_z0);\n\n }\n\n for(i=0;i 1\n for(i=0;i 2\n for(i=0;i 3\n for(i=0;i1 //\n ////////////\n\n #ifdef DOIPD\n // z=1.0;\n // IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model\n IPD=IPD0;\n #endif\n\n DeltaE=(STATES_z1[0][2]-0.0)*eV2J-IPD+mu;\n // DeltaE=fmax(0.0,DeltaE);\n p=exp(-DeltaE/BOLTZMAN/Te);\n // r10=2.0/ne*tmp*Q_z1/Q_z0*p; //r10= ratio of ion-concentrations n(Z=1)/n(Z=0); g_e=2 (statistical weight of electron)\n r10=Q_z1/Q_z0*p;\n // double r01=Q_z0/Q_z1*p;\n //printf(\"IPD0:%f\\n\",IPD*J2eV);\n // if(isnan(r10)!=0 || isinf(r10)!=0)\n // {\n // char errstr[255];\n // sprintf(errstr,\"ERROR in Saha-Init: r10 is inf or nan: p0:%.4e,Q_z1:%.4e,Q_z0:%.4e\\n\",p,Q_z1,Q_z0);\n // error(errstr);\n // }\n // if(myid==0)\n // printf(\"ERROR in Saha-Init: r10 is inf or nan: p0:%.4e,Q_z1:%.4e,Q_z0:%.4e\\n\",p,Q_z1,Q_z0);\n\n\n ////////////\n // Z=1->2 //\n ////////////\n\n #if MAXLEVEL > 1\n\n #ifdef DOIPD\n // z=2.0;\n // IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model\n IPD=IPD1;\n #endif \n DeltaE=(STATES_z2[0][2]-STATES_z1[0][2])*eV2J-IPD+mu;\n // DeltaE=fmax(0.0,DeltaE);\n p=exp(-DeltaE/BOLTZMAN/Te);\n // p=exp(DeltaE/BOLTZMAN/Te);\n // r21=2.0/ne*tmp*Q_z2/Q_z1*p;\n r21=Q_z2/Q_z1*p;\n // double r12=Q_z1/Q_z2*p;\n // if(isnan(r21)!=0 || isinf(r21)!=0)\n // {\n // char errstr[255];\n // sprintf(errstr,\"ERROR in Saha-Init: r21 is inf or nan: p2:%.4e,Q_z2:%.4e,Q_z1:%.4e\\n\",p,Q_z2,Q_z1);\n // error(errstr);\n // }\n#endif\n // ////////////\n // // Z=2->3 //\n // ////////////\n #if MAXLEVEL > 2 \n #ifdef DOIPD \n // z=3.0;\n // IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model\n IPD=IPD2;\n #endif \n DeltaE=(STATES_z3[0][2]-STATES_z2[0][2])*eV2J-IPD+mu;\n // DeltaE=fmax(0.0,DeltaE);\n p=exp(-DeltaE/BOLTZMAN/Te);\n // p=exp(DeltaE/BOLTZMAN/Te);\n // r32=2.0/ne*tmp*Q_z3/Q_z2*p;\n r32=Q_z3/Q_z2*p;\n // double r23=Q_z2/Q_z3*p;\n\n if(isnan(r32)!=0 || isinf(r32)!=0)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR in Saha-Init: r32 is inf or nan: p3:%.4e,Q_z3:%.4e,Q_z2:%.4e\\n\",p,Q_z3,Q_z2);\n error(errstr);\n }\n #endif \n // ////////////\n // // Z=3->4 //\n // ////////////\n #if MAXLEVEL > 3\n #ifdef DOIPD \n // z=4.0;\n // IPD=3.0*z*ECHARGE*ECHARGE/2.0/r0/4.0/pi/ECONST; //Ion-Sphere model\n IPD=IPD3;\n #endif \n DeltaE=(STATES_z4[0][2]-STATES_z3[0][2])*eV2J-IPD+mu;\n // DeltaE=fmax(0.0,DeltaE);\n p=exp(-DeltaE/BOLTZMAN/Te);\n // p=exp(DeltaE/BOLTZMAN/Te);\n // r43=2.0/ne*tmp*Q_z4/Q_z3*p;\n r43=Q_z4/Q_z3*p;\n // double r34=Q_z3/Q_z4*p;\n// printf(\"r34:%.4e,p:%.4e,DeltaE/kT:%.4e\\n\",r34,p,DeltaE/BOLTZMAN/Te);\n // if(isnan(r43)!=0 || isinf(r43)!=0)\n // {\n // char errstr[255];\n // sprintf(errstr,\"ERROR in Saha-Init: r43 is inf or nan: p4:%.4e,Q_z4:%.4e,Q_z3:%.4e\\n\",p,Q_z4,Q_z3);\n // error(errstr);\n // }\n#endif\n //concentrations from ratios and totalc\n\n n0=totalc/(r43*r32*r21*r10+r32*r21*r10+r21*r10+r10+1.0); // ?\n //n0=totalc*Zav/(4*r43*r32*r21*r10 + 3*r32*r21*r10+ 2*r21*r10+1.0);\n n1=r10*n0;\n \n //D.h. Neutrals komplett druck-ionisiert\n if(Q_z0==0)\n {\n n0=0.0;\n // n1=totalc*Zav/(4*r43*r32*r21 + 3*r32*r21+ 2*r21+1.0);\n n1=totalc/(r43*r32*r21 + r32*r21+ r21+1.0);\n }\n\n n2=r21*n1;\n n3=r32*n2;\n n4=r43*n3;\n n5=r54*n4;\n // Zav=(1*n1+4*n2+9*n3+16*n4+25*n5)/(1*n1+2*n2+3*n3+4*n4+5*n5);\n\n // n4=Zav*totalc/(r12*r23*r34+2*r23*r34+3*r34+4);\n // n3=r34*n4;\n // n2=r23*n3;\n // n1=r12*n2;\n // n0=r01*n1;\n\n// if(myid==0)\n// {\n // printf(\"n0:%.4e,n1:%.4e,n2:%.4e,n3:%.4e,n4:%.4e\\n\",n0,n1,n2,n3,n4);\n // printf(\"r10:%.4e,r21:%.4e,r32:%.4e,r43:%.4e\\n\",r10,r21,r32,r43);\n // printf(\"Qz4:%.4e,Qz3:%.4e,Qz2:%.4e,Qz1:%.4e,Qz0:%.4e\\n\",Q_z4, Q_z3,Q_z2,Q_z1,Q_z0);\n// }\n\n\n /*\n printf(\"********************************************************************************************************************** \\n\");\n printf(\" Initial distribution of concentration according to generalized Saha-Equation\\n\");\n printf(\" Ti=Te=%f\\n\",Te);\n printf(\" totalc=%.4e\\n\",totalc);\n printf(\" Zmean=%.4e,ne:%.6e\\n\",ne/totalc,ne);\n printf(\" [Al0]:%.2e,[Al1]:%.2e,[Al2]:%.2e,[Al3]:%.2e,[Al4]:%.2e,[Al5]:%.2e\\n\",n0,n1,n2,n3,n4,n5);\n printf(\" I0=%.4e\\n\",I0);\n printf(\" t_FWHM=%.4e\\n\",tFWHM);\n printf(\" Lambda=%.4e\\n\",lambda);\n printf(\" NEQ:%d\\n\",neq);\n printf(\"********************************************************************************************************************** \\n\");\n */\n\n\n // ************************\n // * FILL Z0 STATES\n // ************************\n int ishift=3;\n //Now fill states\n for(i=0;i0)\n {\n Ith(y,i+ishift)=n0/Q_z0*STATES_z0[i][3]*prob;\n if(Ith(y,i+ishift) < MINCONC)\n Ith(y,i+ishift)=0.0;\n\n // printf(\"ITH(%d):%.4e,prob:%.4e,Q_z0:%.4e,dE:%.4e\\n\",\n // i+ishift,Ith(y,i+ishift), prob, Q_z0, DeltaE);\n }\n\n if(isnan(Ith(y,i+ishift))!=0 || isinf(Ith(y,i+ishift))!=0)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR in do_Saha z0: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%.4e\\n\", \n prob,Ei,DeltaE);\n error(errstr);\n }\n }\n // ************************\n // * FILL Z1 STATES\n // ************************\n for(i=0;i0)\n Ith(y,i+ishift+z0_len)=n1/Q_z1*STATES_z1[i][3]*prob;\n\n if(Ith(y,i+ishift+z0_len) < MINCONC)\n Ith(y,i+ishift+z0_len)=0.0;\n\n if(isnan(Ith(y,i+ishift+z0_len))!=0 || isinf(Ith(y,i+ishift+z0_len))!=0)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR in do_Saha z1: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%.4e\\n\", \n prob,Ei,DeltaE);\n error(errstr);\n } \n }\n // ************************\n // * FILL Z2 STATES\n // ************************\n #if MAXLEVEL > 1\n for(i=0;i0) \n Ith(y,i+ishift+z0_len+z1_len)=n2/Q_z2*STATES_z2[i][3]*prob;\n\n if(Ith(y,i+ishift+z0_len+z1_len) < MINCONC)\n Ith(y,i+ishift+z0_len+z1_len)=0.0;\n\n if(isnan(Ith(y,i+ishift+z0_len+z1_len))!=0 || isinf(Ith(y,i+ishift+z0_len+z1_len))!=0)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR in do_Saha z2: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%.4e\\n\", \n prob,Ei,DeltaE);\n error(errstr);\n }\n\n }\n #endif\n // ************************\n // * FILL Z3 STATES\n // ************************ \n #if MAXLEVEL > 2\n for(i=0;i0)\n Ith(y,i+ishift+z0_len+z1_len+z2_len)=n3/Q_z3*STATES_z3[i][3]*prob;\n\n if(Ith(y,i+ishift+z0_len+z1_len+z2_len) < MINCONC)\n Ith(y,i+ishift+z0_len+z1_len+z2_len)=0.0;\n\n if(isnan(Ith(y,i+ishift+z0_len+z1_len+z2_len))!=0 || isinf(Ith(y,i+ishift+z0_len+z1_len+z2_len))!=0)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR in do_Saha z3: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%4.e\\n\", \n prob,Ei,DeltaE);\n error(errstr);\n } \n }\n #endif\n // ************************\n // * FILL Z4 STATES\n // ************************\n #if MAXLEVEL > 3\n for(i=0;i0)\n Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len)=n4/Q_z4*STATES_z4[i][3]*prob;\n\n if(Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len) < MINCONC)\n Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len)=0.0;\n\n if(isnan(Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len))!=0 || isinf(Ith(y,i+ishift+z0_len+z1_len+z2_len+z3_len))!=0)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR in do_Saha z4: y is inf or nan! prob:%.4e, Ei:%.4e,DeltaE:%4.e\\n\", \n prob,Ei,DeltaE);\n error(errstr);\n }\n\n }\n #endif \n\n double totalc_check=0.0;\n double n0_check=0.0;\n double n1_check=0.0;\n double n2_check=0.0;\n double n3_check=0.0;\n double n4_check=0.0;\n\n for(i=3;i= z0_len && i-3-z0_len < z1_len)\n n1_check+=Ith(y,i);\n\n if(i-3 >= z0_len+z1_len && i-3-z0_len-z1_len < z2_len)\n n2_check+=Ith(y,i);\n\n if(i-3 >= z0_len+z1_len+z2_len && i-3-z0_len-z1_len-z2_len < z3_len)\n n3_check+=Ith(y,i); \n\n if(i-3 >= z0_len+z1_len+z2_len + z3_len && i-3-z0_len-z1_len-z2_len - z3_len < z4_len)\n n4_check+=Ith(y,i); \n\n // if(myid==0) printf(\"y[%d]:%.4e\\n\",i,Ith(y,i));\n } \n\n/*\n if(ABS(totalc-totalc_check) > 0.01*totalc || ABS(n0_check-n0) > 0.01* n0 || \n ABS(n1_check-n1) > 0.01* n1 || ABS(n2_check-n2) > 0.01* n2 || ABS(n3_check-n3) > 0.01* n3 ||\n ABS(n4_check-n4) > 0.01* n4 )\n if(myid==0)\n {\n char errstr[400];\n sprintf(errstr,\"Inconsistency in do_Saha: totalc_check= %.4e, and totalc=%.4e,sum_n:%.4e,\"\n \"n0:%.4e, n1:%.4e,n2:%.4e,n3:%.4e, n4:%.4e\\n\"\n \"n0_check:%.4e, n1_check:%.4e,n2_check:%.4e,n3_check:%.4e, n4_check:%.4e\\n\",\n totalc_check,totalc,n1+n2+n3+n4, n0, n1, n2, n3, n4,n0_check,n1_check,n2_check,n3_check,n4_check);\n error(errstr);\n }\n*/\n\n}\n\n\n\n\n\n// ************************************************************************************************************\n// ACTION\n// ///////////////////////////////////////////////////////////////////////////////////////////////////////////\nint colrad_ydot(double t, N_Vector y, N_Vector colrad_ydot, void *user_data)\n{\n\n/*\n double t0=1e-12;\n double I0=1e17;\n double tFWHM=100e-15;\n double sigmat=tFWHM/2.3548;\n double sigmatsq=sigmat*sigmat;\n */\n\n //It=I0*exp(-POWR((t-t0),2.0)/2.0/sigmatsq);\n\n colrad_UserData data;\n data = (colrad_UserData) user_data;\n\n Real It=data->It;\n It=0; //It ist LOKALE Intesität!\n\n bool initial_equi=data->initial_equi; //falls ja, wird temperatur nicht variiert.\n\n Real Eexc;\n\n P_E_EE=0.0;\n P_E_EI=0.0;\n P_E_MPI2=0.0;\n P_E_MPI3=0.0;\n P_E_RAD_RECOMB=0.0;\n\n Real DeltaE;\n Real kfwd,krev;\n Real kfwd2; // für 3-Photon absorption\n\n\n int i,j;\n int ishift=3; // UND NICHT =4 (colrad_ydot fängt bei 0 das zählen an!)\n int shift,shift1,shift2;\n Real ne=Ith(y,2);\n Real Te=Ith(y,0);\n Real Ti=Ith(y,1);\n\n\n //FOR REABSORPTION\n // Real escape_factor;\n Real Ajk;\n // Real lambda;\n // Real lambda0;\n Real sigma_PI,abs_coeff,thickness,tau,wstark_freq,lambda0,wstark_len,escape_factor,groundstate_ioniz;\n // thickness=1e-3;\n Real sigma_tmp=64.0*POWR(pi,4.0)*POWR(ECHARGE,10.0)*EMASS/3.0/SQRTR(3.0)/POWR(4.0*pi*ECONST,5.0)/POWR(planck,6.0)/LIGHTSPEED/POWR(LASERFREQ,3.0)/POWR(13.6*eV2J,2.0);\n\n\n //Pre-Zero <--- MUI IMPORTANTE!!!!\n //and count totalc for ipd and stark effect \n totalc=0.0;\n // #ifdef OMP\n // #pragma omp parallel for reduction(+: totalc)\n // #endif\n for(i=0;i= 3) totalc+=Ith(y,i);\n if(isnan(Ith(y,i))!=0)\n {\n printf(\"myid:%d, WARNING Ith(y,%d) became NaN! z0len:%d,z1len:%d,z2len:%d\\n\",myid,i,z0_len,z1_len,z2_len);\n return 1;\n }\n }\n data->ni=totalc; \n if(totalc<0)\n return 1; // <-- RHS fail\n\n // IPD KRAM\n Real IPD0,IPD1,IPD2,IPD3,IPD4;\n IPD0=IPD1=IPD2=IPD3=0.0;\n Real EF=fermi_E(ne);\n data->EF=EF;\n#ifdef DOIPD\n Real r0,debye;\n r0=POWR(3.0/4.0/pi/totalc,1.0/3.0);\n debye=SQRTR(BOLTZMAN*Te/4.0/pi/POWR(totalc+ne,2.0));\n // Atoms, solids, and plasmas in super-intense laser fields S.220\n IPD0=1.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD1=2.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD2=3.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD3=4.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n IPD4=5.0*3.0/2.0/r0*ECHARGE*ECHARGE*(POWR(1.0+POWR(debye/r0,3.0),2.0/3.0)-POWR(debye/r0,2.0))/4.0/pi/ECONST;\n\n data->IPD0=IPD0;\n data->IPD1=IPD1;\n data->IPD2=IPD2;\n data->IPD3=IPD3;\n data->IPD4=IPD4;\n\n#endif\n\n int retval=colrad_GetCoeffs(y,It,data);\n if(retval !=0 )\n {\n printf(\"myid:%d, Warning: colrad getcoeefs returned not 0\\n\",myid);\n return 1; //d.h. failure of RHS\n }\n\n\n\n//printf(\"IPD0:%.4e,IPD1:%.4e,IPD2:%.4e\\n\", IPD0*J2eV,IPD1*J2eV,IPD2*J2eV);\n //**********************************************\n //Z=0, Exec/De-Exec + SPONTANEOUS EMISSION\n //**********************************************\n#ifdef OMP //OMP FUNZT AUF DIESE WEISE NICHT !!!\n //#pragma omp parallel for schedule(static) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)\n #pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)\n#endif\n for(i=0;i0 und delta-l=+-1 (nur opt.allowed trans.)\n if((STATES_z0[j][5]-STATES_z0[i][5])>0 && STATES_z0[j][4]-STATES_z0[i][4]==1)\n {\n Ajk=0.0;\n escape_factor=1.0;\n lambda0=planck*LIGHTSPEED/DeltaE;\n Ajk=EinsteinCoeff(STATES_z0[i][5],STATES_z0[j][5],STATES_z0[j][3],DeltaE);\n\n krev=Ith(y,ishift+j)*Ajk; //neues krev\n Ith(colrad_ydot,ishift+j) -= krev;\n Ith(colrad_ydot,ishift+i) += krev;\n //P_A_SE+=krev*DeltaE; ?? \n }\n#endif\n\n }\n }\n\n // *************************************\n //Z=1, Exec/De-Exec & SPONTANEOUS EMISSION\n // ***************************************\n shift2=z0_len;\n#ifdef OMP\n //#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)\n #pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)\n#endif\n for(i=0;i0 und delta-l=+-1 (nur opt.allowed trans.)\n if((STATES_z1[j][5]-STATES_z1[i][5])>0 && STATES_z1[j][4]-STATES_z1[i][4]==1)\n {\n escape_factor=1.0;\n lambda0=planck*LIGHTSPEED/DeltaE;\n Ajk=EinsteinCoeff(STATES_z1[i][5],STATES_z1[j][5],STATES_z1[j][3],DeltaE);\n\n krev=Ith(y,ishift+shift2+j)*Ajk;\n Ith(colrad_ydot,ishift+shift2+j) -= krev;\n Ith(colrad_ydot,ishift+shift2+i) += krev;\n //P_A_SE+=krev*DeltaE; ??\n }\n#endif\n }\n }\n\n// // *************************************\n// //Z=2, Exec/De-Exec & SPONTANEOUS EMISSION\n// // ***************************************\n#if MAXLEVEL > 1\n shift2=z0_len+z1_len;\n#ifdef OMP\n //#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)\n #pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)\n#endif\n for(i=0;i0 und delta-l=+-1 (nur opt.allowed trans.)\n if((STATES_z2[j][5]-STATES_z2[i][5])>0 && STATES_z2[j][4]-STATES_z2[i][4]==1)\n {\n escape_factor=1.0;\n lambda0=planck*LIGHTSPEED/DeltaE;\n Ajk=EinsteinCoeff(STATES_z2[i][5],STATES_z2[j][5],STATES_z2[j][3],DeltaE);\n\n krev=Ith(y,ishift+shift2+j)*Ajk;\n Ith(colrad_ydot,ishift+shift2+j) -= krev;\n Ith(colrad_ydot,ishift+shift2+i) += krev;\n //P_A_SE+=krev*DeltaE; ??\n }\n#endif\n }\n }\n#endif\n\n // *************************************\n //Z=3, Exec/De-Exec & SPONTANEOUS EMISSION\n // ***************************************\n#if MAXLEVEL > 2\n\n shift2=z0_len+z1_len+z2_len;\n#ifdef OMP\n// #pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)\n #pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)\n#endif\n for(i=0;i0 || Ith(y,j+ishift+shift2)>0)\n// printf(\"myid:%d, i:%d,j:%d,kEE3:%.4e, kEE3b:%.4e,kfwd:%.4e,krev:%.4e,ni:%.4e,nj:%.4e,ne:%.4e\\n\",myid,i,j,\n// k_EE_z3_z3[i][j],k_EE_z3_z3_b[i][j],kfwd,krev,\n// Ith(y,i+ishift+shift2),Ith(y,j+ishift+shift2),ne );\n// printf(\"Z3-exc:i:%d,j:%d, kfwd:%.4e,krev:%.4e\\n\", i,j,kfwd,krev);\n\n#ifdef SPONT\n // ********SPONT EMISSION ********* //\n //Spont.emiss: delta-n !=>0 und delta-l=+-1 (nur opt.allowed trans.)\n if((STATES_z3[j][5]-STATES_z3[i][5])>0 && STATES_z3[j][4]-STATES_z3[i][4]==1)\n {\n escape_factor=1.0;\n lambda0=planck*LIGHTSPEED/DeltaE;\n Ajk=EinsteinCoeff(STATES_z3[i][5],STATES_z3[j][5],STATES_z3[j][3],DeltaE);\n\n krev=Ith(y,ishift+shift2+j)*Ajk;\n Ith(colrad_ydot,ishift+shift2+j) -= krev;\n Ith(colrad_ydot,ishift+shift2+i) += krev;\n //P_A_SE+=krev*DeltaE; ??\n }\n#endif\n }\n }\n#endif //MAXLEVEL > 2\n\n\n // *************************************\n //Z=4, Exec/De-Exec & SPONTANEOUS EMISSION\n // ***************************************\n#if MAXLEVEL > 3\n\n shift2=z0_len+z1_len+z2_len+z3_len;\n#ifdef OMP\n// #pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc) num_threads(num_threads)\n #pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,krev,lambda0,Ajk,escape_factor,Eexc)\n#endif\n for(i=0;i0 und delta-l=+-1 (nur opt.allowed trans.)\n if((STATES_z4[j][5]-STATES_z4[i][5])>0 && STATES_z4[j][4]-STATES_z4[i][4]==1)\n {\n escape_factor=1.0;\n lambda0=planck*LIGHTSPEED/DeltaE;\n Ajk=EinsteinCoeff(STATES_z3[i][5],STATES_z3[j][5],STATES_z3[j][3],DeltaE);\n\n krev=Ith(y,ishift+shift2+j)*Ajk;\n Ith(colrad_ydot,ishift+shift2+j) -= krev;\n Ith(colrad_ydot,ishift+shift2+i) += krev;\n //P_A_SE+=krev*DeltaE; ??\n }\n#endif\n }\n }\n#endif // MAXLEVEL > 3 \n\n\n // ********************************************************\n // NOW IONIZATION RATES\n // ********************************************************\n // ***************************\n //Z=0->Z=1, Ioniz./Recomb.\n // ***************************\n shift1=ishift;\n shift2=ishift+z0_len;\n#ifdef OMP\n // #pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)\n#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc)\n#endif\n for(i=0;i0 && STATES_z1[j][5]>STATES_z0[i][5])\n {\n //außerdem geht die quasi-static. approx. nur mit nu-nl>0\n groundstate_ioniz=(STATES_z1[0][2]-STATES_z0[0][2])*eV2J;\n sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);\n abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!\n tau=abs_coeff*thickness;\n wstark_freq=StarkWidth(STATES_z1[j][5],STATES_z0[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);\n lambda0=planck*LIGHTSPEED/DeltaE;\n wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;\n escape_factor=EscapeFactor(wstark_len*1e10,tau);\n }\n#endif\n\n//ACHTUNG: Diskussion ob MPI sich überhaupt für Potential-Lowering interessiert...?\nif(DeltaE >0 ) //DeltaE ist bereits abzgl. IPD\n{\n kfwd= k_MPI_z0_z1[i][j][0]*Ith(y,i+shift1); // Einheit: k_MPI = 1/s\n kfwd2=k_MPI_z0_z1[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!\n\n krev=k_MPI_z1_z0[i][j][0]*Ith(y,j+shift2)*ne;// *escape_factor; // *wlo; // einheit: k_RADRECOMB= m^3/s\n\n //kfwd2=0.0; // 3-photon-ioniz. off\n Ith(colrad_ydot,shift1+i) -=(kfwd +kfwd2);\n Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.\n Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);\n\n //krev=fmin(krev,kfwd);\n Ith(colrad_ydot,shift2+j) -=krev;\n Ith(colrad_ydot,shift1+i) +=krev;\n Ith(colrad_ydot,2)-=krev;\n\n // für 2 photonen und rad.recomb\n P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindet (bisher ohne self-absorption)\n //jetzt für 3 photonen\n P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));\n //jetzt rad recomb\n P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor; //Radiative cooling, c.f. http://www.astronomy.ohio-state.edu/~dhw/A825/notes8.pdf S.2\n}\n#endif //MPI\n\n }\n }\n\n // ***************************\n // Z=1->Z=2, Ioniz./Recomb.\n // ***************************\n#if MAXLEVEL > 1\n\n shift1=ishift+z0_len;\n shift2=ishift+z0_len+z1_len;\n#ifdef OMP\n //#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)\n#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) \n#endif\n for(i=0;i0 && STATES_z2[j][5]>STATES_z1[i][5])\n {\n //außerdem geht die quasi-static. approx. nur mit nu-nl>0\n groundstate_ioniz=(STATES_z2[0][2]-STATES_z1[0][2])*eV2J;\n sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);\n abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!\n tau=abs_coeff*thickness;\n wstark_freq=StarkWidth(STATES_z2[j][5],STATES_z1[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);\n lambda0=planck*LIGHTSPEED/DeltaE;\n wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;\n escape_factor=EscapeFactor(wstark_len*1e10,tau);\n }\n#endif\n\nif(DeltaE >0)\n{\n kfwd= k_MPI_z1_z2[i][j][0]*Ith(y,i+shift1); // *wup;\n kfwd2=k_MPI_z1_z2[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!\n\n krev=k_MPI_z2_z1[i][j][0]*Ith(y,shift2+j)*ne; // *wlo; //eigentlich Rad-recomb.!=k_MPI_rev, einheit von k=m^3/s\n\n //kfwd2=0.0; // 3-photon-ioniz. off\n Ith(colrad_ydot,i+shift1) -=(kfwd +kfwd2);\n Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.\n Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);\n\n //krev=fmin(krev,kfwd);\n Ith(colrad_ydot,shift2+j) -=krev;\n Ith(colrad_ydot,shift1+i) +=krev;\n Ith(colrad_ydot,2)-=krev;\n\n // für 2 photonen und rad.recomb\n P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindert (bisher ohne self-absorption)\n //jetzt für 3 photonen\n P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));\n //jetzt rad recomb\n P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor;\n}\n#endif //MPI\n\n }\n }\n#endif // MAXLEVEL > 1\n\n // ***************************\n // Z=2->Z=3, Ioniz./Recomb.\n // ***************************\n#if MAXLEVEL > 2\n\n shift1=ishift+z0_len+z1_len;\n shift2=ishift+z0_len+z1_len+z2_len;\n#ifdef OMP\n //#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)\n#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) \n#endif\n for(i=0;i0 && STATES_z3[j][5]>STATES_z2[i][5])\n {\n //außerdem geht die quasi-static. approx. nur mit nu-nl>0\n groundstate_ioniz=(STATES_z3[0][2]-STATES_z2[0][2])*eV2J;\n sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);\n abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!\n tau=abs_coeff*thickness;\n wstark_freq=StarkWidth(STATES_z3[j][5],STATES_z2[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);\n lambda0=planck*LIGHTSPEED/DeltaE;\n wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;\n escape_factor=EscapeFactor(wstark_len*1e10,tau);\n }\n#endif\n\nif(DeltaE >0)\n{\n kfwd= k_MPI_z2_z3[i][j][0]*Ith(y,i+shift1); // *wup;\n kfwd2=k_MPI_z3_z2[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!\n\n krev=k_MPI_z3_z2[i][j][0]*Ith(y,shift2+j)*ne; // *wlo; //eigentlich Rad-recomb.!=k_MPI_rev, einheit von k=m^3/s\n\n //kfwd2=0.0; // 3-photon-ioniz. off\n Ith(colrad_ydot,i+shift1) -=(kfwd +kfwd2);\n Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.\n Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);\n\n //krev=fmin(krev,kfwd);\n Ith(colrad_ydot,shift2+j) -=krev;\n Ith(colrad_ydot,shift1+i) +=krev;\n Ith(colrad_ydot,2)-=krev;\n\n // für 2 photonen und rad.recomb\n P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindert (bisher ohne self-absorption)\n //jetzt für 3 photonen\n P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));\n //jetzt rad recomb\n P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor;\n}\n#endif //MPI\n\n }\n }\n#endif // MAXLEVEL > 2\n\n // ***************************\n // Z=3->Z=4, Ioniz./Recomb.\n // ***************************\n#if MAXLEVEL > 3\n\n shift1=ishift+z0_len+z1_len+z2_len;\n shift2=ishift+z0_len+z1_len+z2_len+z3_len;\n#ifdef OMP\n //#pragma omp parallel for schedule(dynamic,1) collapse(2) private(DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) num_threads(num_threads)\n#pragma omp for nowait schedule(static) private(j,DeltaE,kfwd,kfwd2,krev,\\\n escape_factor,groundstate_ioniz,sigma_PI,abs_coeff,tau,wstark_freq,lambda0,Eexc) \n#endif\n for(i=0;i0 && STATES_z4[j][5]>STATES_z3[i][5])\n {\n //außerdem geht die quasi-static. approx. nur mit nu-nl>0\n groundstate_ioniz=(STATES_z4[0][2]-STATES_z3[0][2])*eV2J;\n sigma_PI=sigma_tmp*POWR(DeltaE,2.5)/SQRTR(groundstate_ioniz);\n abs_coeff=sigma_PI*ne; //cross-section mit Pauli-blocking-faktor korrigieren!\n tau=abs_coeff*thickness;\n wstark_freq=StarkWidth(STATES_z4[j][5],STATES_z3[i][5],Te/11605,Ti/11605,Ti/11605,ne,totalc);\n lambda0=planck*LIGHTSPEED/DeltaE;\n wstark_len=wstark_freq*lambda0*lambda0/LIGHTSPEED;\n escape_factor=EscapeFactor(wstark_len*1e10,tau);\n }\n#endif\n\nif(DeltaE >0)\n{\n kfwd= k_MPI_z3_z4[i][j][0]*Ith(y,i+shift1); // *wup;\n kfwd2=k_MPI_z4_z3[i][j][1]*Ith(y,i+shift1); // *wup; // 2 photon- and 3-photon ionization!\n\n krev=k_MPI_z4_z3[i][j][0]*Ith(y,shift2+j)*ne; // *wlo; //eigentlich Rad-recomb.!=k_MPI_rev, einheit von k=m^3/s\n\n //kfwd2=0.0; // 3-photon-ioniz. off\n Ith(colrad_ydot,i+shift1) -=(kfwd +kfwd2);\n Ith(colrad_ydot,2) +=(kfwd +kfwd2); //Ne inc.\n Ith(colrad_ydot,shift2+j) +=(kfwd +kfwd2);\n\n //krev=fmin(krev,kfwd);\n Ith(colrad_ydot,shift2+j) -=krev;\n Ith(colrad_ydot,shift1+i) +=krev;\n Ith(colrad_ydot,2)-=krev;\n\n // für 2 photonen und rad.recomb\n P_E_MPI2 += kfwd* (2.0*planck*LASERFREQ-(DeltaE)); //kein heating durch rad.recomb->Photon verschwindert (bisher ohne self-absorption)\n //jetzt für 3 photonen\n P_E_MPI3 += kfwd2*(3.0*planck*LASERFREQ-(DeltaE));\n //jetzt rad recomb\n P_E_RAD_RECOMB -= krev*(DeltaE)*escape_factor;\n}\n#endif //MPI\n\n }\n }\n#endif //MAXLEVEL > 3 \n\n // ********************** THERMO ******************************************\n\n // double cvinv=1.0/(1.5*BOLTZMAN*ne);\n\n Real P_E_TOTAL=P_E_EI+P_E_EE+P_E_MPI2+P_E_MPI3+P_E_RAD_RECOMB;\n data->P_TOTAL=P_E_TOTAL;\n data->P_EE=P_E_EE;\n data->P_EI=P_E_EI;\n data->P_MPI2=P_E_MPI2;\n data->P_MPI3=P_E_MPI3;\n data->P_RR=P_E_RAD_RECOMB;\n\n // printf(\"myid:%d, PEI:%.4e, PEE:%.4e,MPI2:%.4e, MPI3:%.4e, RADREC:%.4e\\n\",\n // myid,\n // P_E_EI, \n // P_E_EE, \n // P_E_MPI2, \n // P_E_MPI3, \n // P_E_RAD_RECOMB);\n\n //BEI PRE-EQUILIBRIERUNG T=CONST !\n if(initial_equi==false)\n {\n Real cv=EOS_cve_from_r_te(data->dens, Te); \n\n cv *= 1e30/11604.5*eV2J; // von eV/(eV*A^3) to J/(K*m^3) \n Real cvinv=1.0/cv; \n\n // double cvinv= 1.0/Cv(Te/11604.5, ne);\n //double cvinv=1.0/(1.5*BOLTZMAN*Te);\n Ith(colrad_ydot,0) = cvinv*P_E_TOTAL;\n Ith(colrad_ydot,0) += data->Heatrate;\n\n// if(myid==1)\n// for(i=0;iIPD0*J2eV;\n Real IPD1=data->IPD1*J2eV;\n Real IPD2=data->IPD2*J2eV;\n Real IPD3=data->IPD3*J2eV;\n Real IPD4=data->IPD4*J2eV;\n Real EF=data->EF*J2eV;\n\n Real Tinit=data->Tinit;\n bool initial_equi = data->initial_equi;\n\n if(initial_equi)\n {\n if(ABS(Te-Tinit) > Tinit*0.03) // cvode war zu eifrig und probiert extreme temp. aus\n return -1;\n }\n // else\n // {\n // // if(ABS(Te-Tinit) > Tinit*0.5) // cvode war zu eifrig und probiert extreme temp. aus\n // // return -1; \n // if(Te>1e4) //ACHTUNG: Keine gute lösung...eher hotfix\n // return -1;\n // }\n\n //MPI\n // Real k_RR_fact1=32*pi*POWR(bohr_radius,2.0)/3.0/175700.00067;\n // Real k_RR_fact2=POWR((E_ion_H/BOLTZMAN/Te),2.0);\n // Real sigma_MPI_2;//=sigma1/LASERFREQ/POWR(planck*LASERFREQ,2.0); //MPI-cross-sect. (2-photon)\n // Real sigma_MPI_3;\n // Real sigma1;\n\n //const. zur berechnung von sigma1\n // Real sigma_tmp=64.0*POWR(pi,4.0)*POWR(ECHARGE,10.0)*EMASS/3.0/SQRTR(3.0)/POWR(4.0*pi*ECONST,5.0)/POWR(planck,6.0)/LIGHTSPEED/POWR(LASERFREQ,3.0)/POWR(13.6*eV2J,2.0);\n // Real I_sq=It*It; //for 2-photon-ioniz.\n // Real I_cu=I_sq*It; // for 3-photon-ioniz.\n int fail=0;\n\n // Real pow_two_pi_me_kT_hsq_tmp1= POWR(two_pi_me_kT_hsq,1.5); //ACHTUNG: Das ist thermal De-Broglie Lambda\n //Ich muss das für die rückwärts-raten irgendie \n //durch chempot ersetzen sonst pass das net\n //Ebenso in Saha\n#ifdef MULTIPHOTON\n Real twophoton_energy=2.0*planck*LASERFREQ*J2eV;\n Real threephoton_energy=3.0*planck*LASERFREQ*J2eV;\n Real nu_div_hnu_sq=LASERFREQ/POWR(planck*LASERFREQ,2.0);\n Real nu_div_nu_div_hnu_cub=LASERFREQ/LASERFREQ/POWR(planck*LASERFREQ,3.0);\n#endif\n\n\n Real mu=chempot(ne,Te);\n Real mu_eV=mu*J2eV;\n //Real fermi_factor=eval_fermi_integrand(ne,Te,mu);\n Real fermi_factor=1.0;\n if(fermi_factor==-1)\n return -1;\n\n // Real kmax_estim=1e4; \n Real nesq=gsl_pow_2(ne);\n\n\n //PREZERO RATE-COEFFS CODEBLOCK \n {\n //pre-zero k_EE's\n for(i=0;i 1\n for(i=0;i 2 \n for(i=0;i 3\n for(i=0;i 1 \n for(i=0;i 2 \n for(i=0;i 3 \n for(i=0;i 1\n\n fail=0;\n#ifdef OMP\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)\n#endif\n for(i=0;i 1\n\n ////////////////////////\n // Elec. exc. for Z=3\n ///////////////////////\n#if MAXLEVEL > 2\n\n fail=0;\n #ifdef OMP\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)\n #endif\n for(i=0;i 2\n\n\n ////////////////////////\n // Elec. exc. for Z=4\n ///////////////////////\n#if MAXLEVEL > 3\n\n fail=0;\n#ifdef OMP\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_exc,winteg_exc)\n#endif\n for(i=0;i 3\n\n\n // *************************************************\n // * NOW IONIZATION COEFFS\n // *************************************************\n /////////////////\n // Ioniz. 0->1\n /////////////////\n \n fail=0;\n#ifdef OMP\n // #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)\n // #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)\n#endif\n for(i=0;i MINRATE) \n k_EI_z0_z1[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));\n\nif(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+3) > MINRATE)\n k_EI_z1_z0[i][j]=STATES_z0[i][3]/STATES_z1[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J); \n\nk_EI_MAX=MAX(k_EI_MAX,k_EI_z0_z1[i][j]);\nk_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z1_z0[i][j]);\n \n k_EI_z0_z1[i][j]*=fermi_factor;\n k_EI_z1_z0[i][j]*=fermi_factor;\n\n#ifdef MULTIPHOTON\n // *******************\n // * MPI 2 PHOTONS *\n // *******************\n Real dE_SI=DeltaE*eV2J; \n if(twophoton_energy >= DeltaE-IPD0 && DeltaE-IPD0 > 0.0 )\n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;\n k_MPI_z0_z1[i][j][0]=sigma_MPI_2*I_sq;\n }\n // *******************\n // * MPI 3 PHOTONS *\n // ******************* \n if(threephoton_energy >= DeltaE-IPD0 && DeltaE-IPD0 >0.0 ) \n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;\n k_MPI_z0_z1[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);\n }\n#endif \n // ***************\n // * RAD RECOMB *\n // ***************\n // if(DeltaE>0)\n // {\n // if(expint > 0 )\n // {\n // //k_MPI_z1_z0[i][j][0]=v_e*k_RR_fact1*1.0*k_RR_fact2*POWR((DeltaE)*J2eV/STATES_z1[j][2],1.5)*expint*exp(a);\n // k_MPI_z1_z0[i][j][0]=v_e*k_RR_fact1*1.0*k_RR_fact2*POWR((DeltaE)/STATES_z1[j][2],1.5)*expint*exp(a);\n // }\n // else \n // {\n // k_MPI_z1_z0[i][j][0]=0.0; //exp(a) kann +Inf werden--> unsinnige rate coeff.. wenn einer der faktoren=0 --> rest egal\n // }\n // }\n\n }\n }\n\n\n\n /////////////////\n // Ioniz. 1->2\n ///////////////// \n#if MAXLEVEL > 1\n fail=0;\n#ifdef OMP\n // #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)\n // #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)\n#endif\n for(i=0;i MINRATE)\n{\n\n k_EI_z1_z2[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));\n\n // if(myid==1)\n // printf(\"EVAL dE:%.4e, kEI:%.4e,i:%d,j:%d\\n\", DeltaE, k_EI_z1_z2[i][j],i,j); \n}\n\n// if(kmax_estim*ne*ne*Ith(y,j+z0_len+z1_len+3)>MINRATE)\nif(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+z1_len+3) > MINRATE) \n k_EI_z2_z1[i][j]=STATES_z1[i][3]/STATES_z2[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);\n\nk_EI_MAX=MAX(k_EI_MAX,k_EI_z1_z2[i][j]);\nk_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z2_z1[i][j]);\n\n k_EI_z1_z2[i][j]*=fermi_factor;\n k_EI_z2_z1[i][j]*=fermi_factor;\n\n\n\n#ifdef MULTIPHOTON\n Real dE_SI=DeltaE*eV2J; \n // *******************\n // * MPI 2 PHOTONS *\n // *******************\n if(twophoton_energy >= DeltaE - IPD1)\n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;\n k_MPI_z1_z2[i][j][0]=sigma_MPI_2*I_sq;\n }\n // *******************\n // * MPI 3 PHOTONS *\n // ******************* \n if(threephoton_energy > DeltaE - IPD1)\n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;\n k_MPI_z1_z2[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);\n }\n#endif \n // **************\n // * RAD RECOMB *\n // **************\n // if(DeltaE>0)\n // {\n\n // if(expint > 0 )\n // {\n // k_MPI_z2_z1[i][j][0]=v_e*k_RR_fact1*4.0*k_RR_fact2*POWR((DeltaE)/STATES_z2[j][2],1.5)*expint*exp(a); \n // }\n // else \n // {\n // k_MPI_z2_z1[i][j][0]=0.0; //exp(a) kann +Inf werden--> unsinnige rate coeff.. wenn einer der faktoren=0 --> rest egal\n // } \n // } \n\n }\n }\n\n\n#endif //MAXLEVEL > 1\n\n /////////////////\n // Ioniz. 2->3\n ///////////////// \n#if MAXLEVEL > 2\n\n fail=0;\n#ifdef OMP\n // #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)\n // #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)\n#endif\n for(i=0;i MINRATE)\n k_EI_z2_z3[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));\n\n// if(kmax_estim*ne*ne*Ith(y,j+z0_len+z1_len+z2_len+3)>MINRATE) \nif(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+z1_len+z2_len+3) > MINRATE)\n{\n k_EI_z3_z2[i][j]=STATES_z2[i][3]/STATES_z3[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);\n}\n\n\nk_EI_MAX=MAX(k_EI_MAX,k_EI_z1_z2[i][j]);\nk_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z2_z1[i][j]);\n\n k_EI_z2_z3[i][j]*=fermi_factor;\n k_EI_z3_z2[i][j]*=fermi_factor;\n\n#ifdef MULTIPHOTON\n Real dE_SI=DeltaE*eV2J;\n // *******************\n // * MPI 2 PHOTONS *\n // *******************\n if(twophoton_energy > DeltaE - IPD2)\n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;\n k_MPI_z2_z3[i][j][0]=sigma_MPI_2*I_sq;\n }\n // *******************\n // * MPI 3 PHOTONS *\n // ******************* \n if(threephoton_energy > DeltaE -IPD2)\n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;\n k_MPI_z2_z3[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);\n }\n#endif \n \n }\n }\n if(fail==1) return -1;\n\n #endif // MAXLEVEL > 2\n\n /////////////////\n // Ioniz. 3->4\n ///////////////// \n#if MAXLEVEL > 3 \n\n fail=0;\n#ifdef OMP\n // #pragma omp parallel for schedule(static) collapse(2) private(kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2) num_threads(num_threads)\n // #pragma omp for nowait schedule(static) private(j,kronecker,DeltaE,a,expint,G2,I_1,I_2,sigma1,sigma_MPI_2,sigma_MPI_3,tmp0,tmp1,tmp2)\n // #pragma omp for simd schedule(static) private(j,kronecker,DeltaE,fparams_inner, fparams_outer, winteg_inner, winteg_outer,winteg_rb_inner,winteg_rb_outer)\n#endif\n for(i=0;i MINRATE)\n k_EI_z3_z4[i][j]=MAX(0.0,double_integral_ionization2(ne,Te, mu, DeltaE*eV2J));\n\n// if(kmax_estim*ne*ne*Ith(y,j+z0_len+z1_len+z2_len+z3_len+3)>MINRATE) \nif(RATERECOMBMAX*nesq*fermi_factor*Ith(y,j+z0_len+z1_len+z2_len+z3_len+3) > MINRATE) \n k_EI_z4_z3[i][j]=STATES_z3[i][3]/STATES_z4[j][3]*double_integral_recombination(ne,Te, mu, DeltaE*eV2J);\n\nk_EI_MAX=MAX(k_EI_MAX,k_EI_z3_z4[i][j]);\nk_EI_REV_MAX=MAX(k_EI_REV_MAX,k_EI_z4_z3[i][j]); \n\n k_EI_z3_z4[i][j]*=fermi_factor;\n k_EI_z4_z3[i][j]*=fermi_factor;\n\n#ifdef MULTIPHOTON\n Real dE_SI=DeltaE*eV2J;\n // *******************\n // * MPI 2 PHOTONS *\n // *******************\n if(twophoton_energy> DeltaE - IPD3)\n {\n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_2=sigma1*sigma1/nu_div_hnu_sq;\n k_MPI_z3_z4[i][j][0]=sigma_MPI_2*I_sq;\n }\n // *******************\n // * MPI 3 PHOTONS *\n // ******************* \n if(threephoton_energy > DeltaE - IPD3)\n { \n sigma1=sigma_tmp*POWR(dE_SI,2.5)/SQRTR(dE_SI);\n sigma_MPI_3=sigma1*sigma1*sigma1/2.0/nu_div_nu_div_hnu_cub;\n k_MPI_z3_z4[i][j][1]=sigma_MPI_3*I_cu;//*prob*beta_pi(Te,mu,DeltaE);\n }\n#endif\n // **************\n // * RAD RECOMB *\n // **************\n // if(DeltaE>0)\n // {\n // if(expint>0)\n // {\n // k_MPI_z4_z3[i][j][0]=v_e*k_RR_fact1*4.0*k_RR_fact2*POWR((DeltaE)/STATES_z4[j][2],1.5)*expint*exp(a); \n // }\n // else\n // {\n // k_MPI_z4_z3[i][j][0]=0.0;\n // } \n \n // } \n \n }\n }\n\n\n#endif // MAXLEVEL > 3\n// if(k_EI_MAX >0 || k_EI_REV_MAX > 0)\n // printf(\"myid:%d, k_EI_MAX:%.4e, k_EI_REV_MAX:%.4e,fac:%.4e\\n\",myid,k_EI_MAX,k_EI_REV_MAX,fermi_factor);\n return 0;\n\n}\n\n// ***************************************************************************************\n\n\n\n// ********************************************************************\n// * WRITE COLRAD CONCENTRATIONS TO FILE FOR RESTART\n// ********************************************************************\nint colrad_write(int number)\n{\n FILE *outfile;\n char fname[255];\n sprintf(fname, \"%s.%d.%d.colrad\", outfilename, myid,number);\n outfile = fopen(fname, \"w\");\n if (NULL == outfile)\n {\n char errstr[255];\n sprintf(errstr,\"ERROR: cannot open colrad outfile %s\\n\",fname);\n error(errstr);\n }\n\n int i,j,k,l; \n for(i=1; i < local_fd_dim.x-1; i++)\n {\n for(j=1; j < local_fd_dim.y-1; j++)\n {\n for(k=1; k < local_fd_dim.z-1; k++) \n {\n fprintf(outfile,\"%d %d %d\",i,j,k);\n for(l=0;lne;\n Real T=params->T;\n Real mu=params->mu; \n Real DeltaE = params->DeltaE; \n Real E=params->E; //brauche ich nachher für E''=E-E'-DELTAE\n Real E_prime_prime=E-E_prime-DeltaE;\n\n Real Pauli_E_prime=1.0-1.0/(1.0+EXPR((E_prime-mu)/BOLTZMAN/T));\n Real Pauli_E_prime_prime=1.0-1.0/(1.0+EXPR((E_prime_prime-mu)/BOLTZMAN/T));\n\n Real f=Pauli_E_prime*Pauli_E_prime_prime; //F(E), sigmaderiv und SQRTR(2*eng1/emass) im outer integrand\n return f;\n}\n\n\ndouble inner_integrand_recombination(double x, void *p) // x=incoming elec. energy : ACHTUNG: Für x=0 --> NaN\n{ \n struct my_f_params * params = (struct my_f_params *)p;\n Real E_prime=x;\n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n Real DeltaE = params->DeltaE; \n Real E=params->E; \n \n // Anmerkung: E'' und E' sind die enregien der einfallenden elektronen\n // während E=DeltaE+E'+E'' energie des sekunddären Elektrons!\n // Real E=DeltaE+E_prime+E_prime_prime; \n Real E_prime_prime=E-DeltaE-E_prime;\n Real fermi_fun_E_prime= 1.0/(1.0+EXPR((E_prime-mu)/BOLTZMAN/T));\n Real fermi_fun_E_prime_prime=1.0/(1.0+EXPR((E_prime_prime-mu)/BOLTZMAN/T));\n Real f= fermi_fun_E_prime * fermi_fun_E_prime_prime;\n return f;\n}\n\n\ndouble outer_integrand_recombination(double x,void *p)\n{\n struct my_f_params * params = (struct my_f_params *)p;\n Real E=x; //other incoming electron (inneres Integral behandelt E_prime) \n //Das sekundäre Elektron hat Energie E,\n Real DeltaE = params->DeltaE; \n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n\n \n if(E <= DeltaE) \n return 0.0; //Cross section wird =0\n\n Real fermi_fun=1.0/(1.0+EXPR((E-mu)/BOLTZMAN/T));\n Real Pauli_E = 1.0-fermi_fun;\n\n struct my_f_params fparams_inner;\n fparams_inner.T=T;\n fparams_inner.ne=ne;\n fparams_inner.mu=mu;\n fparams_inner.DeltaE=DeltaE;\n fparams_inner.E=E;\n\n gsl_function gslfun_inner;\n gslfun_inner.function=&inner_integrand_recombination;\n gslfun_inner.params=&fparams_inner; \n\n double integ_inner;\n double integ_err;\n\n Real y=E/DeltaE;\n // Real sigma_deriv = 4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J / gsl_pow_2(DeltaE) * alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4) \n // /2.0/(E-DeltaE); \n \n\n //konstanten nach double_integral_recombination verfrachtet \n Real sigma_deriv = (y-1.0)/POWR(y,2.0)*LOGR(beta_i*1.25*y)/(E-DeltaE); \n\n\n // gsl_integration_qag(&gslfun_inner, 1e-21, E-DeltaE, 1e-4, 1e-4, integ_meshdim,1,\n // winteg_inner, &integ_inner, &integ_err); \n\n // size_t evals;\n // gsl_integration_romberg(&gslfun_inner, 1e-21, E-DeltaE, 1e-4, 1e-4, &integ_inner,\n // &evals, winteg_rb_inner);\n\n\n stack_t stack2; \n create_stack(&stack2, sizeof(work_gkq));\n\n integ_inner=gkq(inner_integrand_recombination, 1e-21, E-DeltaE, 1e-3, &fparams_inner, stack2);\n\n free(stack2->elements);\n free(stack2);\n\n\n\n return ((Real) sigma_deriv*Pauli_E*E*integ_inner);\n\n}\n\nReal double_integral_recombination(Real ne,Real T, Real mu, Real DeltaE)\n{\n\n// return 0;\n gsl_function gslfun_outer;\n gslfun_outer.function = &outer_integrand_recombination;\n\n struct my_f_params fparams_outer;\n\n fparams_outer.T=T;\n fparams_outer.ne=ne;\n fparams_outer.mu=mu;\n fparams_outer.DeltaE=DeltaE;\n\n gslfun_outer.params = &fparams_outer;\n\n double integ_outer=0;\n double integ_err=0;\n\n //angepasste obere integr. grenze\n Real eupper=0.0;\n if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE;\n else eupper=10.0*T/11604* eV2J+ DeltaE;\n\n // integrand_inner=@(eng1,eng2) sigma_deriv(eng1).*SQRTR(2*eng1/emass) ...\n // .*F(eng1).*Pauli(eng2).*Pauli(eng1-DeltaE-eng2);\n\n\n // gsl_integration_qagiu(&gslfun_outer, 0.0, integ_abstol, integ_reltol, integ_meshdim,\n // winteg_outer, &integ_outer, &integ_err); \n\n // gsl_integration_qag(&gslfun_outer, DeltaE, eupper, integ_abstol_recomb, integ_reltol, integ_meshdim,1,\n // winteg_outer, &integ_outer, &integ_err); \n\n\n\n stack_t stack; \n create_stack(&stack, sizeof(work_gkq));\n integ_outer=gkq(outer_integrand_recombination,DeltaE*1.001, eupper, 1e-3, &fparams_outer,stack); \n\n free(stack->elements);\n free(stack);\n\n\n\n integ_outer *= 2.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i; //konstanten aus sigma_deriv herausgezogen\n\n // size_t evals;\n // gsl_integration_romberg(&gslfun_outer, DeltaE, muINF, 1e-6, integ_reltol, &integ_outer,\n // &evals, winteg_rb_outer);\n\n\n //NICHT VERGESSEN: RATIO DER STATISTICAL WEIGHTS\n integ_outer *= recomb_const/ne/ne; //Später ne^2 entfernen und in ydot entfernen!\n // if(integ_outer < 1e-100) integ_outer=0.0;\n return MAX((Real) integ_outer,0.0);\n\n}\n\n\n\n\ndouble fermi_integrand(double x, void *p)\n{\n struct my_f_params * params = (struct my_f_params *)p;\n Real eng=x;\n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n\n Real vel=SQRTR(2.0*eng/EMASS);\n Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));\n Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun; // DOS * f_fermi\n\n return F;\n}\nReal eval_fermi_integrand(Real ne,Real T, Real mu)\n{\n struct my_f_params fparams_fermi;\n fparams_fermi.T=T;\n fparams_fermi.ne=ne;\n fparams_fermi.mu=mu; \n\n gsl_function fun;\n fun.function=&fermi_integrand;\n fun.params=&fparams_fermi;\n\n double integ_err=0;\n double integ_result=0;\n\n\n gsl_error_handler_t *old_error_handler=gsl_set_error_handler_off ();\n\n\n // int code= gsl_integration_qags (&fun, mu, muINF, integ_abstol, integ_reltol, integ_meshdim,\n // winteg_fermi, &integ_result, &integ_err); \n\n // int code=gsl_integration_qagiu(&fun, mu, integ_abstol, integ_reltol, integ_meshdim,\n // winteg_fermi, &integ_result, &integ_err); \n\n int code= gsl_integration_qag(&fun, 0, 3.0*muINF, integ_abstol, integ_reltol, integ_meshdim,1,\n winteg_fermi, &integ_result, &integ_err); \n\n\n gsl_set_error_handler(old_error_handler); //reset the error handler \n\n return (code==GSL_SUCCESS ? (Real) integ_result : -1); // RHS abbrechen -> neuer versuch\n\n //return integ_result;\n}\n\n\n\n\nReal eval_excitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed)\n{\n gsl_function fun;\n fun.function = &integrand_excitation;\n\n struct my_f_params fparams_exc;\n\n fparams_exc.T=T;\n fparams_exc.ne=ne;\n fparams_exc.mu=mu;\n fparams_exc.DeltaE=DeltaE;\n fparams_exc.allowed=allowed;\n\n fun.params = &fparams_exc;\n\n double integ_result=0;\n double integ_err=0;\n\n double eupper=0.0;\n if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet\n else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet\n\n\n// integ_result = integral_simpson(&integrand_excitation, DeltaE, 20*DeltaE, 5000, &fparams_exc);\n\n\n // gsl_error_handler_t *old_error_handler=gsl_set_error_handler_off ();\n\n // // int code= gsl_integration_qags (&fun, DeltaE, muINF, integ_abstol, integ_reltol, integ_meshdim,\n // // winteg_exc, &integ_result, &integ_err); \n \n // //Abstol ist zwar nicht streng aber scheint ausreichend...ergebnisse sind genauso gut \n // int code= gsl_integration_qag(&fun, (double) DeltaE, (double) eupper, 1e-6, (double) integ_reltol, integ_meshdim,1,\n // winteg_exc, &integ_result, &integ_err); \n\n\n // gsl_set_error_handler(old_error_handler); //reset the error handler \n\n // if (code != GSL_SUCCESS)\n // {\n // //print integrand\n // int i=0;\n // Real dx=(muINF-DeltaE)/250; \n // for(i=0;i<250;i++)\n // {\n // printf(\"x:%.4e,T:%f, ne:%.2e, dE:%.2e, integ:%.4e\\n\",\n // dx*i,fparams_exc.T, fparams_exc.ne, fparams_exc.DeltaE, integrand_excitation_debug(dx*i,&fparams_exc));\n // }\n\n // error(\"ERROR in eval_excitation_integral\\n\");\n // }\n\n\n stack_t stack; \n create_stack(&stack, sizeof(work_gkq));\n integ_result=gkq(integrand_excitation, DeltaE*1.001, eupper, 1e-3, &fparams_exc,stack); \n free(stack->elements);\n free(stack);\n\n\n \n return MAX((Real) integ_result,0.0);\n\n}\n\n\nReal eval_dexcitation_integral(Real ne,Real T,Real mu, Real DeltaE, int allowed)\n{ \n gsl_function fun;\n fun.function = &integrand_deexcitation;\n\n struct my_f_params fparams_exc;\n\n fparams_exc.T=T;\n fparams_exc.ne=ne;\n fparams_exc.mu=mu;\n fparams_exc.DeltaE=DeltaE;\n fparams_exc.allowed=allowed;\n\n fun.params = &fparams_exc;\n\n double integ_result=0;\n double integ_err=0;\n\n double eupper=0.0;\n if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet\n else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet\n\n // gsl_integration_qagiu(&fun, DeltaE, integ_abstol, integ_reltol, integ_meshdim,\n // winteg_exc, &integ_result, &integ_err); \n\n //Wird sonst immer zu null\n // gsl_integration_qags (&fun, DeltaE, muINF, integ_abstol, integ_reltol, integ_meshdim,\n // winteg_exc, &integ_result, &integ_err); \n\n //Variante Aslan: effektives chem.pot und integriere wieder excitation_integrand statt de-exc.integrand\n fparams_exc.mu=mu+DeltaE;\n fun.function = &integrand_excitation;\n\n\n // gsl_integration_qags (&fun, DeltaE, muINF, integ_abstol, integ_reltol, integ_meshdim,\n // winteg_exc, &integ_result, &integ_err); \n\n // gsl_integration_qag(&fun, DeltaE, eupper, 1e-6, integ_reltol, integ_meshdim,1,\n // winteg_exc, &integ_result, &integ_err); \n\n\n\n stack_t stack; \n create_stack(&stack, sizeof(work_gkq));\n integ_result=gkq(integrand_excitation, DeltaE*1.001, eupper, 1e-3, &fparams_exc,stack); \n free(stack->elements);\n free(stack);\n\n\n return MAX((Real) integ_result,0.0);\n\n}\n\ndouble integrand_deexcitation(double x,void *p)\n{\n struct my_f_params * params = (struct my_f_params *)p;\n Real eng=x;\n Real DeltaE = params->DeltaE; \n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n int allowed=params->allowed;\n\n if(eng <= DeltaE)\n return 0.0;\n\n Real vel=SQRTR(2.0*eng/EMASS);\n // if(vel< 1e-100) return 0;\n\n Real fermi_fun=1.0/(1.0+EXPR((eng-DeltaE-mu)/BOLTZMAN/T)); //mod\n // if(fermi_fun < 1e-100) return 0;\n\n Real sigma=0.0;\n Real y=eng/DeltaE;\n\n Real Pauli=1.0-1.0/(1.0+EXPR((eng+mu)/BOLTZMAN/T)); //mod\n // if(Pauli<1e-100) return 0;\n\n if(allowed==1)\n sigma=4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J* gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4);\n else\n sigma=4.0*M_PI*bohr_radius_sq*alpha_i*(y-1.0)/gsl_pow_2(y);\n\n // Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun*SQRTR(eng/(eng-DeltaE)); //ACHTUNG: Letzter Term --> divergent\n Real F=1.062234185782204e+56/ne*SQRTR(eng/(eng-DeltaE))*fermi_fun;\n return vel*sigma*F*Pauli;\n}\n\ndouble integrand_excitation(double x,void *p)\n{\n struct my_f_params * params = (struct my_f_params *)p;\n Real eng=x;\n Real DeltaE = params->DeltaE; \n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n int allowed=params->allowed;\n \n if(eng <= DeltaE)\n return 0.0; //siehe flychk manual\n\n Real vel=SQRTR(2.0*eng/EMASS);\n Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));\n\n // if(fermi_fun < 1e-100) return 0;\n\n Real sigma=0.0;\n Real y=eng/DeltaE;\n Real Pauli=1.0-1.0/(1.0+EXPR((eng-DeltaE+mu)/BOLTZMAN/T));\n // if(Pauli < 1e-100) return 0;\n \n if(allowed==1)\n sigma=4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J* gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4); \n else\n sigma=4.0*M_PI*bohr_radius_sq*alpha_i*(y-1.0)/gsl_pow_2(y);\n\n\n // Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun; \n Real F=1.062234185782204e+56/ne*SQRTR(eng)*fermi_fun;\n // printf(\"F:%.4e, Pauli:%.4e, eng:%.4e, sigma:%.4e, y:%.4e, de:%.4e,ne:%.4e,T:%.4e\\n\", \n // F, Pauli, eng, sigma, y, DeltaE, ne, T);\n return vel*sigma*F*Pauli;\n}\n\n\n\n\n\n\n// *** EXAKTE KOPIE MIT ZUSÄTZL. PRINTF ****\ndouble integrand_excitation_debug(double x,void *p)\n{\n struct my_f_params * params = (struct my_f_params *)p;\n Real eng=x;\n Real DeltaE = params->DeltaE; \n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n int allowed=params->allowed;\n \n if(eng <= DeltaE)\n return 0.0; //siehe flychk manual\n\n Real vel=SQRTR(2.0*eng/EMASS);\n Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));\n\n // if(fermi_fun < 1e-100) return 0;\n\n Real sigma=0.0;\n Real y=eng/DeltaE;\n Real Pauli=1.0-1.0/(1.0+EXPR((eng-DeltaE+mu)/BOLTZMAN/T));\n // if(Pauli < 1e-100) return 0;\n \n if(allowed==1)\n sigma=4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J* gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4); \n else\n sigma=4.0*M_PI*bohr_radius_sq*alpha_i*(y-1.0)/gsl_pow_2(y);\n\n\n // Real F=double_emass_pow_3_2/2.0/ne/hbar_cub/pi_sq*SQRTR(eng)*fermi_fun; \n Real F=1.062234185782204e+56/ne*SQRTR(eng)*fermi_fun;\n\n printf(\"F:%.4e, Pauli:%.4e, eng:%.4e, sigma:%.4e, y:%.4e, de:%.4e,ne:%.4e,T:%.4e,sqrteng:%.4e,fermi_fun:%.4e\\n\", \n F, Pauli, eng, sigma, y, DeltaE, ne, T, SQRTR(eng),fermi_fun);\n return vel*sigma*F*Pauli;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndouble outer_integrand_ionization(double x,void *p)\n{\n struct my_f_params * params = (struct my_f_params *)p;\n Real eng=x;\n Real DeltaE = params->DeltaE; \n Real ne=params->ne;\n Real T=params->T;\n Real mu=params->mu; \n\n\n Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));\n\n // if(fermi_fun < 1e-100) return 0;\n\n if(eng <= DeltaE)\n return 0.0; //Cross section wird zu 0\n\n Real y=eng/DeltaE;\n\n // Real sigma_deriv = 4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4) \n // /2.0/(eng-DeltaE); \n\n //sigma_deriv: konstanten rausgezogen und nach double_integral_ionization verfrachtet\n Real sigma_deriv = (y-1.0)/POWR(y,2.0)*LOGR(beta_i*1.25*y)/(eng-DeltaE);\n\n struct my_f_params fparams_inner; \n\n fparams_inner.T=T;\n fparams_inner.ne=ne;\n fparams_inner.mu=mu;\n fparams_inner.DeltaE=DeltaE;\n fparams_inner.E=eng;\n\n gsl_function gslfun_inner;\n gslfun_inner.function=&inner_integrand_ionization;\n gslfun_inner.params=&fparams_inner; \n\n double integ_inner=0.0;\n double integ_err;\n\n gsl_integration_qag(&gslfun_inner, 1e-21, eng-DeltaE, 1e-20, 1e-4, integ_meshdim,1,\n winteg_inner, &integ_inner, &integ_err); \n\n // gsl_integration_qags(&gslfun_inner, 1e-21, eng-DeltaE, 1e-20, 1e-4, integ_meshdim, \n // winteg_inner, &integ_inner, &integ_err);\n // size_t evals;\n // gsl_integration_romberg(&gslfun_inner, 1e-21, eng-DeltaE, 1e-4, 1e-4, &integ_inner,\n // &evals, winteg_rb_inner);\n\n stack_t stack2; \n create_stack(&stack2, sizeof(work_gkq));\n double res2=0.0;\n \n terminate_gkq=0;\n res2=gkq(inner_integrand_ionization2, 1e-21, eng-DeltaE, 1e-4, &fparams_inner, stack2);\n \n \n work_gkq wtmp; \n free(stack2->elements); \n free(stack2);//hatte ich vorher vergessen\n\n // double res2=gkq_serial(inner_integrand_ionization2, 1e-21, eng-DeltaE, 1e-4, &fparams_inner);\n\n if(myid==1 && (res2 >0))\n printf(\"gsl:%.4e, gkq:%.4e\\n\", integ_inner, res2);\n\n return ((Real) eng*fermi_fun*sigma_deriv*integ_inner);\n\n}\n\n\ndouble outer_integrand_ionization2(double x, struct my_f_params* p)\n{\n Real eng=x;\n Real DeltaE=p->DeltaE;\n Real T=p->T;\n Real ne=p->ne;\n Real mu=p->mu;\n\n struct my_f_params fparams_inner;\n fparams_inner.T=T;\n fparams_inner.ne=ne;\n fparams_inner.mu=mu;\n fparams_inner.DeltaE=DeltaE;\n fparams_inner.E=eng;\n\n\n Real fermi_fun=1.0/(1.0+EXPR((eng-mu)/BOLTZMAN/T));\n\n // if(fermi_fun < 1e-100) return 0;\n\n if(eng <= DeltaE)\n return 0.0; //Cross section wird zu 0\n\n Real y=eng/DeltaE;\n\n // Real sigma_deriv = 4.0*M_PI*bohr_radius_sq*E_ion_H_sq_J * gsl_pow_2(1.0/DeltaE)*alpha_i*(y-1.0)/gsl_pow_2(y)*LOGR(5*beta_i*y/4) \n // /2.0/(eng-DeltaE); \n\n //sigma_deriv: konstanten rausgezogen und nach double_integral_ionization verfrachtet\n Real sigma_deriv = (y-1.0)/POWR(y,2.0)*LOGR(beta_i*1.25*y)/(eng-DeltaE);\n\n\n terminate_gkq=0;\n stack_t stack2; \n create_stack(&stack2, sizeof(work_gkq));\n\n double integ_inner=gkq(inner_integrand_ionization2, 1e-21, eng-DeltaE, 1e-3, &fparams_inner, stack2);\n\n free(stack2->elements);\n free(stack2);\n\n\n\n return ((Real) eng*fermi_fun*sigma_deriv*integ_inner);\n\n}\n\nReal double_integral_ionization(Real ne,Real T, Real mu, Real DeltaE)\n{\n // return 0;\n\n gsl_function gslfun_outer;\n gslfun_outer.function = &outer_integrand_ionization;\n\n struct my_f_params fparams_outer;\n\n fparams_outer.T=T;\n fparams_outer.ne=ne;\n fparams_outer.mu=mu;\n fparams_outer.DeltaE=DeltaE;\n\n gslfun_outer.params = &fparams_outer;\n\n double integ_outer=0;\n double integ_err=0;\n double eupper=0.0;\n if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet\n else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet\n\n\n gsl_integration_qag(&gslfun_outer, DeltaE*1.001, eupper, 1e-6, 1e-4, integ_meshdim,1,\n winteg_outer, &integ_outer, &integ_err); \n\n\n // serial simpson rule\n // integ_outer = integral_simpson(&outer_integrand_ionization, DeltaE*1.001, eupper, 1000, &fparams_outer);\n\n// *****************************************************\n\n // if(integ_outer 1)\n // if(myid==1 && integ_outer > 0) \n // {\n // if(DeltaE*J2eV > 5.9062 && DeltaE*J2eV < 5.9064) // && T> 1.9826e+03 && T > 1.9828e+03 && mu >1.6238e-18 && mu <1.6240e-18)\n // printf(\"AFTER: dE:%.4e, T:%.6e, mu:%.15e, ne:%.15e, integ:%.4e\\n\",DeltaE*J2eV,T,mu,ne,integ_outer);\n // }\n\n\n//WTF???\n// dE:5.9063e+00, T:1.208983e+03, mu:1.624114145844772e-18, ne:1.465920522460179e+29, integ:8.1974e-105\n// dE:5.9063e+00, T:1.208983e+03, mu:1.624114145844772e-18, ne:1.465920522460179e+29, integ:2.5497e-104\n// dE:5.9063e+00, T:1.208983e+03, mu:1.624114145844772e-18, ne:1.465920522460179e+29, integ:1.6998e-104\n\n\n return MAX((Real) integ_outer,0.0);\n\n}\n\n\nReal double_integral_ionization2(Real ne,Real T, Real mu, Real DeltaE)\n{\n // return 0;\n\n struct my_f_params fparams_outer;\n\n fparams_outer.T=T;\n fparams_outer.ne=ne;\n fparams_outer.mu=mu;\n fparams_outer.DeltaE=DeltaE;\n \n terminate_gkq=0;\n\n double integ_outer=0;\n double integ_err=0;\n double eupper=0.0;\n if(mu> 0) eupper=POWR(3*T,0.33) * eV2J + mu +DeltaE; //entartet\n else eupper=10.0*T/11604* eV2J+ DeltaE; //nicht-entartet\n\n\n stack_t stack; \n create_stack(&stack, sizeof(work_gkq));\n integ_outer=gkq(outer_integrand_ionization2, DeltaE*1.001, eupper, 1e-3, &fparams_outer,stack); \n\n free(stack->elements);\n free(stack);\n\n// *****************************************************\n\n // if(integ_outerne;\n Real T=p->T;\n Real mu=p->mu; \n Real DeltaE = p->DeltaE; \n Real E=p->E; //brauche ich nachher für E''=E-E'-DELTAE\n Real E_prime_prime=E-E_prime-DeltaE;\n\n Real Pauli_E_prime=1.0-1.0/(1.0+EXPR((E_prime-mu)/BOLTZMAN/T));\n Real Pauli_E_prime_prime=1.0-1.0/(1.0+EXPR((E_prime_prime-mu)/BOLTZMAN/T));\n\n Real f=Pauli_E_prime*Pauli_E_prime_prime; //F(E), sigmaderiv und SQRTR(2*eng1/emass) im outer integrand\n return f;\n}", "meta": {"hexsha": "82c1925cbec8da00de331bac9333e3681357b883", "size": 113856, "ext": "c", "lang": "C", "max_stars_repo_path": "imd_colrad.c", "max_stars_repo_name": "fmqeisfeld/IMD", "max_stars_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-30T08:23:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T07:49:51.000Z", "max_issues_repo_path": "imd_colrad.c", "max_issues_repo_name": "fmqeisfeld/IMD", "max_issues_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "imd_colrad.c", "max_forks_repo_name": "fmqeisfeld/IMD", "max_forks_repo_head_hexsha": "38c053355a1fa43168d3c785d8b55d789b07f222", "max_forks_repo_licenses": ["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.0729001585, "max_line_length": 177, "alphanum_fraction": 0.5743658657, "num_tokens": 42728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.269202850411182}} {"text": "#if !defined(lowMachFlow_h)\n#define lowMachFlow_h\n#include \n\n// Define the test field number\ntypedef enum { VTEST, QTEST, WTEST } LowMachFlowTestFields;\n\ntypedef enum { STROUHAL, REYNOLDS, FROUDE, PECLET, HEATRELEASE, GAMMA, PTH, MU, K, CP, BETA, GRAVITY_DIRECTION, TOTAL_LOW_MACH_FLOW_PARAMETERS } LowMachFlowParametersTypes;\nPETSC_EXTERN const char* lowMachFlowParametersTypeNames[TOTAL_LOW_MACH_FLOW_PARAMETERS + 1];\n\ntypedef enum {VEL, PRES, TEMP, TOTAL_LOW_MACH_FLOW_FIELDS} LowMachFlowFields;\n\ntypedef enum {MOM, MASS, ENERGY, TOTAL_LOW_MACH_SOURCE_FIELDS} LowMachSourceFields;\n\n// Low Mach Kernels\nPETSC_EXTERN void LowMachFlow_vIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\nconst PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]);\n\nPETSC_EXTERN void LowMachFlow_vIntegrandTestGradientFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],\n const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],\n PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]);\n\nPETSC_EXTERN void LowMachFlow_wIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]);\n\n\nPETSC_EXTERN void LowMachFlow_wIntegrandTestGradientFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[],\n const PetscScalar u_x[], const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[],\n PetscReal t, const PetscReal X[], PetscInt numConstants, const PetscScalar constants[], PetscScalar f1[]);\n\nPETSC_EXTERN void LowMachFlow_qIntegrandTestFunction(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, const PetscReal X[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar f0[]);\n\nPETSC_EXTERN void LowMachFlow_g0_qu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g1_qu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g0_qT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g0_qT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g1_qT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g0_vT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g0_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g1_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g3_vu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\n\nPETSC_EXTERN void LowMachFlow_g2_vp(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\n\nPETSC_EXTERN void LowMachFlow_g0_wu(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\n\nPETSC_EXTERN void LowMachFlow_g0_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\nPETSC_EXTERN void LowMachFlow_g1_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\n\nPETSC_EXTERN void LowMachFlow_g3_wT(PetscInt dim, PetscInt Nf, PetscInt NfAux, const PetscInt uOff[], const PetscInt uOff_x[], const PetscScalar u[], const PetscScalar u_t[], const PetscScalar u_x[],\n const PetscInt aOff[], const PetscInt aOff_x[], const PetscScalar a[], const PetscScalar a_t[], const PetscScalar a_x[], PetscReal t, PetscReal u_tShift, const PetscReal x[],\n PetscInt numConstants, const PetscScalar constants[], PetscScalar g0[]);\n\n\n#endif", "meta": {"hexsha": "82776e26ec4650a68f5139d04032569d8d42eb7c", "size": 10590, "ext": "h", "lang": "C", "max_stars_repo_path": "ablateCore/flow/lowMachFlow.h", "max_stars_repo_name": "mtmcgurn-buffalo/ablate", "max_stars_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-01-19T21:29:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-20T19:54:49.000Z", "max_issues_repo_path": "ablateCore/flow/lowMachFlow.h", "max_issues_repo_name": "mtmcgurn-buffalo/ablate", "max_issues_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 124.0, "max_issues_repo_issues_event_min_datetime": "2021-01-14T15:30:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T14:44:31.000Z", "max_forks_repo_path": "ablateCore/flow/lowMachFlow.h", "max_forks_repo_name": "mtmcgurn-buffalo/ablate", "max_forks_repo_head_hexsha": "35ee9a30277908775a61d78462ea9724ee631a9b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2021-02-10T22:34:57.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T18:46:06.000Z", "avg_line_length": 108.0612244898, "max_line_length": 216, "alphanum_fraction": 0.6750708215, "num_tokens": 2480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318479832805, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.26906947542758086}} {"text": "/* multifit_nlinear/lm.c\n * \n * Copyright (C) 2014, 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\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 * [2] J. J. More, The Levenberg-Marquardt Algorithm: Implementation\n * and Theory, Lecture Notes in Mathematics, v630, 1978.\n */\n\ntypedef struct\n{\n size_t n; /* number of observations */\n size_t p; /* number of parameters */\n gsl_vector *fvv; /* D_v^2 f(x), size n */\n gsl_vector *vel; /* geodesic velocity (standard LM step), size p */\n gsl_vector *acc; /* geodesic acceleration, size p */\n gsl_vector *workp; /* workspace, length p */\n gsl_vector *workn; /* workspace, length n */\n\n int accel; /* use geodesic acceleration? */\n\n /* tunable parameters */\n gsl_multifit_nlinear_parameters params;\n} lm_state_t;\n\n#include \"common.c\"\n\nstatic void *lm_alloc (const int accel, const void * params, const size_t n, const size_t p);\nstatic void *lm_alloc_noaccel (const void * params, const size_t n, const size_t p);\nstatic void *lm_alloc_accel (const void * params, const size_t n, const size_t p);\nstatic void lm_free(void *vstate);\nstatic int lm_init(const void *vtrust_state, void *vstate);\nstatic int lm_preloop(const void * vtrust_state, void * vstate);\nstatic int lm_step(const void * vtrust_state, const double delta,\n gsl_vector * dx, void * vstate);\nstatic int lm_preduction(const void * vtrust_state, const gsl_vector * dx,\n double * pred, void * vstate);\n\nstatic void *\nlm_alloc (const int accel, const void * params, const size_t n, const size_t p)\n{\n const gsl_multifit_nlinear_parameters *mparams = (const gsl_multifit_nlinear_parameters *) params;\n lm_state_t *state;\n \n state = calloc(1, sizeof(lm_state_t));\n if (state == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate lm state\", GSL_ENOMEM);\n }\n\n state->workp = gsl_vector_alloc(p);\n if (state->workp == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workp\", GSL_ENOMEM);\n }\n\n state->workn = gsl_vector_alloc(n);\n if (state->workn == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for workn\", GSL_ENOMEM);\n }\n\n state->fvv = gsl_vector_alloc(n);\n if (state->fvv == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for fvv\", GSL_ENOMEM);\n }\n\n state->vel = gsl_vector_alloc(p);\n if (state->vel == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for vel\", GSL_ENOMEM);\n }\n\n state->acc = gsl_vector_alloc(p);\n if (state->acc == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for acc\", GSL_ENOMEM);\n }\n\n state->n = n;\n state->p = p;\n state->params = *mparams;\n state->accel = accel;\n\n return state;\n}\n\nstatic void *\nlm_alloc_noaccel (const void * params, const size_t n, const size_t p)\n{\n return lm_alloc(0, params, n, p);\n}\n\nstatic void *\nlm_alloc_accel (const void * params, const size_t n, const size_t p)\n{\n return lm_alloc(1, params, n, p);\n}\n\nstatic void\nlm_free(void *vstate)\n{\n lm_state_t *state = (lm_state_t *) vstate;\n\n if (state->workp)\n gsl_vector_free(state->workp);\n\n if (state->workn)\n gsl_vector_free(state->workn);\n\n if (state->fvv)\n gsl_vector_free(state->fvv);\n\n if (state->vel)\n gsl_vector_free(state->vel);\n\n if (state->acc)\n gsl_vector_free(state->acc);\n\n free(state);\n}\n\n/*\nlm_init()\n Initialize LM solver\n\nInputs: vtrust_state - trust state\n vstate - workspace\n\nReturn: success/error\n*/\n\nstatic int\nlm_init(const void *vtrust_state, void *vstate)\n{\n const gsl_multifit_nlinear_trust_state *trust_state =\n (const gsl_multifit_nlinear_trust_state *) vtrust_state;\n lm_state_t *state = (lm_state_t *) vstate;\n\n gsl_vector_set_zero(state->vel);\n gsl_vector_set_zero(state->acc);\n\n *(trust_state->avratio) = 0.0;\n\n return GSL_SUCCESS;\n}\n\n/*\nlm_preloop()\n Initialize LM method for new Jacobian matrix\n*/\n\nstatic int\nlm_preloop(const void * vtrust_state, void * vstate)\n{\n int status;\n const gsl_multifit_nlinear_trust_state *trust_state =\n (const gsl_multifit_nlinear_trust_state *) vtrust_state;\n const gsl_multifit_nlinear_parameters *params = trust_state->params;\n\n (void)vstate;\n\n /* initialize linear least squares solver */\n status = (params->solver->init)(trust_state, trust_state->solver_state);\n if (status)\n return status;\n\n return GSL_SUCCESS;\n}\n\n/*\nlm_step()\n Calculate a new step vector by solving the linear\nleast squares system:\n\n[ J ] v = - [ f ]\n[ sqrt(mu) D ] [ 0 ]\n*/\n\nstatic int\nlm_step(const void * vtrust_state, const double delta,\n gsl_vector * dx, void * vstate)\n{\n int status;\n const gsl_multifit_nlinear_trust_state *trust_state =\n (const gsl_multifit_nlinear_trust_state *) vtrust_state;\n lm_state_t *state = (lm_state_t *) vstate;\n const gsl_multifit_nlinear_parameters *params = trust_state->params;\n const double mu = *(trust_state->mu);\n\n (void)delta;\n\n /* prepare the linear solver with current LM parameter mu */\n status = (params->solver->presolve)(mu, trust_state, trust_state->solver_state);\n if (status)\n return status;\n\n /*\n * solve: [ J ] v = - [ f ]\n * [ sqrt(mu)*D ] [ 0 ]\n */\n status = (params->solver->solve)(trust_state->f,\n state->vel,\n trust_state,\n trust_state->solver_state);\n if (status)\n return status;\n\n if (state->accel)\n {\n double anorm, vnorm;\n\n /* compute geodesic acceleration */\n status = gsl_multifit_nlinear_eval_fvv(params->h_fvv,\n trust_state->x,\n state->vel,\n trust_state->f,\n trust_state->J,\n trust_state->sqrt_wts,\n trust_state->fdf,\n state->fvv,\n state->workp);\n if (status)\n return status;\n\n /*\n * solve: [ J ] a = - [ fvv ]\n * [ sqrt(mu)*D ] [ 0 ]\n */\n status = (params->solver->solve)(state->fvv,\n state->acc,\n trust_state,\n trust_state->solver_state);\n if (status)\n return status;\n\n anorm = gsl_blas_dnrm2(state->acc);\n vnorm = gsl_blas_dnrm2(state->vel);\n\n /* store |a| / |v| */\n *(trust_state->avratio) = anorm / vnorm;\n }\n\n /* compute step dx = v + 1/2 a */\n scaled_addition(1.0, state->vel, 0.5, state->acc, dx);\n\n return GSL_SUCCESS;\n}\n\n/*\nlm_preduction()\n Compute predicted reduction using Eq 4.4 of More 1978\n*/\n\nstatic int\nlm_preduction(const void * vtrust_state, const gsl_vector * dx,\n double * pred, void * vstate)\n{\n const gsl_multifit_nlinear_trust_state *trust_state =\n (const gsl_multifit_nlinear_trust_state *) vtrust_state;\n lm_state_t *state = (lm_state_t *) vstate;\n const gsl_vector *diag = trust_state->diag;\n const gsl_vector *p = state->vel;\n const double norm_Dp = scaled_enorm(diag, p);\n const double normf = gsl_blas_dnrm2(trust_state->f);\n const double mu = *(trust_state->mu);\n double norm_Jp;\n double u, v;\n\n (void)dx;\n\n /* compute work = J*p */\n gsl_blas_dgemv(CblasNoTrans, 1.0, trust_state->J, p, 0.0, state->workn);\n\n /* compute ||J*p|| */\n norm_Jp = gsl_blas_dnrm2(state->workn);\n\n u = norm_Jp / normf;\n v = norm_Dp / normf;\n\n *pred = u * u + 2.0 * mu * v * v;\n\n return GSL_SUCCESS;\n}\n\nstatic const gsl_multifit_nlinear_trs lm_type =\n{\n \"levenberg-marquardt\",\n lm_alloc_noaccel,\n lm_init,\n lm_preloop,\n lm_step,\n lm_preduction,\n lm_free\n};\n\nconst gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_lm = &lm_type;\n\nstatic const gsl_multifit_nlinear_trs lmaccel_type =\n{\n \"levenberg-marquardt+accel\",\n lm_alloc_accel,\n lm_init,\n lm_preloop,\n lm_step,\n lm_preduction,\n lm_free\n};\n\nconst gsl_multifit_nlinear_trs *gsl_multifit_nlinear_trs_lmaccel = &lmaccel_type;\n", "meta": {"hexsha": "b76f0d9f6c9ae40d488ecce458039729268ad0b8", "size": 9448, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/lm.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/lm.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/lm.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.3855072464, "max_line_length": 100, "alphanum_fraction": 0.6380186283, "num_tokens": 2519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525098, "lm_q2_score": 0.4687906266262437, "lm_q1q2_score": 0.2689350601116076}} {"text": "/* movstat/apply.c\n *\n * Copyright (C) 2018 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\ngsl_movstat_apply_accum()\n Apply moving window statistic to input vector. This is a generalized\nroutine to handle window endpoints and apply a given accumulator to\nthe input vector.\n\nInputs: endtype - end point handling criteria\n x - input vector, size n\n accum - accumulator to apply moving window statistic\n accum_params - parameters to pass to accumulator\n y - output vector, size n\n z - second output vector (i.e. minmax), size n; can be NULL\n w - workspace\n\nNotes:\n1) It is allowed to have x = y for in-place moving statistics\n*/\n\nint\ngsl_movstat_apply_accum(const gsl_movstat_end_t endtype,\n const gsl_vector * x,\n const gsl_movstat_accum * accum,\n void * accum_params,\n gsl_vector * y,\n gsl_vector * z,\n gsl_movstat_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 if (z != NULL && x->size != z->size)\n {\n GSL_ERROR(\"input and output vectors must have same length\", GSL_EBADLEN);\n }\n else\n {\n const int n = (int) x->size;\n const int H = w->H; /* number of samples to left of current sample */\n const int J = w->J; /* number of samples to right of current sample */\n int i;\n double x1 = 0.0; /* pad values for data edges */\n double xN = 0.0;\n double result[2];\n\n /* initialize accumulator */\n (accum->init)(w->K, w->state);\n\n /* pad initial window if necessary */\n if (endtype != GSL_MOVSTAT_END_TRUNCATE)\n {\n if (endtype == GSL_MOVSTAT_END_PADZERO)\n {\n x1 = 0.0;\n xN = 0.0;\n }\n else if (endtype == GSL_MOVSTAT_END_PADVALUE)\n {\n x1 = gsl_vector_get(x, 0);\n xN = gsl_vector_get(x, n - 1);\n }\n\n /* pad initial windows with H values */\n for (i = 0; i < H; ++i)\n (accum->insert)(x1, w->state);\n }\n else if (accum->delete_oldest == NULL) /* FIXME XXX */\n {\n /* save last K - 1 samples of x for later (needed for in-place input/output) */\n int idx1 = GSL_MAX(n - J - H, 0);\n int idx2 = n - 1;\n\n for (i = idx1; i <= idx2; ++i)\n w->work[i - idx1] = gsl_vector_get(x, i);\n }\n\n /* process input vector and fill y(0:n - J - 1) */\n for (i = 0; i < n; ++i)\n {\n double xi = gsl_vector_get(x, i);\n int idx = i - J;\n\n (accum->insert)(xi, w->state);\n\n if (idx >= 0)\n {\n (accum->get)(accum_params, result, w->state);\n gsl_vector_set(y, idx, result[0]);\n\n if (z != NULL)\n gsl_vector_set(z, idx, result[1]);\n }\n }\n\n if (endtype == GSL_MOVSTAT_END_TRUNCATE)\n {\n /* need to fill y(n-J:n-1) using shrinking windows */\n int idx1 = GSL_MAX(n - J, 0);\n int idx2 = n - 1;\n\n if (accum->delete_oldest == NULL)\n {\n int wsize = n - GSL_MAX(n - J - H, 0); /* size of work array */\n\n for (i = idx1; i <= idx2; ++i)\n {\n int nsamp = n - GSL_MAX(i - H, 0); /* number of samples in this window */\n int j;\n\n (accum->init)(w->K, w->state);\n\n for (j = wsize - nsamp; j < wsize; ++j)\n (accum->insert)(w->work[j], w->state);\n\n /* yi = acc_get [ work(i:K-2) ] */\n (accum->get)(accum_params, result, w->state);\n gsl_vector_set(y, i, result[0]);\n\n if (z != NULL)\n gsl_vector_set(z, i, result[1]);\n }\n }\n else\n {\n for (i = idx1; i <= idx2; ++i)\n {\n if (i - H > 0)\n {\n /* delete oldest window sample as we move closer to edge */\n (accum->delete_oldest)(w->state);\n }\n\n /* yi = acc_get [ work(i:K-2) ] */\n (accum->get)(accum_params, result, w->state);\n gsl_vector_set(y, i, result[0]);\n\n if (z != NULL)\n gsl_vector_set(z, i, result[1]);\n }\n }\n }\n else\n {\n /* pad final windows and fill y(n-J:n-1) */\n for (i = 0; i < J; ++i)\n {\n int idx = n - J + i;\n\n (accum->insert)(xN, w->state);\n\n if (idx >= 0)\n {\n (accum->get)(accum_params, result, w->state);\n gsl_vector_set(y, idx, result[0]);\n\n if (z != NULL)\n gsl_vector_set(z, idx, result[1]);\n }\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_movstat_apply()\n Apply user-defined moving window function to input vector\n\nInputs: endtype - end point handling criteria\n F - user-defined function\n x - input vector, size n\n y - output vector, size n\n w - workspace\n*/\n\nint\ngsl_movstat_apply(const gsl_movstat_end_t endtype, const gsl_movstat_function * F,\n const gsl_vector * x, gsl_vector * y, gsl_movstat_workspace * w)\n{\n int status = gsl_movstat_apply_accum(endtype, x, gsl_movstat_accum_userfunc, (void *) F, y, NULL, w);\n return status;\n}\n", "meta": {"hexsha": "8ad56ebb9b37beca83f3523f71a37c3d6a1c8156", "size": 6601, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/movstat/apply.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/apply.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/apply.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": 31.2843601896, "max_line_length": 103, "alphanum_fraction": 0.5056809574, "num_tokens": 1645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736784074525096, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.26893506011160756}} {"text": "/*\n * Copyright (c) 2011-2018 The University of Tennessee and The University\n * of Tennessee Research Foundation. All rights\n * reserved.\n *\n * @precisions normal z -> s d c\n *\n */\n#include \n#include \n#include \n#include \n#include \"dplasma.h\"\n\n/*\n#define DEBUG_BUTTERFLY\n*/\n\n/* Forward declaration of kernels for the butterfly transformation */\nvoid BFT_zQTL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N,\n PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl,\n PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal );\n\nvoid BFT_zQBL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N,\n PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl,\n PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal );\nvoid BFT_zQTR_trans( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N,\n PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl,\n PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans );\nvoid BFT_zQTR( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N,\n PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl,\n PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans);\nvoid BFT_zQBR( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N,\n PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl,\n PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal );\n\nvoid RBMM_zTOP( int mb, int nb, int lda, int i_seg, int lvl, int N, int trans,\n PLASMA_Complex64_t *top, PLASMA_Complex64_t *btm,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_but_vec);\nvoid RBMM_zBTM( int mb, int nb, int lda, int i_seg, int lvl, int N, int trans,\n PLASMA_Complex64_t *top, PLASMA_Complex64_t *btm,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_but_vec);\n\n/* Bodies of kernels for the butterfly transformation */\n\nvoid BFT_zQTL( int mb, int nb, int lda, int i_seg, int j_seg, int lvl, int N,\n PLASMA_Complex64_t *tl, PLASMA_Complex64_t *bl,\n PLASMA_Complex64_t *tr, PLASMA_Complex64_t *br,\n PLASMA_Complex64_t *C, PLASMA_Complex64_t *U_before, PLASMA_Complex64_t *U_after, int bl_is_tr_trans, int is_diagonal )\n{\n int i, j;\n\n (void)lvl;\n (void)N;\n\n#if defined(DEBUG_BUTTERFLY)\n printf (\"BFT_zQTL(mb:%d, nb:%d, lda:%d, i_seg:%d, j_seg:%d, lvl:%d, N:%d, bl_is_tr_trans:%d, is_diagonal:%d)\\n\",\n mb, nb, lda, i_seg, j_seg, lvl, N, bl_is_tr_trans, is_diagonal);\n#endif\n\n if( bl_is_tr_trans ){\n for (j=0; ji ){ /* If the tile of the TL quarter is on the diagonal, then we need to take the transpose element for the tiles that came from TL and BR */\n C[j*lda+i] = si * ((tl[i*lda+j]-bl[j*lda+i]) + (tr[i*lda+j]-br[i*lda+j])) * rj;\n } else{\n C[j*lda+i] = si * ((tl[j*lda+i]-bl[j*lda+i]) + (tr[i*lda+j]-br[j*lda+i])) * rj;\n }\n#if defined(DEBUG_BUTTERFLY)\n printf (\"HE %lf %lf %lf %lf %lf %lf %lf\\n\",creal(C[j*lda+i]), creal(si), creal(tl[j*lda+i]), creal(bl[j*lda+i]), creal(tr[i*lda+j]), creal(br[j*lda+i]), creal(rj));\n#endif\n }\n }\n }else{\n for (j=0; j\n#elif defined HAVE_ATLAS_CBLAS_H\n #include \n#endif\n}\n\n\nnamespace nm { namespace math {\n\n/*\n * GEneral Matrix-Vector multiplication: based on dgemv.f from Netlib.\n *\n * This is an extremely inefficient algorithm. Recommend using ATLAS' version instead.\n *\n * Template parameters: LT -- long version of type T. Type T is the matrix dtype.\n */\ntemplate \ninline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const DType* alpha, const DType* A, const int lda,\n const DType* X, const int incX, const DType* beta, DType* Y, const int incY) {\n int lenX, lenY, i, j;\n int kx, ky, iy, jx, jy, ix;\n\n typename LongDType::type temp;\n\n // Test the input parameters\n if (Trans < 111 || Trans > 113) {\n rb_raise(rb_eArgError, \"GEMV: TransA must be CblasNoTrans, CblasTrans, or CblasConjTrans\");\n return false;\n } else if (lda < std::max(1, N)) {\n fprintf(stderr, \"GEMV: N = %d; got lda=%d\", N, lda);\n rb_raise(rb_eArgError, \"GEMV: Expected lda >= max(1, N)\");\n return false;\n } else if (incX == 0) {\n rb_raise(rb_eArgError, \"GEMV: Expected incX != 0\\n\");\n return false;\n } else if (incY == 0) {\n rb_raise(rb_eArgError, \"GEMV: Expected incY != 0\\n\");\n return false;\n }\n\n // Quick return if possible\n if (!M or !N or (*alpha == 0 and *beta == 1)) return true;\n\n if (Trans == CblasNoTrans) {\n lenX = N;\n lenY = M;\n } else {\n lenX = M;\n lenY = N;\n }\n\n if (incX > 0) kx = 0;\n else kx = (lenX - 1) * -incX;\n\n if (incY > 0) ky = 0;\n else ky = (lenY - 1) * -incY;\n\n // Start the operations. In this version, the elements of A are accessed sequentially with one pass through A.\n if (*beta != 1) {\n if (incY == 1) {\n if (*beta == 0) {\n for (i = 0; i < lenY; ++i) {\n Y[i] = 0;\n }\n } else {\n for (i = 0; i < lenY; ++i) {\n Y[i] *= *beta;\n }\n }\n } else {\n iy = ky;\n if (*beta == 0) {\n for (i = 0; i < lenY; ++i) {\n Y[iy] = 0;\n iy += incY;\n }\n } else {\n for (i = 0; i < lenY; ++i) {\n Y[iy] *= *beta;\n iy += incY;\n }\n }\n }\n }\n\n if (*alpha == 0) return false;\n\n if (Trans == CblasNoTrans) {\n\n // Form y := alpha*A*x + y.\n jx = kx;\n if (incY == 1) {\n for (j = 0; j < N; ++j) {\n if (X[jx] != 0) {\n temp = *alpha * X[jx];\n for (i = 0; i < M; ++i) {\n Y[i] += A[j+i*lda] * temp;\n }\n }\n jx += incX;\n }\n } else {\n for (j = 0; j < N; ++j) {\n if (X[jx] != 0) {\n temp = *alpha * X[jx];\n iy = ky;\n for (i = 0; i < M; ++i) {\n Y[iy] += A[j+i*lda] * temp;\n iy += incY;\n }\n }\n jx += incX;\n }\n }\n\n } else { // TODO: Check that indices are correct! They're switched for C.\n\n // Form y := alpha*A**DType*x + y.\n jy = ky;\n\n if (incX == 1) {\n for (j = 0; j < N; ++j) {\n temp = 0;\n for (i = 0; i < M; ++i) {\n temp += A[j+i*lda]*X[j];\n }\n Y[jy] += *alpha * temp;\n jy += incY;\n }\n } else {\n for (j = 0; j < N; ++j) {\n temp = 0;\n ix = kx;\n for (i = 0; i < M; ++i) {\n temp += A[j+i*lda] * X[ix];\n ix += incX;\n }\n\n Y[jy] += *alpha * temp;\n jy += incY;\n }\n }\n }\n\n return true;\n} // end of GEMV\n\n#if (defined(HAVE_CBLAS_H) || defined(HAVE_ATLAS_CBLAS_H))\ntemplate <>\ninline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const float* alpha, const float* A, const int lda,\n const float* X, const int incX, const float* beta, float* Y, const int incY) {\n cblas_sgemv(CblasRowMajor, Trans, M, N, *alpha, A, lda, X, incX, *beta, Y, incY);\n return true;\n}\n\ntemplate <>\ninline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const double* alpha, const double* A, const int lda,\n const double* X, const int incX, const double* beta, double* Y, const int incY) {\n cblas_dgemv(CblasRowMajor, Trans, M, N, *alpha, A, lda, X, incX, *beta, Y, incY);\n return true;\n}\n\ntemplate <>\ninline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const Complex64* alpha, const Complex64* A, const int lda,\n const Complex64* X, const int incX, const Complex64* beta, Complex64* Y, const int incY) {\n cblas_cgemv(CblasRowMajor, Trans, M, N, alpha, A, lda, X, incX, beta, Y, incY);\n return true;\n}\n\ntemplate <>\ninline bool gemv(const enum CBLAS_TRANSPOSE Trans, const int M, const int N, const Complex128* alpha, const Complex128* A, const int lda,\n const Complex128* X, const int incX, const Complex128* beta, Complex128* Y, const int incY) {\n cblas_zgemv(CblasRowMajor, Trans, M, N, alpha, A, lda, X, incX, beta, Y, incY);\n return true;\n}\n#endif\n\n}} // end of namespace nm::math\n\n#endif // GEMM_H\n", "meta": {"hexsha": "88d3f3c513b2a528f11fd8963e30bec1465d3cfa", "size": 6014, "ext": "h", "lang": "C", "max_stars_repo_path": "ext/nmatrix/math/gemv.h", "max_stars_repo_name": "cjfuller/nmatrix", "max_stars_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/nmatrix/math/gemv.h", "max_issues_repo_name": "cjfuller/nmatrix", "max_issues_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ext/nmatrix/math/gemv.h", "max_forks_repo_name": "cjfuller/nmatrix", "max_forks_repo_head_hexsha": "de9c8ea1d42da57b0a23ce1c2ab9614fa2a65e6d", "max_forks_repo_licenses": ["BSD-3-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.9720930233, "max_line_length": 137, "alphanum_fraction": 0.5555370801, "num_tokens": 1932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.4843800842769843, "lm_q1q2_score": 0.2685744505466304}} {"text": "#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/* don't check ranges in Matrix operations and make Matrix call inline */\n#define GSL_RANGE_CHECK_OFF\n//#define HAVE_INLINE\n\n#define FALSE 0\n#define TRUE 1\n\n#ifndef M_PI\n#define M_PI 3.141592653589793238462643383280 /* pi */\n#endif\n\n#define LN2PI 1.837877066409345339\n\n#define ODEdriver gsl_odeiv2_driver_alloc_y_new\n#define rkf45 gsl_odeiv2_step_rkf45\n#define rk8pd gsl_odeiv2_step_rk8pd\n#define rkck gsl_odeiv2_step_rkck\n#define rk2 gsl_odeiv2_step_rk2\n\n#define EOL -1\n \n#define max(A, B) ((A) > (B) ? (A) : (B))\n#define min(A, B) ((A) < (B) ? (A) : (B))\n#define MIN(A, B) ((A) < (B) ? (A) : (B))\n#define MAX(A, B) ((A) > (B) ? (A) : (B))\n#define V(x) (x)*(x)\n\n#define FIT_TIME_POINT(x) (x->mode == FIT)\n#define RECORD_TIME_POINT(x, u) (x->mode == OUTPUT || (x->mode == FIT && u == x->t[x->i]))\n#define NEXT_TIME_POINT(x) if (x->mode == FIT) x->i++\n#define RESET_TIME_POINT(x) x->i = 0\n\nenum {FIT, OUTPUT};\n \nenum {SUCCESS=0, FAIL=1, ERROR1=1, ERROR2, ERROR3, ERROR4, ERROR5, ERROR6,\n ERROR7, ERROR8, ERROR9, ERROR10};\n\ntypedef uint boolean;\n\n// for internal use\n// type of parameter\nenum {NOTUSED=0, DERIVED=21, FITTED=22, CONSTANT=23, AUXILLARY=24, INDIVIDUAL_CONSTANT=28};\n// whether a fitted or auxillary parameter has a hyperparameter associated with it\nenum {HYPER=26};\n// prior of a fitted parameter that does not have a hyperparameters\nenum {NOTAPPLICABLE=0, NORMAL=1, GAMMA=2, SICHI2=3, UNIFORM=4, PARETO=5,\n TRUNCNORMAL=6, EXPONENTIAL=7, BINOMIAL=8, POISSON=9, INVGAMMA=10, \n UNIFORM0=11, BETA=12, NORMALMEAN=13, CATEGORICAL=14, GEOMETRIC=15,\n USERDEFINED=16, AUXILLARY_HYPER=27, CIRCULAR=29};\n// number type of the parameter\nenum {REAL=17, INTEGER=18, CATEGORY=19, INT = INTEGER};\n// type of data\nenum {NOT_AVAILABLE=0, ABOVE_DETECTION=1, BELOW_DETECTION=2, MEASURED=3};\n\n// for use in model files\n// prior or type of the declared parameter\nenum {Normal =NORMAL, \n Gamma =GAMMA, \n Sichi2 =SICHI2, \n Uniform =UNIFORM,\n Circular =CIRCULAR,\n Pareto =PARETO, \n TruncNormal =TRUNCNORMAL, \n Exponential =EXPONENTIAL, \n Binomial =BINOMIAL, \n Poisson =POISSON, \n InvGamma =INVGAMMA, \n Uniform0 =UNIFORM0, \n Beta =BETA, \n NormalMean =NORMALMEAN,\n Categorical =CATEGORICAL, \n Geometric =GEOMETRIC, \n UserDefined =USERDEFINED, \n HyperP =HYPER, \n Constant =CONSTANT, \n Auxillary =AUXILLARY, \n Auxillary_Hyper =AUXILLARY_HYPER, \n Derived =DERIVED,\n Individual_Constant=INDIVIDUAL_CONSTANT}; \nenum {Nor =NORMAL, \t \n Gam \t =GAMMA, \t \n Sic \t =SICHI2, \t \n Unif \t =UNIFORM, \t \n Circ =CIRCULAR,\n Pare \t =PARETO, \t \n TNorm \t =TRUNCNORMAL, \n Exp \t =EXPONENTIAL, \n Bin \t =BINOMIAL, \t \n Poi \t =POISSON, \t \n IGam \t =INVGAMMA, \t \n Unif0 \t =UNIFORM0, \t \n Be \t =BETA, \t \n NorM \t =NORMALMEAN, \n Cat \t =CATEGORICAL, \n Geom \t =GEOMETRIC, \n UD \t =USERDEFINED, \n Hyp \t =HYPER, \t \n Cst \t =CONSTANT, \t \n Aux \t =AUXILLARY, \n Aux_Hyp =AUXILLARY_HYPER, \n Der\t =DERIVED,\n IndCst =INDIVIDUAL_CONSTANT}; \n\n// number type of the parameter\nenum {Real=REAL, Integer=INTEGER, Category=CATEGORY, Int=INTEGER};\n// type of data\nenum {NA=0, Above_Detection=1, Below_Detection=2, Measured=3};\n\ntypedef struct {\n uint mode, n, i;\n double *t;\n} TimePoints;\n\nstruct line {\n int n;\n double *x;\n double *y;\n double *m;\n double *c;\n};\n\nstruct data_individual {\n int n;\n int np;\n uint **value;\n double **Y;\n double saturated;\n};\n\nstruct data_treatment {\n int nind;\n int *usevar;\n char levels[1000];\n struct data_individual *Individual;\n};\n\nstruct data {\n int ntrt;\n int nvar;\n int maxnind;\n int maxnp;\n char filename[100];\n struct data_treatment *Treatment;\n};\n\ntypedef struct treatmentlist {\n int n;\n int *treatment;\n} Treatments;\n\ntypedef struct hyperblock {\n /* set in CreateBlock */\n int use;\n\n /* set in AddHyperToTreatment */\n int nhypers_used;\n int *hyper_used;\n int **nhypers_with_treatment;\n int ***hyper_with_treatment;\n int nassociated_pars;\n int *associated_par;\n int *ntreatments_with_parameter;\n int **treatment_with_parameter;\n\n /* set in Bayes */\n int hdistribution;\n int pdistribution;\n int *dependent_block;\n} Hyperblock;\n\nstruct hyper {\n int index;\n int use;\n int parno;\n int hdist;\n int number;\n char name[100];\n double location;\n double scale;\n double shape;\n};\n\ntypedef struct allhypers {\n int init;\n int ntrt;\n int *nind;\n int *trtused;\n int nhyper_parameters;\n struct hyper *H;\n int nblocks;\n Hyperblock *block;\n double *hyper; //used for initialisation of thread hyper values\n double **hyper_store;\n} Hyperparameters;\n\nstruct variable {\n int index;\n char name[100];\n};\n \nstruct variables {\n int variables;\n double scaletime;\n struct variable *W;\n};\n\nstruct parameter {\n int index;\n int number;\n int distribution;\n int circular;\n int type;\n int hashyper;\n int hyper_location_block_index;\n int hyper_shape_block_index;\n int hyper_scale_block_index;\n int ncategories;\n double *p; // used for categorical parameters\n double location;\n double scale;\n double shape;\n char name[100];\n double (*(*link))(double);\n};\n \nstruct blocks {\n int nblocks;\n int **pblock;\n};\n\nstruct parameterset {\n int pass;\n int parameters; // maximum parameter index\n int npar; // number of fitted parameters\n int ninteger;\n int *integer;\n int nauxillary;\n int *auxillary;\n struct parameter *P;\n struct blocks Blocks;\n};\n\nstruct parameter_block {\n int categorical;\n int done;\n int npar;\n int *pblock;\n int covfinal;\n int covstart;\n int inrange;\n int storeno;\n int error;\n double accept; /*mcmc acceptances*/\n double proposed; /*mcmc iterations*/\n double covscale; /*covariance matrix scaling factor*/\n // double **L; /*covariance matrix*/\n gsl_matrix *L;\n double **theta_store;\n};\n\nstruct chain {\n int done; /*if current individual is ready for next phase*/\n int loop;\n /* parameters for threads */\n double logmaxL;\n double logL;\n double *logP;\n double logpost;\n double *theta; /*current parameter values*/\n double minlogL;\n double prop_logL;\n double prop_logP;\n double prop_logpost;\n int storeno;\n int laststoreno;\n double accept; /*mcmc acceptances*/\n double proposed; /*mcmc iterations*/\n double **theta_store;\n double *logLstore;\n double *logpoststore;\n double exchangeaccept; /*mcmc acceptances*/\n double exchangeproposed; /*mcmc iterations*/\n struct parameter_block *PB;\n};\n\nstruct sim_individual {\n int done;\n int chains;\n int *chainno;\n double *temp;\n struct chain *Chain;\n struct parameterset Q;\n};\n\ntypedef struct {\n int n;\n int m;\n int **a;\n} Matrix;\n\nstruct sim_treatment {\n struct sim_individual *Individual;\n};\n\nstruct thread {\n double *hyper;\n struct sim_treatment *Treatment;\n gsl_rng *stream;\n};\n\ntypedef struct simulation {\n Hyperparameters HP;\n int *trtused;\n int **indused;\n int ntp; // individual with most parameters\n int nrp; // individual with most parameters\n int rdp;\n int sim;\n int maxc;\n int seed;\n int thin;\n int mcmc;\n int popd;\n int marg;\n int maxnp;\n int error;\n int range;\n int chains;\n int notime;\n int copyind;\n int threads;\n int verbose; /* 0: no output, 1: output chain 0+lowest exchangerate, \n\t\t 2: all chains*/\n int derived;\n int discard;\n int samples;\n int storeno;\n int gsl_error;\n int population;\n int covsamples;\n int growthcurves;\n int parsperblock;\n int phase1adjust;\n int phase2adjust;\n int mincovsamples;\n int ignorewarning;\n int usehypermeans;\n int sample_parameters;\n char expno[50];\n char outexpno[50];\n char *parsfile;\n char *tempfile;\n char logfile[1000];\n char factors[1000];\n double xrate;\n double timeend;\n double lowrate;\n double highrate;\n double minprior;\n double initscale;\n double covthresh;\n double timestart;\n double scalefactor;\n double saturatedlogL;\n double minexchangerate;\n struct sim_individual Sample;\n struct sim_treatment *Treatment;\n struct variables V;\n} Simulation;\n\nextern char expno[];\n\nextern int* integervector( int );\nextern uint* uintegervector( int );\nextern uint** uintegermatrix( int, int );\nextern double* doublevector( int );\nextern double** doublematrix( int, int );\nextern double*** doublematrix3( int, int, int );\nextern double**** doublematrix4( int, int, int, int );\nextern char* charvector( int );\nextern char** charmatrix( int, int );\nextern double factln( int );\nextern double gammln( double );\nextern void binorm( double*, double, double, double, double, double );\nextern long int lrint(double);\nextern double pow10(double);\nextern double round(double);\nextern double rtnewt(void(*)(double, double*, double*, double*), \n\t\t double, double, double, double*);\nextern double rtbis( double (*)(double, double*), double, double, \n\t\t double, int*, double*);\n\nextern void *malloc(size_t);\nextern void exit(int);\nextern void free(void*);\nextern void Error(char*);\nextern void ReadParam( char*, void*, char* ) ;\n\nextern uint binomialRNG(uint, double, const gsl_rng*);\nextern void multinomialRNG(uint, const double*, size_t, unsigned int*, const gsl_rng*);\nextern int poissonRNG(double, const gsl_rng*);\nextern int uniform_intRNG(int, int, const gsl_rng*);\nextern double normalRNG(double, double, const gsl_rng*);\nextern double betaRNG(double, double, const gsl_rng*);\nextern double chisqRNG(double, const gsl_rng*);\nextern double scaleinvchisqRNG(double, double, const gsl_rng*);\nextern double invgammaRNG(double, double, const gsl_rng*);\nextern double gammaRNG(double, double, const gsl_rng*);\nextern double uniformRNG(double, double, const gsl_rng*);\nextern double paretoRNG(double, double, const gsl_rng*);\nextern void dirichlet_multinomialRNG(uint, const double*, size_t, uint*, const gsl_rng*);\nextern void dirichletRNG(const double*, size_t, double*, const gsl_rng*);\nextern uint beta_binomialRNG(uint, double, double, const gsl_rng*);\nextern uint negative_binomialRNG(double, double, const gsl_rng*);\nextern uint beta_negative_binomialRNG(uint, double, double, const gsl_rng*);\n/* Matrix *wishartRNG(int, int, Matrix*, Matrix*, const gsl_rng*); */\n/* void MVNRNG(int, Matrix*, Matrix*, Matrix*, const gsl_rng*); */\n\nextern double poissonCMF(const double, const double, int);\nextern double gamma_scalePDF(const double, const double, const double);\nextern double betaPDF(const double, const double, const double);\nextern double exponentialPDF(const double, const double);\nextern double poissonPMF(const double, const double);\nextern double geometricPDF(const double, const double);\nextern double trnormalPDF(const double, const double, const double);\nextern double normalCDF(const double, const double, const double, int);\nextern double normalPDF(const double, const double, const double);\nextern double binomialPMF(const double, const double, const double);\nextern double multinomialPMF(const unsigned int, const double*, const double*);\nextern double uniformPDF(const double, const double, const double);\nextern double logisticPDF(const double, const double, const double);\nextern double betabinomialPMF(const double, const double, const double, const double);\n//extern double MVNPDF(Matrix*, Matrix*, Matrix*, const double, int);\nextern double von_mises_cdf ( double x, double a, double b );\nextern double von_mises_cdf_inv ( double cdf, double a, double b );\n\nextern Matrix *MatrixInit(Matrix*, int, int, int*);\nextern Matrix *MatrixDestroy(Matrix*);\nextern double identity(double);\nextern double logit(double);\nextern double invlogit(double);\n\nint function(int, int, double*, double*, double*, TimePoints*);\nint Model(const uint, const uint, const uint, double*, double**,\n\t TimePoints*);\n//int Model(int, int, int, double*, double**);\nvoid Block(struct parameterset*, int, ...);\nvoid Par(struct parameterset*, int, int, char*, int, ...);\nvoid Create(Hyperparameters *H, int *h, int block, int par,\n\t Matrix M, char *name, int type, double p1, double p2);\nvoid Hyper(Hyperparameters *HP, int index, int number, char *name, int distribution,\n\t double shape_or_loc, double scale);\nvoid CreateHyperBlock(Hyperparameters *HP, int index);\nvoid AddHyperToATreatment(Hyperparameters *HP, int index, int h, int pindex,\n\t\t\t int treatment);\nvoid AddHyperToTreatments(Hyperparameters *HP, int index, int h, int pindex, ...);\nvoid HyperParameters(Treatments, Hyperparameters*);\nvoid Var(struct variables*, int, char*); \nvoid GlobalParameters(void);\nvoid Variables(struct variables*);\nvoid OutputModel(int, int, double*, double*);\nvoid OutputData(int, int, double*, double*, double*, uint*);\nvoid DerivedHyperParameters(int trt, double *p);\nvoid DerivedParameters(int, int, int, double*, double**, TimePoints*);\nvoid Parameters(int, int, double*, struct parameterset*); \nvoid PredictData(int, int, double*, double*, double*, gsl_rng*);\nvoid SimulateData(int, int, double*, double*, double*, double*, uint*, gsl_rng*);\nvoid SaturatedModel(int, int, double*, double*, double*, uint*); \nvoid Residual(int, int, double*, double*, double*, double*, uint*);\nvoid Equations(double*, double*, int, double*, double*, int, double);\ndouble timestep(void);\ndouble logLikelihood(const uint, const uint, const double*,\n\t\t const double*, const double*, const uint*);\ndouble logLikelihoodI(const uint trt, const uint ind, const double *p, \n\t\t double **V, double *Data, const uint *value,\n\t\t const uint N);\nvoid WAIC(int trt, int ind, double *lnL, double *V,\n\t double *p, double *Data, uint *value);\n//double logLikelihood(int, int, double*, double*, double*, int*);\ndouble UserPDF(double);\nvoid ScaleTime(struct variables*, double);\n", "meta": {"hexsha": "9e2538924837c4f6a2953ba18679ed23ce68dee0", "size": 14301, "ext": "h", "lang": "C", "max_stars_repo_path": "model.h", "max_stars_repo_name": "nicksavill/bayesian-dynamical-model-inference", "max_stars_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "model.h", "max_issues_repo_name": "nicksavill/bayesian-dynamical-model-inference", "max_issues_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "model.h", "max_forks_repo_name": "nicksavill/bayesian-dynamical-model-inference", "max_forks_repo_head_hexsha": "24418e397cca4ffa9b17d1d17b1ff59f3f49c87c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0081135903, "max_line_length": 91, "alphanum_fraction": 0.6835186351, "num_tokens": 3945, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6654105454764747, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.26853764028028027}} {"text": "/*\n * vbHmmTsFret.c\n * Model-specific core functions for VB-HMM-TS.\n *\n * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN\n * Copyright 2011-2015\n * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.\n * All rights reserved.\n *\n * Ver. 1.1.0\n * Last modified on 2015.09.17\n */\n\n#include \"vbHmmTsFret.h\"\n#include \n#include \n#include \n#include \"rand.h\"\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n//// Uncomment one/both of the following defenitions to activate constraint on I or/and K.\n//#define INTENSITY_CAP\n//#define TRANSITION_RATE_CAP\n#ifdef INTENSITY_CAP\n#define maxIntensityRatio 10.0\n#endif\n#ifdef TRANSITION_RATE_CAP\n#define minPhotonNumPerState 10.0\n#endif\n\n#define MAX(a,b) ((a)>(b)?(a):(b))\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\n\n//static int isGlobalAnalysis = 0;\n\nvoid setFunctions_tsFret(){\n commonFunctions funcs;\n funcs.newModelParameters = newModelParameters_tsFret;\n funcs.freeModelParameters = freeModelParameters_tsFret;\n funcs.newModelStats = newModelStats_tsFret;\n funcs.freeModelStats = freeModelStats_tsFret;\n funcs.initializeVbHmm = initializeVbHmm_tsFret;\n funcs.pTilde_z1 = pTilde_z1_tsFret;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1_tsFret;\n funcs.pTilde_xn_zn = pTilde_xn_zn_tsFret;\n funcs.calcStatsVars = calcStatsVars_tsFret;\n funcs.maximization = maximization_tsFret;\n funcs.varLowerBound = varLowerBound_tsFret;\n funcs.reorderParameters = reorderParameters_tsFret;\n funcs.outputResults = outputResults_tsFret;\n setFunctions( funcs );\n}\n\n//void setGFunctions_tsFret(){\n// gCommonFunctions funcs;\n// funcs.newModelParameters = newModelParameters_tsFret;\n// funcs.freeModelParameters = freeModelParameters_tsFret;\n// funcs.newModelStats = newModelStats_tsFret;\n// funcs.freeModelStats = freeModelStats_tsFret;\n// funcs.newModelStatsG = newModelStatsG_tsFret;\n// funcs.freeModelStatsG = freeModelStatsG_tsFret;\n// funcs.initializeVbHmmG = initializeVbHmmG_tsFret;\n// funcs.pTilde_z1 = pTilde_z1_tsFret;\n// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_tsFret;\n// funcs.pTilde_xn_zn = pTilde_xn_zn_tsFret;\n// funcs.calcStatsVarsG = calcStatsVarsG_tsFret;\n// funcs.maximizationG = maximizationG_tsFret;\n// funcs.varLowerBoundG = varLowerBoundG_tsFret;\n// funcs.reorderParametersG = reorderParametersG_tsFret;\n// funcs.outputResultsG = outputResultsG_tsFret;\n// setGFunctions( funcs );\n// isGlobalAnalysis = 1;\n//}\n\n\nvoid outputResults_tsFret( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n outputTsFretResults( xn, gv, iv, logFP );\n}\n\n//void outputResultsG_tsFret( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n// outputTsFretResultsG( xns, gv, ivs, logFP );\n//}\n\n\nvoid *newModelParameters_tsFret( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n int i;\n tsFretParameters *p = (void*)malloc( sizeof(tsFretParameters) );\n \n p->uPiArr = (double*)malloc( sNo * sizeof(double) );\n p->sumUPi = 0.0;\n // hyperparameter for p( k(i,j) ) (i != j)\n p->uKMat = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->uKMat[i] = (double*)malloc( sNo * sizeof(double) );\n }\n p->sumUKArr = (double*)malloc( sNo * sizeof(double) );\n // hyperparameter for p( I(k) )\n p->aIArr = (double*)malloc( sNo * sizeof(double) );\n p->bIArr = (double*)malloc( sNo * sizeof(double) );\n // hyperparameter for p( E(i) )\n p->uEArr = (double*)malloc( sNo * sizeof(double) );\n p->vEArr = (double*)malloc( sNo * sizeof(double) );\n \n // parameters\n p->avgPi = (double *)malloc( sNo * sizeof(double) );\n p->avgLnPi = (double *)malloc( sNo * sizeof(double) );\n p->avgI = (double *)malloc( sNo * sizeof(double) );\n p->avgLnI = (double *)malloc( sNo * sizeof(double) );\n p->avgK = (double **)malloc( sNo * sizeof(double*) );\n p->avgLnK = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->avgK[i] = (double *)malloc( sNo * sizeof(double) );\n p->avgLnK[i] = (double *)malloc( sNo * sizeof(double) );\n }\n p->avgLnKI = (double *)malloc( sNo * sizeof(double) );\n p->avgE = (double *)malloc( sNo * sizeof(double) );\n p->avgLnE = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { p->avgLnE[i] = (double *)malloc( 2 * sizeof(double) ); }\n \n return p;\n}\n\nvoid freeModelParameters_tsFret( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n tsFretParameters *gp = *p;\n int i;\n \n free( gp->uPiArr );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->uKMat[i] );\n }\n free( gp->uKMat );\n free( gp->sumUKArr );\n free( gp->aIArr );\n free( gp->bIArr );\n free( gp->uEArr );\n free( gp->vEArr );\n \n free( gp->avgPi );\n free( gp->avgLnPi );\n free( gp->avgI );\n free( gp->avgLnI );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->avgK[i] );\n free( gp->avgLnK[i] );\n }\n free( gp->avgK );\n free( gp->avgLnK );\n free( gp->avgLnKI );\n free( gp->avgE );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->avgLnE[i] );\n }\n free( gp->avgLnE );\n\n free( *p );\n *p = NULL;\n}\n\n\nvoid *newModelStats_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n tsFretStats *s = (tsFretStats*)malloc( sizeof(tsFretStats) );\n \n int i;\n s->Ni = (double *)malloc( sNo * sizeof(double) );\n s->Ti = (double *)malloc( sNo * sizeof(double) );\n s->Nii = (double *)malloc( sNo * sizeof(double) );\n s->Nij = (double *)malloc( sNo * sizeof(double) );\n s->Mij = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s->Mij[i] = (double *)malloc( sNo * sizeof(double) ); }\n s->eps = (double *)malloc( sNo * sizeof(double) );\n\n return s;\n \n// } else {\n//\n// return NULL;\n//\n// }\n}\n\nvoid freeModelStats_tsFret( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n tsFretStats *gs = *s;\n int i;\n free( gs->Ni );\n free( gs->Ti );\n free( gs->Nii );\n free( gs->Nij );\n for( i = 0 ; i < sNo ; i++ )\n { free( gs->Mij[i] ); }\n free( gs->Mij );\n free( gs->eps );\n\n free( gs );\n *s = NULL;\n// }\n}\n\n//void *newModelStatsG_tsFret( xns, gv, ivs)\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// int sNo = gv->sNo;\n// tsGlobalStats *gs = (tsGlobalStats*)malloc( sizeof(tsGlobalStats) );\n//\n// return gs;\n//}\n\n//void freeModelStatsG_tsFret( gs, xns, gv, ivs )\n//void **gs;\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//\n// free( *gs );\n// *gs = NULL;\n//}\n\n\nvoid initializeVbHmm_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsFretData *d = xn->data;\n int sNo = gv->sNo;\n tsFretParameters *p = gv->params;\n int i, j;\n \n\n // hyperparameter for p( pi(i) )\n p->sumUPi = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n p->uPiArr[i] = 1.0;\n p->sumUPi += p->uPiArr[i];\n }\n\n // hyperparameter for p( k(i,j) ) (i != j)\n for( i = 0 ; i < sNo ; i++ ){\n p->uKMat[i] = (double*)malloc( sNo * sizeof(double) );\n p->sumUKArr[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n p->uKMat[i][j] = 1.0;\n if( j != i ){\n p->sumUKArr[i] += p->uKMat[i][j];\n }\n }\n }\n\n double meanI = (double)xn->N / d->T;\n\n // hyperparameter for p( I(k) )\n for( i = 0 ; i < sNo ; i++ ){\n p->aIArr[i] = 1.0;\n p->bIArr[i] = 1.0 / meanI;\n }\n\n // hyperparameter for p( E(i) )\n for( i = 0 ; i < sNo ; i++ ){\n p->uEArr[i] = 1.0;\n p->vEArr[i] = 1.0;\n }\n\n initialize_indVars_tsFret( xn, gv, iv );\n \n calcStatsVars_tsFret( xn, gv, iv );\n maximization_tsFret( xn, gv, iv );\n}\n\n//void initializeVbHmmG_tsFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid initialize_indVars_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n \n int i;\n size_t n;\n double sumPar;\n for( n = 0 ; n < dLen ; n++ ){\n sumPar = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] = enoise(1.0) + 1.0;\n sumPar += gmMat[n][i];\n }\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] /= sumPar;\n }\n }\n}\n\n\nxnDataSet *newXnDataSet_tsFret( filename )\nconst char *filename;\n{\n xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );\n xn->name = (char*)malloc( strlen(filename) + 2 );\n strncpy( xn->name, filename, strlen(filename)+1 );\n xn->data = (tsFretData*)malloc( sizeof(tsFretData) );\n tsFretData *d = (tsFretData*)xn->data;\n d->T = 0.0;\n d->dt = NULL;\n d->time = NULL;\n d->ch = NULL;\n return xn;\n}\n\nvoid freeXnDataSet_tsFret( xn )\nxnDataSet **xn;\n{\n tsFretData *d = (tsFretData*)(*xn)->data;\n free( d->dt );\n free( d->time );\n free( d->ch );\n free( (*xn)->data );\n free( (*xn)->name );\n free( *xn );\n *xn = NULL;\n}\n\n\ndouble pTilde_z1_tsFret( i, params )\nint i;\nvoid *params;\n{\n tsFretParameters *p = (tsFretParameters*)params;\n return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1_tsFret( i, j, params )\nint i, j;\nvoid *params;\n{\n tsFretParameters *p = (tsFretParameters*)params;\n if( i == j ){\n return exp( p->avgLnI[i] - p->avgLnKI[i] );\n } else {\n return exp( p->avgLnK[i][i] + p->avgLnK[i][j] - p->avgLnKI[i] );\n }\n}\n\ndouble pTilde_xn_zn_tsFret( xn, n, i, params )\nxnDataSet *xn;\nsize_t n;\nint i;\nvoid *params;\n{\n tsFretParameters *p = (tsFretParameters*)params;\n tsFretData *d = (tsFretData*)xn->data;\n return exp( p->avgLnI[i] - (p->avgI[i] * d->dt[n]) + p->avgLnE[i][d->ch[n]] );\n}\n\n\n\nvoid calcStatsVars_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsFretData *d = (tsFretData*)xn->data;\n tsFretStats *s = (tsFretStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;\n double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;\n size_t n;\n int i, j;\n \n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] = 1e-10;\n Ti[i] = 1e-10;\n eps[i] = 1e-10;\n Nii[i] = 0.0;\n Nij[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n Mij[i][j] = 1e-10;\n }\n }\n for( n = 0 ; n < dLen ; n++ ){\n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] += gmMat[n][i];\n Ti[i] += gmMat[n][i] * d->dt[n];\n eps[i] += gmMat[n][i] * d->ch[n];\n Nii[i] += xiMat[n][i][i];\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n Mij[i][j] += xiMat[n][i][j];\n Nij[i] += xiMat[n][i][j];\n }\n }\n }\n }\n for( i = 0 ; i < sNo ; i++ ){\n Nii[i] = MAX( Nii[i], 1.0 );\n Nij[i] = MAX( Nij[i], 1.0 );\n }\n}\n\n//void calcStatsVarsG_tsFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\n\n\nvoid maximization_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsFretParameters *p = (tsFretParameters*)gv->params;\n tsFretStats *s = (tsFretStats*)iv->stats;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK, **avgLnK = p->avgLnK;\n double *avgLnKI = p->avgLnKI, *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *avgE = p->avgE, **avgLnE = p->avgLnE;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;\n double *uEArr = p->uEArr, *vEArr = p->vEArr;\n double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;\n double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;\n int i, j;\n\n for( i = 0 ; i < sNo ; i++ ){\n avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );\n avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );\n\n avgK[i][i] = (Ni[i] + aIArr[i]) * Nij[i] / (Nii[i] - 1.0) / (Ti[i] + bIArr[i]);\n avgLnK[i][i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nij[i]);\n avgLnK[i][i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);\n \n avgI[i] = (Ni[i] + aIArr[i]) / (Ti[i] + bIArr[i]);\n avgLnI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) - log(Ti[i] + bIArr[i]);\n \n avgLnKI[i] = gsl_sf_psi(Ni[i] + aIArr[i]) + gsl_sf_psi(Nii[i] + Nij[i]);\n avgLnKI[i] += -gsl_sf_psi(Nii[i]) - log(Ti[i] + bIArr[i]);\n\n#ifdef INTENSITY_CAP\n double meanI = (double)xnWv->N / xnWv->T;\n avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );\n avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );\n#endif\n#ifdef TRANSITION_RATE_CAP\n avgK[i][i] = MIN( avgK[i][i], avgI[i]/minPhotonNumPerState );\n avgLnK[i][i] = MIN( avgLnK[i][i], avgLnI[i] - log(minPhotonNumPerState) );\n avgLnKI[i] = MIN( avgLnKI[i], avgLnI[i] + log(1.0 + 1.0/minPhotonNumPerState) );\n#endif\n \n for( j = 0 ; j < sNo ; j++ ){\n if( i != j ){\n avgK[i][j] = ( uKMat[i][j] + Mij[i][j] ) / ( sumUKArr[i] + Nij[i] );\n avgLnK[i][j] = gsl_sf_psi( uKMat[i][j] + Mij[i][j] ) - gsl_sf_psi( sumUKArr[i] + Nij[i] );\n }\n }\n\n avgE[i] = ( uEArr[i] + eps[i] ) / ( uEArr[i] + vEArr[i] + Ni[i] );\n avgLnE[i][0] = gsl_sf_psi( vEArr[i] + Ni[i] - eps[i] ); // ln(1-E) for donor\n avgLnE[i][0] -= gsl_sf_psi( uEArr[i] + vEArr[i] + Ni[i] );\n avgLnE[i][1] = gsl_sf_psi( uEArr[i] + eps[i] ); // ln(E) for acceptor\n avgLnE[i][1] -= gsl_sf_psi( uEArr[i] + vEArr[i] + Ni[i] );\n }\n}\n\n//void maximizationG_tsFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\n\n\ndouble varLowerBound_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsFretParameters *p = (tsFretParameters*)gv->params;\n tsFretStats *s = (tsFretStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, *cn = iv->cn;\n double *avgLnPi = p->avgLnPi, **avgLnK = p->avgLnK, *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *avgLnKI = p->avgLnKI, **avgLnE = p->avgLnE;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uKMat = p->uKMat, *sumUKArr = p->sumUKArr;\n double *uEArr = p->uEArr, *vEArr = p->vEArr;\n double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;\n double *Nii = s->Nii, *Nij = s->Nij, **Mij = s->Mij;\n size_t n;\n int i, j;\n\n double lnpPi = gsl_sf_lngamma(sumUPi);\n double Ck = 1.0, lnpKii = sNo * log(Ck);\n double lnpKij = 0.0;\n double lnpI = 0.0;\n double lnpE = 0.0;\n double lnqPi = gsl_sf_lngamma(sumUPi + 1);\n double lnqKiiI = 0.0;\n double lnqKij = 0.0;\n double lnqE = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n\n lnpKii -= avgLnK[i][i];\n\n lnpI += aIArr[i] * log(bIArr[i]) - gsl_sf_lngamma(aIArr[i]);\n lnpI += (aIArr[i]-1.0)*avgLnI[i] - bIArr[i]*avgI[i];\n\n lnpE += gsl_sf_lngamma(uEArr[i]+vEArr[i]) - gsl_sf_lngamma(uEArr[i]);\n lnpE += -gsl_sf_lngamma(vEArr[i]);\n lnpE += (uEArr[i]-1.0)*avgLnE[i][1] + (vEArr[i]-1.0)*avgLnE[i][0];\n\n lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));\n lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);\n\n lnqKiiI += gsl_sf_lngamma(Nii[i] + Nij[i]) + (Ni[i] + aIArr[i]) * log(Ti[i] + bIArr[i]);\n lnqKiiI += -gsl_sf_lngamma(Ni[i] + aIArr[i]) -gsl_sf_lngamma(Nii[i]);\n lnqKiiI += -gsl_sf_lngamma(Nij[i]) + (Nij[i]-1.0)*avgLnK[i][i];\n lnqKiiI += (Ni[i] + Nii[i] + aIArr[i] - 1.0)*avgLnI[i];\n lnqKiiI += -(Nii[i] + Nij[i])*avgLnKI[i] - (Ti[i] + bIArr[i])*avgI[i];\n \n lnqE += gsl_sf_lngamma(uEArr[i] + vEArr[i] + Ni[i]);\n lnqE -= gsl_sf_lngamma(uEArr[i] + eps[i]);\n lnqE -= gsl_sf_lngamma(vEArr[i] + Ni[i] - eps[i]);\n lnqE += (uEArr[i] + eps[i] - 1.0)*avgLnE[i][1];\n lnqE += (vEArr[i] + Ni[i] - eps[i] - 1.0)*avgLnE[i][0];\n\n lnpKij += gsl_sf_lngamma(sumUKArr[i]);\n lnqKij += gsl_sf_lngamma(sumUKArr[i] + Nij[i]);\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n lnpKij += (uKMat[i][j]-1.0)*avgLnK[i][j] - gsl_sf_lngamma(uKMat[i][j]);\n lnqKij += (uKMat[i][j]+Mij[i][j]-1)*(gsl_sf_psi(uKMat[i][j]+Mij[i][j])-gsl_sf_psi(sumUKArr[i]+Nij[i]));\n lnqKij -= gsl_sf_lngamma( uKMat[i][j] + Mij[i][j] );\n }\n }\n }\n\n double lnpX = 0.0;\n for( n = 0 ; n < dLen ; n++ ){\n lnpX += log( cn[n] );\n }\n\n double val;\n val = lnpPi + lnpKii + lnpKij + lnpI + lnpE;\n val -= lnqPi + lnqKiiI + lnqKij + lnqE;\n val += lnpX;\n \n return val;\n}\n\n//double varLowerBoundG_tsFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\n\n\nvoid reorderParameters_tsFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n tsFretParameters *p = (tsFretParameters*)gv->params;\n tsFretStats *s = (tsFretStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgK = p->avgK;\n double **avgLnK = p->avgLnK, *avgLnKI = p->avgLnKI;\n double *avgI = p->avgI, *avgLnI = p->avgLnI, *avgE = p->avgE, **avgLnE = p->avgLnE;\n double *Ni = s->Ni, *Ti = s->Ti, *eps = s->eps;\n size_t n;\n int i, j;\n\n int *index = (int*)malloc( sNo * sizeof(int) );\n double *store = (double*)malloc( sNo * sizeof(double) );\n double **s2D = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s2D[i] = (double*)malloc( MAX(sNo,2) * sizeof(double) ); }\n\n // index indicates order of avgE values (0=biggest avgE -- sNo=smallest avgE).\n for( i = 0 ; i < sNo ; i++ ){\n index[i] = sNo - 1;\n for( j = 0 ; j < sNo ; j++ ){\n if( j != i ){\n if( avgE[i] < avgE[j] ){\n index[i]--;\n } else if( avgE[i] == avgE[j] ){\n if( j > i )\n { index[i]--; }\n }\n }\n }\n }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgPi[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnPi[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnPi[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgI[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgI[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnI[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnI[i] = store[i]; }\n\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgK[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgK[i][j] = s2D[i][j]; }\n }\n\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = avgLnK[i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ avgLnK[i][j] = s2D[i][j]; }\n }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgLnKI[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgLnKI[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = avgE[i]; }\n for( i = 0 ; i < sNo ; i++ ){ avgE[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ )\n { s2D[index[i]][0] = avgLnE[i][0];\n s2D[index[i]][1] = avgLnE[i][1]; }\n for( i = 0 ; i < sNo ; i++ )\n { avgLnE[i][0] = s2D[i][0];\n avgLnE[i][1] = s2D[i][1]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ni[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ni[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ti[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ti[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = eps[i]; }\n for( i = 0 ; i < sNo ; i++ ){ eps[i] = store[i]; }\n\n for( n = 0 ; n < dLen ; n++ ){\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = gmMat[n][i]; }\n for( i = 0 ; i < sNo ; i++ ){ gmMat[n][i] = store[i]; }\n }\n\n for( n = 0 ; n < dLen ; n++ ){\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ s2D[index[i]][index[j]] = xiMat[n][i][j]; }\n }\n for( j = 0 ; j < sNo ; j++ ){\n for( i = 0 ; i < sNo ; i++ ){ xiMat[n][i][j] = s2D[i][j]; }\n }\n }\n\n for( i = 0 ; i < sNo ; i++ ){ free( s2D[i] ); }\n free( s2D );\n free( store );\n free( index );\n}\n\n//void reorderParametersG_tsFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\n\n\nvoid outputTsFretResults( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n tsFretParameters *p = (tsFretParameters*)gv->params;\n int sNo = gv->sNo;\n int i, j;\n\n fprintf(logFP, \" results: K = %d \\n\", sNo);\n\n fprintf(logFP, \" intensities: ( %g\", p->avgI[0]);\n for( i = 1 ; i < sNo ; i++ )\n { fprintf(logFP, \", %g\", p->avgI[i]); }\n fprintf(logFP, \" ) \\n\");\n\n fprintf(logFP, \" FRET efficiencies: ( %g\", p->avgE[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgE[i]);\n }\n fprintf(logFP, \" ) \\n\");\n\n fprintf(logFP, \" pi: ( %g\", p->avgPi[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgPi[i]);\n }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" k_matrix: [\");\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(logFP, \" ( %g\", p->avgK[i][0]);\n for( j = 1 ; j < sNo ; j++ )\n { fprintf(logFP, \", %g\", p->avgK[i][j]); }\n fprintf(logFP, \")\");\n }\n fprintf(logFP, \" ] \\n\\n\");\n\n char fn[256];\n FILE *fp;\n size_t n;\n\n sprintf( fn, \"%s.param%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n fprintf(fp, \"I, E, pi\");\n for( i = 0 ; i < sNo ; i++ )\n { fprintf(fp, \", K%dx\", i); }\n fprintf(fp, \"\\n\");\n\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(fp, \"%g, %g, %g\", p->avgI[i], p->avgE[i], p->avgPi[i]);\n for( j = 0 ; j < sNo ; j++ )\n { fprintf(fp, \", %g\", p->avgK[j][i]); }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n\n sprintf( fn, \"%s.Lq%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < gv->iteration ; n++ ){\n fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n }\n fclose(fp);\n }\n\n sprintf( fn, \"%s.maxS%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < xn->N ; n++ ){\n fprintf( fp, \"%d\\n\", iv->stateTraj[n] );\n }\n fclose(fp);\n }\n}\n\n//void outputTsFretResultsG( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n//}\n\n//\n", "meta": {"hexsha": "2e8dec02c34c872ee02df3f61995a2e54d96f4b5", "size": 23738, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmmTsFret.c", "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_issues_repo_path": "C/vbHmmTsFret.c", "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_licenses": ["MIT"], "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/vbHmmTsFret.c", "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": ["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.0906862745, "max_line_length": 119, "alphanum_fraction": 0.504381161, "num_tokens": 8899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.596433160611502, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.268032669329346}} {"text": "#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\n#include \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#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/BAO.c\"\n#include \"../cosmolike_core/theory/external_prior.c\"\n#include \"../cosmolike_core/theory/covariances_3D.c\"\n#include \"../cosmolike_core/theory/covariances_fourier.c\"\n#include \"../cosmolike_core/theory/CMBxLSS_fourier.c\"\n#include \"../cosmolike_core/theory/covariances_CMBxLSS_fourier.c\"\n\n#include \"init_LSSxCMB.c\"\n\n// Naming convention:\n// l = galaxy positions (\"l\" as in \"lens sample\")\n// k = kappa CMB (\"k\" as in \"kappa\")\n// s = kappa from source galaxies (\"s\" as in \"source sample\")\n// And alphabetical order\n\n\nvoid run_cov_ls_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ll_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ll_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ll_ll(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ls_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ss_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\n\nvoid run_cov_ls_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start);\nvoid run_cov_ls_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zs2, int start);\nvoid run_cov_lk_lk(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int zl2, int start);\nvoid run_cov_lk_ls(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int n2, int start);\nvoid run_cov_lk_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int start);\nvoid run_cov_lk_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int zs2, int start);\nvoid run_cov_lk_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zl1, int n2,int start);\nvoid run_cov_kk_kk(char *OUTFILE, char *PATH, double *ell, double *dell,int start);\nvoid run_cov_kk_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zs2, int start);\nvoid run_cov_kk_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n2, int start);\nvoid run_cov_ks_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int zs2,int start);\nvoid run_cov_ks_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int n2, int start);\nvoid run_cov_ll_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start);\nvoid run_cov_ll_ks(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zs2, int start);\nvoid run_cov_ll_lk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int zl2,int start);\n\n\nvoid run_cov_ls_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)\n{\n int zl,zs,z3,z4,nl1,nl2,weight,i,j;\n double c_ng, c_g;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\"); \n zl = ZL(n1); zs = ZS(n1);\n printf(\"\\nN_ggl = %d (%d, %d)\\n\", n1,zl,zs);\n z3 = Z1(n2); z4 = Z2(n2);\n printf(\"N_shear = %d (%d, %d)\\n\", n2,z3,z4);\n for (nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nl2 = 0; nl2 like.lmax_shear && n1!=n2){c_g = 0.;} \n } \n i=like.Ncl*n1+nl1;\n j=like.Ncl*n2+nl2; \n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);\n //printf(\"%d %d %e %e %d %d %d %d %e %e\\n\", like.Ncl*n1+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);\n }\n }\n fclose(F1);\n}\n\n/*** CMBkappa part ****/\n// ls_kk\nvoid run_cov_ls_kk(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int start)\n{\n int zl1, zs1,i,j, weight;\n double c_ng, c_g;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n zl1 = ZL(n1); zs1 = ZS(n1);\n printf(\"Bin for ls: %d (%d, %d)\\n\", n1, zl1, zs1);\n for (int nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (int nl2 = 0; nl2 < like.Ncl; nl2 ++){\n c_ng = 0.; c_g = 0.;\n weight = test_kmax(ell[nl1], zl1);\n if (weight && ell[nl2]like.lmax_kappacmb || ell[nl2]>like.lmax_kappacmb) && zs2!=zs1){\n c_g = 0;\n }\n i=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs1)+nl1;\n j=like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Nbin+tomo.clustering_Nbin+zs2)+nl2;\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell[nl2],0,zs1,0,zs2,c_g,c_ng);\n }\n }\n fclose(F1);\n}\n\n// ks_ss\nvoid run_cov_ks_ss(char *OUTFILE, char *PATH, double *ell, double *dell, int zs1, int n2, int start)\n{\n int z2,z3,nl1,nl2,i,j,weight;\n double c_ng, c_g;\n FILE *F1;\n char filename[300];\n z2 = Z1(n2); z3 = Z2(n2);\n printf(\"Source bin for ks: %d\\n\", zs1);\n printf(\"Bin for ss: %d (%d, %d)\\n\", n2, z2, z3);\n \n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n for (nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nl2 = 0; nl2 < like.Ncl; nl2 ++){\n c_ng = 0.; c_g = 0.;\n if (ell[nl1]\n#include \n\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\n/* ========================================================================\n * Level 1\n * ========================================================================\n */\n\nGSL_EXPORT int gsl_blas_sdsdot (float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n float * result\n );\n\nGSL_EXPORT int gsl_blas_dsdot (const gsl_vector_float * X,\n const gsl_vector_float * Y,\n double * result\n );\n\nGSL_EXPORT int gsl_blas_sdot (const gsl_vector_float * X,\n const gsl_vector_float * Y,\n float * result\n );\n\nGSL_EXPORT int gsl_blas_ddot (const gsl_vector * X,\n const gsl_vector * Y,\n double * result\n );\n\n\nGSL_EXPORT int gsl_blas_cdotu (const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_complex_float * dotu);\n\nGSL_EXPORT int gsl_blas_cdotc (const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_complex_float * dotc);\n\nGSL_EXPORT int gsl_blas_zdotu (const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_complex * dotu);\n\nGSL_EXPORT int gsl_blas_zdotc (const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_complex * dotc);\n\n\nGSL_EXPORT float gsl_blas_snrm2 (const gsl_vector_float * X);\nGSL_EXPORT float gsl_blas_sasum (const gsl_vector_float * X);\nGSL_EXPORT double gsl_blas_dnrm2 (const gsl_vector * X);\nGSL_EXPORT double gsl_blas_dasum (const gsl_vector * X);\nGSL_EXPORT float gsl_blas_scnrm2 (const gsl_vector_complex_float * X);\nGSL_EXPORT float gsl_blas_scasum (const gsl_vector_complex_float * X);\nGSL_EXPORT double gsl_blas_dznrm2 (const gsl_vector_complex * X);\nGSL_EXPORT double gsl_blas_dzasum (const gsl_vector_complex * X);\n\n\nGSL_EXPORT CBLAS_INDEX_t gsl_blas_isamax (const gsl_vector_float * X);\nGSL_EXPORT CBLAS_INDEX_t gsl_blas_idamax (const gsl_vector * X);\nGSL_EXPORT CBLAS_INDEX_t gsl_blas_icamax (const gsl_vector_complex_float * X);\nGSL_EXPORT CBLAS_INDEX_t gsl_blas_izamax (const gsl_vector_complex * X);\n\n\nGSL_EXPORT int gsl_blas_sswap (gsl_vector_float * X,\n gsl_vector_float * Y);\n\nGSL_EXPORT int gsl_blas_scopy (const gsl_vector_float * X,\n gsl_vector_float * Y);\n\nGSL_EXPORT int gsl_blas_saxpy (float alpha,\n const gsl_vector_float * X,\n gsl_vector_float * Y);\n\nGSL_EXPORT int gsl_blas_dswap (gsl_vector * X,\n gsl_vector * Y);\n\nGSL_EXPORT int gsl_blas_dcopy (const gsl_vector * X,\n gsl_vector * Y);\n\nGSL_EXPORT int gsl_blas_daxpy (double alpha,\n const gsl_vector * X,\n gsl_vector * Y);\n\nGSL_EXPORT int gsl_blas_cswap (gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nGSL_EXPORT int gsl_blas_ccopy (const gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nGSL_EXPORT int gsl_blas_caxpy (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n gsl_vector_complex_float * Y);\n\nGSL_EXPORT int gsl_blas_zswap (gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\nGSL_EXPORT int gsl_blas_zcopy (const gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\nGSL_EXPORT int gsl_blas_zaxpy (const gsl_complex alpha,\n const gsl_vector_complex * X,\n gsl_vector_complex * Y);\n\n\nGSL_EXPORT int gsl_blas_srotg (float a[], float b[], float c[], float s[]);\n\nGSL_EXPORT int gsl_blas_srotmg (float d1[], float d2[], float b1[], float b2, float P[]);\n\nGSL_EXPORT int gsl_blas_srot (gsl_vector_float * X,\n gsl_vector_float * Y,\n float c, float s);\n\nGSL_EXPORT int gsl_blas_srotm (gsl_vector_float * X,\n gsl_vector_float * Y,\n const float P[]);\n\nGSL_EXPORT int gsl_blas_drotg (double a[], double b[], double c[], double s[]);\n\nGSL_EXPORT int gsl_blas_drotmg (double d1[], double d2[], double b1[],\n double b2, double P[]);\n\nGSL_EXPORT int gsl_blas_drot (gsl_vector * X,\n gsl_vector * Y,\n const double c, const double s);\n\nGSL_EXPORT int gsl_blas_drotm (gsl_vector * X,\n gsl_vector * Y,\n const double P[]);\n\n\nGSL_EXPORT void gsl_blas_sscal (float alpha, gsl_vector_float * X);\nGSL_EXPORT void gsl_blas_dscal (double alpha, gsl_vector * X);\nGSL_EXPORT void gsl_blas_cscal (const gsl_complex_float alpha, gsl_vector_complex_float * X);\nGSL_EXPORT void gsl_blas_zscal (const gsl_complex alpha, gsl_vector_complex * X);\nGSL_EXPORT void gsl_blas_csscal (float alpha, gsl_vector_complex_float * X);\nGSL_EXPORT void gsl_blas_zdscal (double alpha, gsl_vector_complex * X);\n\n\n/* ===========================================================================\n * Level 2\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nGSL_EXPORT int gsl_blas_sgemv (CBLAS_TRANSPOSE_t TransA,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_vector_float * X,\n float beta,\n gsl_vector_float * Y);\n\nGSL_EXPORT int gsl_blas_strmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_float * A,\n gsl_vector_float * X);\n\nGSL_EXPORT int gsl_blas_strsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_float * A,\n gsl_vector_float * X);\n\nGSL_EXPORT int gsl_blas_dgemv (CBLAS_TRANSPOSE_t TransA,\n double alpha,\n const gsl_matrix * A,\n const gsl_vector * X,\n double beta,\n gsl_vector * Y);\n\nGSL_EXPORT int gsl_blas_dtrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix * A,\n gsl_vector * X);\n\nGSL_EXPORT int gsl_blas_dtrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix * A,\n gsl_vector * X);\n\nGSL_EXPORT int gsl_blas_cgemv (CBLAS_TRANSPOSE_t TransA,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_vector_complex_float * X,\n const gsl_complex_float beta,\n gsl_vector_complex_float * Y);\n\nGSL_EXPORT int gsl_blas_ctrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex_float * A,\n gsl_vector_complex_float * X);\n\nGSL_EXPORT int gsl_blas_ctrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex_float * A,\n gsl_vector_complex_float * X);\n\nGSL_EXPORT int gsl_blas_zgemv (CBLAS_TRANSPOSE_t TransA,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_vector_complex * X,\n const gsl_complex beta,\n gsl_vector_complex * Y);\n\nGSL_EXPORT int gsl_blas_ztrmv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex * A,\n gsl_vector_complex * X);\n\nGSL_EXPORT int gsl_blas_ztrsv (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t TransA, CBLAS_DIAG_t Diag,\n const gsl_matrix_complex * A,\n gsl_vector_complex *X);\n\n/*\n * Routines with S and D prefixes only\n */\nGSL_EXPORT int gsl_blas_ssymv (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_vector_float * X,\n float beta,\n gsl_vector_float * Y);\n\nGSL_EXPORT int gsl_blas_sger (float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n gsl_matrix_float * A);\n\nGSL_EXPORT int gsl_blas_ssyr (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_float * X,\n gsl_matrix_float * A);\n\nGSL_EXPORT int gsl_blas_ssyr2 (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_float * X,\n const gsl_vector_float * Y,\n gsl_matrix_float * A);\n\nGSL_EXPORT int gsl_blas_dsymv (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_matrix * A,\n const gsl_vector * X,\n double beta,\n gsl_vector * Y);\n\nGSL_EXPORT int gsl_blas_dger (double alpha,\n const gsl_vector * X,\n const gsl_vector * Y,\n gsl_matrix * A);\n\nGSL_EXPORT int gsl_blas_dsyr (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector * X,\n gsl_matrix * A);\n\nGSL_EXPORT int gsl_blas_dsyr2 (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector * X,\n const gsl_vector * Y,\n gsl_matrix * A);\n\n/*\n * Routines with C and Z prefixes only\n */\n\nGSL_EXPORT int gsl_blas_chemv (CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_vector_complex_float * X,\n const gsl_complex_float beta,\n gsl_vector_complex_float * Y);\n\nGSL_EXPORT int gsl_blas_cgeru (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nGSL_EXPORT int gsl_blas_cgerc (const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nGSL_EXPORT int gsl_blas_cher (CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_vector_complex_float * X,\n gsl_matrix_complex_float * A);\n\nGSL_EXPORT int gsl_blas_cher2 (CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_vector_complex_float * X,\n const gsl_vector_complex_float * Y,\n gsl_matrix_complex_float * A);\n\nGSL_EXPORT int gsl_blas_zhemv (CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_vector_complex * X,\n const gsl_complex beta,\n gsl_vector_complex * Y);\n\nGSL_EXPORT int gsl_blas_zgeru (const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\nGSL_EXPORT int gsl_blas_zgerc (const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\nGSL_EXPORT int gsl_blas_zher (CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_vector_complex * X,\n gsl_matrix_complex * A);\n\nGSL_EXPORT int gsl_blas_zher2 (CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_vector_complex * X,\n const gsl_vector_complex * Y,\n gsl_matrix_complex * A);\n\n/*\n * ===========================================================================\n * Prototypes for level 3 BLAS\n * ===========================================================================\n */\n\n/*\n * Routines with standard 4 prefixes (S, D, C, Z)\n */\nGSL_EXPORT int gsl_blas_sgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nGSL_EXPORT int gsl_blas_ssymm (CBLAS_SIDE_t Side, CBLAS_UPLO_t Uplo,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nGSL_EXPORT int gsl_blas_ssyrk (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_float * A,\n float beta,\n gsl_matrix_float * C);\n\nGSL_EXPORT int gsl_blas_ssyr2k (CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_float * A,\n const gsl_matrix_float * B,\n float beta,\n gsl_matrix_float * C);\n\nGSL_EXPORT int gsl_blas_strmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n float alpha,\n const gsl_matrix_float * A,\n gsl_matrix_float * B);\n\nGSL_EXPORT int gsl_blas_strsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n float alpha,\n const gsl_matrix_float * A,\n gsl_matrix_float * B);\n\nGSL_EXPORT int gsl_blas_dgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nGSL_EXPORT int gsl_blas_dsymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nGSL_EXPORT int gsl_blas_dsyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix * A,\n double beta,\n gsl_matrix * C);\n\nGSL_EXPORT int gsl_blas_dsyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix * A,\n const gsl_matrix * B,\n double beta,\n gsl_matrix * C);\n\nGSL_EXPORT int gsl_blas_dtrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n double alpha,\n const gsl_matrix * A,\n gsl_matrix * B);\n\nGSL_EXPORT int gsl_blas_dtrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n double alpha,\n const gsl_matrix * A,\n gsl_matrix * B);\n\nGSL_EXPORT int gsl_blas_cgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_csymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_csyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_csyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_ctrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n gsl_matrix_complex_float * B);\n\nGSL_EXPORT int gsl_blas_ctrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n gsl_matrix_complex_float * B);\n\nGSL_EXPORT int gsl_blas_zgemm (CBLAS_TRANSPOSE_t TransA,\n CBLAS_TRANSPOSE_t TransB,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_EXPORT int gsl_blas_zsymm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_EXPORT int gsl_blas_zsyrk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_EXPORT int gsl_blas_zsyr2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex *C);\n\nGSL_EXPORT int gsl_blas_ztrmm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n gsl_matrix_complex * B);\n\nGSL_EXPORT int gsl_blas_ztrsm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t TransA,\n CBLAS_DIAG_t Diag,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n gsl_matrix_complex * B);\n\n/*\n * Routines with prefixes C and Z only\n */\nGSL_EXPORT int gsl_blas_chemm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n const gsl_complex_float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_cherk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n float alpha,\n const gsl_matrix_complex_float * A,\n float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_cher2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex_float alpha,\n const gsl_matrix_complex_float * A,\n const gsl_matrix_complex_float * B,\n float beta,\n gsl_matrix_complex_float * C);\n\nGSL_EXPORT int gsl_blas_zhemm (CBLAS_SIDE_t Side,\n CBLAS_UPLO_t Uplo,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n const gsl_complex beta,\n gsl_matrix_complex * C);\n\nGSL_EXPORT int gsl_blas_zherk (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n double alpha,\n const gsl_matrix_complex * A,\n double beta,\n gsl_matrix_complex * C);\n\nGSL_EXPORT int gsl_blas_zher2k (CBLAS_UPLO_t Uplo,\n CBLAS_TRANSPOSE_t Trans,\n const gsl_complex alpha,\n const gsl_matrix_complex * A,\n const gsl_matrix_complex * B,\n double beta,\n gsl_matrix_complex * C);\n\n\n__END_DECLS\n\n#endif /* __GSL_BLAS_H__ */\n", "meta": {"hexsha": "3c83815ffa1584a5958435e1074817b6307000c6", "size": 26630, "ext": "h", "lang": "C", "max_stars_repo_path": "src/core/gsl/include/gsl/gsl_blas.h", "max_stars_repo_name": "dynaryu/vaws", "max_stars_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/gsl/include/gsl/gsl_blas.h", "max_issues_repo_name": "dynaryu/vaws", "max_issues_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/gsl/include/gsl/gsl_blas.h", "max_forks_repo_name": "dynaryu/vaws", "max_forks_repo_head_hexsha": "f6ed9b75408f7ce6100ed59b7754f745e59be152", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0894039735, "max_line_length": 94, "alphanum_fraction": 0.4772061585, "num_tokens": 5012, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5389832058771036, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.26738624262408534}} {"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_DESxPlanck.c\"\n\n// Naming convention:\n// g = galaxy positions (\"g\" as in \"galaxy\")\n// k = kappa CMB (\"k\" as in \"kappa\")\n// s = kappa from source galaxies (\"s\" as in \"shear\")\n// And alphabetical order\n\ntypedef double (*C_tomo_pointer)(double l, int n1, int n2);\nvoid twopoint_via_hankel(double **xi, double *logthetamin, double *logthetamax, C_tomo_pointer C_tomo, int ni, int nj, int N_Bessel);\n\n#include \"../cosmolike_core/theory/CMBxLSS_fourier.c\"\n\ntypedef struct input_nuisance_params_des {\n double bias[10];\n // double bias2[10];\n double b_mag[10];\n double source_z_bias[10];\n double lens_z_bias[10];\n double shear_m[10];\n double A_ia;\n double eta_ia;\n // double bary[3];\n} input_nuisance_params_des;\n\ntypedef struct input_cosmo_params_des {\n double omega_m;\n double sigma_8;\n double n_s;\n double w0;\n double wa;\n double omega_b;\n double h0;\n double MGSigma;\n double MGmu;\n} input_cosmo_params_des;\n\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);\ndouble C_ks_sys(double ell, 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_gk(double *ell, double *data, int start);\nvoid set_data_ks(double *ell, double *data, int start);\nvoid set_data_kk(double *ell, 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 BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia);\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 BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia);\nvoid write_datavector_wrapper(char *details, input_cosmo_params_des ic, input_nuisance_params_des in);\ndouble log_like_wrapper(input_cosmo_params_des ic, input_nuisance_params_des in);\nint get_N_tomo_shear(void);\nint get_N_tomo_clustering(void);\nint get_N_ggl(void);\nint get_N_ell(void);\n\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\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.IA==4){C = C_shear_shear_IA_tab(ell,z1,z2);}\n else{printf(\"only support IA==4!\\n\");exit(1);}\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.IA==4){C = C_ggl_IA_tab(ell,zl,zs);}\n else{printf(\"only support IA==4!\\n\");exit(1);}\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\ndouble C_ks_sys(double ell, int zs)\n{\n double C;\n C = C_ks(ell,zs);\n if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);\n return 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 if (mask(Ncl*nz+i)){ 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 if (mask(start+(Ncl*nz)+i)){\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))\n if (mask(start+(Ncl*nz)+i)) {\n data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);\n }\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\n\nvoid set_data_gk(double *ell, double *data, int start)\n{\n for (int nz=0; nz 0.6) return 0;\n if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0;\n if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) 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 //CH BEGINS \n //CH: to use for running planck15_BA0_w0_wa prior alone) \n //printf(\"like_fourier.c from WFIRST_forecasts: cosmology bounds set for running with planck15_BA0_w0_wa prior\\n\");\n //if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0; \n //if (cosmology.omb < 0.01 || cosmology.omb > 0.1) return 0; \n //if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0; \n //if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0; \n //if (cosmology.w0 < -2.1 || cosmology.w0 > 1.5) return 0; \n //if (cosmology.wa < -5.0 || cosmology.wa > 2.6) return 0; \n //if (cosmology.h0 < 0.3 || cosmology.h0 > 0.9) return 0; \n //CH ENDS\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)\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.eta_ia < -10.0 || nuisance.eta_ia> 10.0) return 0;\nreturn 1;\n}\n\n// int set_nuisance_ia(double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q)\n// {\n// nuisance.A_ia=A_ia; \n// nuisance.beta_ia=beta_ia;\n// nuisance.eta_ia=eta_ia;\n// nuisance.eta_ia_highz=eta_ia_highz;\n// nuisance.LF_alpha=LF_alpha;\n// nuisance.LF_P=LF_P;\n// nuisance.LF_Q=LF_Q;\n// nuisance.LF_red_alpha=LF_red_alpha;\n// nuisance.LF_red_P=LF_red_P;\n// nuisance.LF_red_Q=LF_red_Q;\n// if (nuisance.A_ia < 0.0 || nuisance.A_ia > 10.0) return 0;\n// if (nuisance.beta_ia < -4.0 || nuisance.beta_ia > 6.0) return 0;\n// if (nuisance.eta_ia < -10.0 || nuisance.eta_ia> 10.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// // }\n// return 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\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 for (i = 0; i < tomo.clustering_Nbin; i++){\n // printf(\"in set routine %d %le\\n\",i,gbias.b[i]);\n if (gbias.b[i] < 0.4 || gbias.b[i] > 3.0) return 0;\n }\n\n return 1;\n} \n\nint set_nuisance_bmag(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)\n{\n\n int i;\n gbias.b_mag[0] = B1;\n gbias.b_mag[1] = B2;\n gbias.b_mag[2] = B3;\n gbias.b_mag[3] = B4;\n gbias.b_mag[4] = B5;\n gbias.b_mag[5] = B6;\n gbias.b_mag[6] = B7;\n gbias.b_mag[7] = B8;\n gbias.b_mag[8] = B9;\n gbias.b_mag[9] = B10;\n for (i = 0; i < tomo.clustering_Nbin; i++){\n // printf(\"in set routine %d %le\\n\",i,gbias.b[i]);\n if (gbias.b_mag[i] < -5.0 || gbias.b_mag[i] > 5.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 BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia)\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;l10){printf(\"a,i,j: %le, %d, %d, %le, %le, %le\\n\",a,i,j,pred[i]-data_read(1,i),pred[j]-data_read(1,j), invcov_mask(1,i,j));}\n chisqr=chisqr+a;\n }\n // if (fabs(data_read(1,i)) < 1.e-25){\n // printf(\"%d %le %le %le\\n\",i,data_read(1,i),pred[i],invcov_read(1,i,i));\n // }\n }\n if (chisqr<0.0){\n printf(\"error: chisqr = %le\\n\",chisqr);\n //exit(EXIT_FAILURE);\n }\n printf(\"%le\\n\",chisqr);\n return -0.5*chisqr+log_L_prior;\n}\n\nvoid compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double BMAG1, double BMAG2, double BMAG3, double BMAG4,double BMAG5, double BMAG6, double BMAG7, double BMAG8, double BMAG9, double BMAG10, double SP1, double SP2, double SP3, double SP4, double SP5,double SP6, double SP7, double SP8, double SP9, double SP10, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double eta_ia)\n{\n\n int i,j,k,m=0,l;\n static double *pred;\n static double *ell;\n static double *ell_Cluster;\n static double darg;\n double chisqr,a,log_L_prior=0.0;\n \n if(ell==0){\n pred= create_double_vector(0, like.Ndata-1);\n ell= create_double_vector(0, like.Ncl-1);\n darg=(log(like.lmax)-log(like.lmin))/like.Ncl;\n for (l=0;l\n#include \n#include \n#include \n\n#include \n#include \n\n#define check_tsk_error(val) if (val < 0) {\\\n errx(EXIT_FAILURE, \"line %d: %s\", __LINE__, tsk_strerror(val));\\\n}\n\nvoid\nsimulate(tsk_table_collection_t *tables, int N, int T, int simplify_interval, gsl_rng *rng)\n{\n tsk_id_t *buffer, *parents, *children, child, left_parent, right_parent;\n double breakpoint;\n int ret, j, t, b;\n\n assert(simplify_interval != 0); // leads to division by zero\n buffer = malloc(2 * N * sizeof(tsk_id_t));\n if (buffer == NULL) {\n errx(EXIT_FAILURE, \"Out of memory\");\n }\n tables->sequence_length = 1.0;\n parents = buffer;\n for (j = 0; j < N; j++) {\n parents[j] = tsk_node_table_add_row(&tables->nodes, 0, T,\n TSK_NULL, TSK_NULL, NULL, 0);\n check_tsk_error(parents[j]);\n }\n b = 0;\n for (t = T - 1; t >= 0; t--) {\n /* Alternate between using the first and last N values in the buffer */\n parents = buffer + (b * N);\n b = (b + 1) % 2;\n children = buffer + (b * N);\n for (j = 0; j < N; j++) {\n child = tsk_node_table_add_row(&tables->nodes, 0, t,\n TSK_NULL, TSK_NULL, NULL, 0);\n check_tsk_error(child);\n left_parent = parents[gsl_rng_uniform_int(rng, N)];\n right_parent = parents[gsl_rng_uniform_int(rng, N)];\n do {\n breakpoint = gsl_rng_uniform(rng);\n } while (breakpoint == 0); /* tiny proba of breakpoint being 0 */\n ret = tsk_edge_table_add_row(&tables->edges, 0, breakpoint, left_parent, child);\n check_tsk_error(ret);\n ret = tsk_edge_table_add_row(&tables->edges, breakpoint, 1, right_parent, child);\n check_tsk_error(ret);\n children[j] = child;\n }\n if (t % simplify_interval == 0) {\n printf(\"Simplify at generation %d: (%d nodes %d edges)\", t,\n tables->nodes.num_rows, tables->edges.num_rows);\n /* Note: Edges must be sorted for simplify to work, and we use a brute force\n * approach of sorting each time here for simplicity. This is inefficient. */\n ret = tsk_table_collection_sort(tables, NULL, 0);\n check_tsk_error(ret);\n ret = tsk_table_collection_simplify(tables, children, N, 0, NULL);\n check_tsk_error(ret);\n printf(\" -> (%d nodes %d edges)\\n\", tables->nodes.num_rows,\n tables->edges.num_rows);\n for (j = 0; j < N; j++) {\n children[j] = j;\n }\n }\n }\n free(buffer);\n}\n\nint\nmain(int argc, char **argv)\n{\n int ret;\n tsk_table_collection_t tables;\n gsl_rng *rng = gsl_rng_alloc(gsl_rng_default);\n\n if (argc != 5) {\n errx(EXIT_FAILURE, \"usage: N T simplify-interval output-file\");\n }\n ret = tsk_table_collection_init(&tables, 0);\n check_tsk_error(ret);\n simulate(&tables, atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), rng);\n ret = tsk_table_collection_dump(&tables, argv[4], 0);\n check_tsk_error(ret);\n\n tsk_table_collection_free(&tables);\n gsl_rng_free(rng);\n return 0;\n}\n", "meta": {"hexsha": "257496a03750050a1adafc2a02998aa0bb622fd5", "size": 3236, "ext": "c", "lang": "C", "max_stars_repo_path": "c/examples/haploid_wright_fisher.c", "max_stars_repo_name": "winni2k/tskit", "max_stars_repo_head_hexsha": "92fe9c04a27385401732a698843756aa797bacdd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/examples/haploid_wright_fisher.c", "max_issues_repo_name": "winni2k/tskit", "max_issues_repo_head_hexsha": "92fe9c04a27385401732a698843756aa797bacdd", "max_issues_repo_licenses": ["MIT"], "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/examples/haploid_wright_fisher.c", "max_forks_repo_name": "winni2k/tskit", "max_forks_repo_head_hexsha": "92fe9c04a27385401732a698843756aa797bacdd", "max_forks_repo_licenses": ["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.1739130435, "max_line_length": 93, "alphanum_fraction": 0.5791100124, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.2654590286012472}} {"text": "/* This file is auto-generated from countpairs_s_mu_mocks_impl.c.src */\n#ifndef DOUBLE_PREC\n#define DOUBLE_PREC\n#endif\n// # -*- mode: c -*-\n/* File: countpairs_s_mu_mocks_impl.c.src */\n/*\n This file is a part of the Corrfunc package\n Copyright (C) 2015-- Manodeep Sinha (manodeep@gmail.com)\n License: MIT LICENSE. See LICENSE file under the top-level\n directory at https://github.com/manodeep/Corrfunc/\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"countpairs_s_mu_mocks_impl_double.h\"\n#include \"countpairs_s_mu_mocks_kernels_double.c\"\n#include \"cellarray_mocks_double.h\"\n#include \"gridlink_mocks_impl_double.h\"\n\n#include \"defs.h\"\n#include \"utils.h\"\n#include \"cosmology_params.h\"\n#include \"set_cosmo_dist.h\"\n#include \"cpu_features.h\"\n#include \"progressbar.h\"\n#include \"proj_functions_double.h\"\n\n#if defined(_OPENMP)\n#include \n#endif\n\nint interrupt_status_DDsmu_mocks_double=EXIT_SUCCESS;\n\nvoid interrupt_handler_countpairs_s_mu_mocks_double(int signo)\n{\n fprintf(stderr,\"Received signal = `%s' (signo = %d). Aborting \\n\",strsignal(signo), signo);\n interrupt_status_DDsmu_mocks_double = EXIT_FAILURE;\n}\n\n\nint check_ra_dec_cz_s_mu_double(const int64_t N, double *phi, double *theta, double *cz)\n{\n\n if(N==0) {\n return EXIT_SUCCESS;\n }\n if(phi == NULL || theta == NULL || cz == NULL) {\n fprintf(stderr,\"Input arrays can not be NULL. Have RA = %p DEC = %p cz = %p\\n\", phi, theta, cz);\n return EXIT_FAILURE;\n }\n\n int fix_cz = 0;\n int fix_ra = 0;\n int fix_dec = 0;\n\n const double max_cz_threshold = 10.0;//if I find that max cz is smaller than this threshold, then I will assume z has been supplied rather than cz\n double max_cz = 0.0;\n //Check input cz -> ensure that cz contains cz and not z\n for(int64_t i=0;i max_cz) max_cz = cz[i];\n if(phi[i] < 0.0) {\n fix_ra = 1;\n }\n if(theta[i] > 90.0) {\n fix_dec = 1;\n }\n if(theta[i] > 180) {\n fprintf(stderr,\"theta[%\"PRId64\"] = %\"REAL_FORMAT\"should be less than 180 deg\\n\", i, theta[i]);\n return EXIT_FAILURE;\n }\n }\n if(max_cz < max_cz_threshold) fix_cz = 1;\n\n //Only run the loop if something needs to be fixed\n if(fix_cz==1 || fix_ra == 1 || fix_dec == 1) {\n if(fix_ra == 1) {\n fprintf(stderr,\"%s> Out of range values found for ra. Expected ra to be in the range [0.0,360.0]. Found ra values in [-180,180] -- fixing that\\n\", __FUNCTION__);\n }\n if(fix_dec == 1) {\n fprintf(stderr,\"%s> Out of range values found for dec. Expected dec to be in the range [-90.0,90.0]. Found dec values in [0,180] -- fixing that\\n\", __FUNCTION__);\n }\n if(fix_cz == 1) {\n fprintf(stderr,\"%s> Out of range values found for cz. Expected input to be `cz' but found `z' instead. max_cz (found in input) = %\"REAL_FORMAT\" threshold \"\n \"= %\"REAL_FORMAT\"\\n\",__FUNCTION__,max_cz,max_cz_threshold);\n }\n\n for(int64_t i=0;i convert to cz\n }\n }\n }\n\n return EXIT_SUCCESS;\n}\n\n\ncountpairs_mocks_func_ptr_double countpairs_s_mu_mocks_driver_double(const struct config_options *options)\n{\n\n static countpairs_mocks_func_ptr_double function = NULL;\n static isa old_isa=-1;\n if(old_isa == options->instruction_set) {\n return function;\n }\n\n /* Array of function pointers */\n countpairs_mocks_func_ptr_double allfunctions[] = {\n#ifdef __AVX__\n countpairs_s_mu_mocks_avx_intrinsics_double,\n#endif\n#ifdef __SSE4_2__\n countpairs_s_mu_mocks_sse_intrinsics_double,\n#endif\n countpairs_s_mu_mocks_fallback_double\n };\n\n const int num_functions = sizeof(allfunctions)/sizeof(void *);\n const int fallback_offset = num_functions - 1;\n#if defined(__AVX__) || defined __SSE4_2__\n const int highest_isa = instrset_detect();\n#endif\n int curr_offset = 0;\n\n /* Now check if AVX is supported by the CPU */\n int avx_offset = fallback_offset;\n#ifdef __AVX__\n avx_offset = highest_isa >= 7 ? curr_offset:fallback_offset;\n curr_offset++;\n#endif\n\n /* Is the SSE function supported at runtime and enabled at compile-time?*/\n int sse_offset = fallback_offset;\n#ifdef __SSE4_2__\n sse_offset = highest_isa >= 6 ? curr_offset:fallback_offset;\n curr_offset++;\n#endif\n if( curr_offset != fallback_offset) {\n fprintf(stderr,\"ERROR: Bug in code (current offset = %d *should equal* fallback function offset = %d)\\n\",\n curr_offset, fallback_offset);\n return NULL;\n }\n\n int function_dispatch=0;\n /* Check that cpu supports feature */\n if(options->instruction_set >= 0) {\n switch(options->instruction_set) {\n case(AVX512F):\n case(AVX2):\n case(AVX):function_dispatch=avx_offset;break;\n case(SSE42): function_dispatch=sse_offset;break;\n default:function_dispatch=fallback_offset;break;\n }\n }\n\n if(function_dispatch >= num_functions) {\n fprintf(stderr,\"In %s> ERROR: Could not resolve the correct function.\\n Function index = %d must lie between [0, %d)\\n\",\n __FUNCTION__, function_dispatch, num_functions);\n return NULL;\n }\n function = allfunctions[function_dispatch];\n old_isa = options->instruction_set;\n\n if(options->verbose){\n // This must be first (AVX/SSE may be aliased to fallback)\n if(function_dispatch == fallback_offset){\n fprintf(stderr,\"Using fallback kernel\\n\");\n } else if(function_dispatch == avx_offset){\n fprintf(stderr,\"Using AVX kernel\\n\");\n } else if(function_dispatch == sse_offset){\n fprintf(stderr,\"Using SSE kernel\\n\");\n } else {\n printf(\"Unknown kernel!\\n\");\n }\n }\n\n return function;\n}\n\n\nint countpairs_mocks_s_mu_double(const int64_t ND1, double *ra1, double *dec1, double *czD1,\n const int64_t ND2, double *ra2, double *dec2, double *czD2,\n const int numthreads,\n const int autocorr,\n const char *sbinfile,\n const double max_mu,\n const int nmu_bins,\n const int cosmology,\n results_countpairs_mocks_s_mu *results,\n struct config_options *options, struct extra_options *extra)\n{\n\n if(options->float_type != sizeof(double)) {\n fprintf(stderr,\"ERROR: In %s> Can only handle arrays of size=%zu. Got an array of size = %zu\\n\",\n __FUNCTION__, sizeof(double), options->float_type);\n return EXIT_FAILURE;\n }\n\n // If no extra options were passed, create dummy options\n // This allows us to pass arguments like \"extra->weights0\" below;\n // they'll just be NULLs, which is the correct behavior\n struct extra_options dummy_extra;\n if(extra == NULL){\n weight_method_t dummy_method = NONE;\n dummy_extra = get_extra_options(dummy_method);\n extra = &dummy_extra;\n }\n\n int need_weightavg = extra->weight_method != NONE;\n\n options->sort_on_z = 1;\n struct timeval t0;\n if(options->c_api_timer) {\n gettimeofday(&t0, NULL);\n }\n if(options->fast_divide_and_NR_steps >= MAX_FAST_DIVIDE_NR_STEPS) {\n fprintf(stderr, ANSI_COLOR_MAGENTA\"Warning: The number of requested Newton-Raphson steps = %u is larger than max. allowed steps = %u.\"\n \" Switching to a standard divide\"ANSI_COLOR_RESET\"\\n\",\n options->fast_divide_and_NR_steps, MAX_FAST_DIVIDE_NR_STEPS);\n options->fast_divide_and_NR_steps = 0;\n }\n\n //Check inputs\n if(ND1 == 0 || (autocorr == 0 && ND2 == 0)) {\n return EXIT_SUCCESS;\n }\n\n //Check inputs\n int status1 = check_ra_dec_cz_s_mu_double(ND1, ra1, dec1, czD1);\n if(status1 != EXIT_SUCCESS) {\n return status1;\n }\n if(autocorr==0) {\n int status2 = check_ra_dec_cz_s_mu_double(ND2, ra2, dec2, czD2);\n if(status2 != EXIT_SUCCESS) {\n return status2;\n }\n }\n\n#if defined(_OPENMP)\n omp_set_num_threads(numthreads);\n#else\n (void) numthreads;\n#endif\n\n if(options->max_cells_per_dim == 0) {\n fprintf(stderr,\"Warning: Max. cells per dimension is set to 0 - resetting to `NLATMAX' = %d\\n\", NLATMAX);\n options->max_cells_per_dim = NLATMAX;\n }\n for(int i=0;i<3;i++) {\n if(options->bin_refine_factors[i] < 1) {\n fprintf(stderr,\"Warning: bin refine factor along axis = %d *must* be >=1. Instead found bin refine factor =%d\\n\",\n i, options->bin_refine_factors[i]);\n reset_bin_refine_factors(options);\n break;/* all factors have been reset -> no point continuing with the loop */\n }\n }\n\n /* setup interrupt handler -> mostly useful during the python execution.\n Let's Ctrl-C abort the extension */\n SETUP_INTERRUPT_HANDLERS(interrupt_handler_countpairs_s_mu_mocks_double);\n\n //Try to initialize cosmology - code will exit if comoslogy is not implemented.\n //Putting in a different scope so I can call the variable status\n {\n int status = init_cosmology(cosmology);\n if(status != EXIT_SUCCESS) {\n return status;\n }\n }\n\n /***********************\n *initializing the bins\n ************************/\n double *supp;\n int nsbin;\n double smin,smax;\n setup_bins(sbinfile,&smin,&smax,&nsbin,&supp);\n if( ! (smin > 0.0 && smax > 0.0 && smin < smax && nsbin > 0)) {\n fprintf(stderr,\"Error: Could not setup with S bins correctly. (smin = %lf, smax = %lf, with nbins = %d). Expected non-zero smin/smax with smax > smin and nbins >=1 \\n\",\n smin, smax, nsbin);\n return EXIT_FAILURE;\n }\n\n\n if(max_mu <= 0.0 || max_mu > 1.0) {\n fprintf(stderr,\"Error: max_mu (max. value for the cosine of the angle with line of sight) must be greater than 0 and at most 1).\\n\"\n \"The passed value is max_mu = %lf. Please change it to be > 0 and <= 1.0\\n\", max_mu);\n return EXIT_FAILURE;\n }\n\n if(nmu_bins < 1 ) {\n fprintf(stderr,\"Error: Number of mu bins = %d must be at least 1\\n\", nmu_bins);\n return EXIT_FAILURE;\n }\n\n //Change cz into co-moving distance\n double *D1 = NULL, *D2 = NULL;\n if(options->is_comoving_dist == 0) {\n D1 = my_malloc(sizeof(*D1),ND1);\n D2 = autocorr == 0 ? my_malloc(sizeof(*D2),ND2):D1;\n } else {\n D1 = czD1;\n D2 = autocorr == 0 ? czD2:czD1;\n }\n\n if(D1 == NULL || D2 == NULL) {\n free(D1);free(D2);\n return EXIT_FAILURE;\n }\n\n\n if(options->is_comoving_dist == 0) {\n //Setup variables to do the cz->comoving distance\n double czmax = 0.0;\n const double inv_speed_of_light = 1.0/SPEED_OF_LIGHT;\n get_max_double(ND1, czD1, &czmax);\n if(autocorr == 0) {\n get_max_double(ND2, czD2, &czmax);\n }\n const double zmax = czmax * inv_speed_of_light + 0.01;\n\n const int workspace_size = 10000;\n double *interp_redshift = my_calloc(sizeof(*interp_redshift), workspace_size);//the interpolation is done in 'z' and not in 'cz'\n double *interp_comoving_dist = my_calloc(sizeof(*interp_comoving_dist),workspace_size);\n int Nzdc = set_cosmo_dist(zmax, workspace_size, interp_redshift, interp_comoving_dist, cosmology);\n if(Nzdc < 0) {\n free(interp_redshift);free(interp_comoving_dist);\n return EXIT_FAILURE;\n }\n\n gsl_interp *interpolation;\n gsl_interp_accel *accelerator;\n accelerator = gsl_interp_accel_alloc();\n interpolation = gsl_interp_alloc (gsl_interp_linear,Nzdc);\n gsl_interp_init(interpolation, interp_redshift, interp_comoving_dist, Nzdc);\n for(int64_t i=0;ibin_refine_factors[0] = 1;\n }\n if(smax < 0.05*ydiff) {\n options->bin_refine_factors[1] = 1;\n }\n if(smax < 0.05*zdiff) {\n options->bin_refine_factors[2] = 1;\n }\n }\n\n /*---Create 3-D lattice--------------------------------------*/\n int nmesh_x=0,nmesh_y=0,nmesh_z=0;\n cellarray_mocks_index_particles_double *lattice1 = gridlink_mocks_index_particles_double(ND1, X1, Y1, Z1, D1, &(extra->weights0),\n xmin, xmax, ymin, ymax, zmin, zmax,\n smax, smax, smax,\n options->bin_refine_factors[0],\n options->bin_refine_factors[1],\n options->bin_refine_factors[2],\n &nmesh_x, &nmesh_y, &nmesh_z,\n options);\n if(lattice1 == NULL) {\n return EXIT_FAILURE;\n }\n\n /* If there too few cells (BOOST_CELL_THRESH is ~10), and the number of cells can be increased, then boost bin refine factor by ~1*/\n const double avg_np = ((double)ND1)/(nmesh_x*nmesh_y*nmesh_z);\n const int8_t max_nmesh = fmax(nmesh_x, fmax(nmesh_y, nmesh_z));\n if((max_nmesh <= BOOST_CELL_THRESH || avg_np >= BOOST_NUMPART_THRESH)\n && max_nmesh < options->max_cells_per_dim) {\n fprintf(stderr,\"%s> gridlink seems inefficient. nmesh = (%d, %d, %d); avg_np = %.3g. \", __FUNCTION__, nmesh_x, nmesh_y, nmesh_z, avg_np);\n if(get_bin_refine_scheme(options) == BINNING_DFL) {\n fprintf(stderr,\"Boosting bin refine factor - should lead to better performance\\n\");\n // Only boost the first two dimensions. Prevents excessive refinement.\n for(int i=0;i<2;i++) {\n options->bin_refine_factors[i] += BOOST_BIN_REF;\n }\n\n free_cellarray_mocks_index_particles_double(lattice1, nmesh_x * (int64_t) nmesh_y * nmesh_z);\n lattice1 = gridlink_mocks_index_particles_double(ND1, X1, Y1, Z1, D1, &(extra->weights0),\n xmin, xmax, ymin, ymax, zmin, zmax,\n smax, smax, smax,\n options->bin_refine_factors[0],\n options->bin_refine_factors[1],\n options->bin_refine_factors[2],\n &nmesh_x, &nmesh_y, &nmesh_z,\n options);\n if(lattice1 == NULL) {\n return EXIT_FAILURE;\n }\n } else {\n fprintf(stderr,\"Boosting bin refine factor could have helped. However, since custom bin refine factors \"\n \"= (%d, %d, %d) are being used - continuing with inefficient mesh\\n\", options->bin_refine_factors[0],\n options->bin_refine_factors[1], options->bin_refine_factors[2]);\n\n }\n }\n\n cellarray_mocks_index_particles_double *lattice2 = NULL;\n if(autocorr==0) {\n int ngrid2_x=0,ngrid2_y=0,ngrid2_z=0;\n lattice2 = gridlink_mocks_index_particles_double(ND2, X2, Y2, Z2, D2, &(extra->weights1),\n xmin, xmax,\n ymin, ymax,\n zmin, zmax,\n smax, smax, smax,\n options->bin_refine_factors[0],\n options->bin_refine_factors[1],\n options->bin_refine_factors[2],\n &ngrid2_x, &ngrid2_y, &ngrid2_z, options);\n if(lattice2 == NULL) {\n return EXIT_FAILURE;\n }\n if( ! (nmesh_x == ngrid2_x && nmesh_y == ngrid2_y && nmesh_z == ngrid2_z) ) {\n fprintf(stderr,\"Error: The two sets of 3-D lattices do not have identical bins. First has dims (%d, %d, %d) while second has (%d, %d, %d)\\n\",\n nmesh_x, nmesh_y, nmesh_z, ngrid2_x, ngrid2_y, ngrid2_z);\n return EXIT_FAILURE;\n }\n } else {\n lattice2 = lattice1;\n }\n free(X1);free(Y1);free(Z1);\n if(autocorr == 0) {\n free(X2);free(Y2);free(Z2);\n }\n\n if(options->is_comoving_dist == 0) {\n free(D1);\n if(autocorr == 0) {\n free(D2);\n }\n }\n\n\n\n const int64_t totncells = (int64_t) nmesh_x * (int64_t) nmesh_y * (int64_t) nmesh_z;\n {\n int status = assign_ngb_cells_mocks_index_particles_double(lattice1, lattice2, totncells,\n options->bin_refine_factors[0], options->bin_refine_factors[1], options->bin_refine_factors[2],\n nmesh_x, nmesh_y, nmesh_z,\n autocorr);\n if(status != EXIT_SUCCESS) {\n free_cellarray_mocks_index_particles_double(lattice1, totncells);\n if(autocorr == 0) {\n free_cellarray_mocks_index_particles_double(lattice2, totncells);\n }\n free(supp);\n return EXIT_FAILURE;\n }\n }\n /*---Gridlink-variables----------------*/\n const int totnbins = (nmu_bins+1)*(nsbin+1);\n const int nprojbins = nsbin-1;\n#if defined(_OPENMP)\n uint64_t **all_npairs = (uint64_t **) matrix_calloc(sizeof(uint64_t), numthreads, totnbins);\n double **all_savg = NULL;\n if(options->need_avg_sep){\n all_savg = (double **) matrix_calloc(sizeof(double),numthreads,totnbins);\n }\n double **all_weightavg = NULL;\n if(need_weightavg) {\n all_weightavg = (double **) matrix_calloc(sizeof(double),numthreads,totnbins);\n }\n double **all_projpairs = (double **) matrix_calloc(sizeof(double),numthreads,nprojbins);\n double **all_projpairs_tensor = (double **) matrix_calloc(sizeof(double),numthreads,nprojbins*nprojbins);\n\n\n#else //USE_OMP\n uint64_t npairs[totnbins];\n double savg[totnbins], weightavg[totnbins], projpairs[nprojbins];\n double projpairs_tensor[nprojbins*nprojbins];\n\n for(int i=0; i need_avg_sep) {\n savg[i] = ZERO;\n }\n if(need_weightavg) {\n weightavg[i] = ZERO;\n }\n }\n for(int i=0;iverbose) {\n init_my_progressbar(totncells,&interrupted);\n }\n\n\n#if defined(_OPENMP)\n#pragma omp parallel shared(numdone, abort_status, interrupt_status_DDsmu_mocks_double)\n {\n const int tid = omp_get_thread_num();\n uint64_t npairs[totnbins];\n double savg[totnbins], weightavg[totnbins], projpairs[nprojbins];\n double projpairs_tensor[nprojbins*nprojbins];\n\n for(int i=0;ineed_avg_sep) {\n savg[i] = ZERO;\n }\n if(need_weightavg) {\n weightavg[i] = ZERO;\n }\n }\n for(int i=0;iverbose) {\n#if defined(_OPENMP)\n if (omp_get_thread_num() == 0)\n#endif\n my_progressbar(numdone,&interrupted);\n\n\n#if defined(_OPENMP)\n#pragma omp atomic\n#endif\n numdone++;\n }\n\n const cellarray_mocks_index_particles_double *first = &(lattice1[index1]);\n if(first->nelements == 0) {\n continue;\n }\n double *x1 = first->x;\n double *y1 = first->y;\n double *z1 = first->z;\n double *d1 = first->cz;\n const weight_struct_double *weights1 = &(first->weights);\n const int64_t N1 = first->nelements;\n\n if(autocorr == 1) {\n int same_cell = 1;\n double *this_savg = options->need_avg_sep ? &(savg[0]):NULL;\n double *this_weightavg = need_weightavg ? weightavg:NULL;\n const int status = countpairs_s_mu_mocks_function_double(N1, x1, y1, z1, d1, weights1,\n N1, x1, y1, z1, d1, weights1,\n same_cell,\n options->fast_divide_and_NR_steps,\n smax, smin, nsbin,\n nmu_bins, supp_sqr, mu_max,\n this_savg, npairs, projpairs,\n projpairs_tensor,\n this_weightavg, extra->weight_method);\n /* This actually causes a race condition under OpenMP - but mostly\n I care that an error occurred - rather than the exact value of\n the error status */\n abort_status |= status;\n }\n\n for(int64_t ngb=0;ngbnum_ngb;ngb++){\n const cellarray_mocks_index_particles_double *second = first->ngb_cells[ngb];\n if(second->nelements == 0) {\n continue;\n }\n const int same_cell = 0;\n double *x2 = second->x;\n double *y2 = second->y;\n double *z2 = second->z;\n double *d2 = second->cz;\n const weight_struct_double *weights2 = &(second->weights);\n const int64_t N2 = second->nelements;\n double *this_savg = options->need_avg_sep ? &(savg[0]):NULL;\n double *this_weightavg = need_weightavg ? weightavg:NULL;\n const int status = countpairs_s_mu_mocks_function_double(N1, x1, y1, z1, d1, weights1,\n N2, x2, y2, z2, d2, weights2,\n same_cell,\n options->fast_divide_and_NR_steps,\n smax, smin, nsbin,\n nmu_bins, supp_sqr, mu_max,\n this_savg, npairs, projpairs,\n projpairs_tensor,\n this_weightavg, extra->weight_method);\n /* This actually causes a race condition under OpenMP - but mostly\n I care that an error occurred - rather than the exact value of\n the error status */\n abort_status |= status;\n }//loop over ngb cells\n }//abort_status check\n }//i loop over ND1 particles\n#if defined(_OPENMP)\n for(int i=0;ineed_avg_sep) {\n all_savg[tid][i] = savg[i];\n }\n if(need_weightavg) {\n all_weightavg[tid][i] = weightavg[i];\n }\n }\n for (int i=0;ineed_avg_sep) {\n matrix_free((void **) all_savg, numthreads);\n }\n if(need_weightavg) {\n matrix_free((void **) all_weightavg, numthreads);\n }\n matrix_free((void **) all_projpairs, numthreads);\n matrix_free((void **) all_projpairs_tensor, numthreads);\n#endif\n return EXIT_FAILURE;\n }\n\n if(options->verbose) {\n finish_myprogressbar(&interrupted);\n }\n\n\n\n#if defined(_OPENMP)\n uint64_t npairs[totnbins];\n double savg[totnbins], weightavg[totnbins], projpairs[nprojbins];\n double projpairs_tensor[nprojbins*nprojbins];\n for(int i=0;ineed_avg_sep) {\n savg[i] = ZERO;\n }\n if(need_weightavg) {\n weightavg[i] = ZERO;\n }\n }\n for(int i=0;ineed_avg_sep) {\n savg[j] += all_savg[i][j];\n }\n if(need_weightavg) {\n weightavg[j] += all_weightavg[i][j];\n }\n }\n for(int j=0;jneed_avg_sep) {\n matrix_free((void **) all_savg, numthreads);\n }\n if(need_weightavg) {\n matrix_free((void **) all_weightavg, numthreads);\n }\n matrix_free((void **) all_projpairs, numthreads);\n matrix_free((void **) all_projpairs_tensor, numthreads);\n\n#endif //USE_OMP\n\n //The code does not double count for autocorrelations\n //which means the npairs and savg values need to be doubled;\n if(autocorr == 1) {\n const uint64_t int_fac = 2;\n const double dbl_fac = (double) 2.0;\n for(int i=0;ineed_avg_sep) {\n savg[i] *= dbl_fac;\n }\n if(need_weightavg) {\n weightavg[i] *= dbl_fac;\n }\n }\n //TODO: do i also want to double this? think so\n for(int i=0;i 0) {\n if(options->need_avg_sep) {\n savg[i] /= (double) npairs[i] ;\n }\n if(need_weightavg) {\n weightavg[i] /= (double) npairs[i];\n }\n }\n }\n // don't need proj_pairs here, not averaging\n\n\n\n results->nsbin = nsbin;\n results->nmu_bins = nmu_bins;\n results->mu_max = max_mu;//NOTE max_mu which is double and not mu_max (which might be float)\n results->mu_min = ZERO;\n results->npairs = my_malloc(sizeof(*(results->npairs)), totnbins);\n results->projpairs = my_malloc(sizeof(*(results->npairs)), nprojbins);\n results->projpairs_tensor = my_malloc(sizeof(*(results->npairs)), nprojbins*nprojbins);\n results->supp = my_malloc(sizeof(*(results->supp)) , nsbin);\n results->savg = my_malloc(sizeof(*(results->savg)) , totnbins);\n results->weightavg = my_calloc(sizeof(double) , totnbins);\n if(results->npairs == NULL || results->supp == NULL || results->savg == NULL || results->weightavg == NULL || results->projpairs == NULL) {\n free_results_mocks_s_mu(results);\n free(supp);\n return EXIT_FAILURE;\n }\n\n for(int i=0;isupp[i] = supp[i];\n for(int j=0;j= totnbins ) {\n fprintf(stderr, \"ERROR: In %s> index = %d must be in range [0, %d)\\n\", __FUNCTION__, index, totnbins);\n free_results_mocks_s_mu(results);\n free(supp);\n return EXIT_FAILURE;\n }\n results->npairs[index] = npairs[index];\n results->savg[index] = ZERO;\n results->weightavg[index] = ZERO;\n if(options->need_avg_sep) {\n results->savg[index] = savg[index];\n }\n if(need_weightavg) {\n results->weightavg[index] = weightavg[index];\n }\n }\n }\n for(int i=0;iprojpairs[i] = projpairs[i];\n for(int j=0;jprojpairs_tensor[i*nprojbins+j] = projpairs_tensor[i*nprojbins+j];\n }\n }\n free(supp);\n\n /* reset interrupt handlers to default */\n RESET_INTERRUPT_HANDLERS();\n reset_bin_refine_factors(options);\n\n if(options->c_api_timer) {\n struct timeval t1;\n gettimeofday(&t1, NULL);\n options->c_api_time = ADD_DIFF_TIME(t0, t1);\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "0cda749c5cdf450bb0175acf7b7aca87d156f069", "size": 33963, "ext": "c", "lang": "C", "max_stars_repo_path": "mocks/DDsmu_mocks/countpairs_s_mu_mocks_impl_double.c", "max_stars_repo_name": "kstoreyf/foo", "max_stars_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mocks/DDsmu_mocks/countpairs_s_mu_mocks_impl_double.c", "max_issues_repo_name": "kstoreyf/foo", "max_issues_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mocks/DDsmu_mocks/countpairs_s_mu_mocks_impl_double.c", "max_forks_repo_name": "kstoreyf/foo", "max_forks_repo_head_hexsha": "ff72167804f55c46486c3b35143c6da62cf2779a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9483944954, "max_line_length": 176, "alphanum_fraction": 0.5406177311, "num_tokens": 8333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5506073507867328, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2645550920294696}} {"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\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\n/* This file was automatically generated --- DO NOT EDIT */\n/* Generated on Mon Mar 8 17:46:56 EST 1999 */\n\n#include \n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -twiddleinv 32 */\n\n/*\n * This function contains 434 FP additions, 208 FP multiplications,\n * (or, 340 additions, 114 multiplications, 94 fused multiply/add),\n * 90 stack variables, and 128 memory accesses\n */\nstatic const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191);\nstatic const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812);\nstatic const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731);\nstatic const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618);\nstatic const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);\nstatic const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);\nstatic const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);\n\n/*\n * Generator Id's : \n * $Id: exprdag.ml,v 1.36 1999/02/19 17:22:11 athena Exp $\n * $Id: fft.ml,v 1.41 1999/02/19 17:22:13 athena Exp $\n * $Id: to_c.ml,v 1.24 1999/02/19 17:22:17 athena Exp $\n */\n\nvoid fftwi_twiddle_32(fftw_complex *A, const fftw_complex *W, int iostride, int m, int dist)\n{\n int i;\n fftw_complex *inout;\n inout = A;\n for (i = m; i > 0; i = i - 1, inout = inout + dist, W = W + 31) {\n\t fftw_real tmp19;\n\t fftw_real tmp387;\n\t fftw_real tmp472;\n\t fftw_real tmp486;\n\t fftw_real tmp442;\n\t fftw_real tmp456;\n\t fftw_real tmp191;\n\t fftw_real tmp303;\n\t fftw_real tmp161;\n\t fftw_real tmp403;\n\t fftw_real tmp276;\n\t fftw_real tmp316;\n\t fftw_real tmp372;\n\t fftw_real tmp400;\n\t fftw_real tmp259;\n\t fftw_real tmp319;\n\t fftw_real tmp42;\n\t fftw_real tmp455;\n\t fftw_real tmp201;\n\t fftw_real tmp304;\n\t fftw_real tmp390;\n\t fftw_real tmp437;\n\t fftw_real tmp196;\n\t fftw_real tmp305;\n\t fftw_real tmp184;\n\t fftw_real tmp401;\n\t fftw_real tmp375;\n\t fftw_real tmp404;\n\t fftw_real tmp270;\n\t fftw_real tmp317;\n\t fftw_real tmp279;\n\t fftw_real tmp320;\n\t fftw_real tmp66;\n\t fftw_real tmp395;\n\t fftw_real tmp224;\n\t fftw_real tmp312;\n\t fftw_real tmp357;\n\t fftw_real tmp396;\n\t fftw_real tmp219;\n\t fftw_real tmp311;\n\t fftw_real tmp114;\n\t fftw_real tmp410;\n\t fftw_real tmp249;\n\t fftw_real tmp323;\n\t fftw_real tmp363;\n\t fftw_real tmp407;\n\t fftw_real tmp232;\n\t fftw_real tmp326;\n\t fftw_real tmp89;\n\t fftw_real tmp393;\n\t fftw_real tmp213;\n\t fftw_real tmp309;\n\t fftw_real tmp354;\n\t fftw_real tmp392;\n\t fftw_real tmp208;\n\t fftw_real tmp308;\n\t fftw_real tmp137;\n\t fftw_real tmp408;\n\t fftw_real tmp366;\n\t fftw_real tmp411;\n\t fftw_real tmp243;\n\t fftw_real tmp324;\n\t fftw_real tmp252;\n\t fftw_real tmp327;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp1;\n\t fftw_real tmp440;\n\t fftw_real tmp6;\n\t fftw_real tmp439;\n\t fftw_real tmp12;\n\t fftw_real tmp188;\n\t fftw_real tmp17;\n\t fftw_real tmp189;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp1 = c_re(inout[0]);\n\t tmp440 = c_im(inout[0]);\n\t {\n\t\t fftw_real tmp3;\n\t\t fftw_real tmp5;\n\t\t fftw_real tmp2;\n\t\t fftw_real tmp4;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp3 = c_re(inout[16 * iostride]);\n\t\t tmp5 = c_im(inout[16 * iostride]);\n\t\t tmp2 = c_re(W[15]);\n\t\t tmp4 = c_im(W[15]);\n\t\t tmp6 = (tmp2 * tmp3) + (tmp4 * tmp5);\n\t\t tmp439 = (tmp2 * tmp5) - (tmp4 * tmp3);\n\t }\n\t {\n\t\t fftw_real tmp9;\n\t\t fftw_real tmp11;\n\t\t fftw_real tmp8;\n\t\t fftw_real tmp10;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp9 = c_re(inout[8 * iostride]);\n\t\t tmp11 = c_im(inout[8 * iostride]);\n\t\t tmp8 = c_re(W[7]);\n\t\t tmp10 = c_im(W[7]);\n\t\t tmp12 = (tmp8 * tmp9) + (tmp10 * tmp11);\n\t\t tmp188 = (tmp8 * tmp11) - (tmp10 * tmp9);\n\t }\n\t {\n\t\t fftw_real tmp14;\n\t\t fftw_real tmp16;\n\t\t fftw_real tmp13;\n\t\t fftw_real tmp15;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp14 = c_re(inout[24 * iostride]);\n\t\t tmp16 = c_im(inout[24 * iostride]);\n\t\t tmp13 = c_re(W[23]);\n\t\t tmp15 = c_im(W[23]);\n\t\t tmp17 = (tmp13 * tmp14) + (tmp15 * tmp16);\n\t\t tmp189 = (tmp13 * tmp16) - (tmp15 * tmp14);\n\t }\n\t {\n\t\t fftw_real tmp7;\n\t\t fftw_real tmp18;\n\t\t fftw_real tmp470;\n\t\t fftw_real tmp471;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp7 = tmp1 + tmp6;\n\t\t tmp18 = tmp12 + tmp17;\n\t\t tmp19 = tmp7 + tmp18;\n\t\t tmp387 = tmp7 - tmp18;\n\t\t tmp470 = tmp12 - tmp17;\n\t\t tmp471 = tmp440 - tmp439;\n\t\t tmp472 = tmp470 + tmp471;\n\t\t tmp486 = tmp471 - tmp470;\n\t }\n\t {\n\t\t fftw_real tmp438;\n\t\t fftw_real tmp441;\n\t\t fftw_real tmp187;\n\t\t fftw_real tmp190;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp438 = tmp188 + tmp189;\n\t\t tmp441 = tmp439 + tmp440;\n\t\t tmp442 = tmp438 + tmp441;\n\t\t tmp456 = tmp441 - tmp438;\n\t\t tmp187 = tmp1 - tmp6;\n\t\t tmp190 = tmp188 - tmp189;\n\t\t tmp191 = tmp187 - tmp190;\n\t\t tmp303 = tmp187 + tmp190;\n\t }\n\t }\n\t {\n\t fftw_real tmp143;\n\t fftw_real tmp272;\n\t fftw_real tmp159;\n\t fftw_real tmp257;\n\t fftw_real tmp148;\n\t fftw_real tmp273;\n\t fftw_real tmp154;\n\t fftw_real tmp256;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp140;\n\t\t fftw_real tmp142;\n\t\t fftw_real tmp139;\n\t\t fftw_real tmp141;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp140 = c_re(inout[31 * iostride]);\n\t\t tmp142 = c_im(inout[31 * iostride]);\n\t\t tmp139 = c_re(W[30]);\n\t\t tmp141 = c_im(W[30]);\n\t\t tmp143 = (tmp139 * tmp140) + (tmp141 * tmp142);\n\t\t tmp272 = (tmp139 * tmp142) - (tmp141 * tmp140);\n\t }\n\t {\n\t\t fftw_real tmp156;\n\t\t fftw_real tmp158;\n\t\t fftw_real tmp155;\n\t\t fftw_real tmp157;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp156 = c_re(inout[23 * iostride]);\n\t\t tmp158 = c_im(inout[23 * iostride]);\n\t\t tmp155 = c_re(W[22]);\n\t\t tmp157 = c_im(W[22]);\n\t\t tmp159 = (tmp155 * tmp156) + (tmp157 * tmp158);\n\t\t tmp257 = (tmp155 * tmp158) - (tmp157 * tmp156);\n\t }\n\t {\n\t\t fftw_real tmp145;\n\t\t fftw_real tmp147;\n\t\t fftw_real tmp144;\n\t\t fftw_real tmp146;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp145 = c_re(inout[15 * iostride]);\n\t\t tmp147 = c_im(inout[15 * iostride]);\n\t\t tmp144 = c_re(W[14]);\n\t\t tmp146 = c_im(W[14]);\n\t\t tmp148 = (tmp144 * tmp145) + (tmp146 * tmp147);\n\t\t tmp273 = (tmp144 * tmp147) - (tmp146 * tmp145);\n\t }\n\t {\n\t\t fftw_real tmp151;\n\t\t fftw_real tmp153;\n\t\t fftw_real tmp150;\n\t\t fftw_real tmp152;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp151 = c_re(inout[7 * iostride]);\n\t\t tmp153 = c_im(inout[7 * iostride]);\n\t\t tmp150 = c_re(W[6]);\n\t\t tmp152 = c_im(W[6]);\n\t\t tmp154 = (tmp150 * tmp151) + (tmp152 * tmp153);\n\t\t tmp256 = (tmp150 * tmp153) - (tmp152 * tmp151);\n\t }\n\t {\n\t\t fftw_real tmp149;\n\t\t fftw_real tmp160;\n\t\t fftw_real tmp274;\n\t\t fftw_real tmp275;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp149 = tmp143 + tmp148;\n\t\t tmp160 = tmp154 + tmp159;\n\t\t tmp161 = tmp149 + tmp160;\n\t\t tmp403 = tmp149 - tmp160;\n\t\t tmp274 = tmp272 - tmp273;\n\t\t tmp275 = tmp154 - tmp159;\n\t\t tmp276 = tmp274 + tmp275;\n\t\t tmp316 = tmp274 - tmp275;\n\t }\n\t {\n\t\t fftw_real tmp370;\n\t\t fftw_real tmp371;\n\t\t fftw_real tmp255;\n\t\t fftw_real tmp258;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp370 = tmp272 + tmp273;\n\t\t tmp371 = tmp256 + tmp257;\n\t\t tmp372 = tmp370 + tmp371;\n\t\t tmp400 = tmp370 - tmp371;\n\t\t tmp255 = tmp143 - tmp148;\n\t\t tmp258 = tmp256 - tmp257;\n\t\t tmp259 = tmp255 - tmp258;\n\t\t tmp319 = tmp255 + tmp258;\n\t }\n\t }\n\t {\n\t fftw_real tmp24;\n\t fftw_real tmp193;\n\t fftw_real tmp40;\n\t fftw_real tmp199;\n\t fftw_real tmp29;\n\t fftw_real tmp194;\n\t fftw_real tmp35;\n\t fftw_real tmp198;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp21;\n\t\t fftw_real tmp23;\n\t\t fftw_real tmp20;\n\t\t fftw_real tmp22;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp21 = c_re(inout[4 * iostride]);\n\t\t tmp23 = c_im(inout[4 * iostride]);\n\t\t tmp20 = c_re(W[3]);\n\t\t tmp22 = c_im(W[3]);\n\t\t tmp24 = (tmp20 * tmp21) + (tmp22 * tmp23);\n\t\t tmp193 = (tmp20 * tmp23) - (tmp22 * tmp21);\n\t }\n\t {\n\t\t fftw_real tmp37;\n\t\t fftw_real tmp39;\n\t\t fftw_real tmp36;\n\t\t fftw_real tmp38;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp37 = c_re(inout[12 * iostride]);\n\t\t tmp39 = c_im(inout[12 * iostride]);\n\t\t tmp36 = c_re(W[11]);\n\t\t tmp38 = c_im(W[11]);\n\t\t tmp40 = (tmp36 * tmp37) + (tmp38 * tmp39);\n\t\t tmp199 = (tmp36 * tmp39) - (tmp38 * tmp37);\n\t }\n\t {\n\t\t fftw_real tmp26;\n\t\t fftw_real tmp28;\n\t\t fftw_real tmp25;\n\t\t fftw_real tmp27;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp26 = c_re(inout[20 * iostride]);\n\t\t tmp28 = c_im(inout[20 * iostride]);\n\t\t tmp25 = c_re(W[19]);\n\t\t tmp27 = c_im(W[19]);\n\t\t tmp29 = (tmp25 * tmp26) + (tmp27 * tmp28);\n\t\t tmp194 = (tmp25 * tmp28) - (tmp27 * tmp26);\n\t }\n\t {\n\t\t fftw_real tmp32;\n\t\t fftw_real tmp34;\n\t\t fftw_real tmp31;\n\t\t fftw_real tmp33;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp32 = c_re(inout[28 * iostride]);\n\t\t tmp34 = c_im(inout[28 * iostride]);\n\t\t tmp31 = c_re(W[27]);\n\t\t tmp33 = c_im(W[27]);\n\t\t tmp35 = (tmp31 * tmp32) + (tmp33 * tmp34);\n\t\t tmp198 = (tmp31 * tmp34) - (tmp33 * tmp32);\n\t }\n\t {\n\t\t fftw_real tmp30;\n\t\t fftw_real tmp41;\n\t\t fftw_real tmp197;\n\t\t fftw_real tmp200;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp30 = tmp24 + tmp29;\n\t\t tmp41 = tmp35 + tmp40;\n\t\t tmp42 = tmp30 + tmp41;\n\t\t tmp455 = tmp30 - tmp41;\n\t\t tmp197 = tmp35 - tmp40;\n\t\t tmp200 = tmp198 - tmp199;\n\t\t tmp201 = tmp197 + tmp200;\n\t\t tmp304 = tmp200 - tmp197;\n\t }\n\t {\n\t\t fftw_real tmp388;\n\t\t fftw_real tmp389;\n\t\t fftw_real tmp192;\n\t\t fftw_real tmp195;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp388 = tmp198 + tmp199;\n\t\t tmp389 = tmp193 + tmp194;\n\t\t tmp390 = tmp388 - tmp389;\n\t\t tmp437 = tmp389 + tmp388;\n\t\t tmp192 = tmp24 - tmp29;\n\t\t tmp195 = tmp193 - tmp194;\n\t\t tmp196 = tmp192 - tmp195;\n\t\t tmp305 = tmp192 + tmp195;\n\t }\n\t }\n\t {\n\t fftw_real tmp166;\n\t fftw_real tmp261;\n\t fftw_real tmp171;\n\t fftw_real tmp262;\n\t fftw_real tmp260;\n\t fftw_real tmp263;\n\t fftw_real tmp177;\n\t fftw_real tmp266;\n\t fftw_real tmp182;\n\t fftw_real tmp267;\n\t fftw_real tmp265;\n\t fftw_real tmp268;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp163;\n\t\t fftw_real tmp165;\n\t\t fftw_real tmp162;\n\t\t fftw_real tmp164;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp163 = c_re(inout[3 * iostride]);\n\t\t tmp165 = c_im(inout[3 * iostride]);\n\t\t tmp162 = c_re(W[2]);\n\t\t tmp164 = c_im(W[2]);\n\t\t tmp166 = (tmp162 * tmp163) + (tmp164 * tmp165);\n\t\t tmp261 = (tmp162 * tmp165) - (tmp164 * tmp163);\n\t }\n\t {\n\t\t fftw_real tmp168;\n\t\t fftw_real tmp170;\n\t\t fftw_real tmp167;\n\t\t fftw_real tmp169;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp168 = c_re(inout[19 * iostride]);\n\t\t tmp170 = c_im(inout[19 * iostride]);\n\t\t tmp167 = c_re(W[18]);\n\t\t tmp169 = c_im(W[18]);\n\t\t tmp171 = (tmp167 * tmp168) + (tmp169 * tmp170);\n\t\t tmp262 = (tmp167 * tmp170) - (tmp169 * tmp168);\n\t }\n\t tmp260 = tmp166 - tmp171;\n\t tmp263 = tmp261 - tmp262;\n\t {\n\t\t fftw_real tmp174;\n\t\t fftw_real tmp176;\n\t\t fftw_real tmp173;\n\t\t fftw_real tmp175;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp174 = c_re(inout[27 * iostride]);\n\t\t tmp176 = c_im(inout[27 * iostride]);\n\t\t tmp173 = c_re(W[26]);\n\t\t tmp175 = c_im(W[26]);\n\t\t tmp177 = (tmp173 * tmp174) + (tmp175 * tmp176);\n\t\t tmp266 = (tmp173 * tmp176) - (tmp175 * tmp174);\n\t }\n\t {\n\t\t fftw_real tmp179;\n\t\t fftw_real tmp181;\n\t\t fftw_real tmp178;\n\t\t fftw_real tmp180;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp179 = c_re(inout[11 * iostride]);\n\t\t tmp181 = c_im(inout[11 * iostride]);\n\t\t tmp178 = c_re(W[10]);\n\t\t tmp180 = c_im(W[10]);\n\t\t tmp182 = (tmp178 * tmp179) + (tmp180 * tmp181);\n\t\t tmp267 = (tmp178 * tmp181) - (tmp180 * tmp179);\n\t }\n\t tmp265 = tmp177 - tmp182;\n\t tmp268 = tmp266 - tmp267;\n\t {\n\t\t fftw_real tmp172;\n\t\t fftw_real tmp183;\n\t\t fftw_real tmp373;\n\t\t fftw_real tmp374;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp172 = tmp166 + tmp171;\n\t\t tmp183 = tmp177 + tmp182;\n\t\t tmp184 = tmp172 + tmp183;\n\t\t tmp401 = tmp172 - tmp183;\n\t\t tmp373 = tmp261 + tmp262;\n\t\t tmp374 = tmp266 + tmp267;\n\t\t tmp375 = tmp373 + tmp374;\n\t\t tmp404 = tmp374 - tmp373;\n\t }\n\t {\n\t\t fftw_real tmp264;\n\t\t fftw_real tmp269;\n\t\t fftw_real tmp277;\n\t\t fftw_real tmp278;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp264 = tmp260 - tmp263;\n\t\t tmp269 = tmp265 + tmp268;\n\t\t tmp270 = K707106781 * (tmp264 + tmp269);\n\t\t tmp317 = K707106781 * (tmp264 - tmp269);\n\t\t tmp277 = tmp260 + tmp263;\n\t\t tmp278 = tmp268 - tmp265;\n\t\t tmp279 = K707106781 * (tmp277 + tmp278);\n\t\t tmp320 = K707106781 * (tmp278 - tmp277);\n\t }\n\t }\n\t {\n\t fftw_real tmp48;\n\t fftw_real tmp215;\n\t fftw_real tmp64;\n\t fftw_real tmp222;\n\t fftw_real tmp53;\n\t fftw_real tmp216;\n\t fftw_real tmp59;\n\t fftw_real tmp221;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp45;\n\t\t fftw_real tmp47;\n\t\t fftw_real tmp44;\n\t\t fftw_real tmp46;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp45 = c_re(inout[2 * iostride]);\n\t\t tmp47 = c_im(inout[2 * iostride]);\n\t\t tmp44 = c_re(W[1]);\n\t\t tmp46 = c_im(W[1]);\n\t\t tmp48 = (tmp44 * tmp45) + (tmp46 * tmp47);\n\t\t tmp215 = (tmp44 * tmp47) - (tmp46 * tmp45);\n\t }\n\t {\n\t\t fftw_real tmp61;\n\t\t fftw_real tmp63;\n\t\t fftw_real tmp60;\n\t\t fftw_real tmp62;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp61 = c_re(inout[26 * iostride]);\n\t\t tmp63 = c_im(inout[26 * iostride]);\n\t\t tmp60 = c_re(W[25]);\n\t\t tmp62 = c_im(W[25]);\n\t\t tmp64 = (tmp60 * tmp61) + (tmp62 * tmp63);\n\t\t tmp222 = (tmp60 * tmp63) - (tmp62 * tmp61);\n\t }\n\t {\n\t\t fftw_real tmp50;\n\t\t fftw_real tmp52;\n\t\t fftw_real tmp49;\n\t\t fftw_real tmp51;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp50 = c_re(inout[18 * iostride]);\n\t\t tmp52 = c_im(inout[18 * iostride]);\n\t\t tmp49 = c_re(W[17]);\n\t\t tmp51 = c_im(W[17]);\n\t\t tmp53 = (tmp49 * tmp50) + (tmp51 * tmp52);\n\t\t tmp216 = (tmp49 * tmp52) - (tmp51 * tmp50);\n\t }\n\t {\n\t\t fftw_real tmp56;\n\t\t fftw_real tmp58;\n\t\t fftw_real tmp55;\n\t\t fftw_real tmp57;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp56 = c_re(inout[10 * iostride]);\n\t\t tmp58 = c_im(inout[10 * iostride]);\n\t\t tmp55 = c_re(W[9]);\n\t\t tmp57 = c_im(W[9]);\n\t\t tmp59 = (tmp55 * tmp56) + (tmp57 * tmp58);\n\t\t tmp221 = (tmp55 * tmp58) - (tmp57 * tmp56);\n\t }\n\t {\n\t\t fftw_real tmp54;\n\t\t fftw_real tmp65;\n\t\t fftw_real tmp220;\n\t\t fftw_real tmp223;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp54 = tmp48 + tmp53;\n\t\t tmp65 = tmp59 + tmp64;\n\t\t tmp66 = tmp54 + tmp65;\n\t\t tmp395 = tmp54 - tmp65;\n\t\t tmp220 = tmp48 - tmp53;\n\t\t tmp223 = tmp221 - tmp222;\n\t\t tmp224 = tmp220 - tmp223;\n\t\t tmp312 = tmp220 + tmp223;\n\t }\n\t {\n\t\t fftw_real tmp355;\n\t\t fftw_real tmp356;\n\t\t fftw_real tmp217;\n\t\t fftw_real tmp218;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp355 = tmp215 + tmp216;\n\t\t tmp356 = tmp221 + tmp222;\n\t\t tmp357 = tmp355 + tmp356;\n\t\t tmp396 = tmp355 - tmp356;\n\t\t tmp217 = tmp215 - tmp216;\n\t\t tmp218 = tmp59 - tmp64;\n\t\t tmp219 = tmp217 + tmp218;\n\t\t tmp311 = tmp217 - tmp218;\n\t }\n\t }\n\t {\n\t fftw_real tmp96;\n\t fftw_real tmp245;\n\t fftw_real tmp112;\n\t fftw_real tmp230;\n\t fftw_real tmp101;\n\t fftw_real tmp246;\n\t fftw_real tmp107;\n\t fftw_real tmp229;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp93;\n\t\t fftw_real tmp95;\n\t\t fftw_real tmp92;\n\t\t fftw_real tmp94;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp93 = c_re(inout[iostride]);\n\t\t tmp95 = c_im(inout[iostride]);\n\t\t tmp92 = c_re(W[0]);\n\t\t tmp94 = c_im(W[0]);\n\t\t tmp96 = (tmp92 * tmp93) + (tmp94 * tmp95);\n\t\t tmp245 = (tmp92 * tmp95) - (tmp94 * tmp93);\n\t }\n\t {\n\t\t fftw_real tmp109;\n\t\t fftw_real tmp111;\n\t\t fftw_real tmp108;\n\t\t fftw_real tmp110;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp109 = c_re(inout[25 * iostride]);\n\t\t tmp111 = c_im(inout[25 * iostride]);\n\t\t tmp108 = c_re(W[24]);\n\t\t tmp110 = c_im(W[24]);\n\t\t tmp112 = (tmp108 * tmp109) + (tmp110 * tmp111);\n\t\t tmp230 = (tmp108 * tmp111) - (tmp110 * tmp109);\n\t }\n\t {\n\t\t fftw_real tmp98;\n\t\t fftw_real tmp100;\n\t\t fftw_real tmp97;\n\t\t fftw_real tmp99;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp98 = c_re(inout[17 * iostride]);\n\t\t tmp100 = c_im(inout[17 * iostride]);\n\t\t tmp97 = c_re(W[16]);\n\t\t tmp99 = c_im(W[16]);\n\t\t tmp101 = (tmp97 * tmp98) + (tmp99 * tmp100);\n\t\t tmp246 = (tmp97 * tmp100) - (tmp99 * tmp98);\n\t }\n\t {\n\t\t fftw_real tmp104;\n\t\t fftw_real tmp106;\n\t\t fftw_real tmp103;\n\t\t fftw_real tmp105;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp104 = c_re(inout[9 * iostride]);\n\t\t tmp106 = c_im(inout[9 * iostride]);\n\t\t tmp103 = c_re(W[8]);\n\t\t tmp105 = c_im(W[8]);\n\t\t tmp107 = (tmp103 * tmp104) + (tmp105 * tmp106);\n\t\t tmp229 = (tmp103 * tmp106) - (tmp105 * tmp104);\n\t }\n\t {\n\t\t fftw_real tmp102;\n\t\t fftw_real tmp113;\n\t\t fftw_real tmp247;\n\t\t fftw_real tmp248;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp102 = tmp96 + tmp101;\n\t\t tmp113 = tmp107 + tmp112;\n\t\t tmp114 = tmp102 + tmp113;\n\t\t tmp410 = tmp102 - tmp113;\n\t\t tmp247 = tmp245 - tmp246;\n\t\t tmp248 = tmp107 - tmp112;\n\t\t tmp249 = tmp247 + tmp248;\n\t\t tmp323 = tmp247 - tmp248;\n\t }\n\t {\n\t\t fftw_real tmp361;\n\t\t fftw_real tmp362;\n\t\t fftw_real tmp228;\n\t\t fftw_real tmp231;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp361 = tmp245 + tmp246;\n\t\t tmp362 = tmp229 + tmp230;\n\t\t tmp363 = tmp361 + tmp362;\n\t\t tmp407 = tmp361 - tmp362;\n\t\t tmp228 = tmp96 - tmp101;\n\t\t tmp231 = tmp229 - tmp230;\n\t\t tmp232 = tmp228 - tmp231;\n\t\t tmp326 = tmp228 + tmp231;\n\t }\n\t }\n\t {\n\t fftw_real tmp71;\n\t fftw_real tmp204;\n\t fftw_real tmp87;\n\t fftw_real tmp211;\n\t fftw_real tmp76;\n\t fftw_real tmp205;\n\t fftw_real tmp82;\n\t fftw_real tmp210;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp68;\n\t\t fftw_real tmp70;\n\t\t fftw_real tmp67;\n\t\t fftw_real tmp69;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp68 = c_re(inout[30 * iostride]);\n\t\t tmp70 = c_im(inout[30 * iostride]);\n\t\t tmp67 = c_re(W[29]);\n\t\t tmp69 = c_im(W[29]);\n\t\t tmp71 = (tmp67 * tmp68) + (tmp69 * tmp70);\n\t\t tmp204 = (tmp67 * tmp70) - (tmp69 * tmp68);\n\t }\n\t {\n\t\t fftw_real tmp84;\n\t\t fftw_real tmp86;\n\t\t fftw_real tmp83;\n\t\t fftw_real tmp85;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp84 = c_re(inout[22 * iostride]);\n\t\t tmp86 = c_im(inout[22 * iostride]);\n\t\t tmp83 = c_re(W[21]);\n\t\t tmp85 = c_im(W[21]);\n\t\t tmp87 = (tmp83 * tmp84) + (tmp85 * tmp86);\n\t\t tmp211 = (tmp83 * tmp86) - (tmp85 * tmp84);\n\t }\n\t {\n\t\t fftw_real tmp73;\n\t\t fftw_real tmp75;\n\t\t fftw_real tmp72;\n\t\t fftw_real tmp74;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp73 = c_re(inout[14 * iostride]);\n\t\t tmp75 = c_im(inout[14 * iostride]);\n\t\t tmp72 = c_re(W[13]);\n\t\t tmp74 = c_im(W[13]);\n\t\t tmp76 = (tmp72 * tmp73) + (tmp74 * tmp75);\n\t\t tmp205 = (tmp72 * tmp75) - (tmp74 * tmp73);\n\t }\n\t {\n\t\t fftw_real tmp79;\n\t\t fftw_real tmp81;\n\t\t fftw_real tmp78;\n\t\t fftw_real tmp80;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp79 = c_re(inout[6 * iostride]);\n\t\t tmp81 = c_im(inout[6 * iostride]);\n\t\t tmp78 = c_re(W[5]);\n\t\t tmp80 = c_im(W[5]);\n\t\t tmp82 = (tmp78 * tmp79) + (tmp80 * tmp81);\n\t\t tmp210 = (tmp78 * tmp81) - (tmp80 * tmp79);\n\t }\n\t {\n\t\t fftw_real tmp77;\n\t\t fftw_real tmp88;\n\t\t fftw_real tmp209;\n\t\t fftw_real tmp212;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp77 = tmp71 + tmp76;\n\t\t tmp88 = tmp82 + tmp87;\n\t\t tmp89 = tmp77 + tmp88;\n\t\t tmp393 = tmp77 - tmp88;\n\t\t tmp209 = tmp71 - tmp76;\n\t\t tmp212 = tmp210 - tmp211;\n\t\t tmp213 = tmp209 - tmp212;\n\t\t tmp309 = tmp209 + tmp212;\n\t }\n\t {\n\t\t fftw_real tmp352;\n\t\t fftw_real tmp353;\n\t\t fftw_real tmp206;\n\t\t fftw_real tmp207;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp352 = tmp204 + tmp205;\n\t\t tmp353 = tmp210 + tmp211;\n\t\t tmp354 = tmp352 + tmp353;\n\t\t tmp392 = tmp352 - tmp353;\n\t\t tmp206 = tmp204 - tmp205;\n\t\t tmp207 = tmp82 - tmp87;\n\t\t tmp208 = tmp206 + tmp207;\n\t\t tmp308 = tmp206 - tmp207;\n\t }\n\t }\n\t {\n\t fftw_real tmp119;\n\t fftw_real tmp234;\n\t fftw_real tmp124;\n\t fftw_real tmp235;\n\t fftw_real tmp233;\n\t fftw_real tmp236;\n\t fftw_real tmp130;\n\t fftw_real tmp239;\n\t fftw_real tmp135;\n\t fftw_real tmp240;\n\t fftw_real tmp238;\n\t fftw_real tmp241;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp116;\n\t\t fftw_real tmp118;\n\t\t fftw_real tmp115;\n\t\t fftw_real tmp117;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp116 = c_re(inout[5 * iostride]);\n\t\t tmp118 = c_im(inout[5 * iostride]);\n\t\t tmp115 = c_re(W[4]);\n\t\t tmp117 = c_im(W[4]);\n\t\t tmp119 = (tmp115 * tmp116) + (tmp117 * tmp118);\n\t\t tmp234 = (tmp115 * tmp118) - (tmp117 * tmp116);\n\t }\n\t {\n\t\t fftw_real tmp121;\n\t\t fftw_real tmp123;\n\t\t fftw_real tmp120;\n\t\t fftw_real tmp122;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp121 = c_re(inout[21 * iostride]);\n\t\t tmp123 = c_im(inout[21 * iostride]);\n\t\t tmp120 = c_re(W[20]);\n\t\t tmp122 = c_im(W[20]);\n\t\t tmp124 = (tmp120 * tmp121) + (tmp122 * tmp123);\n\t\t tmp235 = (tmp120 * tmp123) - (tmp122 * tmp121);\n\t }\n\t tmp233 = tmp119 - tmp124;\n\t tmp236 = tmp234 - tmp235;\n\t {\n\t\t fftw_real tmp127;\n\t\t fftw_real tmp129;\n\t\t fftw_real tmp126;\n\t\t fftw_real tmp128;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp127 = c_re(inout[29 * iostride]);\n\t\t tmp129 = c_im(inout[29 * iostride]);\n\t\t tmp126 = c_re(W[28]);\n\t\t tmp128 = c_im(W[28]);\n\t\t tmp130 = (tmp126 * tmp127) + (tmp128 * tmp129);\n\t\t tmp239 = (tmp126 * tmp129) - (tmp128 * tmp127);\n\t }\n\t {\n\t\t fftw_real tmp132;\n\t\t fftw_real tmp134;\n\t\t fftw_real tmp131;\n\t\t fftw_real tmp133;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp132 = c_re(inout[13 * iostride]);\n\t\t tmp134 = c_im(inout[13 * iostride]);\n\t\t tmp131 = c_re(W[12]);\n\t\t tmp133 = c_im(W[12]);\n\t\t tmp135 = (tmp131 * tmp132) + (tmp133 * tmp134);\n\t\t tmp240 = (tmp131 * tmp134) - (tmp133 * tmp132);\n\t }\n\t tmp238 = tmp130 - tmp135;\n\t tmp241 = tmp239 - tmp240;\n\t {\n\t\t fftw_real tmp125;\n\t\t fftw_real tmp136;\n\t\t fftw_real tmp364;\n\t\t fftw_real tmp365;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp125 = tmp119 + tmp124;\n\t\t tmp136 = tmp130 + tmp135;\n\t\t tmp137 = tmp125 + tmp136;\n\t\t tmp408 = tmp125 - tmp136;\n\t\t tmp364 = tmp234 + tmp235;\n\t\t tmp365 = tmp239 + tmp240;\n\t\t tmp366 = tmp364 + tmp365;\n\t\t tmp411 = tmp365 - tmp364;\n\t }\n\t {\n\t\t fftw_real tmp237;\n\t\t fftw_real tmp242;\n\t\t fftw_real tmp250;\n\t\t fftw_real tmp251;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp237 = tmp233 - tmp236;\n\t\t tmp242 = tmp238 + tmp241;\n\t\t tmp243 = K707106781 * (tmp237 + tmp242);\n\t\t tmp324 = K707106781 * (tmp237 - tmp242);\n\t\t tmp250 = tmp233 + tmp236;\n\t\t tmp251 = tmp241 - tmp238;\n\t\t tmp252 = K707106781 * (tmp250 + tmp251);\n\t\t tmp327 = K707106781 * (tmp251 - tmp250);\n\t }\n\t }\n\t {\n\t fftw_real tmp91;\n\t fftw_real tmp383;\n\t fftw_real tmp444;\n\t fftw_real tmp446;\n\t fftw_real tmp186;\n\t fftw_real tmp445;\n\t fftw_real tmp386;\n\t fftw_real tmp435;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp43;\n\t\t fftw_real tmp90;\n\t\t fftw_real tmp436;\n\t\t fftw_real tmp443;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp43 = tmp19 + tmp42;\n\t\t tmp90 = tmp66 + tmp89;\n\t\t tmp91 = tmp43 + tmp90;\n\t\t tmp383 = tmp43 - tmp90;\n\t\t tmp436 = tmp357 + tmp354;\n\t\t tmp443 = tmp437 + tmp442;\n\t\t tmp444 = tmp436 + tmp443;\n\t\t tmp446 = tmp443 - tmp436;\n\t }\n\t {\n\t\t fftw_real tmp138;\n\t\t fftw_real tmp185;\n\t\t fftw_real tmp384;\n\t\t fftw_real tmp385;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp138 = tmp114 + tmp137;\n\t\t tmp185 = tmp161 + tmp184;\n\t\t tmp186 = tmp138 + tmp185;\n\t\t tmp445 = tmp138 - tmp185;\n\t\t tmp384 = tmp372 + tmp375;\n\t\t tmp385 = tmp363 + tmp366;\n\t\t tmp386 = tmp384 - tmp385;\n\t\t tmp435 = tmp385 + tmp384;\n\t }\n\t c_re(inout[16 * iostride]) = tmp91 - tmp186;\n\t c_re(inout[0]) = tmp91 + tmp186;\n\t c_re(inout[24 * iostride]) = tmp383 - tmp386;\n\t c_re(inout[8 * iostride]) = tmp383 + tmp386;\n\t c_im(inout[0]) = tmp435 + tmp444;\n\t c_im(inout[16 * iostride]) = tmp444 - tmp435;\n\t c_im(inout[8 * iostride]) = tmp445 + tmp446;\n\t c_im(inout[24 * iostride]) = tmp446 - tmp445;\n\t }\n\t {\n\t fftw_real tmp359;\n\t fftw_real tmp379;\n\t fftw_real tmp450;\n\t fftw_real tmp452;\n\t fftw_real tmp368;\n\t fftw_real tmp381;\n\t fftw_real tmp377;\n\t fftw_real tmp380;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp351;\n\t\t fftw_real tmp358;\n\t\t fftw_real tmp448;\n\t\t fftw_real tmp449;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp351 = tmp19 - tmp42;\n\t\t tmp358 = tmp354 - tmp357;\n\t\t tmp359 = tmp351 + tmp358;\n\t\t tmp379 = tmp351 - tmp358;\n\t\t tmp448 = tmp66 - tmp89;\n\t\t tmp449 = tmp442 - tmp437;\n\t\t tmp450 = tmp448 + tmp449;\n\t\t tmp452 = tmp449 - tmp448;\n\t }\n\t {\n\t\t fftw_real tmp360;\n\t\t fftw_real tmp367;\n\t\t fftw_real tmp369;\n\t\t fftw_real tmp376;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp360 = tmp114 - tmp137;\n\t\t tmp367 = tmp363 - tmp366;\n\t\t tmp368 = tmp360 - tmp367;\n\t\t tmp381 = tmp360 + tmp367;\n\t\t tmp369 = tmp161 - tmp184;\n\t\t tmp376 = tmp372 - tmp375;\n\t\t tmp377 = tmp369 + tmp376;\n\t\t tmp380 = tmp376 - tmp369;\n\t }\n\t {\n\t\t fftw_real tmp378;\n\t\t fftw_real tmp451;\n\t\t fftw_real tmp382;\n\t\t fftw_real tmp447;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp378 = K707106781 * (tmp368 + tmp377);\n\t\t c_re(inout[20 * iostride]) = tmp359 - tmp378;\n\t\t c_re(inout[4 * iostride]) = tmp359 + tmp378;\n\t\t tmp451 = K707106781 * (tmp368 - tmp377);\n\t\t c_im(inout[12 * iostride]) = tmp451 + tmp452;\n\t\t c_im(inout[28 * iostride]) = tmp452 - tmp451;\n\t\t tmp382 = K707106781 * (tmp380 - tmp381);\n\t\t c_re(inout[28 * iostride]) = tmp379 - tmp382;\n\t\t c_re(inout[12 * iostride]) = tmp379 + tmp382;\n\t\t tmp447 = K707106781 * (tmp381 + tmp380);\n\t\t c_im(inout[4 * iostride]) = tmp447 + tmp450;\n\t\t c_im(inout[20 * iostride]) = tmp450 - tmp447;\n\t }\n\t }\n\t {\n\t fftw_real tmp391;\n\t fftw_real tmp419;\n\t fftw_real tmp398;\n\t fftw_real tmp454;\n\t fftw_real tmp422;\n\t fftw_real tmp462;\n\t fftw_real tmp406;\n\t fftw_real tmp417;\n\t fftw_real tmp457;\n\t fftw_real tmp463;\n\t fftw_real tmp426;\n\t fftw_real tmp433;\n\t fftw_real tmp413;\n\t fftw_real tmp416;\n\t fftw_real tmp429;\n\t fftw_real tmp432;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp394;\n\t\t fftw_real tmp397;\n\t\t fftw_real tmp424;\n\t\t fftw_real tmp425;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp391 = tmp387 - tmp390;\n\t\t tmp419 = tmp387 + tmp390;\n\t\t tmp394 = tmp392 - tmp393;\n\t\t tmp397 = tmp395 + tmp396;\n\t\t tmp398 = K707106781 * (tmp394 - tmp397);\n\t\t tmp454 = K707106781 * (tmp397 + tmp394);\n\t\t {\n\t\t\t fftw_real tmp420;\n\t\t\t fftw_real tmp421;\n\t\t\t fftw_real tmp402;\n\t\t\t fftw_real tmp405;\n\t\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t\t tmp420 = tmp395 - tmp396;\n\t\t\t tmp421 = tmp393 + tmp392;\n\t\t\t tmp422 = K707106781 * (tmp420 + tmp421);\n\t\t\t tmp462 = K707106781 * (tmp420 - tmp421);\n\t\t\t tmp402 = tmp400 - tmp401;\n\t\t\t tmp405 = tmp403 - tmp404;\n\t\t\t tmp406 = (K382683432 * tmp402) - (K923879532 * tmp405);\n\t\t\t tmp417 = (K923879532 * tmp402) + (K382683432 * tmp405);\n\t\t }\n\t\t tmp457 = tmp455 + tmp456;\n\t\t tmp463 = tmp456 - tmp455;\n\t\t tmp424 = tmp400 + tmp401;\n\t\t tmp425 = tmp403 + tmp404;\n\t\t tmp426 = (K923879532 * tmp424) - (K382683432 * tmp425);\n\t\t tmp433 = (K382683432 * tmp424) + (K923879532 * tmp425);\n\t\t {\n\t\t\t fftw_real tmp409;\n\t\t\t fftw_real tmp412;\n\t\t\t fftw_real tmp427;\n\t\t\t fftw_real tmp428;\n\t\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t\t tmp409 = tmp407 - tmp408;\n\t\t\t tmp412 = tmp410 - tmp411;\n\t\t\t tmp413 = (K382683432 * tmp409) + (K923879532 * tmp412);\n\t\t\t tmp416 = (K382683432 * tmp412) - (K923879532 * tmp409);\n\t\t\t tmp427 = tmp407 + tmp408;\n\t\t\t tmp428 = tmp410 + tmp411;\n\t\t\t tmp429 = (K923879532 * tmp427) + (K382683432 * tmp428);\n\t\t\t tmp432 = (K923879532 * tmp428) - (K382683432 * tmp427);\n\t\t }\n\t }\n\t {\n\t\t fftw_real tmp399;\n\t\t fftw_real tmp414;\n\t\t fftw_real tmp415;\n\t\t fftw_real tmp418;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp399 = tmp391 - tmp398;\n\t\t tmp414 = tmp406 - tmp413;\n\t\t c_re(inout[30 * iostride]) = tmp399 - tmp414;\n\t\t c_re(inout[14 * iostride]) = tmp399 + tmp414;\n\t\t tmp415 = tmp391 + tmp398;\n\t\t tmp418 = tmp416 + tmp417;\n\t\t c_re(inout[22 * iostride]) = tmp415 - tmp418;\n\t\t c_re(inout[6 * iostride]) = tmp415 + tmp418;\n\t }\n\t {\n\t\t fftw_real tmp465;\n\t\t fftw_real tmp466;\n\t\t fftw_real tmp461;\n\t\t fftw_real tmp464;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp465 = tmp416 - tmp417;\n\t\t tmp466 = tmp463 - tmp462;\n\t\t c_im(inout[14 * iostride]) = tmp465 + tmp466;\n\t\t c_im(inout[30 * iostride]) = tmp466 - tmp465;\n\t\t tmp461 = tmp413 + tmp406;\n\t\t tmp464 = tmp462 + tmp463;\n\t\t c_im(inout[6 * iostride]) = tmp461 + tmp464;\n\t\t c_im(inout[22 * iostride]) = tmp464 - tmp461;\n\t }\n\t {\n\t\t fftw_real tmp423;\n\t\t fftw_real tmp430;\n\t\t fftw_real tmp431;\n\t\t fftw_real tmp434;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp423 = tmp419 - tmp422;\n\t\t tmp430 = tmp426 - tmp429;\n\t\t c_re(inout[26 * iostride]) = tmp423 - tmp430;\n\t\t c_re(inout[10 * iostride]) = tmp423 + tmp430;\n\t\t tmp431 = tmp419 + tmp422;\n\t\t tmp434 = tmp432 + tmp433;\n\t\t c_re(inout[18 * iostride]) = tmp431 - tmp434;\n\t\t c_re(inout[2 * iostride]) = tmp431 + tmp434;\n\t }\n\t {\n\t\t fftw_real tmp459;\n\t\t fftw_real tmp460;\n\t\t fftw_real tmp453;\n\t\t fftw_real tmp458;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp459 = tmp432 - tmp433;\n\t\t tmp460 = tmp457 - tmp454;\n\t\t c_im(inout[10 * iostride]) = tmp459 + tmp460;\n\t\t c_im(inout[26 * iostride]) = tmp460 - tmp459;\n\t\t tmp453 = tmp429 + tmp426;\n\t\t tmp458 = tmp454 + tmp457;\n\t\t c_im(inout[2 * iostride]) = tmp453 + tmp458;\n\t\t c_im(inout[18 * iostride]) = tmp458 - tmp453;\n\t }\n\t }\n\t {\n\t fftw_real tmp307;\n\t fftw_real tmp335;\n\t fftw_real tmp338;\n\t fftw_real tmp492;\n\t fftw_real tmp487;\n\t fftw_real tmp493;\n\t fftw_real tmp314;\n\t fftw_real tmp484;\n\t fftw_real tmp322;\n\t fftw_real tmp333;\n\t fftw_real tmp342;\n\t fftw_real tmp349;\n\t fftw_real tmp329;\n\t fftw_real tmp332;\n\t fftw_real tmp345;\n\t fftw_real tmp348;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp306;\n\t\t fftw_real tmp336;\n\t\t fftw_real tmp337;\n\t\t fftw_real tmp485;\n\t\t fftw_real tmp310;\n\t\t fftw_real tmp313;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp306 = K707106781 * (tmp304 - tmp305);\n\t\t tmp307 = tmp303 - tmp306;\n\t\t tmp335 = tmp303 + tmp306;\n\t\t tmp336 = (K382683432 * tmp312) - (K923879532 * tmp311);\n\t\t tmp337 = (K923879532 * tmp308) + (K382683432 * tmp309);\n\t\t tmp338 = tmp336 + tmp337;\n\t\t tmp492 = tmp336 - tmp337;\n\t\t tmp485 = K707106781 * (tmp196 - tmp201);\n\t\t tmp487 = tmp485 + tmp486;\n\t\t tmp493 = tmp486 - tmp485;\n\t\t tmp310 = (K382683432 * tmp308) - (K923879532 * tmp309);\n\t\t tmp313 = (K382683432 * tmp311) + (K923879532 * tmp312);\n\t\t tmp314 = tmp310 - tmp313;\n\t\t tmp484 = tmp313 + tmp310;\n\t }\n\t {\n\t\t fftw_real tmp318;\n\t\t fftw_real tmp321;\n\t\t fftw_real tmp340;\n\t\t fftw_real tmp341;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp318 = tmp316 - tmp317;\n\t\t tmp321 = tmp319 - tmp320;\n\t\t tmp322 = (K195090322 * tmp318) - (K980785280 * tmp321);\n\t\t tmp333 = (K980785280 * tmp318) + (K195090322 * tmp321);\n\t\t tmp340 = tmp316 + tmp317;\n\t\t tmp341 = tmp319 + tmp320;\n\t\t tmp342 = (K831469612 * tmp340) - (K555570233 * tmp341);\n\t\t tmp349 = (K555570233 * tmp340) + (K831469612 * tmp341);\n\t }\n\t {\n\t\t fftw_real tmp325;\n\t\t fftw_real tmp328;\n\t\t fftw_real tmp343;\n\t\t fftw_real tmp344;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp325 = tmp323 - tmp324;\n\t\t tmp328 = tmp326 - tmp327;\n\t\t tmp329 = (K195090322 * tmp325) + (K980785280 * tmp328);\n\t\t tmp332 = (K195090322 * tmp328) - (K980785280 * tmp325);\n\t\t tmp343 = tmp323 + tmp324;\n\t\t tmp344 = tmp326 + tmp327;\n\t\t tmp345 = (K831469612 * tmp343) + (K555570233 * tmp344);\n\t\t tmp348 = (K831469612 * tmp344) - (K555570233 * tmp343);\n\t }\n\t {\n\t\t fftw_real tmp315;\n\t\t fftw_real tmp330;\n\t\t fftw_real tmp331;\n\t\t fftw_real tmp334;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp315 = tmp307 - tmp314;\n\t\t tmp330 = tmp322 - tmp329;\n\t\t c_re(inout[31 * iostride]) = tmp315 - tmp330;\n\t\t c_re(inout[15 * iostride]) = tmp315 + tmp330;\n\t\t tmp331 = tmp307 + tmp314;\n\t\t tmp334 = tmp332 + tmp333;\n\t\t c_re(inout[23 * iostride]) = tmp331 - tmp334;\n\t\t c_re(inout[7 * iostride]) = tmp331 + tmp334;\n\t }\n\t {\n\t\t fftw_real tmp495;\n\t\t fftw_real tmp496;\n\t\t fftw_real tmp491;\n\t\t fftw_real tmp494;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp495 = tmp332 - tmp333;\n\t\t tmp496 = tmp493 - tmp492;\n\t\t c_im(inout[15 * iostride]) = tmp495 + tmp496;\n\t\t c_im(inout[31 * iostride]) = tmp496 - tmp495;\n\t\t tmp491 = tmp329 + tmp322;\n\t\t tmp494 = tmp492 + tmp493;\n\t\t c_im(inout[7 * iostride]) = tmp491 + tmp494;\n\t\t c_im(inout[23 * iostride]) = tmp494 - tmp491;\n\t }\n\t {\n\t\t fftw_real tmp339;\n\t\t fftw_real tmp346;\n\t\t fftw_real tmp347;\n\t\t fftw_real tmp350;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp339 = tmp335 - tmp338;\n\t\t tmp346 = tmp342 - tmp345;\n\t\t c_re(inout[27 * iostride]) = tmp339 - tmp346;\n\t\t c_re(inout[11 * iostride]) = tmp339 + tmp346;\n\t\t tmp347 = tmp335 + tmp338;\n\t\t tmp350 = tmp348 + tmp349;\n\t\t c_re(inout[19 * iostride]) = tmp347 - tmp350;\n\t\t c_re(inout[3 * iostride]) = tmp347 + tmp350;\n\t }\n\t {\n\t\t fftw_real tmp489;\n\t\t fftw_real tmp490;\n\t\t fftw_real tmp483;\n\t\t fftw_real tmp488;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp489 = tmp348 - tmp349;\n\t\t tmp490 = tmp487 - tmp484;\n\t\t c_im(inout[11 * iostride]) = tmp489 + tmp490;\n\t\t c_im(inout[27 * iostride]) = tmp490 - tmp489;\n\t\t tmp483 = tmp345 + tmp342;\n\t\t tmp488 = tmp484 + tmp487;\n\t\t c_im(inout[3 * iostride]) = tmp483 + tmp488;\n\t\t c_im(inout[19 * iostride]) = tmp488 - tmp483;\n\t }\n\t }\n\t {\n\t fftw_real tmp203;\n\t fftw_real tmp287;\n\t fftw_real tmp290;\n\t fftw_real tmp478;\n\t fftw_real tmp473;\n\t fftw_real tmp479;\n\t fftw_real tmp226;\n\t fftw_real tmp468;\n\t fftw_real tmp254;\n\t fftw_real tmp285;\n\t fftw_real tmp294;\n\t fftw_real tmp301;\n\t fftw_real tmp281;\n\t fftw_real tmp284;\n\t fftw_real tmp297;\n\t fftw_real tmp300;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t\t fftw_real tmp202;\n\t\t fftw_real tmp288;\n\t\t fftw_real tmp289;\n\t\t fftw_real tmp469;\n\t\t fftw_real tmp214;\n\t\t fftw_real tmp225;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp202 = K707106781 * (tmp196 + tmp201);\n\t\t tmp203 = tmp191 - tmp202;\n\t\t tmp287 = tmp191 + tmp202;\n\t\t tmp288 = (K923879532 * tmp224) - (K382683432 * tmp219);\n\t\t tmp289 = (K382683432 * tmp208) + (K923879532 * tmp213);\n\t\t tmp290 = tmp288 + tmp289;\n\t\t tmp478 = tmp288 - tmp289;\n\t\t tmp469 = K707106781 * (tmp305 + tmp304);\n\t\t tmp473 = tmp469 + tmp472;\n\t\t tmp479 = tmp472 - tmp469;\n\t\t tmp214 = (K923879532 * tmp208) - (K382683432 * tmp213);\n\t\t tmp225 = (K923879532 * tmp219) + (K382683432 * tmp224);\n\t\t tmp226 = tmp214 - tmp225;\n\t\t tmp468 = tmp225 + tmp214;\n\t }\n\t {\n\t\t fftw_real tmp244;\n\t\t fftw_real tmp253;\n\t\t fftw_real tmp292;\n\t\t fftw_real tmp293;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp244 = tmp232 - tmp243;\n\t\t tmp253 = tmp249 - tmp252;\n\t\t tmp254 = (K555570233 * tmp244) - (K831469612 * tmp253);\n\t\t tmp285 = (K831469612 * tmp244) + (K555570233 * tmp253);\n\t\t tmp292 = tmp232 + tmp243;\n\t\t tmp293 = tmp249 + tmp252;\n\t\t tmp294 = (K980785280 * tmp292) - (K195090322 * tmp293);\n\t\t tmp301 = (K195090322 * tmp292) + (K980785280 * tmp293);\n\t }\n\t {\n\t\t fftw_real tmp271;\n\t\t fftw_real tmp280;\n\t\t fftw_real tmp295;\n\t\t fftw_real tmp296;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp271 = tmp259 - tmp270;\n\t\t tmp280 = tmp276 - tmp279;\n\t\t tmp281 = (K555570233 * tmp271) + (K831469612 * tmp280);\n\t\t tmp284 = (K555570233 * tmp280) - (K831469612 * tmp271);\n\t\t tmp295 = tmp259 + tmp270;\n\t\t tmp296 = tmp276 + tmp279;\n\t\t tmp297 = (K980785280 * tmp295) + (K195090322 * tmp296);\n\t\t tmp300 = (K980785280 * tmp296) - (K195090322 * tmp295);\n\t }\n\t {\n\t\t fftw_real tmp227;\n\t\t fftw_real tmp282;\n\t\t fftw_real tmp283;\n\t\t fftw_real tmp286;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp227 = tmp203 + tmp226;\n\t\t tmp282 = tmp254 + tmp281;\n\t\t c_re(inout[21 * iostride]) = tmp227 - tmp282;\n\t\t c_re(inout[5 * iostride]) = tmp227 + tmp282;\n\t\t tmp283 = tmp203 - tmp226;\n\t\t tmp286 = tmp284 - tmp285;\n\t\t c_re(inout[29 * iostride]) = tmp283 - tmp286;\n\t\t c_re(inout[13 * iostride]) = tmp283 + tmp286;\n\t }\n\t {\n\t\t fftw_real tmp477;\n\t\t fftw_real tmp480;\n\t\t fftw_real tmp481;\n\t\t fftw_real tmp482;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp477 = tmp285 + tmp284;\n\t\t tmp480 = tmp478 + tmp479;\n\t\t c_im(inout[5 * iostride]) = tmp477 + tmp480;\n\t\t c_im(inout[21 * iostride]) = tmp480 - tmp477;\n\t\t tmp481 = tmp254 - tmp281;\n\t\t tmp482 = tmp479 - tmp478;\n\t\t c_im(inout[13 * iostride]) = tmp481 + tmp482;\n\t\t c_im(inout[29 * iostride]) = tmp482 - tmp481;\n\t }\n\t {\n\t\t fftw_real tmp291;\n\t\t fftw_real tmp298;\n\t\t fftw_real tmp299;\n\t\t fftw_real tmp302;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp291 = tmp287 + tmp290;\n\t\t tmp298 = tmp294 + tmp297;\n\t\t c_re(inout[17 * iostride]) = tmp291 - tmp298;\n\t\t c_re(inout[iostride]) = tmp291 + tmp298;\n\t\t tmp299 = tmp287 - tmp290;\n\t\t tmp302 = tmp300 - tmp301;\n\t\t c_re(inout[25 * iostride]) = tmp299 - tmp302;\n\t\t c_re(inout[9 * iostride]) = tmp299 + tmp302;\n\t }\n\t {\n\t\t fftw_real tmp467;\n\t\t fftw_real tmp474;\n\t\t fftw_real tmp475;\n\t\t fftw_real tmp476;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp467 = tmp301 + tmp300;\n\t\t tmp474 = tmp468 + tmp473;\n\t\t c_im(inout[iostride]) = tmp467 + tmp474;\n\t\t c_im(inout[17 * iostride]) = tmp474 - tmp467;\n\t\t tmp475 = tmp294 - tmp297;\n\t\t tmp476 = tmp473 - tmp468;\n\t\t c_im(inout[9 * iostride]) = tmp475 + tmp476;\n\t\t c_im(inout[25 * iostride]) = tmp476 - tmp475;\n\t }\n\t }\n }\n}\n\nstatic const int twiddle_order[] =\n{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31};\nfftw_codelet_desc fftwi_twiddle_32_desc =\n{\n \"fftwi_twiddle_32\",\n (void (*)()) fftwi_twiddle_32,\n 32,\n FFTW_BACKWARD,\n FFTW_TWIDDLE,\n 520,\n 31,\n twiddle_order,\n};\n", "meta": {"hexsha": "9cc6a9b711bb2fb147b85a6560e4a86996122365", "size": 40717, "ext": "c", "lang": "C", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/ftwi_32.c", "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlp_numeric/old/fftw2_src/ftwi_32.c", "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlp_numeric/old/fftw2_src/ftwi_32.c", "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "avg_line_length": 29.3985559567, "max_line_length": 122, "alphanum_fraction": 0.5732986222, "num_tokens": 12675, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.4571367168274948, "lm_q1q2_score": 0.2639943352241371}} {"text": "/**\n * @file utilities.h\n * @author Matthew Nicely (mnicely@nvidia.com)\n * @date 2020-01-06\n * @version 1.0\n * @brief Contains additional functions used throughout\n * the application.\n *\n * @copyright Copyright (c) 2020\n *\n * @license This project is released under the GNU Public License\n *\n * @note * Target Processor: Intel x86\n * @n * Target Compiler: GCC 7.4.0\n * @n * NVCC Compiler: CUDA Toolkit 10.0 or later\n */\n#ifndef UTILITIES_H_\n#define UTILITIES_H_\n\n#include // std::remove_if, std::nth_element\n#include // assert\n#include //cblas_sgemm\n#include // std::sqrt,\n#include // std::ofstream\n#include // std::vector<>::const_iterator\n#include // LAPACKE_sgetrf, LAPACKE_sgetri\n#include // std::map\n#include // std::accumulate, std::inner_product\n#include // std::default_random_engine, std::random_device, std::uniform_real_distribution\n#include // std::runtime_error\n#include // std::string\n#include // std::vector\n\n// *************** FOR ERROR CHECKING *******************\n#ifndef CUDA_RT_CALL\n#define CUDA_RT_CALL( call ) \\\n { \\\n auto status = static_cast( call ); \\\n if ( status != cudaSuccess ) \\\n fprintf( stderr, \\\n \"ERROR: CUDA RT call \\\"%s\\\" in line %d of file %s failed \" \\\n \"with \" \\\n \"%s (%d).\\n\", \\\n #call, \\\n __LINE__, \\\n __FILE__, \\\n cudaGetErrorString( status ), \\\n status ); \\\n }\n#endif // CUDA_RT_CALL\n// *************** FOR ERROR CHECKING *******************\n\n/**\n * @brief Contains additional functions used throughout application\n */\nnamespace utility {\n\nconstexpr int kSysDim { 4 }; /**< Number of states in system model */\nconstexpr int kMeasDim { 2 }; /**< Number of states in measurement model */\n\n/**\n * @enum Processor\n * @brief Enumeration of processor types\n */\nenum class Processor : bool { kCpu, kGpu };\n\nusing ProcessorMap = std::map;\n\nstatic const ProcessorMap processor_map = { { Processor::kCpu, \"CPU\" }, { Processor::kGpu, \"GPU\" } };\n\n/**\n * @enum Timing\n * @brief Enumeration of timing calculations\n */\nenum class Timing : int { kMedian, kMean, kStdDev, kCount };\n\nusing TimingMap = std::map;\n\nstatic const TimingMap timing_map = { { Timing::kMedian, \"Median\" },\n { Timing::kMean, \"Mean\" },\n { Timing::kStdDev, \"StdDev\" } };\n\n/**\n * @enum Filter\n * @brief Enumeration of possible particle filters\n */\nenum class Filter : int { kBootstrap, kCount };\n\nusing FilterMap = std::map;\n\nstatic const FilterMap filters_map = { { Filter::kBootstrap, \"Bootstrap\" } };\n\n/**\n * @enum Method\n * @brief Enumeration of possible resampling method\n */\nenum class Method : int { kSystematic, kStratified, kMetropolisC2, kCount };\n\nusing MethodMap = std::map;\n\nstatic const MethodMap method_map = { { Method::kSystematic, \"Systematic\" },\n { Method::kStratified, \"Stratified\" },\n { Method::kMetropolisC2, \"MetropolisC2\" } };\n\n/**\n * @struct FilterInfo\n * @brief Structure to store user-specified data and send to filter classes\n */\ntypedef struct _filterInfo {\n int samples; /**< Quantity of samples specified from input file */\n int particles; /**< Quantity of particles specified from input file */\n int num_mcs; /**< Quantity of Monte Carlos specified from input file */\n int resampling; /**< Systmatic = 0, Stratified = 1, Metropolis = 2 */\n int filter_type; /**< Type of filter: Bootstrap = 0 */\n} FilterInfo;\n\n/**\n * @struct Matrix\n * @brief Structure to store matrix and information\n *\n * @param[in] row Stores quantity of rows\n * @param[in] col Stores quantity of columns\n * @param[in] val Store matrix data in a vector\n */\ntypedef struct _matrix {\n\n int row;\n int col;\n std::vector val;\n\n _matrix( const _matrix &a ) : row( a.row ), col( a.col ), val( a.val ) {};\n\n _matrix( int const &row, int const &col, std::initializer_list const &list ) :\n row( row ), col( col ), val( list ) {}\n\n _matrix( int const &row, int const &col ) : row( row ), col( col ) {\n val.resize( row * col, 0.0f );\n }\n\n _matrix( int const &row, int const &col, std::vector const val ) : row( row ), col( col ), val( val ) {}\n} Matrix;\n\n/**\n * @brief Template function to compute square root of a matrix using floats\n *\n * @see http://www.netlib.org/lapack/lapacke.html\n * @see\n * http://www.netlib.org/lapack/explore-html/d7/d75/lapacke__ssyevr_8c_source.html\n * @see http://www.openblas.net/\n * @see http://www.seehuhn.de/pages/matrixfn\n *\n * @param[in,out] matrix_a Matrix to process\n */\ninline void MatrixSqrt( utility::Matrix &matrix_a ) {\n\n int n { matrix_a.row };\n float *a { matrix_a.val.data( ) };\n\n /* allocate space for the output parameters and workspace arrays */\n int m {};\n float abstol { -1.0f };\n\n std::vector w( n, 0.0f );\n std::vector z( n * n, 0.0f );\n std::vector suppz( 2 * n, 0 );\n\n /* get the eigenvalues and eigenvectors */\n int info = LAPACKE_ssyevr(\n LAPACK_ROW_MAJOR, 'V', 'A', 'L', n, a, n, 0, 0, 0, 0, abstol, &m, w.data( ), z.data( ), n, suppz.data( ) );\n\n if ( info != 0 ) {\n throw std::runtime_error( \"Issue with LAPACKE_ssyevr.\\n\" );\n }\n\n /* allocate and Initialize a new matrix B=Z*D */\n std::vector b( n * n, 0.0f );\n for ( int j = 0; j < n; ++j ) {\n float lambda = std::sqrt( w[j] );\n for ( int i = 0; i < n; ++i ) {\n b[i * n + j] = z[i * n + j] * lambda;\n }\n }\n\n float alpha { 1.0f };\n float beta { 0.0f };\n\n /* calculate the square root A=B*Z^T */\n cblas_sgemm( CblasRowMajor, CblasNoTrans, CblasTrans, n, n, n, alpha, b.data( ), n, z.data( ), n, beta, a, n );\n}\n\n/**\n * @brief Matrix-Matrix multiplication function using floats\n *\n * @see http://www.openblas.net/\n *\n * @param[out] matrix_c Structure to store A * B\n * @param[in] matrix_a Structure reference to matrix A\n * @param[in] matrix_b Structure reference to matrix B\n */\n\ninline void MatrixMult( utility::Matrix &matrix_c, utility::Matrix const &matrix_a, utility::Matrix const &matrix_b ) {\n\n assert( matrix_a.col == matrix_b.row );\n\n float const *a { matrix_a.val.data( ) };\n float const *b { matrix_b.val.data( ) };\n float * c { matrix_c.val.data( ) };\n\n float alpha { 1.0f };\n float beta { 0.0f };\n\n cblas_sgemm( CblasRowMajor,\n CblasNoTrans,\n CblasNoTrans,\n matrix_a.row,\n matrix_b.col,\n matrix_b.row,\n alpha,\n a,\n matrix_b.row,\n b,\n matrix_b.col,\n beta,\n c,\n matrix_b.col );\n}\n\n/**\n * @brief Matrix-Matrix-Matrix multiplication function using floats\n *\n * @see http://www.openblas.net/\n *\n * @param[out] matrix_d Structure to store A * B * C\n * @param[in] matrix_a Structure reference to matrix A\n * @param[in] matrix_b Structure reference to matrix B\n * @param[in] matrix_c Structure reference to matrix C\n */\ninline void MatrixMult( utility::Matrix & matrix_d,\n utility::Matrix const &matrix_a,\n utility::Matrix const &matrix_b,\n utility::Matrix const &matrix_c ) {\n\n assert( matrix_a.col == matrix_b.row );\n assert( matrix_b.col == matrix_c.row );\n\n float const *a { matrix_a.val.data( ) };\n float const *b { matrix_b.val.data( ) };\n float const *c { matrix_c.val.data( ) };\n float * d { matrix_d.val.data( ) };\n\n std::vector temp_storage( matrix_a.row * matrix_b.col, 0.0f );\n float * ab { temp_storage.data( ) }; // Temp store for A*B\n\n float alpha { 1.0f };\n float beta { 0.0f };\n\n cblas_sgemm( CblasRowMajor,\n CblasNoTrans,\n CblasNoTrans,\n matrix_a.row,\n matrix_b.col,\n matrix_b.row,\n alpha,\n a,\n matrix_b.row,\n b,\n matrix_b.col,\n beta,\n ab,\n matrix_b.col );\n\n cblas_sgemm( CblasRowMajor,\n CblasNoTrans,\n CblasNoTrans,\n matrix_a.row,\n matrix_c.col,\n matrix_c.row,\n alpha,\n ab,\n matrix_c.row,\n c,\n matrix_c.col,\n beta,\n d,\n matrix_c.col );\n}\n\n/**\n * @brief Matrix-Vector multiplication function using floats\n *\n * @see http://www.openblas.net/\n *\n * @param[out] vector_c Vector to store A * B\n * @param[in] matrix_a Structure reference to matrix A\n * @param[in] vector_b Vector reference to vector B\n */\ninline void\nMatrixMult( std::vector &vector_c, utility::Matrix const &matrix_a, std::vector const &vector_b ) {\n\n assert( matrix_a.col == vector_b.size( ) );\n\n float const *a { matrix_a.val.data( ) };\n float const *b { vector_b.data( ) };\n float * c { vector_c.data( ) };\n\n float alpha { 1.0f };\n float beta { 0.0f };\n\n cblas_sgemv( CblasRowMajor, CblasNoTrans, matrix_a.row, matrix_a.col, alpha, a, matrix_a.col, b, 1, beta, c, 1 );\n}\n\n/**\n * @brief Function to compute the inversion of a matrix using floats\n *\n * @see http://www.netlib.org/lapack/lapacke.html\n * @see\n * http://www.netlib.org/lapack/explore-html/d2/d96/lapacke__dgetrf_8c_source.html\n * @see\n * http://www.netlib.org/lapack/explore-html/da/d0e/lapacke__dgetri_8c_source.html\n * @see\n * https://stackoverflow.com/questions/3519959/computing-the-inverse-of-a-matrix-using-lapack-in-c\n *\n * @param[in,out] matrix_a Matrix to be inverted\n */\ninline void ComputeInverse( utility::Matrix &matrix_a ) {\n\n // A must be a square matrix???\n int n { matrix_a.row };\n float * a = matrix_a.val.data( );\n std::vector piv( n + 1, 0 );\n\n int info {};\n info = LAPACKE_sgetrf( LAPACK_ROW_MAJOR, n, n, a, n, piv.data( ) );\n\n if ( info != 0 ) {\n throw std::runtime_error( \"Issue with LAPACKE_sgetrf.\\n\" );\n }\n\n info = LAPACKE_sgetri( LAPACK_ROW_MAJOR, n, a, n, piv.data( ) );\n\n if ( info != 0 ) {\n throw std::runtime_error( \"Issue with LAPACKE_sgetri.\\n\" );\n }\n}\n\n/**\n * @brief Normal distribution random number generator\n *\n * @param[in] random_numbers Stores random numbers\n * @param[in] lBound Lower bound of distribution\n * @param[in] uBound Upper bound of distribution\n */\ninline void GenerateRandomNum( std::vector &random_numbers, float const &lBound, float const &uBound ) {\n\n // Random device class instance, source of 'true' randomness for\n // initializing random seed\n std::default_random_engine gen( std::random_device {}( ) );\n\n // Instance of class std::normal_distribution with specific mean and stddev\n // Lower and Upper limits are declared in base class\n std::normal_distribution distr( lBound, uBound );\n\n // Compute random numbers for all particles\n for_each( random_numbers.begin( ), random_numbers.end( ), [&distr, &gen]( float &a ) { a = distr( gen ); } );\n}\n\n/**\n * @brief Compute median for Monte Carlos times\n *\n * @param[in/out] time_vector Vector holding times for all Monte Carlos\n * @param[out] median Median time for all Monte Carlos\n */\ninline void ComputeMedianTime( std::vector &time_vector, float &median ) {\n // Compute median\n std::nth_element( time_vector.begin( ), time_vector.begin( ) + time_vector.size( ) / 2, time_vector.end( ) );\n median = time_vector[time_vector.size( ) / 2];\n\n // Remove outliers\n time_vector.erase( std::remove_if( time_vector.begin( ),\n time_vector.end( ),\n [&median]( float const &n ) { return ( n > ( median * 1.05f ) ); } ),\n time_vector.end( ) );\n}\n\n/**\n * @brief Compute mean for Monte Carlos times\n *\n * @param[in] time_vector Vector holding times for all Monte Carlos\n * @param[out] mean Mean time for all Monte Carlos\n */\ninline void ComputeMeanTime( std::vector const &time_vector, float &mean ) {\n // Compute mean\n mean = std::accumulate( time_vector.begin( ), time_vector.end( ), 0.0f ) / time_vector.size( );\n}\n\n/**\n * @brief Compute standard deviation for Monte Carlos times\n *\n * @param[in] time_vector Vector holding times for all Monte Carlos\n * @param[in] mean Mean time for all Monte Carlos\n * @param[out] stdDev\n */\ninline void ComputeStdDevTime( std::vector const &time_vector, float const &mean, float &stdDev ) {\n\n // Compute standard deviation\n std::vector diff( time_vector.size( ) );\n std::transform(\n time_vector.begin( ), time_vector.end( ), diff.begin( ), [&mean]( float const &x ) { return ( x - mean ); } );\n\n // Compute difference\n float sqrtSum { std::inner_product( diff.begin( ), diff.end( ), diff.begin( ), 0.0f ) }; // Compute product\n stdDev = std::sqrt( sqrtSum / time_vector.size( ) );\n}\n\n/**\n * @brief Compute median, mean, standard deviation for Monte Carlo times\n *\n * @param[in/out] time_vector\n * @param[in/out] median\n * @param[in/out] mean\n * @param[in/out] stdDev\n */\ninline void ComputeOverallTiming( std::vector &timeVec, float &median, float &mean, float &stdDev ) {\n ComputeMedianTime( timeVec, median );\n ComputeMeanTime( timeVec, mean );\n ComputeStdDevTime( timeVec, mean, stdDev );\n}\n\n/**\n * @brief Compute overall timing across all Monte Carlos\n *\n * @param[in] timing_results 2D vector containing timing results for each Monte\n * Carlo\n */\ninline void PrintTimingResults( std::vector> const &timing_results ) {\n\n for ( int i = 0; i < static_cast( utility::Timing::kCount ); i++ ) {\n std::printf( \"%s\\t \", utility::timing_map.find( utility::Timing( i ) )->second.c_str( ) );\n }\n std::printf( \"\\n\" );\n\n for ( int i = 0; i < static_cast( utility::Timing::kCount ); i++ ) {\n float sum { std::accumulate( timing_results[i].begin( ), timing_results[i].end( ), 0.0f ) };\n float mean { sum / timing_results[i].size( ) };\n std::printf( \"%0.0f\\t \", mean );\n }\n std::printf( \"\\n\\n\" );\n}\n\n/**\n * @brief Writes data to output file for generated system\n * and measurement truth data\n *\n * @param[in] filename Output filename\n * @param[in] dim Number of system dimensions\n * @param[in] samples Number of samples\n * @param[in] it Iterator to beginning of vector to be printed\n */\ninline void WriteToFile( std::string const & filename,\n int const & dim,\n int const & samples,\n typename std::vector::const_iterator &it ) {\n\n // We jump to the end to add each Monte Carlo\n std::ofstream fout( filename, std::ios_base::app );\n fout.precision( 15 );\n fout.setf( std::ios::fixed, std::ios::floatfield );\n // fout << dim << \" \" << samples << \"\\n\";\n for ( int i = 0; i < samples; i++ ) {\n int idxS { i * dim };\n int idxE { idxS + dim };\n std::copy( it + idxS, it + idxE, std::ostream_iterator( fout, \" \" ) );\n fout << \"\\n\";\n }\n fout.close( );\n}\n\n/**\n * @brief Writes data to output file for filtered estimates\n *\n * @param[in] filename Output filename\n * @param[in] type Filter type\n * @param[in] samples Number of samples\n * @param[in] median Timing median across all Monte Carlos\n * @param[in] mean Timing mean across all Monte Carlos\n * @param[in] stdDev Timing standard deviation across all Monte Carlos\n * @param[in] it Iterator to beginning of vector to be printed\n */\ninline void WriteToFile( std::string const & filename,\n std::string const & type,\n int const & samples,\n float const & median,\n float const & mean,\n float const & stdDev,\n typename std::vector::const_iterator &it ) {\n\n // We jump to the end to add each Monte Carlo\n std::ofstream fout( filename, std::ios_base::app );\n fout.setf( std::ios::fixed, std::ios::floatfield );\n fout << type << \" \" << median << \" \" << mean << \" \" << stdDev << \"\\n\";\n fout.precision( 15 );\n for ( int i = 0; i < samples; i++ ) {\n int idxS { i * utility::kSysDim };\n int idxE { idxS + utility::kSysDim };\n std::copy( it + idxS, it + idxE, std::ostream_iterator( fout, \" \" ) );\n fout << \"\\n\";\n }\n fout.close( );\n}\n\n/**\n * @brief Write header to output file for generated system\n * and measurement truth data\n *\n * @param[in] filename Output filename\n * @param[in] info Struct containing filter information\n */\ninline void WriteTruthHeader( std::string const &filename, int const &num_mcs, int const &dim, int const &samples ) {\n std::ofstream fout( filename, std::ios_base::trunc );\n fout.setf( std::ios::fixed, std::ios::floatfield );\n fout << num_mcs << \" \" << dim << \" \" << samples << \"\\n\";\n fout.close( );\n}\n\n/**\n * @brief Write header to output file.\n *\n * @param[in] filename Output filename\n * @param[in] info Struct containing filter information\n */\ninline void WriteDataHeader( std::string const &filename, utility::FilterInfo const &filter_info ) {\n std::ofstream fout( filename, std::ios_base::trunc );\n fout.setf( std::ios::fixed, std::ios::floatfield );\n fout << filter_info.num_mcs << \" \" << kSysDim << \" \" << filter_info.samples << \" \" << filter_info.particles << \"\\n\";\n fout.close( );\n}\n\n#ifdef USE_NVTX\n#include \"nvtx3/nvToolsExt.h\"\n\nuint32_t const colors[] { 0x0000ff00, 0x0f0000ff, 0x000000ff, 0x00ffff00, 0x00ff00ff,\n 0x0000ffff, 0x00ff0000, 0x00ffffff, 0x0f0f0f0f };\nint const num_colors { sizeof( colors ) / sizeof( uint32_t ) };\n\n/**\n * class Tracer\n */\nclass Tracer {\n public:\n /**\n * @brief Construct a new Tracer object\n *\n * @see\n * https://docs.nvidia.com/gameworks/content/gameworkslibrary/nvtx/nvidia_tools_extension_library_nvtx.htm\n * @see\n * https://devblogs.nvidia.com/cuda-pro-tip-generate-custom-application-profile-timelines-nvtx/\n *\n * @param[in] name Function name\n * @param[in] cid color id\n */\n\n Tracer( char const *name, int const &cid ) {\n int color_id = cid;\n color_id = color_id % num_colors;\n nvtxEventAttributes_t eventAttrib = {};\n eventAttrib.version = NVTX_VERSION;\n eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE;\n eventAttrib.colorType = NVTX_COLOR_ARGB;\n eventAttrib.color = colors[color_id];\n eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII;\n eventAttrib.message.ascii = name;\n nvtxRangePushEx( &eventAttrib );\n }\n\n /**\n * @brief Destroy the Tracer object\n *\n */\n ~Tracer( ) {\n nvtxRangePop( );\n }\n};\n\n#define RANGE( name, cid ) utility::Tracer uniq_name_using_macros( name, cid );\n#else\n#define RANGE( name, cid )\n#endif\n\n} /* namespace utility */\n\n#endif /* UTILITIES_H_ */\n", "meta": {"hexsha": "bab3f687cea88c5d2308e97f9d585368cd5e821e", "size": 21041, "ext": "h", "lang": "C", "max_stars_repo_path": "src/utilities.h", "max_stars_repo_name": "mnicely/particle_filter", "max_stars_repo_head_hexsha": "56611a6ba5f1edd7f8c7393c60d0f8678adb4695", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T16:47:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T09:15:13.000Z", "max_issues_repo_path": "src/utilities.h", "max_issues_repo_name": "mnicely/particle_filter", "max_issues_repo_head_hexsha": "56611a6ba5f1edd7f8c7393c60d0f8678adb4695", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities.h", "max_forks_repo_name": "mnicely/particle_filter", "max_forks_repo_head_hexsha": "56611a6ba5f1edd7f8c7393c60d0f8678adb4695", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5422297297, "max_line_length": 120, "alphanum_fraction": 0.5561047479, "num_tokens": 5154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.519521321952093, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.2638190910332891}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"parmt_config.h\"\n#ifdef PARMT_USE_INTEL\n#include \n#include \n#include \n#else\n#include \n#endif\n#include \"compearth.h\"\n#include \"parmt_mtsearch.h\"\n#include \"parmt_postProcess.h\"\n#include \"parmt_utils.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n\n#define PROGRAM_NAME \"parmt\"\nstatic int parseArguments(int argc, char *argv[],\n const int nprocs,\n int *npInObsGroups,\n int *npInLocGroups,\n int *npInMTGroups,\n char iniFile[PATH_MAX]);\nstatic void printUsage(void);\nint parmt_freeData(struct parmtData_struct *data);\nint parmt_freeLocalMTs(struct localMT_struct *mts);\n/*!\n *\n */\nint main(int argc, char *argv[])\n{\n char iniFile[PATH_MAX];\n double *betas, *h, *kappas, *gammas, *M0s, *sigmas, *thetas, *u, *v;\n double *deps, *luneMPDF, *phi, t0, t1, du, dv, dh, dk, ds;\n int64_t ngridSearch;\n double hLower, hUpper, uLower, uUpper, vLower, vUpper, xnorm;\n int *lags, i, ierr, iobs, myid, npInLocGroups, nmt, npInMTGroups,\n npInObsGroups, nprocs, provided;\n int ix, iy, k;\n MPI_Comm mtComm, locComm, obsComm;\n bool linMTComm, linLocComm, linObsComm;\n const int master = 0;\n const int ldm = 8;\nstruct parmtGeneralParms_struct parms;\nstruct parmtData_struct data;\nstruct parmtMtSearchParms_struct mtsearch;\n struct localMT_struct mtloc;\n //------------------------------------------------------------------------//\n //\n // initialize MPI, ISCL, and handle threading issues\n MPI_Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &provided);\n MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n MPI_Comm_size(MPI_COMM_WORLD, &nprocs);\n iscl_init();\n#ifdef PARMT_USE_INTEL\n //omp_set_num_threads(2);\n mkl_set_num_threads(1);\n ippSetNumThreads(1);\n#endif\n // initialize\n phi = NULL;\n M0s = NULL;\n betas = NULL;\n gammas = NULL;\n sigmas = NULL;\n kappas = NULL;\n thetas = NULL;\n h = NULL;\n u = NULL;\n v = NULL;\n lags = NULL;\n memset(&parms, 0, sizeof(struct parmtGeneralParms_struct));\n memset(&data, 0, sizeof(struct parmtData_struct));\n memset(&mtsearch, 0, sizeof(struct parmtMtSearchParms_struct));\n memset(&mtloc, 0, sizeof(struct localMT_struct));\n if (myid == master)\n {\n ierr = parseArguments(argc, argv, nprocs,\n &npInObsGroups, &npInLocGroups, &npInMTGroups,\n iniFile);\n if (ierr != 0){goto INIT_ERROR;}\n // read the ini file\n printf(\"%s: Parsing ini file %s...\\n\", PROGRAM_NAME, iniFile);\n ierr = 0;\n ierr += parmt_utils_readGeneralParms(iniFile, &parms);\n strcpy(parms.programName, PROGRAM_NAME);\n parms.programID = PARMT_ID;\n ierr += parmt_utils_readMtSearch(iniFile, &mtsearch);\n if (ierr != 0)\n {\n printf(\"%s: Error reading ini file\\n\", PROGRAM_NAME);\n goto INIT_ERROR;\n }\n printf(\"%s: Process management:\\n\", PROGRAM_NAME);\n printf(\" Number of processes in observation groups %d\\n\",\n npInObsGroups);\n printf(\" Number of processes in location groups %d\\n\",\n npInLocGroups);\n printf(\" Number of processes in moment tensor groups %d\\n\",\n npInMTGroups);\n// npInObsGroups = 1;\n// npInLocGroups = 1;\n// npInMTGroups = nprocs;\nprintf(\"verify greens fns are correct\\n\");\n/*\n double pAxis[3], nAxis[3], tAxis[3], beta, gamma, u,v;\n u= 3.0*M_PI/8.0;\n v=-1.0/9.0;\n compearth_u2beta(1, 10, 2, &u, 1.e-10, &beta);\n compearth_v2gamma(1, &v, &gamma);\n postprocess_tt2tnp(beta, gamma, 4.0*M_PI/5.0, -M_PI/2.0, 0.723,\n pAxis, nAxis, tAxis);\n int nxp = 51;\n double *xw1 = memory_calloc64f(nxp*nxp);\n double *yw1 = memory_calloc64f(nxp*nxp);\n int8_t *pn1 = (int8_t *) calloc(nxp*nxp, sizeof(int8_t));\n const double xc = 1.5; const double yc = 1.5; const double rad = 1.0;\n // Compute the corresponding moment tensor\n double M0loc = 1.0/sqrt(2.0), Muse[6], lamUse[9], Uuse[9];\n double gammaDeg = gamma*180.0/M_PI;\n double deltaDeg = (M_PI_2 - beta)*180.0/M_PI;\n double kappaDeg = (4.0*M_PI/5.0)*180.0/M_PI;\n double sigmaDeg = (-M_PI_2)*180.0/M_PI;\n double thetaDeg = 0.723*180.0/M_PI;\n compearth_tt2cmt(gammaDeg, deltaDeg, M0loc, \n kappaDeg, thetaDeg,\n sigmaDeg,\n Muse, lamUse, Uuse);\n printf(\"mt = [%f,%f,%f,%f,%f,%f]\\n\", Muse[0], Muse[1], Muse[2], Muse[3], Muse[4], Muse[5]);\nprintf(\"drawing\\n\");\nfor (int i=0; i<10000; i++)\n{\n postprocess_tnp2beachballPolarity(nxp, xc, yc, rad,\n pAxis, nAxis, tAxis,\n xw1, yw1, pn1);\n}\n FILE *fwork = fopen(\"depmag/beachball.txt\", \"w\");\n for (int iy=0; iy INT_MAX)\n {\n printf(\"%s: Error - grid search too big - integer overflow\",\n PROGRAM_NAME);\n ierr = 1;\n }\n }\n MPI_Bcast(&ierr, 1, MPI_INT, master, MPI_COMM_WORLD);\n if (ierr != 0){goto FINISH;}\n // Send the inputs to everyone\n if (myid == master)\n {\n printf(\"%s: Broadcasting parameters...\\n\", PROGRAM_NAME);\n }\n ierr = parmt_broadcast_mtSearchParms(&mtsearch, master, MPI_COMM_WORLD);\n if (ierr != 0)\n {\n printf(\"%s: Fatal error broadcasting parameters\\n\", PROGRAM_NAME);\n MPI_Abort(MPI_COMM_WORLD, 30);\n }\n ierr = parmt_broadcast_generalParms(&parms, master, MPI_COMM_WORLD);\n if (ierr != 0)\n {\n printf(\"%s: Fatal error broadcasting general parameters\\n\",\n PROGRAM_NAME);\n MPI_Abort(MPI_COMM_WORLD, 30);\n }\n // Send the waveforms to everyone\n ierr = parmt_broadcast_data(&data, master, MPI_COMM_WORLD);\n if (ierr != 0)\n {\n printf(\"%s: Fatal error broadcasting waveforms\\n\", PROGRAM_NAME);\n MPI_Abort(MPI_COMM_WORLD, 30);\n }\n // Discretize the moment tensor space in (u, v, h) space\n if (myid == master)\n {\n printf(\"%s: Discretizing MT space...\\n\", PROGRAM_NAME);\n }\n // Discretize the moment tensor space in (u, v, h) space\n ierr = parmt_discretizeCells64f(\n mtsearch.nb, mtsearch.betaLower, mtsearch.betaUpper,\n mtsearch.ng, mtsearch.gammaLower, mtsearch.gammaUpper,\n mtsearch.nk, mtsearch.kappaLower, mtsearch.kappaUpper,\n mtsearch.ns, mtsearch.sigmaLower, mtsearch.sigmaUpper,\n mtsearch.nt, mtsearch.thetaLower, mtsearch.thetaUpper,\n mtsearch.nm, mtsearch.m0Lower, mtsearch.m0Upper,\n mtsearch.luseLog,\n &betas, &gammas, &kappas,\n &sigmas, &thetas, &M0s);\n if (ierr != 0)\n { \n printf(\"%s: Error discretizing MT space\\n\", PROGRAM_NAME);\n MPI_Abort(MPI_COMM_WORLD, 30);\n }\n/*\n compearth_beta2u(1, &mtsearch.betaLower, &uLower);\n compearth_beta2u(1, &mtsearch.betaUpper, &uUpper);\n compearth_gamma2v(1, &mtsearch.gammaLower, &vLower);\n compearth_gamma2v(1, &mtsearch.gammaUpper, &vUpper);\n compearth_theta2h(1, &mtsearch.thetaLower, &hLower);\n compearth_theta2h(1, &mtsearch.thetaUpper, &hUpper);\n du = (uUpper - uLower)/(double) mtsearch.nb;\n dv = (vUpper - vLower)/(double) mtsearch.ng;\n dh =-(hUpper - hLower)/(double) mtsearch.nt;\n dk = (mtsearch.kappaUpper - mtsearch.kappaLower)/(double) mtsearch.nk;\n ds = (mtsearch.sigmaUpper - mtsearch.sigmaLower)/(double) mtsearch.ns;\n//if (myid == master){printf(\"%f %f %f\\n\", du, dv, dh);}\n u = array_linspace64f(uLower+du/2, uUpper-du/2, mtsearch.nb, &ierr);\n v = array_linspace64f(vLower+dv/2, vUpper-dv/2, mtsearch.ng, &ierr);\n h = array_linspace64f(hLower-dh/2, hUpper+dh/2, mtsearch.nt, &ierr);\n betas = memory_calloc64f(mtsearch.nb);\n gammas = memory_calloc64f(mtsearch.ng);\n thetas = memory_calloc64f(mtsearch.nt);\n compearth_u2beta(mtsearch.nb, 20, 2, u, 1.e-6, betas);\n compearth_v2gamma(mtsearch.ng, v, gammas);\n compearth_h2theta(mtsearch.nt, h, thetas); \n M0s = array_linspace64f(mtsearch.m0Lower, mtsearch.m0Upper,\n mtsearch.nm, &ierr);\n kappas = array_linspace64f(mtsearch.kappaLower+dk/2, mtsearch.kappaUpper-dk/2,\n mtsearch.nk, &ierr);\n sigmas = array_linspace64f(mtsearch.sigmaLower+ds/2, mtsearch.sigmaUpper-ds/2,\n mtsearch.ns, &ierr);\n*/\n//if (myid != master){for (int i=0; i 0){lwantLags = true;}\n*/\n if (myid == master)\n {\n phi = memory_calloc64f(data.nlocs*mtloc.nmtAll);\n }\n else\n {\n phi = memory_calloc64f(1);\n }\n // Perform the grid search\n MPI_Wtime();\n ierr = parmt_obsSearch64f(MPI_COMM_WORLD,\n obsComm, locComm,\n linObsComm, linLocComm,\n parms, data, mtloc, phi);\n if (ierr != 0)\n {\n printf(\"%s: Error calling obsSearch64f\\n\", PROGRAM_NAME);\n MPI_Abort(MPI_COMM_WORLD, 30);\n }\n MPI_Barrier(MPI_COMM_WORLD);\n if (myid == master)\n {\n MPI_Wtime();\n printf(\"%s: Objective function computation time: %f\\n\",\n PROGRAM_NAME, MPI_Wtime() - t0);\n }\n if (ierr != 0)\n {\n printf(\"%s: Error calling locSearchXC64f\\n\", PROGRAM_NAME);\n MPI_Abort(MPI_COMM_WORLD, 30);\n }\n if (myid == master)\n {\n printf(\"%s: Writing results...\\n\", PROGRAM_NAME);\n ierr = parmt_io_writeObjectiveFunction64f(\n //parms.resultsDir, parms.projnm, parms.resultsFileSuffix,\n parms.parmtArchive, nmt, phi);\n if (ierr != 0)\n {\n printf(\"%s: Error writing objective function\\n\", PROGRAM_NAME);\n goto FINISH;\n }\n int jloc, jm, jb, jg, jk, js, jt; \n int imtopt = array_argmax64f(data.nlocs*mtloc.nmtAll, phi, &ierr);\n marginal_getOptimum(data.nlocs, mtsearch.nm, mtsearch.nb,\n mtsearch.ng, mtsearch.nk, mtsearch.ns,\n mtsearch.nt, phi,\n &jloc, &jm, &jb, &jg,\n &jk, &js, &jt);\n printf(\"%d %f %f %f %f %f %f\\n\", jloc,\n gammas[jg]*180.0/M_PI, 90.0-betas[jb]*180.0/M_PI, 1.0,\n kappas[jk]*180.0/M_PI, thetas[jt]*180.0/M_PI,\n sigmas[js]*180.0/M_PI);\n double Muse[6], Mned[6], lam[3], U[9];\n printf(\"phi opt: %d %e\\n\", imtopt, phi[imtopt]);\n printf(\"%d %d %d %d %d %d %d\\n\", jloc, jg, jb, jm, jk, jt, js);\n double gammaOpt = gammas[jg]*180.0/M_PI;\n double deltaOpt = 90.0-betas[jb]*180.0/M_PI;\n double kappaOpt = kappas[jk]*180.0/M_PI;\n double thetaOpt = thetas[jt]*180.0/M_PI;\n double sigmaOpt = sigmas[js]*180.0/M_PI; \n compearth_TT2CMT(1, &gammaOpt,\n &deltaOpt,\n &M0s[jm],\n &kappaOpt,\n &thetaOpt,\n &sigmaOpt,\n Muse, lam, U);\n/*\n compearth_tt2cmt(gammas[jg]*180.0/M_PI,\n 90.0-betas[jb]*180.0/M_PI,\n M0s[jm],\n kappas[jk]*180.0/M_PI,\n thetas[jt]*180.0/M_PI,\n sigmas[js]*180.0/M_PI,\n Muse, lam, U);\n*/\n parmt_discretizeMT64f(1, &gammas[jg],\n 1, &betas[jb],\n 1, &M0s[jm],\n 1, &kappas[jk],\n 1, &thetas[jt],\n 1, &sigmas[js],\n 6, 1, Mned);\n //printf(\"%e %e %e\\n\", phi[0], phi[1000], phi[500000]); \n printf(\"mtUSE =[%f,%f,%f,%f,%f,%f]\\n\",\n Muse[0], Muse[1], Muse[2], Muse[3], Muse[4], Muse[5]);\n printf(\"mtNED =[%f,%f,%f,%f,%f,%f]\\n\",\n Mned[0], Mned[1], Mned[2], Mned[3], Mned[4], Mned[5]);\n }\nFINISH:;\n if (linObsComm){MPI_Comm_free(&obsComm);}\n if (linLocComm){MPI_Comm_free(&locComm);}\n if (linMTComm){MPI_Comm_free(&mtComm);}\n memory_free64f(&M0s);\n memory_free64f(&h);\n memory_free64f(&u);\n memory_free64f(&v);\n memory_free64f(&betas);\n memory_free64f(&gammas);\n memory_free64f(&kappas);\n memory_free64f(&sigmas);\n memory_free64f(&thetas);\n memory_free64f(&phi);\n memory_free32i(&lags);\n parmt_freeData(&data);\n parmt_freeLocalMTs(&mtloc);\n iscl_finalize();\n MPI_Finalize();\n return EXIT_SUCCESS;\n}\n\nstatic int parseArguments(int argc, char *argv[],\n const int nprocs,\n int *npInObsGroups,\n int *npInLocGroups,\n int *npInMTGroups,\n char iniFile[PATH_MAX])\n{\n bool linFile;\n int prod;\n linFile = false;\n *npInObsGroups = 1;\n *npInLocGroups = 1;\n *npInMTGroups = 1;\n memset(iniFile, 0, PATH_MAX*sizeof(char));\n while (true)\n {\n static struct option longOptions[] =\n {\n {\"help\", no_argument, 0, '?'},\n {\"help\", no_argument, 0, 'h'},\n {\"ini_file\", required_argument, 0, 'i'},\n {\"obsGroupSize\", required_argument, 0, 'w'},\n {\"mtGroupSize\", required_argument, 0, 'm'},\n {\"locGroupSize\", required_argument, 0, 'l'},\n {0, 0, 0, 0}\n }; \n int c, optionIndex;\n c = getopt_long(argc, argv, \"?hi:w:m:l:\",\n longOptions, &optionIndex);\n if (c ==-1){break;}\n if (c == 'i')\n {\n strcpy(iniFile, (const char *) optarg);\n linFile = true; \n }\n else if (c == 'w' && nprocs > 1)\n {\n *npInObsGroups = atoi(optarg);\n }\n else if (c == 'l' && nprocs > 1)\n {\n *npInLocGroups = atoi(optarg);\n }\n else if (c == 'm' && nprocs > 1)\n {\n *npInMTGroups = atoi(optarg);\n }\n else if (c == 'h' || c == '?')\n {\n printUsage();\n return -2;\n }\n else\n {\n printf(\"%s: Unknown options: %s\\n\",\n PROGRAM_NAME, argv[optionIndex]);\n }\n }\n if (!linFile)\n {\n printf(\"%s: Error must specify ini file\\n\\n\", PROGRAM_NAME);\n printUsage();\n return -1;\n }\n prod = (*npInObsGroups)*(*npInLocGroups)*(*npInMTGroups);\n if (prod != nprocs)\n {\n if (prod != 1)\n {\n printf(\"%s: Invalid process layout - defaulting to (%d,%d,%d)\\n\", \n PROGRAM_NAME, 1, 1, nprocs); \n }\n *npInObsGroups = 1;\n *npInLocGroups = 1;\n *npInMTGroups = nprocs;\n }\n return 0;\n}\n\nstatic void printUsage(void)\n{\n printf(\"Usage:\\n parmt -i input_file\\n\\n\");\n printf(\"Required arguments:\\n\");\n printf(\" -i input_file specifies the initialization file\\n\");\n printf(\"\\n\");\n printf(\"Optional arguments:\\n\");\n printf(\" -m number of processes in moment-tensor groups\\n\");\n printf(\" -w number of processes in waveform (observation) groups\\n\");\n printf(\" -l number of processes in location groups\\n\");\n printf(\" -h displays this message\\n\");\n printf(\" Note if m*w*l must equal the number of processes\\n\");\n printf(\" If they are not set the program will set -m=nprocs\\n\");\n return;\n}\n\nint parmt_freeData(struct parmtData_struct *data)\n{\n int i;\n if (data->nobs > 0 && data->nlocs > 0 &&\n data->sacGxx != NULL && data->sacGyy != NULL && data->sacGzz != NULL &&\n data->sacGxy != NULL && data->sacGxz != NULL && data->sacGyz != NULL)\n {\n for (i=0; inobs*data->nlocs; i++)\n {\n sacio_freeData(&data->sacGxx[i]);\n sacio_freeData(&data->sacGyy[i]);\n sacio_freeData(&data->sacGzz[i]); \n sacio_freeData(&data->sacGxy[i]);\n sacio_freeData(&data->sacGxz[i]);\n sacio_freeData(&data->sacGyz[i]);\n }\n free(data->sacGxx);\n free(data->sacGyy);\n free(data->sacGzz); \n free(data->sacGxy);\n free(data->sacGxz);\n free(data->sacGyz);\n }\n if (data->nobs > 0 && data->data != NULL)\n {\n for (i=0; inobs; i++)\n {\n sacio_freeData(&data->data[i]);\n }\n free(data->data);\n }\n if (data->nobs > 0 && data->est != NULL)\n {\n free(data->est);\n }\n memset(data, 0, sizeof(struct parmtData_struct));\n return 0;\n}\n\nint parmt_freeLocalMTs(struct localMT_struct *mtloc)\n{\n memory_free64f(&mtloc->mts);\n //memory_free32i(&mtloc->l2g); // TODO remove\n memory_free32i(&mtloc->offset);\n memset(mtloc, 0, sizeof(struct localMT_struct));\n return 0;\n}\n", "meta": {"hexsha": "9ffc3011409bcef4f6ab9c01318d7d99c5d0f706", "size": 22134, "ext": "c", "lang": "C", "max_stars_repo_path": "src/parmt.c", "max_stars_repo_name": "bakerb845/parmt", "max_stars_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_stars_repo_licenses": ["Intel"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/parmt.c", "max_issues_repo_name": "bakerb845/parmt", "max_issues_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_issues_repo_licenses": ["Intel"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/parmt.c", "max_forks_repo_name": "bakerb845/parmt", "max_forks_repo_head_hexsha": "2b4097df02ef5e56407d40e821d5c7155c2e4416", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.9902439024, "max_line_length": 99, "alphanum_fraction": 0.5298635583, "num_tokens": 6248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297745935070806, "lm_q2_score": 0.4186969093556867, "lm_q1q2_score": 0.2636846758921486}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \"chealpix.h\"\n#include \n\n#include \"pmpfft.h\"\n#include \"pmghosts.h\"\n\nstatic double RNDTABLE[8192];\n\ngsl_rng * random_generator;\nvoid fastpm_utils_init_randtable() {\n random_generator = gsl_rng_alloc(gsl_rng_ranlxd1);\n int rank;\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n gsl_rng_set(random_generator, 37 * (rank + 1) + 1); /* start-up seed */\n int i;\n for(i = 0; i < 8192; i ++) {\n RNDTABLE[i] = gsl_rng_uniform(random_generator);\n }\n //gsl_rng_free(random_generator);\n}\n\ndouble \nfastpm_utils_get_random(uint64_t id) \n{\n return gsl_rng_uniform(random_generator);\n uint64_t ind = 0;\n ind = id;\n \n while(id != 0) {\n ind += id;\n id /= 8192;\n } \n ind %= 8192;\n return RNDTABLE[ind];\n}\n\nvoid \nfastpm_utils_dump(PM * pm , const char * filename, FastPMFloat *data) \n{\n char fn1[1024];\n char fn2[1024];\n if(pm->NTask > 1) {\n sprintf(fn1, \"%s.%03d.geometry\", filename, pm->ThisTask);\n sprintf(fn2, \"%s.%03d\", filename, pm->ThisTask);\n } else {\n sprintf(fn1, \"%s.geometry\", filename);\n sprintf(fn2, \"%s\", filename);\n }\n\n fastpm_path_ensure_dirname(filename);\n\n FILE * fp;\n fp = fopen(fn2, \"w\");\n if(pm->allocsize != fwrite(data, sizeof(FastPMFloat), pm->allocsize, fp)) {\n fastpm_raise(-1, \"IO failed.\\n\");\n }\n fclose(fp);\n fp = fopen(fn1, \"w\");\n fprintf(fp, \"# real\\n\");\n fprintf(fp, \"start: %td %td %td\\n\", \n pm->IRegion.start[0],\n pm->IRegion.start[1],\n pm->IRegion.start[2]);\n fprintf(fp, \"size: %td %td %td\\n\", \n pm->IRegion.size[0],\n pm->IRegion.size[1],\n pm->IRegion.size[2]);\n fprintf(fp, \"strides: %td %td %td\\n\", \n pm->IRegion.strides[0],\n pm->IRegion.strides[1],\n pm->IRegion.strides[2]);\n\n fprintf(fp, \"# complex\\n\");\n fprintf(fp, \"start: %td %td %td\\n\", \n pm->ORegion.start[0],\n pm->ORegion.start[1],\n pm->ORegion.start[2]);\n fprintf(fp, \"size: %td %td %td\\n\", \n pm->ORegion.size[0],\n pm->ORegion.size[1],\n pm->ORegion.size[2]);\n fprintf(fp, \"strides: %td %td %td\\n\", \n pm->ORegion.strides[0],\n pm->ORegion.strides[1],\n pm->ORegion.strides[2]);\n\n fclose(fp);\n}\n\nvoid \nfastpm_utils_load(PM * pm , const char * filename, FastPMFloat *data) \n{\n char fn1[1024];\n char fn2[1024];\n if(pm->NTask > 1) {\n sprintf(fn1, \"%s.%03d.geometry\", filename, pm->ThisTask);\n sprintf(fn2, \"%s.%03d\", filename, pm->ThisTask);\n } else {\n sprintf(fn1, \"%s.geometry\", filename);\n sprintf(fn2, \"%s\", filename);\n }\n FILE * fp;\n fp = fopen(fn2, \"r\");\n if(pm->allocsize != fread(data, sizeof(FastPMFloat), pm->allocsize, fp)) {\n fastpm_raise(-1, \"File was bad\\n\");\n };\n fclose(fp);\n}\n\nstatic double \ntk_eh(double k, struct fastpm_powerspec_eh_params * params)\t\t/* from Martin White */\n{\n double q, theta, ommh2, a, s, gamma, L0, C0;\n double tmp;\n double omegam, ombh2, hubble;\n\n /* other input parameters */\n hubble = params->hubble_param;\n omegam = params->omegam;\n ombh2 = params->omegab * hubble * hubble;\n\n theta = 2.728 / 2.7;\n ommh2 = omegam * hubble * hubble;\n s = 44.5 * log(9.83 / ommh2) / sqrt(1. + 10. * exp(0.75 * log(ombh2))) * hubble;\n a = 1. - 0.328 * log(431. * ommh2) * ombh2 / ommh2\n + 0.380 * log(22.3 * ommh2) * (ombh2 / ommh2) * (ombh2 / ommh2);\n gamma = a + (1. - a) / (1. + exp(4 * log(0.43 * k * s)));\n gamma *= omegam * hubble;\n q = k * theta * theta / gamma;\n L0 = log(2. * exp(1.) + 1.8 * q);\n C0 = 14.2 + 731. / (1. + 62.5 * q);\n tmp = L0 / (L0 + C0 * q * q);\n return (tmp);\n}\n\ndouble \nfastpm_utils_powerspec_eh(double k, struct fastpm_powerspec_eh_params * param)\t/* Eisenstein & Hu */\n{\n return param->Norm * k * pow(tk_eh(k, param), 2);\n}\n\ndouble \nfastpm_utils_powerspec_white(double k, double * amplitude) \t/* White Noise*/\n{\n return *amplitude;\n}\n\nstatic void\n_sort_pix(const void * ptr, void * radix, void * arg)\n{\n memcpy(radix, ptr, 8);\n}\n\n/* generate evenly balanced healpix positions that are inside the lightcone. */\nvoid\nfastpm_utils_healpix_ra_dec (\n int nside,\n double **ra,\n double **dec,\n uint64_t **pix,\n size_t * n,\n FastPMLightCone * lc,\n MPI_Comm comm\n )\n{\n const double rad_to_degree = 180./M_PI;\n\n size_t npix = nside2npix (nside);\n int ThisTask, NTask;\n\n MPI_Comm_rank(comm, &ThisTask);\n MPI_Comm_size(comm, &NTask);\n\n //fastpm_info(\"healpix npix %ld \\n\",*npix);\n size_t i = 0;\n\n size_t pix_start = ThisTask * npix / NTask;\n size_t pix_end = (ThisTask + 1) * npix / NTask;\n\n uint64_t local_npix = 0;\n\n uint64_t * pixels = NULL;\n\n /* two iterations; estimate and fill */\n while(1) {\n size_t j = 0;\n\n for (i = pix_start; i < pix_end; i++)\n {\n double vec[3];\n\n pix2vec_ring(nside, i, vec);\n\n if(!fastpm_lc_inside(lc, vec)) continue;\n\n if(pixels != NULL) {\n pixels[j] = i;\n }\n\n j ++;\n }\n if(pixels == NULL) {\n local_npix = j;\n pixels = malloc(sizeof(uint64_t) * local_npix);\n\n } else {\n break;\n }\n }\n\n /* count total */\n uint64_t valid_npix = local_npix;\n MPI_Allreduce(MPI_IN_PLACE, &valid_npix, 1, MPI_LONG, MPI_SUM, comm);\n\n /* redistribute / balance */\n\n size_t localsize =\n (ThisTask + 1) * valid_npix / NTask\n -\n (ThisTask ) * valid_npix / NTask;\n\n uint64_t * recv_buffer = malloc(sizeof(uint64_t) * localsize);\n\n mpsort_mpi_newarray(pixels, local_npix, recv_buffer, localsize, sizeof(uint64_t), _sort_pix, 8, NULL, comm);\n\n free(pixels);\n\n *ra = malloc(sizeof(double) * localsize);\n *dec = malloc(sizeof(double) * localsize);\n\n for(i = 0; i < localsize; i ++) {\n double phi, theta;\n\n pix2ang_ring(nside, recv_buffer[i], &theta, &phi);\n\n phi *= rad_to_degree;\n theta*= rad_to_degree;\n (*ra)[i] = phi;\n (*dec)[i]= 90 - theta;\n recv_buffer[i] += (((uint64_t)nside) << 48);\n }\n *n = localsize;\n *pix = recv_buffer;\n}\n\nvoid\nfastpm_gldot(double glmatrix[4][4], double xi[4], double xo[4])\n{\n int i, j;\n for(i = 0; i < 4; i ++) {\n xo[i] = 0;\n for(j = 0; j < 4; j ++) {\n xo[i] += glmatrix[i][j] * xi[j];\n }\n }\n}\n\nvoid\nfastpm_gldotf(double glmatrix[4][4], float vi[4], float vo[4])\n{\n int i, j;\n for(i = 0; i < 4; i ++) {\n vo[i] = 0;\n for(j = 0; j < 4; j ++) {\n vo[i] += glmatrix[i][j] * vi[j];\n }\n }\n}\n\n/* returns MPI_LOR reduction */\nint\nMPIU_Any(MPI_Comm comm, int value)\n{\n MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_INT, MPI_LOR, comm);\n return value;\n}\n\n/* returns MPI_LAND reduction */\nint\nMPIU_All(MPI_Comm comm, int value)\n{\n MPI_Allreduce(MPI_IN_PLACE, &value, 1, MPI_INT, MPI_LAND, comm);\n return value;\n}\n\n/*\n * Compute the standard statistics of a value over communicator.\n * fmt is a string, describing the list of stats to return:\n * < : minimum (double)\n * , : rank of minimum (int)\n * > : maximum (double)\n * . : rank of maximum (int)\n * - : mean (double)\n * s : std (biased standard derivation)\n * v : variance (biased variance)\n * S : unbiased std\n * V : unbiased variance\n *\n * e.g.\n *\n * double min, max;\n * MPIU_stats(comm, r, \"<>\", &min, &max);\n *\n * returns number of items converted;\n * if a fmt char is unknown, the input variable is unmodified.\n *\n * */\nint\nMPIU_stats(MPI_Comm comm,\n const double value,\n const char * fmt, ...)\n{\n \n va_list va;\n va_start(va, fmt);\n\n int NTask;\n MPI_Comm_size(comm, &NTask);\n int ThisTask;\n MPI_Comm_rank(comm, &ThisTask);\n\n double sum = value;\n struct {\n double value;\n int rank;\n } min = {value, ThisTask},\n max = {value, ThisTask};\n\n double sumsq = value * value;\n\n MPI_Allreduce(MPI_IN_PLACE, &sum, 1, MPI_DOUBLE, MPI_SUM, comm);\n MPI_Allreduce(MPI_IN_PLACE, &sumsq, 1, MPI_DOUBLE, MPI_SUM, comm);\n MPI_Allreduce(MPI_IN_PLACE, &min, 1, MPI_DOUBLE_INT, MPI_MINLOC, comm);\n MPI_Allreduce(MPI_IN_PLACE, &max, 1, MPI_DOUBLE_INT, MPI_MAXLOC, comm);\n\n double avg = (sum) / NTask;\n double avg_sq = (sumsq) / NTask;\n double var = avg_sq - avg * avg;\n double std = sqrt(avg_sq - avg * avg);\n\n int i;\n int c = 0;\n for(i = 0; i < strlen(fmt); i ++) {\n void * r = va_arg(va, void *);\n int * ir = (int * ) r;\n double * dr = (double * ) r;\n\n c++;\n switch(fmt[i]) {\n case '-':\n *dr = avg;\n break;\n case '<':\n *dr = min.value;\n break;\n case '>':\n *dr = max.value;\n break;\n case ',':\n *ir = min.rank;\n break;\n case '.':\n *ir = max.rank;\n break;\n case 's':\n *dr = std;\n break;\n case 'S':\n *dr = std * sqrt(1.0 * NTask / (NTask - 1.0));\n break;\n case 'v':\n *dr = var;\n break;\n case 'V':\n *dr = var * 1.0 * NTask / (NTask - 1.0);\n break;\n default:\n c--;\n }\n }\n va_end(va);\n\n return c;\n}\n\n/*\n *\n * create a copy of string src and broadcast it to all ranks.\n *\n * Every rank receives a copy of src as the return value, including the root.\n *\n * if free is not NULL, the function is called as free(src)\n * */\nchar *\nMPIU_Bcast_string(MPI_Comm comm, char * src, int root, void(*free)(void * ptr))\n{\n int srcNULL = src == NULL;\n MPI_Bcast(&srcNULL, 1, MPI_INT, root, comm);\n\n if(srcNULL) return NULL;\n\n int rank;\n int N;\n MPI_Comm_rank(comm, &rank);\n\n if(rank == root) {\n N = strlen(src) + 1;\n }\n MPI_Bcast(&N, 1, MPI_INT, root, comm);\n\n char * ret = malloc(N);\n if(rank == root) {\n strcpy(ret, src);\n }\n\n if(free && rank == root) free(src);\n MPI_Bcast(ret, N, MPI_BYTE, root, comm);\n\n return ret;\n}\n", "meta": {"hexsha": "3c4ebed2f98a9509f59bd0939ade4a0ac512945f", "size": 10756, "ext": "c", "lang": "C", "max_stars_repo_path": "fastpm/libfastpm/utils.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/utils.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/utils.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": 25.0139534884, "max_line_length": 112, "alphanum_fraction": 0.5282632949, "num_tokens": 3211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.2635296922878342}} {"text": "// clang -DHAVE_INLINE -O3 mussel.c -o mussel -lgsl -lgslcblas\n\n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char *argv[])\n{\n // Setup the random number generator:\n gsl_rng_env_setup();\n gsl_rng *rng = gsl_rng_alloc(gsl_rng_taus2);\n const unsigned int seed = (argc == 2)? atof(argv[1]) : time(NULL);\n gsl_rng_set(rng, seed);\n\n // Parameters:\n const int T = 1000;\n const double A0 = 0.5;\n const double A1 = 0.025;\n const double A2 = 0.2;\n const int N = 1000;\n const int TWO_N = N * N;\n\n // Allocate memory for the matrix:\n int **m = (int**)malloc(N * sizeof(int*));\n int i;\n for (i = 0; i < N; ++i)\n {\n m[i] = (int*)malloc(N * sizeof(int));\n }\n\n // Fill the matrix:\n int x0, y0;\n for (x0 = 0; x0 < N; ++x0)\n {\n for (y0 = 0; y0 < N; ++y0)\n {\n m[x0][y0] = (gsl_rng_uniform(rng) < 0.5) ? 0 : 2;\n }\n }\n\n // Main loop\n int n, x, y, x1, y1, t, cell;\n for (t = 0; t < T; ++t)\n {\n // Loop around the lattice at random to update cells;\n for (cell = 0; cell < TWO_N; ++cell)\n {\n // Select at random the cell to update\n x0 = (int)(gsl_rng_uniform(rng) * N);\n y0 = (int)(gsl_rng_uniform(rng) * N);\n\n // Update the mussels\n // Disturbed cells automatically transformed into empty cells\n if (m[x0][y0] == 0)\n {\n m[x0][y0] = 1;\n }\n else if (m[x0][y0] == 1) // If the cell is empty, test if there is colonization\n {\n // First calculate the number of neighbours\n n = 0;\n for (x = -1; x <= 1; ++x)\n {\n for (y = -1; y <= 1; ++y)\n {\n if (x0 + x == -1)\n {\n x1 = N - 1;\n }\n else if (x0 + x == N)\n {\n x1 = 0;\n }\n else\n {\n x1 = x0 + x;\n }\n\n if (y0 + y == -1)\n {\n y1 = N - 1;\n }\n else if (y0 + y == N)\n {\n y1 = 0;\n }\n else\n {\n y1 = y0 + y;\n }\n\n if (x != 0 && y != 0 && m[x1][y1] == 2)\n {\n ++n;\n }\n }\n }\n // Calculate if the status if the cell is changed\n if (gsl_rng_uniform(rng) < A2 * n * 0.125)\n {\n m[x0][y0] = 2;\n }\n }\n else if (m[x0][y0] == 2)\n { // If the cell is occupied, test if there is disturbance\n n = 0;\n for (x = -1; x <= 1; x++)\n {\n for (y = -1; y <= 1; y++)\n {\n if (x0 + x == -1)\n {\n x1 = N - 1;\n }\n else if (x0 + x == N)\n {\n x1 = 0;\n }\n else\n {\n x1 = x0 + x;\n }\n\n if (y0 + y == -1)\n {\n y1 = N - 1;\n }\n else if (y0 + y == N)\n {\n y1 = 0;\n }\n else\n {\n y1 = y0 + y;\n }\n\n if (x != 0 && y != 0 && m[x1][y1] == 0)\n {\n n = 1;\n }\n }\n }\n // Calculate if the status of the cell is changed\n if (gsl_rng_uniform(rng) < A0 * n * 0.125 + A1)\n {\n m[x0][y0] = 0;\n }\n }\n }\n }\n\n char buffer[100];\n sprintf(buffer, \"mussel-%u.txt\", seed);\n FILE *out = fopen(buffer, \"w\");\n\n for (x0 = 0; x0 < N; ++x0)\n {\n for (y0 = 0; y0 < N; ++y0)\n {\n fprintf(out, \"%d \", m[x0][y0]);\n }\n fprintf(out, \"\\n\");\n }\n fclose(out);\n\n gsl_rng_free(rng);\n for (i = 0; i < N; ++i)\n {\n free(m[i]);\n }\n free(m);\n return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "7fd8ab96831e1b678ae842aa5a45e6e59a2df959", "size": 4922, "ext": "c", "lang": "C", "max_stars_repo_path": "ecology/mussel/mussel.c", "max_stars_repo_name": "vadmus/cuda_examples", "max_stars_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2015-06-08T03:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T14:32:35.000Z", "max_issues_repo_path": "ecology/mussel/mussel.c", "max_issues_repo_name": "bh6025/CUDA-training", "max_issues_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ecology/mussel/mussel.c", "max_forks_repo_name": "bh6025/CUDA-training", "max_forks_repo_head_hexsha": "ba09fe2f2274d89eb38d57bde9063d77ae789a7e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 51.0, "max_forks_repo_forks_event_min_datetime": "2015-11-13T12:21:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T06:15:11.000Z", "avg_line_length": 27.8079096045, "max_line_length": 91, "alphanum_fraction": 0.29195449, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.4225046348141882, "lm_q1q2_score": 0.2629919524161234}} {"text": "/* multifit/multireg.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/*\n * References:\n *\n * [1] P. C. Hansen & D. P. O'Leary, \"The use of the L-curve in\n * the regularization of discrete ill-posed problems\", SIAM J. Sci.\n * Comput. 14 (1993), pp. 1487-1503.\n *\n * [2] P. C. Hansen, \"Discrete Inverse Problems: Insight and Algorithms,\"\n * SIAM Press, 2010.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"linear_common.c\"\n\nint\ngsl_multifit_linear_solve (const double lambda,\n const gsl_matrix * X,\n const gsl_vector * y,\n gsl_vector * c,\n double *rnorm,\n double *snorm,\n gsl_multifit_linear_workspace * work)\n{\n size_t rank;\n int status;\n\n status = multifit_linear_solve(X, y, GSL_DBL_EPSILON, lambda, &rank, c,\n rnorm, snorm, work);\n\n return status;\n} /* gsl_multifit_linear_solve() */\n\n/*\ngsl_multifit_linear_applyW()\n Apply weight matrix to (X,y) LS system\n\nInputs: X - least squares matrix n-by-p\n w - weight vector n-by-1 or NULL for W = I\n y - right hand side n-by-1\n WX - (output) sqrt(W) X, n-by-p\n Wy - (output) sqrt(W) y, n-by-1\n\nNotes:\n1) If w = NULL, on output WX = X and Wy = y\n2) It is allowed for WX = X and Wy = y for in-place transform\n*/\n\nint\ngsl_multifit_linear_applyW(const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_matrix * WX,\n gsl_vector * Wy)\n{\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (n != y->size)\n {\n GSL_ERROR(\"y vector does not match X\", GSL_EBADLEN);\n }\n else if (w != NULL && n != w->size)\n {\n GSL_ERROR(\"weight vector does not match X\", GSL_EBADLEN);\n }\n else if (n != WX->size1 || p != WX->size2)\n {\n GSL_ERROR(\"WX matrix dimensions do not match X\", GSL_EBADLEN);\n }\n else if (n != Wy->size)\n {\n GSL_ERROR(\"Wy vector must be length n\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* copy WX = X; Wy = y if distinct pointers */\n if (WX != X)\n gsl_matrix_memcpy(WX, X);\n if (Wy != y)\n gsl_vector_memcpy(Wy, y);\n\n if (w != NULL)\n {\n /* construct WX = sqrt(W) X and Wy = sqrt(W) y */\n for (i = 0; i < n; ++i)\n {\n double wi = gsl_vector_get(w, i);\n double swi;\n gsl_vector_view row = gsl_matrix_row(WX, i);\n double *yi = gsl_vector_ptr(Wy, i);\n\n if (wi < 0.0)\n wi = 0.0;\n\n swi = sqrt(wi);\n gsl_vector_scale(&row.vector, swi);\n *yi *= swi;\n }\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_multifit_linear_wstdform1()\n Using regularization matrix\nL = diag(l_1,l_2,...,l_p), transform to Tikhonov standard form:\n\nX~ = sqrt(W) X L^{-1}\ny~ = sqrt(W) y\nc~ = L c\n\nInputs: L - Tikhonov matrix as a vector of diagonal elements p-by-1;\n or NULL for L = I\n X - least squares matrix n-by-p\n y - right hand side vector n-by-1\n w - weight vector n-by-1; or NULL for W = I\n Xs - least squares matrix in standard form X~ n-by-p\n ys - right hand side vector in standard form y~ n-by-1\n work - workspace\n\nReturn: success/error\n\nNotes:\n1) It is allowed for X = Xs and y = ys\n*/\n\nint\ngsl_multifit_linear_wstdform1 (const gsl_vector * L,\n const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_multifit_linear_workspace * work)\n{\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (n > work->nmax || p > work->pmax)\n {\n GSL_ERROR(\"observation matrix larger than workspace\", GSL_EBADLEN);\n }\n else if (L != NULL && p != L->size)\n {\n GSL_ERROR(\"L vector does not match X\", GSL_EBADLEN);\n }\n else if (n != y->size)\n {\n GSL_ERROR(\"y vector does not match X\", GSL_EBADLEN);\n }\n else if (w != NULL && n != w->size)\n {\n GSL_ERROR(\"weight vector does not match X\", GSL_EBADLEN);\n }\n else if (n != Xs->size1 || p != Xs->size2)\n {\n GSL_ERROR(\"Xs matrix dimensions do not match X\", GSL_EBADLEN);\n }\n else if (n != ys->size)\n {\n GSL_ERROR(\"ys vector must be length n\", GSL_EBADLEN);\n }\n else\n {\n int status = GSL_SUCCESS;\n\n /* compute Xs = sqrt(W) X and ys = sqrt(W) y */\n status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);\n if (status)\n return status;\n\n if (L != NULL)\n {\n size_t j;\n\n /* construct X~ = sqrt(W) X * L^{-1} matrix */\n for (j = 0; j < p; ++j)\n {\n gsl_vector_view Xj = gsl_matrix_column(Xs, j);\n double lj = gsl_vector_get(L, j);\n\n if (lj == 0.0)\n {\n GSL_ERROR(\"L matrix is singular\", GSL_EDOM);\n }\n\n gsl_vector_scale(&Xj.vector, 1.0 / lj);\n }\n }\n\n return status;\n }\n}\n\n/*\ngsl_multifit_linear_stdform1()\n Using regularization matrix L = diag(l_1,l_2,...,l_p),\nand W = I, transform to Tikhonov standard form:\n\nX~ = X L^{-1}\ny~ = y\nc~ = L c\n\nInputs: L - Tikhonov matrix as a vector of diagonal elements p-by-1\n X - least squares matrix n-by-p\n y - right hand side vector n-by-1\n Xs - least squares matrix in standard form X~ n-by-p\n ys - right hand side vector in standard form y~ n-by-1\n work - workspace\n\nReturn: success/error\n\nNotes:\n1) It is allowed for X = Xs\n*/\n\nint\ngsl_multifit_linear_stdform1 (const gsl_vector * L,\n const gsl_matrix * X,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_multifit_linear_workspace * work)\n{\n int status;\n\n status = gsl_multifit_linear_wstdform1(L, X, NULL, y, Xs, ys, work);\n\n return status;\n}\n\nint\ngsl_multifit_linear_L_decomp (gsl_matrix * L, gsl_vector * tau)\n{\n const size_t m = L->size1;\n const size_t p = L->size2;\n int status;\n\n if (tau->size != GSL_MIN(m, p))\n {\n GSL_ERROR(\"tau vector must be min(m,p)\", GSL_EBADLEN);\n }\n else if (m >= p)\n {\n /* square or tall L matrix */\n status = gsl_linalg_QR_decomp(L, tau);\n return status;\n }\n else\n {\n /* more columns than rows, compute qr(L^T) */\n gsl_matrix_view LTQR = gsl_matrix_view_array(L->data, p, m);\n gsl_matrix *LT = gsl_matrix_alloc(p, m);\n\n /* XXX: use temporary storage due to difficulties in transforming\n * a rectangular matrix in-place */\n gsl_matrix_transpose_memcpy(LT, L);\n gsl_matrix_memcpy(<QR.matrix, LT);\n gsl_matrix_free(LT);\n\n status = gsl_linalg_QR_decomp(<QR.matrix, tau);\n\n return status;\n }\n}\n\n/*\ngsl_multifit_linear_wstdform2()\n Using regularization matrix L which is m-by-p, transform to Tikhonov\nstandard form. This routine is separated into two cases:\n\nCase 1: m >= p, here we can use the QR decomposition of L = QR, and note\nthat ||L c|| = ||R c|| where R is p-by-p. Therefore,\n\nX~ = X R^{-1} is n-by-p\ny~ = y is n-by-1\nc~ is p-by-1\nM is not used\n\nCase 2: m < p\n\nX~ is (n - p + m)-by-m\ny~ is (n - p + m)-by-1\nc~ is m-by-1\nM is n-by-p (workspace)\n\nInputs: LQR - output from gsl_multifit_linear_L_decomp()\n Ltau - output from gsl_multifit_linear_L_decomp()\n X - least squares matrix n-by-p\n w - weight vector n-by-1; or NULL for W = I\n y - right hand side vector n-by-1\n Xs - (output) least squares matrix in standard form\n case 1: n-by-p\n case 2: (n - p + m)-by-m\n ys - (output) right hand side vector in standard form\n case 1: n-by-1\n case 2: (n - p + m)-by-1\n M - (output) workspace matrix needed to reconstruct solution vector\n case 1: not used\n case 2: n-by-p\n work - workspace\n\nReturn: success/error\n\nNotes:\n1) If m >= p, on output:\n Xs = X R^{-1}\n ys = y\n\n2) If m < p, on output:\n M(:,1:pm) contains QR decomposition of A * K_o, needed to reconstruct\n solution vector, where pm = p - m; M(:,p) contains Householder scalars\n*/\n\nint\ngsl_multifit_linear_wstdform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_matrix * M,\n gsl_multifit_linear_workspace * work)\n{\n const size_t m = LQR->size1;\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (n > work->nmax || p > work->pmax)\n {\n GSL_ERROR(\"observation matrix larger than workspace\", GSL_EBADLEN);\n }\n else if (p != LQR->size2)\n {\n GSL_ERROR(\"LQR and X matrices have different numbers of columns\", GSL_EBADLEN);\n }\n else if (n != y->size)\n {\n GSL_ERROR(\"y vector does not match X\", GSL_EBADLEN);\n }\n else if (w != NULL && n != w->size)\n {\n GSL_ERROR(\"weights vector must be length n\", GSL_EBADLEN);\n }\n else if (m >= p) /* square or tall L matrix */\n {\n /* the sizes of Xs and ys depend on whether m >= p or m < p */\n if (n != Xs->size1 || p != Xs->size2)\n {\n GSL_ERROR(\"Xs matrix must be n-by-p\", GSL_EBADLEN);\n }\n else if (n != ys->size)\n {\n GSL_ERROR(\"ys vector must have length n\", GSL_EBADLEN);\n }\n else\n {\n int status;\n size_t i;\n gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p);\n\n /* compute Xs = sqrt(W) X and ys = sqrt(W) y */\n status = gsl_multifit_linear_applyW(X, w, y, Xs, ys);\n if (status)\n return status;\n\n /* compute X~ = X R^{-1} using QR decomposition of L */\n for (i = 0; i < n; ++i)\n {\n gsl_vector_view v = gsl_matrix_row(Xs, i);\n\n /* solve: R^T y = X_i */\n gsl_blas_dtrsv(CblasUpper, CblasTrans, CblasNonUnit, &R.matrix, &v.vector);\n }\n\n return GSL_SUCCESS;\n }\n }\n else /* L matrix with m < p */\n {\n const size_t pm = p - m;\n const size_t npm = n - pm;\n\n /*\n * This code closely follows section 2.6.1 of Hansen's\n * \"Regularization Tools\" manual\n */\n\n if (npm != Xs->size1 || m != Xs->size2)\n {\n GSL_ERROR(\"Xs matrix must be (n-p+m)-by-m\", GSL_EBADLEN);\n }\n else if (npm != ys->size)\n {\n GSL_ERROR(\"ys vector must be of length (n-p+m)\", GSL_EBADLEN);\n }\n else if (n != M->size1 || p != M->size2)\n {\n GSL_ERROR(\"M matrix must be n-by-p\", GSL_EBADLEN);\n }\n else\n {\n int status;\n gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n gsl_vector_view b = gsl_vector_subvector(work->t, 0, n);\n\n gsl_matrix_view LTQR = gsl_matrix_view_array(LQR->data, p, m); /* qr(L^T) */\n gsl_matrix_view Rp = gsl_matrix_view_array(LQR->data, m, m); /* R factor of L^T */\n gsl_vector_const_view LTtau = gsl_vector_const_subvector(Ltau, 0, m);\n\n /*\n * M(:,1:p-m) will hold QR decomposition of A K_o; M(:,p) will hold\n * Householder scalars\n */\n gsl_matrix_view MQR = gsl_matrix_submatrix(M, 0, 0, n, pm);\n gsl_vector_view Mtau = gsl_matrix_subcolumn(M, p - 1, 0, GSL_MIN(n, pm));\n\n gsl_matrix_view AKo, AKp, HqTAKp;\n gsl_vector_view v;\n size_t i;\n\n /* compute A = sqrt(W) X and b = sqrt(W) y */\n status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector);\n if (status)\n return status;\n\n /* compute: A <- A K = [ A K_p ; A K_o ] */\n gsl_linalg_QR_matQ(<QR.matrix, <tau.vector, &A.matrix);\n AKp = gsl_matrix_submatrix(&A.matrix, 0, 0, n, m); \n AKo = gsl_matrix_submatrix(&A.matrix, 0, m, n, pm); \n\n /* compute QR decomposition [H,T] = qr(A * K_o) and store in M */\n gsl_matrix_memcpy(&MQR.matrix, &AKo.matrix);\n gsl_linalg_QR_decomp(&MQR.matrix, &Mtau.vector);\n\n /* AKp currently contains A K_p; apply H^T from the left to get H^T A K_p */\n gsl_linalg_QR_QTmat(&MQR.matrix, &Mtau.vector, &AKp.matrix);\n\n /* the last npm rows correspond to H_q^T A K_p */\n HqTAKp = gsl_matrix_submatrix(&AKp.matrix, pm, 0, npm, m);\n\n /* solve: Xs R_p^T = H_q^T A K_p for Xs */\n gsl_matrix_memcpy(Xs, &HqTAKp.matrix);\n for (i = 0; i < npm; ++i)\n {\n gsl_vector_view x = gsl_matrix_row(Xs, i);\n gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &Rp.matrix, &x.vector);\n }\n\n /*\n * compute: ys = H_q^T b; this is equivalent to computing\n * the last q elements of H^T b (q = npm)\n */\n v = gsl_vector_subvector(&b.vector, pm, npm);\n gsl_linalg_QR_QTvec(&MQR.matrix, &Mtau.vector, &b.vector);\n gsl_vector_memcpy(ys, &v.vector);\n\n return GSL_SUCCESS;\n }\n }\n}\n\nint\ngsl_multifit_linear_stdform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * y,\n gsl_matrix * Xs,\n gsl_vector * ys,\n gsl_matrix * M,\n gsl_multifit_linear_workspace * work)\n{\n int status;\n\n status = gsl_multifit_linear_wstdform2(LQR, Ltau, X, NULL, y, Xs, ys, M, work);\n\n return status;\n}\n\n/*\ngsl_multifit_linear_genform1()\n Backtransform regularized solution vector using matrix\nL = diag(L)\n*/\n\nint\ngsl_multifit_linear_genform1 (const gsl_vector * L,\n const gsl_vector * cs,\n gsl_vector * c,\n gsl_multifit_linear_workspace * work)\n{\n if (L->size > work->pmax)\n {\n GSL_ERROR(\"L vector does not match workspace\", GSL_EBADLEN);\n }\n else if (L->size != cs->size)\n {\n GSL_ERROR(\"cs vector does not match L\", GSL_EBADLEN);\n }\n else if (L->size != c->size)\n {\n GSL_ERROR(\"c vector does not match L\", GSL_EBADLEN);\n }\n else\n {\n /* compute true solution vector c = L^{-1} c~ */\n gsl_vector_memcpy(c, cs);\n gsl_vector_div(c, L);\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_multifit_linear_wgenform2()\n Backtransform regularized solution vector in standard form to recover\noriginal vector\n\nInputs: LQR - output from gsl_multifit_linear_L_decomp()\n Ltau - output from gsl_multifit_linear_L_decomp()\n X - original least squares matrix n-by-p\n w - original weight vector n-by-1 or NULL for W = I\n y - original rhs vector n-by-1\n cs - standard form solution vector\n c - (output) original solution vector p-by-1\n M - matrix computed by gsl_multifit_linear_wstdform2()\n work - workspace\n*/\n\nint\ngsl_multifit_linear_wgenform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * w,\n const gsl_vector * y,\n const gsl_vector * cs,\n const gsl_matrix * M,\n gsl_vector * c,\n gsl_multifit_linear_workspace * work)\n{\n const size_t m = LQR->size1;\n const size_t n = X->size1;\n const size_t p = X->size2;\n\n if (n > work->nmax || p > work->pmax)\n {\n GSL_ERROR(\"X matrix does not match workspace\", GSL_EBADLEN);\n }\n else if (p != LQR->size2)\n {\n GSL_ERROR(\"LQR matrix does not match X\", GSL_EBADLEN);\n }\n else if (p != c->size)\n {\n GSL_ERROR(\"c vector does not match X\", GSL_EBADLEN);\n }\n else if (w != NULL && n != w->size)\n {\n GSL_ERROR(\"w vector does not match X\", GSL_EBADLEN);\n }\n else if (n != y->size)\n {\n GSL_ERROR(\"y vector does not match X\", GSL_EBADLEN);\n }\n else if (m >= p) /* square or tall L matrix */\n {\n if (p != cs->size)\n {\n GSL_ERROR(\"cs vector must be length p\", GSL_EBADLEN);\n }\n else\n {\n int s;\n gsl_matrix_const_view R = gsl_matrix_const_submatrix(LQR, 0, 0, p, p); /* R factor of L */\n\n /* solve R c = cs for true solution c, using QR decomposition of L */\n gsl_vector_memcpy(c, cs);\n s = gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &R.matrix, c);\n\n return s;\n }\n }\n else /* rectangular L matrix with m < p */\n {\n if (m != cs->size)\n {\n GSL_ERROR(\"cs vector must be length m\", GSL_EBADLEN);\n }\n else if (n != M->size1 || p != M->size2)\n {\n GSL_ERROR(\"M matrix must be size n-by-p\", GSL_EBADLEN);\n }\n else\n {\n int status;\n const size_t pm = p - m;\n gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n gsl_vector_view b = gsl_vector_subvector(work->t, 0, n);\n gsl_matrix_view Rp = gsl_matrix_view_array(LQR->data, m, m); /* R_p */\n gsl_matrix_view LTQR = gsl_matrix_view_array(LQR->data, p, m);\n gsl_vector_const_view LTtau = gsl_vector_const_subvector(Ltau, 0, m);\n gsl_matrix_const_view MQR = gsl_matrix_const_submatrix(M, 0, 0, n, pm);\n gsl_vector_const_view Mtau = gsl_matrix_const_subcolumn(M, p - 1, 0, GSL_MIN(n, pm));\n gsl_matrix_const_view To = gsl_matrix_const_submatrix(&MQR.matrix, 0, 0, pm, pm);\n gsl_vector_view workp = gsl_vector_subvector(work->xt, 0, p);\n gsl_vector_view v1, v2;\n\n /* compute A = sqrt(W) X and b = sqrt(W) y */\n status = gsl_multifit_linear_applyW(X, w, y, &A.matrix, &b.vector);\n if (status)\n return status;\n\n /* initialize c to zero */\n gsl_vector_set_zero(c);\n\n /* compute c = L_inv cs = K_p R_p^{-T} cs */\n\n /* set c(1:m) = R_p^{-T} cs */\n v1 = gsl_vector_subvector(c, 0, m);\n gsl_vector_memcpy(&v1.vector, cs);\n gsl_blas_dtrsv(CblasUpper, CblasTrans, CblasNonUnit, &Rp.matrix, &v1.vector);\n\n /* c <- K R_p^{-T} cs = [ K_p R_p^{_T} cs ; 0 ] */\n gsl_linalg_QR_Qvec(<QR.matrix, <tau.vector, c);\n\n /* compute: b1 = b - A L_inv cs */\n gsl_blas_dgemv(CblasNoTrans, -1.0, &A.matrix, c, 1.0, &b.vector);\n\n /* compute: b2 = H^T b1 */\n gsl_linalg_QR_QTvec(&MQR.matrix, &Mtau.vector, &b.vector);\n\n /* compute: b3 = T_o^{-1} b2 */\n v1 = gsl_vector_subvector(&b.vector, 0, pm);\n gsl_blas_dtrsv(CblasUpper, CblasNoTrans, CblasNonUnit, &To.matrix, &v1.vector);\n\n /* compute: b4 = K_o b3 */\n gsl_vector_set_zero(&workp.vector);\n v2 = gsl_vector_subvector(&workp.vector, m, pm);\n gsl_vector_memcpy(&v2.vector, &v1.vector);\n gsl_linalg_QR_Qvec(<QR.matrix, <tau.vector, &workp.vector);\n\n /* final solution vector */\n gsl_vector_add(c, &workp.vector);\n\n return GSL_SUCCESS;\n }\n }\n}\n\nint\ngsl_multifit_linear_genform2 (const gsl_matrix * LQR,\n const gsl_vector * Ltau,\n const gsl_matrix * X,\n const gsl_vector * y,\n const gsl_vector * cs,\n const gsl_matrix * M,\n gsl_vector * c,\n gsl_multifit_linear_workspace * work)\n{\n int status;\n\n status = gsl_multifit_linear_wgenform2(LQR, Ltau, X, NULL, y, cs, M, c, work);\n\n return status;\n}\n\n/*\ngsl_multifit_linear_lreg()\n Calculate regularization parameters to use in L-curve\nanalysis\n\nInputs: smin - smallest singular value of LS system\n smax - largest singular value of LS system > 0\n reg_param - (output) vector of regularization parameters\n derived from singular values\n\nReturn: success/error\n*/\n\nint\ngsl_multifit_linear_lreg (const double smin, const double smax,\n gsl_vector * reg_param)\n{\n if (smax <= 0.0)\n {\n GSL_ERROR(\"smax must be positive\", GSL_EINVAL);\n }\n else\n {\n const size_t N = reg_param->size;\n\n /* smallest regularization parameter */\n const double smin_ratio = 16.0 * GSL_DBL_EPSILON;\n const double new_smin = GSL_MAX(smin, smax*smin_ratio);\n double ratio;\n size_t i;\n\n gsl_vector_set(reg_param, N - 1, new_smin);\n\n /* ratio so that reg_param(1) = s(1) */\n ratio = pow(smax / new_smin, 1.0 / ((double)N - 1.0));\n\n /* calculate the regularization parameters */\n for (i = N - 1; i > 0 && i--; )\n {\n double rp1 = gsl_vector_get(reg_param, i + 1);\n gsl_vector_set(reg_param, i, ratio * rp1);\n }\n\n return GSL_SUCCESS;\n }\n}\n\n/*\ngsl_multifit_linear_lcurve()\n Calculate L-curve using regularization parameters estimated\nfrom singular values of least squares matrix\n\nInputs: y - right hand side vector\n reg_param - (output) vector of regularization parameters\n derived from singular values\n rho - (output) vector of residual norms ||y - X c||\n eta - (output) vector of solution norms ||lambda c||\n work - workspace\n\nReturn: success/error\n\nNotes:\n1) SVD of X must be computed first by calling multifit_linear_svd();\n work->n and work->p are initialized by this function\n*/\n\nint\ngsl_multifit_linear_lcurve (const gsl_vector * y,\n gsl_vector * reg_param,\n gsl_vector * rho, gsl_vector * eta,\n gsl_multifit_linear_workspace * work)\n{\n const size_t n = y->size;\n const size_t N = rho->size; /* number of points on L-curve */\n\n if (n != work->n)\n {\n GSL_ERROR(\"y vector does not match workspace\", GSL_EBADLEN);\n }\n else if (N < 3)\n {\n GSL_ERROR (\"at least 3 points are needed for L-curve analysis\",\n GSL_EBADLEN);\n }\n else if (N != eta->size)\n {\n GSL_ERROR (\"size of rho and eta vectors do not match\",\n GSL_EBADLEN);\n }\n else if (reg_param->size != eta->size)\n {\n GSL_ERROR (\"size of reg_param and eta vectors do not match\",\n GSL_EBADLEN);\n }\n else\n {\n int status = GSL_SUCCESS;\n const size_t p = work->p;\n\n size_t i, j;\n\n gsl_matrix_view A = gsl_matrix_submatrix(work->A, 0, 0, n, p);\n gsl_vector_view S = gsl_vector_subvector(work->S, 0, p);\n gsl_vector_view xt = gsl_vector_subvector(work->xt, 0, p);\n gsl_vector_view workp = gsl_matrix_subcolumn(work->QSI, 0, 0, p);\n gsl_vector_view workp2 = gsl_vector_subvector(work->D, 0, p); /* D isn't used for regularized problems */\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 double normy = gsl_blas_dnrm2(y);\n double normUTy;\n\n /* compute projection xt = U^T y */\n gsl_blas_dgemv (CblasTrans, 1.0, &A.matrix, y, 0.0, &xt.vector);\n\n normUTy = gsl_blas_dnrm2(&xt.vector);\n dr = normy*normy - normUTy*normUTy;\n\n /* calculate regularization parameters */\n gsl_multifit_linear_lreg(smin, smax, reg_param);\n\n for (i = 0; i < N; ++i)\n {\n double lambda = gsl_vector_get(reg_param, i);\n double lambda_sq = lambda * lambda;\n\n for (j = 0; j < p; ++j)\n {\n double sj = gsl_vector_get(&S.vector, j);\n double xtj = gsl_vector_get(&xt.vector, j);\n double f = sj / (sj*sj + lambda_sq);\n\n gsl_vector_set(&workp.vector, j, f * xtj);\n gsl_vector_set(&workp2.vector, j, (1.0 - sj*f) * xtj);\n }\n\n gsl_vector_set(eta, i, gsl_blas_dnrm2(&workp.vector));\n gsl_vector_set(rho, i, gsl_blas_dnrm2(&workp2.vector));\n }\n\n if (n > p && dr > 0.0)\n {\n /* add correction to residual norm (see eqs 6-7 of [1]) */\n for (i = 0; i < N; ++i)\n {\n double rhoi = gsl_vector_get(rho, i);\n double *ptr = gsl_vector_ptr(rho, i);\n\n *ptr = sqrt(rhoi*rhoi + dr);\n }\n }\n\n /* restore D to identity matrix */\n gsl_vector_set_all(work->D, 1.0);\n\n return status;\n }\n} /* gsl_multifit_linear_lcurve() */\n\n/*\ngsl_multifit_linear_lcorner()\n Determine point on L-curve of maximum curvature. For each\nset of 3 points on the L-curve, the circle which passes through\nthe 3 points is computed. The radius of the circle is then used\nas an estimate of the curvature at the middle point. The point\nwith maximum curvature is then selected.\n\nInputs: rho - vector of residual norms ||A x - b||\n eta - vector of solution norms ||L x||\n idx - (output) index i such that\n (log(rho(i)),log(eta(i))) is the point of\n maximum curvature\n\nReturn: success/error\n*/\n\nint\ngsl_multifit_linear_lcorner(const gsl_vector *rho,\n const gsl_vector *eta,\n size_t *idx)\n{\n const size_t n = rho->size;\n\n if (n < 3)\n {\n GSL_ERROR (\"at least 3 points are needed for L-curve analysis\",\n GSL_EBADLEN);\n }\n else if (n != eta->size)\n {\n GSL_ERROR (\"size of rho and eta vectors do not match\",\n GSL_EBADLEN);\n }\n else\n {\n int s = GSL_SUCCESS;\n size_t i;\n double x1, y1; /* first point of triangle on L-curve */\n double x2, y2; /* second point of triangle on L-curve */\n double rmin = -1.0; /* minimum radius of curvature */\n\n /* initial values */\n x1 = log(gsl_vector_get(rho, 0));\n y1 = log(gsl_vector_get(eta, 0));\n\n x2 = log(gsl_vector_get(rho, 1));\n y2 = log(gsl_vector_get(eta, 1));\n\n for (i = 1; i < n - 1; ++i)\n {\n /*\n * The points (x1,y1), (x2,y2), (x3,y3) are the previous,\n * current, and next point on the L-curve. We will find\n * the circle which fits these 3 points and take its radius\n * as an estimate of the curvature at this point.\n */\n double x3 = log(gsl_vector_get(rho, i + 1));\n double y3 = log(gsl_vector_get(eta, i + 1));\n\n double x21 = x2 - x1;\n double y21 = y2 - y1;\n double x31 = x3 - x1;\n double y31 = y3 - y1;\n double h21 = x21*x21 + y21*y21;\n double h31 = x31*x31 + y31*y31;\n double d = fabs(2.0 * (x21*y31 - x31*y21));\n double r = sqrt(h21*h31*((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2))) / d;\n\n /* if d =~ 0 then there are nearly colinear points */\n if (gsl_finite(r))\n {\n /* check for smallest radius of curvature */\n if (r < rmin || rmin < 0.0)\n {\n rmin = r;\n *idx = i;\n }\n }\n\n /* update previous/current L-curve values */\n x1 = x2;\n y1 = y2;\n x2 = x3;\n y2 = y3;\n }\n\n /* check if a minimum radius was found */\n if (rmin < 0.0)\n {\n /* possibly co-linear points */\n GSL_ERROR(\"failed to find minimum radius\", GSL_EINVAL);\n }\n\n return s;\n }\n} /* gsl_multifit_linear_lcorner() */\n\n/*\ngsl_multifit_linear_lcorner2()\n Determine point on L-curve (lambda^2, ||c||^2) of maximum curvature.\nFor each set of 3 points on the L-curve, the circle which passes through\nthe 3 points is computed. The radius of the circle is then used\nas an estimate of the curvature at the middle point. The point\nwith maximum curvature is then selected.\n\nThis routine is based on the paper\n\nM. Rezghi and S. M. Hosseini, \"A new variant of L-curve for Tikhonov\nregularization\", J. Comp. App. Math., 231 (2009).\n\nInputs: reg_param - vector of regularization parameters\n eta - vector of solution norms ||L x||\n idx - (output) index i such that\n (lambda(i)^2,eta(i)^2) is the point of\n maximum curvature\n\nReturn: success/error\n*/\n\nint\ngsl_multifit_linear_lcorner2(const gsl_vector *reg_param,\n const gsl_vector *eta,\n size_t *idx)\n{\n const size_t n = reg_param->size;\n\n if (n < 3)\n {\n GSL_ERROR (\"at least 3 points are needed for L-curve analysis\",\n GSL_EBADLEN);\n }\n else if (n != eta->size)\n {\n GSL_ERROR (\"size of reg_param and eta vectors do not match\",\n GSL_EBADLEN);\n }\n else\n {\n int s = GSL_SUCCESS;\n size_t i;\n double x1, y1; /* first point of triangle on L-curve */\n double x2, y2; /* second point of triangle on L-curve */\n double rmin = -1.0; /* minimum radius of curvature */\n\n /* initial values */\n x1 = gsl_vector_get(reg_param, 0);\n x1 *= x1;\n y1 = gsl_vector_get(eta, 0);\n y1 *= y1;\n\n x2 = gsl_vector_get(reg_param, 1);\n x2 *= x2;\n y2 = gsl_vector_get(eta, 1);\n y2 *= y2;\n\n for (i = 1; i < n - 1; ++i)\n {\n /*\n * The points (x1,y1), (x2,y2), (x3,y3) are the previous,\n * current, and next point on the L-curve. We will find\n * the circle which fits these 3 points and take its radius\n * as an estimate of the curvature at this point.\n */\n double lamip1 = gsl_vector_get(reg_param, i + 1);\n double etaip1 = gsl_vector_get(eta, i + 1);\n double x3 = lamip1 * lamip1;\n double y3 = etaip1 * etaip1;\n\n double x21 = x2 - x1;\n double y21 = y2 - y1;\n double x31 = x3 - x1;\n double y31 = y3 - y1;\n double h21 = x21*x21 + y21*y21;\n double h31 = x31*x31 + y31*y31;\n double d = fabs(2.0 * (x21*y31 - x31*y21));\n double r = sqrt(h21*h31*((x3-x2)*(x3-x2)+(y3-y2)*(y3-y2))) / d;\n\n /* if d =~ 0 then there are nearly colinear points */\n if (gsl_finite(r))\n {\n /* check for smallest radius of curvature */\n if (r < rmin || rmin < 0.0)\n {\n rmin = r;\n *idx = i;\n }\n }\n\n /* update previous/current L-curve values */\n x1 = x2;\n y1 = y2;\n x2 = x3;\n y2 = y3;\n }\n\n /* check if a minimum radius was found */\n if (rmin < 0.0)\n {\n /* possibly co-linear points */\n GSL_ERROR(\"failed to find minimum radius\", GSL_EINVAL);\n }\n\n return s;\n }\n} /* gsl_multifit_linear_lcorner2() */\n\n#define GSL_MULTIFIT_MAXK 100\n\n/*\ngsl_multifit_linear_L()\n Compute discrete approximation to derivative operator of order\nk on a regular grid of p points, ie: L is (p-k)-by-p\n*/\n\nint\ngsl_multifit_linear_Lk(const size_t p, const size_t k, gsl_matrix *L)\n{\n if (p <= k)\n {\n GSL_ERROR(\"p must be larger than derivative order\", GSL_EBADLEN);\n }\n else if (k >= GSL_MULTIFIT_MAXK - 1)\n {\n GSL_ERROR(\"derivative order k too large\", GSL_EBADLEN);\n }\n else if (p - k != L->size1 || p != L->size2)\n {\n GSL_ERROR(\"L matrix must be (p-k)-by-p\", GSL_EBADLEN);\n }\n else\n {\n double c_data[GSL_MULTIFIT_MAXK];\n gsl_vector_view cv = gsl_vector_view_array(c_data, k + 1);\n size_t i, j;\n\n /* zeroth derivative */\n if (k == 0)\n {\n gsl_matrix_set_identity(L);\n return GSL_SUCCESS;\n }\n\n gsl_matrix_set_zero(L);\n \n gsl_vector_set_zero(&cv.vector);\n gsl_vector_set(&cv.vector, 0, -1.0);\n gsl_vector_set(&cv.vector, 1, 1.0);\n\n for (i = 1; i < k; ++i)\n {\n double cjm1 = 0.0;\n\n for (j = 0; j < k + 1; ++j)\n {\n double cj = gsl_vector_get(&cv.vector, j);\n\n gsl_vector_set(&cv.vector, j, cjm1 - cj);\n cjm1 = cj;\n }\n }\n\n /* build L, the c_i are the entries on the diagonals */\n for (i = 0; i < k + 1; ++i)\n {\n gsl_vector_view v = gsl_matrix_superdiagonal(L, i);\n double ci = gsl_vector_get(&cv.vector, i);\n\n gsl_vector_set_all(&v.vector, ci);\n }\n\n return GSL_SUCCESS;\n }\n} /* gsl_multifit_linear_Lk() */\n\n/*\ngsl_multifit_linear_Lsobolev()\n Construct Sobolev smoothing norm operator\n\nL = [ a_0 I; a_1 L_1; a_2 L_2; ...; a_k L_k ]\n\nby computing the Cholesky factor of L^T L\n\nInputs: p - number of columns of L\n kmax - maximum derivative order (< p)\n alpha - vector of weights; alpha_k multiplies L_k, size kmax + 1\n L - (output) upper triangular Sobolev matrix p-by-p,\n stored in upper triangle\n work - workspace\n\nNotes:\n1) work->Q is used to store intermediate L_k matrices\n*/\n\nint\ngsl_multifit_linear_Lsobolev(const size_t p, const size_t kmax,\n const gsl_vector *alpha, gsl_matrix *L,\n gsl_multifit_linear_workspace *work)\n{\n if (p > work->pmax)\n {\n GSL_ERROR(\"p is larger than workspace\", GSL_EBADLEN);\n }\n else if (p <= kmax)\n {\n GSL_ERROR(\"p must be larger than derivative order\", GSL_EBADLEN);\n }\n else if (kmax + 1 != alpha->size)\n {\n GSL_ERROR(\"alpha must be size kmax + 1\", GSL_EBADLEN);\n }\n else if (p != L->size1)\n {\n GSL_ERROR(\"L matrix is wrong size\", GSL_EBADLEN);\n }\n else if (L->size1 != L->size2)\n {\n GSL_ERROR(\"L matrix is not square\", GSL_ENOTSQR);\n }\n else\n {\n int s;\n size_t j, k;\n gsl_vector_view d = gsl_matrix_diagonal(L);\n const double alpha0 = gsl_vector_get(alpha, 0);\n\n /* initialize L to alpha0^2 I */\n gsl_matrix_set_zero(L);\n gsl_vector_add_constant(&d.vector, alpha0 * alpha0);\n\n for (k = 1; k <= kmax; ++k)\n {\n gsl_matrix_view Lk = gsl_matrix_submatrix(work->Q, 0, 0, p - k, p);\n double ak = gsl_vector_get(alpha, k);\n\n /* compute a_k L_k */\n s = gsl_multifit_linear_Lk(p, k, &Lk.matrix);\n if (s)\n return s;\n\n gsl_matrix_scale(&Lk.matrix, ak);\n\n /* LTL += L_k^T L_k */\n gsl_blas_dsyrk(CblasLower, CblasTrans, 1.0, &Lk.matrix, 1.0, L);\n }\n\n s = gsl_linalg_cholesky_decomp(L);\n if (s)\n return s;\n\n /* copy Cholesky factor to upper triangle and zero out bottom */\n gsl_matrix_transpose_tricpy('L', 1, L, L);\n\n for (j = 0; j < p; ++j)\n {\n for (k = 0; k < j; ++k)\n gsl_matrix_set(L, j, k, 0.0);\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "4573fa930cd11bce3aad8330cd7b28d9345db1e8", "size": 36516, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/multifit/multireg.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/multireg.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/multireg.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": 29.9066339066, "max_line_length": 111, "alphanum_fraction": 0.544008106, "num_tokens": 10072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5039061705290806, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.26178999985308476}} {"text": "/*\n * Copyright (c) 2011-2018 The University of Tennessee and The University\n * of Tennessee Research Foundation. All rights\n * reserved.\n * Copyright (c) 2013 Inria. All rights reserved.\n *\n * @precisions normal z -> c d s\n *\n */\n\n#include \"dplasma.h\"\n#include \"dplasmatypes.h\"\n#include \"dplasmaaux.h\"\n#include \"parsec/data_dist/matrix/two_dim_rectangle_cyclic.h\"\n#include \"parsec/data_dist/matrix/vector_two_dim_cyclic.h\"\n\n#include \"zpltmg_chebvand.h\"\n#include \"zpltmg_fiedler.h\"\n#include \"zpltmg_hankel.h\"\n#include \"zpltmg_toeppd.h\"\n\n#include \n#include \n\n/**\n *******************************************************************************\n *\n * Generic case\n *\n *******************************************************************************\n */\nstruct zpltmg_args_s {\n PLASMA_enum mtxtype;\n unsigned long long int seed;\n parsec_complex64_t *W;\n};\ntypedef struct zpltmg_args_s zpltmg_args_t;\n\nstatic int\ndplasma_zpltmg_generic_operator( parsec_execution_stream_t *es,\n const parsec_tiled_matrix_dc_t *descA,\n void *_A,\n PLASMA_enum uplo, int m, int n,\n void *op_data )\n{\n int tempmm, tempnn, ldam;\n zpltmg_args_t *args = (zpltmg_args_t*)op_data;\n parsec_complex64_t *A = (parsec_complex64_t*)_A;\n (void)es;\n (void)uplo;\n\n tempmm = (m == (descA->mt-1)) ? (descA->m - m * descA->mb) : descA->mb;\n tempnn = (n == (descA->nt-1)) ? (descA->n - n * descA->nb) : descA->nb;\n ldam = BLKLDD( descA, m );\n\n if ( args->mtxtype == PlasmaMatrixCircul ) {\n return CORE_zpltmg_circul(\n tempmm, tempnn, A, ldam,\n descA->m, m*descA->mb, n*descA->nb, args->W );\n } else {\n return CORE_zpltmg(\n args->mtxtype, tempmm, tempnn, A, ldam,\n descA->m, descA->n, m*descA->mb, n*descA->nb, args->seed );\n }\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_generic - Generic wrapper for cases that are based on the map\n * function. This is the default for many test matrices generation.\n *\n * See parsec_apply() for further information.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in] mtxtype\n * Type of matrix to be generated.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[out] W\n * Workspace required by some generators.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_genvect\n * @sa dplasma_dpltmg_genvect\n * @sa dplasma_spltmg_genvect\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_generic( parsec_context_t *parsec,\n PLASMA_enum mtxtype,\n parsec_tiled_matrix_dc_t *A,\n parsec_complex64_t *W,\n unsigned long long int seed)\n{\n parsec_taskpool_t *parsec_zpltmg = NULL;\n zpltmg_args_t *params = (zpltmg_args_t*)malloc(sizeof(zpltmg_args_t));\n\n params->mtxtype = mtxtype;\n params->seed = seed;\n params->W = W;\n\n parsec_zpltmg = parsec_apply_New( PlasmaUpperLower, A, dplasma_zpltmg_generic_operator, params );\n if ( parsec_zpltmg != NULL )\n {\n parsec_context_add_taskpool(parsec, (parsec_taskpool_t*)parsec_zpltmg);\n dplasma_wait_until_completion(parsec);\n parsec_apply_Destruct( parsec_zpltmg );\n return 0;\n }\n return -101;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_genvect - Generic wrapper for cases that are using two\n * datatypes: the default one, and one describing a vector.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in] mtxtype\n * Type of matrix to be generated.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_genvect\n * @sa dplasma_dpltmg_genvect\n * @sa dplasma_spltmg_genvect\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_genvect( parsec_context_t *parsec,\n PLASMA_enum mtxtype,\n parsec_tiled_matrix_dc_t *A,\n unsigned long long int seed )\n{\n size_t vectorsize = 0;\n parsec_taskpool_t* tp;\n\n switch( mtxtype ) {\n case PlasmaMatrixChebvand:\n tp = (parsec_taskpool_t*)parsec_zpltmg_chebvand_new( seed,\n A );\n vectorsize = 2 * A->nb * sizeof(parsec_complex64_t);\n break;\n\n case PlasmaMatrixFiedler:\n tp = (parsec_taskpool_t*)parsec_zpltmg_fiedler_new( seed,\n A );\n vectorsize = A->mb * sizeof(parsec_complex64_t);\n break;\n\n case PlasmaMatrixHankel:\n tp = (parsec_taskpool_t*)parsec_zpltmg_hankel_new( seed,\n A );\n vectorsize = A->mb * sizeof(parsec_complex64_t);\n break;\n\n case PlasmaMatrixToeppd:\n tp = (parsec_taskpool_t*)parsec_zpltmg_toeppd_new( seed,\n A );\n vectorsize = 2 * A->mb * sizeof(parsec_complex64_t);\n break;\n\n default:\n return -2;\n }\n\n if (tp != NULL) {\n parsec_zpltmg_hankel_taskpool_t *zpltmg_tp = (parsec_zpltmg_hankel_taskpool_t*)tp;\n\n /* Default type */\n dplasma_add2arena_tile( zpltmg_tp->arenas[PARSEC_zpltmg_hankel_DEFAULT_ARENA],\n A->mb*A->nb*sizeof(parsec_complex64_t),\n PARSEC_ARENA_ALIGNMENT_SSE,\n parsec_datatype_double_complex_t, A->mb );\n\n /* Vector type */\n dplasma_add2arena_tile( zpltmg_tp->arenas[PARSEC_zpltmg_hankel_VECTOR_ARENA],\n vectorsize,\n PARSEC_ARENA_ALIGNMENT_SSE,\n parsec_datatype_double_complex_t, A->mb );\n\n parsec_context_add_taskpool(parsec, tp);\n dplasma_wait_until_completion(parsec);\n\n parsec_matrix_del2arena( zpltmg_tp->arenas[PARSEC_zpltmg_hankel_DEFAULT_ARENA] );\n parsec_matrix_del2arena( zpltmg_tp->arenas[PARSEC_zpltmg_hankel_VECTOR_ARENA ] );\n parsec_taskpool_free(tp);\n return 0;\n }\n return -101;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_circul - Generates a Circulant test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_circul\n * @sa dplasma_dpltmg_circul\n * @sa dplasma_spltmg_circul\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_circul( parsec_context_t *parsec,\n parsec_tiled_matrix_dc_t *A,\n unsigned long long int seed )\n{\n int info;\n parsec_complex64_t *V = (parsec_complex64_t*) malloc( A->m * sizeof(parsec_complex64_t) );\n\n CORE_zplrnt( A->m, 1, V, A->m, A->m, 0, 0, seed );\n\n info = dplasma_zpltmg_generic(parsec, PlasmaMatrixCircul, A, V, seed);\n\n free(V);\n return info;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_internal\n *\n * dplasma_zpltmg_condex - Generates a Condex test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_condex\n * @sa dplasma_dpltmg_condex\n * @sa dplasma_spltmg_condex\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_condex( parsec_context_t *parsec,\n parsec_tiled_matrix_dc_t *A )\n{\n /* gallery('condex', A->m, 4, 100.) */\n parsec_complex64_t theta = 100.;\n two_dim_block_cyclic_t *twodA = (two_dim_block_cyclic_t *)A;\n two_dim_block_cyclic_t Q;\n two_dim_block_cyclic_init( &Q, matrix_ComplexDouble, matrix_Tile,\n 1, A->super.myrank,\n A->mb, A->nb, A->mb*A->mt, 3, 0, 0, A->m, 3, twodA->grid.strows, twodA->grid.stcols, 1 );\n Q.mat = parsec_data_allocate((size_t)Q.super.nb_local_tiles *\n (size_t)Q.super.bsiz *\n (size_t)parsec_datadist_getsizeoftype(Q.super.mtype));\n parsec_data_collection_set_key((parsec_data_collection_t*)&Q, \"Q\");\n\n if (A->super.myrank == 0) {\n parsec_complex64_t *Qmat;\n\n Qmat = (parsec_complex64_t*)(Q.mat);\n\n /* Initialize the Q matrix */\n CORE_zpltmg_condexq( A->m, A->n, Qmat, Q.super.lm );\n\n /*\n * Conversion to tile layout\n */\n {\n parsec_complex64_t *W = (parsec_complex64_t*) malloc (A->mb * sizeof(parsec_complex64_t) );\n int *leaders = NULL;\n int i, nleaders;\n\n /* Get all the cycles leaders and length\n * They are the same for each independent problem (each panel) */\n GKK_getLeaderNbr( Q.super.lmt, A->nb, &nleaders, &leaders );\n\n /* shift cycles. */\n for(i=0; imb, A->mb * sizeof(parsec_complex64_t) );\n CORE_zshiftw(leaders[i*3], leaders[i*3+1], A->mt, A->nb, A->mb, Qmat, W);\n }\n\n free(leaders); free(W);\n }\n }\n\n dplasma_zlaset( parsec, PlasmaUpperLower, 0., 1. + theta, A );\n dplasma_zgemm( parsec, PlasmaNoTrans, PlasmaConjTrans,\n -theta, (parsec_tiled_matrix_dc_t*)&Q,\n (parsec_tiled_matrix_dc_t*)&Q,\n 1., A );\n\n parsec_data_free(Q.mat);\n parsec_tiled_matrix_dc_destroy((parsec_tiled_matrix_dc_t*)&Q);\n return 0;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg_house - Generates a Householder test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg_house\n * @sa dplasma_dpltmg_house\n * @sa dplasma_spltmg_house\n *\n ******************************************************************************/\nstatic inline int\ndplasma_zpltmg_house( parsec_context_t *parsec,\n parsec_tiled_matrix_dc_t *A,\n unsigned long long int seed )\n{\n /* gallery('house', random, 0 ) */\n vector_two_dim_cyclic_t V;\n parsec_complex64_t *Vmat, tau;\n\n vector_two_dim_cyclic_init( &V, matrix_ComplexDouble, PlasmaVectorDiag,\n 1, A->super.myrank,\n A->mb, A->m, 0, A->m, 1 );\n V.mat = parsec_data_allocate((size_t)V.super.nb_local_tiles *\n (size_t)V.super.bsiz *\n (size_t)parsec_datadist_getsizeoftype(V.super.mtype));\n parsec_data_collection_set_key((parsec_data_collection_t*)&V, \"V\");\n Vmat = (parsec_complex64_t*)(V.mat);\n\n /* Initialize Householder vector */\n if (A->super.myrank == 0) {\n CORE_zplrnt( A->m, 1, Vmat, A->m, A->m, 0, 0, seed );\n LAPACKE_zlarfg_work( A->m, Vmat, Vmat+1, 1, &tau );\n Vmat[0] = 1.;\n }\n\n#if defined(PARSEC_HAVE_MPI)\n /* If we don't need to broadcast, don't do it, this way we don't require MPI to be initialized */\n if( A->super.nodes > 1 )\n MPI_Bcast( &tau, 1, parsec_datatype_double_complex_t, 0, *(MPI_Comm*)dplasma_pcomm );\n#endif\n\n /* Compute the Householder matrix I - tau v * v' */\n dplasma_zlaset( parsec, PlasmaUpperLower, 0., 1., A);\n dplasma_zgerc( parsec, -tau,\n (parsec_tiled_matrix_dc_t*)&V,\n (parsec_tiled_matrix_dc_t*)&V,\n A );\n\n parsec_data_free(V.mat);\n parsec_tiled_matrix_dc_destroy((parsec_tiled_matrix_dc_t*)&V);\n\n return 0;\n}\n\n/**\n *******************************************************************************\n *\n * @ingroup dplasma_complex64\n *\n * dplasma_zpltmg - Generates a special test matrix by tiles.\n *\n *******************************************************************************\n *\n * @param[in,out] parsec\n * The parsec context of the application that will run the operation.\n *\n * @param[in] mtxtype\n * See PLASMA_zpltmg() for possible values and information on generated\n * matrices.\n *\n * @param[in,out] A\n * Descriptor of the distributed matrix A to generate. Any tiled matrix\n * descriptor can be used.\n * On exit, the matrix A generated.\n *\n * @param[in] seed\n * The seed used in the random generation.\n *\n *******************************************************************************\n *\n * @return\n * \\retval -i if the ith parameters is incorrect.\n * \\retval 0 on success.\n *\n *******************************************************************************\n *\n * @sa dplasma_cpltmg\n * @sa dplasma_dpltmg\n * @sa dplasma_spltmg\n *\n ******************************************************************************/\nint\ndplasma_zpltmg( parsec_context_t *parsec,\n PLASMA_enum mtxtype,\n parsec_tiled_matrix_dc_t *A,\n unsigned long long int seed)\n{\n\n switch( mtxtype ) {\n case PlasmaMatrixCircul:\n return dplasma_zpltmg_circul(parsec, A, seed);\n break;\n\n case PlasmaMatrixChebvand:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case PlasmaMatrixCondex:\n return dplasma_zpltmg_condex(parsec, A);\n break;\n\n case PlasmaMatrixFiedler:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case PlasmaMatrixHankel:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case PlasmaMatrixHouse:\n return dplasma_zpltmg_house(parsec, A, seed);\n break;\n\n case PlasmaMatrixToeppd:\n return dplasma_zpltmg_genvect(parsec, mtxtype,\n A, seed);\n break;\n\n case PlasmaMatrixCauchy:\n case PlasmaMatrixCompan:\n case PlasmaMatrixDemmel:\n case PlasmaMatrixDorr:\n case PlasmaMatrixFoster:\n case PlasmaMatrixHadamard:\n case PlasmaMatrixHilb:\n case PlasmaMatrixInvhess:\n case PlasmaMatrixKms:\n case PlasmaMatrixLangou:\n case PlasmaMatrixLehmer:\n case PlasmaMatrixLotkin:\n case PlasmaMatrixMinij:\n case PlasmaMatrixMoler:\n case PlasmaMatrixOrthog:\n case PlasmaMatrixParter:\n case PlasmaMatrixRandom:\n case PlasmaMatrixRiemann:\n case PlasmaMatrixRis:\n case PlasmaMatrixWilkinson:\n case PlasmaMatrixWright:\n return dplasma_zpltmg_generic(parsec, mtxtype, A, NULL, seed);\n break;\n default:\n return -2;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "83d9a5c014c593a01275552c51736120e9f2ea56", "size": 18147, "ext": "c", "lang": "C", "max_stars_repo_path": "dplasma/lib/zpltmg_wrapper.c", "max_stars_repo_name": "NLAFET/ABFT", "max_stars_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_stars_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-13T10:13:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-13T10:13:00.000Z", "max_issues_repo_path": "dplasma/lib/zpltmg_wrapper.c", "max_issues_repo_name": "NLAFET/ABFT", "max_issues_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_issues_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dplasma/lib/zpltmg_wrapper.c", "max_forks_repo_name": "NLAFET/ABFT", "max_forks_repo_head_hexsha": "73af5b9ffe65cdb06b58c0cb34029ee6265d2bf8", "max_forks_repo_licenses": ["BSD-3-Clause-Open-MPI"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9346642468, "max_line_length": 120, "alphanum_fraction": 0.51176503, "num_tokens": 4276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.2608342326594719}} {"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\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\n/* This file was automatically generated --- DO NOT EDIT */\n/* Generated on Sun Nov 7 20:44:44 EST 1999 */\n\n#include \n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-forward 5 */\n\n/*\n * This function contains 64 FP additions, 40 FP multiplications,\n * (or, 44 additions, 20 multiplications, 20 fused multiply/add),\n * 27 stack variables, and 40 memory accesses\n */\nstatic const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000);\nstatic const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590);\nstatic const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438);\nstatic const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634);\n\n/*\n * Generator Id's : \n * $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $\n * $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $\n * $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $\n */\n\nvoid fftw_hc2hc_forward_5(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist)\n{\n int i;\n fftw_real *X;\n fftw_real *Y;\n X = A;\n Y = A + (5 * iostride);\n {\n\t fftw_real tmp70;\n\t fftw_real tmp67;\n\t fftw_real tmp68;\n\t fftw_real tmp63;\n\t fftw_real tmp71;\n\t fftw_real tmp66;\n\t fftw_real tmp69;\n\t fftw_real tmp72;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp70 = X[0];\n\t {\n\t fftw_real tmp61;\n\t fftw_real tmp62;\n\t fftw_real tmp64;\n\t fftw_real tmp65;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp61 = X[4 * iostride];\n\t tmp62 = X[iostride];\n\t tmp67 = tmp62 + tmp61;\n\t tmp64 = X[2 * iostride];\n\t tmp65 = X[3 * iostride];\n\t tmp68 = tmp64 + tmp65;\n\t tmp63 = tmp61 - tmp62;\n\t tmp71 = tmp67 + tmp68;\n\t tmp66 = tmp64 - tmp65;\n\t }\n\t Y[-iostride] = (K951056516 * tmp63) - (K587785252 * tmp66);\n\t Y[-2 * iostride] = (K587785252 * tmp63) + (K951056516 * tmp66);\n\t X[0] = tmp70 + tmp71;\n\t tmp69 = K559016994 * (tmp67 - tmp68);\n\t tmp72 = tmp70 - (K250000000 * tmp71);\n\t X[iostride] = tmp69 + tmp72;\n\t X[2 * iostride] = tmp72 - tmp69;\n }\n X = X + dist;\n Y = Y - dist;\n for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 4) {\n\t fftw_real tmp13;\n\t fftw_real tmp52;\n\t fftw_real tmp42;\n\t fftw_real tmp45;\n\t fftw_real tmp49;\n\t fftw_real tmp50;\n\t fftw_real tmp51;\n\t fftw_real tmp54;\n\t fftw_real tmp53;\n\t fftw_real tmp24;\n\t fftw_real tmp35;\n\t fftw_real tmp36;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp13 = X[0];\n\t tmp52 = Y[-4 * iostride];\n\t {\n\t fftw_real tmp18;\n\t fftw_real tmp40;\n\t fftw_real tmp34;\n\t fftw_real tmp44;\n\t fftw_real tmp23;\n\t fftw_real tmp41;\n\t fftw_real tmp29;\n\t fftw_real tmp43;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp15;\n\t\t fftw_real tmp17;\n\t\t fftw_real tmp14;\n\t\t fftw_real tmp16;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp15 = X[iostride];\n\t\t tmp17 = Y[-3 * iostride];\n\t\t tmp14 = c_re(W[0]);\n\t\t tmp16 = c_im(W[0]);\n\t\t tmp18 = (tmp14 * tmp15) - (tmp16 * tmp17);\n\t\t tmp40 = (tmp16 * tmp15) + (tmp14 * tmp17);\n\t }\n\t {\n\t\t fftw_real tmp31;\n\t\t fftw_real tmp33;\n\t\t fftw_real tmp30;\n\t\t fftw_real tmp32;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp31 = X[3 * iostride];\n\t\t tmp33 = Y[-iostride];\n\t\t tmp30 = c_re(W[2]);\n\t\t tmp32 = c_im(W[2]);\n\t\t tmp34 = (tmp30 * tmp31) - (tmp32 * tmp33);\n\t\t tmp44 = (tmp32 * tmp31) + (tmp30 * tmp33);\n\t }\n\t {\n\t\t fftw_real tmp20;\n\t\t fftw_real tmp22;\n\t\t fftw_real tmp19;\n\t\t fftw_real tmp21;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp20 = X[4 * iostride];\n\t\t tmp22 = Y[0];\n\t\t tmp19 = c_re(W[3]);\n\t\t tmp21 = c_im(W[3]);\n\t\t tmp23 = (tmp19 * tmp20) - (tmp21 * tmp22);\n\t\t tmp41 = (tmp21 * tmp20) + (tmp19 * tmp22);\n\t }\n\t {\n\t\t fftw_real tmp26;\n\t\t fftw_real tmp28;\n\t\t fftw_real tmp25;\n\t\t fftw_real tmp27;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp26 = X[2 * iostride];\n\t\t tmp28 = Y[-2 * iostride];\n\t\t tmp25 = c_re(W[1]);\n\t\t tmp27 = c_im(W[1]);\n\t\t tmp29 = (tmp25 * tmp26) - (tmp27 * tmp28);\n\t\t tmp43 = (tmp27 * tmp26) + (tmp25 * tmp28);\n\t }\n\t tmp42 = tmp40 - tmp41;\n\t tmp45 = tmp43 - tmp44;\n\t tmp49 = tmp40 + tmp41;\n\t tmp50 = tmp43 + tmp44;\n\t tmp51 = tmp49 + tmp50;\n\t tmp54 = tmp29 - tmp34;\n\t tmp53 = tmp18 - tmp23;\n\t tmp24 = tmp18 + tmp23;\n\t tmp35 = tmp29 + tmp34;\n\t tmp36 = tmp24 + tmp35;\n\t }\n\t X[0] = tmp13 + tmp36;\n\t {\n\t fftw_real tmp46;\n\t fftw_real tmp48;\n\t fftw_real tmp39;\n\t fftw_real tmp47;\n\t fftw_real tmp37;\n\t fftw_real tmp38;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp46 = (K951056516 * tmp42) + (K587785252 * tmp45);\n\t tmp48 = (K951056516 * tmp45) - (K587785252 * tmp42);\n\t tmp37 = K559016994 * (tmp24 - tmp35);\n\t tmp38 = tmp13 - (K250000000 * tmp36);\n\t tmp39 = tmp37 + tmp38;\n\t tmp47 = tmp38 - tmp37;\n\t Y[-4 * iostride] = tmp39 - tmp46;\n\t X[iostride] = tmp39 + tmp46;\n\t X[2 * iostride] = tmp47 - tmp48;\n\t Y[-3 * iostride] = tmp47 + tmp48;\n\t }\n\t Y[0] = tmp51 + tmp52;\n\t {\n\t fftw_real tmp55;\n\t fftw_real tmp60;\n\t fftw_real tmp58;\n\t fftw_real tmp59;\n\t fftw_real tmp56;\n\t fftw_real tmp57;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp55 = (K951056516 * tmp53) + (K587785252 * tmp54);\n\t tmp60 = (K951056516 * tmp54) - (K587785252 * tmp53);\n\t tmp56 = K559016994 * (tmp49 - tmp50);\n\t tmp57 = tmp52 - (K250000000 * tmp51);\n\t tmp58 = tmp56 + tmp57;\n\t tmp59 = tmp57 - tmp56;\n\t X[4 * iostride] = -(tmp55 + tmp58);\n\t Y[-iostride] = tmp58 - tmp55;\n\t X[3 * iostride] = -(tmp59 - tmp60);\n\t Y[-2 * iostride] = tmp60 + tmp59;\n\t }\n }\n if (i == m) {\n\t fftw_real tmp8;\n\t fftw_real tmp3;\n\t fftw_real tmp6;\n\t fftw_real tmp9;\n\t fftw_real tmp12;\n\t fftw_real tmp11;\n\t fftw_real tmp7;\n\t fftw_real tmp10;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp8 = X[0];\n\t {\n\t fftw_real tmp1;\n\t fftw_real tmp2;\n\t fftw_real tmp4;\n\t fftw_real tmp5;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp1 = X[2 * iostride];\n\t tmp2 = X[3 * iostride];\n\t tmp3 = tmp1 - tmp2;\n\t tmp4 = X[4 * iostride];\n\t tmp5 = X[iostride];\n\t tmp6 = tmp4 - tmp5;\n\t tmp9 = tmp3 + tmp6;\n\t tmp12 = tmp4 + tmp5;\n\t tmp11 = tmp1 + tmp2;\n\t }\n\t X[2 * iostride] = tmp8 + tmp9;\n\t tmp7 = K559016994 * (tmp3 - tmp6);\n\t tmp10 = tmp8 - (K250000000 * tmp9);\n\t X[0] = tmp7 + tmp10;\n\t X[iostride] = tmp10 - tmp7;\n\t Y[0] = -((K951056516 * tmp11) + (K587785252 * tmp12));\n\t Y[-iostride] = -((K951056516 * tmp12) - (K587785252 * tmp11));\n }\n}\n\nstatic const int twiddle_order[] =\n{1, 2, 3, 4};\nfftw_codelet_desc fftw_hc2hc_forward_5_desc =\n{\n \"fftw_hc2hc_forward_5\",\n (void (*)()) fftw_hc2hc_forward_5,\n 5,\n FFTW_FORWARD,\n FFTW_HC2HC,\n 113,\n 4,\n twiddle_order,\n};\n", "meta": {"hexsha": "d64df79bd8ab78bfd1a02915225b94ead7a7317e", "size": 7839, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_5.c", "max_stars_repo_name": "albertsgrc/ftdock-opt", "max_stars_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2018-10-03T19:57:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T14:37:24.000Z", "max_issues_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_5.c", "max_issues_repo_name": "albertsgrc/ftdock-opt", "max_issues_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_5.c", "max_forks_repo_name": "albertsgrc/ftdock-opt", "max_forks_repo_head_hexsha": "3361d1f18bf529958b78231fdcf139b1c1c1f232", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-11-20T07:52:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T02:59:10.000Z", "avg_line_length": 29.1412639405, "max_line_length": 124, "alphanum_fraction": 0.5864268402, "num_tokens": 2606, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.41111086923216805, "lm_q1q2_score": 0.2604018440811736}} {"text": "//! \\file heat_driver.h\n//! Driver for Magnolia's heat transfer solver\n#ifndef ENRICO_SURROGATE_HEAT_DRIVER_H\n#define ENRICO_SURROGATE_HEAT_DRIVER_H\n\n#include \"driver.h\"\n\n#include \"pugixml.hpp\"\n#include \"xtensor/xtensor.hpp\"\n#include \n#include \n\n#include \n\nnamespace enrico {\n\nclass SurrogateHeatDriver : public Driver {\npublic:\n //! Initializes heat-fluids surrogate with the given MPI communicator.\n //!\n //! \\param comm The MPI communicator used to initialze the surrogate\n //! \\param node XML node containing settings for surrogate\n explicit SurrogateHeatDriver(MPI_Comm comm, pugi::xml_node node);\n\n //! Solves the heat-fluids surrogate solver\n void solve_step() final;\n\n //! Number of rings in fuel and clad\n //! \\return Number of rings\n std::size_t n_rings() { return n_fuel_rings_ + n_clad_rings_; }\n\n //! Write data to VTK\n void write_step(int timestep, int iteration) final;\n\n xt::xtensor temperature() const;\n\n double temperature(int pin, int axial, int ring) const;\n\n // Data on fuel pins\n xt::xtensor pin_centers_; //!< (x,y) values for center of fuel pins\n xt::xtensor z_; //!< Bounding z-values for axial segments\n std::size_t n_pins_; //!< number of fuel pins\n std::size_t n_axial_; //!< number of axial segments\n\n // Dimensions for a single fuel pin axial segment\n double clad_outer_radius_; //!< clad outer radius in [cm]\n double clad_inner_radius_; //!< clad inner radius in [cm]\n double pellet_radius_; //!< fuel pellet radius in [cm]\n std::size_t n_fuel_rings_{20}; //!< number of fuel rings\n std::size_t n_clad_rings_{2}; //!< number of clad rings\n\n // solver variables and settings\n double tol_; //!< tolerance on convergence\n xt::xtensor source_; //!< heat source for each (axial segment, ring)\n xt::xtensor r_grid_clad_; //!< radii of each clad ring in [cm]\n xt::xtensor r_grid_fuel_; //!< radii of each fuel ring in [cm]\n\n // visualization\n std::string viz_basename_{\n \"heat_surrogate\"}; //!< base filename for visualization files (default: magnolia)\n std::string viz_iterations_{\n \"none\"}; //!< visualization iterations to write (none, all, final)\n std::string viz_data_{\"all\"}; //!< visualization data to write\n std::string viz_regions_{\"all\"}; //!< visualization regions to write\n size_t vtk_radial_res_{20}; //!< radial resolution of resulting vtk files\n\nprivate:\n //! Create internal arrays used for heat equation solver\n void generate_arrays();\n\n //!< temperature in [K] for each (axial segment, ring)\n xt::xtensor temperature_;\n\n}; // end SurrogateHeatDriver\n\n} // namespace enrico\n\n#endif //ENRICO_SURROGATE_HEAT_DRIVER_H\n", "meta": {"hexsha": "2ccb7c9b6bc2a2b6a09f1b6241497563624fbdd2", "size": 2807, "ext": "h", "lang": "C", "max_stars_repo_path": "include/enrico/surrogate_heat_driver.h", "max_stars_repo_name": "aprilnovak/enrico", "max_stars_repo_head_hexsha": "991880628a4bd3c2695d475f3f37edf5b13f85dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/enrico/surrogate_heat_driver.h", "max_issues_repo_name": "aprilnovak/enrico", "max_issues_repo_head_hexsha": "991880628a4bd3c2695d475f3f37edf5b13f85dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-12-11T16:51:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-11T16:51:18.000Z", "max_forks_repo_path": "include/enrico/surrogate_heat_driver.h", "max_forks_repo_name": "aprilnovak/enrico", "max_forks_repo_head_hexsha": "991880628a4bd3c2695d475f3f37edf5b13f85dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5316455696, "max_line_length": 89, "alphanum_fraction": 0.691841824, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.4416730056646256, "lm_q1q2_score": 0.2600964323894571}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"php_rindow_openblas.h\"\n\n\nstatic zend_object_handlers rindow_openblas_blas_object_handlers;\n\n// destractor\nstatic void php_rindow_openblas_blas_free_object(zend_object* object)\n{\n zend_object_std_dtor(object);\n}\n\n// constructor\nstatic zend_object* php_rindow_openblas_blas_create_object(zend_class_entry* class_type) /* {{{ */\n{\n zend_object* intern = NULL;\n\n intern = (zend_object*)ecalloc(1, sizeof(zend_object) + zend_object_properties_size(class_type));\n\n zend_object_std_init(intern, class_type);\n object_properties_init(intern, class_type);\n\n intern->handlers = &rindow_openblas_blas_object_handlers;\n\n return intern;\n} /* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function getNumThreads() : int\n {{{ */\nstatic PHP_METHOD(Blas, getNumThreads)\n{\n int n;\n n = openblas_get_num_threads();\n RETURN_LONG(n);\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function getNumProcs() : int\n {{{ */\nstatic PHP_METHOD(Blas, getNumProcs)\n{\n int n;\n n = openblas_get_num_procs();\n RETURN_LONG(n);\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function getConfig() : string\n {{{ */\nstatic PHP_METHOD(Blas, getConfig)\n{\n char *s;\n s = openblas_get_config();\n RETURN_STRING(s);\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function getCorename() : string\n {{{ */\nstatic PHP_METHOD(Blas, getCorename)\n{\n char *s;\n s = openblas_get_corename();\n RETURN_STRING(s);\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function scal(\n int $n,\n float $alpha,\n Buffer $X, int $offsetX, int $incX) : void\n {{{ */\nstatic PHP_METHOD(Blas, scal)\n{\n php_interop_polite_math_matrix_linear_buffer_t* buffer;\n zend_long n;\n double alpha;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 5, 5)\n Z_PARAM_LONG(n)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n ZEND_PARSE_PARAMETERS_END();\n\n buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(buffer,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) {\n return;\n }\n switch (buffer->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_sscal((blasint)n, (float)alpha, &(((float *)buffer->data)[offsetX]), (blasint)incX);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dscal((blasint)n, (double)alpha, &(((double *)buffer->data)[offsetX]), (blasint)incX);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function axpy(\n int $n,\n float $alpha,\n Buffer $X, int $offsetX, int $incX,\n Buffer $Y, int $offsetY, int $incY ) : void\n {{{ */\nstatic PHP_METHOD(Blas, axpy)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferX;\n php_interop_polite_math_matrix_linear_buffer_t* bufferY;\n zend_long n;\n double alpha;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n zval* y=NULL;\n zend_long offsetY;\n zend_long incY;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 8, 8)\n Z_PARAM_LONG(n)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n Z_PARAM_OBJECT(y) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetY)\n Z_PARAM_LONG(incY)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer X\n bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(bufferX,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) {\n return;\n }\n\n // Check Buffer Y\n bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y);\n if(php_rindow_openblas_assert_buffer_type(bufferY,\"y\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) {\n return;\n }\n\n // Check Buffer X and Y\n if(bufferX->dtype!=bufferY->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for X and Y\", 0);\n return;\n }\n\n switch (bufferX->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_saxpy((blasint)n, (float)alpha,\n &(((float *)bufferX->data)[offsetX]), (blasint)incX,\n &(((float *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_daxpy((blasint)n, (double)alpha,\n &(((double *)bufferX->data)[offsetX]), (blasint)incX,\n &(((double *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function dot(\n int $n,\n Buffer $X, int $offsetX, int $incX,\n Buffer $Y, int $offsetY, int $incY ) : float\n {{{ */\nstatic PHP_METHOD(Blas, dot)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferX;\n php_interop_polite_math_matrix_linear_buffer_t* bufferY;\n zend_long n;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n zval* y=NULL;\n zend_long offsetY;\n zend_long incY;\n double result;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n Z_PARAM_OBJECT(y) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetY)\n Z_PARAM_LONG(incY)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer X\n bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(bufferX,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) {\n return;\n }\n\n // Check Buffer Y\n bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y);\n if(php_rindow_openblas_assert_buffer_type(bufferY,\"y\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) {\n return;\n }\n\n // Check Buffer X and Y\n if(bufferX->dtype!=bufferY->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for X and Y\", 0);\n return;\n }\n\n switch (bufferX->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n result = (double)cblas_sdot((blasint)n,\n &(((float *)bufferX->data)[offsetX]), (blasint)incX,\n &(((float *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n result = (double)cblas_ddot((blasint)n,\n &(((double *)bufferX->data)[offsetX]), (blasint)incX,\n &(((double *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n RETURN_DOUBLE(result);\n}\n/* }}} */\n\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function asum(\n int $n,\n Buffer $X, int $offsetX, int $incX ) : float\n {{{ */\nstatic PHP_METHOD(Blas, asum)\n{\n php_interop_polite_math_matrix_linear_buffer_t* buffer;\n zend_long n;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n double result;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(buffer,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) {\n return;\n }\n switch (buffer->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n result = (double)cblas_sasum((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n result = (double)cblas_dasum((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n RETURN_DOUBLE(result);\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function iamax(\n int $n,\n Buffer $X, int $offsetX, int $incX ) : int\n {{{ */\nstatic PHP_METHOD(Blas, iamax)\n{\n php_interop_polite_math_matrix_linear_buffer_t* buffer;\n zend_long n;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n zend_long resultIdx;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(buffer,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) {\n return;\n }\n switch (buffer->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n resultIdx = (zend_long)cblas_isamax((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n resultIdx = (zend_long)cblas_idamax((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n RETURN_LONG(resultIdx);\n}\n/* }}} */\n\n#ifdef OPENBLAS_HAVE_IAMIN\n/* Method Rindow\\OpenBLAS\\Blas::\n public function iamin(\n int $n,\n Buffer $X, int $offsetX, int $incX ) : int\n {{{ */\nstatic PHP_METHOD(Blas, iamin)\n{\n php_interop_polite_math_matrix_linear_buffer_t* buffer;\n zend_long n;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n zend_long resultIdx;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 4, 4)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n buffer = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(buffer,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, buffer,n,offsetX,incX)) {\n return;\n }\n switch (buffer->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n resultIdx = (zend_long)cblas_isamin((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n resultIdx = (zend_long)cblas_idamin((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n RETURN_LONG(resultIdx);\n}\n/* }}} */\n#endif\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function copy(\n int $n,\n Buffer $X, int $offsetX, int $incX,\n Buffer $Y, int $offsetY, int $incY ) : void\n {{{ */\nstatic PHP_METHOD(Blas, copy)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferX;\n php_interop_polite_math_matrix_linear_buffer_t* bufferY;\n zend_long n;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n zval* y=NULL;\n zend_long offsetY;\n zend_long incY;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n Z_PARAM_OBJECT(y) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetY)\n Z_PARAM_LONG(incY)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer X\n bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(bufferX,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) {\n return;\n }\n\n // Check Buffer Y\n bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y);\n if(php_rindow_openblas_assert_buffer_type(bufferY,\"y\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) {\n return;\n }\n\n // Check Buffer X and Y\n if(bufferX->dtype!=bufferY->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for X and Y\", 0);\n return;\n }\n\n switch (bufferX->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_scopy((blasint)n,\n &(((float *)bufferX->data)[offsetX]), (blasint)incX,\n &(((float *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dcopy((blasint)n,\n &(((double *)bufferX->data)[offsetX]), (blasint)incX,\n &(((double *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n default:\n {\n zend_long i,idX,idY;\n int valueSize;\n uint8_t *x,*y;\n valueSize = php_rindow_openblas_common_dtype_to_valuesize(bufferX->dtype);\n x = php_rindow_openblas_get_address(bufferX,offsetX,valueSize);\n y = php_rindow_openblas_get_address(bufferY,offsetY,valueSize);\n if(incX==1 && incY==1) {\n memcpy(y,x,valueSize*n);\n } else {\n for(i=0,idX=0,idY=0; idtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n result = (double)cblas_snrm2((blasint)n, &(((float *)buffer->data)[offsetX]), (blasint)incX);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n result = (double)cblas_dnrm2((blasint)n, &(((double *)buffer->data)[offsetX]), (blasint)incX);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n RETURN_DOUBLE(result);\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function rotg(\n Buffer $A, int $offsetA,\n Buffer $B, int $offsetB,\n Buffer $C, int $offsetC,\n Buffer $S, int $offsetS,\n ) : void\n {{{ */\nstatic PHP_METHOD(Blas, rotg)\n{\n zval* a;\n zend_long offsetA;\n zval* b;\n zend_long offsetB;\n zval* c;\n zend_long offsetC;\n zval* s;\n zend_long offsetS;\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferB;\n php_interop_polite_math_matrix_linear_buffer_t* bufferC;\n php_interop_polite_math_matrix_linear_buffer_t* bufferS;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 8, 8)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_OBJECT(b) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetB)\n Z_PARAM_OBJECT(c) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetC)\n Z_PARAM_OBJECT(s) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetS)\n ZEND_PARSE_PARAMETERS_END();\n\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferA,1,offsetA,1)) {\n return;\n }\n\n // Check Buffer B\n bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b);\n if(php_rindow_openblas_assert_buffer_type(bufferB,\"b\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferB,1,offsetB,1)) {\n return;\n }\n\n // Check Buffer C\n bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c);\n if(php_rindow_openblas_assert_buffer_type(bufferC,\"c\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferC,1,offsetC,1)) {\n return;\n }\n\n // Check Buffer S\n bufferS = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(s);\n if(php_rindow_openblas_assert_buffer_type(bufferS,\"s\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferS,1,offsetS,1)) {\n return;\n }\n\n\n // Check Buffer A and B and C and S\n if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype ||\n bufferC->dtype!=bufferS->dtype || bufferS->dtype!=bufferA->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A,B,C and S\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_srotg(\n &(((float *)bufferA->data)[offsetA]),\n &(((float *)bufferB->data)[offsetB]),\n &(((float *)bufferC->data)[offsetC]),\n &(((float *)bufferS->data)[offsetS])\n );\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_drotg(\n &(((double *)bufferA->data)[offsetA]),\n &(((double *)bufferB->data)[offsetB]),\n &(((double *)bufferC->data)[offsetC]),\n &(((double *)bufferS->data)[offsetS])\n );\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function rot(\n int $n,\n Buffer $X, int $offsetX, int $incX,\n Buffer $Y, int $offsetY, int $incY,\n Buffer $C, int $offsetC,\n Buffer $S, int $offsetS,\n ) : void\n {{{ */\nstatic PHP_METHOD(Blas, rot)\n{\n zend_long n;\n zval* x;\n zend_long offsetX;\n zend_long incX;\n zval* y;\n zend_long offsetY;\n zend_long incY;\n zval* c;\n zend_long offsetC;\n zval* s;\n zend_long offsetS;\n php_interop_polite_math_matrix_linear_buffer_t* bufferX;\n php_interop_polite_math_matrix_linear_buffer_t* bufferY;\n php_interop_polite_math_matrix_linear_buffer_t* bufferC;\n php_interop_polite_math_matrix_linear_buffer_t* bufferS;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 11, 11)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n Z_PARAM_OBJECT(y) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetY)\n Z_PARAM_LONG(incY)\n Z_PARAM_OBJECT(c) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetC)\n Z_PARAM_OBJECT(s) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetS)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer X\n bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(bufferX,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) {\n return;\n }\n\n // Check Buffer Y\n bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y);\n if(php_rindow_openblas_assert_buffer_type(bufferY,\"y\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) {\n return;\n }\n\n // Check Buffer C\n bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c);\n if(php_rindow_openblas_assert_buffer_type(bufferC,\"c\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferC,1,offsetC,1)) {\n return;\n }\n\n // Check Buffer S\n bufferS = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(s);\n if(php_rindow_openblas_assert_buffer_type(bufferS,\"s\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferS,1,offsetS,1)) {\n return;\n }\n\n // Check Buffer X and Y\n if(bufferX->dtype!=bufferY->dtype||bufferY->dtype!=bufferC->dtype||\n bufferC->dtype!=bufferS->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for X,Y,C and S\", 0);\n return;\n }\n\n switch (bufferX->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_srot((blasint)n,\n &(((float *)bufferX->data)[offsetX]), (blasint)incX,\n &(((float *)bufferY->data)[offsetY]), (blasint)incY,\n ((float *)bufferC->data)[offsetC],\n ((float *)bufferS->data)[offsetS]\n );\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_drot((blasint)n,\n &(((double *)bufferX->data)[offsetX]), (blasint)incX,\n &(((double *)bufferY->data)[offsetY]), (blasint)incY,\n ((double *)bufferC->data)[offsetC],\n ((double *)bufferS->data)[offsetS]\n );\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function swap(\n int $n,\n Buffer $X, int $offsetX, int $incX,\n Buffer $Y, int $offsetY, int $incY ) : void\n {{{ */\nstatic PHP_METHOD(Blas, swap)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferX;\n php_interop_polite_math_matrix_linear_buffer_t* bufferY;\n zend_long n;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n zval* y=NULL;\n zend_long offsetY;\n zend_long incY;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 7, 7)\n Z_PARAM_LONG(n)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n Z_PARAM_OBJECT(y) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetY)\n Z_PARAM_LONG(incY)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer X\n bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(bufferX,\"x\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,n,offsetX,incX)) {\n return;\n }\n\n // Check Buffer Y\n bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y);\n if(php_rindow_openblas_assert_buffer_type(bufferY,\"y\")) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,n,offsetY,incY)) {\n return;\n }\n\n // Check Buffer X and Y\n if(bufferX->dtype!=bufferY->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for X and Y\", 0);\n return;\n }\n\n switch (bufferX->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_sswap((blasint)n,\n &(((float *)bufferX->data)[offsetX]), (blasint)incX,\n &(((float *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dswap((blasint)n,\n &(((double *)bufferX->data)[offsetX]), (blasint)incX,\n &(((double *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function gemv(\n int $order,\n int $trans,\n int $m,\n int $n,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n Buffer $X, int $offsetX, int $incX,\n float $beta,\n Buffer $Y, int $offsetY, int $incY ) : void\n {{{ */\nstatic PHP_METHOD(Blas, gemv)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferX;\n php_interop_polite_math_matrix_linear_buffer_t* bufferY;\n zend_long order;\n zend_long trans;\n zend_long m;\n zend_long n;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n zval* x=NULL;\n zend_long offsetX;\n zend_long incX;\n double beta;\n zval* y=NULL;\n zend_long offsetY;\n zend_long incY;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 15, 15)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(trans)\n Z_PARAM_LONG(m)\n Z_PARAM_LONG(n)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_OBJECT(x) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetX)\n Z_PARAM_LONG(incX)\n Z_PARAM_DOUBLE(beta)\n Z_PARAM_OBJECT(y) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetY)\n Z_PARAM_LONG(incY)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_M, m)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,m,n,offsetA,ldA)) {\n return;\n }\n\n // Check Buffer X\n bufferX = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(x);\n if(php_rindow_openblas_assert_buffer_type(bufferX,\"x\")) {\n return;\n }\n\n // Check Buffer Y\n bufferY = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(y);\n if(php_rindow_openblas_assert_buffer_type(bufferY,\"y\")) {\n return;\n }\n\n // Check Buffer size X and Y\n {\n zend_long rows,cols;\n if(trans==CblasNoTrans || trans==CblasConjNoTrans ) {\n rows = m; cols = n;\n } else if(trans==CblasTrans || trans==CblasConjTrans) {\n rows = n; cols = m;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_X, bufferX,cols,offsetX,incX)) {\n return;\n }\n if(php_rindow_openblas_assert_vector_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_Y, bufferY,rows,offsetY,incY)) {\n return;\n }\n }\n\n // Check Buffer A and X and Y\n if(bufferA->dtype!=bufferX->dtype || bufferX->dtype!=bufferY->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and X and Y\", 0);\n return;\n }\n\n switch (bufferX->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_sgemv(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (blasint)m,(blasint)n,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((float *)bufferX->data)[offsetX]), (blasint)incX,\n (float)beta,\n &(((float *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dgemv(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (blasint)m,(blasint)n,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((double *)bufferX->data)[offsetX]), (blasint)incX,\n (double)beta,\n &(((double *)bufferY->data)[offsetY]), (blasint)incY);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function gemm(\n int $order,\n int $transA,\n int $transB,\n int $m,\n int $n,\n int $k,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n Buffer $B, int $offsetB, int $ldB,\n float $beta,\n Buffer $C, int $offsetC, int $ldC ) : void\n {{{ */\nstatic PHP_METHOD(Blas, gemm)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferB;\n php_interop_polite_math_matrix_linear_buffer_t* bufferC;\n zend_long order;\n zend_long transA;\n zend_long transB;\n zend_long m;\n zend_long n;\n zend_long k;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n zval* b=NULL;\n zend_long offsetB;\n zend_long ldB;\n double beta;\n zval* c=NULL;\n zend_long offsetC;\n zend_long ldC;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 17, 17)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(transA)\n Z_PARAM_LONG(transB)\n Z_PARAM_LONG(m)\n Z_PARAM_LONG(n)\n Z_PARAM_LONG(k)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_OBJECT(b) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetB)\n Z_PARAM_LONG(ldB)\n Z_PARAM_DOUBLE(beta)\n Z_PARAM_OBJECT(c) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetC)\n Z_PARAM_LONG(ldC)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_M, m)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_K, k)) {\n return;\n }\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n {\n zend_long rows,cols;\n if(transA==CblasNoTrans || transA==CblasConjNoTrans) {\n rows = m; cols = k;\n } else if(transA==CblasTrans || transA==CblasConjTrans) {\n rows = k; cols = m;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,cols,offsetA,ldA)) {\n return;\n }\n }\n\n // Check Buffer B\n bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b);\n if(php_rindow_openblas_assert_buffer_type(bufferB,\"b\")) {\n return;\n }\n {\n zend_long rows,cols;\n if(transB==CblasNoTrans || transB==CblasConjNoTrans) {\n rows = k; cols = n;\n } else if(transB==CblasTrans || transB==CblasConjTrans) {\n rows = n; cols = k;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferB.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,rows,cols,offsetB,ldB)) {\n return;\n }\n }\n\n // Check Buffer C\n bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c);\n if(php_rindow_openblas_assert_buffer_type(bufferC,\"c\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,m,n,offsetC,ldC)) {\n return;\n }\n\n // Check Buffer A and B and C\n if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and B and C\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_sgemm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transA,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transB,\n (blasint)m,(blasint)n,(blasint)k,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((float *)bufferB->data)[offsetB]), (blasint)ldB,\n (float)beta,\n &(((float *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dgemm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transA,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)transB,\n (blasint)m,(blasint)n,(blasint)k,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((double *)bufferB->data)[offsetB]), (blasint)ldB,\n (double)beta,\n &(((double *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function symm(\n int $order,\n int $side,\n int $uplo,\n int $m,\n int $n,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n Buffer $B, int $offsetB, int $ldB,\n float $beta,\n Buffer $C, int $offsetC, int $ldC ) : void\n {{{ */\nstatic PHP_METHOD(Blas, symm)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferB;\n php_interop_polite_math_matrix_linear_buffer_t* bufferC;\n zend_long order;\n zend_long side;\n zend_long uplo;\n zend_long m;\n zend_long n;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n zval* b=NULL;\n zend_long offsetB;\n zend_long ldB;\n double beta;\n zval* c=NULL;\n zend_long offsetC;\n zend_long ldC;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 16, 16)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(side)\n Z_PARAM_LONG(uplo)\n Z_PARAM_LONG(m)\n Z_PARAM_LONG(n)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_OBJECT(b) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetB)\n Z_PARAM_LONG(ldB)\n Z_PARAM_DOUBLE(beta)\n Z_PARAM_OBJECT(c) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetC)\n Z_PARAM_LONG(ldC)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_M, m)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n if(!php_interop_polite_math_matrix_is_linear_buffer(bufferA)) {\n zend_throw_exception(zend_ce_type_error, \"invalid type.\", 0);\n return;\n }\n {\n zend_long rows;\n if(side==CblasLeft) {\n rows = m;\n } else if(side==CblasRight) {\n rows = n;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown side mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,rows,offsetA,ldA)) {\n return;\n }\n }\n\n // Check Buffer B\n bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b);\n if(php_rindow_openblas_assert_buffer_type(bufferB,\"b\")) {\n return;\n }\n {\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,m,n,offsetB,ldB)) {\n return;\n }\n }\n\n // Check Buffer C\n bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c);\n if(php_rindow_openblas_assert_buffer_type(bufferC,\"c\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,m,n,offsetC,ldC)) {\n return;\n }\n\n // Check Buffer A and B and C\n if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and B and C\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_ssymm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_SIDE)side,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (blasint)m,(blasint)n,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((float *)bufferB->data)[offsetB]), (blasint)ldB,\n (float)beta,\n &(((float *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dsymm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_SIDE)side,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (blasint)m,(blasint)n,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((double *)bufferB->data)[offsetB]), (blasint)ldB,\n (double)beta,\n &(((double *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function syrk(\n int $order,\n int $uplo,\n int $trans,\n int $n,\n int $k,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n float $beta,\n Buffer $C, int $offsetC, int $ldC ) : void\n {{{ */\nstatic PHP_METHOD(Blas, syrk)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferC;\n zend_long order;\n zend_long uplo;\n zend_long trans;\n zend_long n;\n zend_long k;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n double beta;\n zval* c=NULL;\n zend_long offsetC;\n zend_long ldC;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 13, 13)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(uplo)\n Z_PARAM_LONG(trans)\n Z_PARAM_LONG(n)\n Z_PARAM_LONG(k)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_DOUBLE(beta)\n Z_PARAM_OBJECT(c) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetC)\n Z_PARAM_LONG(ldC)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_K, k)) {\n return;\n }\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n {\n zend_long rows,cols;\n if(trans==CblasNoTrans || trans==CblasConjNoTrans) {\n rows = n; cols = k;\n } else if(trans==CblasTrans || trans==CblasConjTrans) {\n rows = k; cols = n;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,cols,offsetA,ldA)) {\n return;\n }\n }\n\n // Check Buffer C\n bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c);\n if(php_rindow_openblas_assert_buffer_type(bufferC,\"c\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,n,n,offsetC,ldC)) {\n return;\n }\n\n // Check Buffer A and C\n if(bufferA->dtype!=bufferC->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and C\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_ssyrk(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (blasint)n,(blasint)k,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n (float)beta,\n &(((float *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dsyrk(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (blasint)n,(blasint)k,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n (double)beta,\n &(((double *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function syr2k(\n int $order,\n int $uplo,\n int $trans,\n int $n,\n int $k,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n Buffer $B, int $offsetB, int $ldB,\n float $beta,\n Buffer $C, int $offsetC, int $ldC ) : void\n {{{ */\nstatic PHP_METHOD(Blas, syr2k)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferB;\n php_interop_polite_math_matrix_linear_buffer_t* bufferC;\n zend_long order;\n zend_long uplo;\n zend_long trans;\n zend_long n;\n zend_long k;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n zval* b=NULL;\n zend_long offsetB;\n zend_long ldB;\n double beta;\n zval* c=NULL;\n zend_long offsetC;\n zend_long ldC;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 16, 16)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(uplo)\n Z_PARAM_LONG(trans)\n Z_PARAM_LONG(n)\n Z_PARAM_LONG(k)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_OBJECT(b) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetB)\n Z_PARAM_LONG(ldB)\n Z_PARAM_DOUBLE(beta)\n Z_PARAM_OBJECT(c) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetC)\n Z_PARAM_LONG(ldC)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_M, k)) {\n return;\n }\n // Check Buffer A and B\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b);\n if(php_rindow_openblas_assert_buffer_type(bufferB,\"b\")) {\n return;\n }\n {\n zend_long rows,cols;\n if(trans==CblasNoTrans || trans==CblasConjNoTrans) {\n rows = n; cols = k;\n } else if(trans==CblasTrans || trans==CblasConjTrans) {\n rows = k; cols = n;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,rows,cols,offsetA,ldA)) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,rows,cols,offsetB,ldB)) {\n return;\n }\n }\n\n // Check Buffer C\n bufferC = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(c);\n if(php_rindow_openblas_assert_buffer_type(bufferC,\"c\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_C, bufferC,n,n,offsetC,ldC)) {\n return;\n }\n\n // Check Buffer A and B and C\n if(bufferA->dtype!=bufferB->dtype || bufferB->dtype!=bufferC->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and B and C\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_ssyr2k(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (blasint)n,(blasint)k,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((float *)bufferB->data)[offsetB]), (blasint)ldB,\n (float)beta,\n &(((float *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dsyr2k(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (blasint)n,(blasint)k,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((double *)bufferB->data)[offsetB]), (blasint)ldB,\n (double)beta,\n &(((double *)bufferC->data)[offsetC]), (blasint)ldC);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function trmm(\n int $order,\n int $side,\n int $uplo,\n int $trans,\n int $diag,\n int $m,\n int $n,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n Buffer $B, int $offsetB, int $ldB) : void\n {{{ */\nstatic PHP_METHOD(Blas, trmm)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferB;\n zend_long order;\n zend_long side;\n zend_long uplo;\n zend_long trans;\n zend_long diag;\n zend_long m;\n zend_long n;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n zval* b=NULL;\n zend_long offsetB;\n zend_long ldB;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 14, 14)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(side)\n Z_PARAM_LONG(uplo)\n Z_PARAM_LONG(trans)\n Z_PARAM_LONG(diag)\n Z_PARAM_LONG(m)\n Z_PARAM_LONG(n)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_OBJECT(b) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetB)\n Z_PARAM_LONG(ldB)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_M, m)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n {\n zend_long sizeA;\n if(side==CblasLeft) {\n sizeA = m;\n } else if(side==CblasRight) {\n sizeA = n;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,sizeA,sizeA,offsetA,ldA)) {\n return;\n }\n }\n bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b);\n if(php_rindow_openblas_assert_buffer_type(bufferB,\"b\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,m,n,offsetB,ldB)) {\n return;\n }\n\n // Check Buffer A and B\n if(bufferA->dtype!=bufferB->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and B\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_strmm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_SIDE)side,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (OPENBLAS_CONST enum CBLAS_DIAG)diag,\n (blasint)m,(blasint)n,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((float *)bufferB->data)[offsetB]), (blasint)ldB);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dtrmm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_SIDE)side,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (OPENBLAS_CONST enum CBLAS_DIAG)diag,\n (blasint)m,(blasint)n,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((double *)bufferB->data)[offsetB]), (blasint)ldB);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\n/* Method Rindow\\OpenBLAS\\Blas::\n public function trsm(\n int $order,\n int $side,\n int $uplo,\n int $trans,\n int $diag,\n int $m,\n int $n,\n float $alpha,\n Buffer $A, int $offsetA, int $ldA,\n Buffer $B, int $offsetB, int $ldB) : void\n {{{ */\nstatic PHP_METHOD(Blas, trsm)\n{\n php_interop_polite_math_matrix_linear_buffer_t* bufferA;\n php_interop_polite_math_matrix_linear_buffer_t* bufferB;\n zend_long order;\n zend_long side;\n zend_long uplo;\n zend_long trans;\n zend_long diag;\n zend_long m;\n zend_long n;\n double alpha;\n zval* a=NULL;\n zend_long offsetA;\n zend_long ldA;\n zval* b=NULL;\n zend_long offsetB;\n zend_long ldB;\n\n ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 14, 14)\n Z_PARAM_LONG(order)\n Z_PARAM_LONG(side)\n Z_PARAM_LONG(uplo)\n Z_PARAM_LONG(trans)\n Z_PARAM_LONG(diag)\n Z_PARAM_LONG(m)\n Z_PARAM_LONG(n)\n Z_PARAM_DOUBLE(alpha)\n Z_PARAM_OBJECT(a) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetA)\n Z_PARAM_LONG(ldA)\n Z_PARAM_OBJECT(b) // Interop\\Polite\\Math\\Matrix\\LinearBuffer\n Z_PARAM_LONG(offsetB)\n Z_PARAM_LONG(ldB)\n ZEND_PARSE_PARAMETERS_END();\n\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_M, m)) {\n return;\n }\n if(php_rindow_openblas_assert_shape_parameter(\n PHP_RINDOW_OPENBLAS_ASSERT_N, n)) {\n return;\n }\n // Check Buffer A\n bufferA = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(a);\n if(php_rindow_openblas_assert_buffer_type(bufferA,\"a\")) {\n return;\n }\n {\n zend_long sizeA;\n if(side==CblasLeft) {\n sizeA = m;\n } else if(side==CblasRight) {\n sizeA = n;\n } else {\n zend_throw_exception(spl_ce_RuntimeException, \"unknown transpose mode for bufferA.\", 0);\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_A, bufferA,sizeA,sizeA,offsetA,ldA)) {\n return;\n }\n }\n bufferB = Z_INTEROP_POLITE_MATH_MATRIX_LINEAR_BUFFER_OBJ_P(b);\n if(php_rindow_openblas_assert_buffer_type(bufferB,\"b\")) {\n return;\n }\n if(php_rindow_openblas_assert_matrix_buffer_spec(\n PHP_RINDOW_OPENBLAS_ASSERT_B, bufferB,m,n,offsetB,ldB)) {\n return;\n }\n\n // Check Buffer A and B\n if(bufferA->dtype!=bufferB->dtype) {\n zend_throw_exception(spl_ce_InvalidArgumentException, \"Unmatch data type for A and B\", 0);\n return;\n }\n\n switch (bufferA->dtype) {\n case php_interop_polite_math_matrix_dtype_float32:\n cblas_strsm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_SIDE)side,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (OPENBLAS_CONST enum CBLAS_DIAG)diag,\n (blasint)m,(blasint)n,\n (float)alpha,\n &(((float *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((float *)bufferB->data)[offsetB]), (blasint)ldB);\n break;\n case php_interop_polite_math_matrix_dtype_float64:\n cblas_dtrsm(\n (OPENBLAS_CONST enum CBLAS_ORDER)order,\n (OPENBLAS_CONST enum CBLAS_SIDE)side,\n (OPENBLAS_CONST enum CBLAS_UPLO)uplo,\n (OPENBLAS_CONST enum CBLAS_TRANSPOSE)trans,\n (OPENBLAS_CONST enum CBLAS_DIAG)diag,\n (blasint)m,(blasint)n,\n (double)alpha,\n &(((double *)bufferA->data)[offsetA]), (blasint)ldA,\n &(((double *)bufferB->data)[offsetB]), (blasint)ldB);\n break;\n default:\n zend_throw_exception(spl_ce_RuntimeException, \"Unsupported data type.\", 0);\n return;\n }\n}\n/* }}} */\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_scal, 0, 0, 5)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_axpy, 0, 0, 8)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\n ZEND_ARG_OBJ_INFO(0, y, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetY)\n ZEND_ARG_INFO(0, incY)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_dot, 0, 0, 7)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\n ZEND_ARG_OBJ_INFO(0, y, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetY)\n ZEND_ARG_INFO(0, incY)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_asum, 0, 0, 4)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_iamax, 0, 0, 4)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\nZEND_END_ARG_INFO()\n\n#ifdef OPENBLAS_HAVE_IAMIN\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_iamin, 0, 0, 4)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\nZEND_END_ARG_INFO()\n#endif\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_copy, 0, 0, 7)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\n ZEND_ARG_OBJ_INFO(0, y, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetY)\n ZEND_ARG_INFO(0, incY)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_nrm2, 0, 0, 4)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_rotg, 0, 0, 8)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_OBJ_INFO(0, b, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetB)\n ZEND_ARG_OBJ_INFO(0, c, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetC)\n ZEND_ARG_OBJ_INFO(0, s, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetS)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_rot, 0, 0, 11)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\n ZEND_ARG_OBJ_INFO(0, y, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetY)\n ZEND_ARG_INFO(0, incY)\n ZEND_ARG_OBJ_INFO(0, c, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetC)\n ZEND_ARG_OBJ_INFO(0, s, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetS)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_swap, 0, 0, 7)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\n ZEND_ARG_OBJ_INFO(0, y, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetY)\n ZEND_ARG_INFO(0, incY)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_gemv, 0, 0, 15)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, trans)\n ZEND_ARG_INFO(0, m)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetX)\n ZEND_ARG_INFO(0, incX)\n ZEND_ARG_INFO(0, beta)\n ZEND_ARG_OBJ_INFO(0, x, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetY)\n ZEND_ARG_INFO(0, incY)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_gemm, 0, 0, 17)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, transA)\n ZEND_ARG_INFO(0, transB)\n ZEND_ARG_INFO(0, m)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, k)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_OBJ_INFO(0, b, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetB)\n ZEND_ARG_INFO(0, ldB)\n ZEND_ARG_INFO(0, beta)\n ZEND_ARG_OBJ_INFO(0, c, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetC)\n ZEND_ARG_INFO(0, ldC)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_symm, 0, 0, 16)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, side)\n ZEND_ARG_INFO(0, uplo)\n ZEND_ARG_INFO(0, m)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_OBJ_INFO(0, b, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetB)\n ZEND_ARG_INFO(0, ldB)\n ZEND_ARG_INFO(0, beta)\n ZEND_ARG_OBJ_INFO(0, c, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetC)\n ZEND_ARG_INFO(0, ldC)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_syrk, 0, 0, 13)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, uplo)\n ZEND_ARG_INFO(0, trans)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, k)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_INFO(0, beta)\n ZEND_ARG_OBJ_INFO(0, c, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetC)\n ZEND_ARG_INFO(0, ldC)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_syr2k, 0, 0, 16)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, uplo)\n ZEND_ARG_INFO(0, trans)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, k)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_OBJ_INFO(0, b, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetB)\n ZEND_ARG_INFO(0, ldB)\n ZEND_ARG_INFO(0, beta)\n ZEND_ARG_OBJ_INFO(0, c, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetC)\n ZEND_ARG_INFO(0, ldC)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_trmm, 0, 0, 14)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, side)\n ZEND_ARG_INFO(0, uplo)\n ZEND_ARG_INFO(0, trans)\n ZEND_ARG_INFO(0, diag)\n ZEND_ARG_INFO(0, m)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_OBJ_INFO(0, b, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetB)\n ZEND_ARG_INFO(0, ldB)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_trsm, 0, 0, 14)\n ZEND_ARG_INFO(0, order)\n ZEND_ARG_INFO(0, side)\n ZEND_ARG_INFO(0, uplo)\n ZEND_ARG_INFO(0, trans)\n ZEND_ARG_INFO(0, diag)\n ZEND_ARG_INFO(0, m)\n ZEND_ARG_INFO(0, n)\n ZEND_ARG_INFO(0, alpha)\n ZEND_ARG_OBJ_INFO(0, a, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetA)\n ZEND_ARG_INFO(0, ldA)\n ZEND_ARG_OBJ_INFO(0, b, Interop\\\\Polite\\\\Math\\\\Matrix\\\\LinearBuffer, 0)\n ZEND_ARG_INFO(0, offsetB)\n ZEND_ARG_INFO(0, ldB)\nZEND_END_ARG_INFO()\n\nZEND_BEGIN_ARG_INFO_EX(ai_Blas_void, 0, 0, 0)\nZEND_END_ARG_INFO()\n\n/* {{{ Rindow\\OpenBLAS\\Blas function entries */\nstatic zend_function_entry php_rindow_openblas_blas_me[] = {\n /* clang-format off */\n PHP_ME(Blas, getNumThreads, ai_Blas_void, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, getNumProcs, ai_Blas_void, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, getConfig, ai_Blas_void, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, getCorename, ai_Blas_void, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, scal, ai_Blas_scal, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, axpy, ai_Blas_axpy, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, dot, ai_Blas_dot, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, asum, ai_Blas_asum, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, iamax, ai_Blas_iamax, ZEND_ACC_PUBLIC)\n#ifdef OPENBLAS_HAVE_IAMIN\n PHP_ME(Blas, iamin, ai_Blas_iamin, ZEND_ACC_PUBLIC)\n#endif\n PHP_ME(Blas, copy, ai_Blas_copy, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, nrm2, ai_Blas_nrm2, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, rotg, ai_Blas_rotg, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, rot, ai_Blas_rot, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, swap, ai_Blas_swap, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, gemv, ai_Blas_gemv, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, gemm, ai_Blas_gemm, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, symm, ai_Blas_symm, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, syrk, ai_Blas_syrk, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, syr2k, ai_Blas_syr2k, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, trmm, ai_Blas_trmm, ZEND_ACC_PUBLIC)\n PHP_ME(Blas, trsm, ai_Blas_trsm, ZEND_ACC_PUBLIC)\n PHP_FE_END\n /* clang-format on */\n};\n/* }}} */\n\n/* Class Rindow\\OpenBLAS\\Blas {{{ */\nstatic zend_class_entry* rindow_openblas_blas_ce;\n\nvoid php_rindow_openblas_blas_init_ce(INIT_FUNC_ARGS)\n{\n zend_class_entry ce;\n\n INIT_NS_CLASS_ENTRY(ce, \"Rindow\\\\OpenBLAS\", \"Blas\", php_rindow_openblas_blas_me);\n rindow_openblas_blas_ce = zend_register_internal_class(&ce);\n rindow_openblas_blas_ce->create_object = php_rindow_openblas_blas_create_object;\n\n memcpy(&rindow_openblas_blas_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));\n rindow_openblas_blas_object_handlers.offset = 0;\n rindow_openblas_blas_object_handlers.free_obj = php_rindow_openblas_blas_free_object;\n rindow_openblas_blas_object_handlers.clone_obj = NULL;\n\n //zend_class_implements(rindow_openblas_blas_ce, 2, spl_ce_ArrayAccess, spl_ce_Countable);\n}\n/* }}} */\n", "meta": {"hexsha": "b29deacae898fcd57f2996bc02863d2c5d0fbed6", "size": 69177, "ext": "c", "lang": "C", "max_stars_repo_path": "src/Rindow/OpenBLAS/Blas.c", "max_stars_repo_name": "yuichiis/rindow-openblas", "max_stars_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T05:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T05:59:12.000Z", "max_issues_repo_path": "src/Rindow/OpenBLAS/Blas.c", "max_issues_repo_name": "yuichiis/rindow-openblas", "max_issues_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Rindow/OpenBLAS/Blas.c", "max_forks_repo_name": "yuichiis/rindow-openblas", "max_forks_repo_head_hexsha": "c835d5dba089e2e244803de540e57638baeaf8ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-11T19:59:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-11T19:59:53.000Z", "avg_line_length": 32.8164136622, "max_line_length": 113, "alphanum_fraction": 0.6425979733, "num_tokens": 19051, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.25985576301744695}} {"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 equation.c\n * \\brief Source file with the equation 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 \"config.h\"\n#include \"utils.h\"\n#include \"equation.h\"\n\n#define DEBUG_EQUATION 0 ///< macro to debug the equation functions.\n\nlong double r0[3]; ///< position vector.\nlong double r1[3]; ///< velocity vector.\nlong double r2[3]; ///< acceleration vector.\nlong double ro0[3]; ///< backup of the position vector.\nlong double ro1[3]; ///< backup of the velocity vector.\nlong double ro2[3]; ///< backup of the acceleration vector.\nvoid (*equation_acceleration) (Equation * eq, long double *r0,\n long double *r1, long double *r2, long double t);\n///< pointer to the function to calculate the acceleration.\nvoid (*equation_solution) (Equation * eq, long double *r0, long double *r1,\n long double t);\n///< pointer to the function to calculate the analytical solution.\nlong double (*equation_step_size) (Equation * eq);\n///< pointer to the function to calculate the time step size.\nint (*equation_land) (Equation * eq, long double, long double *t,\n long double *dt);\n///< pointer to the function to finalize the trajectory.\nlong double kt;\n///< stability time step size coefficient.\nlong double dt;\n///< time step size.\nunsigned long int nevaluations;\n///< number of evaluations of the acceleration function.\n\n/**\n * Function to calculate the acceleration on non-resitance model.\n *\n * This function calculates the acceleration vector on a non-resistance\n * model. The movement equation is:\n * \\f{equation}\\ddot{\\vec{r}}=\\vec{g}\\f}\n * with \\f$\\vec{g}=(0,\\;0,\\;-g)\\f$ the gravity field vector.\n */\nstatic void\nequation_acceleration_0 (Equation * eq __attribute__ ((unused)),\n ///< Equation struct.\n long double *r0 __attribute__ ((unused)),\n ///< position vector.\n long double *r1 __attribute__ ((unused)),\n ///< velocity vector.\n long double *r2, ///< acceleration vector.\n long double t __attribute__ ((unused)))\n ///< actual time.\n{\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_0: start\\n\");\n#endif\n r2[0] = r2[1] = 0.L;\n r2[2] = -G;\n ++nevaluations;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_0: ax=%Lg ay=%Lg az=%Lg\\n\",\n r2[0], r2[1], r2[2]);\n fprintf (stderr, \"equation_acceleration_0: end\\n\");\n#endif\n}\n\n/**\n * Function to solve the non-resistance model.\n *\n * This function solves the movement on a resistance model characterized by the\n * movement equation:\n * \\f{equation}{\\ddot{\\vec{r}}=\\vec{g},\\f}\n * with \\f$\\vec{g}=(0,\\;0,\\;-g)\\f$ the gravity field vector.\n * The analytical solution is:\n * \\f{equation}\\dot{\\vec{r}}=\\dot{\\vec{r}}_0+\\vec{g}\\,t,\\f}\n * \\f{equation}\\vec{r}=\\vec{r}_0+\\dot{\\vec{r}}_0\\,t+\\frac12\\,\\vec{g}\\,t^2.\\f}\n */\nstatic void\nequation_solution_0 (Equation * eq, ///< Equation struct.\n long double *r0, ///< position vector.\n long double *r1, ///< velocity vector.\n long double t) ///< time.\n{\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_0: start\\n\");\n#endif\n r1[0] = eq->v[0];\n r1[1] = eq->v[1];\n r1[2] = eq->v[2] - eq->g * t;\n r0[0] = eq->r[0] + eq->v[0] * t;\n r0[1] = eq->r[1] + eq->v[1] * t;\n r0[2] = eq->r[2] + t * (eq->v[2] - t * 0.5L * G);\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_0: vx=%Lg vy=%Lg vz=%Lg\\n\",\n r1[0], r1[1], r1[2]);\n fprintf (stderr, \"equation_solution_0: x=%Lg y=%Lg z=%Lg\\n\",\n r0[0], r0[1], r0[2]);\n fprintf (stderr, \"equation_solution_0: end\\n\");\n#endif\n}\n\n/**\n * Function to calculate the acceleration on the 1st resistance model.\n *\n * This function calculates the acceleration vector on a resistance model\n * model characterized by the movement equation:\n * \\f[\\ddot{\\vec{r}}=\\vec{g}-\\lambda\\,\\left(\\dot{\\vec{r}}-\\vec{w}\\right)\\f]\n * with \\f$\\vec{g}=(0,\\;0,\\;-g)\\f$ the gravity field vector,\n * \\f$\\vec{w}=\\left(w_x,\\;w_y\\;0\\right)\\f$ the wind velocity vector and\n * \\f$\\lambda\\f$ a resistance coefficient.\n */\nstatic void\nequation_acceleration_1 (Equation * eq, ///< Equation struct.\n long double *r0 __attribute__ ((unused)),\n ///< position vector.\n long double *r1, ///< velocity vector.\n long double *r2, ///< acceleration vector.\n long double t __attribute__ ((unused)))\n ///< actual time.\n{\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_1: start\\n\");\n#endif\n r2[0] = -eq->lambda * (r1[0] - eq->w[0]);\n r2[1] = -eq->lambda * (r1[1] - eq->w[1]);\n r2[2] = -eq->g - eq->lambda * r1[2];\n ++nevaluations;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_1: ax=%Lg ay=%Lg az=%Lg\\n\",\n r2[0], r2[1], r2[2]);\n fprintf (stderr, \"equation_acceleration_1: end\\n\");\n#endif\n}\n\n/**\n * Function to solve the 1st resistance model.\n *\n * This function solves the movement on a resistance model characterized by the\n * movement equation:\n * \\f{equation}\n * \\ddot{\\vec{r}}=\\vec{g}-\\lambda\\,\\left(\\dot{\\vec{r}}-\\vec{w}\\right),\n * \\f}\n * with \\f$\\vec{g}=(0,\\;0,\\;-g)\\f$ the gravity field vector,\n * \\f$\\vec{w}=(w_x,\\;w_y,\\;0)\\f$ the wind velocity vector and\n * \\f$\\lambda\\f$ a resistance coefficient.\n * The analytical solution is:\n * \\f{equation}\n * \\dot{\\vec{r}}=\\dot{\\vec{r}}_0\\,\\exp\\left(-\\lambda\\,t\\right)\n * +\\left(\\vec{w}+\\frac{\\vec{g}}{\\lambda}\\right)\n * \\,\\left[1-\\exp\\left(-\\lambda\\,t\\right)\\right],\n * \\f}\n * \\f{equation}\n * \\vec{r}=\\vec{r}_0+\\left(\\vec{w}+\\frac{\\vec{g}}{\\lambda}\\right)\\,t\n * +\\frac{\\dot{\\vec{r}}_0-\\vec{w}-\\vec{g}/\\lambda}{\\lambda}\n * \\,\\left[1-\\exp\\left(-\\lambda\\,t\\right)\\right].\n * \\f}\n */\nstatic void\nequation_solution_1 (Equation * eq, ///< Equation struct.\n long double *r0, ///< position vector.\n long double *r1, ///< velocity vector.\n long double t) ///< time.\n{\n long double v[2];\n long double li, gl, elt, k;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_1: start\\n\");\n#endif\n v[0] = eq->v[0] - eq->w[0];\n v[1] = eq->v[1] - eq->w[1];\n elt = expl (-eq->lambda * t);\n r1[0] = eq->w[0] + v[0] * elt;\n r1[1] = eq->w[1] + v[1] * elt;\n li = 1.L / eq->lambda;\n gl = eq->g * li;\n r1[2] = (eq->v[2] + gl) * elt - gl;\n k = li * (1.L - elt);\n r0[0] = eq->r[0] + eq->w[0] * t + v[0] * k;\n r0[1] = eq->r[1] + eq->w[1] * t + v[1] * k;\n r0[2] = eq->r[2] - gl * t + (eq->v[2] + gl) * k;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_1: vx=%Lg vy=%Lg vz=%Lg\\n\",\n r1[0], r1[1], r1[2]);\n fprintf (stderr, \"equation_solution_1: x=%Lg y=%Lg z=%Lg\\n\",\n r0[0], r0[1], r0[2]);\n fprintf (stderr, \"equation_solution_1: end\\n\");\n#endif\n}\n\n/**\n * Function to calculate the acceleration on 2nd resistance model.\n *\n * This function calculates the acceleration vector on a resistance model\n * model characterized by the movement equations:\n * \\f[\\left.\\begin{array}{r}\n * \\ddot{x}=-\\lambda\\,\\left|\\dot{x}-w_x\\right|\\,\\left(\\dot{x}-w_x\\right),\\\\\n * \\ddot{y}=-\\lambda\\,\\left|\\dot{y}-w_y\\right|\\,\\left(\\dot{y}-w_y\\right),\\\\\n * \\ddot{z}=-g-\\lambda\\,\\left|\\dot{z}\\right|\\,\\dot{z},\n * \\end{array}\\right\\}\\f]\n * with g the gravitational constant, \\f$w_x\\f$ and \\f$w_y\\f$ the wind velocity\n * vector components and \\f$\\lambda\\f$ a resistance coefficient.\n */\nstatic void\nequation_acceleration_2 (Equation * eq, ///< Equation struct.\n long double *r0 __attribute__ ((unused)),\n ///< position vector.\n long double *r1, ///< velocity vector.\n long double *r2, ///< acceleration vector.\n long double t __attribute__ ((unused)))\n ///< actual time.\n{\n long double v[2];\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_2: start\\n\");\n#endif\n v[0] = r1[0] - eq->w[0];\n v[1] = r1[1] - eq->w[1];\n r2[0] = -eq->lambda * fabsl (v[0]) * v[0];\n r2[1] = -eq->lambda * fabsl (v[1]) * v[1];\n r2[2] = -eq->g - eq->lambda * fabsl (r1[2]) * r1[2];\n ++nevaluations;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_2: ax=%Lg ay=%Lg az=%Lg\\n\",\n r2[0], r2[1], r2[2]);\n fprintf (stderr, \"equation_acceleration_2: end\\n\");\n#endif\n}\n\n/**\n * Function to solve the 2nd resistance mode.\n *\n * This function solves the movement on a resistance model characterized by the\n * movement equations:\n * \\f{equation}\\left.\\begin{array}{r}\n * \\ddot{x}=-\\lambda\\,\\left|\\dot{x}-w_x\\right|\\,\\left(\\dot{x}-w_x\\right)\\\\\n * \\ddot{y}=-\\lambda\\,\\left|\\dot{y}-w_y\\right|\\,\\left(\\dot{y}-w_y\\right)\\\\\n * \\ddot{z}=-g-\\lambda\\,\\left|\\dot{z}\\right|\\,\\dot{z}\n * \\end{array}\\right\\}\\f}\n * with g the gravitational constant, \\f$w_x\\f$ and \\f$w_y\\f$ the wind velocity\n * vector components and \\f$\\lambda\\f$ a resistance coefficient.\n * The analytical solution is:\n * \\f{equation}\n * \\dot{x}=w_x+\\frac{\\dot{x}_0-w_x}{1+\\lambda\\,\\left|\\dot{x}_0-w_x\\right|\\,t},\n * \\f}\n * \\f{equation}\n * \\dot{y}=w_y+\\frac{\\dot{y}_0-w_y}{1+\\lambda\\,\\left|\\dot{y}_0-w_y\\right|\\,t},\n * \\f}\n * \\f{equation}\n * \\dot{z}=\\left\\{\\begin{array}{cl}\n * \\dot{z}_0\\leq 0\\Rightarrow & \\sqrt{\\frac{g}{\\lambda}}\\,\n * \\frac{\\dot{z}_0\\,\\cosh\\left(\\sqrt{g\\,\\lambda}\\,t\\right)\n * -\\sqrt{g/\\lambda}\\,\\sinh\\left(\\sqrt{g\\,\\lambda}\\,t\\right)}\n * {\\sqrt{g/\\lambda}\\,\\cosh\\left(\\sqrt{g\\,\\lambda}\\,t\\right)\n * -\\dot{z}_0\\,\\sinh\\left(\\sqrt{g\\,\\lambda}\\,t\\right)},\\\\\n * \\dot{z}_0>0,\\;\n * t\\leq\\frac{\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)}\n * {\\sqrt{g\\,\\lambda}}\\Rightarrow & \n * \\sqrt{\\frac{g}{\\lambda}}\n * \\,\\tan\\left[\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\frac{\\lambda}{g}}\\right)\n * -\\sqrt{g\\,\\lambda}\\,t\\right],\\\\\n * \\dot{z}_0>0,\\;\n * t>\\frac{\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)}\n * {\\sqrt{g\\,\\lambda}}\\Rightarrow & \n * -\\sqrt{\\frac{g}{\\lambda}}\\,\\tanh\\left[\\sqrt{g\\,\\lambda}\\,t\n * -\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\frac{\\lambda}{g}}\\right)\\right],\n * \\end{array}\\right.\n * \\f}\n * \\f{equation}\n * x=x_0+w_x\\,t+\\frac{\\dot{x}_0-w_x}{\\lambda\\,\\left|\\dot{x}_0-w_x\\right|}\n * \\,\\ln\\left(1+\\lambda\\,\\left|\\dot{x}_0-w_x\\right|\\,t\\right),\n * \\f}\n * \\f{equation}\n * y=y_0+w_y\\,t+\\frac{\\dot{y}_0-w_y}{\\lambda\\,\\left|\\dot{y}_0-w_y\\right|}\n * \\,\\ln\\left(1+\\lambda\\,\\left|\\dot{y}_0-w_y\\right|\\,t\\right),\n * \\f}\n * \\f{equation}\n * z=\\left\\{\\begin{array}{cl}\n * \\dot{z}_0\\leq 0\\Rightarrow & z_0\n * -\\frac{\\ln\\left[\\cosh\\left(\\sqrt{g\\,\\lambda}\\,t\\right)\n * -\\dot{z}_0\\,\\sqrt{\\lambda/g}\\,\n * \\sinh\\left(\\sqrt{g\\,\\lambda}\\,t\\right)\\right]}{\\lambda},\\\\\n * \\dot{z}_0>0,\\;\n * t\\leq\\frac{\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)}\n * {\\sqrt{g\\,\\lambda}}\\Rightarrow & \n * z_0+\\frac{1}{\\lambda}\\,\\ln\\left\\{\\frac{\\cos\\left[\n * \\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)-\\sqrt{g\\,\\lambda}\\,t\\right]}\n * {\\cos\\left[\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)\\right]}\\right\\},\\\\\n * \\dot{z}_0>0,\\;\n * t>\\frac{\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)}\n * {\\sqrt{g\\,\\lambda}}\\Rightarrow & \n * z_0-\\frac{\\ln\\left\\{\n * \\cos\\left[\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)\\right]\n * \\,\\cosh\\left[\\sqrt{g\\,\\lambda}\\,t\n * -\\arctan\\left(\\dot{z}_0\\,\\sqrt{\\lambda/g}\\right)\\right]\\right\\}}{\\lambda}\n * \\end{array}\\right.\n * \\f}\n */\nstatic void\nequation_solution_2 (Equation * eq, ///< Equation struct.\n long double *r0, ///< position vector.\n long double *r1, ///< velocity vector.\n long double t) ///< actual time.\n{\n long double v[2], k[2];\n long double tc, g_l, gl, glt, lt, li, alpha;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_2: start\\n\");\n#endif\n v[0] = eq->v[0] - eq->w[0];\n v[1] = eq->v[1] - eq->w[1];\n lt = eq->lambda * t;\n k[0] = 1.L + lt * fabsl (v[0]);\n k[1] = 1.L + lt * fabsl (v[1]);\n r1[0] = eq->w[0] + v[0] / k[0];\n r1[1] = eq->w[1] + v[1] / k[1];\n li = 1.L / eq->lambda;\n k[0] = li * logl (k[0]);\n k[1] = li * logl (k[1]);\n r0[0] = eq->r[0] + eq->w[0] * t;\n r0[1] = eq->r[1] + eq->w[1] * t;\n if (v[0] >= 0.L)\n r0[0] += k[0];\n else\n r0[0] -= k[0];\n if (v[1] >= 0.L)\n r0[1] += k[1];\n else\n r0[1] -= k[1];\n gl = sqrtl (eq->g * eq->lambda);\n glt = gl * t;\n g_l = sqrtl (eq->g / eq->lambda);\n r0[2] = eq->r[2];\n if (eq->v[2] <= 0.L)\n {\n k[0] = coshl (glt);\n k[1] = sinhl (glt);\n r1[2] = g_l * (eq->v[2] * k[0] - g_l * k[1])\n / (g_l * k[0] - eq->v[2] * k[1]);\n r0[2] -= li * logl (k[0] - eq->v[2] * k[1] / g_l);\n }\n else\n {\n alpha = atanl (eq->v[2] / g_l);\n tc = alpha / gl;\n if (t <= tc)\n {\n r1[2] = g_l * tanl (alpha - glt);\n r0[2] += li * logl (cosl (alpha - glt) / cosl (alpha));\n }\n else\n {\n t -= tc;\n glt = gl * t;\n r1[2] = -g_l * tanhl (glt);\n r0[2] -= li * logl (cosl (alpha) * coshl (glt));\n }\n }\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_2: vx=%Lg vy=%Lg vz=%Lg\\n\",\n r1[0], r1[1], r1[2]);\n fprintf (stderr, \"equation_solution_2: x=%Lg y=%Lg z=%Lg\\n\",\n r0[0], r0[1], r0[2]);\n fprintf (stderr, \"equation_solution_2: end\\n\");\n#endif\n}\n\n/**\n * Function to calculate the acceleration on a forced model.\n *\n * This function calculates the acceleration vector on a forced model. The\n * movement equation is:\n * \\f{equation}\n * \\ddot{\\vec{r}}=\\vec{g}+\\vec{w}\\,\\exp\\left(-\\lambda\\,t\\right)\n * \\f}\n * with \\f$\\vec{g}=(0,\\;0,\\;-g)\\f$ the gravity field vector, \\f$\\lambda\\f$ the\n * force decay factor and \\f$\\vec{w}=\\left(w_x,\\;w_y\\;0\\right)\\f$ the force\n * vector.\n */\nstatic void\nequation_acceleration_3 (Equation * eq, ///< Equation struct.\n long double *r0 __attribute__ ((unused)),\n ///< position vector.\n long double *r1 __attribute__ ((unused)),\n ///< velocity vector.\n long double *r2, ///< acceleration vector.\n long double t) ///< actual time.\n{\n long double elt;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_3: start\\n\");\n#endif\n elt = expl (-eq->lambda * t);\n r2[0] = eq->w[0] * elt;\n r2[1] = eq->w[1] * elt;\n r2[2] = -G;\n ++nevaluations;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_acceleration_3: ax=%Lg ay=%Lg az=%Lg\\n\",\n r2[0], r2[1], r2[2]);\n fprintf (stderr, \"equation_acceleration_3: end\\n\");\n#endif\n}\n\n/**\n * Function to solve the forced model.\n *\n * This function solves the movement on a forced model characterized by the\n * movement equation:\n * \\f{equation}\n * \\ddot{\\vec{r}}=\\vec{g}+\\vec{w}\\,\\exp\\left(-\\lambda\\,t\\right)\n * \\f}\n * with \\f$\\vec{g}=(0,\\;0,\\;-g)\\f$ the gravity field vector, \\f$\\lambda\\f$ the\n * force decay factor and \\f$\\vec{w}=\\left(w_x,\\;w_y\\;0\\right)\\f$ the force\n * vector.\n * The analytical solution is:\n * \\f{equation}\n * \\dot{\\vec{r}}=\\dot{\\vec{r}}_0+\\vec{g}\\,t\n * +\\frac{\\vec{w}}{\\lambda}\\left[1-\\exp\\left(-\\lambda\\,t\\right)\\right],\\f}\n * \\f{equation}\\vec{r}=\\vec{r}_0\n * +\\left(\\dot{\\vec{r}}_0+\\frac{\\vec{w}}{\\lambda}\\right)\\,t\n * +\\frac12\\,\\vec{g}\\,t^2\n * +\\frac{\\vec{w}}{\\lambda^2}\\,\\left[1-\\exp\\left(-\\lambda\\,t\\right)\\right].\n * \\f}\n */\nstatic void\nequation_solution_3 (Equation * eq, ///< Equation struct.\n long double *r0, ///< position vector.\n long double *r1, ///< velocity vector.\n long double t) ///< time.\n{\n long double li, k;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_3: start\\n\");\n#endif\n li = 1.L / eq->lambda;\n k = li * (1.L - expl (-eq->lambda * t));\n r1[0] = eq->v[0] + eq->w[0] * k;\n r1[1] = eq->v[1] + eq->w[1] * k;\n r1[2] = eq->v[2] - eq->g * t;\n k *= li;\n r0[0] = eq->r[0] + (eq->v[0] + eq->w[0] * li) * t - eq->w[0] * k;\n r0[1] = eq->r[1] + (eq->v[1] + eq->w[1] * li) * t - eq->w[1] * k;\n r0[2] = eq->r[2] + t * (eq->v[2] - t * 0.5L * G);\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solution_3: vx=%Lg vy=%Lg vz=%Lg\\n\",\n r1[0], r1[1], r1[2]);\n fprintf (stderr, \"equation_solution_3: x=%Lg y=%Lg z=%Lg\\n\",\n r0[0], r0[1], r0[2]);\n fprintf (stderr, \"equation_solution_3: end\\n\");\n#endif\n}\n\n/**\n * Function to solve numerically the equation by the mean point method.\n *\n * \\return solution time.\n */\nlong double\nequation_solve (Equation * eq, ///< Equation struct.\n long double *r0, ///< position vector solution.\n long double *r1) ///< velocity vector solution.\n{\n long double r02[3], r12[3];\n long double t1, t2, t3;\n unsigned int i;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solve: start\\n\");\n#endif\n t1 = 0.L;\n t2 = 1.L;\n equation_solution (eq, r02, r12, t2);\n while (r02[2] > 0.L)\n {\n t2 *= 2.L;\n equation_solution (eq, r02, r12, t2);\n }\n for (i = 0; i < 64; ++i)\n {\n t3 = 0.5L * (t1 + t2);\n equation_solution (eq, r02, r12, t3);\n if (r02[2] > 0.L)\n t1 = t3;\n else\n t2 = t3;\n }\n memcpy (r0, r02, 3 * sizeof (long double));\n memcpy (r1, r12, 3 * sizeof (long double));\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_solve: vx=%Lg vy=%Lg vz=%Lg\\n\",\n r1[0], r1[1], r1[2]);\n fprintf (stderr, \"equation_solve: x=%Lg y=%Lg z=%Lg\\n\", r0[0], r0[1], r0[2]);\n fprintf (stderr, \"equation_solve: t=%Lg\\n\", t3);\n fprintf (stderr, \"equation_solve: end\\n\");\n#endif\n return t3;\n}\n\n/**\n * Function to set a constant time step size.\n *\n * \\return time step size.\n */\nstatic long double\nequation_step_size_0 (Equation * eq __attribute__ ((unused)))\n///< Equation struct.\n{\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_step_size_0: start\\n\");\n fprintf (stderr, \"equation_step_size_0: dt=%Lg\\n\", dt);\n fprintf (stderr, \"equation_step_size_0: end\\n\");\n#endif\n return dt;\n}\n\n/**\n * Function to set the time step size based on stability condition for the 1st\n * resistance model.\n *\n * \\return time step size.\n */\nstatic long double\nequation_step_size_1 (Equation * eq) ///< Equation struct.\n{\n long double dt;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_step_size_1: start\\n\");\n#endif\n dt = kt / fabsl (eq->lambda);\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_step_size_1: dt=%Lg\\n\", dt);\n fprintf (stderr, \"equation_step_size_1: end\\n\");\n#endif\n return dt;\n}\n\n/**\n * Function to set the time step size based on stability condition for the 2nd\n * resistance model.\n *\n * \\return time step size.\n */\nstatic long double\nequation_step_size_2 (Equation * eq) ///< Equation struct.\n{\n long double dt;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_step_size_2: start\\n\");\n#endif\n dt = kt / (fabsl (eq->lambda) *\n fmaxl (fabsl (r1[0] - eq->w[0]),\n fmaxl (fabsl (r1[1] - eq->w[1]), fabsl (r1[2]))));\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_step_size_2: dt=%Lg\\n\", dt);\n fprintf (stderr, \"equation_step_size_2: end\\n\");\n#endif\n return dt;\n}\n\n/**\n * Function to finish the trajectory based on final time.\n *\n * \\return 1 on finish, 0 on continuing.\n */\nstatic int\nequation_land_0 (Equation * eq, ///< Equation struct.\n long double to, ///< old time.\n long double *t, ///< next time.\n long double *dt) ///< time step size.\n{\n long double tf;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_0: start\\n\");\n fprintf (stderr, \"equation_land_0: to=%Lg\\n\", to);\n#endif\n tf = eq->tf;\n if (to >= tf)\n {\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_0: landing\\n\");\n fprintf (stderr, \"equation_land_0: end\\n\");\n#endif\n return 1;\n }\n *t = to + *dt;\n if (*t >= tf)\n {\n *dt = tf - to;\n *t = tf;\n }\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_0: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_0: no landing\\n\");\n fprintf (stderr, \"equation_land_0: end\\n\");\n#endif\n return 0;\n}\n\n/**\n * Function to finish the trajectory based on 1st order landing.\n *\n * \\return 1 on finish, 0 on continuing.\n */\nstatic int\nequation_land_1 (Equation * eq __attribute__ ((unused)),\n ///< Equation struct.\n long double to, ///< old time.\n long double *t, ///< next time.\n long double *dt) ///< time step size.\n{\n long double h;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_1: start\\n\");\n fprintf (stderr, \"equation_land_1: to=%Lg\\n\", to);\n#endif\n if (r0[2] > 0.)\n {\n *t = to + *dt;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_1: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_1: no landing\\n\");\n fprintf (stderr, \"equation_land_1: end\\n\");\n#endif\n return 0;\n }\n h = r0[2] / r1[2];\n r0[0] -= h * r1[0];\n r0[1] -= h * r1[1];\n r0[2] -= h * r1[2];\n r1[0] -= h * r2[0];\n r1[1] -= h * r2[1];\n r1[2] -= h * r2[2];\n *t = to - h;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_1: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_1: landing\\n\");\n fprintf (stderr, \"equation_land_1: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to finish the trajectory based on 2nd order landing.\n *\n * \\return 1 on finish, 0 on continuing.\n */\nstatic int\nequation_land_2 (Equation * eq __attribute__ ((unused)),\n ///< Equation struct.\n long double to, ///< old time.\n long double *t, ///< next time.\n long double *dt) ///< time step size.\n{\n long double h;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_2: start\\n\");\n fprintf (stderr, \"equation_land_2: to=%Lg\\n\", to);\n#endif\n if (r0[2] > 0.)\n {\n *t = to + *dt;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_2: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_2: no landing\\n\");\n fprintf (stderr, \"equation_land_2: end\\n\");\n#endif\n return 0;\n }\n h = solve_quadratic (0.5L * r2[2], -r1[2], r0[2], 0.L, *dt);\n r0[0] -= h * (r1[0] - h * 0.5L * r2[0]);\n r0[1] -= h * (r1[1] - h * 0.5L * r2[1]);\n r0[2] -= h * (r1[2] - h * 0.5L * r2[2]);\n r1[0] -= h * r2[0];\n r1[1] -= h * r2[1];\n r1[2] -= h * r2[2];\n *t = to - h;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_2: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_2: landing\\n\");\n fprintf (stderr, \"equation_land_2: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to finish the trajectory based on 3rd order landing.\n *\n * \\return 1 on finish, 0 on continuing.\n */\nstatic int\nequation_land_3 (Equation * eq __attribute__ ((unused)),\n ///< Equation struct.\n long double to, ///< old time.\n long double *t, ///< next time.\n long double *dt) ///< time step size.\n{\n long double h, r3[3];\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_3: start\\n\");\n fprintf (stderr, \"equation_land_3: to=%Lg\\n\", to);\n#endif\n if (r0[2] > 0.)\n {\n *t = to + *dt;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_3: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_3: no landing\\n\");\n fprintf (stderr, \"equation_land_3: end\\n\");\n#endif\n return 0;\n }\n r3[0] = (r2[0] - ro2[0]) / *dt;\n r3[1] = (r2[1] - ro2[1]) / *dt;\n r3[2] = (r2[2] - ro2[2]) / *dt;\n h = solve_cubic (-1.L / 6.L * r3[2], 0.5L * r2[2], -r1[2], r0[2], 0.L, *dt);\n r0[0] -= h * (r1[0] - h * (0.5L * r2[0] - h * 1.L / 6.L * r3[0]));\n r0[1] -= h * (r1[1] - h * (0.5L * r2[1] - h * 1.L / 6.L * r3[1]));\n r0[2] -= h * (r1[2] - h * (0.5L * r2[2] - h * 1.L / 6.L * r3[2]));\n r1[0] -= h * (r2[0] - h * 0.5L * r3[0]);\n r1[1] -= h * (r2[1] - h * 0.5L * r3[1]);\n r1[2] -= h * (r2[2] - h * 0.5L * r3[2]);\n *t = to - h;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_land_3: t=%Lg dt=%Lg\\n\", *t, *dt);\n fprintf (stderr, \"equation_land_3: landing\\n\");\n fprintf (stderr, \"equation_land_3: end\\n\");\n#endif\n return 1;\n}\n\n/**\n * Function to init the equation variables.\n */\nvoid\nequation_init (Equation * eq, ///< Equation struct.\n gsl_rng * rng) ///< gsl_rng struct.\n{\n long double v, ha, va;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_init: start\\n\");\n#endif\n switch (eq->type)\n {\n case 1:\n case 2:\n case 3:\n eq->lambda = eq->min_lambda\n + (eq->max_lambda - eq->min_lambda) * gsl_rng_uniform (rng);\n }\n v = eq->min_velocity\n + (eq->max_velocity - eq->min_velocity) * gsl_rng_uniform (rng);\n ha = 2.L * M_PIl * gsl_rng_uniform (rng);\n eq->r[0] = eq->r[1] = 0.L;\n va = eq->vertical_angle * M_PIl / 180.L;\n eq->v[2] = v * sinl (va);\n eq->v[1] = v * cosl (va);\n eq->v[0] = eq->v[1] * cosl (ha);\n eq->v[1] *= sinl (ha);\n v = eq->max_wind * gsl_rng_uniform (rng);\n ha = 2.L * M_PIl * gsl_rng_uniform (rng);\n eq->w[0] = v * cosl (ha);\n eq->w[1] = v * sinl (ha);\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_init: end\\n\");\n#endif\n}\n\n/**\n * Function to read the equation data on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nequation_read_xml (Equation * eq, ///< Equation struct.\n xmlNode * node, ///< XML node.,\n\t\t\t\t\t\t\t\t\t unsigned int initial) ///< type of initial conditions.\n{\n const char *message[] = {\n \"Bad XML node\",\n \"Bad type\",\n \"Unknown type\",\n \"Bad x\",\n \"Bad y\",\n \"Bad z\",\n \"Bad vx\",\n \"Bad vy\",\n \"Bad vz\",\n \"Bad wx\",\n \"Bad wy\",\n \"Bad lambda\",\n\t\t\"Bad minimum velocity\",\n\t\t\"Bad maximum velocity\",\n\t\t\"Bad vertical angle\",\n\t\t\"Bad maximum wind\",\n\t\t\"Bad minimum lambda\",\n\t\t\"Bad maximum lambda\",\n \"Bad g\",\n \"Bad time step type\",\n \"Bad dt\",\n \"Bad kt\",\n \"Unknown time step type\",\n \"Bad land type\",\n \"Bad t\",\n \"Unknown land type\"\n };\n int e, error_code;\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_read_xml: start\\n\");\n fprintf (stderr, \"equation_read_xml: name=%s\\n\", node->name);\n#endif\n if (xmlStrcmp (node->name, XML_EQUATION))\n {\n e = 0;\n goto exit_on_error;\n }\n eq->type = xml_node_get_uint (node, XML_TYPE, &error_code);\n if (error_code)\n {\n e = 1;\n goto exit_on_error;\n }\n switch (eq->type)\n {\n case 0:\n equation_acceleration = equation_acceleration_0;\n equation_solution = equation_solution_0;\n break;\n case 1:\n equation_acceleration = equation_acceleration_1;\n equation_solution = equation_solution_1;\n break;\n case 2:\n equation_acceleration = equation_acceleration_2;\n equation_solution = equation_solution_2;\n break;\n case 3:\n equation_acceleration = equation_acceleration_3;\n equation_solution = equation_solution_3;\n break;\n default:\n e = 2;\n goto exit_on_error;\n }\n eq->r[0] = xml_node_get_float_with_default (node, XML_X, 0.L, &error_code);\n if (error_code)\n {\n e = 3;\n goto exit_on_error;\n }\n eq->r[1] = xml_node_get_float_with_default (node, XML_Y, 0.L, &error_code);\n if (error_code)\n {\n e = 4;\n goto exit_on_error;\n }\n eq->r[2] = xml_node_get_float (node, XML_Z, &error_code);\n if (error_code || eq->r[2] < 0.L)\n {\n e = 5;\n goto exit_on_error;\n }\n\tif (initial)\n\t {\n eq->v[0] \n\t\t\t\t= xml_node_get_float_with_default (node, XML_VX, 0.L, &error_code);\n if (error_code)\n {\n e = 6;\n goto exit_on_error;\n }\n eq->v[1] \n\t\t\t\t= xml_node_get_float_with_default (node, XML_VY, 0.L, &error_code);\n if (error_code)\n {\n e = 7;\n goto exit_on_error;\n }\n eq->v[2] \n\t\t\t\t= xml_node_get_float_with_default (node, XML_VZ, 0.L, &error_code);\n if (error_code)\n {\n e = 8;\n goto exit_on_error;\n }\n eq->w[0] \n\t\t\t\t= xml_node_get_float_with_default (node, XML_WX, 0.L, &error_code);\n if (error_code)\n {\n e = 9;\n goto exit_on_error;\n }\n eq->w[1]\n\t\t\t \t= xml_node_get_float_with_default (node, XML_WY, 0.L, &error_code);\n if (error_code)\n {\n e = 10;\n goto exit_on_error;\n }\n switch (eq->type)\n {\n case 1:\n case 2:\n case 3:\n eq->lambda = xml_node_get_float_with_default (node, XML_LAMBDA, 0.L, \n\t\t\t\t\t\t\t &error_code);\n if (error_code)\n {\n e = 11;\n goto exit_on_error;\n }\n\t\t\t\t}\n\t\t}\n\telse\n\t {\n eq->min_velocity\n\t\t\t\t= xml_node_get_float_with_default (node, XML_VMIN, 0.L, &error_code);\n\t\t\tif (error_code || eq->min_velocity < 0.L)\n\t\t\t {\n\t\t\t\t\te = 12;\n\t\t\t\t\tgoto exit_on_error;\n\t\t\t\t}\n eq->max_velocity = xml_node_get_float (node, XML_VMAX, &error_code);\n\t\t\tif (error_code || eq->max_velocity <= 0.L)\n\t\t\t {\n\t\t\t\t\te = 13;\n\t\t\t\t\tgoto exit_on_error;\n\t\t\t\t}\n eq->vertical_angle\n\t\t\t\t= xml_node_get_float (node, XML_VERTICAL_ANGLE, &error_code);\n\t\t\tif (error_code)\n\t\t\t {\n\t\t\t\t\te = 14;\n\t\t\t\t\tgoto exit_on_error;\n\t\t\t\t}\n eq->max_wind \n\t\t\t\t= xml_node_get_float_with_default (node, XML_WMAX, 0.L, &error_code);\n\t\t\tif (error_code || eq->max_wind < 0.L)\n\t\t\t {\n\t\t\t\t\te = 15;\n\t\t\t\t\tgoto exit_on_error;\n\t\t\t\t}\n switch (eq->type)\n {\n case 1:\n case 2:\n case 3:\n eq->min_lambda\n\t\t\t\t\t\t= xml_node_get_float_with_default (node, XML_LAMBDA_MIN, 0.L, \n\t\t\t\t\t\t\t\t &error_code);\n\t\t\t\t if (error_code)\n\t\t\t\t\t {\n\t\t\t\t\t\t e = 16;\n\t\t\t\t\t\t goto exit_on_error;\n\t\t\t\t\t\t}\n eq->max_lambda\n\t\t\t\t\t\t= xml_node_get_float_with_default (node, XML_LAMBDA_MAX, 0.L, \n\t\t\t\t\t\t\t\t &error_code);\n\t\t\t\t if (error_code || eq->max_lambda < eq->min_lambda)\n\t\t\t\t\t {\n\t\t\t\t\t\t e = 17;\n\t\t\t\t\t\t goto exit_on_error;\n\t\t\t\t\t\t}\n\t\t\t }\t\n\t\t}\n eq->g = xml_node_get_float_with_default (node, XML_G, G, &error_code);\n if (error_code)\n {\n e = 18;\n goto exit_on_error;\n }\n eq->size_type = xml_node_get_uint (node, XML_TIME_STEP, &error_code);\n if (error_code)\n {\n e = 19;\n goto exit_on_error;\n }\n switch (eq->size_type)\n {\n case 0:\n equation_step_size = equation_step_size_0;\n dt = xml_node_get_float (node, XML_DT, &error_code);\n if (error_code)\n {\n e = 20;\n goto exit_on_error;\n }\n break;\n case 1:\n switch (eq->type)\n {\n case 1:\n equation_step_size = equation_step_size_1;\n break;\n case 2:\n equation_step_size = equation_step_size_2;\n }\n kt = xml_node_get_float (node, XML_KT, &error_code);\n if (error_code)\n {\n e = 21;\n goto exit_on_error;\n }\n break;\n default:\n e = 22;\n goto exit_on_error;\n }\n eq->land_type = xml_node_get_uint (node, XML_LAND, &error_code);\n if (error_code)\n {\n e = 23;\n goto exit_on_error;\n }\n switch (eq->land_type)\n {\n case 0:\n equation_land = equation_land_0;\n eq->tf = xml_node_get_float (node, XML_T, &error_code);\n if (error_code || eq->tf < 0.)\n {\n e = 24;\n goto exit_on_error;\n }\n break;\n case 1:\n equation_land = equation_land_1;\n break;\n case 2:\n equation_land = equation_land_2;\n break;\n case 3:\n equation_land = equation_land_3;\n break;\n default:\n e = 25;\n goto exit_on_error;\n }\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_read_xml: success\\n\");\n fprintf (stderr, \"equation_read_xml: end\\n\");\n#endif\n return 1;\nexit_on_error:\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_read_xml: error\\n\");\n#endif\n error_add (message[e]);\n#if DEBUG_EQUATION\n fprintf (stderr, \"equation_read_xml: end\\n\");\n#endif\n return 0;\n}\n", "meta": {"hexsha": "8297b7c1d6c20a265669031fc6586ca611a9f7f8", "size": 33361, "ext": "c", "lang": "C", "max_stars_repo_path": "1.1.0/equation.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/equation.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/equation.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": 30.6345270891, "max_line_length": 80, "alphanum_fraction": 0.5683582626, "num_tokens": 11218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.43014734858584286, "lm_q1q2_score": 0.25977967700380705}} {"text": "\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"limits.h\"\n#include \"stattest.h\"\n#include \"cat.h\"\n#include \"fisher.h\"\n#include \"min2.h\"\n#include \"bvr.h\"\n\ntypedef unsigned int count_t;\ntypedef const count_t COUNT_T;\ntypedef double prob_t;\n\n/**\n * This class is stateful in the interest of efficiency\n * because some methods share preliminary computations:\n * 1) statistics require expectation, and \n * 2) expectation requires marginals\n * (which may also be used incidentally for other purposes), so this \n * variable captures the progress towards complete calculations\n * to enable implicit just-in-time calculation.\n */\nenum State {\n\tNothing = 0,\n\tMarginals,\n\tExpectation\n};\n\n\nstruct CatCovars {\n\n\t/**\n\t * Buffers are sized to accomodate these dimensions at construction\n\t * and are not changeable thereafter.\n\t */\n\tunsigned int ROW_CAPACITY, COL_CAPACITY;\n\n\t/**\n\t * \"decl(ared)_\" because the bounds says nothing about the row/col \n\t * content--empty rows/columns may exist! I'm just driving this point\n\t * home in these members' names because it has already burned me once!\n\t */\n\tunsigned int decl_rows, decl_cols, decl_cells;\n\n\t/**\n\t * Count of samples pushed since last cat_clear.\n\t */\n\tcount_t sample_count;\n\n\t// Calculation state ///////////////////////////////////////////////////\n\n\tprob_t minimumExpected;\n\n\t/**\n\t * This is used strictly by badCellExists\n\t */\n\tcount_t REQUIRED_CELL_MINIMUM;\n\n\tenum State calculated;\n\n\t// Buffers /////////////////////////////////////////////////////////////\n\n\tsize_t SIZEOF_PROB_BUF;\n\n\tprob_t *expect;\n\n\tsize_t SIZEOF_COUNT_BUF;\n\n\t/**\n\t * The counts matrix is stored packed against the head of this\n\t * (heap-allocated) buffer. In other words, though this buffer\n\t * is -expected- to be larger than required (since the class \n\t * is designed to be iteratively re-used), only the first \n\t * (decl_rows*decl_cols) of the buffer are used for any given \n\t * matrix.\n\t */\n\tcount_t *counts;\n\n\t/**\n\t * Following are derivative data...computed from counts.\n\t */\n\tcount_t *rmarg;\n\tcount_t *cmarg;\n};\n\n\nstatic void _coordsOfOffset(\n\tstruct CatCovars *co, unsigned int off, unsigned int *r, unsigned int *c ) {\n\t*r = off / co->decl_cols;\n\t*c = off % co->decl_cols;\n}\n\n\nstatic count_t _count( struct CatCovars *co, coord_t r, coord_t c ) {\n\tconst int C = co->decl_cols;\n\tassert( r < co->decl_rows && c < C );\n\treturn co->counts[ r*C + c ];\n}\n\n\nstatic prob_t _expected( struct CatCovars *co, coord_t r, coord_t c ) {\n\tconst int C = co->decl_cols;\n\tassert( r < co->decl_rows && c < C );\n\treturn co->expect[ r*C + c ];\n}\n\n\nstatic void _recalcSampleCount( struct CatCovars *co ) {\n\tint n = co->decl_cells;\n\tco->sample_count = 0;\n\twhile( n-- > 0 ) co->sample_count += co->counts[n];\n}\n\n\n/**\n * This starts searching at the given coordinates and continues linearly\n * through the matrix until it finds a violating cell at which point it\n * turns the linear index into 2D coordinates.\n */\nstatic bool _badCellExists( struct CatCovars *co,\n\t\tunsigned int *offset ) {\n\n\tunsigned int i = *offset;\n\twhile( i < co->decl_cells ) {\n\t\tif( co->counts[i] < co->REQUIRED_CELL_MINIMUM ) {\n\t\t\t*offset = i;\n\t\t\treturn true;\n\t\t}\n\t\ti++;\n\t}\n\treturn false;\n}\n\n\n/**\n * If after accumulation there are fewer than 2 rows or fewer than 2\n * columns, the table is degenerate. Rows or columns with zero marginal\n * sum are OK! For a contingency table that's bad but not -degenerate-.\n */\nstatic bool _immediatelyDegenerate( struct CatCovars *co ) {\n\treturn ! ( co->decl_rows >= 2 && co->decl_cols >= 2 );\n}\n\n#if 0\nstatic bool _eventuallyDegenerate( struct CatCovars *co ) {\n\tunsigned nonemprows = 0;\n\tunsigned nonempcols = 0;\n\tunsigned i;\n\tfor(i = 0; i < co->decl_rows; i++ ) if( co->rmarg[i] > 0 ) nonemprows++;\n\tfor(i = 0; i < co->decl_cols; i++ ) if( co->cmarg[i] > 0 ) nonempcols++;\n\treturn ! ( nonemprows >= 2 && nonempcols >= 2 );\n}\n#endif\n\nstatic void _cullRow( struct CatCovars *co, unsigned int r ) {\n\n\t// An over-writing copy suffices since matrix is\n\t// stored row-major. mergeCols is more intricate.\n\t\n\tif( r+1 < co->decl_rows ) { // ...so 0 < rows-U-1\n\t\tmemmove( \n\t\t\tco->counts + (r )*co->decl_cols, \n\t\t\tco->counts + (r+1)*co->decl_cols, \n\t\t\t(co->decl_rows - r - 1)*co->decl_cols*sizeof(count_t) );\n\t} else {\n\t\t// ...it's the last row, and there's nothing to move.\n\t}\n\tco->decl_rows -= 1;\n\tco->decl_cells -= co->decl_cols;\n\n\tco->sample_count = 0;\n\tco->calculated = Nothing; // ...to trigger recomputation.\n}\n\n\nstatic void _cullCol( struct CatCovars *co, unsigned int c ) {\n\n\tconst unsigned int N = co->decl_cells;\n\t// Shrink. Because matrices are stored row-major and calculations\n\t// throughout this class assume the matrix is packed at the head of\n\t// the buffer, there is actually a fairly complex shifting of all \n\t// but the first c entries that has to occurr...\n\t// Basically, traverse the matrix linearly (storage order) shifting\n\t// \"left\" all entries that are NOT in the c'th column...\n\tfor(unsigned int src = 0, dst = 0 ; src < N; src++ ) {\n\t\tif( src % co->decl_cols != c ) {\n\t\t\tco->counts[dst++] = co->counts[src];\n\t\t}\n\t}\n\tco->decl_cols -= 1;\n\tco->decl_cells -= co->decl_rows;\n\n\tco->sample_count = 0;\n\tco->calculated = Nothing; // ...to trigger recomputation.\n}\n\n\n/**\n * Following two MUST be called in order before any of\n * the statistics are computed. In other words,\n * !!!! THESE ARE NOT CALLED IMPLICITLY! !!!!\n * (Statistical methods which -ought- to be const can't be unless\n * 'expect', '[rc]marg' and friends are made mutable->)\n */\nstatic void _calc_marginals( struct CatCovars *co ) {\n\n\tconst int R = co->decl_rows;\n\tconst int C = co->decl_cols;\n\tco->sample_count = 0;\n\n\tmemset( co->rmarg, 0, R*sizeof(count_t) );\n\tmemset( co->cmarg, 0, C*sizeof(count_t) );\n\n\t// Calculate the marginals...\n\n\tfor(unsigned int i = 0; i < R; i++ ) {\n\t\tfor(unsigned int j = 0; j < C; j++ ) {\n\t\t\tconst count_t C = _count( co, i,j);\n\t\t\tco->rmarg[i] += C;\n\t\t\tco->cmarg[j] += C;\n\t\t\tco->sample_count += C;\n\t\t}\n\t}\n\n\tco->calculated = Marginals;\n}\n\n\n/**\n * Calculates the expected probabilities of a contingency table assuming\n * independence of the two variables.\n * \"Since the Chi-square and G^2 statistics rest on the normal approximation\n * to the hypergeometric distribution, these approximations get strained\n * when there are zero frequency cells or when the expected counts are\n * 'very small'.\" ...from Yaramakala's Masters Thesis, p.43\n *\n * \"...for an independence test to be reliable, all cells have non-zero\n * expected values and at least 80% of the cells should have expected\n * values greater than 5.\" [Everitt 1977, Upton 1978]\n */\nstatic void _calc_expectation( struct CatCovars *co ) {\n\n\tconst int R = co->decl_rows;\n\tconst int C = co->decl_cols;\n\n\tif( co->calculated < Marginals ) \n\t\t_calc_marginals( co );\n\n\tif( co->sample_count > 0 ) {\t\n\t\tco->minimumExpected \n\t\t\t= (prob_t)(co->rmarg[0] * co->cmarg[0]) \n\t\t\t/ (prob_t)co->sample_count;\n\t\tfor(unsigned int i = 0; i < R; i++ ) {\n\t\t\tfor(unsigned int j = 0; j < C; j++ ) {\n\t\t\t\tconst prob_t E \n\t\t\t\t\t= (prob_t)(co->rmarg[i] * co->cmarg[j]) \n\t\t\t\t\t/ (prob_t)co->sample_count;\n\t\t\t\tco->expect[i*co->decl_cols + j] = E;\n\t\t\t\tif( co->minimumExpected > E ) \n\t\t\t\t\tco->minimumExpected = E;\n\t\t\t}\n\t\t}\n\t}\n\n\tco->calculated = Expectation;\n}\n\n\n/**\n * This function cannot fail. Valid results always exist.\n * Returns the indices of the minimal row and columns marginals.\n */\n#if 0\nstatic void _minimalMarginals( struct CatCovars *co, unsigned int *rm, unsigned int *cm ) {\n\n\tunsigned int MIN_DIM\n\t\t= co->decl_rows < co->decl_cols ? co->decl_rows : co->decl_cols;\n\tunsigned int i, ri = 0, ci = 0;\n\tcount_t mr, mc;\n\n\tif( co->calculated < Marginals )\n\t\t_calc_marginals( co );\n\n\tmr = co->rmarg[ri]; \n\tmc = co->cmarg[ci];\n\n\t// Iterate over marginals at indices [0,min(rows,cols) )\n\n\tfor(i = 0; i < MIN_DIM; i++ ) {\n\t\tif( mr > co->rmarg[i] ) {\n\t\t\tmr = co->rmarg[i];\n\t\t\tri = i;\n\t\t}\n\t\tif( mc > co->cmarg[i] ) {\n\t\t\tmc = co->cmarg[i];\n\t\t\tci = i;\n\t\t}\n\t}\n\n\t// ...continue iteration over [ min(rows,cols), max(rows,cols) ).\n\n\tif( co->decl_cols > co->decl_rows )\n\t\tfor(; i < co->decl_cols; i++ ) {\n\t\t\tif( mc > co->cmarg[i] ) {\n\t\t\t\tmc = co->cmarg[i];\n\t\t\t\tci = i;\n\t\t\t}\n\t\t}\n\telse\n\tif( co->decl_rows > co->decl_cols )\n\t\tfor(; i < co->decl_rows; i++ ) {\n\t\t\tif( mr > co->rmarg[i] ) {\n\t\t\t\tmr = co->rmarg[i];\n\t\t\t\tri = i;\n\t\t\t}\n\t\t}\n\n\t*rm = ri;\n\t*cm = ci;\n}\n#endif\n\n\n/**\n * A pretty printer...primarily for debugging.\n */\n#ifdef _DEBUG\nstatic void dbg_dump( struct CatCovars *co, FILE *fp, const char *prefix ) {\n\n\tif( prefix==NULL ) prefix=\"\";\n\n\tfprintf( fp, \"%s %d(r) x %d(c) (capacity = %dx%d)\\n\",\n\t\tprefix,\n\t\tco->decl_rows,\n\t\tco->decl_cols,\n\t\tco->ROW_CAPACITY,\n\t\tco->COL_CAPACITY );\n\n\tfprintf( fp, \"%s cell counts...\\n\", prefix );\n\tfor(unsigned int r = 0; r < co->decl_rows; r++ ) {\n\t\tfputs( prefix, fp );\n\t\tfor(unsigned int c = 0; c < co->decl_cols; c++ ) {\n\t\t\tfprintf( fp, \"\\t%d\", _count(co,r,c) );\n\t\t}\n\t\tfputc( '\\n', fp );\n\t}\n\n\tif( co->calculated >= Expectation ) {\n\t\tfprintf( fp, \"%s %d total samples, expectation...\\n\", prefix, co->sample_count );\n\t\tfor(unsigned int r = 0; r < co->decl_rows; r++ ) {\n\t\t\tfputs( prefix, fp );\n\t\t\tfor(unsigned int c = 0; c < co->decl_cols; c++ ) {\n\t\t\t\tfprintf( fp, \"\\t%.3e\", _expected( co, r, c) );\n\t\t\t}\n\t\t\tfputc( '\\n', fp );\n\t\t}\n\t}\n}\n#endif\n\n\n/***************************************************************************\n * Publics\n */\n\nvoid cat_destroy( void *pv ) {\n\n\tif( pv ) {\n\t\tstruct CatCovars *co = (struct CatCovars *)pv;\n\t\tif( co->expect )\n\t\t\tfree( co->expect );\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 *cat_create( unsigned int rcap, unsigned int ccap ) {\n\n\tstruct CatCovars *co\n\t\t= calloc( 1, sizeof(struct CatCovars) );\n\n\tif( co ) {\n\t\tco->ROW_CAPACITY = rcap;\n\t\tco->COL_CAPACITY = ccap;\n\t\tco->SIZEOF_COUNT_BUF\n\t\t\t= (rcap*ccap+rcap+ccap)*sizeof(count_t);\n\t\tco->SIZEOF_PROB_BUF\n\t\t\t= rcap*ccap*sizeof(prob_t);\n\n\t\t// Allocate one large buffer and partition it up.\n\t\tco->expect\n\t\t\t= calloc( co->SIZEOF_PROB_BUF + co->SIZEOF_COUNT_BUF, sizeof(char) );\n\t\tco->counts\n\t\t\t= (count_t*)( co->expect + rcap*ccap );\n\t\tco->rmarg\n\t\t\t= co->counts + rcap*ccap;\n\t\tco->cmarg\n\t\t\t= co->rmarg + rcap;\n\n\t\tco->REQUIRED_CELL_MINIMUM = 5;\n\n\t\t// If -anything- failed clean up any successes.\n\t\tif( (NULL == co->counts) || \n\t\t\t(NULL == co->expect) ) {\n\t\t\tcat_destroy( co );\n\t\t\treturn NULL;\n\t\t}\n\t\treturn co;\n\t}\n\treturn NULL;\n}\n\n\nvoid cat_clear( void *pv, coord_t nr, coord_t nc ) {\n\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\n\tassert( nr <= co->ROW_CAPACITY && nc <= co->COL_CAPACITY );\n\n\t// Set dimensions and cell count.\n\n\tco->decl_rows = nr;\n\tco->decl_cols = nc;\n\tco->decl_cells = nr*nc;\n\n\tco->sample_count = 0;\n\tco->minimumExpected = 0.0;\n\tco->calculated = Marginals;\n\n\t// OPTIMIZATION: Only clearing the part of capacity intended for use!\n\n\tmemset( co->counts, 0, co->decl_cells*sizeof(count_t) );\n\tmemset( co->rmarg, 0, co->decl_rows*sizeof(count_t) );\n\tmemset( co->cmarg, 0, co->decl_cols*sizeof(count_t) );\n\tmemset( co->expect, 0, co->decl_cells*sizeof(prob_t) );\n}\n\n\nvoid cat_setMinCellCount( void *pv, unsigned n ) {\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\tco->REQUIRED_CELL_MINIMUM = n;\n}\n\n\n/**\n * Only this one is public in order that we may count the samples\n * as they're added...\n */\nvoid cat_push( void *pv, coord_t r, coord_t c ) {\n\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\n\tassert( r < co->decl_rows );\n\tassert( c < co->decl_cols );\n\n\tco->counts[ r*co->decl_cols + c ] += 1;\n\n\t// size and marginals are kept up to date...\n\tco->sample_count++;\n\tco->rmarg[r] += 1;\n\tco->cmarg[c] += 1;\n}\n\n\nsize_t cat_size( void *pv ) {\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\treturn co->sample_count;\n}\n\n\nbool cat_complete( void *pv ) {\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\treturn ! _immediatelyDegenerate( co );\n}\n\n\nbool cat_is2x2( void *pv ) {\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\treturn (2 == co->decl_rows) && (2 == co->decl_cols);\n}\n\n\n/**\n * will ALWAYS be non-zero on entry, but it may only contain\n * a single set bit.\n */\nstatic int _offsetOfLeastLoss( unsigned bits, COUNT_T *loss, count_t *leastLoss ) {\n\tint v = __builtin_ctz( bits );\n\tint l = loss[v];\n\tbits ^= (1< loss[i] ) {\n\t\t\tl = loss[i];\n\t\t\tv = i;\n\t\t}\n\t}\n\t*leastLoss = l;\n\treturn v;\n}\n\n/**\n * This removes all rows and any columns containing cells with\n * counts LESS THAN OR EQUAL TO REQUIRED_CELL_MINIMUM.\n * \n * This method assumes we start with a table larger in at least\n * one dimention than 2x2 and halts when/if we reach a 2x2.\n */\nunsigned int cat_cullBadCells( void *pv, char *log, int buflen ) {\n\n\tunsigned int culled = 0;\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\tconst char * const EOL = log + buflen - 2; // leave room for \"+\\0\".\n\t// BEGIN log maintenance...\n\tconst int MIN_LOG_RECORD_LEN = 3; // \"R99\"\n\t// ...since tables will never exceed 99 rows or columns.\n\tchar *pc = log;\n\t// ...END log maintenance.\n\tunsigned int victim;\n\tunsigned int raw_mem_offset = 0; // linear offsets of \"bad\" cell.\n\n#ifdef _DEBUG\n\tconst bool SHOW_CULLING = getenv(\"SHOW_CULLING\") != NULL;\n\tif( SHOW_CULLING ) {\n\t\tfprintf( stderr, \"CULL log: original matrix\\n\" );\n\t\tdbg_dump( co, stderr, \"CULL\" );\n\t}\n#endif\n\n\tassert( ! _immediatelyDegenerate( co ) ); // so BOTH dims >= 2\n\n\twhile( (co->decl_rows > 2 || co->decl_cols > 2) && _badCellExists( co, &raw_mem_offset ) ) {\n\n\t\tunsigned int r, c;\n\t\tchar cullty = '?';\n\n\t\t/**\n\t\t * It is always necessary to cull a row or column.\n\t\t * If |columns| > 3, calculate \"best\" column to cull.\n\t\t * If |rows| > 3, calculate \"best\" row to cull.\n\t\t * \"Best\" victim is row OR column among the candidates for\n\t\t * culling with minimal marginal.\n\t\t */\n\n\t\tunsigned row_bitfield = 0;\n\t\tunsigned col_bitfield = 0;\n\t\tcount_t minRowCost, minColCost;\n\n\t\tassert( sizeof(row_bitfield)*8 >= MAX_CATEGORY_COUNT );\n\n\t\t// Find ALL rows and columns that are candidates for culling by \n\t\t// virtue of containing a bad cell.\n\n\t\tdo {\n\t\t\t_coordsOfOffset( co, raw_mem_offset, &r, &c );\n\t\t\trow_bitfield |= (1<calculated < Marginals ) \n\t\t\t_calc_marginals( co );\n\n\t\tif( co->decl_rows > 2 ) {\n\n\t\t\tr = _offsetOfLeastLoss( row_bitfield, co->rmarg, &minRowCost );\n\n\t\t\tif( co->decl_cols > 2 ) { // EITHER a col OR row may be culled\n\n\t\t\t\tc = _offsetOfLeastLoss( col_bitfield, co->cmarg, &minColCost );\n\t\t\t\tcullty = minRowCost < minColCost ? 'R' : 'C';\n\n\t\t\t} else // ONLY a row may be culled\n\t\t\t\tcullty = 'R';\n\n\t\t} else { // ONLY a column may be culled\n\n\t\t\tc = _offsetOfLeastLoss( col_bitfield, co->cmarg, &minColCost );\n\t\t\tcullty = 'C';\n\t\t}\n\n\t\tif( cullty == 'R' )\n\t\t\t_cullRow( co, (victim = r) );\n\t\telse {\n\t\t\tassert( cullty == 'C' );\n\t\t\t_cullCol( co, (victim = c) );\n\t\t}\n\n\t\t// Log it, if possible...\n\n\t\tif( pc ) {\n\n\t\t\tpc += sprintf( pc, \"%c%d\", cullty, victim );\n\n\t\t\t// Following is a bit of overkill to make sure we can\n\t\t\t// give some indication that we ran out of log space.\n\n\t\t\tif( EOL - pc < MIN_LOG_RECORD_LEN ) {\n\t\t\t\tif( EOL - pc > 0 ) strcpy( pc, \"+\");\n\t\t\t\tpc = NULL; // no more logging.\n\t\t\t\t// Really this should never be executed if log buffer\n\t\t\t\t// is always sufficient.\n\t\t\t}\n\t\t}\n\n\t\t// Unlike merging, decimating CAN leave a 0 cell at a lower\n\t\t// linear index, so reset is required...\n\t\tculled++;\n\t\traw_mem_offset = 0;\n\n#ifdef _DEBUG\n\t\tif( SHOW_CULLING ) {\n\t\t\tfprintf( stderr,\n\t\t\t\t\"CULL After %d selected %c%d (from R:%08X,C:%08X) costing %d samples\\n\", \n\t\t\t\tculled, cullty, victim,\n\t\t\t\trow_bitfield, col_bitfield, \n\t\t\t \tcullty=='R' ? minRowCost : minColCost );\n\t\t\tdbg_dump( co, stderr, \"CULL\" );\n\t\t}\n#endif\n\t}\n\n\tif( culled > 0 ) \n\t\t_recalcSampleCount( co );\n\n\treturn culled;\n}\n\n\n#ifdef HAVE_G_TEST\nint cat_g( void *pv, struct Statistic *result ) {\n\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\tconst int R = co->decl_rows;\n\tconst int C = co->decl_cols;\n\tdouble g = 0.0;\n\n\tabort(); // unfinished.\n\n\tif( co->calculated < Expectation )\n\t\t_calc_expectation( co );\n\n\tfor(unsigned int i = 0; i < R; i++ ) {\n\t\tfor(unsigned int j = 0; j < C; j++ ) {\n\t\t\tconst double O = _count( co, i, j );\n\t\t\tconst double E = _expected( co, i, j );\n\t\t\tif( E > 0 && O > 0 ) \n\t\t\t\tg += ( O * log( O / E ) );\n\t\t}\n\t}\n\n\tg *= 2.0; // TODO: verify!\n\n\tresult->name\n\t\t= \"G\";\n\tresult->sample_count\n\t\t= co->sample_count;\n\tresult->probability\n\t\t= gsl_cdf_chisq_Q( g, (R-1)*(C-1) );\n\n\treturn 0;\n}\n#endif\n\n\nint cat_chi_square( void *pv, struct Statistic *result ) {\n\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\tconst int R = co->decl_rows;\n\tconst int C = co->decl_cols;\n\n\tunsigned int n_empty = 0;\n\tdouble chi = 0.0;\n\n\tif( co->calculated < Expectation )\n\t\t_calc_expectation( co );\n\n\tfor(unsigned int i = 0; i < R; i++ ) {\n\t\tfor(unsigned int j = 0; j < C; j++ ) {\n\t\t\tconst double O = _count( co, i, j );\n\t\t\tconst double E = _expected( co, i, j );\n\t\t\tif( E > 0 && O > 0 ) \n\t\t\t\tchi += ((O-E)*(O-E))/E;\n\t\t\telse\n\t\t\tif( O == 0 )\n\t\t\t\tn_empty++;\n\t\t}\n\t}\n\n\tresult->name\n\t\t= \"Chi-square\";\n\tresult->sample_count\n\t\t= co->sample_count;\n\tresult->probability\n\t\t= gsl_cdf_chisq_Q( chi, (R-1)*(C-1) );\n\n\tresult->extra_value[0] = R;\n\tresult->extra_value[1] = C;\n\tresult->extra_value[2] = co->minimumExpected;\n\tresult->extra_value[3] = n_empty;\n\n\treturn 0;\n}\n\n\nint cat_fisher_exact( void *pv, struct Statistic *result ) {\n\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\n\t// OPTIMIZE: does not make sense to call fisher exact without\n\t// NULL stest_t argument. Keeping this signature for consistency\n\t// with all other stats, but it might make sense to change the\n\t// signature of just this function to return P-value (unless I\n\t// ever added log-likelihood ratio calculation which is what\n\t// ought to be returned as the function value).\n\n\t/**\n\t * Given the table:\n\t * a | b\n\t * --+--\n\t * c | d\n\t *\n\t * ...we need to pass fexact_prob( x, m, n, k )\n\t * m == a+c\n\t * n == b+d\n\t * k == a+b\n\t * x == a\n\t */\n\tresult->name\n\t\t= \"Fisher_Exact\";\n\tresult->sample_count\n\t\t= co->sample_count;\n\tresult->probability\n\t\t= fexact_prob( \n\t\t\t_count(co,0,0), \n\t\t\t_count(co,0,0) + _count(co,1,0), // a+c\n\t\t\t_count(co,0,1) + _count(co,1,1), // b+d\n\t\t\t_count(co,0,0) + _count(co,0,1) ); // a+b\n\n\t// TODO: Don't need these now.\n\tresult->extra_value[0] = co->decl_rows;\n\tresult->extra_value[1] = co->decl_cols;\n\n\treturn 0;\n}\n\n\n/**\n */\ndouble cat_spearman_rho( void *pv ) {\n\n\tstruct CatCovars *co = (struct CatCovars *)pv;\n\tdouble rho = nan(\"nan\");\n\tconst unsigned r0 = _count(co,0,0) + _count(co,0,1);\n\tconst unsigned r1 = _count(co,1,0) + _count(co,1,1);\n\tconst unsigned c0 = _count(co,0,0) + _count(co,1,0);\n\tconst unsigned c1 = _count(co,0,1) + _count(co,1,1);\n\n\t// Continuing is pointless if any of these are 0.\n\n\tif( r0 > 0 && r1 > 0 && c0 > 0 && c1 > 0 ) {\n\n\t\tconst float MU = (co->sample_count+1.0)/2.0;\n\t\tconst float r0_mu = (r0+1.0)/2.0;\n\t\tconst float r1_mu = MEAN_RANK_OF_TIES( r0, co->sample_count );\n\t\tconst float c0_mu = (c0+1.0)/2.0;\n\t\tconst float c1_mu = MEAN_RANK_OF_TIES( c0, co->sample_count );\n\n\t\t/**\n\t\t * Following is a heavily compacted form of the Pearson rho,\n\t\t * compacted because thanks to all the ties there are only two\n\t\t * \"versions\" of (x_i-x_mu) and (y_i-x_mu), and the general\n\t\t * sums in the Pearson quotient just become multiples of these.\n\t\t */\n\t\tconst double DENOM\n\t\t\t= sqrt(\n\t\t\t (r0*(r0_mu-MU)*(r0_mu-MU) + r1*(r1_mu-MU)*(r1_mu-MU))\n\t\t\t* (c0*(c0_mu-MU)*(c0_mu-MU) + c1*(c1_mu-MU)*(c1_mu-MU)) );\n\n\t\tif( isnormal(DENOM) ) {\n\t\t\trho =\n\t\t\t\t( _count(co,0,0)*(r0_mu-MU)*(c0_mu-MU)\n\t\t\t\t+ _count(co,0,1)*(r0_mu-MU)*(c1_mu-MU)\n\t\t\t\t+ _count(co,1,0)*(r1_mu-MU)*(c0_mu-MU)\n\t\t\t\t+ _count(co,1,1)*(r1_mu-MU)*(c1_mu-MU) )\n\t\t\t\t/\n\t\t\t\tDENOM;\n\t\t}\n\t\t\n\t}\n\treturn rho;\n}\n\n\n#ifdef _UNITTEST_CAT_\n\n#include \n\nint main( int argc, char *argv[] ) {\n\n\tif( argc >= 3 ) {\n\n\t\tconst int MERGE_LOG_LEN = 128;\n\t\tchar merge_log[ MERGE_LOG_LEN ]; \n\n\t\tstruct Statistic result;\n\n\t\tconst unsigned int MAXROW\n\t\t\t= atoi(argv[1]);\n\t\tconst unsigned int MAXCOL\n\t\t\t= atoi(argv[2]);\n\n\t\tFILE *fp \n\t\t\t= argc > 3\n\t\t\t? fopen( argv[3], \"r\" )\n\t\t\t: stdin;\n\n\t\tint err = 0;\n\t\tchar *line = NULL;\n\t\tsize_t n = 0;\n\n\t\tvoid *accum\n\t\t\t= cat_create( MAXROW, MAXCOL);\n\n\t\tcat_setMinCellCount( accum, 5 );\n\t\tcat_clear( accum, MAXROW, MAXCOL ); // ...as per command line.\n\n\t\twhile( getline( &line, &n, fp ) > 0 ) {\n\t\t\tint cat[2];\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%d\\n\", cat+0, cat+1 ) ) {\n\t\t\t\tif( 0 <= cat[0] && 0 <= cat[1] ) {\n\t\t\t\t\tcat_push( accum, cat[0], cat[1] );\n\t\t\t\t}\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\tputs( \"Original...\" );\n\t\tdbg_dump( accum, stdout, \"\" );\n\n\t\tif( cat_cullBadCells( accum, merge_log, MERGE_LOG_LEN ) > 0 ) {\n\t\t\tfprintf( stdout, \"Culled %s, leaving...\\n\", merge_log );\n\t\t\tdbg_dump( accum, stdout, \"\" );\n\t\t}\n\n\t\tmemset( &result, 0, sizeof(struct Statistic) );\n\t\terr = cat_is2x2( accum )\n\t\t\t? cat_fisher_exact( accum, &result )\n\t\t\t: cat_chi_square( accum, &result );\n\n\t\tif( ! err ) {\n\t\t\tprintf( \"p-value=%f\", result.probability );\n\t\t\tif( cat_is2x2( accum ) )\n\t\t\t\tprintf( \", spearman=%f\\n\", cat_spearman_rho( accum ) );\n\t\t\telse\n\t\t\t\tfputc( '\\n', stdout );\n\t\t} else\n\t\t\tprintf( \"error\\n\" );\n\n\t\tcat_destroy( accum );\n\n\t} else\n\t\terr( -1, \"%s [ <2-column file> ]\", argv[0] );\n\treturn 0;\n}\n#endif\n\n", "meta": {"hexsha": "dab9ec88c75e6c785809d4f5005ddae4405f874a", "size": 21766, "ext": "c", "lang": "C", "max_stars_repo_path": "pairwise/src/cat.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/cat.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/cat.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.4561797753, "max_line_length": 93, "alphanum_fraction": 0.621198199, "num_tokens": 7006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.25890718627037573}} {"text": "/**\n * \\author Sylvain Marsat, University of Maryland - NASA GSFC\n *\n * \\brief C header for functions windowing and computing FFT/IFFT of time/frequency series.\n *\n */\n\n#ifndef __COMPUTELISASNR_H__\n#define __COMPUTELISASNR_H__ 1\n\n#ifdef __GNUC__\n#define UNUSED __attribute__ ((unused))\n#else\n#define UNUSED\n#endif\n\n#define _XOPEN_SOURCE 500\n\n#include \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 \"waveform.h\"\n#include \"fft.h\"\n#include \"LISAgeometry.h\"\n#include \"LISAFDresponse.h\"\n#include \"LISAutils.h\"\n\n/********************************** Structures ******************************************/\n\n/* Parameters for the generation of a LISA waveform (in the form of a list of modes) */\ntypedef struct tagComputeLISASNRparams {\n double tRef; /* reference time (s) - GPS time at the frequency representing coalescence */\n double phiRef; /* reference phase (rad) - phase at the frequency representing coalescence (or at fRef if specified) */\n double fRef; /* reference frequency at which phiRef is set (Hz, default 0 which is interpreted as Mf=0.14) */\n double m1; /* mass of companion 1 (solar masses, default 2e6) */\n double m2; /* mass of companion 2 (solar masses, default 1e6) */\n double distance; /* distance of source (Mpc, default 1e3) */\n double inclination; /* inclination of source (rad, default pi/3) */\n double lambda; /* first angle for the position in the sky (rad, default 0) */\n double beta; /* second angle for the position in the sky (rad, default 0) */\n double polarization; /* polarization angle (rad, default 0) */\n\n int nbmode; /* number of modes to generate (starting with 22) - defaults to 5 (all modes) */\n double deltatobs; /* Observation duration (years, default=2) */\n double minf; /* Minimal frequency (Hz, default=0) - when set to 0, use the lowest frequency where the detector noise model is trusted __LISASimFD_Noise_fLow (set somewhat arbitrarily)*/\n double maxf; /* Maximal frequency (Hz, default=0) - when set to 0, use the highest frequency where the detector noise model is trusted __LISASimFD_Noise_fHigh (set somewhat arbitrarily)*/\n int tagextpn; /* Tag to allow PN extension of the waveform at low frequencies */\n double Mfmatch; /* When PN extension allowed, geometric matching frequency: will use ROM above this value. If <=0, use ROM down to the lowest covered frequency */\n int tagtdi; /* Tag selecting the desired TDI observables */\n int tagint; /* Tag choosing the integrator: 0 for Fresnel (default), 1 for linear integration */\n int nbptsoverlap; /* Number of points to use in loglinear overlaps (default 32768) */\n LISAconstellation *variant; /* A structure defining the LISA constellation features */\n int frozenLISA; /* Freeze the orbital configuration to the time of peak of the injection (default 0) */\n ResponseApproxtag responseapprox; /* Approximation in the GAB and orb response - choices are full (full response, default), lowfL (keep orbital delay frequency-dependence but simplify constellation response) and lowf (simplify constellation and orbital response) - WARNING : at the moment noises are not consistent, and TDI combinations from the GAB are unchanged */\n int fromtditdfile; /* Option for loading time series for TDI observables and FFTing */\n int nlinesinfile; /* Number of lines of input file */\n char indir[256]; /* Input directory */\n char infile[256]; /* Input file */\n int loadparamsfile; /* Option to load physical parameters from file and to output result to file (default 0) */\n int nlinesparams; /* Number of lines in params file */\n char paramsdir[256]; /* Directory for the input/output file */\n char paramsfile[256]; /* Input file with the parameters */\n char outputfile[256]; /* Output file */\n} ComputeLISASNRparams;\n\n\n#if 0\n{ /* so that editors will match succeeding brace */\n#elif defined(__cplusplus)\n}\n#endif\n\n#endif /* _COMPUTELISASNR_H */\n", "meta": {"hexsha": "9589158303fbd220a84fdbee0d7bce502f344a26", "size": 4517, "ext": "h", "lang": "C", "max_stars_repo_path": "LISAinference/ComputeLISASNR.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": "LISAinference/ComputeLISASNR.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": "LISAinference/ComputeLISASNR.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": 50.1888888889, "max_line_length": 371, "alphanum_fraction": 0.6716847465, "num_tokens": 1088, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.40733340004593027, "lm_q1q2_score": 0.25800915069026736}} {"text": "/* multifit/fdfridge.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\nstatic int fdfridge_f(const gsl_vector * x, void * params, gsl_vector * f);\nstatic int fdfridge_df(const gsl_vector * x, void * params, gsl_matrix * J);\n\ngsl_multifit_fdfridge *\ngsl_multifit_fdfridge_alloc (const gsl_multifit_fdfsolver_type * T,\n const size_t n, const size_t p)\n{\n gsl_multifit_fdfridge * work;\n\n work = calloc(1, sizeof(gsl_multifit_fdfridge));\n if (work == NULL)\n {\n GSL_ERROR_VAL(\"failed to allocate workspace\",\n GSL_ENOMEM, 0);\n }\n\n work->s = gsl_multifit_fdfsolver_alloc (T, n + p, p);\n if (work->s == NULL)\n {\n gsl_multifit_fdfridge_free(work);\n GSL_ERROR_VAL(\"failed to allocate space for fdfsolver\",\n GSL_ENOMEM, 0);\n }\n\n work->wts = gsl_vector_alloc(n + p);\n if (work->wts == NULL)\n {\n gsl_multifit_fdfridge_free(work);\n GSL_ERROR_VAL(\"failed to allocate space for weight vector\",\n GSL_ENOMEM, 0);\n }\n\n work->f = gsl_vector_alloc(n);\n if (work->f == NULL)\n {\n gsl_multifit_fdfridge_free(work);\n GSL_ERROR_VAL(\"failed to allocate space for f vector\",\n GSL_ENOMEM, 0);\n }\n\n work->n = n;\n work->p = p;\n work->lambda = 0.0;\n\n /* initialize weights to 1 (for augmented portion of vector) */\n gsl_vector_set_all(work->wts, 1.0);\n\n return work;\n} /* gsl_multifit_fdfridge_alloc() */\n\nvoid\ngsl_multifit_fdfridge_free(gsl_multifit_fdfridge *work)\n{\n if (work->s)\n gsl_multifit_fdfsolver_free(work->s);\n\n if (work->wts)\n gsl_vector_free(work->wts);\n \n if (work->f)\n gsl_vector_free(work->f);\n\n free(work);\n}\n\nconst char *\ngsl_multifit_fdfridge_name(const gsl_multifit_fdfridge * w)\n{\n return gsl_multifit_fdfsolver_name(w->s);\n}\n\ngsl_vector *\ngsl_multifit_fdfridge_position (const gsl_multifit_fdfridge * w)\n{\n return gsl_multifit_fdfsolver_position(w->s);\n}\n\ngsl_vector *\ngsl_multifit_fdfridge_residual (const gsl_multifit_fdfridge * w)\n{\n return gsl_multifit_fdfsolver_residual(w->s);\n}\n\nsize_t\ngsl_multifit_fdfridge_niter (const gsl_multifit_fdfridge * w)\n{\n return w->s->niter;\n}\n\nint\ngsl_multifit_fdfridge_set (gsl_multifit_fdfridge * w,\n gsl_multifit_function_fdf * f,\n const gsl_vector * x,\n const double lambda)\n{\n return gsl_multifit_fdfridge_wset(w, f, x, lambda, NULL);\n} /* gsl_multifit_fdfridge_set() */\n\nint\ngsl_multifit_fdfridge_wset (gsl_multifit_fdfridge * w,\n gsl_multifit_function_fdf * f,\n const gsl_vector * x,\n const double lambda,\n const gsl_vector * wts)\n{\n const size_t n = w->n;\n const size_t p = w->p;\n\n if (n != f->n || p != f->p)\n {\n GSL_ERROR (\"function size does not match solver\", GSL_EBADLEN);\n }\n else if (p != x->size)\n {\n GSL_ERROR (\"vector length does not match solver\", GSL_EBADLEN);\n }\n else if (wts != NULL && n != wts->size)\n {\n GSL_ERROR (\"weight vector length does not match solver\", GSL_EBADLEN);\n }\n else\n {\n int status;\n gsl_vector_view wv = gsl_vector_subvector(w->wts, 0, n);\n\n /* save user defined fdf */\n w->fdf = f;\n\n /* build modified fdf for Tikhonov terms */\n w->fdftik.f = &fdfridge_f;\n w->fdftik.df = &fdfridge_df;\n w->fdftik.n = n + p; /* add p for Tikhonov terms */\n w->fdftik.p = p;\n w->fdftik.params = (void *) w;\n\n /* store damping parameter */\n w->lambda = lambda;\n w->L = NULL;\n\n if (wts)\n {\n /* copy weight vector into user portion of w->wts */\n gsl_vector_memcpy(&wv.vector, wts);\n status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, w->wts);\n }\n else\n {\n status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, NULL);\n }\n\n /* update function/Jacobian evaluations */\n f->nevalf = w->fdftik.nevalf;\n f->nevaldf = w->fdftik.nevaldf;\n\n return status;\n }\n} /* gsl_multifit_fdfridge_wset() */\n\nint\ngsl_multifit_fdfridge_set2 (gsl_multifit_fdfridge * w,\n gsl_multifit_function_fdf * f,\n const gsl_vector * x,\n const gsl_vector * lambda)\n{\n return gsl_multifit_fdfridge_wset2(w, f, x, lambda, NULL);\n} /* gsl_multifit_fdfridge_set2() */\n\nint\ngsl_multifit_fdfridge_wset2 (gsl_multifit_fdfridge * w,\n gsl_multifit_function_fdf * f,\n const gsl_vector * x,\n const gsl_vector * lambda,\n const gsl_vector * wts)\n{\n const size_t n = w->n;\n const size_t p = w->p;\n\n if (n != f->n || p != f->p)\n {\n GSL_ERROR (\"function size does not match solver\", GSL_EBADLEN);\n }\n else if (p != x->size)\n {\n GSL_ERROR (\"vector length does not match solver\", GSL_EBADLEN);\n }\n else if (lambda->size != p)\n {\n GSL_ERROR (\"lambda vector size does not match solver\", GSL_EBADLEN);\n }\n else if (wts != NULL && n != wts->size)\n {\n GSL_ERROR (\"weight vector length does not match solver\", GSL_EBADLEN);\n }\n else\n {\n int status;\n gsl_vector_view wv = gsl_vector_subvector(w->wts, 0, n);\n\n /* save user defined fdf */\n w->fdf = f;\n w->fdf->nevalf = 0;\n w->fdf->nevaldf = 0;\n\n /* build modified fdf for Tikhonov terms */\n w->fdftik.f = &fdfridge_f;\n w->fdftik.df = &fdfridge_df;\n w->fdftik.n = n + p; /* add p for Tikhonov terms */\n w->fdftik.p = p;\n w->fdftik.params = (void *) w;\n\n /* store damping matrix */\n w->lambda = 0.0;\n w->L_diag = lambda;\n w->L = NULL;\n\n if (wts)\n {\n /* copy weight vector into user portion */\n gsl_vector_memcpy(&wv.vector, wts);\n status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, w->wts);\n }\n else\n {\n status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, NULL);\n }\n\n /* update function/Jacobian evaluations */\n f->nevalf = w->fdftik.nevalf;\n f->nevaldf = w->fdftik.nevaldf;\n\n return status;\n }\n} /* gsl_multifit_fdfridge_wset2() */\n\nint\ngsl_multifit_fdfridge_set3 (gsl_multifit_fdfridge * w,\n gsl_multifit_function_fdf * f,\n const gsl_vector * x,\n const gsl_matrix * L)\n{\n return gsl_multifit_fdfridge_wset3(w, f, x, L, NULL);\n} /* gsl_multifit_fdfridge_set3() */\n\nint\ngsl_multifit_fdfridge_wset3 (gsl_multifit_fdfridge * w,\n gsl_multifit_function_fdf * f,\n const gsl_vector * x,\n const gsl_matrix * L,\n const gsl_vector * wts)\n{\n const size_t n = w->n;\n const size_t p = w->p;\n\n if (n != f->n || p != f->p)\n {\n GSL_ERROR (\"function size does not match solver\", GSL_EBADLEN);\n }\n else if (p != x->size)\n {\n GSL_ERROR (\"vector length does not match solver\", GSL_EBADLEN);\n }\n else if (L->size2 != p)\n {\n GSL_ERROR (\"L matrix size2 does not match solver\", GSL_EBADLEN);\n }\n else if (wts != NULL && n != wts->size)\n {\n GSL_ERROR (\"weight vector length does not match solver\", GSL_EBADLEN);\n }\n else\n {\n int status;\n gsl_vector_view wv = gsl_vector_subvector(w->wts, 0, n);\n\n /* save user defined fdf */\n w->fdf = f;\n w->fdf->nevalf = 0;\n w->fdf->nevaldf = 0;\n\n /* build modified fdf for Tikhonov terms */\n w->fdftik.f = &fdfridge_f;\n w->fdftik.df = &fdfridge_df;\n w->fdftik.n = n + p; /* add p for Tikhonov terms */\n w->fdftik.p = p;\n w->fdftik.params = (void *) w;\n\n /* store damping matrix */\n w->lambda = 0.0;\n w->L_diag = NULL;\n w->L = L;\n\n if (wts)\n {\n /* copy weight vector into user portion */\n gsl_vector_memcpy(&wv.vector, wts);\n status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, w->wts);\n }\n else\n {\n status = gsl_multifit_fdfsolver_wset(w->s, &(w->fdftik), x, NULL);\n }\n\n /* update function/Jacobian evaluations */\n f->nevalf = w->fdftik.nevalf;\n f->nevaldf = w->fdftik.nevaldf;\n\n return status;\n }\n} /* gsl_multifit_fdfridge_wset3() */\n\nint\ngsl_multifit_fdfridge_iterate (gsl_multifit_fdfridge * w)\n{\n int status = gsl_multifit_fdfsolver_iterate(w->s);\n\n /* update function/Jacobian evaluations */\n w->fdf->nevalf = w->fdftik.nevalf;\n w->fdf->nevaldf = w->fdftik.nevaldf;\n\n return status;\n}\n\nint\ngsl_multifit_fdfridge_driver (gsl_multifit_fdfridge * w,\n const size_t maxiter,\n const double xtol,\n const double gtol,\n const double ftol,\n int *info)\n{\n int status = gsl_multifit_fdfsolver_driver(w->s, maxiter, xtol,\n gtol, ftol, info);\n return status;\n} /* gsl_multifit_fdfridge_driver() */\n\n/*\nfdfridge_f()\n Callback function to provide residuals, including extra p\nTikhonov terms. The residual vector will have the form:\n\nf~ = [ f ]\n [ \\lambda x ]\n\nwhere f is the user supplied residuals, x are the model\nparameters, and \\lambda is the Tikhonov damping parameter\n\nInputs: x - model parameters (size p)\n params - pointer to fdfridge workspace\n f - (output) (n+p) vector to store f~\n*/\n\nstatic int\nfdfridge_f(const gsl_vector * x, void * params, gsl_vector * f)\n{\n int status;\n gsl_multifit_fdfridge *w = (gsl_multifit_fdfridge *) params;\n const size_t n = w->n;\n const size_t p = w->p;\n gsl_vector_view f_user = gsl_vector_subvector(f, 0, n);\n gsl_vector_view f_tik = gsl_vector_subvector(f, n, p);\n\n /* call user callback function to get residual vector f */\n status = gsl_multifit_eval_wf(w->fdf, x, NULL, &f_user.vector);\n if (status)\n return status;\n\n if (w->L_diag)\n {\n /* store diag(L_diag) x in Tikhonov portion of f~ */\n gsl_vector_memcpy(&f_tik.vector, x);\n gsl_vector_mul(&f_tik.vector, w->L_diag);\n }\n else if (w->L)\n {\n /* store Lx in Tikhonov portion of f~ */\n gsl_blas_dgemv(CblasNoTrans, 1.0, w->L, x, 0.0, &f_tik.vector);\n }\n else\n {\n /* store \\lambda x in Tikhonov portion of f~ */\n gsl_vector_memcpy(&f_tik.vector, x);\n gsl_vector_scale(&f_tik.vector, w->lambda);\n }\n\n return GSL_SUCCESS;\n} /* fdfridge_f() */\n\nstatic int\nfdfridge_df(const gsl_vector * x, void * params, gsl_matrix * J)\n{\n int status;\n gsl_multifit_fdfridge *w = (gsl_multifit_fdfridge *) params;\n const size_t n = w->n;\n const size_t p = w->p;\n gsl_matrix_view J_user = gsl_matrix_submatrix(J, 0, 0, n, p);\n gsl_matrix_view J_tik = gsl_matrix_submatrix(J, n, 0, p, p);\n gsl_vector_view diag = gsl_matrix_diagonal(&J_tik.matrix);\n\n /* compute Jacobian */\n if (w->fdf->df)\n status = gsl_multifit_eval_wdf(w->fdf, x, NULL, &J_user.matrix);\n else\n {\n /* compute f(x) and then finite difference Jacobian */\n status = gsl_multifit_eval_wf(w->fdf, x, NULL, w->f);\n status += gsl_multifit_fdfsolver_dif_df(x, NULL, w->fdf, w->f,\n &J_user.matrix);\n }\n\n if (status)\n return status;\n\n if (w->L_diag)\n {\n /* store diag(L_diag) in Tikhonov portion of J */\n gsl_matrix_set_zero(&J_tik.matrix);\n gsl_vector_memcpy(&diag.vector, w->L_diag);\n }\n else if (w->L)\n {\n /* store L in Tikhonov portion of J */\n gsl_matrix_memcpy(&J_tik.matrix, w->L);\n }\n else\n {\n /* store \\lambda I_p in Tikhonov portion of J */\n gsl_matrix_set_zero(&J_tik.matrix);\n gsl_vector_set_all(&diag.vector, w->lambda);\n }\n\n return GSL_SUCCESS;\n} /* fdfridge_df() */\n", "meta": {"hexsha": "eeb710c399da2fd51aa789813ba8dbd804b0d209", "size": 12919, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit/fdfridge.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/fdfridge.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/fdfridge.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.0238611714, "max_line_length": 81, "alphanum_fraction": 0.5937766081, "num_tokens": 3770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5583270090337582, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.2573981195078215}} {"text": "/*\n** Copyright (c) 2008, 2009 Gerald I. Evenden\n*/\nstatic const char\nRCS_ID[] = \"$Id: proj_gdinverse.c,v 5.6 2009/05/17 19:41:47 gie Exp gie $\";\n/*\n** Permission is hereby granted, free of charge, to any person obtaining\n** a copy of this software and associated documentation files (the\n** \"Software\"), to deal in the Software without restriction, including\n** without limitation the rights to use, copy, modify, merge, publish,\n** distribute, sublicense, and/or sell copies of the Software, and to\n** permit persons to whom the Software is furnished to do so, subject to\n** 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 NONINFRINGEMENT.\n** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n/** @file proj_gdinverse.c \n * @brief general inverse projection support\n * @author Gerald I. Evenden\n */\n#include \"config.h\"\n#include \n\n#if HAVE_LIBGSL\n\n#include \n#include \n#include \n#define LOOP_LIMIT 10\n\nstruct p_gsl { PROJ *P; double x, y; };\ntypedef struct p_gsl GP;\n\tstatic int\nfunc_f(const gsl_vector *x, void *p, gsl_vector *f) {\n//func_f(const gsl_vector *x, GP *p, gsl_vector *f) {\n\tPROJ_LP lp;\n\n\tlp.lam = gsl_vector_get(x,0);\n\tlp.phi = gsl_vector_get(x,1);\n\tPROJ_XY xy = (*((GP *)p)->P->fwd)(lp, ((GP *)p)->P);\n\tgsl_vector_set(f, 0, xy.x - ((GP *)p)->x);\n\tgsl_vector_set(f, 1, xy.y - ((GP *)p)->y);\n\treturn GSL_SUCCESS;\n}\n\tstatic int\nfunc_df(const gsl_vector * x, void *p, gsl_matrix *J) {\n\tstruct PROJ_DERIVS der;\n\tPROJ_LP lp;\n\n\tlp.lam = gsl_vector_get(x,0);\n\tlp.phi = gsl_vector_get(x,1);\n\t(*((GP *)p)->P->derivs)(((GP *)p)->P, lp, &der);\n\tgsl_matrix_set(J, 0, 0, der.x_l);\n\tgsl_matrix_set(J, 0, 1, der.x_p);\n\tgsl_matrix_set(J, 1, 0, der.y_l);\n\tgsl_matrix_set(J, 1, 1, der.y_p);\n\treturn GSL_SUCCESS;\n}\n\tstatic int\nfunc_fdf(const gsl_vector * x, void *p, gsl_vector *f, gsl_matrix *J) {\n\tfunc_f(x, p, f);\n\tfunc_df(x, p, J);\n\treturn GSL_SUCCESS;\n}\n/* @brief determine projection inverse\n * @param[in] P projection control structure\n * @param est estimated geographic answer\n * @param[in] xy Cartesian location\n * @param[in] tol tolerance\n * @return ==0 if successful\n */\n\tint\nproj_gdinverse(PROJ *P, PROJ_LP *est, PROJ_XY xy, double tol) {\n\tconst gsl_multiroot_fdfsolver_type *T2;\n\tconst gsl_multiroot_fsolver_type *T1;\n\tgsl_multiroot_fdfsolver *s2;\n\tgsl_multiroot_fsolver *s1;\n\tint status;\n\tsize_t i, iter = 0;\n\tconst size_t n = 2;\n\tGP p;\n\tint ders = P->derivs != NULL;\n\tgsl_multiroot_function_fdf f2 = {&func_f, &func_df, &func_fdf, n, &p};\n\tgsl_multiroot_function f1 = {&func_f, n, &p};\n\n\tp.P = P;\n\tp.x = xy.x;\n\tp.y = xy.y;\n\tgsl_vector *x = gsl_vector_alloc(n);\n\tgsl_vector_set(x, 0, est->lam);\n\tgsl_vector_set(x, 1, est->phi);\n\tif (ders) {\n\t\tT2 = gsl_multiroot_fdfsolver_gnewton;\n\t\ts2 = gsl_multiroot_fdfsolver_alloc(T2, n);\n\t\tgsl_multiroot_fdfsolver_set(s2, &f2, x);\n\t} else {\n\t\tT1 = gsl_multiroot_fsolver_hybrids;\n\t\ts1 = gsl_multiroot_fsolver_alloc(T1, n);\n\t\tgsl_multiroot_fsolver_set(s1, &f1, x);\n\t}\n\tdo {\n\t\t++iter;\n\t\tstatus = ders ? gsl_multiroot_fdfsolver_iterate(s2):\n\t\t\t\t\t\tgsl_multiroot_fsolver_iterate(s1);\n\t\tif (status)\n\t\t\tbreak;\n\t\tstatus = gsl_multiroot_test_residual( ders?s2->f : s1->f, tol);\n\t} while (status == GSL_CONTINUE && iter < LOOP_LIMIT);\n\tif (ders) {\n\t\test->lam = gsl_vector_get(s2->x,0);\n\t\test->phi = gsl_vector_get(s2->x,1);\n\t\tgsl_multiroot_fdfsolver_free(s2);\n\t} else {\n\t\test->lam = gsl_vector_get(s1->x,0);\n\t\test->phi = gsl_vector_get(s1->x,1);\n\t\tgsl_multiroot_fsolver_free(s1);\n\t}\n\tgsl_vector_free(x);\n\treturn 0;\n}\n#else // end LIBGSL true\n/* the following is present to resolve any funky linking and to\n * ensure the system fails if gdinverse is called when the GSL flag\n * is not set.\n*/\n#include \n#include \n\tint\nproj_gdinverse(PROJ *P, PROJ_LP *est, PROJ_XY xy, double tol) {\n\tfprintf(stderr,\"libproj4: entered gdinverse---no GSL avail. See admin\\n\");\n\texit(-1);\n\treturn -1;\n}\n#endif // end LIBGSL condition\n/*\n * $Log:\n */\n", "meta": {"hexsha": "8bcdcda6b6143c3099ecd0baf7db826338bf8cb1", "size": 4481, "ext": "c", "lang": "C", "max_stars_repo_path": "libproject-1.01/src/proj_gdinverse.c", "max_stars_repo_name": "rouault/libproj4", "max_stars_repo_head_hexsha": "d7c3bde003b7d4c2c408f905f2fcdfe3d53c2313", "max_stars_repo_licenses": ["X11", "MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libproject-1.01/src/proj_gdinverse.c", "max_issues_repo_name": "rouault/libproj4", "max_issues_repo_head_hexsha": "d7c3bde003b7d4c2c408f905f2fcdfe3d53c2313", "max_issues_repo_licenses": ["X11", "MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libproject-1.01/src/proj_gdinverse.c", "max_forks_repo_name": "rouault/libproj4", "max_forks_repo_head_hexsha": "d7c3bde003b7d4c2c408f905f2fcdfe3d53c2313", "max_forks_repo_licenses": ["X11", "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.4829931973, "max_line_length": 75, "alphanum_fraction": 0.7005132783, "num_tokens": 1386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307806984443, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2570845078990605}} {"text": "/* multilarge_nlinear/gsl_multilarge_nlinear.h\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#ifndef __GSL_MULTILARGE_NLINEAR_H__\n#define __GSL_MULTILARGE_NLINEAR_H__\n\n#if !defined( GSL_FUN )\n# if !defined( GSL_DLL )\n# define GSL_FUN extern\n# elif defined( BUILD_GSL_DLL )\n# define GSL_FUN extern __declspec(dllexport)\n# else\n# define GSL_FUN extern __declspec(dllimport)\n# endif\n#endif\n\n#include \n#include \n#include \n#include \n#include \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\ntypedef enum\n{\n GSL_MULTILARGE_NLINEAR_FWDIFF,\n GSL_MULTILARGE_NLINEAR_CTRDIFF\n} gsl_multilarge_nlinear_fdtype;\n\n/* Definition of vector-valued functions and gradient with parameters\n based on gsl_vector */\n\ntypedef struct\n{\n int (* f) (const gsl_vector * x, void * params, gsl_vector * f);\n int (* df) (CBLAS_TRANSPOSE_t TransJ, const gsl_vector * x,\n const gsl_vector * u, void * params, gsl_vector * v,\n gsl_matrix * JTJ);\n int (* fvv) (const gsl_vector * x, const gsl_vector * v, void * params,\n gsl_vector * fvv);\n size_t n; /* number of functions */\n size_t p; /* number of independent variables */\n void * params; /* user parameters */\n size_t nevalf; /* number of function evaluations */\n size_t nevaldfu; /* number of Jacobian matrix-vector evaluations */\n size_t nevaldf2; /* number of Jacobian J^T J evaluations */\n size_t nevalfvv; /* number of fvv evaluations */\n} gsl_multilarge_nlinear_fdf;\n\n/* trust region subproblem method */\ntypedef struct\n{\n const char *name;\n void * (*alloc) (const void * params, const size_t n, const size_t p);\n int (*init) (const void * vtrust_state, void * vstate);\n int (*preloop) (const void * vtrust_state, void * vstate);\n int (*step) (const void * vtrust_state, const double delta,\n gsl_vector * dx, void * vstate);\n int (*preduction) (const void * vtrust_state, const gsl_vector * dx,\n double * pred, void * vstate);\n void (*free) (void * vstate);\n} gsl_multilarge_nlinear_trs;\n\n/* scaling matrix specification */\ntypedef struct\n{\n const char *name;\n int (*init) (const gsl_matrix * JTJ, gsl_vector * diag);\n int (*update) (const gsl_matrix * JTJ, gsl_vector * diag);\n} gsl_multilarge_nlinear_scale;\n\n/*\n * linear least squares solvers - there are three steps to\n * solving a least squares problem using a direct method:\n *\n * 1. init: called once per iteration when a new Jacobian matrix\n * is required; form normal equations matrix J^T J\n * 2. presolve: called each time a new LM parameter value mu is available;\n * used for cholesky method in order to factor\n * the (J^T J + mu D^T D) matrix\n * 3. solve: solve the least square system for a given rhs\n */\ntypedef struct\n{\n const char *name;\n void * (*alloc) (const size_t n, const size_t p);\n int (*init) (const void * vtrust_state, void * vstate);\n int (*presolve) (const double mu, const void * vtrust_state, void * vstate);\n int (*solve) (const gsl_vector * g, gsl_vector * x,\n const void * vtrust_state, void * vstate);\n int (*rcond) (double * rcond, const gsl_matrix * JTJ, void * vstate);\n int (*covar) (const gsl_matrix * JTJ, gsl_matrix * covar, void * vstate);\n void (*free) (void * vstate);\n} gsl_multilarge_nlinear_solver;\n\n/* tunable parameters */\ntypedef struct\n{\n const gsl_multilarge_nlinear_trs *trs; /* trust region subproblem method */\n const gsl_multilarge_nlinear_scale *scale; /* scaling method */\n const gsl_multilarge_nlinear_solver *solver; /* solver method */\n gsl_multilarge_nlinear_fdtype fdtype; /* finite difference method */\n double factor_up; /* factor for increasing trust radius */\n double factor_down; /* factor for decreasing trust radius */\n double avmax; /* max allowed |a|/|v| */\n double h_df; /* step size for finite difference Jacobian */\n double h_fvv; /* step size for finite difference fvv */\n size_t max_iter; /* maximum iterations for trs method */\n double tol; /* tolerance for solving trs */\n} gsl_multilarge_nlinear_parameters;\n\ntypedef struct\n{\n const char *name;\n void * (*alloc) (const gsl_multilarge_nlinear_parameters * params,\n const size_t n, const size_t p);\n int (*init) (void * state, const gsl_vector * wts,\n gsl_multilarge_nlinear_fdf * fdf, const gsl_vector * x,\n gsl_vector * f, gsl_vector * g, gsl_matrix * JTJ);\n int (*iterate) (void * state, const gsl_vector * wts,\n gsl_multilarge_nlinear_fdf * fdf, gsl_vector * x,\n gsl_vector * f, gsl_vector * g, gsl_matrix * JTJ,\n gsl_vector * dx);\n int (*rcond) (double * rcond, const gsl_matrix * JTJ, void * state);\n int (*covar) (const gsl_matrix * JTJ, gsl_matrix * covar, void * state);\n double (*avratio) (void * state);\n void (*free) (void * state);\n} gsl_multilarge_nlinear_type;\n\n/* current state passed to low-level trust region algorithms */\ntypedef struct\n{\n const gsl_vector * x; /* parameter values x */\n const gsl_vector * f; /* residual vector f(x) */\n const gsl_vector * g; /* gradient J^T f */\n const gsl_matrix * JTJ; /* matrix J^T J */\n const gsl_vector * diag; /* scaling matrix D */\n const gsl_vector * sqrt_wts; /* sqrt(diag(W)) or NULL for unweighted */\n const double *mu; /* LM parameter */\n const gsl_multilarge_nlinear_parameters * params;\n void *solver_state; /* workspace for direct least squares solver */\n gsl_multilarge_nlinear_fdf * fdf;\n double *avratio; /* |a| / |v| */\n} gsl_multilarge_nlinear_trust_state;\n\ntypedef struct\n{\n const gsl_multilarge_nlinear_type * type;\n gsl_multilarge_nlinear_fdf * fdf ;\n gsl_vector * x; /* parameter values x */\n gsl_vector * f; /* residual vector f(x) */\n gsl_vector * dx; /* step dx */\n gsl_vector * g; /* gradient J^T f */\n gsl_matrix * JTJ; /* matrix J^T J */\n gsl_vector * sqrt_wts_work; /* sqrt(W) */\n gsl_vector * sqrt_wts; /* ptr to sqrt_wts_work, or NULL if not using weights */\n size_t n; /* number of residuals */\n size_t p; /* number of parameters */\n size_t niter; /* number of iterations performed */\n gsl_multilarge_nlinear_parameters params;\n void *state;\n} gsl_multilarge_nlinear_workspace;\n\nGSL_FUN gsl_multilarge_nlinear_workspace *\ngsl_multilarge_nlinear_alloc (const gsl_multilarge_nlinear_type * T,\n const gsl_multilarge_nlinear_parameters * params,\n size_t n, size_t p);\n\nGSL_FUN void gsl_multilarge_nlinear_free (gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN gsl_multilarge_nlinear_parameters gsl_multilarge_nlinear_default_parameters(void);\n\nGSL_FUN int\ngsl_multilarge_nlinear_init (const gsl_vector * x,\n gsl_multilarge_nlinear_fdf * fdf,\n gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN int gsl_multilarge_nlinear_winit (const gsl_vector * x,\n const gsl_vector * wts,\n gsl_multilarge_nlinear_fdf * fdf,\n gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN int\ngsl_multilarge_nlinear_iterate (gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN double\ngsl_multilarge_nlinear_avratio (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN int\ngsl_multilarge_nlinear_rcond (double * rcond, const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN int\ngsl_multilarge_nlinear_covar (gsl_matrix * covar, gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN int\ngsl_multilarge_nlinear_driver (const size_t maxiter,\n const double xtol,\n const double gtol,\n const double ftol,\n void (*callback)(const size_t iter, void *params,\n const gsl_multilarge_nlinear_workspace *w),\n void *callback_params,\n int *info,\n gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN const char *\ngsl_multilarge_nlinear_name (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN gsl_vector *\ngsl_multilarge_nlinear_position (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN gsl_vector *\ngsl_multilarge_nlinear_residual (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN gsl_vector *\ngsl_multilarge_nlinear_step (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN size_t\ngsl_multilarge_nlinear_niter (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN const char *\ngsl_multilarge_nlinear_trs_name (const gsl_multilarge_nlinear_workspace * w);\n\nGSL_FUN int gsl_multilarge_nlinear_eval_f(gsl_multilarge_nlinear_fdf *fdf,\n const gsl_vector *x,\n const gsl_vector *swts,\n gsl_vector *y);\n\nGSL_FUN int\ngsl_multilarge_nlinear_eval_df(const CBLAS_TRANSPOSE_t TransJ,\n const gsl_vector *x,\n const gsl_vector *f,\n const gsl_vector *u,\n const gsl_vector *swts,\n const double h,\n const gsl_multilarge_nlinear_fdtype fdtype,\n gsl_multilarge_nlinear_fdf *fdf,\n gsl_vector *v,\n gsl_matrix *JTJ,\n gsl_vector *work);\n\nGSL_FUN int\ngsl_multilarge_nlinear_eval_fvv(const double h,\n const gsl_vector *x,\n const gsl_vector *v,\n const gsl_vector *f,\n const gsl_vector *swts,\n gsl_multilarge_nlinear_fdf *fdf,\n gsl_vector *yvv,\n gsl_vector *work);\n\n/* convergence.c */\nGSL_FUN int\ngsl_multilarge_nlinear_test (const double xtol, const double gtol,\n const double ftol, int *info,\n const gsl_multilarge_nlinear_workspace * w);\n\n/* fdjac.c */\nGSL_FUN int\ngsl_multilarge_nlinear_df(const double h, const gsl_multilarge_nlinear_fdtype fdtype,\n const gsl_vector *x, const gsl_vector *wts,\n gsl_multilarge_nlinear_fdf *fdf,\n const gsl_vector *f, gsl_matrix *J, gsl_vector *work);\n\n/* fdfvv.c */\nGSL_FUN int\ngsl_multilarge_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_multilarge_nlinear_fdf *fdf,\n gsl_vector *fvv, gsl_vector *work);\n\n/* top-level algorithms */\nGSL_VAR const gsl_multilarge_nlinear_type * gsl_multilarge_nlinear_trust;\n\n/* trust region subproblem methods */\nGSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_lm;\nGSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_lmaccel;\nGSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_dogleg;\nGSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_ddogleg;\nGSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_subspace2D;\nGSL_VAR const gsl_multilarge_nlinear_trs * gsl_multilarge_nlinear_trs_cgst;\n\n/* scaling matrix strategies */\nGSL_VAR const gsl_multilarge_nlinear_scale * gsl_multilarge_nlinear_scale_levenberg;\nGSL_VAR const gsl_multilarge_nlinear_scale * gsl_multilarge_nlinear_scale_marquardt;\nGSL_VAR const gsl_multilarge_nlinear_scale * gsl_multilarge_nlinear_scale_more;\n\n/* linear solvers */\nGSL_VAR const gsl_multilarge_nlinear_solver * gsl_multilarge_nlinear_solver_cholesky;\nGSL_VAR const gsl_multilarge_nlinear_solver * gsl_multilarge_nlinear_solver_mcholesky;\nGSL_VAR const gsl_multilarge_nlinear_solver * gsl_multilarge_nlinear_solver_none;\n\n__END_DECLS\n\n#endif /* __GSL_MULTILARGE_NLINEAR_H__ */\n", "meta": {"hexsha": "bdad1b23885bccd94352aff2f81263dc7cc4c85c", "size": 13486, "ext": "h", "lang": "C", "max_stars_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_multilarge_nlinear.h", "max_stars_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_stars_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-28T08:20:20.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-28T08:20:20.000Z", "max_issues_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_multilarge_nlinear.h", "max_issues_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_issues_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Chimera/3rd_Party/GSL_MSVC/gsl/gsl_multilarge_nlinear.h", "max_forks_repo_name": "zzpwahaha/Chimera-Control-Trim", "max_forks_repo_head_hexsha": "df1bbf6bea0b87b8c7c9a99dce213fdc249118f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-14T12:45:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-14T12:45:35.000Z", "avg_line_length": 41.4953846154, "max_line_length": 93, "alphanum_fraction": 0.6509713777, "num_tokens": 3292, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141571, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2560875842757364}} {"text": "#include \n#include \n#include \"mex.h\"\n#include \"mx_blas.h\"\n\n\n/* Level 1 BLAS */\nvoid\nmx_swap(mxArray *mxx, mxArray *mxy)\n{\n const ptrdiff_t incx = 1;\n const ptrdiff_t incy = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n float *x = (float *)mxGetData(mxx);\n float *y = (float *)mxGetData(mxy);\n sswap(&n, x, &incx, y, &incy);\n\n } else if (mxIsDouble(mxx)) {\n double *x = (double *)mxGetData(mxx);\n double *y = (double *)mxGetData(mxy);\n dswap(&n, x, &incx, y, &incy);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return;\n} /* mx_swap() */\n\n\nvoid\nmx_scal(const double a, mxArray *mxx)\n{\n const ptrdiff_t incx = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n const float af = (const float)a;\n float *x = (float *)mxGetData(mxx);\n sscal(&n, &af, x, &incx);\n\n } else if (mxIsDouble(mxx)) {\n double *x = (double *)mxGetData(mxx);\n dscal(&n, &a, x, &incx);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return;\n} /* mx_scal() */\n\n\nvoid\nmx_copy(const mxArray *mxx, mxArray *mxy)\n{\n const ptrdiff_t incx = 1;\n const ptrdiff_t incy = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n float *y = (float *)mxGetData(mxy);\n const float *x = (const float *)mxGetData(mxx);\n scopy(&n, x, &incx, y, &incy);\n\n } else if (mxIsDouble(mxx)) {\n double *y = (double *)mxGetData(mxy);\n const double *x = (const double *)mxGetData(mxx);\n dcopy(&n, x, &incx, y, &incy);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return;\n} /* mx_copy() */\n\n\nvoid\nmx_axpy(const double a, const mxArray *mxx, mxArray *mxy)\n{\n const ptrdiff_t incx = 1;\n const ptrdiff_t incy = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n float *y = (float *)mxGetData(mxy);\n const float *x = (const float *)mxGetData(mxx);\n const float af = (const float)a;\n saxpy(&n, &af, x, &incx, y, &incy);\n\n } else if (mxIsDouble(mxx)) {\n double *y = (double *)mxGetData(mxy);\n const double *x = (const double *)mxGetData(mxx);\n daxpy(&n, &a, x, &incx, y, &incy);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return;\n} /* mx_axpy() */\n\n\ndouble\nmx_dot(const mxArray *mxx, const mxArray *mxy)\n{\n double p = -1.0;\n\n const ptrdiff_t incx = 1;\n const ptrdiff_t incy = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n const float *x = (const float *)mxGetData(mxx);\n const float *y = (const float *)mxGetData(mxy);\n p = (double)sdot(&n, x, &incx, y, &incy);\n\n } else if (mxIsDouble(mxx)) {\n const double *x = (const double *)mxGetData(mxx);\n const double *y = (const double *)mxGetData(mxy);\n p = ddot(&n, x, &incx, y, &incy);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return p;\n} /* mx_dot() */\n\n\ndouble\nmx_nrm2(const mxArray *mxx)\n{\n double p = -1.0;\n\n const ptrdiff_t incx = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n const float *x = (const float *)mxGetData(mxx);\n p = (double)snrm2(&n, x, &incx);\n\n } else if (mxIsDouble(mxx)) {\n const double *x = (const double *)mxGetData(mxx);\n p = dnrm2(&n, x, &incx);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return p;\n} /* mx_nrm2() */\n\n\ndouble\nmx_asum(const mxArray *mxx)\n{\n double p = -1.0;\n\n const ptrdiff_t incx = 1;\n const ptrdiff_t n = (const ptrdiff_t)mxGetNumberOfElements(mxx);\n\n if (mxIsSingle(mxx)) {\n const float *x = (const float *)mxGetData(mxx);\n p = (double)sasum(&n, x, &incx);\n\n } else if (mxIsDouble(mxx)) {\n const double *x = (const double *)mxGetData(mxx);\n p = dasum(&n, x, &incx);\n\n } else {\n mexErrMsgTxt(\"not implemented\");\n }\n\n return p;\n} /* mx_asum() */\n", "meta": {"hexsha": "f2d1d8a649b7f90d75db3dcbbc5716dbd4c67ee6", "size": 4178, "ext": "c", "lang": "C", "max_stars_repo_path": "src/utils/poisson_solver/mex/mx_blas.c", "max_stars_repo_name": "WeberLab/QSM.m", "max_stars_repo_head_hexsha": "f22dc40d81495b37438fbf66f86c9281f8326813", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-09-18T20:04:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-18T09:12:14.000Z", "max_issues_repo_path": "src/utils/poisson_solver/mex/mx_blas.c", "max_issues_repo_name": "n644t031/QSM.m", "max_issues_repo_head_hexsha": "f22dc40d81495b37438fbf66f86c9281f8326813", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/poisson_solver/mex/mx_blas.c", "max_forks_repo_name": "n644t031/QSM.m", "max_forks_repo_head_hexsha": "f22dc40d81495b37438fbf66f86c9281f8326813", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-05-06T20:41:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T11:14:24.000Z", "avg_line_length": 23.2111111111, "max_line_length": 68, "alphanum_fraction": 0.5682144567, "num_tokens": 1324, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.5, "lm_q1q2_score": 0.2558583023520827}} {"text": "/*\n * Copyright 2020 Makani Technologies LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef SIM_MATH_UTIL_H_\n#define SIM_MATH_UTIL_H_\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"common/c_math/util.h\"\n\n// Generates random numbers using a generator seeded by a string hash. This\n// facilitates binding of generators to simulator models.\n//\n// A static seed offset can be specified using SetSeedOffset, supporting\n// deterministic perturbation of the generators used by all models.\nclass NamedRandomNumberGenerator {\n public:\n explicit NamedRandomNumberGenerator(const std::string &name)\n : generator_(static_cast(std::hash{}(name)) +\n seed_offset_),\n normal_(0.0, 1.0),\n uniform_real_(0.0, 1.0),\n uniform_int32_(0, std::numeric_limits::max()) {}\n\n // Returns a random number drawn from a normal distribution with mean=0.0\n // and stddev=1.0.\n double GetNormal() { return normal_(generator_); }\n\n // Returns a random number drawn from a uniform distribution on [0.0, 1.0).\n double GetUniformReal() { return uniform_real_(generator_); }\n\n // Returns a random integer drawn from a uniform distribution on\n // [0, std::numeric_limits::max()].\n int32_t GetUniformInt32() { return uniform_int32_(generator_); }\n\n static void SetSeedOffset(uint32_t offset) { seed_offset_ = offset; }\n\n private:\n static uint32_t seed_offset_;\n\n // 32-bit Mersenne Twister generator.\n std::mt19937 generator_;\n\n std::normal_distribution normal_;\n std::uniform_real_distribution uniform_real_;\n std::uniform_int_distribution uniform_int32_;\n};\n\n// The hypergeometric function, {_2}F_1(a, b; c; z)\ndouble HyperGeom(double a, double b, double c, double z);\nuint32_t Factorial(uint32_t n);\n\n// The rising factorial, denoted by the Pochhammer symbol (q)_n, is\n// defined by:\n//\n// (q)_n = 1 if n == 0\n// q*(q+1)*...*(q+n-1) if n > 0\n//\n// Warning: The Pochhammer symbol can denote either rising or falling\n// factorial depending on context.\ndouble RisingFactorial(double q, int32_t n);\n\n// Computes the intersection point of two circles in a coordinate\n// system centered at the first circle and with the positive x-axis\n// along the line between the centers of the first and second circles.\n// For both the non-degenerate intersecting and single point\n// intersecting cases, this returns the intersection point with\n// non-negative y. For the identical center case, this returns the\n// point (r1, 0) where r1 is the radius of the first circle. For the\n// remaining non-intersecting case, this returns the point:\n//\n// ((d^2 + r1^2 - r2^2) / (2 * d), 0)\n//\n// For a derivation of the formulas used here, see:\n// http://mathworld.wolfram.com/Circle-CircleIntersection.html\n//\n// Args:\n// d: Distance, always positive, between circle centers.\n// r1: Radius of first circle.\n// r2: Radius of second circle.\n// x: Output pointer to x coordinate of intersection (i.e. the\n// distance along line between first and second circle).\n// y: Output pointer to y coordinate of intersection (i.e. the\n// perpendicular distance, always positive, from line connecting\n// circle centers).\n//\n// Returns:\n// True if the circles intersect.\nbool IntersectCircles(double d, double r1, double r2, double *x, double *y);\n\n// Finds the fractional index of a value x_i in a GSL vector x\n// assuming x is monotonically increasing.\ndouble gsl_interp_index(const gsl_vector *x, double x_i);\n\n// Performs a linear interpolation along a pair of GSL vectors. The\n// function to interpolate on is described by the input GSL vector x\n// and the output GSL vector y. Interp1 linearly interpolates to find\n// the value of y for input x_i. If opt is kInterpOptionDefault,\n// extrapolate linearly beyond the end of the vectors. If opt is\n// kInterpOptionSaturate, saturate the output value at the\n// ends of the output (y) vector.\n//\n// Warning: This currently assumes a monotonically increasing x.\ndouble gsl_interp1(const gsl_vector *x, const gsl_vector *y, double xi,\n InterpOption opt);\n\n// Linear interpolation along a pair of vectors and a matrix.\n//\n// The function to interpolate on is described by the input vectors x\n// and y and the output matrix z, with corresponding entries for its\n// value at each (x,y) input pair. Interp2 bilinearly interpolates to\n// find the value of z for inputs x_i and y_i. If opt is\n// kInterpOptionDefault, extrapolate linearly beyond the end of the\n// vectors. If opt is kInterpOptionSaturate, saturate the\n// output value at the edges of the output (z) matrix.\n//\n// Warning: This currently assumes a monotonically increasing x, y.\ndouble gsl_interp2(const gsl_vector *x, const gsl_vector *y,\n const gsl_matrix *z, double x_i, double y_i,\n InterpOption opt);\ndouble gsl_interp2_scaled(double s, double t, const gsl_matrix *z,\n InterpOption opt);\nvoid gsl_interp2_indices(double s, double t, int32_t size1, int32_t size2,\n InterpOption opt, int32_t *s0, int32_t *t0, double *ds,\n double *dt);\ndouble gsl_interp2_scaled_helper(const gsl_matrix *z, int32_t s0, int32_t t0,\n double ds, double dt);\n\n// Linear interpolation along a set of three vectors and a\n// three-dimensional matrix.\n//\n// The function to interpolate on is described by the input vectors x,\n// y, and z and the output matrix mat, with corresponding entries for\n// its value at each (x,y,z) input pair. Interp3 bilinearly\n// interpolates to find the value of mat for inputs x_i, y_i, and z_i.\n// If opt is kInterpOptionDefault, extrapolate linearly beyond the\n// end of the vectors. If opt is kInterpOptionSaturate,\n// saturate the output value at the edges of the output (mat) matrix.\n//\n// Warning: This currently assumes a monotonically increasing x, y, z.\ndouble gsl_interp3(const gsl_vector *x, const gsl_vector *y,\n const gsl_vector *z, const gsl_vector *mat, double x_i,\n double y_i, double z_i, InterpOption opt);\ndouble gsl_interp3_scaled(double u, double v, double w, const gsl_vector *z,\n int32_t size1, int32_t size2, int32_t size3,\n InterpOption opt);\nvoid gsl_interp3_indices(double u, double v, double w, int32_t size1,\n int32_t size2, int32_t size3, InterpOption opt,\n int32_t *indices, double *du, double *dv, double *dw);\ndouble gsl_interp3_scaled_helper(const gsl_vector *z, int32_t indices[],\n double du, double dv, double dw);\n\n#endif // SIM_MATH_UTIL_H_\n", "meta": {"hexsha": "8684c33bdb8e67fca410beea097ef0788c3ce9b0", "size": 7391, "ext": "h", "lang": "C", "max_stars_repo_path": "sim/math/util.h", "max_stars_repo_name": "leozz37/makani", "max_stars_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1178.0, "max_stars_repo_stars_event_min_datetime": "2020-09-10T17:15:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:59:35.000Z", "max_issues_repo_path": "sim/math/util.h", "max_issues_repo_name": "leozz37/makani", "max_issues_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-22T05:22:35.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-22T05:22:35.000Z", "max_forks_repo_path": "sim/math/util.h", "max_forks_repo_name": "leozz37/makani", "max_forks_repo_head_hexsha": "c94d5c2b600b98002f932e80a313a06b9285cc1b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T17:29:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:00:14.000Z", "avg_line_length": 42.2342857143, "max_line_length": 80, "alphanum_fraction": 0.7042348803, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.49609382947091957, "lm_q1q2_score": 0.2557958585425036}} {"text": "#include \n#include \n\n#ifdef HAS_MKL\n#include \n#else\n#include \n#endif\n\n#ifdef __SSE4_2__\n#include \n#endif\n\ntypedef double Real;\n\n\ninline void GetTotalTraction_(Real *TotalTraction, const Real *CauchyStressTensor,\n const Real *ElectricDisplacementx, int ndim) {\n if (ndim==3) {\n TotalTraction[0] = CauchyStressTensor[0];\n TotalTraction[1] = CauchyStressTensor[4];\n TotalTraction[2] = CauchyStressTensor[8];\n TotalTraction[3] = CauchyStressTensor[1];\n TotalTraction[4] = CauchyStressTensor[2];\n TotalTraction[5] = CauchyStressTensor[5];\n \n TotalTraction[6] = ElectricDisplacementx[0];\n TotalTraction[7] = ElectricDisplacementx[1];\n TotalTraction[8] = ElectricDisplacementx[2];\n }\n else if (ndim == 2) {\n TotalTraction[0] = CauchyStressTensor[0];\n TotalTraction[1] = CauchyStressTensor[3];\n TotalTraction[2] = CauchyStressTensor[1];\n \n TotalTraction[3] = ElectricDisplacementx[0];\n TotalTraction[4] = ElectricDisplacementx[1];\n }\n}\n\n\ninline void FillConstitutiveB_(Real *B, const Real* SpatialGradient,\n int ndim, int nvar, int rows, int cols) {\n int i = 0;\n\n if (ndim == 3) {\n\n for (; i\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"capsulethunk.h\"\r\n\r\n#define WITH_TCC\r\n\r\n#ifdef WITH_TCC\r\n#include \"tcc/libtcc.h\"\r\n#endif\r\n\r\n#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\r\n#include \r\n\r\n#ifdef _MSC_VER \r\n#\tdefine GSL_DLL\r\n#\tdefine WIN32\r\n#endif\r\n\r\n#ifdef WITH_GSL\r\n#include \r\n#include \r\n#else\r\n#include \"cspline.c\"\r\n#endif\r\n\r\n#include \"radar5.h\"\r\n\r\n#ifndef MIN\r\n#define MIN(a,b) (((a)>(b))?(b):(a))\r\n#endif \r\n#ifndef MAX\r\n#define MAX(a,b) (((a)>(b))?(a):(b))\r\n#endif\r\n\r\ntypedef void (*equ_c_t)(double *F, const double *Y, double X, double (*lag)(int, int, void*), void *ctx, void *params);\r\ntypedef double (*lag_c_t)(double X, const double *Y);\r\n\r\ntypedef struct\r\n{\r\n\tdouble *X,*Y;\r\n\tARGLAG_t ARGLAG;\r\n\tPHI_t PHI;\r\n\tdouble *RPAR;\r\n\tint *IPAR;\r\n\tdouble *PAST;\r\n\tint *IPAST, *NRDS;\r\n\tint lag_flag[10];\r\n\tint ipos[10];\r\n\tdouble alphas[10];\r\n} _lag_ctx;\r\n\r\ntypedef struct params_ params_t;\r\nstruct params_\r\n{\r\n\tPyObject_HEAD\r\n\t\r\n\tint full_output;\r\n\tint xpos;\r\n\tdouble *xvalues;\r\n\tint xvalues_len;\r\n\t\r\n\tdouble *array;\r\n\tunsigned int array_size;\r\n\tunsigned int array_pos;\r\n\tunsigned int array_incr;\r\n\t\r\n\t\r\n\tPyObject *py_fcn;\r\n\tequ_c_t c_fcn;\r\n\t\r\n\tPyObject *py_y0[10];\r\n\tdouble constant_y0[10];\r\n\tPyObject *py_lagfuns[10];\r\n\tlag_c_t c_lagfuns[10];\r\n\tdouble constant_lags[10];\r\n\tPyThreadState *_thread_save;\r\n\tint interactive;\r\n\tint fail;\r\n\tvoid *user_params;\r\n\t\r\n\tPyObject *py_rpar;\r\n\tPyObject *py_lag_callback;\r\n\r\n#if WITH_GSL\r\n\tgsl_interp_accel *spline_acc;\r\n\tgsl_spline **y0_spline;\r\n#else\r\n\tcspline_t *y0_spline;\r\n#endif\r\n\tdouble y0_t0;\r\n\t\r\n\t_lag_ctx *lag_ctx;\r\n\t\r\n\tparams_t *next, *prev;\r\n};\r\n\r\nstatic double _lag_c(int il, int ip, _lag_ctx *ctx)\r\n{\r\n\tint IL = il + 1, IP = ip + 1;\r\n\t\r\n\t/* Store the result of LAGR5 for a little speedup if a delay is used for more than one variable... */\r\n\tif(ctx->lag_flag[il] == 0)\r\n\t{\r\n\t\tlagr5_(&IL,ctx->X,ctx->Y,ctx->ARGLAG,ctx->PAST,&ctx->alphas[il],&ctx->ipos[il],ctx->RPAR,ctx->IPAR,ctx->PHI,ctx->IPAST,ctx->NRDS); \r\n\t\tctx->lag_flag[il] = 1;\r\n\t}\r\n\t\r\n\t/* Effective computation of the delayed value for this variable. */\r\n\treturn ylagr5_(&IP,&ctx->alphas[il],&ctx->ipos[il],ctx->PHI,ctx->RPAR,ctx->IPAR,ctx->PAST,ctx->IPAST,ctx->NRDS);\r\n}\r\n\r\nstatic PyObject *_lag_py(PyObject *self, PyObject *args)\r\n{\r\n\tint il, ip;\r\n\tparams_t *p = PyCapsule_GetPointer(self, NULL);\r\n\tPyArg_ParseTuple(args, \"ii\", &il, &ip);\r\n\treturn PyFloat_FromDouble(_lag_c(il, ip, p->lag_ctx));\r\n}\r\n\r\nstatic void FCN(int *N, double *X, double *Y, double *F, ARGLAG_t ARGLAG, PHI_t PHI, double *RPAR, int *IPAR, double *PAST,int *IPAST, int *NRDS)\r\n{\r\n\tint i, len;\r\n\tPyObject *seq;\r\n\tPyObject *ret;\r\n\tPyObject *y_array;\r\n\tnpy_intp dims[1] = {*N};\r\n\tparams_t *p = (params_t*)IPAR;\r\n\t_lag_ctx ctx = {X,Y,ARGLAG,PHI,RPAR,IPAR,PAST,IPAST,NRDS,{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}};\r\n\t\r\n\t/* If it's a C function then it's easy, just run it. */\r\n\tif(p->c_fcn)\r\n\t{\r\n\t\tp->c_fcn(F,Y,*X,(void*)_lag_c,&ctx,RPAR);\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tif(p->fail)\r\n\t\treturn;\r\n\t\r\n\t/* If it's a Python function, then we have to tell Python we're going to maybe modify things. */\r\n\tif(!p->interactive)\r\n\t{\r\n\t\tPyEval_RestoreThread(p->_thread_save);\r\n\t\tp->_thread_save = NULL;\r\n\t}\r\n\t\r\n\tp->lag_ctx = &ctx;\r\n\t\r\n\t/* Create an array from Y values */\r\n\ty_array = PyArray_SimpleNewFromData(1,dims,NPY_DOUBLE,Y);\r\n\t\t\r\n\t/* Call the function, with following signature : func(Y, X, lagfun, params if any) */\r\n\tif(p->py_rpar)\r\n\t\tret = PyObject_CallFunctionObjArgs(p->py_fcn, y_array, PyFloat_FromDouble(*X), p->py_lag_callback, p->py_rpar, NULL);\r\n\telse\r\n\t\tret = PyObject_CallFunctionObjArgs(p->py_fcn, y_array, PyFloat_FromDouble(*X), p->py_lag_callback, NULL);\r\n\t\r\n\tif(!ret)\r\n\t{\r\n\t\tPyErr_Print();\r\n\t\tPy_DECREF(y_array);\r\n\t\tif(!p->interactive) p->_thread_save = PyEval_SaveThread();\r\n\t\tp->fail = 1;\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tPy_DECREF(y_array);\r\n\t\r\n\tseq = PySequence_Fast(ret, \"Equation must return a sequence !\");\r\n\tif(!seq)\r\n\t{\r\n\t\tPyObject *a, *b, *c;\r\n\t\tdouble dy;\r\n\t\t\r\n\t\tPyErr_Fetch(&a, &b, &c);\r\n\t\tPyErr_Clear();\r\n\t\t\r\n\t\tdy = PyFloat_AsDouble(ret);\r\n\t\t\r\n\t\tif(!PyErr_Occurred() && *N == 1)\r\n\t\t{\r\n\t\t\tif(a) Py_DECREF(a);\r\n\t\t\tif(b) Py_DECREF(b);\r\n\t\t\tif(c) Py_DECREF(c);\r\n\t\t\tF[0] = dy;\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tPyErr_Restore(a, b, c);\r\n\t\t\tif(!p->interactive) p->_thread_save = PyEval_SaveThread();\r\n\t\t\tp->fail = 4;\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\t\r\n\tlen = PySequence_Size(ret);\r\n\t\r\n\tif(len != *N)\r\n\t{\r\n\t\tPySys_WriteStderr(\"Equation returned a sequence of wrong size (%d, expected %d)...\\n\",len,*N);\r\n\t\tPyErr_SetString(PyExc_RuntimeError, \"Equation function returned bad F(Y) length.\");\r\n\t\tp->fail = 5;\r\n\t\tif(!p->interactive) p->_thread_save = PyEval_SaveThread();\r\n\t\tPy_DECREF(ret);\r\n\t\treturn;\r\n\t}\r\n\t\r\n\t/* Give the output values to the integrator */\r\n\tfor(i = 0; i < *N; i++)\r\n\t{\r\n\t\tPyObject *item = PySequence_Fast_GET_ITEM(seq, i);\r\n\t\tF[i] = PyFloat_AsDouble(item);\r\n\t}\r\n\t\r\n\tPy_DECREF(seq); \r\n\t\r\ncleanup:\t\r\n\tPy_DECREF(ret);\r\n\t\r\n\tif(!p->interactive) p->_thread_save = PyEval_SaveThread();\r\n}\r\n\r\nstatic double PHI(int *I, double *X, double *RPAR, int *IPAR)\r\n{\r\n\tPyObject *ret;\r\n\tint i = *I - 1;\r\n\tparams_t *p = (params_t*)IPAR;\r\n\tPyObject *fun = p->py_y0[i];\r\n\tdouble y0;\r\n\t\r\n\tif(fun)\r\n\t{\t\r\n\t\tif(!p->interactive && p->_thread_save) {\r\n\t\t\tPyEval_RestoreThread(p->_thread_save);\r\n\t\t}\r\n\t\t\r\n\t\tret = PyObject_CallFunction(fun, \"d\", *X);\r\n\t\t\r\n\t\tif(!ret || PyErr_Occurred())\r\n\t\t{\r\n\t\t\tPyErr_Print();\r\n\t\t\tp->fail = 1;\r\n\t\t\tif(!p->interactive && p->_thread_save) p->_thread_save = PyEval_SaveThread();\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\ty0 = PyFloat_AsDouble(ret);\r\n\t\tif(PyErr_Occurred())\r\n\t\t{\r\n\t\t\tPyErr_Print();\r\n\t\t\tp->fail = 4;\r\n\t\t}\r\n\t\tPy_DECREF(ret);\r\n\t\t\r\n\t\tif(!p->interactive && p->_thread_save) p->_thread_save = PyEval_SaveThread();\r\n\t\treturn y0;\r\n\t}\r\n\telse if(p->y0_spline)\r\n\t{\r\n#ifdef WITH_GSL\r\n\t\treturn gsl_spline_eval (p->y0_spline[i], *X + p->y0_t0, p->spline_acc);\r\n#else\r\n\t\tdouble y = 0;\r\n\t\tcspline_eval(&p->y0_spline[i], *X + p->y0_t0, &y);\r\n\t\treturn y;\r\n#endif\r\n//\t\tfprintf(stderr,\"PHI(%g->%g)[%d]=%g\\n\",*X,*X+p->y0_t0,i,y);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn p->constant_y0[i];\r\n\t}\r\n}\r\n\r\nstatic double ARGLAG(int *IL, double *X, double *Y,double *RPAR, int *IPAR, PHI_t PHI, double *PAST, int *IPAST, int *NRDS)\r\n{\r\n\tPyObject *ret;\r\n int ilag = *IL-1;\r\n params_t *p = (params_t*)IPAR;\r\n PyObject *pyfun = p->py_lagfuns[ilag];\r\n\tlag_c_t cfun = p->c_lagfuns[ilag];\r\n\tdouble r;\r\n\t\r\n if(!pyfun)\r\n {\r\n if(!cfun)\r\n {\r\n return *X-p->constant_lags[ilag];\r\n }\r\n else\r\n {\r\n return cfun(*X,Y);\r\n }\r\n }\r\n else\r\n {\r\n if(!p->interactive && p->_thread_save) PyEval_RestoreThread(p->_thread_save);\r\n ret = PyObject_CallFunction(pyfun, \"dd\", *X, *Y);\r\n if(!ret || PyErr_Occurred())\r\n {\r\n PyErr_Print();\r\n }\r\n \r\n\t\tr = PyFloat_AsDouble(ret);\r\n Py_DECREF(ret);\r\n// fprintf(stderr,\"Lag %d: %p -> %f\\n\", ilag, fun, r);\r\n\tif(!p->interactive && p->_thread_save) p->_thread_save = PyEval_SaveThread();\r\n return r;\r\n }\r\n}\r\n\r\nstatic void JFCN(int *N, double *X, double *Y, double *DFY, int LDFY, ARGLAG_t ARGLAG, PHI_t PHI, double *RPAR, int *IPAR, double *PAST,int *IPAST, int *NRDS)\r\n{\r\n fprintf(stderr,\"JFCN\\n\");\r\n}\r\nstatic void JACLAG(int *N, double *X, double *Y, int *DFYL, ARGLAG_t ARGLAG, PHI_t PHI, int *IVE, int *IVC, int *IVL, double *RPAR, int *IPAR, double *PAST, int *IPAST, int *NRDS)\r\n{\r\n fprintf(stderr,\"JACLAG\\n\");\r\n}\r\n\r\n\r\nstatic void SOLOUT(int *NR, double *XOLD, double *X, double *HSOL, double *Y, double *CONT, int *LRC, int *N, double *RPAR, int *IPAR, int *IRTRN)\r\n{ \r\n int i;\r\n params_t *p = (params_t*)IPAR;\r\n\tdouble *ptr;\r\n\tdouble *new_array;\r\n\tdouble next_x;\r\n \r\n if(p->interactive)\r\n {\r\n if(PyErr_CheckSignals())\r\n {\r\n p->fail = 6;\r\n }\r\n }\r\n \r\n if(p->fail)\r\n {\r\n *IRTRN = -1;\r\n return;\r\n } \r\n \r\n// fprintf(stderr,\"h=%g, dx=%g\\n\",*HSOL,*X-*XOLD);\r\n// fprintf(stderr,\"SOLOUT %f %f / %p %d %d %d\\n\",*X,*Y, p->array,p->array_size,p->array_pos,p->array_incr);\r\n \r\n if(p->xvalues)\r\n { \r\n\t if(*NR == 1)\r\n\t {\r\n\t\t\tptr = p->array + p->array_pos * (*N+1);\r\n\t\t\tptr[0] = *X;\r\n\t\t\r\n\t\t\tfor(i = 0; i < *N; i++)\r\n\t\t\t{\r\n\t\t\t\tptr[i + 1] = Y[i]; \r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tp->array_pos += 1;\r\n\t\t\tp->xpos += 1;\r\n\t }\r\n\t \r\n\t next_x = p->xvalues[p->xpos];\r\n\t \r\n\t while(*X >= next_x && p->xpos < p->xvalues_len)\r\n\t {\r\n\t\t\tif(p->array_size == p->array_pos)\r\n\t\t\t{\r\n\t\t\t\tp->array_size += p->array_incr;\r\n\t\t\t// fprintf(stderr,\"realloc %d->%d (%i)\", p->array_size - p->array_incr, p->array_size , p->array_size*(*N+1)*sizeof(double));\r\n\t\t\t\tnew_array = PyMem_Realloc(p->array, p->array_size*(*N+1)*sizeof(double));\r\n\t\t\t\tif(new_array == NULL)\r\n\t\t\t\t{\r\n\t\t\t\t\tp->fail = 2;\r\n\t\t\t\t\t*IRTRN = -1;\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t// fprintf(stderr,\" -> %p\\n\", new_array);\r\n\t\t\t\tp->array = new_array;\r\n\t\t\t} \r\n\t\t\t\r\n\t\t\tptr = p->array + p->array_pos * (*N+1);\r\n\t\t\tptr[0] = next_x;\r\n\t\t\r\n\t\t\tfor(i = 1; i < *N + 1; i++)\r\n\t\t\t{\r\n\t\t\t\tptr[i] = contr5_(&i, N, &next_x, CONT, X, HSOL);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tp->array_pos += 1;\r\n\t\t\tp->xpos += 1;\r\n\t\t\tnext_x = p->xvalues[p->xpos];\r\n\t }\r\n }\r\n \r\n \r\n if(p->full_output)\r\n {\r\n\t\tif(p->array_size == p->array_pos)\r\n\t\t{\r\n\t\t\tp->array_size += p->array_incr;\r\n\t\t// fprintf(stderr,\"realloc %d->%d (%i)\", p->array_size - p->array_incr, p->array_size , p->array_size*(*N+1)*sizeof(double));\r\n\t\t\tnew_array = PyMem_Realloc(p->array, p->array_size*(*N+1)*sizeof(double));\r\n\t\t\tif(new_array == NULL)\r\n\t\t\t{\r\n\t\t\t\tp->fail = 2;\r\n\t\t\t\t*IRTRN = -1;\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t// fprintf(stderr,\" -> %p\\n\", new_array);\r\n\t\t\tp->array = new_array;\r\n\t\t}\t \r\n\t\t\t\r\n\t\tptr = p->array + p->array_pos * (*N+1);\r\n\t\tptr[0] = *X;\r\n\t\t\r\n\t\tfor(i = 0; i < *N; i++)\r\n\t\t{\r\n\t\t\tptr[i+1] = Y[i]; \r\n\t\t}\r\n\t\t\r\n\t\tp->array_pos += 1;\r\n }\r\n}\r\n\r\nvoid _tcc_error(void *opaque, const char *msg)\r\n{\r\n\tPyErr_SetString(PyExc_RuntimeError, msg);\r\n\t//PySys_WriteStderr(\"! %s\\n\", msg);\r\n}\r\n\r\n\r\n// radar5(equ,y0,xend,[rpar],grid=grid) \r\n\r\nstatic params_t *current_p = NULL;\r\n\r\nstatic PyMethodDef py_lag_def = {\"lag\", _lag_py, METH_VARARGS, \"Returns delayed values of variables inside right-hand-side function.\"};\r\n\r\nstatic PyObject *radar5_radar5(PyObject *self, PyObject *args,PyObject *keywds)\r\n{ \r\n\tPyObject *output_array = NULL;\r\n\tint verbose = 0;\r\n\tint NGRID = 200;\r\n\tdouble XEND = 100;\r\n\tint N = 0;\r\n int MXST = 4*16384;\r\n\tparams_t par;\r\n\tparams_t *p = ∥\r\n\tint *IPAR = (void*)p;\r\n\t\r\n\tdouble X = 0;\r\n\tdouble *Y = NULL;\r\n\r\n\tdouble H = 1e-6;\r\n\tdouble RTOL = 1e-6;\r\n\tdouble ATOL = RTOL;\r\n\tdouble ITOL = 0;\r\n\tint IJAC = 0;\r\n\tint MLJAC = N;\r\n\tint MUJAC = 0; // not needed\r\n\tint NLAGS = 0;\r\n\tint NJACL = 0;\r\n\tint IMAS = 0;\r\n\tint IOUT = verbose ? 1 : 3;\r\n\tdouble WORK[30];\r\n\tint IWORK[30];\r\n\tdouble *RPAR = NULL;\r\n\r\n\tint IDID = 0;\r\n\r\n\tint *IPAST = NULL;\r\n\tint DUMMY;\r\n\tint MLMAS = N;\r\n\tint MUMAS = 0; // not needed\r\n\t\r\n\tint RPAR_len = 0;\r\n\t\r\n\tdouble *GRID = NULL;\r\n\r\n\tint i;\r\n\t\r\n\tint prev_interactive;\r\n\t\r\n\tPyObject* rpar_obj=NULL;\r\n\tPyObject* lagvars_obj=NULL;\r\n\tPyObject* lagfuns_obj=NULL; \r\n\tPyObject* equ_obj=NULL;\r\n\tPyObject* y0_obj=NULL;\r\n\tPyObject* xend_obj=NULL;\r\n\t\r\n\t\r\n\tint full_output_flag = 0;\r\n\t\r\n\tPyObject *py_p = NULL;\r\n\t\r\n\tint len;\r\n\r\n#ifdef WITH_TCC\r\n\tTCCState *tcc = NULL;\r\n#endif\t\r\n\t\r\n\t/* Parse arguments */\r\n\tstatic char *kwlist[] = {\"equ\", \"y0\", \"xend\", \"rpar\", \"ngrid\", \"lagvars\", \"lags\", \"verbose\", \"mxst\", \"full_output\", \"rtol\", \"atol\", \"initial_stepsize\", NULL};\r\n\t\r\n\tmemset(p,0,sizeof(params_t));\r\n\t\r\n\tif (!PyArg_ParseTupleAndKeywords(args, keywds, \"OOO|OiOOiiifff\", kwlist, &equ_obj, &y0_obj, &xend_obj, &rpar_obj, &NGRID, &lagvars_obj, &lagfuns_obj, &verbose, &MXST,&full_output_flag,&RTOL,&ATOL,&H))\r\n\t\treturn NULL;\r\n \r\n\tif(verbose) PySys_WriteStderr(\"RADAR5 wrapper (verbose = %d)\\n\", verbose);\r\n\r\n\t\r\n\t/* SPECIFIED X VALUES OR XEND */\r\n\tif(xend_obj)\r\n\t{\r\n\t\tPyArrayObject *xvalues = (PyArrayObject*)PyArray_ContiguousFromAny(xend_obj, NPY_DOUBLE, 0, 1);\r\n\t\tif(xvalues == NULL)\r\n\t\t{\r\n\t\t\tPyErr_SetString(PyExc_ValueError, \"Cannot parse x values.\");\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\t\t\r\n\t\tp->full_output = full_output_flag;\t/* Full output only if specified... */\r\n\t\t\r\n\t\tif(PyArray_NDIM(xvalues) == 0)\t/* if a single value if given for X, force full output */\r\n\t\t{\r\n\t\t\tp->xvalues = NULL;\r\n\t\t\tp->full_output = 1;\r\n\t\t\tXEND = *(double*)PyArray_GETPTR1(xvalues, 0);\r\n\t\t\tif(verbose) PySys_WriteStderr(\"Full output up to X=%g (all points)\\n\", XEND);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tp->xvalues = (double*)PyArray_GETPTR1(xvalues, 0);\r\n\t\t\tp->xvalues_len = PyArray_DIM(xvalues, 0);\r\n\t\t\tp->xpos = 0;\r\n\t\t\tXEND = p->xvalues[p->xvalues_len - 1];\r\n\t\t\tif(verbose) PySys_WriteStderr(\"%s output up to X=%g (%d points)\\n\", p->full_output ? \"Full\" : \"User-specified\", XEND, p->xvalues_len);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/* LOADING INITIAL VALUES : */\r\n\t\r\n\tif(y0_obj)\r\n\t{\r\n\t\tPyObject *seq = PySequence_Fast(y0_obj, \"Initial values must be provided as a sequence.\");\r\n\t\tif(!seq)\r\n\t\t\treturn NULL;\r\n\t\tlen = PySequence_Size(y0_obj);\r\n\r\n\t\tif(len == 2)\r\n\t\t{\r\n\t\t\t/* It might be a tuple (time, values) */\r\n\t\t\tPyObject *time = PySequence_Fast_GET_ITEM(seq, 0);\r\n\t\t\tPyObject *values = PySequence_Fast_GET_ITEM(seq, 1);\r\n\t\t\t\r\n\t\t\t/* Check each of (time, values) is iterables. If it is, we suppose we can use them as array. */\r\n\t\t\tif(PySequence_Check(time) && PySequence_Check(values))\r\n\t\t\t{\r\n\t\t\t\tint y0_len;\r\n\t\t\t\t\r\n\t\t\t\tPyArrayObject *time_array = (PyArrayObject*)PyArray_ContiguousFromAny(time, NPY_DOUBLE, 1, 1);\r\n\t\t\t\tPyArrayObject *values_array = (PyArrayObject*)PyArray_ContiguousFromAny(values, NPY_DOUBLE, 1, 2);\r\n\t\t\t\t\r\n\t\t\t\t/* Account for format errors */\r\n\t\t\t\tif(!time_array || !values_array)\r\n\t\t\t\t{\r\n\t\t\t\t\tPyErr_Print();\r\n\t\t\t\t\treturn NULL;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\ty0_len = PyArray_DIM(time_array, 0);\t/* Get initial sequence length */\r\n\t\t\t\t\r\n\t\t\t\tif(PyArray_NDIM(values_array) == 1) N = 1;\r\n\t\t\t\telse N = PyArray_DIM(values_array, 1);\t/* Get system dimension from initial data */\r\n\t\t\t\t\r\n\t\t\t\tp->y0_t0 = *(double*)PyArray_GETPTR1(time_array, y0_len - 1);\t/* Get the final time of the initial sequence */\r\n\t\t\t\tif(verbose) PySys_WriteStderr(\"Initial values array as (time->%g, [i0:%d])\\n\", p->y0_t0, y0_len);\r\n#ifdef WITH_GSL\r\n\t\t\t\tp->y0_spline = (gsl_spline**)malloc(sizeof(void*) * N);\r\n#else\r\n\t\t\t\tp->y0_spline = (cspline_t*)malloc(sizeof(cspline_t) * N);\r\n#endif\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tfor(i = 0; i < N; i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tint j;\r\n#ifdef WITH_GSL\r\n\t\t\t\t\tgsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, y0_len);\r\n#else\r\n\t\t\t\t\tcspline_t *spline = &p->y0_spline[i];\r\n\t\t\t\t\tcspline_init(spline);\r\n\t\t\t\t\tcspline_alloc_xy(spline, y0_len);\r\n#endif\r\n\r\n\t\t\t\t\t/* Copy time data */\r\n\t\t\t\t\tmemcpy (spline->x, (double*)PyArray_DATA(time_array), y0_len * sizeof(double));\r\n\t\t\t\t\t\r\n\t\t\t\t\t/* Copy variable data */\r\n\t\t\t\t\tfor(j = 0; j < y0_len; j++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tspline->y[j] = *(double*)PyArray_GETPTR2(values_array, j, i);\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t/* Initialize interpolator */\r\n#ifdef WITH_GSL\t\t\t\t\t\r\n\t\t\t\t\tgsl_interp_init (spline->interp, spline->x, spline->y, y0_len);\r\n\t\t\t\t\tp->y0_spline[i] = spline;\r\n#else\r\n\t\t\t\t\tcspline_compute_nat (spline);\r\n#endif\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\tPy_DECREF(time_array);\r\n\t\t\t\tPy_DECREF(values_array);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if(len > 0 && PySequence_Check(PySequence_Fast_GET_ITEM(seq, 0)))\r\n\t\t{\r\n\t\t\tint y0_len;\r\n\t\t\t\r\n\t\t\t/* Looks like a 2D array : time data might be its first row. This is useful to \"continue\" an integration, because it's the integrator output format. */\r\n\t\t\tPyArrayObject *full_array = (PyArrayObject*)PyArray_ContiguousFromAny(y0_obj, NPY_DOUBLE, 2, 2);\r\n\t\t\tif(PyErr_Occurred())\r\n\t\t\t{\r\n\t\t\t\tPy_DECREF(seq);\r\n\t\t\t\tgoto cleanup;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ty0_len = PyArray_DIM(full_array, 0);\r\n\t\t\tN = PyArray_DIM(full_array, 1) - 1;\r\n\t\t\t\t\t\r\n\t\t\tp->y0_t0 = *(double*)PyArray_GETPTR2(full_array, y0_len - 1, 0);\r\n#ifdef WITH_GSL\r\n\t\t\tp->y0_spline = (gsl_spline**)malloc(sizeof(void*) * N);\r\n#else\r\n\t\t\tp->y0_spline = (cspline_t*)malloc(sizeof(cspline_t) * N);\r\n#endif\t\r\n\t\t\t\r\n\t\t\tif(verbose) PySys_WriteStderr(\"Initial values array as [time->%g, y0:%d]\\n\", p->y0_t0, y0_len);\r\n\t\t\t\t\r\n\t\t\tfor(i = 0; i < N; i++)\r\n\t\t\t{\r\n\t\t\t\tint j;\r\n#ifdef WITH_GSL\r\n\t\t\t\tgsl_spline *spline = gsl_spline_alloc(gsl_interp_cspline, y0_len);\r\n#else\r\n\t\t\t\tcspline_t *spline = &p->y0_spline[i];\r\n\t\t\t\tcspline_init(spline);\r\n\t\t\t\tcspline_alloc_xy(spline, y0_len);\r\n#endif\r\n\r\n\t\t\t\tfor(j = 0; j < y0_len; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tspline->x[j] = *(double*)PyArray_GETPTR2(full_array, j, 0);\r\n\t\t\t\t\tspline->y[j] = *(double*)PyArray_GETPTR2(full_array, j, i + 1);\r\n\t\t\t\t}\r\n\t\t\t\t\t\r\n#ifdef WITH_GSL\t\t\t\t\t\r\n\t\t\t\tgsl_interp_init (spline->interp, spline->x, spline->y, y0_len);\r\n\t\t\t\tp->y0_spline[i] = spline;\r\n#else\r\n\t\t\t\tcspline_compute_nat (spline);\r\n#endif\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tPy_DECREF(full_array);\r\n\t\t}\r\n\t\t\r\n\t\tif(!p->y0_spline)\r\n\t\t{\r\n\t\t\t/* Each variable is specified on its own. */\r\n\t\t\tfor (i = 0; i < len; i++)\r\n\t\t\t{\r\n\t\t\t\tPyObject *item = PySequence_Fast_GET_ITEM(seq, i);\r\n\t\t\t\t\r\n\t\t\t\t/* Check whether it's a Python function or a constant value. */\r\n\t\t\t\tif(PyCallable_Check(item))\r\n\t\t\t\t{\r\n\t\t\t\t\tp->py_y0[i] = item;\r\n\t\t\t\t\tif(verbose)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tPyObject *repr = PyObject_Repr(item);\r\n#if PY_MAJOR_VERSION >= 3\r\n\t\t\t\t\t\tPySys_WriteStderr(\"Initial value: y[%d](t<0) = %s\\n\", i, PyUnicode_AsUTF8(repr));\r\n#else\t\t\t\r\n\t\t\t\t\t\tPySys_WriteStderr(\"Initial value: y[%d](t<0) = %s\\n\", i, PyString_AsString(repr));\r\n#endif\r\n\t\t\t\t\t\tPy_DECREF(repr);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble y0 = PyFloat_AsDouble(item);\r\n\t\t\t\t\tif(PyErr_Occurred())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tPy_DECREF(seq);\r\n\t\t\t\t\t\tgoto cleanup;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tp->constant_y0[i] = y0;\r\n\t\t\t\t\tp->py_y0[i] = NULL;\r\n\t\t\t\t\tif(verbose) PySys_WriteStderr(\"Initial value: y[%d](t<0) = %g (constant)\\n\", i, y0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tN = len;\r\n\t\t}\r\n\t\t\r\n\t\tPy_DECREF(seq);\r\n\t}\r\n\t\r\n\tif(N == 0)\r\n\t{\r\n\t\tPyErr_SetString(PyExc_ValueError, \"Could not guess system dimension from initial values.\");\r\n\t\tgoto cleanup;\r\n\t}\r\n\t\r\n\tif(verbose) PySys_WriteStderr(\"System dimension: N = %d\\n\", N);\r\n\t\r\n\tY = (double*)malloc(N * sizeof(double));\r\n\tIPAST = (int*)malloc(N * sizeof(int));\r\n\r\n\t/* Set all integrator parameters to default values. */\r\n\tfor(i = 0; i < 30; i++)\r\n\t{\r\n\t\tWORK[i] = 0;\r\n\t\tIWORK[i] = 0;\r\n\t}\r\n\t\r\n\t/* Load system numerical parameters. */\r\n\tif(rpar_obj)\r\n\t{\r\n\t\tPyObject *seq = PySequence_Fast(rpar_obj, \"Constant parameters must be provided as a sequence.\");\r\n\t\tif(!seq) goto cleanup;\r\n\t\tRPAR_len = PySequence_Size(rpar_obj);\r\n\t\t\r\n\t\tRPAR = malloc(sizeof(double) * RPAR_len);\r\n\t\t\r\n\t\tfor (i = 0; i < RPAR_len; i++) {\r\n\t\t\tPyObject *item = PySequence_Fast_GET_ITEM(seq, i);\r\n\t\t\tRPAR[i] = PyFloat_AsDouble(item);\r\n\t\t\t\r\n\t\t\tif(verbose) PySys_WriteStderr(\"Constant parameter %d : %g\\n\", i,RPAR[i]);\r\n\t\t}\r\n\t\tPy_DECREF(seq); \r\n\t}\r\n \r\n\tif(lagvars_obj)\r\n\t{\r\n\t\tPyObject *seq = PySequence_Fast(lagvars_obj, \"Delayed variables must be provided as a sequence.\");\r\n\t\tif(!seq) goto cleanup;\r\n\t\tlen = PySequence_Size(lagvars_obj);\r\n\r\n\t\tfor (i = 0; i < len; i++) {\r\n\t\t\tPyObject *item = PySequence_Fast_GET_ITEM(seq, i);\r\n\t\t\tint lagparam = PyLong_AsLong(item);\r\n\t\t\t\r\n\t\t\tif(lagparam < 0 || lagparam >= N)\r\n\t\t\t{\r\n\t\t\t\tPyErr_SetString(PyExc_ValueError, \"Invalid lag parameter\");\r\n\t\t\t\tPy_DECREF(seq);\r\n\t\t\t\tgoto cleanup;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tIPAST[i]=lagparam+1;\r\n\t\t\t\r\n\t\t\tif(verbose) PySys_WriteStderr(\"Variable %d is delayed (#%d)\\n\", lagparam, i);\r\n\t\t}\r\n\t\t\r\n\t\tIWORK[14] = i; // number of dense solution (lags)\r\n\t\tPy_DECREF(seq); \r\n\t}\r\n\telse\r\n\t{\r\n\t\t/* By default, all variables are delayed */\r\n\t\tfor (i = 0; i < N; i++)\r\n\t\t{\r\n\t\t\tIPAST[i]=i+1;\r\n\t\t}\r\n\t\tIWORK[14] = N;\r\n\t\tif(verbose) PySys_WriteStderr(\"Delayed variables unspecified: by default all %d variables are selected.\\n\", N);\r\n\t}\r\n\t\r\n\t\t\t\r\n\tif(lagfuns_obj)\r\n\t{\r\n\t\tPyObject *seq = PySequence_Fast(lagfuns_obj, \"Lags must be provided as a sequence.\");\r\n\t\tif(!seq) goto cleanup;\r\n\t\tlen = PySequence_Size(lagfuns_obj);\r\n\r\n\t\tfor (i = 0; i < len; i++) {\r\n\t\t\tPyObject *item = PySequence_Fast_GET_ITEM(seq, i);\r\n\t\t\t\r\n\t\t\tif(PyCallable_Check(item))\r\n\t\t\t{\r\n\t\t\t\tp->py_lagfuns[i]=item;\r\n\t\t\t\tp->c_lagfuns[i]=NULL;\r\n\t\t\t\t\r\n\t\t\t\tif(verbose)\r\n\t\t\t\t{\r\n\t\t\t\t\tPyObject *repr = PyObject_Repr(item);\r\n#if PY_MAJOR_VERSION >= 3\r\n\t\t\t\t\tPySys_WriteStderr(\"Lag %d is a Python function: %s\\n\", i, PyUnicode_AsUTF8(repr));\r\n#else\t\t\t\r\n\t\t\t\t\tPySys_WriteStderr(\"Lag %d is a Python function: %s\\n\", i, PyString_AsString(repr));\r\n#endif\r\n\t\t\t\t\tPy_DECREF(repr);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if(PyNumber_Check(item))\r\n\t\t\t{\r\n\t\t\t\tdouble delay = PyFloat_AsDouble(item);\r\n\t\t\t\tp->constant_lags[i]=delay;\r\n\t\t\t\tp->py_lagfuns[i]=NULL;\r\n\t\t\t\tp->c_lagfuns[i]=NULL;\r\n\t\t\t\tif(verbose) PySys_WriteStderr(\"Lag %d is constant: %g\\n\", i, delay);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tp->c_lagfuns[i]=PyCapsule_GetPointer(item, NULL);\r\n\t\t\t\tp->py_lagfuns[i]=NULL;\r\n\t\t\t\tif(verbose) PySys_WriteStderr(\"Lag %d is a raw C function: %p\\n\", i, p->c_lagfuns[i]);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tPy_DECREF(seq); \r\n\t}\r\n\t\r\n\t/* Set RHS function, either Python or C. */\r\n\tif(PyCallable_Check(equ_obj))\r\n\t{\r\n\t\tp->py_fcn = equ_obj;\r\n\t\tp->c_fcn = NULL;\r\n\t\t\r\n\t\tif(verbose)\r\n\t\t{\r\n\t\t\tPyObject *repr = PyObject_Repr(equ_obj);\r\n#if PY_MAJOR_VERSION >= 3\r\n\t\t\tPySys_WriteStderr(\"Equation is a Python function: %s\\n\", PyUnicode_AsUTF8(repr));\r\n#else\t\t\t\r\n\t\t\tPySys_WriteStderr(\"Equation is a Python function: %s\\n\", PyString_AsString(repr));\r\n#endif\r\n\t\t\tPy_DECREF(repr);\r\n\t\t}\r\n\t\t\r\n\t\t/* Create a Python wrapper for the function that will be used to get delayed values in RHS */\r\n\t\tpy_p = PyCapsule_New(p, NULL, NULL);\r\n\t\tp->py_lag_callback = PyCFunction_New(&py_lag_def, py_p);\r\n\t\t\r\n\t\t/* We need a Python version of RPAR */\r\n\t\tif(RPAR_len > 0)\r\n\t\t{\r\n\t\t\tnpy_intp dims[1] = {RPAR_len};\r\n\t\t\tp->py_rpar = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, RPAR);\r\n\t\t}\r\n\t}\r\n#if PY_MAJOR_VERSION >= 3\t\r\n\telse if(PyUnicode_Check(equ_obj))\r\n\t{\r\n#ifdef WITH_TCC\t\t\r\n\t\tPyObject *str = PyUnicode_AsASCIIString(equ_obj);\r\n\t\tif(!str)\r\n\t\t\tgoto cleanup;\r\n#endif\r\n#else\r\n\telse if(PyString_Check(equ_obj))\r\n\t{\r\n\t\tPyObject *str = equ_obj;\r\n#endif\r\n#ifdef WITH_TCC\r\n\r\n\t\t/* We need to provide some math functions in order to do useful stuff. */\r\n\t\tconst struct\r\n\t\t{\r\n\t\t\tconst char *name;\r\n\t\t\tvoid *ptr;\r\n\t\t} symbols[] = {{\"cos\", cos},\t{\"sin\", sin},\t{\"tan\", tan},\r\n\t\t\t\t\t {\"acos\", acos},\t{\"asin\", asin},\t{\"atan\", atan},\r\n\t\t\t\t\t {\"log\", log},\t{\"pow\", pow},\t{\"log10\", log10},\r\n\t\t\t\t\t {\"cosh\", cosh},\t{\"sinh\", sinh},\t{\"tanh\", tanh}};\r\n\t\tconst int nsymbols = sizeof(symbols)/sizeof(symbols[0]);\r\n\t\tchar *source = malloc(PyBytes_Size(str) + nsymbols * 128 + 128);\r\n\t\t\r\n\t\t/* This one can be useful too. */\r\n\t\tint pos = sprintf(source, \"#define M_PI 3.14159265358979323846\\n\");\r\n\t\t\r\n\t\tfor(i = 0; i < nsymbols; i++)\r\n\t\t\tpos += sprintf(source + pos, \"double %s(double);\", symbols[i].name);\r\n\r\n\t\tsprintf(source + pos, \"\\n%s\", PyBytes_AsString(str));\r\n\t\t\r\n\t\tif(verbose) PySys_WriteStderr(\"Equation is C code, try to compile it...\\n\");\r\n\t\t\r\n\t\t/* Create a minimal TCC context */\r\n\t\ttcc = tcc_new();\r\n\t\ttcc_set_options(tcc, \"-nostdlib\");\r\n\t\ttcc_set_error_func(tcc, NULL, _tcc_error);\r\n\t\ttcc_set_output_type(tcc, TCC_OUTPUT_MEMORY);\r\n\t\t\r\n\t\t/* Compile the code snippet */\r\n\t\tif(tcc_compile_string(tcc, source) < 0)\r\n\t\t{\r\n\t\t\tfree(source);\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\t\t\r\n\t\t//Py_DECREF(str);\r\n\t\tfree(source);\r\n\t\t\r\n\t\t/* Add math symbols for the linking step. */\r\n\t\tfor(i = 0; i < nsymbols; i++)\r\n\t\t\ttcc_add_symbol(tcc, symbols[i].name, symbols[i].ptr);\r\n\t\t\r\n\t\t/* Linking */\r\n\t\tif(tcc_relocate(tcc, TCC_RELOCATE_AUTO) < 0)\r\n\t\t{\r\n// \t\t\tPyErr_SetString(PyExc_RuntimeError, \"Equation could not be compiled (relocation error).\");\r\n\t\t\tgoto cleanup;\r\n\t\t}\r\n\t\t\r\n\t\tp->py_fcn = NULL;\r\n\t\tp->c_fcn = tcc_get_symbol(tcc, \"equation\");\t\t/* Get pointer to the compiled function */\r\n\t\t\r\n\t\tif(!p->c_fcn)\r\n\t\t{\r\n\t\t\tp->c_fcn = tcc_get_symbol(tcc, \"y\");\r\n\t\t\tif(!p->c_fcn)\r\n\t\t\t{\r\n\t\t\t\tp->c_fcn = tcc_get_symbol(tcc, \"rhs\");\r\n\t\t\t\tif(!p->c_fcn)\r\n\t\t\t\t{\r\n\t\t\t\t\tPyErr_SetString(PyExc_ValueError, \"No function named 'equation', 'y' or 'rhs' in provided C code.\");\r\n\t\t\t\t\tgoto cleanup;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(verbose) PySys_WriteStderr(\"Equation successfully compiled : %p\\n\", p->c_fcn);\r\n#else\r\n\t\tPyErr_SetString(PyExc_RuntimeError, \"Equation provided as string, but we were compiled without TCC.\");\r\n\t\tgoto cleanup;\r\n#endif\r\n\t}\r\n\telse\r\n\t{\r\n\t\tp->py_fcn = NULL;\r\n\t\tp->c_fcn = PyCapsule_GetPointer(equ_obj, NULL);\r\n\t\tif(verbose) PySys_WriteStderr(\"Equation is a raw C function: %p\\n\", p->c_fcn);\r\n\t}\r\n\t\r\n\tGRID = malloc(sizeof(double) * (NGRID + 1));\r\n\t\t\t\r\n\t\r\n\tif(p->xvalues)\r\n\t{\r\n\t\tp->array_size = p->xvalues_len;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tp->array_size = NGRID; // taille initiale\r\n\t}\r\n\t\r\n\tp->array = PyMem_Malloc(p->array_size*(N+1)*sizeof(double));\r\n\tif(verbose) PySys_WriteStderr(\"Allocate initial array (size %gkB) at %p\\n\", p->array_size*(N+1.)*sizeof(double)/1024, p->array);\r\n\t\r\n\tp->array_pos = 0;\r\n\tp->array_incr = p->array_size / 4; // increment taille\r\n\t\r\n\tp->user_params = RPAR;\r\n \r\n\tp->fail = 0;\r\n\tp->interactive = 0;\r\n\t\r\n\tIWORK[13] = 1; // ne pas utiliser JACLAG\r\n\t\r\n\t/* NOTE: Black magic... */\r\n\tIWORK[12] = NGRID; // WORKSPACE FOR GRID\r\n\t\r\n//\tMXST = 1024*1024*32; //4*16384*IWORK[14]; //MAX(NGRID*IWORK[14],8192); // pourquoi c'était divisé par /N ?\r\n\tIWORK[11] = MXST; // WORKSPACE FOR PAST \r\n\t\r\n\tIWORK[1] = INT_MAX;\r\n\t\r\n\tfor(i = 0; i < NGRID; i++)\r\n\t{\r\n\t\tGRID[i] = XEND/(NGRID+1)*i;\r\n\t} \r\n \r\n /* Load initial values */\r\n\tprev_interactive = p->interactive;\r\n\tp->interactive = 1;\r\n\tfor(i=1;iinteractive = prev_interactive;\r\n\t\r\n \r\n\t/* MAIN CALL TO THE INTEGRATOR AHEAD */\r\n\t\r\n\tif(!p->interactive)\r\n\t{\r\n\t\tp->_thread_save = PyEval_SaveThread();\t/* Promise Python that we are not going to mess with any of its data. */\r\n\t\t\t\t\t\t\t/* This allows other threads/event loops to run during the integration. */\r\n\t}\r\n\r\n\tcurrent_p = p;\r\n\t\r\n\tradar5_(&N,FCN,PHI,ARGLAG,&X,Y,&XEND,&H, \\\r\n\t\t\t\t\t&RTOL,&ATOL,&ITOL, \\\r\n\t\t\t\t\tJFCN,&IJAC,&MLJAC,&MUJAC, \\\r\n\t\t\t\t\tJACLAG,&NLAGS,&NJACL, \\\r\n\t\t\t\t\t&IMAS,SOLOUT,&IOUT, \\\r\n\t\t\t\t\tWORK,IWORK,RPAR,IPAR,&IDID, \\\r\n\t\t\t\t\tGRID,IPAST,&DUMMY,&MLMAS,&MUMAS);\r\n\r\n\tcurrent_p = NULL;\r\n\t\r\n\tif(!p->interactive)\r\n\t{\r\n\t\tPyEval_RestoreThread(p->_thread_save);\r\n\t}\r\n\t\r\n\t/* DONE ! */\r\n\t\r\n\tif(verbose)\r\n\t{\r\n\t\tswitch(p->fail)\r\n\t\t{\r\n\t\t\tcase 1: PySys_WriteStderr(\"Python function produced an error.\\n\"); break;\r\n\t\t\tcase 3: PySys_WriteStderr(\"Computation halted by stop().\\n\"); break;\r\n\t\t\tcase 4: \r\n\t\t\tcase 5: PySys_WriteStderr(\"Python function provided wrong return type.\\n\"); break;\r\n\t\t\tcase 6: PySys_WriteStderr(\"Computation halted by an external signal.\\n\"); break;\r\n\t\t}\r\n\t}\r\n\t\r\n\tif(p->fail == 2)\r\n\t{\r\n\t\tPyErr_SetString(PyExc_MemoryError, \"Cannot grow output array.\");\r\n\t}\r\n\t\r\n\tif(verbose)\r\n\t{\r\n\t\tPySys_WriteStderr(\"Solver output: IDID = %d (\", IDID);\r\n\t\tswitch(IDID)\r\n\t\t{\r\n\t\t\tcase 1: PySys_WriteStderr(\"Successful computation\"); break;\r\n\t\t\tcase 2: PySys_WriteStderr(\"Successful computation interrupted by routine SOLOUT\"); break;\r\n\t\t\tcase -1: PySys_WriteStderr(\"Non-consistent input values\"); break;\r\n\t\t\tcase -2: PySys_WriteStderr(\"Too many stepsizes required (>NMAX)\"); break;\r\n\t\t\tcase -3: PySys_WriteStderr(\"Stepsize becomes too small\"); break;\r\n\t\t\tcase -4: PySys_WriteStderr(\"Jacobian matrix repeatedly singular\"); break;\r\n\t\t\tcase -5: PySys_WriteStderr(\"Computation interrupted by routine YLAGR5\"); break;\r\n\t\t\tcase -6: PySys_WriteStderr(\"The equation makes use of advanced arguments\"); break;\r\n\t\t\tdefault: PySys_WriteStderr(\"Unexpected return code\"); break;\r\n\t\t}\r\n\t\tPySys_WriteStderr(\")\\nComputed points: %d\\n\", p->array_pos);\r\n\t}\r\n\t\r\n\t/* Create numpy array based on integrator output : */\r\n\t{\r\n\t\tnpy_intp dims[2] = {p->array_pos, N+1};\r\n\t\toutput_array = PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE, p->array);\r\n\t}\r\n \r\n#if NPY_API_VERSION >= 9\r\n\tPyArray_ENABLEFLAGS((PyArrayObject*)output_array, NPY_ARRAY_OWNDATA);\r\n#else\r\n\t((PyArrayObject*)output_array)->flags |= NPY_OWNDATA;\r\n#endif\r\n \r\n\t\r\n\t/* CLEANUP : */\r\ncleanup:\r\n\r\n\tif(RPAR) free(RPAR);\r\n\tif(Y) free(Y);\r\n\tif(IPAST) free(IPAST);\r\n\tif(GRID) free(GRID);\r\n\t\r\n\tif(p->y0_spline)\r\n\t{\r\n\t\tif(verbose) PySys_WriteStderr(\"Clearing initial values...\\n\");\r\n\t\tfor(i = 0; i < N; i++)\r\n\t\t{\r\n#ifdef WITH_GSL\t\t\t\r\n\t\t\tif(p->y0_spline[i])\r\n\t\t\t\tgsl_spline_free(p->y0_spline[i]);\r\n#else\r\n\t\t\tcspline_free(&p->y0_spline[i]);\r\n#endif\r\n\t\t}\r\n\t\tfree(p->y0_spline);\r\n\t}\r\n\t\r\n#ifdef WITH_GSL\t\r\n\tif(p->spline_acc)\r\n\t{\r\n\t\tgsl_interp_accel_free (p->spline_acc);\r\n\t}\r\n#endif\r\n\t\r\n\tif(p->py_lag_callback)\r\n\t\tPy_DECREF(p->py_lag_callback);\r\n\t\r\n\tif(py_p)\r\n\t\tPy_DECREF(py_p);\r\n\t\r\n\tif(p->py_rpar)\r\n\t\tPy_DECREF(p->py_rpar);\r\n\t\r\n\tif(p->xvalues)\r\n\t\tPy_DECREF(p->xvalues);\r\n\t\r\n#ifdef WITH_TCC\r\n\tif(tcc)\r\n\t\ttcc_delete(tcc);\r\n#endif\t\t\r\n\r\n\treturn output_array;\r\n}\r\n\r\nstatic PyObject *radar5_stop(PyObject *self, PyObject *args)\r\n{ \r\n\tif(current_p)\r\n\t{\r\n\t\tcurrent_p->fail = 3;\r\n\t}\r\n\tPy_RETURN_NONE;\r\n}\r\n\r\n\r\nPyDoc_STRVAR(radar5_doc,\r\n\"Call the RADAR5 solver, which numerically solves delayed differential equations (DDE) using an implicit collocation Runge-Kutta method based on Radau nodes.\\n\"\r\n\"\\n\"\r\n\"Beware : some functionalities are not implemented yet :\\n\"\r\n\" - providing custom jacobians ;\\n\"\r\n\" - mass matrix ;\\n\"\r\n\" - lots of options...\\n\"\r\n\"\\n\"\r\n\"For more extensive details, see the documentation [1]_ of the original FORTRAN code, which is the work of Nicola Guglielmi and Ernst Hairer.\\n\"\r\n\"More details can be found on : http://www.unige.ch/~hairer/software.html\\n\"\r\n\"\\n\"\r\n\":param equation : callable, pointer to c function, or string\\n\"\r\n\" Right-hand side of the equation, computing the time derivatives.\\n\"\r\n\" It is fundamentally a function that takes three or four arguments:\\n\"\r\n\" * y[i], an array containing the current values:\\n\"\r\n\" * t, the current time;\\n\" \r\n\" * lag(i,j), a function that can be called compute delayed variable i with the lag j.\\n\"\r\n\" * params, an extra array of user-defined parameters\\n\\n\"\r\n\" This function can be a Python callable, but this can be quite slow when integrating large systems. For better performances, a pointer to a C function can be provided. This function can be loaded by ctypes, or be part of a C extension, etc. It must have the following signature:\\n\"\r\n\" void equation(double *dy, const double *y, double t, double (*lag)(int,int,void*), void* ctx, void *params)\\n\"\r\n\" The output derivatives should be written in dy, and the extra 'ctx' argument has to be provided as 'lag' third parameters.\\n\"\r\n\" For more convenience, a string containing C code can also be provided. It must contain a function called 'equation', 'equ', or 'rhs' with the same signature. It will be internally compiled using the 'tcc' compiler. Standard math function (sin, cos, ...) are made available in the global scope.\\n\"\r\n\"\\n\"\r\n\":param y0 : array, or tuple of arrays\\n\"\r\n\" Provides initial and past values. It can be either a constant, and in that case all t<0 values are the same. If non-constant past values are needed, they must be provided as a tuple (time, values). Missing points will be computed using a cubic spline interpolation. For a more precise control, a list of Python callable computing the past values for each variable can also be used. Finally, a single array can be used, and its first row will be considered as the time values. This is particularly useful for resuming integration from the output of another call.\\n\"\r\n\"\\n\"\r\n\":param time : array, or float\\n\"\r\n\" Specifies the points on which the result of the integration has to be stored. Note that this does not correspond to the integrating grid, as the solver uses an adaptative step. If a single number is provided, full output is turned on, and all output steps are stored.\\n\"\r\n\"\\n\"\r\n\":param params : array, optional\\n\"\r\n\" Extra parameters to be provided to the integrating function.\\n\"\r\n\"\\n\"\r\n\":param lagvars : array, optional\\n\"\r\n\" List of variables subjected to delay. If it is not specified, all variables are considered delayed variable. You can specifiy an empty list or tuple if no delayed variable are needed.\\n\"\r\n\"\\n\"\r\n\":param lags : array, optional\\n\"\r\n\" List of delays used in the equations. They can be either constant, or functions of the other variables or current time.\\n\"\r\n\"\\n\"\r\n\":param ngrid : int, optional\\n\"\r\n\" Changes the size of the internal grid. Might need some tuning if integration fails unexpectedly.\"\r\n\":param mxst : int, optional\\n\"\r\n\" Changes the size of the internal past storage. Might need some tuning if integration fails unexpectedly with 'MXST' related errors.\"\r\n\":param atol : float, optional\\n\"\r\n\" Changes the absolute tolerance (default is 1e-6)\\n\"\r\n\":param rtol : float, optional\\n\"\r\n\" Changes the relative tolerance (default is 1e-6)\\n\"\r\n\":param initial_stepsize : float, optional\\n\"\r\n\" Initial guess for the stepsize; for stiff equations with initial transient, H=1/(norm of F'); usually 1e-3 or 1e-5 is good. (default is 1e-6)\\n\" \r\n\":param verbose : bool, optional\\n\"\r\n\" Enable printing of troubleshooting informations.\"\r\n\":param full_output : bool, optional\\n\"\r\n\" Turns on the output of every integration step. This can make the output array much bigger than the specified times.\\n\"\r\n\"\\n\"\r\n\":return: The result of the integration, the first row of which being the \\\"time\\\" variable, and the latter the integrated components.\\n\"\r\n\"\\n\"\r\n\".. References :\\n\"\r\n\"[1] N. Guglielmi and E. Hairer, \\\"Users' Guide for the code RADAR5 - Version 2.1\\\", Technical Report, July 2005.\\n\"\r\n);\r\n\r\nstatic PyMethodDef Radar5Methods[] = {\r\n {\"radar5\", (PyCFunction)radar5_radar5, METH_VARARGS|METH_KEYWORDS, radar5_doc},\r\n {\"stop\", (PyCFunction)radar5_stop, METH_VARARGS, \"Stop running computation.\"},\r\n {NULL, NULL, 0, NULL} /* Sentinel */\r\n};\r\n\r\n\r\n#if PY_MAJOR_VERSION >= 3\r\n\r\nstatic struct PyModuleDef Radar5Def = {\r\n PyModuleDef_HEAD_INIT,\r\n \"radar5\",\r\n NULL,\r\n -1,\r\n\t\tRadar5Methods\r\n};\r\n\r\n#define INITERROR return NULL\r\n\r\n#else\r\n#define INITERROR return\r\n#endif\r\n\r\n#if PY_MAJOR_VERSION >= 3\r\nPyMODINIT_FUNC PyInit_radar5(void)\r\n{\r\n PyObject *module = PyModule_Create(&Radar5Def);\r\n#else\r\nPyMODINIT_FUNC initradar5(void)\r\n{\t\r\n PyObject *module = Py_InitModule(\"radar5\", Radar5Methods);\r\n#endif\r\n\r\n if (module == NULL)\r\n INITERROR;\r\n\t\r\n\timport_array();\r\n\r\n\t// TODO : add dummy integration WITH lag so integration without lag works properly...\r\n\t\r\n#if PY_MAJOR_VERSION >= 3\r\n return module;\r\n#endif\r\n}\r\n\r\n", "meta": {"hexsha": "8becc3acc80e9e2bc93a3a9e8cc53b29c5c8f2cb", "size": 34665, "ext": "c", "lang": "C", "max_stars_repo_path": "wrapper.c", "max_stars_repo_name": "GColom/pyradar5", "max_stars_repo_head_hexsha": "c2c30fa8c0afa8b7d0efdc19aacdadd1e1ef092d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-09-22T14:05:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T10:06:06.000Z", "max_issues_repo_path": "wrapper.c", "max_issues_repo_name": "thoduv/pyradar5", "max_issues_repo_head_hexsha": "c2c30fa8c0afa8b7d0efdc19aacdadd1e1ef092d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-06-06T13:49:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-08T21:46:00.000Z", "max_forks_repo_path": "wrapper.c", "max_forks_repo_name": "GColom/pyradar5", "max_forks_repo_head_hexsha": "c2c30fa8c0afa8b7d0efdc19aacdadd1e1ef092d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-27T10:14:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-27T10:14:46.000Z", "avg_line_length": 27.7987169206, "max_line_length": 570, "alphanum_fraction": 0.6197605654, "num_tokens": 10800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.542863297964157, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.2523780002644766}} {"text": "/*\n * Copyright (c) 2011-2018 The University of Tennessee and The University\n * of Tennessee Research Foundation. All rights\n * reserved.\n * Copyright (c) 2013 Inria. All rights reserved.\n *\n * @precisions normal z -> c d s\n *\n */\n\n#include \n#include \"dplasma.h\"\n#include \"dplasmatypes.h\"\n\n\nstatic int\ndplasma_zlascal_operator( parsec_execution_stream_t *es,\n const parsec_tiled_matrix_dc_t *descA,\n void *_A,\n PLASMA_enum uplo, int m, int n,\n void *args )\n{\n parsec_complex64_t *A = (parsec_complex64_t*)_A;\n parsec_complex64_t alpha = *((parsec_complex64_t*)args);\n int i;\n int tempmm, tempnn, ldam;\n (void)es;\n\n tempmm = ((m)==((descA->mt)-1)) ? ((descA->m)-(m*(descA->mb))) : (descA->mb);\n tempnn = ((n)==((descA->nt)-1)) ? ((descA->n)-(n*(descA->nb))) : (descA->nb);\n ldam = BLKLDD( descA, m );\n\n /* Overwrite uplo when outside the diagonal */\n if (m != n) {\n uplo = PlasmaUpperLower;\n }\n\n switch ( uplo ) {\n case PlasmaUpper:\n for(i=0; i\n#include\n#include \n#include \n#include \n\nvoid SGEMM_NT_MP(float *C, float *A, float *B, long\tM, long N, long K, \n\t\t\tlong LN, long LK, float *SB, long k_tag)\n{\n\tasm volatile(\n\t\t\".macro PACK_KERNEL5x4_BEGIN_K \t \\n\"\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq5, [x16], #16\t\t\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64] \t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x17, #128]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v0.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv13.4s, v1.4s, v5.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v2.4s, v5.4s\t\t \t \\n\"\n\t\t\"\tldr\t\tq4, [x15], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv15.4s, v3.4s, v5.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq6, [x17], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv16.4s, v4.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq7, [x18], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv17.4s, v0.4s, v6.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq8, [x19], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[0], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmul\tv18.4s, v1.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv19.4s, v2.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv20.4s, v3.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv21.4s, v4.4s, v6.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq10, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[1], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmul\tv22.4s, v0.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv23.4s, v1.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv24.4s, v2.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv25.4s, v3.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv26.4s, v4.4s, v7.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq11, [x13], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[2], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmul\tv27.4s, v0.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq0, [x14], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv28.4s, v1.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x15], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[3], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\t\t\"\tldr\t\tq5, [x16], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv29.4s, v2.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv30.4s, v3.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfmul\tv31.4s, v4.4s, v8.4s\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\n\t\t\".macro PACK_KERNEL5x4_K0 \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x16, #128]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq6, [x17], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v0.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v1.4s, v5.4s\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x17, #128]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq7, [x18], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v2.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v3.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv16.4s, v4.4s, v5.4s\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq8, [x19], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[0], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv17.4s, v0.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv18.4s, v1.4s, v6.4s\t\t \t \\n\"\n\t\t\"\tfmla\tv19.4s, v2.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv20.4s, v3.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v4.4s, v6.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq9, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[1], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v0.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v1.4s, v7.4s\t\t \t \\n\"\n\n\t\t\"\tldr\t\tq10, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[2], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v2.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v3.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv26.4s, v4.4s, v7.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq11, [x13], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[3], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv27.4s, v0.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq5, [x16], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq0, [x14], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv28.4s, v1.4s, v8.4s\t\t \t \\n\"\n\t\t\"\tldr\t\tq1, [x15], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv29.4s, v2.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv30.4s, v3.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v4.4s, v8.4s\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro PACK_KERNEL5x4_K1 \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x18, #128]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq6, [x17], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv12.4s, v9.4s, v5.4s \t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v10.4s, v5.4s\t\t \t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x19, #128]\t\t\t \\n\"\n\t\t\"\tldr\t\tq7, [x18], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv14.4s, v11.4s, v5.4s\t\t \t \\n\"\n\t\t\"\tfmla\tv15.4s, v0.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv16.4s, v1.4s, v5.4s\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x19], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[0], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv17.4s, v9.4s, v6.4s \t\t\t \\n\"\n\t\t\"\tfmla\tv18.4s, v10.4s, v6.4s\t\t \t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[1], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v6.4s\t\t \t \\n\"\n\t\t\"\tfmla\tv20.4s, v0.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v1.4s, v6.4s\t\t\t \\n\"\n\n\t\t\"\tprfm \tPLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv25.4s, v0.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv26.4s, v1.4s, v7.4s\t\t\t \\n\"\n\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[2], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v0.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v1.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v9.4s, v7.4s\t\t \t \\n\"\n\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[3], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\t\t\"\tldr\t\tq5, [x16], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv23.4s, v10.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv24.4s, v11.4s, v7.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq4, [x15], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv27.4s, v9.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv28.4s, v10.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v8.4s\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro PACK_KERNEL5x4_END_K \\n\"\n\n\t\t\"\tldr\t\tq6, [x17], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv12.4s, v9.4s, v5.4s \t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v10.4s, v5.4s\t\t \t \\n\"\n\n\t\t\"\tldr\t\tq7, [x18], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv14.4s, v11.4s, v5.4s\t\t \t \\n\"\n\t\t\"\tfmla\tv15.4s, v0.4s, v5.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv16.4s, v1.4s, v5.4s\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq8, [x19], #16\t\t\t\t\t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[0], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv17.4s, v9.4s, v6.4s \t\t\t \\n\"\n\t\t\"\tfaddp\tv12.4s, v12.4s, v17.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv18.4s, v10.4s, v6.4s\t\t \t \\n\"\n\t\t\"\tfaddp\tv13.4s, v13.4s, v18.4s\t\t\t \\n\"\n\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[1], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv19.4s, v11.4s, v6.4s\t\t \t \\n\"\n\t\t\"\tfaddp\tv14.4s, v14.4s, v19.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv20.4s, v0.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv15.4s, v15.4s, v20.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v1.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv16.4s, v16.4s, v21.4s\t\t\t \\n\"\n\n\t\t\"\tfmla\tv25.4s, v0.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv26.4s, v1.4s, v7.4s\t\t\t \\n\"\n\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[2], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v0.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv25.4s, v25.4s, v30.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v1.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv26.4s, v26.4s, v31.4s\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v9.4s, v7.4s\t\t \t \\n\"\n\t\t\"\tst4\t\t{v5.s, v6.s, v7.s, v8.s}[3], [x24]\t\t\\n\"\n\t\t\"\tadd\t\tx24, x24, x8, lsl #2\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v10.4s, v7.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv24.4s, v11.4s, v7.4s\t\t\t \\n\"\n\n\t\t\"\tfaddp\tv15.4s, v15.4s, v25.4s\t\t\t \\n\"\n\t\t\"\tfaddp \tv16.4s, v16.4s, v26.4s\t\t\t \\n\"\n\n\t\t\"\tfmla\tv27.4s, v9.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfaddp \tv22.4s, v22.4s, v27.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv28.4s, v10.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv23.4s, v23.4s, v28.4s\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v8.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv24.4s, v24.4s, v29.4s\t\t\t \\n\"\n\n\t\t\"\tfaddp\tv12.4s, v12.4s, v22.4s\t\t\t \\n\"\n\t\t\"\tfaddp\tv13.4s, v13.4s, v23.4s\t\t \t \\n\"\n\t\t\"\tfaddp\tv14.4s, v14.4s, v24.4s\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro\tPACKB_ADD_C \t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x25]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x26]\t\t\t\t\t\t \\n\"\n\n\t\t\"\tfadd \tv12.4s, v12.4s, v0.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq2, [x27]\t\t\t\t\t\t \\n\"\n\t\t\"\tfadd \tv13.4s, v13.4s, v1.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq3, [x28]\t\t\t\t\t\t \\n\"\n\t\t\"\tfadd \tv14.4s, v14.4s, v2.4s\t\t\t \\n\"\n\t\t\"\tldr\t\tq4, [x29]\t\t\t\t\t\t \\n\"\n\t\t\"\tfadd \tv15.4s, v15.4s, v3.4s\t\t\t \\n\"\n\t\t\"\tfadd \tv16.4s, v16.4s, v4.4s\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro SAVE5x4\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tsubs\tx7, x7, #1\t\t\t\t\t \t \\n\"\n\n\t\t\"\tstr\t\tq12, [x25], #16\t\t\t\t\t \\n\"\n\t\t\"\tstr\t\tq13, [x26], #16\t\t\t\t\t \\n\"\n\t\t\"\tstr\t\tq14, [x27], #16\t\t \t\t\t \\n\"\n\t\t\"\tstr\t\tq15, [x28], #16\t\t \t\t\t \\n\"\n\t\t\"\tstr\t\tq16, [x29], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro ADD_C\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x29, #64]\t\t\t \\n\"\n\n\t\t\"\tldp\t\tq0, q1, [x25]\t\t\t\t\t \\n\"\n\n\t\t\"\tfadd\tv12.4s, v12.4s, v0.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x25, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv13.4s, v13.4s, v1.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv22.4s, v2.4s, v22.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq4, q5, [x26]\t\t\t\t\t \\n\"\n\t\t\"\tfadd\tv23.4s, v3.4s, v23.4s\t\t \t \\n\"\n\n\t\t\"\tfadd\tv14.4s, v4.4s, v14.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq6, q7, [x26, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv15.4s, v5.4s, v15.4s\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x29, #64]\t\t\t \\n\"\n\n\t\t\"\tfadd\tv24.4s, v6.4s, v24.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tfadd \tv25.4s, v7.4s, v25.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv16.4s, v8.4s, v16.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x27, #32]\t\t\t \\n\"\n\t\t\"\tfadd\tv17.4s, v9.4s, v17.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv26.4s, v10.4s, v26.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq0, q1, [x28]\t\t\t\t \t \\n\"\n\t\t\"\tfadd\tv27.4s, v11.4s, v27.4s\t\t\t \\n\"\n\n\n\t\t\"\tfadd\tv18.4s, v0.4s, v18.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x28, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv19.4s, v1.4s, v19.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv28.4s, v2.4s, v28.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq4, q5, [x29]\t\t\t\t\t \\n\"\n\t\t\"\tfadd\tv29.4s, v3.4s, v29.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv20.4s, v4.4s, v20.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq6, q7, [x29, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv21.4s, v5.4s, v21.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv30.4s, v30.4s, v6.4s\t\t\t \\n\"\n\t\t\"\tfadd\tv31.4s, v31.4s, v7.4s\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro SAVE5x16\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tsubs\tx21, x21, #1\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\t\t\"\tstp\t\tq16, q17, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq18, q19, [x28]\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq20, q21, [x29]\t\t\t\t\t \\n\"\n\n//\t\t\"\tadd \tx10, x10, x9\t\t\t\t\t \\n\"\n\n\t\t\"\tadd \tx10, x10, x6, lsl #4\t\t\t \\n\"\n\t\t\"\tadd\t\tx10, x10, x6, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tstp\t\tq22, q23, [x25, #32]\t\t\t \\n\"\n\t\t\"\tadd\t\tx25, x29, x9, lsl #2\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq24, q25, [x26, #32]\t\t\t \\n\"\n\t\t\"\tadd\t\tx26, x29, x9, lsl #3\t\t\t \\n\"\n\t\t\"\tstp\t\tq26, q27, [x27, #32]\t\t\t \\n\"\n\t\t\"\tadd\t\tx27, x25, x9, lsl #3 \t\t\t \\n\"\n\t\t\"\tstp\t\tq28, q29, [x28, #32]\t\t\t \\n\"\n\t\t\"\tadd\t\tx28, x26, x9, lsl #3 \t\t\t \\n\"\n\t\t\"\tstp\t\tq30, q31, [x29, #32]\t\t\t \\n\"\n\t\t\"\tadd\t\tx29, x27, x9, lsl #3\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL5x16_BEGIN_K \t \t \\n\"\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64] \t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv16.4s, v8.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv17.4s, v9.4s, v2.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq4, [x15], #16\t\t\t\t \t \\n\"\n\n\t\t\"\tfmul\tv18.4s, v8.4s, v3.s[0]\t \\n\"\n\t\t\"\tfmul\tv19.4s, v9.4s, v3.s[0]\t \\n\"\n\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv20.4s, v8.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv21.4s, v9.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmul\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv24.4s, v10.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv25.4s, v11.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tfmul\tv26.4s, v10.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv27.4s, v11.4s, v2.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq5, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv28.4s, v10.4s, v3.s[0]\t \\n\"\n\t\t\"\tfmul\tv29.4s, v11.4s, v3.s[0]\t \\n\"\n\n\t\t\"\tfmul\tv30.4s, v10.4s, v4.s[0]\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv31.4s, v11.4s, v4.s[0]\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[0]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq5, [x11], #16\t\t\t\t\t \\n\" // \n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v3.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v4.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v4.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[1]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq6, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v4.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v4.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v4.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v4.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[2]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq7, [x13], #16\t\t\t\t\t \\n\" // \n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v4.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v4.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x15, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v4.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v4.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x15], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v4.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t \t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v4.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K4 \t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v5.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v5.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v6.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v6.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v7.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v7.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v5.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v5.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v6.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v6.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v7.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v7.s[0]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\" // \n\n\t\t\"\tfmla\tv28.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K5 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x14, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v5.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v5.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v6.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v6.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v7.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v7.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v5.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v5.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v6.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v6.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v7.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v7.s[1]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K6 \t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v5.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v5.s[2]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v6.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v6.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v7.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v7.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v5.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v5.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v6.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v6.s[2]\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v7.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v7.s[2]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq4, [x15], #16\t\t\t\t\t \\n\" // \n\n\t\t\"\tfmla\tv28.4s, v10.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL5x16_K7 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v5.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v5.s[3]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v6.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v6.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v7.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v7.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t \t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v5.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v5.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v6.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v6.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v7.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v7.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL5x16_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v5.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v5.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v6.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v6.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v7.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v7.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv30.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv31.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v5.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v5.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v6.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v6.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v7.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v7.s[3]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\n\t\t\".macro\tKERNEL4x16_BEGIN_K\t\t\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64] \t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv16.4s, v8.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv17.4s, v9.4s, v2.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv18.4s, v8.4s, v3.s[0]\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv19.4s, v9.4s, v3.s[0]\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmul\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv24.4s, v10.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv25.4s, v11.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tfmul\tv26.4s, v10.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv27.4s, v11.4s, v2.s[0]\t \\n\"\n\n//\t\t\"\tldr\t\tq5, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv28.4s, v10.4s, v3.s[0]\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv29.4s, v11.4s, v3.s[0]\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL4x16_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[0]\t\t\t \\n\"\n\n//\t\t\"\tldr\t\tq5, [x11], #16\t\t\t\t\t \\n\" // \n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL4x16_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[1]\t\t\t \\n\"\n\n//\t\t\"\tldr\t\tq6, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL4x16_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[2]\t\t\t \\n\"\n\n//\t\t\"\tldr\t\tq7, [x13], #16\t\t\t\t\t \\n\" // \n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL4x16_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x14, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t \t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL4x16_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v9.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv28.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv29.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tM4_ADD_C \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\n\t\t\"\tldp\t\tq0, q1, [x25]\t\t\t\t\t \\n\"\n\n\t\t\"\tfadd\tv12.4s, v12.4s, v0.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x25, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv13.4s, v13.4s, v1.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv22.4s, v2.4s, v22.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq4, q5, [x26]\t\t\t\t\t \\n\"\n\t\t\"\tfadd\tv23.4s, v3.4s, v23.4s\t\t \t \\n\"\n\n\t\t\"\tfadd\tv14.4s, v4.4s, v14.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq6, q7, [x26, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv15.4s, v5.4s, v15.4s\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\n\t\t\"\tfadd\tv24.4s, v6.4s, v24.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tfadd \tv25.4s, v7.4s, v25.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv16.4s, v8.4s, v16.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x27, #32]\t\t\t \\n\"\n\t\t\"\tfadd\tv17.4s, v9.4s, v17.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv26.4s, v10.4s, v26.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq0, q1, [x28]\t\t\t\t \t \\n\"\n\t\t\"\tfadd\tv27.4s, v11.4s, v27.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv18.4s, v0.4s, v18.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x28, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv19.4s, v1.4s, v19.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv28.4s, v2.4s, v28.4s\t\t\t \\n\"\n\t\t\"\tfadd\tv29.4s, v3.4s, v29.4s\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro SAVE4x16\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\t\t\"\tstp\t\tq16, q17, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq18, q19, [x28]\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq22, q23, [x25, #32]\t\t\t \\n\"\n\t\t\"\tstp\t\tq24, q25, [x26, #32]\t\t\t \\n\"\n\t\t\"\tstp\t\tq26, q27, [x27, #32]\t\t\t \\n\"\n\t\t\"\tstp\t\tq28, q29, [x28, #32]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tKERNEL3x16_BEGIN_K\t\t\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv16.4s, v8.4s, v2.s[0]\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv17.4s, v9.4s, v2.s[0]\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmul\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv24.4s, v10.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv25.4s, v11.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tfmul\tv26.4s, v10.4s, v2.s[0]\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv27.4s, v11.4s, v2.s[0]\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL3x16_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL3x16_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL3x16_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL3x16_K3 \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t \t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL3x16_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v9.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv26.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv27.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tM3_ADD_C \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\n\t\t\"\tldp\t\tq0, q1, [x25]\t\t\t\t\t \\n\"\n\n\t\t\"\tfadd\tv12.4s, v12.4s, v0.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x25, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv13.4s, v13.4s, v1.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv22.4s, v2.4s, v22.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq4, q5, [x26]\t\t\t\t\t \\n\"\n\t\t\"\tfadd\tv23.4s, v3.4s, v23.4s\t\t \t \\n\"\n\n\t\t\"\tfadd\tv14.4s, v4.4s, v14.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq6, q7, [x26, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv15.4s, v5.4s, v15.4s\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\n\t\t\"\tfadd\tv24.4s, v6.4s, v24.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tfadd \tv25.4s, v7.4s, v25.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv16.4s, v8.4s, v16.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x27, #32]\t\t\t \\n\"\n\t\t\"\tfadd\tv17.4s, v9.4s, v17.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv26.4s, v10.4s, v26.4s\t\t\t \\n\"\n\t\t\"\tfadd\tv27.4s, v11.4s, v27.4s\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro SAVE3x16\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\t\t\"\tstp\t\tq16, q17, [x27]\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq22, q23, [x25, #32]\t\t\t \\n\"\n\t\t\"\tstp\t\tq24, q25, [x26, #32]\t\t\t \\n\"\n\t\t\"\tstp\t\tq26, q27, [x27, #32]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tKERNEL2x16_BEGIN_K\t\t\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmul\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv24.4s, v10.4s, v1.s[0]\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv25.4s, v11.4s, v1.s[0]\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL2x16_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL2x16_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL2x16_K2 \t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL2x16_K3 \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t \t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL2x16_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v9.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv24.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv25.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tM2_ADD_C \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\n\t\t\"\tldp\t\tq0, q1, [x25]\t\t\t\t\t \\n\"\n\n\t\t\"\tfadd\tv12.4s, v12.4s, v0.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x25, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv13.4s, v13.4s, v1.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv22.4s, v2.4s, v22.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq4, q5, [x26]\t\t\t\t\t \\n\"\n\t\t\"\tfadd\tv23.4s, v3.4s, v23.4s\t\t \t \\n\"\n\n\t\t\"\tfadd\tv14.4s, v4.4s, v14.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq6, q7, [x26, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv15.4s, v5.4s, v15.4s\t\t\t \\n\"\n\n\n\t\t\"\tfadd\tv24.4s, v6.4s, v24.4s\t\t\t \\n\"\n\t\t\"\tfadd \tv25.4s, v7.4s, v25.4s\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro SAVE2x16\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\n\t\t\"\tstp\t\tq22, q23, [x25, #32]\t\t\t \\n\"\n\t\t\"\tstp\t\tq24, q25, [x26, #32]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\n\t\t\".macro\tKERNEL1x16_BEGIN_K\t\t\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmul\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL1x16_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL1x16_K1 \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL1x16_K2 \t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro KERNEL1x16_K3 \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq8, [x24], #16\t\t\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq9, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq10, [x24], #16\t\t\t\t \t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tldr\t\tq11, [x24], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tM1_ADD_C \t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\n\t\t\"\tldp\t\tq0, q1, [x25]\t\t\t\t\t \\n\"\n\n\t\t\"\tfadd\tv12.4s, v12.4s, v0.4s\t\t\t \\n\"\n\t\t\"\tldp\t\tq2, q3, [x25, #32]\t\t\t\t \\n\"\n\t\t\"\tfadd\tv13.4s, v13.4s, v1.4s\t\t\t \\n\"\n\n\t\t\"\tfadd\tv22.4s, v2.4s, v22.4s\t\t\t \\n\"\n\t\t\"\tfadd\tv23.4s, v3.4s, v23.4s\t\t \t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro KERNEL1x16_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv22.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv23.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro SAVE1x16\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq22, q23, [x25, #32]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_SAVE5x8\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tsubs\tx21, x21, #1\t\t\t\t\t \\n\"\n\n\t\t\"\tadd \tx10, x10, x5, lsl #4\t\t\t \\n\"\n\t\t\"\tadd\t\tx10, x10, x5, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tadd\t\tx25, x29, x6\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\t\t\"\tadd\t\tx26, x25, x6\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq16, q17, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx27, x26, x6\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq18, q19, [x28]\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx28, x27, x6\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq20, q21, [x29]\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx29, x28, x6\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro\tN8_KERNEL5x8_BEGIN_K \t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64] \t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv16.4s, v8.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv17.4s, v9.4s, v2.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq4, [x15], #16\t\t\t\t \t \\n\"\n\n\t\t\"\tfmul\tv18.4s, v8.4s, v3.s[0]\t \\n\"\n\t\t\"\tfmul\tv19.4s, v9.4s, v3.s[0]\t \\n\"\n\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv20.4s, v8.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tfmul\tv21.4s, v9.4s, v4.s[0]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL5x8_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v4.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v4.s[0]\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL5x8_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v10.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v3.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v10.4s, v4.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v11.4s, v4.s[1]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL5x8_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v8.4s, v4.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v9.4s, v4.s[2]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL5x8_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x15, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v10.4s, v4.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v11.4s, v4.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq4, [x15], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL5x8_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv20.4s, v10.4s, v4.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv21.4s, v11.4s, v4.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro \tN8_KERNEL4x8_BEGIN_K\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64] \t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv16.4s, v8.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv17.4s, v9.4s, v2.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv18.4s, v8.4s, v3.s[0]\t \\n\"\n\t\t\"\tfmul\tv19.4s, v9.4s, v3.s[0]\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL4x8_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[0]\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL4x8_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v10.4s, v3.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v3.s[1]\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL4x8_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v8.4s, v3.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv19.4s, v9.4s, v3.s[2]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL4x8_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x15, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq3, [x14], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL4x8_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv18.4s, v10.4s, v3.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv19.4s, v11.4s, v3.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_SAVE4x8 \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\t\t\"\tstp\t\tq16, q17, [x27]\t\t\t\t\t \\n\"\n\t\t\"\tstp\t\tq18, q19, [x28]\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro \tN8_KERNEL3x8_BEGIN_K\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x14, #64] \t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv16.4s, v8.4s, v2.s[0]\t \\n\"\n\t\t\"\tfmul\tv17.4s, v9.4s, v2.s[0]\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL3x8_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[0]\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL3x8_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[1]\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL3x8_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x13, #64] \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v8.4s, v2.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv17.4s, v9.4s, v2.s[2]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL3x8_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x15, #64] \t \\n\"\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq2, [x13], #16\t\t\t\t\t \\n\"\n\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL3x8_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv16.4s, v10.4s, v2.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv17.4s, v11.4s, v2.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_SAVE3x8 \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\t\t\"\tstp\t\tq16, q17, [x27]\t\t\t\t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\n\t\t\".macro N8_KERNEL2x8_BEGIN_K\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x12, #64] \t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv14.4s, v8.4s, v1.s[0]\t \\n\"\n\t\t\"\tfmul\tv15.4s, v9.4s, v1.s[0]\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL2x8_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[0]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[0]\t\t\t \\n\"\n\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL2x8_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x12, #64] \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[1]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL2x8_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v8.4s, v1.s[2]\t\t\t \\n\"\n\t\t\"\tfmla \tv15.4s, v9.4s, v1.s[2]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL2x8_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq1, [x12], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL2x8_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tfmla\tv14.4s, v10.4s, v1.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv15.4s, v11.4s, v1.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_SAVE2x8 \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\t\t\"\tstp\t\tq14, q15, [x26]\t\t\t \t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL1x8_BEGIN_K\t\t\t \\n\"\n\n\t\t\"\t\t\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #128]\t\t\t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmul\tv12.4s, v8.4s, v0.s[0]\t \\n\"\n\t\t\"\tfmul\tv13.4s, v9.4s, v0.s[0]\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL1x8_K0 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x11, #64] \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[0]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[0]\t\t\t \\n\"\n\t\t\".endm \t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\".macro N8_KERNEL1x8_K1 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[1]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[1]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL1x8_K2 \t\t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq10, q11, [x24], #32\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v8.4s, v0.s[2]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v9.4s, v0.s[2]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL1x8_K3 \t \\n\"\n\n\t\t\" prfm PLDL1KEEP, [x24, #128] \t \\n\"\n\t\t\"\tldp\t\tq8, q9, [x24], #32\t\t\t\t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\"\tldr\t\tq0, [x11], #16\t\t\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_KERNEL1x8_END_K \t \\n\"\n\n\t\t\"\tfmla\tv12.4s, v10.4s, v0.s[3]\t\t\t \\n\"\n\t\t\"\tfmla\tv13.4s, v11.4s, v0.s[3]\t\t\t \\n\"\n\n\t\t\".endm\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\n\t\t\".macro N8_SAVE1x8 \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tstp\t\tq12, q13, [x25]\t\t\t \t\t \\n\"\n\n\t\t\".endm \t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\n\n//----------------------------------------------------\n\n\t\t\"SMM:\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tldr\t\tx0, %[C]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx1, %[A]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx2, %[B]\t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tx3, %[M]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx4, %[N]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx5, %[K]\t\t\t\t\t\t \\n\"\n//\t\t\"\tldr\t\tx7, %[temp]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx9, %[LN] \t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx6, %[LK]\t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tx19, %[SB]\t\t\t\t\t\t \\n\"\n\t\t\"\tldr\t\tx8, %[k_tag] \t\t\t\t\t \\n\"\n//\t\t\"\tlsl\t\tx6, x4, #2\t\t\t\t\t\t \\n\" //sizeof(N)\n\n\t\t\"\tadd\t\tsp, sp, #-32\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx23, #5\t\t\t\t\t\t \t \\n\"\n//\t\t\"\tlsl\t\tx8, x5, #2\t\t\t\t\t\t \\n\" //sizeof(K)\n\n\t\t\" prfm PLDL1KEEP, [x1] \t \\n\"\n\t\t\" prfm PLDL1KEEP, [x2] \t \\n\"\n\n\t\t\"\tudiv\tx30, x3, x23\t\t\t\t \t \\n\"\t// M / 5\n\t\t\"\tlsr\t\tx20, x4, #4\t\t\t\t\t \t \\n\"\t// N / 16\n\n\t\t\"\tmsub\tx23, x30, x23, x3 \t\t\t\t \\n\"\t// M % 5\n\t\t\"\tstr \tx23, [sp] \t\t\t\t\t\t \\n\"\n\t\t\"\tmov \tx23, x19 \t\t\t\t\t\t \\n\" //SB\n\t\t\"\tstr \tx8, [sp, #16]\t\t\t\t\t \\n\"\n\n//\t\t\"\tcmp\t\tx20, #0\t\t\t\t\t\t\t \\n\"\n//\t\t\"\tbeq\t\tBEGIN_N8\t\t\t\t\t\t \\n\"\n\n\n\n//-----------------------------------------------N16\n\t\t\"BEGIN_N16:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tmov \tx25, x0 \t\t\t\t\t\t \\n\" //C1*\n\t\t\"\tadd\t\tx26, x25, x9, lsl #2 \t\t\t \\n\" //C2*\n\t\t\"\tadd \tx27, x25, x9, lsl #3 \t\t\t \\n\" //C3*\n\t\t\" \tadd \tx28, x26, x9, lsl #3 \t\t\t \\n\" //C4*\n\t\t\"\tadd\t\tx29, x27, x9, lsl #3 \t\t\t \\n\" //C5*\n\n\t\t\"\tmov\t\tx10, x1 \t\t\t\t\t\t \\n\"\n\t\t\"\tmov\t\tx21, x30 \t\t\t\t\t\t \\n\"\n\t\t\"\tmov\t\tx24, x23\t\t\t\t\t\t \\n\" //还原SB的地址\n\n\t\t\"\tmov\t\tx7, #4\t\t\t\t\t\t\t \\n\" //4次B的循环\n\t\t\"\tmov\t\tx8, #16\t\t\t\t\t\t\t \\n\"\n\n\t\t\"BEGIN_PACKB:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx16, x2\t\t\t\t\t\t \t \\n\" //B0*\n\t\t\"\tadd\t\tx17, x16, x6, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx18, x17, x6, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx19, x18, x6, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10\t\t\t\t\t\t \\n\" //A0*\n\t\t\"\tadd\t\tx12, x11, x6, lsl #2\t\t\t \\n\" //A1*\n\t\t\"\tadd\t\tx13, x12, x6, lsl #2\t\t\t \\n\"\t//A2*\n\t\t\"\tadd\t\tx14, x13, x6, lsl #2\t\t\t \\n\"\t//A3*\n\t\t\"\tadd\t\tx15, x14, x6, lsl #2 \t\t\t \\n\"\t//A4*\n\n\t\t\"\tprfm PLDL1KEEP, [x16, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x17, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x18, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x19, #64]\t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\t\t\"PACK_Body_K:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #3 \t\t\t\t\t \\n\" // K / 8\n\n\t\t\"\tPACK_KERNEL5x4_BEGIN_K\t\t\t\t \t \\n\"\n\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\t\n\t\t\"\tb \t\tPACK_K1_7\t\t\t\t\t\t \\n\"\n\n\t\t\"PACK_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tPACK_KERNEL5x4_K0\t\t\t\t\t\t \\n\"\n\t\t\"PACK_K1_7:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tPACK_Edge_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tPACK_KERNEL5x4_K1\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tPACK_K\t\t\t \t\t\t\t \\n\"\t\n\n\t\t\"PACK_Edge_K:\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x29, #64]\t\t\t \\n\"\n\n\t\t\"\tPACK_KERNEL5x4_END_K\t\t\t \\n\"\t\t\n\n\t\t\"\tldr\t\tx8, [sp, #16]\t\t\t\t\t \\n\"\t\n\t\t\"\tcmp\t\tx8, #0\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tPACKB_SAVE1 \t\t\t\t\t \\n\"\n\t\t\"\tPACKB_ADD_C \t\t\t\t\t\t\t \\n\"\n\t\t\"PACKB_SAVE1: \t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tSAVE5x4\t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"\tmov\t\tx8, #16\t\t\t\t\t\t\t \\n\"\n\n//\t\t\"\tbeq\t\tEND_PACKB\t\t\t\t\t\t \\n\"\n\n\t\t\"\tadd\t\tx23, x23, #16\t\t\t\t\t \\n\"\n\t\t\"\tmov\t\tx24, x23 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx2, x2, x6, lsl #4\t\t\t\t \\n\"\n\n\t\t\"\tbgt \tBEGIN_PACKB\t\t\t\t\t \t \\n\"\n\n\t\t\"END_PACKB:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tsub\t\tx23, x23, x8, lsl #2\t\t\t \\n\" //还原SB的索引\n\n\t\t\"\tsub \tx29, x29, x8, lsl #2\t\t\t \\n\" //C矩阵的偏移量还原\n\t\t\"\tadd\t\tx25, x29, x9, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx26, x25, x9, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx27, x26, x9, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx28, x27, x9, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx29, x28, x9, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tadd\t\tx10, x10, x6, lsl #4\t\t\t \\n\" \n\t\t\"\tadd \tx10, x10, x6, lsl #2 \t\t\t \\n\"\t// A + 5行\n\n\t\t\"\tcmp\t\tx8, #16\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tN8_END_PACKB\t\t\t\t\t \\n\"\n\n\t\t\"\tsubs\tx21, x21, #1\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tEND_M5\t\t\t\t\t\t\t \\n\"\n\n\n\t\t//---------------------------------------------------\n\n\t\t\"BEGIN_M5:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx24, x23\t \t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10\t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x6, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx13, x12, x6, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx14, x13, x6, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx15, x14, x6, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x24, #512]\t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\n\t\t\"Body_K:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #3 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tKERNEL5x16_BEGIN_K\t\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb K1_7\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"Main_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\n\t\t\"\tKERNEL5x16_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"K1_7:\t\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL5x16_K1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL5x16_K2\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL5x16_K3\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL5x16_K4\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL5x16_K5\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL5x16_K6\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tEdge_K\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tKERNEL5x16_K7\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tMain_K\t\t\t \t\t\t\t \\n\"\t\n\n\t\t\"Edge_K:\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x29, #64]\t\t\t \\n\"\n\n\t\t\"\tKERNEL5x16_END_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tx8, [sp, #16]\t\t\t\t\t \\n\"\t\n\t\t\"\tcmp\t\tx8, #0\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tM5_SAVE1 \t\t\t\t\t\t \\n\"\n\t\t\"\tADD_C \t\t\t\t\t\t\t\t \t \\n\"\n\t\t\"M5_SAVE1: \t\t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tSAVE5x16\t\t\t\t\t\t\t\t \\n\"\t\n\n//\t\t\"\tSAVE5x16\t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbgt \tBEGIN_M5\t\t\t\t\t\t \\n\"\n\n\t\t\"END_M5:\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tmov\t\tx24, x23\t \t\t\t\t \\n\" //B0*\n\n\t\t\"\tldr\t\tx21, [sp]\t\t\t\t\t \t \\n\"\n\t\t\"\tcmp\t\tx21, #4\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tBEGIN_M3 \t\t\t\t\t\t \\n\"\n\n\n\n\t//--------------------------------------------------------\n\t\t\"BEGIN_M4:\t\t\t\t\t\t \t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x6, lsl #2 \t\t \\n\"\n\t\t\"\tadd\t\tx13, x12, x6, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx14, x13, x6, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\n\n\t\t\"M4_Body_K:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tKERNEL4x16_BEGIN_K\t\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tM4_K1_3\t\t\t\t\t\t\t \\n\"\n\n\t\t\"M4_Main_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL4x16_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"M4_K1_3:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL4x16_K1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL4x16_K2\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tM4_Edge_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tKERNEL4x16_K3\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tM4_Main_K\t\t\t \t\t\t \\n\"\t\n\n\t\t\"M4_Edge_K:\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\n\t\t\"\tKERNEL4x16_END_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tx8, [sp, #16]\t\t\t\t\t \\n\"\t\n\t\t\"\tcmp\t\tx8, #0\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tM4_SAVE1 \t\t\t\t\t\t \\n\"\n\t\t\"\tM4_ADD_C \t\t\t\t\t\t\t\t \\n\"\n\t\t\"M4_SAVE1: \t\t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tSAVE4x16\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tEND_M \t\t\t\t\t\t\t \\n\"\n\n\n\t\t//--------------------------------------------------------\n\n\t\t\"BEGIN_M3:\t\t\t \t\t\t\t\t\t \\n\"\n\t\t\"\tcmp\t\tx21, #3\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tBEGIN_M2 \t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x6, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx13, x12, x6, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\n\t\t\"M3_Body_K:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tKERNEL3x16_BEGIN_K\t\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tM3_K1_3\t\t\t\t\t\t\t \\n\"\n\n\t\t\"M3_Main_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL3x16_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"M3_K1_3:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL3x16_K1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL3x16_K2\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tM3_Edge_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tKERNEL3x16_K3\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tM3_Main_K\t\t\t \t\t\t \\n\"\t\n\n\t\t\"M3_Edge_K:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\n\t\t\"\tKERNEL3x16_END_K\t\t\t\t\t\t \\n\"\t\n\n\t\t\"\tldr\t\tx8, [sp, #16]\t\t\t\t\t \\n\"\t\n\t\t\"\tcmp\t\tx8, #0\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tM3_SAVE1 \t\t\t\t\t\t \\n\"\n\t\t\"\tM3_ADD_C \t\t\t\t\t\t\t\t \\n\"\n\t\t\"M3_SAVE1: \t\t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tSAVE3x16\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tEND_M \t\t\t\t\t\t\t \\n\"\n\n\n\n\n//----------------------------------------------------------\n\t\t\"BEGIN_M2:\t\t\t \t\t\t\t\t\t \\n\"\n\n\t\t\"\tcmp\t\tx21, #2\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tBEGIN_M1 \t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x6, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\n\t\t\"M2_Body_K:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tKERNEL2x16_BEGIN_K\t\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tM2_K1_3\t\t\t\t\t\t\t \\n\"\n\n\t\t\"M2_Main_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL2x16_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"M2_K1_3:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL2x16_K1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL2x16_K2\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tM2_Edge_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tKERNEL2x16_K3\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tM2_Main_K\t\t\t \t\t\t \\n\"\t\n\n\t\t\"M2_Edge_K:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\n\t\t\"\tKERNEL2x16_END_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tx8, [sp, #16]\t\t\t\t\t \\n\"\t\n\t\t\"\tcmp\t\tx8, #0\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tM2_SAVE1 \t\t\t\t\t\t \\n\"\n\t\t\"\tM2_ADD_C \t\t\t\t\t\t\t\t \\n\"\n\t\t\"M2_SAVE1: \t\t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tSAVE2x16\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tEND_M \t\t\t\t\t\t\t \\n\"\n\n\n\n\n//---------------------------------------------------------\t\t\n\n\t\t\"BEGIN_M1:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tcmp\t\tx21, #1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tEND_M \t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\n\t\t\"M1_Body_K:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tKERNEL1x16_BEGIN_K\t\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tM1_K1_3\t\t\t\t\t\t\t \\n\"\n\n\t\t\"M1_Main_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL1x16_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"M1_K1_3:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tKERNEL1x16_K1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tKERNEL1x16_K2\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tM1_Edge_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tKERNEL1x16_K3\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tM1_Main_K\t\t\t \t\t\t \\n\"\t\n\n\t\t\"M1_Edge_K:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\n\t\t\"\tKERNEL1x16_END_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tldr\t\tx8, [sp, #16]\t\t\t\t\t \\n\"\t\n\t\t\"\tcmp\t\tx8, #0\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tM1_SAVE1 \t\t\t\t\t\t \\n\"\n\t\t\"\tM1_ADD_C \t\t\t\t\t\t\t\t \\n\"\n\t\t\"M1_SAVE1: \t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tSAVE1x16\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"END_M:\t\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tsubs\tx20, x20, #1\t\t\t\t\t \\n\"\n\n\t\t\"\tadd\t\tx16, x16, #64\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx0, x0, #64\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbgt\t\tBEGIN_N16\t\t\t\t\t\t \\n\"\n\n\t\t\"END_N16:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tands\tx20, x4, #15\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tEND_N \t\t\t\t\t\t\t \\n\"\n\n\n\t \"N8_END_PACKB:\t \t\t\t\t\t\t \\n\"\n\t/*\t\n\n\t\t\"BEGIN_N8:\t\t\t\t\t\t\t\t\t\\n\"\n\n\n//----------------------------------------------------------N8\n\t\t\"N8_BEGIN_PACKB:\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov \tx25, x0 \t\t\t\t\t\t \\n\" //C1*\n\t\t\"\tadd\t\tx26, x25, x6 \t\t\t\t\t \\n\" //C2*\n\t\t\"\tadd \tx27, x25, x6, lsl #1 \t\t\t \\n\" //C3*\n\t\t\" \tadd \tx28, x26, x6, lsl #1 \t\t\t \\n\" //C4*\n\t\t\"\tadd\t\tx29, x27, x6, lsl #1 \t\t\t \\n\" //C5*\n\n\t\t\"\tmov\t\tx10, x1 \t\t\t\t\t\t \\n\" //A0*\n\t\t\"\tmov\t\tx21, x30 \t\t\t\t\t\t \\n\" // M / 5\n\t\t\"\tmov\t\tx7, #2\t\t\t\t\t\t\t \\n\"\n\t\t\"\tmov\t\tx24, x23\t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx8, #8 \t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tBEGIN_PACKB \t\t\t\t\t \\n\"\n\n\t\t\"N8_END_PACKB:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tsubs\tx21, x21, #1\t\t\t\t\t \\n\"\n\t\t\"\tbeq\t\tN8_END_M5\t\t\t\t\t\t \\n\"\n\n\n//--------------------------------------------------N8M5\n\t\t\"N8_BEGIN_M5:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx24, x23\t \t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10\t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x5, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx13, x12, x5, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx14, x13, x5, lsl #2\t\t\t \\n\"\n\t\t\"\tadd\t\tx15, x14, x5, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x15, #64]\t\t\t \\n\"\n\n\n\t\t\"N8_Body_K:\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tN8_KERNEL5x8_BEGIN_K\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tN8_K1_3\t\t\t\t\t\t\t \\n\"\n\n\t\t\"N8_Main_K:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\n\t\t\"\tN8_KERNEL5x8_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"N8_K1_3:\t\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL5x8_K1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tN8_KERNEL5x8_K2\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tbeq\t\tN8_Edge_K\t\t\t\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL5x8_K3\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tN8_Main_K\t\t\t \t\t\t \\n\"\t\n\n\t\t\"N8_Edge_K:\t\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #64]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x29, #64]\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL5x8_END_K\t\t\t\t\t\t \\n\"\t\t\n\n\t\t\"\tN8_SAVE5x8\t\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbgt \tN8_BEGIN_M5\t\t\t\t\t \t \\n\"\n\n\n\n\n\n//---------------------------------------------------------\n\n\t\t\"N8_END_M5:\t\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx24, x23\t \t\t\t\t \\n\" //B0*\n\n\t\t\"\tldr\t\tx21, [sp]\t\t\t\t\t\t \\n\"\n\t\t\"\tcmp\t\tx21, #4\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tN8_BEGIN_M3 \t\t\t\t\t \\n\"\n\n\t//--------------------------------------------------------\n\t\t\"N8_BEGIN_M4:\t\t\t\t\t\t \t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x5, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx13, x12, x5, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx14, x13, x5, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x14, #64]\t\t\t \\n\"\n\n\n\t\t\"N8_M4_Body_K:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tN8_KERNEL4x8_BEGIN_K\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tN8_M4_K1_3\t\t\t\t\t\t \\n\"\n\n\t\t\"N8_M4_Main_K:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL4x8_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"N8_M4_K1_3:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL4x8_K1\t\t\t\t\t\t \t \\n\"\n\t\t\"\tN8_KERNEL4x8_K2\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tbeq\t\tN8_M4_Edge_K\t\t\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL4x8_K3\t\t\t\t\t\t \t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tN8_M4_Main_K\t\t\t \t\t \\n\"\t\n\n\t\t\"N8_M4_Edge_K:\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #32]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #32]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #32]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x28, #32]\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL4x8_END_K\t\t\t\t\t\t \\n\"\t\t\n\t\t\"\tN8_SAVE4x8\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tN8_END_M \t\t\t\t\t\t \\n\"\n\n\n//------------------------------------------------------------------\n\n\t\t\"N8_BEGIN_M3: \t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tcmp\t\tx21, #3\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tN8_BEGIN_M2 \t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x5, lsl #2 \t\t\t \\n\"\n\t\t\"\tadd\t\tx13, x12, x5, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x13, #64]\t\t\t \\n\"\n\n\n\t\t\"N8_M3_Body_K:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tN8_KERNEL3x8_BEGIN_K\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tN8_M3_K1_3\t\t\t\t\t\t \\n\"\n\n\t\t\"N8_M3_Main_K:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL3x8_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"N8_M3_K1_3:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL3x8_K1\t\t\t\t\t\t \t \\n\"\n\t\t\"\tN8_KERNEL3x8_K2\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tbeq\t\tN8_M3_Edge_K\t\t\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL3x8_K3\t\t\t\t\t\t \t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tN8_M3_Main_K\t\t\t \t\t \\n\"\t\n\n\t\t\"N8_M3_Edge_K:\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #32]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #32]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x27, #32]\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL3x8_END_K\t\t\t\t\t\t \\n\"\t\t\n\t\t\"\tN8_SAVE3x8\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tN8_END_M \t\t\t\t\t\t \\n\"\n\n\n\n\n\n//--------------------------------------------------------\n\n\t\t\"N8_BEGIN_M2:\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tcmp\t\tx21, #2\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tN8_BEGIN_M1 \t\t\t\t\t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\t\t\"\tadd\t\tx12, x11, x5, lsl #2 \t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\t\t\"\tprfm PLDL1KEEP, [x12, #64]\t\t\t \\n\"\n\n\n\t\t\"N8_M2_Body_K:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tN8_KERNEL2x8_BEGIN_K\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tN8_M2_K1_3\t\t\t\t\t\t \\n\"\n\n\t\t\"N8_M2_Main_K:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL2x8_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"N8_M2_K1_3:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL2x8_K1\t\t\t\t\t\t \t \\n\"\n\t\t\"\tN8_KERNEL2x8_K2\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tbeq\t\tN8_M2_Edge_K\t\t\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL2x8_K3\t\t\t\t\t\t \t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tN8_M2_Main_K\t\t\t \t\t \\n\"\t\n\n\t\t\"N8_M2_Edge_K:\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #32]\t\t\t \\n\"\n\t\t\"\tprfm\tPLDL1KEEP, [x26, #32]\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL2x8_END_K\t\t\t\t\t\t \\n\"\t\t\n\t\t\"\tN8_SAVE2x8\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tb \t\tN8_END_M \t\t\t\t\t\t \\n\"\n\n\n\n\n\n//-----------------------------------------------------\n\t\t\"N8_BEGIN_M1:\t\t\t\t\t\t\t\t \\n\"\n\n\n\t\t\"\tcmp\t\tx21, #1\t\t\t\t\t\t\t \\n\"\n\t\t\"\tbne \tN8_END_M \t\t\t\t\t \t \\n\"\n\n\t\t\"\tmov\t\tx11, x10 \t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm PLDL1KEEP, [x11, #64]\t\t\t \\n\"\n\n\t\t\"N8_M1_Body_K:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tlsr\t\tx22, x5, #2 \t\t\t\t\t \\n\" // K / 8\n\t\t\"\tN8_KERNEL1x8_BEGIN_K\t\t\t\t\t \\n\"\n\t\t\"\tsubs\tx22, x22, #1\t\t \t\t \\n\"\t\n\t\t\"\tb \t\tN8_M1_K1_3\t\t\t\t\t\t \\n\"\n\n\t\t\"N8_M1_Main_K:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL1x8_K0\t\t\t\t\t\t \t \\n\"\n\t\t\"N8_M1_K1_3:\t\t\t\t\t\t\t\t \\n\"\n\t\t\n\t\t\"\tN8_KERNEL1x8_K1\t\t\t\t\t\t \t \\n\"\n\t\t\"\tN8_KERNEL1x8_K2\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tbeq\t\tN8_M1_Edge_K\t\t\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL1x8_K3\t\t\t\t\t\t \t \\n\"\n\t\t\n\t\t\"\tsubs\tx22, x22, #1\t\t\t \t\t \\n\"\n\t\t\"\tb \t\tN8_M1_Main_K\t\t\t \t\t \\n\"\t\n\n\t\t\"N8_M1_Edge_K:\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"\tprfm\tPLDL1KEEP, [x25, #32]\t\t\t \\n\"\n\n\t\t\"\tN8_KERNEL1x8_END_K\t\t\t\t\t\t \\n\"\t\t\n\t\t\"\tN8_SAVE1x8\t\t\t\t\t\t\t\t \\n\"\n\n\t\t\"N8_END_M: \t\t\t\t\t\t\t\t\t \\n\"\n*/\n\t\t\"END_N:\t\t\t\t\t\t\t\t\t \t \\n\"\n\n\t\t\"\tadd\t\tsp, sp, #32\t\t\t\t\t\t \\n\"\n\t\t\n\t\t:\n\t\t:\t\n\t\t\t[C] \"m\" (C),\n\t\t\t[A] \"m\" (A),\n [B] \"m\" (B), \n [M] \"m\" (M),\n [N] \"m\" (N),\n [K] \"m\" (K),\n [LN] \"m\" (LN),\n [LK] \"m\" (LK),\n [SB] \"m\" (SB),\n [k_tag] \"m\" (k_tag)\n : \"x0\", \"x1\", \"x2\", \"x3\", \"x4\", \"x5\", \"x6\", \"x7\", \"x8\",\n \t\"x9\", \"x10\", \"x11\", \"x12\", \"x13\",\"x14\", \"x15\", \"x16\",\n \t\"x17\", \"x18\", \"x19\", \"x20\", \"x21\", \"x22\", \"x23\", \"x24\",\"x25\",\n \t\"x26\", \"x27\", \"x28\", \"x29\", \"x30\",\n \"v0\", \"v1\", \"v2\", \"v3\", \"v4\", \"v5\", \"v6\", \"v7\",\n \"v8\", \"v9\", \"v10\", \"v11\", \"v12\", \"v13\", \"v14\", \"v15\",\n \"v16\", \"v17\", \"v18\", \"v19\", \"v20\", \"v21\", \"v22\", \"v23\",\n \"v24\", \"v25\", \"v26\", \"v27\", \"v28\", \"v29\", \"v30\", \"v31\"\n\n\t\t);\n}\n\nvoid Small_SGEMM(float *C, float *A, float *B, long M, long N, \n\t\t\t\t\tlong K, long *temp, long LD)\n{\n\n\tomp_set_num_threads(num);\n\tlong i, k, kc;\n\tlong LK = K;\n long GEMM_K = 328;\n void *ptr;\n posix_memalign(&ptr, 64, num * GEMM_K * 16 *sizeof( float ));\n float *SSB = (float *)ptr;\n\n\t# pragma omp parallel for private(k,kc)\n\tfor(i=0; i< LD; i= i + N)\n\t{\n\t\tfloat *CC = C + i ;\n\n\t\tfor(k = 0; k < LK; k = k + kc)\n\t\t{ \n\t\t\tkc = GEMM_K;\n\t\t\tif(LK - k < GEMM_K)\n\t\t\t\tkc = LK - k;\n\t\t\tfloat * AA = A + k;\n\t\t\tfloat *BB = B + i * LK + k ;\n\n\t\t\tSMM(CC, AA, BB, M, N, kc, temp, LD, LK, \n\t\t\t\t&SSB[i/N * GEMM_K * 16], k);\n\t\t}\n\t}\n\n\tfree(SSB);\n\t\n}\n\nint main()\n{\n\n\topenblas_set_num_threads(num);\n\n\tint i,j,k;\n\tint loop=5;\n\tlong M, N, K;\n\tdouble start, cost;\n\tint flag =0 ;\n\tvoid *ptr, *ptr1;\n\tlong temp =-1;\n\tint pc;\n\n\tFILE *fp;\n \tif( (fp=fopen(\"NSMM_P_FT.txt\",\"w\")) == NULL )\n \t{\n \tputs(\"Fail to open file!\");\n \texit(0);\n \t}\n\n\tK = 576;\n\tfor(j = 5; j < 6;j++)\n\t{\n M = 262; \n N = 50176;\n//\t\tK = 4992 + 8 * j; \n\t\tdouble ops = M *N *K * 1.0e-09 * 2;\n\n\t\tfprintf(fp, \"%d %d %d\", M,N,K);\n\t\tfor(pc =0; pc < 5; pc++)\n\t\t{\n\t\t\tposix_memalign(&ptr1, 4096, M* K * sizeof( float ));\n\t\t\tposix_memalign(&ptr, 4096, K* N * sizeof( float ));\n\t\t\tfloat *A = (float *)ptr1;\t\n\t\t\tfloat *B = (float *)ptr;\n\t\t float *C = ( float * ) malloc( M* N * sizeof( float ) );\n\n\t\t random_matrix(M,K,A);\n\t\t random_matrix(K,N,B);\n\t\t // transpose(K, N, B);\n\n\t\t for( i =0 ;i< 2; i++)\n\t\t \tSmall_SGEMM(C, A, B, M, N/num, K, &temp, N);\n\n\t\t\tstart = dclock();\n\t\t\tfor( i= 0; i< loop ;i++)\n\t\t\t\tSmall_SGEMM(C, A, B, M, N/num, K, &temp, N);\n\t\t\tcost =(dclock()-start)/loop; \n\n\t\t\tops = M * N * K * 1.0e-09 * 2;\n\t\t\tprintf(\"\\nN_SMM: M= %d N=%d K=%d flops = %lf effic= %.3lf %\\n\", \n\t\t\t\t\tM, N, K, ops/cost, ops/cost/17.6 * 100/num);\n\n\n\t\t\tfprintf(fp, \" %.3f\", ops/cost);\n\t\t free(A);\n\t\t free(B);\n\t\t free(C);\n\t\t}\n\n\t\tfprintf(fp, \"\\n\");\n\t}\n\n\tfclose(fp);\n return 0;\n\n}\n", "meta": {"hexsha": "50cfb13b65775787f1862d2395f70ad35967249e", "size": 78009, "ext": "c", "lang": "C", "max_stars_repo_path": "NN_LIB/test_SMM_m5n16_thread.c", "max_stars_repo_name": "AnonymousYWL/MYLIB", "max_stars_repo_head_hexsha": "2497123bf3bfd12f215b428ae83afd223cd072fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2021-06-04T14:39:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T10:45:29.000Z", "max_issues_repo_path": "NN_LIB/test_SMM_m5n16_thread.c", "max_issues_repo_name": "AnonymousYWL/LibShalom", "max_issues_repo_head_hexsha": "63a36c010d5a307d98e8470a75313a777dba0514", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-10-18T11:26:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T07:03:37.000Z", "max_forks_repo_path": "NN_LIB/test_SMM_m5n16_thread.c", "max_forks_repo_name": "AnonymousYWL/LibShalom", "max_forks_repo_head_hexsha": "63a36c010d5a307d98e8470a75313a777dba0514", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-11-17T15:31:02.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T02:32:05.000Z", "avg_line_length": 23.9071406681, "max_line_length": 71, "alphanum_fraction": 0.4114525247, "num_tokens": 44798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.3665897432423099, "lm_q1q2_score": 0.25146202988157024}} {"text": "/*\n * vbHmmGaussIntensity.c\n * Model-specific core functions for VB-HMM-GAUSS.\n *\n * Created by OKAMOTO Kenji, SAKO Yasushi and RIKEN\n * Copyright 2011-2016\n * Cellular Informatics Laboratory, Advance Science Institute, RIKEN, Japan.\n * All rights reserved.\n *\n * Ver. 1.0.0\n * Last modified on 2016.02.08\n */\n\n#include \"vbHmmGaussIntensity.h\"\n#include \n#include \n#include \n#include \"rand.h\"\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n#define MAX(a,b) ((a)>(b)?(a):(b))\n#define MIN(a,b) ((a)<(b)?(a):(b))\n\nstatic int isGlobalAnalysis = 0;\n\nvoid setFunctions_gaussInt(){\n commonFunctions funcs;\n funcs.newModelParameters = newModelParameters_gaussInt;\n funcs.freeModelParameters = freeModelParameters_gaussInt;\n funcs.newModelStats = newModelStats_gaussInt;\n funcs.freeModelStats = freeModelStats_gaussInt;\n funcs.initializeVbHmm = initializeVbHmm_gaussInt;\n funcs.pTilde_z1 = pTilde_z1_gaussInt;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gaussInt;\n funcs.pTilde_xn_zn = pTilde_xn_zn_gaussInt;\n funcs.calcStatsVars = calcStatsVars_gaussInt;\n funcs.maximization = maximization_gaussInt;\n funcs.varLowerBound = varLowerBound_gaussInt;\n funcs.reorderParameters = reorderParameters_gaussInt;\n funcs.outputResults = outputResults_gaussInt;\n setFunctions( funcs );\n}\n\nvoid setGFunctions_gaussInt(){\n gCommonFunctions funcs;\n funcs.newModelParameters = newModelParameters_gaussInt;\n funcs.freeModelParameters = freeModelParameters_gaussInt;\n funcs.newModelStats = newModelStats_gaussInt;\n funcs.freeModelStats = freeModelStats_gaussInt;\n funcs.newModelStatsG = newModelStatsG_gaussInt;\n funcs.freeModelStatsG = freeModelStatsG_gaussInt;\n funcs.initializeVbHmmG = initializeVbHmmG_gaussInt;\n funcs.pTilde_z1 = pTilde_z1_gaussInt;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1_gaussInt;\n funcs.pTilde_xn_zn = pTilde_xn_zn_gaussInt;\n funcs.calcStatsVarsG = calcStatsVarsG_gaussInt;\n funcs.maximizationG = maximizationG_gaussInt;\n funcs.varLowerBoundG = varLowerBoundG_gaussInt;\n funcs.reorderParametersG = reorderParametersG_gaussInt;\n funcs.outputResultsG = outputResultsG_gaussInt;\n setGFunctions( funcs );\n isGlobalAnalysis = 1;\n}\n\n\n\nvoid outputResults_gaussInt( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n outputGaussIntResults( xn, gv, iv, logFP );\n}\n\nvoid outputResultsG_gaussInt( xns, gv, ivs, logFP )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\nFILE *logFP;\n{\n outputGaussIntResultsG( xns, gv, ivs, logFP );\n}\n\n\nvoid *newModelParameters_gaussInt( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n int i;\n gaussIntParameters *p = (gaussIntParameters*)malloc( sizeof(gaussIntParameters) );\n \n p->uPiArr = (double*)malloc( sNo * sizeof(double) );\n p->sumUPi = 0.0;\n p->uAMat = (double**)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->uAMat[i] = (double*)malloc( sNo * sizeof(double) );\n }\n p->sumUAArr = (double*)malloc( sNo * sizeof(double) );\n\n p->avgPi = (double *)malloc( sNo * sizeof(double) );\n p->avgLnPi = (double *)malloc( sNo * sizeof(double) );\n p->avgA = (double **)malloc( sNo * sizeof(double*) );\n p->avgLnA = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ ){\n p->avgA[i] = (double *)malloc( sNo * sizeof(double) );\n p->avgLnA[i] = (double *)malloc( sNo * sizeof(double) );\n }\n\n return p;\n}\n\n\n\nvoid freeModelParameters_gaussInt( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n gaussIntParameters *gp = *p;\n int i;\n \n free( gp->uPiArr );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->uAMat[i] );\n }\n free( gp->uAMat );\n free( gp->sumUAArr );\n\n free( gp->avgPi );\n free( gp->avgLnPi );\n for( i = 0 ; i < sNo ; i++ ){\n free( gp->avgA[i] );\n free( gp->avgLnA[i] );\n }\n free( gp->avgA );\n free( gp->avgLnA );\n \n free( gp );\n *p = NULL;\n}\n\n\nvoid *newModelStats_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n gaussIntStats *s = (gaussIntStats*)malloc( sizeof(gaussIntStats) );\n \n int i;\n s->Ni = (double *)malloc( sNo * sizeof(double) );\n s->Nij = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { s->Nij[i] = (double *)malloc( sNo * sizeof(double) ); }\n s->Nii = (double *)malloc( sNo * sizeof(double) );\n\n return s;\n \n } else {\n \n return NULL;\n \n }\n}\n\nvoid freeModelStats_gaussInt( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n gaussIntStats *gs = *s;\n int i;\n\n free( gs->Ni );\n for( i = 0 ; i < sNo ; i++ )\n { free( gs->Nij[i] ); }\n free( gs->Nij );\n free( gs->Nii );\n\n free( gs );\n *s = NULL;\n }\n}\n\nvoid *newModelStatsG_gaussInt( xns, gv, ivs)\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n int sNo = gv->sNo;\n gaussIntGlobalStats *gs = (gaussIntGlobalStats*)malloc( sizeof(gaussIntGlobalStats) );\n \n int i;\n gs->NijR = (double **)malloc( sNo * sizeof(double*) );\n for( i = 0 ; i < sNo ; i++ )\n { gs->NijR[i] = (double *)malloc( sNo * sizeof(double) ); }\n gs->NiiR = (double *)malloc( sNo * sizeof(double) );\n gs->NiR = (double *)malloc( sNo * sizeof(double) );\n gs->z1iR = (double *)malloc( sNo * sizeof(double) );\n \n return gs;\n}\n\nvoid freeModelStatsG_gaussInt( gs, xns, gv, ivs )\nvoid **gs;\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n int sNo = gv->sNo;\n gaussIntGlobalStats *ggs = *gs;\n int i;\n free( ggs->NiR );\n for( i = 0 ; i < sNo ; i++ )\n { free( ggs->NijR[i] ); }\n free( ggs->NijR );\n free( ggs->NiiR );\n free( ggs->z1iR );\n \n free( *gs );\n *gs = NULL;\n}\n\n\nvoid initializeVbHmm_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n gaussIntData *d = xn->data;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n gaussIntParameters *p = gv->params;\n\n int i, j;\n double totalX = 0.0, precX, varX = 0.0;\n for( i = 0 ; i < dLen ; i++ ){\n totalX += d->v[i];\n }\n double meanX = totalX / (double)dLen;\n for( i = 0 ; i < dLen ; i++ ){\n varX += pow(d->v[i] - meanX, 2.0);\n }\n varX /= (double)(dLen - 1);\n precX = 1.0 / varX;\n\n // hyper parameter for p( pi(i) )\n p->sumUPi = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n p->uPiArr[i] = 1.0;\n p->sumUPi += p->uPiArr[i];\n }\n \n // hyper parameter for p( A(i,j) )\n for( i = 0 ; i < sNo ; i++ ){\n p->sumUAArr[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n if( j == i ){\n p->uAMat[i][j] = 5.0;\n } else {\n p->uAMat[i][j] = 1.0;\n }\n p->sumUAArr[i] += p->uAMat[i][j];\n }\n }\n \n // hyper parameter for p( mu(k), lm(k) )\n for( i = 0 ; i < sNo ; i++ ){\n p->uBt = 1.0;\n p->uMu = meanX * 2.0 / (double)sNo;\n p->uA = 1.0;\n p->uB = p->uA / precX ;\n }\n \n initialize_indVars_gaussInt( xn, gv, iv );\n \n calcStatsVars_gaussInt( xn, gv, iv );\n maximization_gaussInt( xn, gv, iv );\n\n}\n\nvoid initializeVbHmmG_gaussInt( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n gaussIntData *d;\n size_t dLen, totalN;\n int sNo = gv->sNo, rNo = xns->R;\n gaussIntParameters *p = gv->params;\n \n int i, j, r;\n double totalX, precX, varX, meanX;\n \n totalX = 0.0;\n totalN = 0;\n for( r = 0 ; r < rNo ; r++ ){\n d = xns->xn[r]->data;\n dLen = xns->xn[r]->N;\n for( i = 0 ; i < dLen ; i++ ){\n totalX += d->v[i];\n }\n totalN += dLen;\n }\n meanX = totalX / (double)totalN;\n varX = 0.0;\n for( r = 0 ; r < rNo ; r++ ){\n d = xns->xn[r]->data;\n dLen = xns->xn[r]->N;\n for( i = 0 ; i < dLen ; i++ ){\n varX += pow(d->v[i] - meanX, 2.0);\n }\n }\n varX /= (double)(totalN - 1);\n precX = 1.0 / varX;\n \n p->sumUPi = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n p->uPiArr[i] = 1.0;\n p->sumUPi += p->uPiArr[i];\n }\n \n for( i = 0 ; i < sNo ; i++ ){\n p->sumUAArr[i] = 0.0;\n for( j = 0 ; j < sNo ; j++ ){\n if( j == i ){\n p->uAMat[i][j] = 5.0;\n } else {\n p->uAMat[i][j] = 1.0;\n }\n p->sumUAArr[i] += p->uAMat[i][j];\n }\n }\n \n // hyper parameter for p( mu(k), lm(k) )\n for( i = 0 ; i < sNo ; i++ ){\n p->uBt = 1.0;\n p->uMu = meanX * 2.0 / (double)sNo;\n p->uA = 1.0;\n p->uB = p->uA / precX ;\n }\n \n for( r = 0 ; r < rNo ; r++ ){\n initialize_indVars_gaussInt( xns->xn[r], gv, ivs->indVars[r] );\n }\n \n calcStatsVarsG_gaussInt( xns, gv, ivs );\n maximizationG_gaussInt( xns, gv, ivs );\n}\n\n\nvoid initialize_indVars_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n \n int i;\n size_t n;\n double sumPar;\n for( n = 0 ; n < dLen ; n++ ){\n sumPar = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] = enoise(1.0) + 1.0;\n sumPar += gmMat[n][i];\n }\n for( i = 0 ; i < sNo ; i++ ){\n gmMat[n][i] /= sumPar;\n }\n }\n}\n\n\nxnDataSet *newXnDataSet_gaussInt( filename )\nconst char *filename;\n{\n xnDataSet *xn = (xnDataSet*)malloc( sizeof(xnDataSet) );\n xn->name = (char*)malloc( strlen(filename) + 2 );\n strncpy( xn->name, filename, strlen(filename)+1 );\n xn->data = (gaussIntData*)malloc( sizeof(gaussIntData) );\n gaussIntData *d = (gaussIntData*)xn->data;\n d->v = NULL;\n return xn;\n}\n\nvoid freeXnDataSet_gaussInt( xn )\nxnDataSet **xn;\n{\n gaussIntData *d = (gaussIntData*)(*xn)->data;\n free( d->v );\n free( (*xn)->data );\n free( (*xn)->name );\n free( *xn );\n *xn = NULL;\n}\n\n\ndouble pTilde_z1_gaussInt( i, params )\nint i;\nvoid *params;\n{\n gaussIntParameters *p = (gaussIntParameters*)params;\n return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1_gaussInt( i, j, params )\nint i, j;\nvoid *params;\n{\n gaussIntParameters *p = (gaussIntParameters*)params;\n return exp( p->avgLnA[i][j] );\n}\n\ndouble pTilde_xn_zn_gaussInt( xnWv, n, i, params )\nxnDataSet *xnWv;\nsize_t n;\nint i;\nvoid *params;\n{\n gaussIntParameters *p = (gaussIntParameters*)params;\n gaussIntData *xn = (gaussIntData*)xnWv->data;\n double val, di = (double)(i+1);\n val = p->avgLnLm - log(2.0 * M_PI * di);\n val -= di/p->btMu + p->aLm * pow(xn->v[n] - di * p->mu0, 2.0) / di / p->bLm;\n return exp(val / 2.0);\n}\n\n\nvoid calcStatsVars_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n gaussIntData *d = (gaussIntData*)xn->data;\n gaussIntStats *s = (gaussIntStats*)iv->stats;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, ***xiMat = iv->xiMat;\n double *Nii = s->Nii, **Nij = s->Nij, *Ni = s->Ni;\n size_t n;\n int i, j;\n\n s->N0 = (double)xn->N;\n s->N0i = 1e-10;\n s->Nx = 1e-10;\n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] = 1e-10;\n Nii[i] = 1e-10;\n for( j = 0 ; j < sNo ; j++ ){\n Nij[i][j] = 1e-10;\n }\n\n for( n = 0 ; n < dLen ; n++ ){\n Ni[i] += gmMat[n][i];\n s->Nx += gmMat[n][i] * d->v[n];\n for( j = 0 ; j < sNo ; j++ ){\n Nii[i] += xiMat[n][i][j];\n Nij[i][j] += xiMat[n][i][j];\n }\n }\n s->N0i += (double)(i+1) * Ni[i];\n }\n}\n\nvoid calcStatsVarsG_gaussInt( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n gaussIntData *d;\n gaussIntGlobalStats *gs = (gaussIntGlobalStats*)ivs->stats;\n int sNo = gv->sNo, rNo = xns->R;\n double **gmMat, ***xiMat;\n double *NiiR = gs->NiiR, **NijR = gs->NijR, *NiR = gs->NiR, *z1iR = gs->z1iR;\n size_t dLen, n;\n int i, j, r;\n\n gs->N0R = 0.0;\n gs->N0iR = 1e-10;\n gs->NxR = 1e-10;\n for( i = 0 ; i < sNo ; i++ ){\n NiR[i] = 1e-10;\n NiiR[i] = 1e-10;\n for( j = 0 ; j < sNo ; j++ ){\n NijR[i][j] = 1e-10;\n }\n z1iR[i] = 1e-10;\n }\n for( r = 0 ; r < rNo ; r++ ){\n d = (gaussIntData*)xns->xn[r]->data;\n dLen = xns->xn[r]->N;\n gmMat = ivs->indVars[r]->gmMat;\n xiMat = ivs->indVars[r]->xiMat;\n for( i = 0 ; i < sNo ; i++ ){\n z1iR[i] += gmMat[0][i];\n for( n = 0 ; n < dLen ; n++ ){\n NiR[i] += gmMat[n][i];\n gs->NxR += gmMat[n][i] * d->v[n];\n for( j = 0 ; j < sNo ; j++ ){\n NiiR[i] += xiMat[n][i][j];\n NijR[i][j] += xiMat[n][i][j];\n }\n }\n }\n gs->N0R += (double)xns->xn[r]->N;\n }\n for( i = 0 ; i < sNo ; i++ ){\n gs->N0iR += (double)(i+1) * NiR[i];\n }\n}\n\n\nvoid maximization_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n gaussIntParameters *p = (gaussIntParameters*)gv->params;\n gaussIntStats *s = (gaussIntStats*)iv->stats;\n gaussIntData *d = (gaussIntData*)xn->data;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n double *Nii = s->Nii, **Nij = s->Nij, N0 = s->N0, N0i = s->N0i, Nx = s->Nx;\n int i, j, m;\n\n double bLm = 0.0, di;\n for( i = 0 ; i < sNo ; i++ ){\n avgPi[i] = ( uPiArr[i] + gmMat[0][i] ) / ( sumUPi + 1.0 );\n avgLnPi[i] = gsl_sf_psi( uPiArr[i] + gmMat[0][i] ) - gsl_sf_psi( sumUPi + 1.0 );\n\n for( j = 0 ; j < sNo ; j++ ){\n avgA[i][j] = ( uAMat[i][j] + Nij[i][j] ) / ( sumUAArr[i] + Nii[i] );\n avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Nii[i] );\n }\n\n di = (double)(i+1);\n for( m = 0 ; m < dLen ; m++ ){\n bLm += gmMat[m][i] * d->v[m] * d->v[m] / di;\n }\n }\n bLm /= 2.0;\n\n p->btMu = uBt + N0i;\n p->mu0 = (uBt * uMu + Nx) / p->btMu;\n p->aLm = uA + (N0 / 2.0);\n bLm += uB + (uBt * uMu * uMu / 2.0);\n bLm -= p->btMu * p->mu0 * p->mu0 / 2.0;\n p->bLm = bLm;\n\n p->avgMu = p->mu0;\n p->avgLm = p->aLm / p->bLm;\n p->avgLnLm = gsl_sf_psi( p->aLm ) - log( p->bLm );\n}\n\nvoid maximizationG_gaussInt( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n gaussIntParameters *p = (gaussIntParameters*)gv->params;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n gaussIntGlobalStats *gs = (gaussIntGlobalStats*)ivs->stats;\n double *NiiR = gs->NiiR, **NijR = gs->NijR, N0R = gs->N0R, N0iR = gs->N0iR, NxR = gs->NxR;\n double *z1iR = gs->z1iR, dR = (double)(xns->R), di, bLm = 0.0;\n int sNo = gv->sNo, rNo = xns->R;\n int i, j, m, r;\n \n for( i = 0 ; i < sNo ; i++ ){\n avgPi[i] = ( uPiArr[i] + z1iR[i] ) / ( sumUPi + dR );\n avgLnPi[i] = gsl_sf_psi( uPiArr[i] + z1iR[i] ) - gsl_sf_psi( sumUPi + dR );\n \n for( j = 0 ; j < sNo ; j++ ){\n avgA[i][j] = ( uAMat[i][j] + NijR[i][j] ) / ( sumUAArr[i] + NiiR[i] );\n avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + NijR[i][j] ) - gsl_sf_psi( sumUAArr[i] + NiiR[i] );\n }\n\n di = (double)(i+1);\n for( r = 0 ; r < rNo ; r++ ){\n size_t dLen = xns->xn[r]->N;\n gaussIntData *d = (gaussIntData*)xns->xn[r]->data;\n double **gmMat = ivs->indVars[r]->gmMat;\n for( m = 0 ; m < dLen ; m++ ){\n bLm += gmMat[m][i] * d->v[m] * d->v[m] / di;\n }\n }\n\n }\n bLm /= 2.0;\n\n p->btMu = uBt + N0iR;\n p->mu0 = (uBt * uMu + NxR) / p->btMu;\n p->aLm = uA + N0R / 2.0;\n bLm += uB + uBt * uMu * uMu / 2.0;\n bLm -= p->btMu * p->mu0 * p->mu0 / 2.0;\n p->bLm = bLm;\n \n p->avgMu = p->mu0;\n p->avgLm = p->aLm / p->bLm;\n p->avgLnLm = gsl_sf_psi( p->aLm ) - log( p->bLm );\n}\n\n\ndouble varLowerBound_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n gaussIntParameters *p = (gaussIntParameters*)gv->params;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat, *cn = iv->cn;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB;\n double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n double avgLm = p->avgLm, avgLnLm = p->avgLnLm;\n double mu0 = p->mu0, btMu = p->btMu, aLm = p->aLm, bLm = p->bLm;\n gaussIntStats *s = (gaussIntStats*)iv->stats;\n double *Nii = s->Nii, **Nij = s->Nij;\n size_t n;\n int i, j;\n\n double lnpPi = gsl_sf_lngamma(sumUPi);\n double lnpA = 0.0;\n double lnpMuLm = log(uBt) / 2.0;\n lnpMuLm -= uBt * (1.0 / btMu + aLm * pow(mu0 - uMu, 2.0) / bLm ) / 2.0;\n lnpMuLm += - gsl_sf_lngamma(uA) + uA * log(uB);\n lnpMuLm += (uA - 0.5) * avgLnLm - uB * avgLm;\n\n double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);\n double lnqA = 0.0;\n double lnqMuLm = (log(btMu) - 1.0) / 2.0 - gsl_sf_lngamma(aLm) + aLm * log(bLm);\n lnqMuLm += (aLm - 0.5) * avgLnLm - aLm;\n\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n\n \n lnqPi += (uPiArr[i]+gmMat[0][i]-1.0) * (gsl_sf_psi(uPiArr[i]+gmMat[0][i]) - gsl_sf_psi(sumUPi+1.0));\n lnqPi -= gsl_sf_lngamma(uPiArr[i] + gmMat[0][i]);\n\n lnpA += gsl_sf_lngamma(sumUAArr[i]);\n lnqA += gsl_sf_lngamma(sumUAArr[i] + Nii[i]);\n for( j = 0 ; j < sNo ; j++ ){\n lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);\n\n lnqA += (uAMat[i][j] + Nij[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+Nij[i][j]) - gsl_sf_psi(sumUAArr[i]+Nii[i]));\n lnqA -= gsl_sf_lngamma( uAMat[i][j] + Nij[i][j] );\n }\n }\n\n double lnpX = 0.0;\n for( n = 0 ; n < dLen ; n++ ){\n lnpX += log( cn[n] );\n }\n\n double val;\n val = lnpPi + lnpA + lnpMuLm;\n val -= lnqPi + lnqA + lnqMuLm;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n\n return val;\n}\n\ndouble varLowerBoundG_gaussInt( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n gaussIntParameters *p = (gaussIntParameters*)gv->params;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double uBt = p->uBt, uMu = p->uMu, uA = p->uA, uB = p->uB;\n double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n double avgLm = p->avgLm, avgLnLm = p->avgLnLm;\n double mu0 = p->mu0, btMu = p->btMu, aLm = p->aLm, bLm = p->bLm;\n gaussIntGlobalStats *gs = (gaussIntGlobalStats*)ivs->stats;\n double *NiiR = gs->NiiR, **NijR = gs->NijR, *z1iR = gs->z1iR, dR = (double)xns->R;\n size_t n;\n int sNo = gv->sNo, rNo = xns->R;\n int i, j, r;\n \n double lnpPi = gsl_sf_lngamma(sumUPi);\n double lnpA = 0.0;\n double lnpMuLm = log(uBt) / 2.0;\n lnpMuLm -= uBt * (1.0 / btMu + aLm * pow(mu0 - uMu, 2.0) / bLm ) / 2.0;\n lnpMuLm += - gsl_sf_lngamma(uA) + uA * log(uB);\n lnpMuLm += (uA - 0.5) * avgLnLm - uB * avgLm;\n\n double lnqPi = gsl_sf_lngamma(sumUPi + dR);\n double lnqA = 0.0;\n double lnqMuLm = (log(btMu) - 1.0) / 2.0 - gsl_sf_lngamma(aLm) + aLm * log(bLm);\n lnqMuLm += (aLm - 0.5) * avgLnLm - aLm;\n\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[i]);\n\n lnqPi += (uPiArr[i]+z1iR[i]-1.0) * (gsl_sf_psi(uPiArr[i]+z1iR[i]) - gsl_sf_psi(sumUPi+dR));\n lnqPi -= gsl_sf_lngamma(uPiArr[i] + z1iR[i]);\n \n lnpA += gsl_sf_lngamma(sumUAArr[i]);\n lnqA += gsl_sf_lngamma(sumUAArr[i] + NiiR[i]);\n for( j = 0 ; j < sNo ; j++ ){\n lnpA += (uAMat[i][j]-1.0)*avgLnA[i][j] - gsl_sf_lngamma(uAMat[i][j]);\n \n lnqA += (uAMat[i][j] + NijR[i][j] - 1.0) * (gsl_sf_psi(uAMat[i][j]+NijR[i][j]) - gsl_sf_psi(sumUAArr[i]+NiiR[i]));\n lnqA -= gsl_sf_lngamma( uAMat[i][j] + NijR[i][j] );\n }\n }\n\n double lnpX = 0.0;\n for( r = 0 ; r < rNo ; r++ ){\n size_t dLen = xns->xn[r]->N;\n for( n = 0 ; n < dLen ; n++ ){\n lnpX += log( ivs->indVars[r]->cn[n] );\n }\n }\n \n double val;\n val = lnpPi + lnpA + lnpMuLm;\n val -= lnqPi + lnqA + lnqMuLm;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n \n return val;\n} \n\n\nvoid reorderParameters_gaussInt( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n}\n\nvoid reorderParametersG_gaussInt( xns, gv, ivs )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\n{\n}\n\n\nvoid outputGaussIntResults( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n gaussIntParameters *p = (gaussIntParameters*)gv->params;\n int sNo = gv->sNo;\n\n int i, j;\n fprintf(logFP, \" results: K = %d \\n\", sNo);\n\n fprintf(logFP, \" mean: ( %g ) \\n\", p->avgMu);\n\n fprintf(logFP, \" lambda: ( %g ) \\n\", p->avgLm);\n\n fprintf(logFP, \" pi: ( %g\", p->avgPi[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgPi[i]);\n }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" A_matrix: [\");\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(logFP, \" ( %g\", p->avgA[i][0]);\n for( j = 1 ; j < sNo ; j++ )\n { fprintf(logFP, \", %g\", p->avgA[i][j]); }\n fprintf(logFP, \")\");\n }\n fprintf(logFP, \" ] \\n\\n\");\n\n char fn[256];\n FILE *fp;\n size_t n;\n\n sprintf( fn, \"%s.param%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n fprintf(fp, \"mu, lambda, pi\");\n for( i = 0 ; i < sNo ; i++ )\n { fprintf(fp, \", A%dx\", i); }\n fprintf(fp, \"\\n\");\n\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(fp, \"%g, %g, %g\", (double)(i+1)*p->avgMu, (double)(i+1)*p->avgLm, p->avgPi[i]);\n for( j = 0 ; j < sNo ; j++ )\n { fprintf(fp, \", %g\", p->avgA[j][i]); }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n\n sprintf( fn, \"%s.Lq%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < gv->iteration ; n++ ){\n fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.maxS%03d\", xn->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < xn->N ; n++ ){\n fprintf( fp, \"%d\\n\", iv->stateTraj[n] );\n }\n fclose(fp);\n }\n \n}\n\nvoid outputGaussIntResultsG( xns, gv, ivs, logFP )\nxnDataBundle *xns;\nglobalVars *gv;\nindVarBundle *ivs;\nFILE *logFP;\n{\n int sNo = gv->sNo, rNo = xns->R;\n gaussIntParameters *p = (gaussIntParameters*)gv->params;\n int i, j, r;\n \n fprintf(logFP, \" results: K = %d \\n\", sNo);\n \n fprintf(logFP, \" mean: ( %g ) \\n\", p->avgMu);\n \n fprintf(logFP, \" lambda: ( %g ) \\n\", p->avgLm);\n \n fprintf(logFP, \" pi: ( %g\", p->avgPi[0]);\n for( i = 1 ; i < sNo ; i++ ){\n fprintf(logFP, \", %g\", p->avgPi[i]);\n }\n fprintf(logFP, \" ) \\n\");\n \n fprintf(logFP, \" A_matrix: [\");\n for( i = 0 ; i < sNo ; i++ ){\n fprintf(logFP, \" ( %g\", p->avgA[i][0]);\n for( j = 1 ; j < sNo ; j++ )\n { fprintf(logFP, \", %g\", p->avgA[i][j]); }\n fprintf(logFP, \")\");\n }\n fprintf(logFP, \" ] \\n\\n\");\n \n char fn[256];\n FILE *fp;\n size_t n;\n \n sprintf( fn, \"%s.param%03d\", xns->xn[0]->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n fprintf(fp, \"mu, lambda, pi\");\n for( i = 0 ; i < sNo ; i++ )\n { fprintf(fp, \", A%dx\", i); }\n fprintf(fp, \"\\n\");\n \n for( i = 0 ; i < sNo ; i++ ){\n fprintf(fp, \"%g, %g, %g\", (double)(i+1)*p->avgMu, (double)(i+1)*p->avgLm, p->avgPi[i]);\n for( j = 0 ; j < sNo ; j++ )\n { fprintf(fp, \", %g\", p->avgA[j][i]); }\n fprintf(fp, \"\\n\");\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.Lq%03d\", xns->xn[0]->name, sNo );\n if( (fp = fopen( fn, \"w\")) != NULL ){\n for( n = 0 ; n < gv->iteration ; n++ ){\n fprintf( fp, \"%24.20e\\n\", gv->LqArr[n] );\n }\n fclose(fp);\n }\n \n sprintf( fn, \"%s.maxS%03d\", xns->xn[0]->name, sNo );\n int flag = 0;\n if( (fp = fopen( fn, \"w\")) != NULL ){\n n = 0;\n do{\n flag = 1;\n for( r = 0 ; r < rNo ; r++ ){\n xnDataSet *xn = xns->xn[r];\n indVars *iv = ivs->indVars[r];\n \n if( r > 0 ){\n fprintf( fp, \",\" );\n }\n if( n < xn->N ){\n fprintf( fp, \"%d\", iv->stateTraj[n] );\n }\n flag &= (n >= (xn->N - 1));\n }\n fprintf( fp, \"\\n\" );\n n++;\n }while( !flag );\n fclose(fp);\n }\n}\n\n//\n", "meta": {"hexsha": "fcc3a699ba51b21b99e8f726ab5032525bff86f5", "size": 25760, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmmGaussIntensity.c", "max_stars_repo_name": "okamoto-kenji/varBayes-HMM", "max_stars_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-03-31T06:59:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-01T06:35:57.000Z", "max_issues_repo_path": "C/vbHmmGaussIntensity.c", "max_issues_repo_name": "okamoto-kenji/varBayes-HMM", "max_issues_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_issues_repo_licenses": ["MIT"], "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/vbHmmGaussIntensity.c", "max_forks_repo_name": "okamoto-kenji/varBayes-HMM", "max_forks_repo_head_hexsha": "77afe3c336c9e1ebeb115ca4f0b2bc25060556bd", "max_forks_repo_licenses": ["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.0304678999, "max_line_length": 126, "alphanum_fraction": 0.4989906832, "num_tokens": 9826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.2513203076179137}} {"text": "/* rng/ranlxs.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 M. Luescher's second generation\n version of the RANLUX generator.\n\n Thanks to Martin Luescher for providing information on this\n generator.\n\n */\n\nstatic unsigned long int ranlxs_get (void *vstate);\nstatic inline double ranlxs_get_double (void *vstate);\nstatic void ranlxs_set_lux (void *state, unsigned long int s, unsigned int luxury);\nstatic void ranlxs0_set (void *state, unsigned long int s);\nstatic void ranlxs1_set (void *state, unsigned long int s);\nstatic void ranlxs2_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};\nstatic const int snext[24] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,\n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0};\n\nstatic const double sbase = 16777216.0;\t\t/* 2^24 */\nstatic const double sone_bit = 1.0 / 16777216.0;\t/* 1/2^24 */\nstatic const double one_bit = 1.0 / 281474976710656.0;\t/* 1/2^48 */\n\nstatic const double shift = 268435456.0;\t/* 2^28 */\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], ydbl[12]; /* doubles first so they are 8-byte aligned */\n double carry;\n float xflt[24];\n unsigned int ir;\n unsigned int jr;\n unsigned int is;\n unsigned int is_old;\n unsigned int pr;\n }\nranlxs_state_t;\n\nstatic void increment_state (ranlxs_state_t * state);\n\nstatic void\nincrement_state (ranlxs_state_t * state)\n{\n int k, kmax, m;\n double x, y1, y2, y3;\n\n float *xflt = state->xflt;\n double *xdbl = state->xdbl;\n double *ydbl = state->ydbl;\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 ydbl[ir] = y2 + shift;\n ir = next[ir];\n jr = next[jr];\n }\n\n ydbl[ir] = xdbl[ir] + shift;\n\n for (k = next[ir]; k > 0;)\n {\n ydbl[k] = xdbl[k] + shift;\n k = next[k];\n }\n\n for (k = 0, m = 0; k < 12; ++k)\n {\n x = xdbl[k];\n y2 = ydbl[k] - shift;\n if (y2 > x)\n\ty2 -= sone_bit;\n y1 = (x - y2) * sbase;\n\n xflt[m++] = (float) y1;\n xflt[m++] = (float) y2;\n }\n\n state->ir = ir;\n state->is = 2 * ir;\n state->is_old = 2 * ir;\n state->jr = jr;\n state->carry = carry;\n}\n\n\nstatic inline double\nranlxs_get_double (void *vstate)\n{\n ranlxs_state_t *state = (ranlxs_state_t *) vstate;\n\n const unsigned int is = snext[state->is];\n\n state->is = is;\n\n if (is == state->is_old)\n increment_state (state);\n\n return state->xflt[state->is];\n}\n\nstatic unsigned long int\nranlxs_get (void *vstate)\n{\n return ranlxs_get_double (vstate) * 16777216.0;\t/* 2^24 */\n}\n\nstatic void\nranlxs_set_lux (void *vstate, unsigned long int s, unsigned int luxury)\n{\n ranlxs_state_t *state = (ranlxs_state_t *) vstate;\n\n int ibit, jbit, i, k, m, 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 (m = 1; m <= 48; ++m)\n\t{\n\t y = (double) xbit[ibit];\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 = 0;\n state->jr = 7;\n state->is = 23;\n state->is_old = 0;\n state->pr = luxury;\n}\n\nstatic void\nranlxs0_set (void *vstate, unsigned long int s)\n{\n ranlxs_set_lux (vstate, s, 109);\n}\n\nvoid\nranlxs1_set (void *vstate, unsigned long int s)\n{\n ranlxs_set_lux (vstate, s, 202);\n}\n\nstatic void\nranlxs2_set (void *vstate, unsigned long int s)\n{\n ranlxs_set_lux (vstate, s, 397);\n}\n\n\nstatic const gsl_rng_type ranlxs0_type =\n{\"ranlxs0\",\t\t\t/* name */\n 0x00ffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlxs_state_t),\n &ranlxs0_set,\n &ranlxs_get,\n &ranlxs_get_double};\n\nstatic const gsl_rng_type ranlxs1_type =\n{\"ranlxs1\",\t\t\t/* name */\n 0x00ffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlxs_state_t),\n &ranlxs1_set,\n &ranlxs_get,\n &ranlxs_get_double};\n\nstatic const gsl_rng_type ranlxs2_type =\n{\"ranlxs2\",\t\t\t/* name */\n 0x00ffffffUL,\t\t\t/* RAND_MAX */\n 0,\t\t\t\t/* RAND_MIN */\n sizeof (ranlxs_state_t),\n &ranlxs2_set,\n &ranlxs_get,\n &ranlxs_get_double};\n\nconst gsl_rng_type *gsl_rng_ranlxs0 = &ranlxs0_type;\nconst gsl_rng_type *gsl_rng_ranlxs1 = &ranlxs1_type;\nconst gsl_rng_type *gsl_rng_ranlxs2 = &ranlxs2_type;\n", "meta": {"hexsha": "0a3275defc788925c55116be70af9d4a8276321d", "size": 6662, "ext": "c", "lang": "C", "max_stars_repo_path": "code/em/treba/gsl-1.0/rng/ranlxs.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/ranlxs.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/ranlxs.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.9867986799, "max_line_length": 83, "alphanum_fraction": 0.5728009607, "num_tokens": 2470, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953506426082, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.2506222781893201}}