{"text": "#ifdef __cplusplus\nextern \"C\"\n{\n#endif // __cplusplus\n#ifdef USE_BLAS\n#include \n\nint _use_blas()\n{\n return 1;\n}\n#else // USE_BLAS\n#include \n\n#if defined(_MSC_VER)\n#define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))\n#elif defined(__GNUC__)\n#define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))\n#endif\n\nfloat cblas_snrm2(const int N, const float *m1, const int incX)\n{\n if (N % 4 != 0) {\n fprintf(stderr, \"cblas_snrm2() expects N to be a multiple of 4.\\n\");\n exit(EXIT_FAILURE);\n }\n\n float norm = 0;\n ALIGNAS(16) float z[4];\n __m128 X;\n __m128 Z = _mm_setzero_ps();\n\n for (int i=0; i\n#include \n#include \n#include \n#include \n#include \n\nconst int SAMPLENUM = 1000;\nint obsnum;\ngsl_rng * r;\n\ntypedef struct {\n\tint prey;\n\tint predator;\n} lvstate;\n\ntypedef struct {\n\tdouble time;\n\tdouble rawdata;\n} obsdata;\n\nvoid simPrior(lvstate *simData);\nvoid rowsample(int *rows, double *w);\nvoid stepLV(lvstate *state, double *t0p, double *dtp, double *lvParam);\nvoid peturb(double *lvParam);\n\ndouble obsLik(lvstate *mystate, double obs) {\n\tconst double SIGMA = 10.0;\n\treturn log(gsl_ran_gaussian_pdf((obs - mystate->prey), SIGMA));\n}\n\nvoid callStepLV(lvstate *simData, double *t0p, double *dtp, double *lvParam) {\n\tint j;\n\tfor (j=0;jvpptuple == NULL) {\n\t\t(tempStateVec + 0)->vpptuple = (lvstate*) malloc(\n\t\t\t\tSAMPLENUM * sizeof(lvstate));\n\t\tif ((tempStateVec + 0)->vpptuple == NULL) {\n\t\t\tprintf(\"Fail to initiate myStateVec->vpptuple...Exit\");\n\t\t\tgoto freeMem;\n\t\t\t//free(tempStateVec);\n\t\t\t//goto error;\n\t\t}\n\t}\n\n\tmemset(tempStateVec[0].vpptuple, 0, SAMPLENUM * sizeof(lvstate));\n\tfor (j = 0; j < SAMPLENUM; j++) {\n\t\t((tempStateVec + 0)->vpptuple + j)->predator = (simData + j)->predator;\n\t\t((tempStateVec + 0)->vpptuple + j)->prey = (simData + j)->prey;\n\t}\n\n\tfor (i = 1; i < obsnum; i++) {\n\t\tcurTime = myobsdata[i - 1].time;\n\n\t\twSum = 0.0;\n\n\t\tif ((tempStateVec + i)->vpptuple == NULL) {\n\t\t\t//printf(\"init temp \\n\");\n\t\t\t(tempStateVec + i)->vpptuple = (lvstate*) malloc(\n\t\t\t\t\tSAMPLENUM * sizeof(lvstate));\n\t\t\tif ((tempStateVec + i)->vpptuple == NULL) {\n\t\t\t\tprintf(\"Fail to initiate myStateVec->vpptuple...Exit\");\n\t\t\t\tgoto freeMem;\n\t\t\t}\n\t\t\tmemset((tempStateVec + i)->vpptuple, 0,\n\t\t\t\t\tSAMPLENUM * sizeof(lvstate));\n\t\t}\n\n\t\t//printf(\"tempvec 1 %i\\n\", ((tempStateVec+0)->vpptuple+1)->prey);\n\t\tcallStepLV(simData, &curTime, &delTime, lvParam);\n\n\t\tfor (j = 0; j < SAMPLENUM; j++) {\n\t\t\t//stepLV(simData + j, &curTime, &delTime, lvParam);\n\t\t\t((tempStateVec + i)->vpptuple + j)->predator =\n\t\t\t\t\t(simData + j)->predator;\n\t\t\t((tempStateVec + i)->vpptuple + j)->prey = (simData + j)->prey;\n\t\t\t//printf(\"tempState %i vpptuple %i , %p\\n\", i,j,(tempStateVec+i)->vpptuple+j);\n\t\t\tlw[j] = obsLik(((tempStateVec + i)->vpptuple + j),\n\t\t\t\t\tmyobsdata[i].rawdata);\n\n\t\t\tif (j == 0) {\n\t\t\t\tmaxLw = lw[0];\n\t\t\t} else {\n\t\t\t\tif (lw[j] > maxLw) {\n\t\t\t\t\tmaxLw = lw[j];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (l = 0; l < SAMPLENUM; l++) {\n\t\t\tw[l] = exp(lw[l] - maxLw);\n\t\t\twSum = wSum + w[l];\n\t\t}\n\t\trowsample(rows, w);\n\n\t\t//reorganize the vector with only keeping the rows in 'rows'\n\t\tfor (k = 0; k <= i; k++) {\n\t\t\tif ((myStateVec + k)->vpptuple == NULL) {\n\t\t\t\t//printf(\"init mystatevec \\n\");\n\t\t\t\t(myStateVec + k)->vpptuple = (lvstate*) malloc(\n\t\t\t\t\t\tSAMPLENUM * sizeof(lvstate));\n\t\t\t\tif ((myStateVec + k)->vpptuple == NULL) {\n\t\t\t\t\tprintf(\"Fail to initiate myStateVec->vpptuple...Exit\");\n\t\t\t\t\tgoto freeMem;\n\t\t\t\t}\n\t\t\t}\n//\t\t\tmemset(myStateVec[k].vpptuple,0,SAMPLENUM * sizeof(lvstate));\n\n\t\t\tfor (j = 0; j < SAMPLENUM; j++) {\n\t\t\t\t((myStateVec + k)->vpptuple + j)->predator =\n\t\t\t\t\t\t((tempStateVec + k)->vpptuple + rows[j])->predator;\n\t\t\t\t((myStateVec + k)->vpptuple + j)->prey =\n\t\t\t\t\t\t((tempStateVec + k)->vpptuple + rows[j])->prey;\n\t\t\t\t//printf(\"row %i %i,%i,%i,%i,%i\\n\", i,k,j,rows[j],((myStateVec+k)->vpptuple+j)->prey,((tempStateVec+k)->vpptuple+rows[j])->prey);\n\t\t\t}\n\t\t\tfor (j = 0; j < SAMPLENUM; j++) {\n\t\t\t\t((tempStateVec + k)->vpptuple + j)->predator =\n\t\t\t\t\t\t((myStateVec + k)->vpptuple + j)->predator;\n\t\t\t\t((tempStateVec + k)->vpptuple + j)->prey =\n\t\t\t\t\t\t((myStateVec + k)->vpptuple + j)->prey;\n\t\t\t}\n\t\t}\n\t\tfor (j = 0; j < SAMPLENUM; j++) {\n\t\t\tsimData[j].predator = ((myStateVec + i)->vpptuple + j)->predator;\n\t\t\tsimData[j].prey = ((myStateVec + i)->vpptuple + j)->prey;\n\t\t}\n\t\tlikehood = likehood + maxLw + log(wSum / SAMPLENUM);\n\t\t*ll = likehood;\n\t\trows[SAMPLENUM] = NULL;\n\t}\n\n\tfor (i = 0; i < obsnum; i++) {\n\t\tppstate[i].prey = ((myStateVec + i)->vpptuple + 0)->prey;\n\t\tppstate[i].predator = ((myStateVec + i)->vpptuple + 0)->predator;\n\t}\n\n\tfreeMem:\n\t//printf(\"free mem...\");\n\tif (myStateVec != NULL) {\n\t\t//printf(\"free mem 2...\");\n\t\tfor (i = 0; ((myStateVec + i)->vpptuple != NULL) && i < obsnum; i++) {\n\t\t\t//printf(\"free myStateVec...i %i\\n\", i);\n\t\t\tfree((myStateVec + i)->vpptuple);\n\t\t\t(myStateVec + i)->vpptuple = NULL;\n\t\t}\n\t\tfree(myStateVec);\n\t\tmyStateVec = NULL;\n\t}\n\tif (tempStateVec != NULL) {\n\t\tfor (i = 0; NULL != (tempStateVec + i)->vpptuple && i < obsnum; i++) {\n\t\t\t//printf(\"free tempStateVec...i %i\\n\", i);\n\t\t\tfree((tempStateVec + i)->vpptuple);\n\t\t\t(tempStateVec + i)->vpptuple = NULL;\n\t\t}\n\t\tfree(tempStateVec);\n\t\ttempStateVec = NULL;\n\t}\n\tif (simData != NULL) {\n\t\tfree(simData);\n\t\tsimData = NULL;\n\t}\n\n}\n\nvoid stepLV(lvstate *state, double *t0p, double *dtp, double *lvParam) {\n\t//printf(\"Starting stepLV...\\n\");\n\tregister double t0 = *t0p, dt = *dtp, t;\n\tregister double h0, h1, h2, h3, u, l0, l1, l2;\n\tregister int prey, predator;\n\tprey = state->prey;\n\tpredator = state->predator;\n\tl0 = lvParam[0];\n\tl1 = lvParam[1];\n\tl2 = lvParam[2];\n\n\twhile (dt > 0) {\n\t\th1 = l0 * prey;\n\t\th2 = l1 * prey * predator;\n\t\th3 = l2 * predator;\n\t\th0 = h1 + h2 + h3;\n\n\t\tif ((h0 < (1e-10)) || (prey >= 1000000))\n\t\t\tt = 1e99;\n\t\telse {\n\t\t\tt = gsl_ran_exponential(r, 1/h0);\n\t\t}\n\t\tif (t > dt) {\n\t\t\tstate->prey = prey;\n\t\t\tstate->predator = predator;\n\t\t\treturn;\n\t\t} else {\n\t\t\tu = gsl_rng_uniform(r);\n\t\t\tif (u < (h1 / h0)) {\n\t\t\t\tprey = prey + 1;\n\t\t\t\tt0 = t0 + t;\n\t\t\t\tdt = dt - t;\n\t\t\t} else if (u < ((h1 + h2) / h0)) {\n\t\t\t\tprey = prey - 1;\n\t\t\t\tpredator = predator + 1;\n\t\t\t\tt0 = t0 + t;\n\t\t\t\tdt = dt - t;\n\t\t\t} else {\n\t\t\t\tpredator = predator - 1;\n\t\t\t\tt0 = t0 + t;\n\t\t\t\tdt = dt - t;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn;\n}\n\n//mcmc process\nvoid runPmmhPath(int its, double *lvParam, double *obslik, lvstate ppstate[16],\n\t\tobsdata *myobsdata) {\n\t//printf(\"Starting runPmmhPath...\\n\");\n\tint i, j;\n\tdouble propParam[3];\n\tdouble curParam[3];\n\tdouble ll;\n\tdouble propMll, curMll = -1e99;\n\tlvstate curPath[obsnum];\n\tlvstate propPath[obsnum];\n\n\tFILE *fp = fopen(\"mcmc-out.txt\", \"wab+\");\n\tif (fp == NULL) {\n\t\tprintf(\"file is null.\\n\");\n\t\treturn;\n\t}\n\tfprintf(fp, \"th1,th2,th3,\");\n\tfor (i = 0; i <= 30; i++) {\n\t\tif ((i % 2) == 0) {\n\t\t\tif (i == 30) {\n\t\t\t\tfprintf(fp, \"x%i,y%i\", i, i);\n\t\t\t} else {\n\t\t\t\tfprintf(fp, \"x%i,y%i,\", i, i);\n\t\t\t}\n\t\t}\n\t}\n\tfprintf(fp, \"\\n\");\n\n\tmemcpy(curPath, ppstate, sizeof(lvstate) * obsnum);\n\tmemcpy(curParam, lvParam, sizeof(double) * 3);\n\tfor (i = its; i > 0; i--) {\n\t\t//calculate measurements and decide moving to next state or not\n\t\tmemcpy(propParam, curParam, sizeof(double) * 3);\n\t\tpeturb(propParam);\n\n\t\tpfPropPar(propPath, myobsdata, propParam, &ll);\n\t\tpropMll = ll;\n\t\tif (log(gsl_ran_flat(r, 0.0, 1.0)) < (propMll - curMll)) {\n\t\t\tcurMll = propMll;\n\t\t\tmemcpy(curParam, propParam, sizeof(double) * 3);\n\t\t\tmemcpy(curPath, propPath, sizeof(lvstate) * obsnum);\n\t\t}\n\t\t//write current parameters and state sequence into output\n\t\tfprintf(fp, \"%f,%f,%f,\", curParam[0], curParam[1], curParam[2]);\n\n\t\tfor (j = 0; j < obsnum; j++) {\n\t\t\tif (j == (obsnum - 1)) {\n\t\t\t\tfprintf(fp, \"%i,%i\", (int)curPath[j].prey, (int)curPath[j].predator);\n\t\t\t} else {\n\t\t\t\tfprintf(fp, \"%i,%i,\", (int)curPath[j].prey, (int)curPath[j].predator);\n\t\t\t}\n\t\t}\n\t\tfprintf(fp, \"\\n\");\n\t}\n\tfclose(fp);\n}\n\nvoid rowsample(int *rows, double *w) {\n\t//printf(\"Starting rowsample...\\n\");\n\tgsl_ran_discrete_t * grdp;\n\tint row;\n\tint i;\n\tgrdp = gsl_ran_discrete_preproc(SAMPLENUM, w);\n\tfor (i = 0; i < SAMPLENUM; i++) {\n\n\t\trow = (int) gsl_ran_discrete(r, grdp);\n\t\trows[i] = row;\n\n\t}\n\tgsl_ran_discrete_free(grdp);\n\treturn;\n}\n\nvoid peturb(double *lvParam) {\n\t//printf(\"Starting peturb...\\n\");\n\n\tconst double SIGMA = 0.01;\n\t//printf(\"lvParam_before %f, %f, %f\\n\", lvParam[0], lvParam[1], lvParam[2]);\n\tlvParam[0] = lvParam[0] * exp(gsl_ran_gaussian(r, SIGMA));\n\tlvParam[1] = lvParam[1] * exp(gsl_ran_gaussian(r, SIGMA));\n\tlvParam[2] = lvParam[2] * exp(gsl_ran_gaussian(r, SIGMA));\n\t//printf(\"lvParam_after %f, %f, %f\\n\", lvParam[0], lvParam[1], lvParam[2]);\n}\n\n//to get the prior simulate value of prey and predator\nvoid simPrior(lvstate *simData) {\n\t//printf(\"Starting simPrior...\\n\");\n\tint i;\n\n\tconst double PREY_MEAN = 50.0;\n\tconst double PRED_MEAN = 100.0;\n\n\tfor (i = 0; i < SAMPLENUM; i++) {\n\t\tsimData[i].prey = gsl_ran_poisson(r, PREY_MEAN);\n\t\tsimData[i].predator = gsl_ran_poisson(r, PRED_MEAN);\n\t\t//printf(\"simPrior %i\\n\", simData[i].prey);\n\t}\n\t//printf(\"End simPrior...\\n\");\n\n}\n\nvoid runModel(int its) {\n\tobsnum = 16;\n\tobsdata myobsdata[obsnum];\n\tlvstate mylvstate[obsnum];\n\tdouble ll = 0.0;\n\n\tdouble lvParam[3] = { 1.0, 0.005, 0.6 };\n\n\t//produce time list(with even number in)\n\tint i;\n\tint j = 0;\n\n\tfor (i = 0; i <= 30; i++) {\n\t\tif ((i % 2) == 0) {\n\t\t\tmyobsdata[j].time = (double) i;\n\t\t\tj++;\n\t\t}\n\t}\n\n\t//read external txt file\n\tFILE *file = fopen(\"LVpreyNoise10.txt\", \"r\");\n\tchar line[1024];\n\tif (file == NULL) {\n\t\tprintf(\"file is null.\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tif (file != NULL) {\n\t\ti = 0;\n\t\twhile (fgets(line, 1024, file)) {\n\t\t\tmyobsdata[i].rawdata = atof(line);\n\t\t\ti++;\n\t\t}\n\t\tfclose(file);\n\t}\n\trunPmmhPath(its, lvParam, &ll, mylvstate, myobsdata);\n\treturn;\n}\n\nint main(int argc, char *argv[]) {\n\tconst gsl_rng_type * T;\n\tlong seed;\n\tgsl_rng_env_setup();\n\tT = gsl_rng_default;\n\tr = gsl_rng_alloc(T);\n\tseed = time(NULL) * getpid(); // set seed\n\tgsl_rng_set(r, seed);\n\tclock_t begin, end;\n\tdouble time_spent;\n\n\tbegin = clock();\n\tint its;\n\tprintf(\"Starting main...\\n\");\n\n\tif (argc == 1) {\n\t\tits = 5;\n\t} else {\n\t\tits = atoi(argv[1]);\n\t}\n\trunModel(its);\n\n\tgsl_rng_free(r);\n\n\tend = clock();\n\ttime_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n\tprintf(\"Time consuming in total is %f\\n\", time_spent);\n\n\tprintf(\"Running for %i\", its);\n\tprintf(\" iterations, Done.\");\n\treturn 0;\n}\n", "meta": {"hexsha": "fc0a92ef6cd26feaa8c872f843b1d960bf8f2e90", "size": 10988, "ext": "c", "lang": "C", "max_stars_repo_path": "MPI/main/bayeskit.c", "max_stars_repo_name": "scania/scania-pmcmc", "max_stars_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-31T04:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-31T04:07:03.000Z", "max_issues_repo_path": "MPI/main/bayeskit.c", "max_issues_repo_name": "scania/scania-pmcmc", "max_issues_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MPI/main/bayeskit.c", "max_forks_repo_name": "scania/scania-pmcmc", "max_forks_repo_head_hexsha": "e1d0a15de73136355afb0e89baa5dcd8d08bad30", "max_forks_repo_licenses": ["Apache-2.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.0867579909, "max_line_length": 133, "alphanum_fraction": 0.6063887878, "num_tokens": 3934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792044, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.24795610126175752}} {"text": "/* +---------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http://www.mrpt.org/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http://www.mrpt.org/Authors - All rights reserved. |\n | Released under BSD License. See details in http://www.mrpt.org/License |\n +---------------------------------------------------------------------------+ */\n\n#include \"xform.h\"\n#include \"imgfeatures.h\"\n#include \"utils.h\"\n\n//#include \"cxcore.h\"\n//#include \n// Universal include for all versions of OpenCV\n#include \n\n#include \n#include \n#include \n\n#include \n\n/************************* Local Function Prototypes *************************/\n\nstatic __inline struct feature* get_match( struct feature*, int );\nint get_matched_features( struct feature*, int, int, struct feature*** );\nint calc_min_inliers( int, int, double, double );\nstruct feature** draw_ransac_sample( struct feature**, int, int, gsl_rng* );\nvoid extract_corresp_pts( struct feature**, int, int, CvPoint2D64f**,\n\t\t\t\t\t\t CvPoint2D64f** );\nint find_consensus( struct feature**, int, int, CvMat*, ransac_err_fn,\n\t\t\t\t double, struct feature*** );\nstatic __inline void release_mem( CvPoint2D64f*, CvPoint2D64f*,\nstruct feature** );\n\n/********************** Functions prototyped in xform.h **********************/\n\n\n/*\nCalculates a best-fit image transform from image feature correspondences\nusing RANSAC.\n\nFor more information refer to:\n\nFischler, M. A. and Bolles, R. C. Random sample consensus: a paradigm for\nmodel fitting with applications to image analysis and automated cartography.\nCommunications of the ACM, 24, 6 (1981), pp. 381--395.\n\n@param features an array of features; only features with a non-NULL match\n\tof type mtype are used in homography computation\n@param n number of features in feat\n@param mtype determines which of each feature's match fields to use\n\tfor model computation; should be one of FEATURE_FWD_MATCH,\n\tFEATURE_BCK_MATCH, or FEATURE_MDL_MATCH; if this is FEATURE_MDL_MATCH,\n\tcorrespondences are assumed to be between a feature's img_pt field\n\tand its match's mdl_pt field, otherwise correspondences are assumed to\n\tbe between the the feature's img_pt field and its match's img_pt field\n@param xform_fn pointer to the function used to compute the desired\n\ttransformation from feature correspondences\n@param m minimum number of correspondences necessary to instantiate the\n\tmodel computed by xform_fn\n@param p_badxform desired probability that the final transformation\n\treturned by RANSAC is corrupted by outliers (i.e. the probability that\n\tno samples of all inliers were drawn)\n@param err_fn pointer to the function used to compute a measure of error\n\tbetween putative correspondences and a computed model\n@param err_tol correspondences within this distance of a computed model are\n\tconsidered as inliers\n@param inliers if not NULL, output as an array of pointers to the final\n\tset of inliers\n@param n_in if not NULL and \\a inliers is not NULL, output as the final\n\tnumber of inliers\n\n@return Returns a transformation matrix computed using RANSAC or NULL\n\ton error or if an acceptable transform could not be computed.\n*/\nCvMat* ransac_xform( struct feature* features, int n, int mtype,\n\t\t\t\t\transac_xform_fn xform_fn, int m, double p_badxform,\n\t\t\t\t\transac_err_fn err_fn, double err_tol,\nstruct feature*** inliers, int* n_in )\n{\n\tstruct feature** matched, ** sample, ** consensus, ** consensus_max = NULL;\n\tstruct ransac_data* rdata;\n\tCvPoint2D64f* pts, * mpts;\n\tCvMat* M = NULL;\n\tgsl_rng* rng;\n\tdouble p, in_frac = RANSAC_INLIER_FRAC_EST;\n\tint i, nm, in, in_min, in_max = 0, k = 0;\n\n\tnm = get_matched_features( features, n, mtype, &matched );\n\tif( nm < m )\n\t{\n\t\tfprintf( stderr, \"Warning: not enough matches to compute xform, %s\" \\\n\t\t\t\" line %d\\n\", __FILE__, __LINE__ );\n\t\tgoto end;\n\t}\n\n\t/* initialize random number generator */\n\trng = gsl_rng_alloc( gsl_rng_mt19937 );\n\tgsl_rng_set( rng, time(NULL) );\n\n\tin_min = calc_min_inliers( nm, m, RANSAC_PROB_BAD_SUPP, p_badxform );\n\tp = pow( 1.0 - pow( in_frac, m ), k );\n\ti = 0;\n\twhile( p > p_badxform )\n\t{\n\t\tsample = draw_ransac_sample( matched, nm, m, rng );\n\t\textract_corresp_pts( sample, m, mtype, &pts, &mpts );\n\t\tM = xform_fn( pts, mpts, m );\n\t\tif( ! M )\n\t\t\tgoto iteration_end;\n\t\tin = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus);\n\t\tif( in > in_max )\n\t\t{\n\t\t\tif( consensus_max )\n\t\t\t\tfree( consensus_max );\n\t\t\tconsensus_max = consensus;\n\t\t\tin_max = in;\n\t\t\tin_frac = (double)in_max / nm;\n\t\t}\n\t\telse\n\t\t\tfree( consensus );\n\t\tcvReleaseMat( &M );\n\niteration_end:\n\t\trelease_mem( pts, mpts, sample );\n\t\tp = pow( 1.0 - pow( in_frac, m ), ++k );\n\t}\n\n\t/* calculate final transform based on best consensus set */\n\tif( in_max >= in_min )\n\t{\n\t\textract_corresp_pts( consensus_max, in_max, mtype, &pts, &mpts );\n\t\tM = xform_fn( pts, mpts, in_max );\n\t\tin = find_consensus( matched, nm, mtype, M, err_fn, err_tol, &consensus);\n\t\tcvReleaseMat( &M );\n\t\trelease_mem( pts, mpts, consensus_max );\n\t\textract_corresp_pts( consensus, in, mtype, &pts, &mpts );\n\t\tM = xform_fn( pts, mpts, in );\n\t\tif( inliers )\n\t\t{\n\t\t\t*inliers = consensus;\n\t\t\tconsensus = NULL;\n\t\t}\n\t\tif( n_in )\n\t\t\t*n_in = in;\n\t\trelease_mem( pts, mpts, consensus );\n\t}\n\telse if( consensus_max )\n\t{\n\t\tif( inliers )\n\t\t\t*inliers = NULL;\n\t\tif( n_in )\n\t\t\t*n_in = 0;\n\t\tfree( consensus_max );\n\t}\n\n\tgsl_rng_free( rng );\nend:\n\tfor( i = 0; i < nm; i++ )\n\t{\n\t\trdata = feat_ransac_data( matched[i] );\n\t\tmatched[i]->feature_data = rdata->orig_feat_data;\n\t\tfree( rdata );\n\t}\n\tfree( matched );\n\treturn M;\n}\n\n\n\n/*\nCalculates a least-squares planar homography from point correspondeces.\n\n@param pts array of points\n@param mpts array of corresponding points; each pts[i], i=0..n-1, corresponds\n\tto mpts[i]\n@param n number of points in both pts and mpts; must be at least 4\n\n@return Returns the 3 x 3 least-squares planar homography matrix that\n\ttransforms points in pts to their corresponding points in mpts or NULL if\n\tfewer than 4 correspondences were provided\n*/\nCvMat* lsq_homog( CvPoint2D64f* pts, CvPoint2D64f* mpts, int n )\n{\n\tCvMat* H, * A, * B, X;\n\tdouble x[9];\n\tint i;\n\n\tif( n < 4 )\n\t{\n\t\tfprintf( stderr, \"Warning: too few points in lsq_homog(), %s line %d\\n\",\n\t\t\t__FILE__, __LINE__ );\n\t\treturn NULL;\n\t}\n\n\t/* set up matrices so we can unstack homography into X; AX = B */\n\tA = cvCreateMat( 2*n, 8, CV_64FC1 );\n\tB = cvCreateMat( 2*n, 1, CV_64FC1 );\n\tX = cvMat( 8, 1, CV_64FC1, x );\n\tH = cvCreateMat(3, 3, CV_64FC1);\n\tcvZero( A );\n\tfor( i = 0; i < n; i++ )\n\t{\n\t\tcvmSet( A, i, 0, pts[i].x );\n\t\tcvmSet( A, i+n, 3, pts[i].x );\n\t\tcvmSet( A, i, 1, pts[i].y );\n\t\tcvmSet( A, i+n, 4, pts[i].y );\n\t\tcvmSet( A, i, 2, 1.0 );\n\t\tcvmSet( A, i+n, 5, 1.0 );\n\t\tcvmSet( A, i, 6, -pts[i].x * mpts[i].x );\n\t\tcvmSet( A, i, 7, -pts[i].y * mpts[i].x );\n\t\tcvmSet( A, i+n, 6, -pts[i].x * mpts[i].y );\n\t\tcvmSet( A, i+n, 7, -pts[i].y * mpts[i].y );\n\t\tcvmSet( B, i, 0, mpts[i].x );\n\t\tcvmSet( B, i+n, 0, mpts[i].y );\n\t}\n\tcvSolve( A, B, &X, CV_SVD );\n\tx[8] = 1.0;\n\tX = cvMat( 3, 3, CV_64FC1, x );\n\tcvConvert( &X, H );\n\n\tcvReleaseMat( &A );\n\tcvReleaseMat( &B );\n\treturn H;\n}\n\n\n\n/*\nCalculates the transfer error between a point and its correspondence for\na given homography, i.e. for a point x, it's correspondence x', and\nhomography H, computes d(x', Hx)^2.\n\n@param pt a point\n@param mpt pt's correspondence\n@param H a homography matrix\n\n@return Returns the transfer error between pt and mpt given H\n*/\ndouble homog_xfer_err( CvPoint2D64f pt, CvPoint2D64f mpt, CvMat* H )\n{\n\tCvPoint2D64f xpt = persp_xform_pt( pt, H );\n\n\treturn sqrt( dist_sq_2D( xpt, mpt ) );\n}\n\n\n\n/*\nPerforms a perspective transformation on a single point. That is, for a\npoint (x, y) and a 3 x 3 matrix T this function returns the point\n(u, v), where\n\n[x' y' w']^T = T * [x y 1]^T,\n\nand\n\n(u, v) = (x'/w', y'/w').\n\nNote that affine transforms are a subset of perspective transforms.\n\n@param pt a 2D point\n@param T a perspective transformation matrix\n\n@return Returns the point (u, v) as above.\n*/\nCvPoint2D64f persp_xform_pt( CvPoint2D64f pt, CvMat* T )\n{\n\tCvMat XY, UV;\n\tdouble xy[3] = { pt.x, pt.y, 1.0 }, uv[3] = { 0 };\n\tCvPoint2D64f rslt;\n\n\tcvInitMatHeader( &XY, 3, 1, CV_64FC1, xy, CV_AUTOSTEP );\n\tcvInitMatHeader( &UV, 3, 1, CV_64FC1, uv, CV_AUTOSTEP );\n\tcvMatMul( T, &XY, &UV );\n\trslt = cvPoint2D64f( uv[0] / uv[2], uv[1] / uv[2] );\n\n\treturn rslt;\n}\n\n\n/************************ Local funciton definitions *************************/\n\n/*\nReturns a feature's match according to a specified match type\n\n@param feat feature\n@param mtype match type, one of FEATURE_FWD_MATCH, FEATURE_BCK_MATCH, or\nFEATURE_MDL_MATCH\n\n@return Returns feat's match corresponding to mtype or NULL for bad mtype\n*/\nstatic __inline struct feature* get_match( struct feature* feat, int mtype )\n{\n\tif( mtype == FEATURE_MDL_MATCH )\n\t\treturn feat->mdl_match;\n\tif( mtype == FEATURE_BCK_MATCH )\n\t\treturn feat->bck_match;\n\tif( mtype == FEATURE_FWD_MATCH )\n\t\treturn feat->fwd_match;\n\treturn NULL;\n}\n\n\n\n/*\nFinds all features with a match of a specified type and stores pointers\nto them in an array. Additionally initializes each matched feature's\nfeature_data field with a ransac_data structure.\n\n@param features array of features\n@param n number of features in features\n@param mtype match type, one of FEATURE_{FWD,BCK,MDL}_MATCH\n@param matched output as an array of pointers to features with a match of\nthe specified type\n\n@return Returns the number of features output in matched.\n*/\nint get_matched_features( struct feature* features, int n, int mtype,\nstruct feature*** matched )\n{\n\tstruct feature** _matched;\n\tstruct ransac_data* rdata;\n\tint i, m = 0;\n\n\t_matched = calloc( n, sizeof( struct feature* ) );\n\tfor( i = 0; i < n; i++ )\n\t\tif( get_match( features + i, mtype ) )\n\t\t{\n\t\t\trdata = malloc( sizeof( struct ransac_data ) );\n\t\t\tmemset( rdata, 0, sizeof( struct ransac_data ) );\n\t\t\trdata->orig_feat_data = features[i].feature_data;\n\t\t\t_matched[m] = features + i;\n\t\t\t_matched[m]->feature_data = rdata;\n\t\t\tm++;\n\t\t}\n\t\t*matched = _matched;\n\t\treturn m;\n}\n\n\n\n/*\nCalculates the minimum number of inliers as a function of the number of\nputative correspondences. Based on equation (7) in\n\nChum, O. and Matas, J. Matching with PROSAC -- Progressive Sample Consensus.\nIn Conference on Computer Vision and Pattern Recognition (CVPR),\n(2005), pp. 220--226.\n\n@param n number of putative correspondences\n@param m min number of correspondences to compute the model in question\n@param p_badsupp prob. that a bad model is supported by a correspondence\n@param p_badxform desired prob. that the final transformation returned is bad\n\n@return Returns the minimum number of inliers required to guarantee, based\n\ton p_badsupp, that the probability that the final transformation returned\n\tby RANSAC is less than p_badxform\n*/\nint calc_min_inliers( int n, int m, double p_badsupp, double p_badxform )\n{\n\tdouble pi, sum;\n\tint i, j;\n\n\tfor( j = m+1; j <= n; j++ )\n\t{\n\t\tsum = 0;\n\t\tfor( i = j; i <= n; i++ )\n\t\t{\n\t\t\tpi = ( i - m ) * log( p_badsupp ) + ( n - i + m ) * log( 1.0 - p_badsupp ) +\n\t\t\t\tgsl_sf_lnchoose( n - m, i - m );\n\t\t\tsum += exp( pi );\n\t\t}\n\t\tif( sum < p_badxform )\n\t\t\tbreak;\n\t}\n\treturn j;\n}\n\n\n\n/*\nDraws a RANSAC sample from a set of features.\n\n@param features array of pointers to features from which to sample\n@param n number of features in features\n@param m size of the sample\n@param rng random number generator used to sample\n\n@return Returns an array of pointers to the sampled features; the sampled\n\tfield of each sampled feature's ransac_data is set to 1\n*/\nstruct feature** draw_ransac_sample( struct feature** features, int n,\n\t\t\t\t\t\t\t\t\tint m, gsl_rng* rng )\n{\n\tstruct feature** sample, * feat;\n\tstruct ransac_data* rdata;\n\tint i, x;\n\n\tfor( i = 0; i < n; i++ )\n\t{\n\t\trdata = feat_ransac_data( features[i] );\n\t\trdata->sampled = 0;\n\t}\n\n\tsample = calloc( m, sizeof( struct feature* ) );\n\tfor( i = 0; i < m; i++ )\n\t{\n\t\tdo\n\t\t{\n\t\t\tx = gsl_rng_uniform_int( rng, n );\n\t\t\tfeat = features[x];\n\t\t\trdata = feat_ransac_data( feat );\n\t\t}\n\t\twhile( rdata->sampled );\n\t\tsample[i] = feat;\n\t\trdata->sampled = 1;\n\t}\n\n\treturn sample;\n}\n\n\n\n/*\nExtrancs raw point correspondence locations from a set of features\n\n@param features array of features from which to extract points and match\n\tpoints; each of these is assumed to have a match of type mtype\n@param n number of features\n@param mtype match type; if FEATURE_MDL_MATCH correspondences are assumed\n\tto be between each feature's img_pt field and it's match's mdl_pt field,\n\totherwise, correspondences are assumed to be between img_pt and img_pt\n@param pts output as an array of raw point locations from features\n@param mpts output as an array of raw point locations from features' matches\n*/\nvoid extract_corresp_pts( struct feature** features, int n, int mtype,\n\t\t\t\t\t\t CvPoint2D64f** pts, CvPoint2D64f** mpts )\n{\n\tstruct feature* match;\n\tCvPoint2D64f* _pts, * _mpts;\n\tint i;\n\n\t_pts = calloc( n, sizeof( CvPoint2D64f ) );\n\t_mpts = calloc( n, sizeof( CvPoint2D64f ) );\n\n\tif( mtype == FEATURE_MDL_MATCH )\n\t\tfor( i = 0; i < n; i++ )\n\t\t{\n\t\t\tmatch = get_match( features[i], mtype );\n\t\t\tif( ! match )\n\t\t\t\tfatal_error( \"feature does not have match of type %d, %s line %d\",\n\t\t\t\t\t\t\tmtype, __FILE__, __LINE__ );\n\t\t\t_pts[i] = features[i]->img_pt;\n\t\t\t_mpts[i] = match->mdl_pt;\n\t\t}\n\n\telse\n\t\tfor( i = 0; i < n; i++ )\n\t\t{\n\t\t\tmatch = get_match( features[i], mtype );\n\t\t\tif( ! match )\n\t\t\t\tfatal_error( \"feature does not have match of type %d, %s line %d\",\n\t\t\t\t\t\t\tmtype, __FILE__, __LINE__ );\n\t\t\t_pts[i] = features[i]->img_pt;\n\t\t\t_mpts[i] = match->img_pt;\n\t\t}\n\n\t\t*pts = _pts;\n\t\t*mpts = _mpts;\n}\n\n\n\n/*\nFor a given model and error function, finds a consensus from a set of\nfeature correspondences.\n\n@param features set of pointers to features; every feature is assumed to\n\thave a match of type mtype\n@param n number of features in features\n@param mtype determines the match field of each feature against which to\n\tmeasure error; if this is FEATURE_MDL_MATCH, correspondences are assumed\n\tto be between the feature's img_pt field and the match's mdl_pt field;\n\totherwise matches are assumed to be between img_pt and img_pt\n@param M model for which a consensus set is being found\n@param err_fn error function used to measure distance from M\n@param err_tol correspondences within this distance of M are added to the\n\tconsensus set\n@param consensus output as an array of pointers to features in the\n\tconsensus set\n\n@return Returns the number of points in the consensus set\n*/\nint find_consensus( struct feature** features, int n, int mtype,\n\t\t\t\t CvMat* M, ransac_err_fn err_fn, double err_tol,\n\t\t\t\t struct feature*** consensus )\n{\n\tstruct feature** _consensus;\n\tstruct feature* match;\n\tCvPoint2D64f pt, mpt;\n\tdouble err;\n\tint i, in = 0;\n\n\t_consensus = calloc( n, sizeof( struct feature* ) );\n\n\tif( mtype == FEATURE_MDL_MATCH )\n\t\tfor( i = 0; i < n; i++ )\n\t\t{\n\t\t\tmatch = get_match( features[i], mtype );\n\t\t\tif( ! match )\n\t\t\t\tfatal_error( \"feature does not have match of type %d, %s line %d\",\n\t\t\t\t\t\t\tmtype, __FILE__, __LINE__ );\n\t\t\tpt = features[i]->img_pt;\n\t\t\tmpt = match->mdl_pt;\n\t\t\terr = err_fn( pt, mpt, M );\n\t\t\tif( err <= err_tol )\n\t\t\t\t_consensus[in++] = features[i];\n\t\t}\n\n\telse\n\t\tfor( i = 0; i < n; i++ )\n\t\t{\n\t\t\tmatch = get_match( features[i], mtype );\n\t\t\tif( ! match )\n\t\t\t\tfatal_error( \"feature does not have match of type %d, %s line %d\",\n\t\t\t\t\t\t\tmtype, __FILE__, __LINE__ );\n\t\t\tpt = features[i]->img_pt;\n\t\t\tmpt = match->img_pt;\n\t\t\terr = err_fn( pt, mpt, M );\n\t\t\tif( err <= err_tol )\n\t\t\t\t_consensus[in++] = features[i];\n\t\t}\n\t*consensus = _consensus;\n\treturn in;\n}\n\n\n\n/*\nReleases memory and reduces code size above\n\n@param pts1 an array of points\n@param pts2 an array of points\n@param features an array of pointers to features; can be NULL\n*/\nstatic __inline void release_mem( CvPoint2D64f* pts1, CvPoint2D64f* pts2,\nstruct feature** features )\n{\n\tfree( pts1 );\n\tfree( pts2 );\n\tif( features )\n\t\tfree( features );\n}\n", "meta": {"hexsha": "a144d6b8b5439240aebe3db6da58f9bb9a859eb1", "size": 16241, "ext": "c", "lang": "C", "max_stars_repo_path": "libs/vision/src/sift-hess/xform.c", "max_stars_repo_name": "amitsingh19975/mrpt", "max_stars_repo_head_hexsha": "451480f9815cc029ae427ed8067732606bcfbb43", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-11-19T16:18:09.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-16T02:13:43.000Z", "max_issues_repo_path": "libs/vision/src/sift-hess/xform.c", "max_issues_repo_name": "amitsingh19975/mrpt", "max_issues_repo_head_hexsha": "451480f9815cc029ae427ed8067732606bcfbb43", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/vision/src/sift-hess/xform.c", "max_forks_repo_name": "amitsingh19975/mrpt", "max_forks_repo_head_hexsha": "451480f9815cc029ae427ed8067732606bcfbb43", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-06-08T07:55:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T08:56:28.000Z", "avg_line_length": 29.105734767, "max_line_length": 83, "alphanum_fraction": 0.6689858999, "num_tokens": 4805, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.4148988457967688, "lm_q1q2_score": 0.24589668826323885}} {"text": "#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 \"ccl.h\"\n\n//\n// Macros for replacing relative paths\n#define EXPAND_STR(s) STRING(s)\n#define STRING(s) #s\n\n\nconst ccl_configuration default_config = {\n ccl_boltzmann_class, ccl_halofit, ccl_nobaryons,\n ccl_tinker10, ccl_duffy2008, ccl_emu_strict};\n\n\n//Precision parameters\n/**\n * Default relative precision if not otherwise specified\n */\n#define GSL_EPSREL 1E-4\n\n/**\n * Default number of iterations for integration and root-finding if not otherwise\n * specified\n */\n#define GSL_N_ITERATION 1000\n\n/**\n * Default number of Gauss-Kronrod points in QAG integration if not otherwise\n * specified\n */\n#define GSL_INTEGRATION_GAUSS_KRONROD_POINTS GSL_INTEG_GAUSS41\n\n/**\n * Relative precision in sigma_R calculations\n */\n#define GSL_EPSREL_SIGMAR 1E-5\n\n/**\n * Relative precision in k_NL calculations\n */\n#define GSL_EPSREL_KNL 1E-5\n\n/**\n * Relative precision in distance calculations\n */\n#define GSL_EPSREL_DIST 1E-6\n\n/**\n * Relative precision in growth calculations\n */\n#define GSL_EPSREL_GROWTH 1E-6\n\n/**\n * Relative precision in dNdz calculations\n */\n#define GSL_EPSREL_DNDZ 1E-6\n\nconst ccl_gsl_params default_gsl_params = {\n GSL_N_ITERATION, // N_ITERATION\n GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_GAUSS_KRONROD_POINTS\n GSL_EPSREL, // INTEGRATION_EPSREL\n GSL_INTEGRATION_GAUSS_KRONROD_POINTS,// INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS\n GSL_EPSREL, // INTEGRATION_LIMBER_EPSREL\n GSL_EPSREL_DIST, // INTEGRATION_DISTANCE_EPSREL\n GSL_EPSREL_SIGMAR, // INTEGRATION_SIGMAR_EPSREL\n GSL_EPSREL_KNL, // INTEGRATION_KNL_EPSREL\n GSL_EPSREL, // ROOT_EPSREL\n GSL_N_ITERATION, // ROOT_N_ITERATION\n GSL_EPSREL_GROWTH, // ODE_GROWTH_EPSREL\n 1E-6, // EPS_SCALEFAC_GROWTH\n 1E7, // HM_MMIN\n 1E17, // HM_MMAX\n 0.0, // HM_EPSABS\n 1E-4, // HM_EPSREL\n 1000, // HM_LIMIT\n GSL_INTEG_GAUSS41 // HM_INT_METHOD\n };\n\n#undef GSL_EPSREL\n#undef GSL_N_ITERATION\n#undef GSL_INTEGRATION_GAUSS_KRONROD_POINTS\n#undef GSL_EPSREL_SIGMAR\n#undef GSL_EPSREL_KNL\n#undef GSL_EPSREL_DIST\n#undef GSL_EPSREL_GROWTH\n#undef GSL_EPSREL_DNDZ\n\n\nconst ccl_spline_params default_spline_params = {\n\n // scale factor spline params\n 250, // A_SPLINE_NA\n 0.1, // A_SPLINE_MIN\n 0.01, // A_SPLINE_MINLOG_PK\n 0.1, // A_SPLINE_MIN_PK,\n 0.01, // A_SPLINE_MINLOG_SM,\n 0.1, // A_SPLINE_MIN_SM,\n 1.0, // A_SPLINE_MAX,\n 0.0001, // A_SPLINE_MINLOG,\n 250, // A_SPLINE_NLOG,\n\n // mass splines\n 0.025, // LOGM_SPLINE_DELTA\n 50, // LOGM_SPLINE_NM\n 6, // LOGM_SPLINE_MIN\n 17, // LOGM_SPLINE_MAX\n\n // PS a and k spline\n 13, // A_SPLINE_NA_SM\n 6, // A_SPLINE_NLOG_SM\n 40, // A_SPLINE_NA_PK\n 11, // A_SPLINE_NLOG_PK\n\n // k-splines and integrals\n 50, // K_MAX_SPLINE\n 1E3, // K_MAX\n 5E-5, // K_MIN\n 0.025, // DLOGK_INTEGRATION\n 167, // N_K\n 100000, // N_K_3DCOR\n\n // correlation function parameters\n 0.01, // ELL_MIN_CORR\n 60000, // ELL_MAX_CORR\n 5000, // N_ELL_CORR\n\n //Spline types\n NULL,\n NULL,\n NULL,\n NULL,\n NULL,\n NULL,\n NULL\n};\n\n\nccl_physical_constants ccl_constants = {\n /**\n * Lightspeed / H0 in units of Mpc/h (from CODATA 2014)\n */\n 2997.92458,\n\n /**\n * Newton's gravitational constant in units of m^3/Kg/s^2\n */\n //6.6738e-11, /(from PDG 2013) in m^3/Kg/s^2\n //6.67428e-11, // CLASS VALUE\n 6.67408e-11, // from CODATA 2014\n\n /**\n * Solar mass in units of kg (from GSL)\n */\n //GSL_CONST_MKSA_SOLAR_MASS,\n //1.9885e30, //(from PDG 2015) in Kg\n 1.9884754153381438E+30, //from IAU 2015\n\n /**\n * Mpc to meters (from PDG 2016 and using M_PI)\n */\n 3.085677581491367399198952281E+22,\n\n /**\n * pc to meters (from PDG 2016 and using M_PI)\n */\n 3.085677581491367399198952281E+16,\n\n /**\n * Rho critical in units of M_sun/h / (Mpc/h)^3\n */\n ((3*100*100)/(8*M_PI*6.67408e-11)) * (1000*1000*3.085677581491367399198952281E+22/1.9884754153381438E+30),\n\n /**\n * Boltzmann constant in units of J/K\n */\n //GSL_CONST_MKSA_BOLTZMANN,\n 1.38064852E-23, //from CODATA 2014\n\n /**\n * Stefan-Boltzmann constant in units of kg/s^3 / K^4\n */\n //GSL_CONST_MKSA_STEFAN_BOLTZMANN_CONSTANT,\n 5.670367E-8, //from CODATA 2014\n\n /**\n * Planck's constant in units kg m^2 / s\n */\n //GSL_CONST_MKSA_PLANCKS_CONSTANT_H,\n 6.626070040E-34, //from CODATA 2014\n\n /**\n * The speed of light in m/s\n */\n //GSL_CONST_MKSA_SPEED_OF_LIGHT,\n 299792458.0, //from CODATA 2014\n\n /**\n * Electron volt to Joules convestion\n */\n //GSL_CONST_MKSA_ELECTRON_VOLT,\n 1.6021766208e-19, //from CODATA 2014\n\n /**\n * Temperature of the CMB in K\n */\n 2.725,\n //2.7255, // CLASS value\n\n /**\n * T_ncdm, as taken from CLASS, explanatory.ini\n */\n 0.71611,\n\n /**\n * neutrino mass splitting differences\n * See Lesgourgues and Pastor, 2012 for these values.\n * Adv. High Energy Phys. 2012 (2012) 608515,\n * arXiv:1212.6154, page 13\n */\n 7.62E-5,\n 2.55E-3,\n -2.43E-3\n};\n\n\n\n/* ------- ROUTINE: ccl_cosmology_create ------\nINPUTS: ccl_parameters params\n ccl_configuration config\nTASK: creates the ccl_cosmology struct and passes some values to it\nDEFINITIONS:\nchi: comoving distance [Mpc]\ngrowth: growth function (density)\nfgrowth: logarithmic derivative of the growth (density) (dlnD/da?)\nE: E(a)=H(a)/H0\ngrowth0: growth at z=0, defined to be 1\nsigma: ?\np_lnl: nonlinear matter power spectrum at z=0?\ncomputed_distances, computed_growth,\ncomputed_power, computed_sigma: store status of the computations\n*/\nccl_cosmology * ccl_cosmology_create(ccl_parameters params, ccl_configuration config)\n{\n ccl_cosmology * cosmo = malloc(sizeof(ccl_cosmology));\n cosmo->params = params;\n cosmo->config = config;\n cosmo->gsl_params = default_gsl_params;\n cosmo->spline_params = default_spline_params;\n cosmo->spline_params.A_SPLINE_TYPE = gsl_interp_akima;\n cosmo->spline_params.K_SPLINE_TYPE = gsl_interp_akima;\n cosmo->spline_params.M_SPLINE_TYPE = gsl_interp_akima;\n cosmo->spline_params.D_SPLINE_TYPE = gsl_interp_akima;\n cosmo->spline_params.PNL_SPLINE_TYPE = gsl_interp2d_bicubic;\n cosmo->spline_params.PLIN_SPLINE_TYPE = gsl_interp2d_bicubic;\n cosmo->spline_params.CORR_SPLINE_TYPE = gsl_interp_akima;\n\n cosmo->data.chi = NULL;\n cosmo->data.growth = NULL;\n cosmo->data.fgrowth = NULL;\n cosmo->data.E = NULL;\n cosmo->data.growth0 = 1.;\n cosmo->data.achi = NULL;\n\n cosmo->data.logsigma = NULL;\n\n cosmo->data.rsd_splines[0] = NULL;\n cosmo->data.rsd_splines[1] = NULL;\n cosmo->data.rsd_splines[2] = NULL;\n\n cosmo->computed_distances = false;\n cosmo->computed_growth = false;\n cosmo->computed_sigma = false;\n cosmo->status = 0;\n ccl_cosmology_set_status_message(cosmo, \"\");\n\n if(cosmo->spline_params.A_SPLINE_MAX !=1.) {\n cosmo->status = CCL_ERROR_SPLINE;\n ccl_cosmology_set_status_message(cosmo,\n \"ccl_core.c: ccl_cosmology_create(): \"\n \"A_SPLINE_MAX needs to be 1.\\n\");\n }\n\n return cosmo;\n}\n\n/* ------ ROUTINE: ccl_parameters_fill_initial -------\nINPUT: ccl_parameters: params\nTASK: fill parameters not set by ccl_parameters_create with some initial values\nDEFINITIONS:\nOmega_g = (Omega_g*h^2)/h^2 is the radiation parameter; \"g\" is for photons, as in CLASS\nT_CMB: CMB temperature in Kelvin\nOmega_l: Lambda\nA_s: amplitude of the primordial PS, enforced here to initially set to NaN\nsigma8: variance in 8 Mpc/h spheres for normalization of matter PS, enforced here to initially set to NaN\nz_star: recombination redshift\n */\nvoid ccl_parameters_fill_initial(ccl_parameters * params, int *status)\n{\n // Fixed radiation parameters\n // Omega_g * h**2 is known from T_CMB\n params->T_CMB = ccl_constants.T_CMB;\n // kg / m^3\n double rho_g = 4. * ccl_constants.STBOLTZ / pow(ccl_constants.CLIGHT, 3) * pow(params->T_CMB, 4);\n // kg / m^3\n double rho_crit =\n ccl_constants.RHO_CRITICAL *\n ccl_constants.SOLAR_MASS/pow(ccl_constants.MPC_TO_METER, 3) *\n pow(params->h, 2);\n params->Omega_g = rho_g/rho_crit;\n\n // Get the N_nu_rel from Neff and N_nu_mass\n params->N_nu_rel = params->Neff - params->N_nu_mass * pow(ccl_constants.TNCDM, 4) / pow(4./11.,4./3.);\n\n // Temperature of the relativistic neutrinos in K\n double T_nu= (params->T_CMB) * pow(4./11.,1./3.);\n // in kg / m^3\n double rho_nu_rel =\n params->N_nu_rel* 7.0/8.0 * 4. *\n ccl_constants.STBOLTZ / pow(ccl_constants.CLIGHT, 3) *\n pow(T_nu, 4);\n params-> Omega_nu_rel = rho_nu_rel/rho_crit;\n\n // If non-relativistic neutrinos are present, calculate the phase_space integral.\n if((params->N_nu_mass)>0) {\n params->Omega_nu_mass = ccl_Omeganuh2(\n 1.0, params->N_nu_mass, params->m_nu, params->T_CMB, status) / ((params->h)*(params->h));\n }\n else{\n params->Omega_nu_mass = 0.;\n }\n\n params->Omega_m = params->Omega_b + params-> Omega_c + params->Omega_nu_mass;\n params->Omega_l = 1.0 - params->Omega_m - params->Omega_g - params->Omega_nu_rel - params->Omega_k;\n // Initially undetermined parameters - set to nan to trigger\n // problems if they are mistakenly used.\n if (isfinite(params->A_s)) {params->sigma8 = NAN;}\n if (isfinite(params->sigma8)) {params->A_s = NAN;}\n params->z_star = NAN;\n\n if(fabs(params->Omega_k)<1E-6)\n params->k_sign=0;\n else if(params->Omega_k>0)\n params->k_sign=-1;\n else\n params->k_sign=1;\n params->sqrtk=sqrt(fabs(params->Omega_k))*params->h/ccl_constants.CLIGHT_HMPC;\n}\n\n\n/* ------ ROUTINE: ccl_parameters_create -------\nINPUT: numbers for the basic cosmological parameters needed by CCL\nTASK: fill params with some initial values provided by the user\nDEFINITIONS:\nOmega_c: cold dark matter\nOmega_b: baryons\nOmega_m: matter\nOmega_k: curvature\nlittle omega_x means Omega_x*h^2\nNeff : Effective number of neutrino speces\nmnu : Pointer to either sum of neutrino masses or list of three masses.\nmnu_type : how the neutrino mass(es) should be treated\nw0: Dark energy eq of state parameter\nwa: Dark energy eq of state parameter, time variation\nH0: Hubble's constant in km/s/Mpc.\nh: Hubble's constant divided by (100 km/s/Mpc).\nA_s: amplitude of the primordial PS\nn_s: index of the primordial PS\n\n */\nccl_parameters ccl_parameters_create(double Omega_c, double Omega_b, double Omega_k,\n\t\t\t\t double Neff, double* mnu, int n_mnu,\n\t\t\t\t double w0, double wa, double h, double norm_pk,\n\t\t\t\t double n_s, double bcm_log10Mc, double bcm_etab,\n\t\t\t\t double bcm_ks, double mu_0, double sigma_0,\n\t\t\t\t int nz_mgrowth, double *zarr_mgrowth,\n\t\t\t\t double *dfarr_mgrowth, int *status)\n{\n #ifndef USE_GSL_ERROR\n gsl_set_error_handler_off();\n #endif\n\n ccl_parameters params;\n // Initialize params\n params.m_nu = NULL;\n params.z_mgrowth=NULL;\n params.df_mgrowth=NULL;\n params.sigma8 = NAN;\n params.A_s = NAN;\n params.Omega_c = Omega_c;\n params.Omega_b = Omega_b;\n params.Omega_k = Omega_k;\n params.Neff = Neff;\n params.m_nu = malloc(n_mnu*sizeof(double));\n params.sum_nu_masses = 0.;\n for(int i = 0; i0\n if(nz_mgrowth>0) {\n params.has_mgrowth=true;\n params.nz_mgrowth=nz_mgrowth;\n params.z_mgrowth=malloc(params.nz_mgrowth*sizeof(double));\n params.df_mgrowth=malloc(params.nz_mgrowth*sizeof(double));\n memcpy(params.z_mgrowth,zarr_mgrowth,params.nz_mgrowth*sizeof(double));\n memcpy(params.df_mgrowth,dfarr_mgrowth,params.nz_mgrowth*sizeof(double));\n }\n else {\n params.has_mgrowth=false;\n params.nz_mgrowth=0;\n params.z_mgrowth=NULL;\n params.df_mgrowth=NULL;\n }\n\n return params;\n}\n\n\n/**\n * Write a cosmology parameters object to a file in yaml format.\n * @param cosmo Cosmological parameters\n * @param f FILE* pointer opened for reading\n * @return void\n */\nvoid ccl_parameters_write_yaml(ccl_parameters * params, const char * filename, int *status)\n{\n FILE * f = fopen(filename, \"w\");\n\n if (!f){\n *status = CCL_ERROR_FILE_WRITE;\n return;\n }\n\n#define WRITE_DOUBLE(name) fprintf(f, #name \": %le\\n\",params->name)\n#define WRITE_INT(name) fprintf(f, #name \": %d\\n\",params->name)\n\n // Densities: CDM, baryons, total matter, curvature\n WRITE_DOUBLE(Omega_c);\n WRITE_DOUBLE(Omega_b);\n WRITE_DOUBLE(Omega_m);\n WRITE_DOUBLE(Omega_k);\n WRITE_INT(k_sign);\n\n // Dark Energy\n WRITE_DOUBLE(w0);\n WRITE_DOUBLE(wa);\n\n // Hubble parameters\n WRITE_DOUBLE(H0);\n WRITE_DOUBLE(h);\n\n // Neutrino properties\n WRITE_DOUBLE(Neff);\n WRITE_INT(N_nu_mass);\n WRITE_DOUBLE(N_nu_rel);\n\n if (params->N_nu_mass>0){\n fprintf(f, \"m_nu: [\");\n for (int i=0; iN_nu_mass; i++){\n fprintf(f, \"%le, \", params->m_nu[i]);\n }\n fprintf(f, \"]\\n\");\n }\n\n WRITE_DOUBLE(sum_nu_masses);\n WRITE_DOUBLE(Omega_nu_mass);\n WRITE_DOUBLE(Omega_nu_rel);\n\n // Primordial power spectra\n WRITE_DOUBLE(A_s);\n WRITE_DOUBLE(n_s);\n\n // Radiation parameters\n WRITE_DOUBLE(Omega_g);\n WRITE_DOUBLE(T_CMB);\n\n // BCM baryonic model parameters\n WRITE_DOUBLE(bcm_log10Mc);\n WRITE_DOUBLE(bcm_etab);\n WRITE_DOUBLE(bcm_ks);\n\n // Modified gravity parameters\n WRITE_DOUBLE(mu_0);\n WRITE_DOUBLE(sigma_0);\n\n // Derived parameters\n WRITE_DOUBLE(sigma8);\n WRITE_DOUBLE(Omega_l);\n WRITE_DOUBLE(z_star);\n\n WRITE_INT(has_mgrowth);\n WRITE_INT(nz_mgrowth);\n\n if (params->has_mgrowth){\n fprintf(f, \"z_mgrowth: [\");\n for (int i=0; inz_mgrowth; i++){\n fprintf(f, \"%le, \", params->z_mgrowth[i]);\n }\n fprintf(f, \"]\\n\");\n\n fprintf(f, \"df_mgrowth: [\");\n for (int i=0; inz_mgrowth; i++){\n fprintf(f, \"%le, \", params->df_mgrowth[i]);\n }\n fprintf(f, \"]\\n\");\n }\n\n#undef WRITE_DOUBLE\n#undef WRITE_INT\n\n fclose(f);\n}\n\n/**\n * Write a cosmology parameters object to a file in yaml format.\n * @param cosmo Cosmological parameters\n * @param f FILE* pointer opened for reading\n * @return void\n */\nccl_parameters ccl_parameters_read_yaml(const char * filename, int *status) {\n FILE * f = fopen(filename, \"r\");\n\n if (!f) {\n *status = CCL_ERROR_FILE_READ;\n ccl_parameters bad_params;\n ccl_raise_warning(CCL_ERROR_FILE_READ,\n \"ccl_core.c: ccl_parameters_read_yaml(): \"\n \"Failed to read parameters from file.\");\n\n return bad_params;\n }\n\n#define READ_DOUBLE(name) double name; *status |= (0==fscanf(f, #name \": %le\\n\",&name));\n#define READ_INT(name) int name; *status |= (0==fscanf(f, #name \": %d\\n\",&name))\n\n // Densities: CDM, baryons, total matter, curvature\n READ_DOUBLE(Omega_c);\n READ_DOUBLE(Omega_b);\n READ_DOUBLE(Omega_m);\n READ_DOUBLE(Omega_k);\n READ_INT(k_sign);\n\n // Dark Energy\n READ_DOUBLE(w0);\n READ_DOUBLE(wa);\n\n // Hubble parameters\n READ_DOUBLE(H0);\n READ_DOUBLE(h);\n\n // Neutrino properties\n READ_DOUBLE(Neff);\n READ_INT(N_nu_mass);\n READ_DOUBLE(N_nu_rel);\n\n double mnu[3] = {0.0, 0.0, 0.0};\n if (N_nu_mass>0){\n *status |= (0==fscanf(f, \"m_nu: [\"));\n for (int i=0; ichi);\n gsl_spline_free(data->growth);\n gsl_spline_free(data->fgrowth);\n gsl_spline_free(data->E);\n gsl_spline_free(data->achi);\n gsl_spline2d_free(data->logsigma);\n ccl_f1d_t_free(data->rsd_splines[0]);\n ccl_f1d_t_free(data->rsd_splines[1]);\n ccl_f1d_t_free(data->rsd_splines[2]);\n}\n\n/* ------- ROUTINE: ccl_cosmology_set_status_message --------\nINPUT: ccl_cosmology struct, status_string\nTASK: set the status message safely.\n*/\nvoid ccl_cosmology_set_status_message(ccl_cosmology * cosmo, const char * message, ...) {\n const int trunc = 480; /* must be < 500 - 4 */\n\n va_list va;\n va_start(va, message);\n\n #pragma omp critical\n {\n vsnprintf(cosmo->status_message, trunc, message, va);\n\n /* if truncation happens, message[trunc - 1] is not NULL, ... will show up. */\n strcpy(&cosmo->status_message[trunc], \"...\");\n }\n\n va_end(va);\n}\n\n/* ------- ROUTINE: ccl_parameters_free --------\nINPUT: ccl_parameters struct\nTASK: free allocated quantities in the parameters struct\n*/\nvoid ccl_parameters_free(ccl_parameters * params) {\n if (params->m_nu != NULL){\n free(params->m_nu);\n params->m_nu = NULL;\n }\n if (params->z_mgrowth != NULL){\n free(params->z_mgrowth);\n params->z_mgrowth = NULL;\n }\n if (params->df_mgrowth != NULL){\n free(params->df_mgrowth);\n params->df_mgrowth = NULL;\n }\n}\n\n\n/* ------- ROUTINE: ccl_cosmology_free --------\nINPUT: ccl_cosmology struct\nTASK: free the input data and the cosmology struct\n*/\nvoid ccl_cosmology_free(ccl_cosmology * cosmo) {\n if (cosmo != NULL)\n ccl_data_free(&cosmo->data);\n free(cosmo);\n}\n\nint ccl_get_pk_spline_na(ccl_cosmology *cosmo) {\n return cosmo->spline_params.A_SPLINE_NA_PK + cosmo->spline_params.A_SPLINE_NLOG_PK - 1;\n}\n\nvoid ccl_get_pk_spline_a_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status) {\n double *d = NULL;\n if (ndout != ccl_get_pk_spline_na(cosmo))\n *status = CCL_ERROR_INCONSISTENT;\n if (*status == 0) {\n d = ccl_linlog_spacing(cosmo->spline_params.A_SPLINE_MINLOG_PK,\n cosmo->spline_params.A_SPLINE_MIN_PK,\n cosmo->spline_params.A_SPLINE_MAX,\n cosmo->spline_params.A_SPLINE_NLOG_PK,\n cosmo->spline_params.A_SPLINE_NA_PK);\n if (d == NULL)\n *status = CCL_ERROR_MEMORY;\n }\n if(*status==0)\n memcpy(doutput, d, ndout*sizeof(double));\n\n free(d);\n}\n\nint ccl_get_pk_spline_nk(ccl_cosmology *cosmo) {\n double ndecades = log10(cosmo->spline_params.K_MAX) - log10(cosmo->spline_params.K_MIN);\n return (int)ceil(ndecades*cosmo->spline_params.N_K);\n}\n\nvoid ccl_get_pk_spline_lk_array(ccl_cosmology *cosmo,int ndout,double* doutput,int *status) {\n double *d = NULL;\n if (ndout != ccl_get_pk_spline_nk(cosmo))\n *status = CCL_ERROR_INCONSISTENT;\n if (*status == 0) {\n d = ccl_log_spacing(cosmo->spline_params.K_MIN, cosmo->spline_params.K_MAX, ndout);\n if (d == NULL)\n *status = CCL_ERROR_MEMORY;\n }\n if (*status == 0) {\n for(int ii=0; ii < ndout; ii++)\n doutput[ii] = log(d[ii]);\n }\n free(d);\n}\n", "meta": {"hexsha": "961ede46a4d121cda8053746cb3c9ee906e300bb", "size": 21611, "ext": "c", "lang": "C", "max_stars_repo_path": "src/ccl_core.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_core.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_core.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": 26.1951515152, "max_line_length": 108, "alphanum_fraction": 0.6752116977, "num_tokens": 6853, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.546738151984614, "lm_q2_score": 0.44939263446475963, "lm_q1q2_score": 0.2457000984827598}} {"text": "/*\n * Barcode\n * Copyright E.G.P. Bos and F.S. Kitaura\n *\n * Distributed under the terms of the MIT License.\n * The full license is in the file LICENSE, distributed with this software.\n */\n\n\n#pragma once\n\n// EGP: cleared out most includes, just left the two here:\n#include // For the gsl_rng type // EGP: added this one\n#include \"define_opt.h\" // For the ULONG and real_prec types\n// #include \"curses_funcs.h\"\n// EGP: toch maar weer terug gezet, gingen dingen mis\n/* #include */\n/* #include */\n/* #include */\n// #include \n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n/* #include */\n\n/* #include \"fftw_array.h\" */\n\n/* #include \"define_opt.h\" */\n\n#include \n#include \"HMC_models.h\"\n#include \"struct_main.h\"\n#include \n\nusing namespace std;\n\n/* --- structures --- */\n\nstruct HAMIL_NUMERICAL {\n unsigned N1; /* Number of cells per axis */\n unsigned N2; /* Number of cells per axis */\n unsigned N3; /* Number of cells per axis */\n ULONG N;\n ULONG Nhalf;\n\n int mk;\n\n real_prec L1;\n real_prec L2;\n real_prec L3;\n\n real_prec vol;\n\n real_prec d1;\n real_prec d2;\n real_prec d3;\n\n real_prec min1;\n real_prec min2;\n real_prec min3;\n\n // Redshift space distortions\n real_prec xobs;\n real_prec yobs;\n real_prec zobs;\n bool planepar;\n bool periodic;\n\n ULONG N_bin;\n\n ULONG iGibbs;\n ULONG rejections;\n ULONG total_steps_lim;\n\n // EGP: some extra parameters for statistics on performance:\n bool accepted;\n real_prec epsilon;\n ULONG Neps;\n real_prec dH, dK, dE, dprior, dlikeli, psi_prior, psi_likeli, psi_prior_i,\n psi_prior_f, psi_likeli_i, psi_likeli_f, H_kin_i, H_kin_f;\n\n int method;\t\t\t/* which method */\n int filter;\t\t\t/* which filter method */\n ULONG itmax;\t\t\t/* maximal number of iterations */\n int i_reset;\t\t\t/* number to reset */\n int INV_SUCCESS;\t\t/* indicate inversion success */\n\n real_prec epsi; /* precision */\n\n real_prec kth;\n\n // EGP: pseudo-timestep parameters\n real_prec N_eps_fac;\n real_prec eps_fac;\n real_prec eps_fac_target;\n real_prec eps_fac_power;\n ULONG s_eps_total;\n\n // mass type\n bool mass_fs;\n bool mass_rs;\n int mass_type;\n ULONG massnum_init;\n ULONG massnum_burn;\n\n // EGP: testing:\n real_prec mass_factor;\n\n /// TESTING ///\n real_prec grad_psi_prior_factor;\n real_prec grad_psi_likeli_factor;\n bool grad_psi_prior_conjugate;\n bool grad_psi_likeli_conjugate;\n bool grad_psi_prior_times_i;\n bool grad_psi_likeli_times_i;\n bool div_dH_by_N;\n int calc_h;\n real_prec deltaQ_factor;\n\n bool correct_delta;\n\n int particle_kernel;\n real_prec particle_kernel_h;\n\n // FFTW\n real_prec *in_r2c;\n real_prec *out_c2r;\n complex_prec *in_c2r;\n complex_prec *out_r2c;\n struct plan_pkg *R2Cplan;\n struct plan_pkg *C2Rplan;\n};\n\nstruct HAMIL_DATA {\n struct HAMIL_NUMERICAL *numerical; // numerical parameters\n\n // set arrays\n real_prec *mass_f;\n real_prec *mass_r;\n // real_prec *massi;\n real_prec *gradpsi;\n real_prec *x;\n // real_prec *growth;\n\n real_prec *posx;\n real_prec *posy;\n real_prec *posz;\n\n real_prec *signal_PS;\n real_prec *window;\n real_prec *func;\n real_prec *noise;\n real_prec *nobs;\n real_prec *deltaX;\n real_prec *corrf;\n\n // function pointers\n void (*partial_f_delta_x_log_like)(struct HAMIL_DATA*, real_prec*,\n real_prec*);\n real_prec (*log_like)(struct HAMIL_DATA*, real_prec*);\n void (*grad_f_delta_x_comp)(struct HAMIL_DATA *, real_prec *, real_prec *, unsigned int);\n\n real_prec (*log_prior)(struct HAMIL_DATA*, real_prec*);\n void (*grad_log_prior)(struct HAMIL_DATA*, real_prec*, real_prec*);\n\n // model flags\n int sfmodel;\n bool rsd_model;\n\n // set scalars\n real_prec Nmean_Gal;\n real_prec rho_c;\n real_prec code_norm;\n real_prec mu;\n\n real_prec sigma_fac;\n real_prec sigma_min;\n real_prec delta_min;\n\n real_prec biasP;\n real_prec biasE;\n\n real_prec z;\n real_prec ascale;\n\n real_prec D1;\n real_prec D2;\n\n real_prec OM;\n real_prec OL;\n real_prec h;\n\n // external inputs\n real_prec *M;\n\n // curses\n // struct CURSES_STRUCT *curses;\n\n // stuff for SPH_kernel_3D_cells\n const int N_cells;\n const std::vector kernel_cells_i, kernel_cells_j, kernel_cells_k;\n\n\n // default constructor; initialize everything yourself!\n HAMIL_DATA() : N_cells(0), kernel_cells_i(0, 0), kernel_cells_j(0, 0),\n kernel_cells_k(0, 0) {\n numerical = new HAMIL_NUMERICAL;\n }\n\n\n // secondary constructor; used by call_hamil\n HAMIL_DATA(struct DATA *data, real_prec *A, real_prec *B_f, real_prec *B_r,\n real_prec *C, real_prec *D, real_prec *E, vector cells_i,\n std::vector cells_j, std::vector cells_k,\n int N_cells_i) :\n N_cells(N_cells_i),\n kernel_cells_i(cells_i.begin(), cells_i.end()),\n kernel_cells_j(cells_j.begin(), cells_j.end()),\n kernel_cells_k(cells_k.begin(), cells_k.end()) {\n numerical = new HAMIL_NUMERICAL;\n\n numerical->N1 = data->numerical->N1;\n numerical->N2 = data->numerical->N2;\n numerical->N3 = data->numerical->N3;\n numerical->N = data->numerical->N;\n numerical->Nhalf = data->numerical->Nhalf;\n numerical->L1 = data->numerical->L1;\n numerical->L2 = data->numerical->L2;\n numerical->L3 = data->numerical->L3;\n numerical->vol = data->numerical->vol;\n numerical->d1 = data->numerical->d1;\n numerical->d2 = data->numerical->d2;\n numerical->d3 = data->numerical->d3;\n numerical->min1 = data->numerical->xllc;\n numerical->min2 = data->numerical->yllc;\n numerical->min3 = data->numerical->zllc;\n // Redshift space distortions\n numerical->xobs = data->numerical->xobs;\n numerical->yobs = data->numerical->yobs;\n numerical->zobs = data->numerical->zobs;\n numerical->planepar = data->numerical->planepar;\n numerical->periodic = data->numerical->periodic;\n \n numerical->N_bin = data->numerical->N_bin;\n numerical->mk = data->numerical->mk;\n\n numerical->kth = data->numerical->slength;\n\n numerical->iGibbs = data->numerical->iGibbs;\n\n numerical->rejections = 0; // EGP: added for rejection rate\n numerical->total_steps_lim = data->numerical->total_steps_lim;\n\n numerical->itmax = 2000; \n numerical->INV_SUCCESS = 0;/* indicate inversion success initialize with 0*/\n \n numerical->N_eps_fac = data->numerical->N_eps_fac;\n numerical->eps_fac = data->numerical->eps_fac;\n numerical->eps_fac_target = data->numerical->eps_fac_target;\n numerical->eps_fac_power = data->numerical->eps_fac_power;\n numerical->s_eps_total = data->numerical->s_eps_total;\n\n numerical->mass_type = data->numerical->mass_type;\n switch (numerical->mass_type) {\n case 0: // 0: R: all ones (essentially: no mass term)\n numerical->mass_rs = true;\n numerical->mass_fs = false;\n break;\n case 1: // 1: FS: inverse power spectrum\n numerical->mass_rs = false;\n numerical->mass_fs = true;\n break;\n case 2: // 2: FS+FS: inverse power spectrum + likelihood force spectrum\n numerical->mass_rs = false;\n numerical->mass_fs = true;\n break;\n case 3: // 3: FS+FS: inverse power spectrum + mean likelihood force (Wang+13)\n numerical->mass_rs = false;\n numerical->mass_fs = true;\n break;\n case 4: // 4: FS: power spectrum\n numerical->mass_rs = false;\n numerical->mass_fs = true;\n break;\n case 5: // 5: FS+R: inverse power spectrum + 1st order likelihood force expansion (Jasche+13)\n numerical->mass_rs = true;\n numerical->mass_fs = true;\n break;\n case 6: // 1st order likelihood force expansion (Jasche+13) (R)\n numerical->mass_rs = true;\n numerical->mass_fs = false;\n break;\n case 60: // type 0 until burn-in, type 6 afterwards\n numerical->mass_rs = true;\n numerical->mass_fs = false;\n break;\n default:\n stringstream message;\n message << \"mass_type \" << numerical->mass_type << \" is not a valid value!\";\n throw runtime_error(message.str());\n }\n\n numerical->massnum_init = data->numerical->massnum_init;\n numerical->massnum_burn = data->numerical->massnum_burn;\n\n gradpsi = A;\n mass_f = B_f;\n mass_r = B_r;\n posx = C;\n posy = D;\n posz = E; \n\n z = data->cosmology->z;\n ascale = data->cosmology->ascale;\n\n D1 = data->cosmology->D1;\n D2 = data->cosmology->D2;\n\n OM = data->cosmology->omega_m;\n OL = data->cosmology->omega_q;\n h = data->cosmology->h;\n\n biasP = data->observational->biasP;\n biasE = data->observational->biasE;\n\n x = data->observational->signal;\n nobs = data->observational->nobs;\n deltaX = data->observational->signalX;\n noise = data->observational->noise_sf;\n corrf = data->observational->corrf;\n \n Nmean_Gal = data->observational->Nmean_Gal;\n rho_c = data->observational->rho_c;\n code_norm = data->numerical->code_norm;\n mu = data->observational->mu;\n\n sigma_fac = data->observational->sigma_fac; \n sigma_min = data->observational->sigma_min; \n delta_min = data->observational->delta_min; \n\n signal_PS = data->observational->Power;\n \n window = data->observational->window;\n\n // function pointers\n log_like = data->observational->log_like;\n partial_f_delta_x_log_like = data->observational->partial_f_delta_x_log_like;\n grad_f_delta_x_comp = data->observational->grad_f_delta_x_comp;\n log_prior = data->observational->log_prior;\n grad_log_prior = data->observational->grad_log_prior;\n\n // model flags\n sfmodel = data->numerical->sfmodel;\n rsd_model = data->numerical->rsd_model;\n\n // Testing:\n numerical->mass_factor = data->numerical->mass_factor;\n numerical->grad_psi_prior_factor = data->numerical->grad_psi_prior_factor;\n numerical->grad_psi_likeli_factor = data->numerical->grad_psi_likeli_factor;\n numerical->grad_psi_prior_conjugate = data->numerical->grad_psi_prior_conjugate;\n numerical->grad_psi_likeli_conjugate = data->numerical->grad_psi_likeli_conjugate;\n numerical->grad_psi_prior_times_i = data->numerical->grad_psi_prior_times_i;\n numerical->grad_psi_likeli_times_i = data->numerical->grad_psi_likeli_times_i;\n numerical->div_dH_by_N = data->numerical->div_dH_by_N;\n numerical->calc_h = data->numerical->calc_h;\n numerical->deltaQ_factor = data->numerical->deltaQ_factor;\n\n numerical->particle_kernel = data->numerical->particle_kernel;\n numerical->particle_kernel_h = data->numerical->particle_kernel_h;\n\n // FFTW\n numerical->in_r2c = data->numerical->in_r2c;\n numerical->out_c2r = data->numerical->out_c2r;\n numerical->in_c2r = data->numerical->in_c2r;\n numerical->out_r2c = data->numerical->out_r2c;\n numerical->R2Cplan = data->numerical->R2Cplan;\n numerical->C2Rplan = data->numerical->C2Rplan;\n\n // curses\n // curses = data->curses;\n\n numerical->correct_delta = data->numerical->correct_delta;\n } \n\n ~HAMIL_DATA() {\n delete numerical;\n }\n};\n\n", "meta": {"hexsha": "ca401e6ec39291651f16828773f979ac7dd85261", "size": 11330, "ext": "h", "lang": "C", "max_stars_repo_path": "barlib/include/struct_hamil.h", "max_stars_repo_name": "egpbos/barcode", "max_stars_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "barlib/include/struct_hamil.h", "max_issues_repo_name": "egpbos/barcode", "max_issues_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-12-13T10:44:12.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-13T10:44:12.000Z", "max_forks_repo_path": "barlib/include/struct_hamil.h", "max_forks_repo_name": "egpbos/barcode", "max_forks_repo_head_hexsha": "1127e12fa80075389c1d247d30b430b77becbbc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-11T06:56:47.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-11T06:56:47.000Z", "avg_line_length": 28.184079602, "max_line_length": 100, "alphanum_fraction": 0.6786407767, "num_tokens": 3283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.24565156951046088}} {"text": "\n#include \n#include \n#include \n#ifdef _WIN32\n #include \"blas.c\"\n#else\n #include \"blas.c\"\n // #include \n#endif\n#include \n#include \n#include \n#include \n#include \n\ndouble mf_float(mt_object* x, int* e);\nextern mt_table* mv_type_array;\n\nvoid mf_array_delete(mt_array* a){\n if(a->data->refcount==1){\n mf_free(a->data);\n }else{\n a->data->refcount--;\n }\n mf_free(a);\n}\n\nvoid mf_array_dec_refcount(mt_array* a){\n if(a->refcount==1){\n mf_array_delete(a);\n }else{\n a->refcount--;\n }\n}\n\nstatic\nmt_array* mf_new_array(long size, int type){\n mt_array* a = mf_malloc(sizeof(mt_array));\n if(type==mv_array_float){\n a->data = mf_malloc(sizeof(mt_array_data)+size*sizeof(double));\n }else{\n abort();\n }\n a->data->refcount = 1;\n a->data->type = type;\n a->base = a->data->a;\n a->refcount = 1;\n a->size = size;\n return a;\n}\n\nstatic\nmt_array* mf_array_copy(mt_array* a){\n mt_array* b;\n if(a->n==2){\n if(a->plain){\n goto plain;\n }else{\n unsigned long m=a->shape[0];\n unsigned long n=a->shape[1];\n long si=a->stride[0];\n long sj=a->stride[1];\n b = mf_new_array(m*n,mv_array_float);\n b->n = a->n; b->plain = 1;\n b->shape[0] = m; b->shape[1] = n;\n b->stride[0] = 1; b->stride[1] = m;\n double* pa = (double*)a->base;\n double* pb = (double*)b->base;\n unsigned long i,j,mj;\n long sjj;\n for(j=0; jn==1){\n b = mf_new_array(a->shape[0],mv_array_float);\n b->n = 1;\n b->shape[0] = a->shape[0];\n b->stride[0] = 1;\n cblas_dcopy(a->shape[0],(double*)a->base,a->stride[0],(double*)b->base,1);\n return b;\n }else{\n if(a->plain) goto plain;\n abort();\n }\n\n plain:\n b = mf_new_array(a->size,mv_array_float);\n b->n = a->n;\n b->plain = 1;\n unsigned long i;\n for(i=0; in; i++){\n b->shape[i] = a->shape[i];\n b->stride[i] = a->stride[i];\n }\n cblas_dcopy(a->size,(double*)a->base,1,(double*)b->base,1);\n return b;\n}\n\nvoid mf_ensure_plain(mt_array* a){\n if(a->n==2){\n if(a->plain) return;\n mt_array_data* data = mf_malloc(sizeof(mt_array_data)+a->size*sizeof(double));\n data->refcount = 1;\n data->type = mv_array_float;\n double* pa = (double*)a->base;\n double* pb = (double*)data->a;\n\n unsigned long m = a->shape[0];\n unsigned long n = a->shape[1];\n long si = a->stride[0];\n long sj = a->stride[1];\n unsigned long i,j,mj;\n long sjj;\n for(j=0; jdata->refcount==1){\n mf_free(a->data);\n }else{\n a->data->refcount--;\n }\n a->stride[0] = 1;\n a->stride[1] = m;\n a->data = data;\n a->base = data->a;\n a->plain = 1;\n }else if(a->n==1){\n abort();\n }else{\n if(a->plain) return;\n abort();\n }\n}\n\nstatic\nmt_array* mf_array_map_dd(mt_array* a, double(*f)(double)){\n mt_array* b;\n if(a->n==2){\n if(a->plain){\n goto plain;\n }else{\n unsigned long m = a->shape[0];\n unsigned long n = a->shape[1];\n long si = a->stride[0];\n long sj = a->stride[1];\n b = mf_new_array(m*n,mv_array_float);\n b->n = a->n; b->plain = 1;\n b->shape[0] = m; b->shape[1] = n;\n b->stride[0] = 1; b->stride[1] = m;\n double* pa = (double*)a->base;\n double* pb = (double*)b->base;\n unsigned long i,j,mj;\n long sjj;\n for(j=0; jn==1){\n unsigned long n=a->shape[0];\n b = mf_new_array(n,mv_array_float);\n b->n = 1; b->shape[0] = n;\n b->stride[0] = 1;\n long s = a->stride[0];\n unsigned long k;\n double* pa = (double*)a->base;\n double* pb = (double*)b->base;\n for(k=0; kplain) goto plain;\n abort();\n }\n\n plain:\n b = mf_new_array(a->size,mv_array_float);\n b->n = a->n;\n b->plain = 1;\n unsigned long i;\n for(i=0; in; i++){\n b->shape[i] = a->shape[i];\n b->stride[i] = a->stride[i];\n }\n double* pa = (double*)a->base;\n double* pb = (double*)b->base;\n unsigned long size = a->size;\n unsigned long k;\n for(k=0; kn){\n case 1:\n return a->shape[0];\n case 2:\n return a->shape[0]*a->shape[1];\n default:\n p=1;\n for(k=0; kn; k++){\n p = p*a->shape[k];\n }\n return p;\n }\n}\n\nmt_array* mf_array(long size, mt_object* v){\n mt_array* a;\n if(size>0 && v[0].type==mv_list){\n long i,j;\n mt_list* list = (mt_list*)v[0].value.p;\n long n = list->size;\n a = mf_new_array(size*n,mv_array_float);\n a->n = 2;\n a->shape[0] = size; a->shape[1] = n;\n a->stride[0] = 1; a->stride[1] = size;\n a->plain = 1;\n double* b = (double*)a->base;\n int e=0;\n for(i=0; isize!=n) abort();\n for(j=0; ja+j,&e);\n if(e) abort();\n }\n }\n }else{\n a = mf_new_array(size,mv_array_float);\n a->n = 1;\n a->shape[0] = size;\n a->stride[0] = 1;\n long i;\n double* b = (double*)a->base;\n int e=0;\n for(i=0; isize, list->a);\n if(a==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)a;\n return 0;\n}\n\nint la_vector(mt_object* x, int argc, mt_object* v){\n mt_array* a = mf_array(argc,v+1);\n if(a==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)a;\n return 0;\n}\n\nint la_matrix(mt_object* x, int argc, mt_object* v){\n mt_array* a = mf_array(argc,v+1);\n if(a==NULL) return 1;\n if(a->n==1){\n a->n = 2;\n unsigned long size = a->shape[0];\n a->shape[0] = size;\n a->shape[1] = 1;\n a->stride[0] = 1;\n a->stride[1] = size;\n a->plain = 0;\n }\n x->type = mv_array;\n x->value.p = (mt_basic*)a;\n return 0;\n}\n\nstatic\nvoid vector_str(mt_bs* bs, mt_array* T){\n char buffer[100];\n unsigned long i;\n double* a = (double*)T->base;\n unsigned long size = T->shape[0];\n long step = T->stride[0];\n\n mf_bs_push_cstr(bs,\"[\");\n for(i=0; ibase;\n unsigned long m,n,is,js;\n m = T->shape[0];\n n = T->shape[1];\n is = T->stride[0];\n js = T->stride[1];\n int max = 0;\n int size;\n for(i=0; imax) max=size;\n }\n }\n mf_bs_push_cstr(bs,\"[\");\n for(i=0; in==1){\n vector_str(&bs,T);\n }else if(T->n==2){\n matrix_str(&bs,T);\n }else{\n abort();\n }\n\n x->type = mv_string;\n x->value.p = (mt_basic*)mf_str_new(bs.size,(const char*)bs.a);\n mf_free(bs.a);\n return 0;\n}\n\nstatic\nint array_list(mt_object* x, int argc, mt_object* v){\n if(argc!=0){\n mf_argc_error(argc,0,0,\"array.type.list\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a.list(): a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* T = (mt_array*)v[0].value.p;\n mt_list* list = mf_raw_list(T->size);\n unsigned long i;\n double* a = (double*)T->base;\n unsigned long size = T->shape[0];\n long step = T->stride[0];\n for(i=0; ia[i].type = mv_float;\n list->a[i].value.f = a[step*i];\n }\n \n x->type = mv_list;\n x->value.p = (mt_basic*)list;\n return 0;\n}\n\ndouble addc;\ndouble add(double x){\n return x+addc;\n}\ndouble subc;\ndouble sub(double x){\n return x-subc;\n}\n\nstatic\nint array_add(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.add\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a+b: a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n mt_array* c;\n if(v[1].type!=mv_array){\n int e = 0;\n addc = mf_float(&v[1],&e);\n if(e){\n mf_type_error1(\"in a+r: cannot convert r (type: %s) to float.\",&v[1]);\n return 1;\n }\n c = mf_array_map_dd(a,add);\n if(c==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)c;\n return 0;\n }\n mt_array* b = (mt_array*)v[1].value.p;\n if(a->n!=b->n){\n mf_value_error(\"value error in a+b: a and b have unequal order.\");\n return 1;\n }\n if(a->n==1){\n unsigned long size=a->shape[0];\n if(size!=b->shape[0]){\n mf_value_error(\"Value error in a+b: a and b have unequal shape.\");\n return 1;\n }\n c = mf_new_array(size,mv_array_float);\n c->n = 1; c->stride[0] = 1;\n c->shape[0] = size;\n cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)c->base,1);\n cblas_daxpy(size,1,(double*)b->base,b->stride[0],(double*)c->base,1);\n }else{\n unsigned long i;\n for(i=0; in; i++){\n if(a->shape[i]!=b->shape[i]) abort();\n }\n c = mf_array_copy(a);\n mf_ensure_plain(b);\n cblas_daxpy(c->size,1,(double*)b->base,1,(double*)c->base,1);\n }\n x->type = mv_array;\n x->value.p = (mt_basic*)c;\n return 0;\n}\n\nstatic\nint array_radd(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.radd\");\n return 1;\n }\n if(v[1].type!=mv_array){\n mf_type_error1(\"in r*a: a (type: %s) is not an array.\",&v[1]);\n return 1;\n }\n int e = 0;\n addc = mf_float(&v[0],&e);\n if(e){\n mf_type_error1(\"in r+a: cannot convert r (type: %s) to float.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[1].value.p;\n mt_array* y = mf_array_map_dd(a,add);\n if(y==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)y;\n return 0;\n}\n\nstatic\nint array_sub(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.sub\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a-b: a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n mt_array* c;\n if(v[1].type!=mv_array){\n int e = 0;\n subc = mf_float(&v[1],&e);\n if(e){\n mf_type_error1(\"in a-r: cannot convert r (type: %s) to float.\",&v[1]);\n return 1;\n }\n c = mf_array_map_dd(a,sub);\n if(c==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)c;\n return 0;\n }\n mt_array* b = (mt_array*)v[1].value.p;\n if(a->n==1){\n unsigned long size = a->shape[0];\n if(size!=b->shape[0]){\n mf_value_error(\"Value error in a-b: a and b have unequal shape.\");\n return 1;\n }\n\n c = mf_new_array(size,mv_array_float);\n c->n = 1;\n c->shape[0] = size;\n c->stride[0] = 1;\n cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)c->base,1);\n cblas_daxpy(size,-1,(double*)b->base,b->stride[0],(double*)c->base,1);\n }else{\n unsigned long i;\n for(i=0; in; i++){\n if(a->shape[i]!=b->shape[i]) abort();\n }\n c = mf_array_copy(a);\n mf_ensure_plain(b);\n cblas_daxpy(c->size,-1,(double*)b->base,1,(double*)c->base,1);\n }\n x->type = mv_array;\n x->value.p = (mt_basic*)c;\n return 0;\n}\n\nstatic\nmt_array* mf_array_scal(double r, mt_array* a){\n mt_array* b;\n if(a->n==1){\n unsigned long size = a->shape[0];\n b = mf_new_array(size,mv_array_float);\n b->n = 1;\n b->shape[0] = size;\n b->stride[0] = 1;\n cblas_dcopy(size,(double*)a->base,a->stride[0],(double*)b->base,1);\n }else{\n b = mf_array_copy(a);\n }\n cblas_dscal(b->size,r,(double*)b->base,1);\n return b;\n}\n\nstatic\nmt_array* array_mpy_array(mt_array* a, mt_array* b){\n if(b->n==1){\n unsigned long m = a->shape[0];\n unsigned long n = a->shape[1];\n if(n!=b->shape[0]){\n mf_value_error(\"Value error in A*x: shape does not match.\");\n return NULL;\n }\n if(a->stride[0]!=1){\n mf_ensure_plain(a);\n }\n mt_array* c = mf_new_array(m,mv_array_float);\n c->n = 1;\n c->shape[0] = m;\n c->stride[0] = 1;\n cblas_dgemv(CblasColMajor,CblasNoTrans,m,n,1,\n (double*)a->base, a->stride[1],\n (double*)b->base, b->stride[0],\n 0,(double*)c->base,1\n );\n return c;\n }else if(b->n==2){\n if(a->n==2){\n if(a->shape[1]!=b->shape[0]){\n mf_value_error(\"Value error in A*B: incompatible matrices.\");\n return NULL;\n }\n if(a->stride[0]!=1){\n mf_ensure_plain(a);\n }\n if(b->stride[0]!=1){\n mf_ensure_plain(b);\n }\n\n unsigned long m = a->shape[0];\n unsigned long k = a->shape[1];\n unsigned long n = b->shape[1];\n mt_array* c = mf_new_array(m*n,mv_array_float);\n c->n = 2;\n c->shape[0] = m;\n c->shape[1] = n;\n c->stride[0] = 1;\n c->stride[1] = m;\n c->plain = 1;\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, m, n, k, 1,\n (double*)a->base, a->stride[1],\n (double*)b->base, b->stride[1],\n 0, (double*)c->base, m\n );\n return c;\n }else{\n abort();\n }\n }else{\n abort();\n }\n}\n\nstatic\nmt_array* matrix_identity(unsigned long n){\n mt_array* a = mf_new_array(n*n,mv_array_float);\n a->n = 2;\n a->plain = 1;\n a->shape[0] = n;\n a->shape[1] = n;\n a->stride[0] = 1;\n a->stride[1] = n;\n double* b = (double*)a->base;\n unsigned long i,j,nj;\n for(j=0; jstride[0]!=1){\n mf_ensure_plain(a);\n }\n if(b->stride[0]!=1){\n mf_ensure_plain(b);\n }\n unsigned long n = a->shape[0];\n mt_array* c = mf_new_array(n*n,mv_array_float);\n c->n = 2;\n c->shape[0] = n;\n c->shape[1] = n;\n c->stride[0] = 1;\n c->stride[1] = n;\n c->plain = 1;\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1,\n (double*)a->base, a->stride[1],\n (double*)b->base, b->stride[1],\n 0, (double*)c->base, n\n );\n return c;\n}\n\nstatic\nmt_array* square_matrix_pow(mt_array* a, unsigned long n){\n if(n==0){\n return matrix_identity(a->shape[0]);\n }\n mt_array *p,*h;\n p = mf_array_copy(a);\n a = p;\n a->refcount++;\n n--;\n while(n){\n if(n&1){\n h = p;\n p = square_matrix_mpy(p,a);\n mf_array_dec_refcount(h);\n }\n n>>=1;\n if(n==0) break;\n h = a;\n a = square_matrix_mpy(a,a);\n mf_array_dec_refcount(h);\n }\n mf_array_dec_refcount(a);\n return p;\n}\n\nstatic\nint array_mul(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.mul\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a*b: a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n mt_array* b;\n double r;\n if(v[1].type==mv_array){\n b=(mt_array*)v[1].value.p;\n if(a->n==2){\n if(b->n==2 && a->shape[0]==1 && b->shape[1]==1){\n if(a->shape[1]!=b->shape[0]){\n mf_value_error(\"Value error in a*b: incompatible matrices.\");\n return 1;\n }\n // todo: strides\n r = cblas_ddot(a->shape[1],\n (double*)a->base,a->stride[1],\n (double*)b->base,b->stride[0]\n );\n x->type = mv_float;\n x->value.f = r;\n return 0;\n }\n mt_array* c = array_mpy_array(a,b);\n if(c==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)c;\n return 0;\n }\n if(a->n!=1){\n mf_value_error(\"Value error in a*b: a and b have incompatible shape.\");\n return 1;\n }\n if(b->n==2){\n mt_array* c = array_mpy_array(b,a);\n if(c==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)c;\n return 0;\n }\n if(a->shape[0]!=b->shape[0]){\n mf_value_error(\"Value error in a*b: a and b have unequal shape.\");\n return 1;\n }\n r = cblas_ddot(a->shape[0],\n (double*)a->base,a->stride[0],\n (double*)b->base,b->stride[0]\n );\n x->type = mv_float;\n x->value.f = r;\n return 0;\n }else{\n int e = 0;\n r = mf_float(&v[1],&e);\n if(e){\n mf_type_error1(\"in a*r: cannot convert r (type: %s) to float.\",&v[1]);\n return 1;\n }\n x->type = mv_array;\n x->value.p = (mt_basic*)mf_array_scal(r,a);\n return 0;\n }\n}\n\nstatic\nint array_pow(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.pow\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a^n: a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n \n double r;\n if(a->n!=1){\n if(a->n==2 && v[1].type==mv_int){\n long n = v[1].value.i;\n if(a->shape[0]!=a->shape[1]){\n mf_value_error(\"Value error in A^n: A is not a square matrix\");\n return 1;\n }\n x->type = mv_array;\n x->value.p = (mt_basic*)square_matrix_pow(a,(unsigned long)n);\n return 0;\n }\n mf_value_error(\"Value error in a^n: a is not a vector.\");\n return 1;\n }\n r = cblas_ddot(a->shape[0],\n (double*)a->base,a->stride[0],\n (double*)a->base,a->stride[0]\n );\n x->type = mv_float;\n if(v[1].type==mv_int && v[1].value.i==2){\n x->value.f = r;\n }else{\n int e = 0;\n double n = mf_float(&v[1],&e);\n if(e){\n mf_type_error1(\"in a^n: cannot convert n (type: %s) to float.\",&v[1]);\n return 1;\n }\n x->value.f = pow(r,n);\n }\n return 0;\n}\n\nstatic\nint array_rmul(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.rmul\");\n return 1;\n }\n if(v[1].type!=mv_array){\n mf_type_error1(\"in r*a: a (type: %s) is not an array.\",&v[1]);\n return 1;\n }\n int e=0;\n double r = mf_float(&v[0],&e);\n if(e){\n mf_type_error1(\"in r*a: cannot convert r (type: %s) to float.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[1].value.p;\n x->type = mv_array;\n x->value.p = (mt_basic*)mf_array_scal(r,a);;\n return 0;\n}\n\nstatic\nint array_neg(mt_object* x, int argc, mt_object* v){\n if(argc!=0){\n mf_argc_error(argc,0,0,\"Array.neg\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in -a: a (type: %s) is not an array.\",&v[1]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n x->type = mv_array;\n x->value.p = (mt_basic*)mf_array_scal(-1,a);;\n return 0;\n}\n\nstatic\nint array_div(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"Array.div\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a/r: a (type: %s) is not an array.\",&v[1]);\n return 1;\n }\n int e = 0;\n double r = mf_float(&v[1],&e);\n if(e){\n mf_type_error1(\"in a/r: cannot convert r (type: %s) to float.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n x->type = mv_array;\n x->value.p = (mt_basic*)mf_array_scal(1/r,a);;\n return 0;\n}\n\nstatic\nint array_T(mt_object* x, int argc, mt_object* v){\n if(argc!=0){\n mf_argc_error(argc,0,0,\"array.type.T\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a.T(): a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n if(a->n==2){\n mt_array* b = mf_malloc(sizeof(mt_array));\n b->refcount = 1;\n b->n = 2;\n a->data->refcount++;\n b->data = a->data;\n b->base = a->base;\n b->size = a->size;\n b->plain = 0;\n b->shape[0] = a->shape[1];\n b->shape[1] = a->shape[0];\n b->stride[0] = a->stride[1];\n b->stride[1] = a->stride[0];\n x->type = mv_array;\n x->value.p = (mt_basic*)b;\n }else{\n a->refcount++;\n x->type = mv_array;\n x->value.p = (mt_basic*)a;\n }\n return 0;\n}\n\nstatic\nint array_plain(mt_object* x, int argc, mt_object* v){\n if(v[0].type!=mv_array) abort();\n mt_array* a = (mt_array*)v[0].value.p;\n mf_ensure_plain(a);\n a->refcount++;\n x->type = mv_array;\n x->value.p = (mt_basic*)a;\n return 0;\n}\n\nstatic\nint array_copy(mt_object* x, int argc, mt_object* v){\n if(v[0].type!=mv_array) abort();\n mt_array* a = (mt_array*)v[0].value.p;\n x->type = mv_array;\n x->value.p = (mt_basic*)mf_array_copy(a);\n return 0;\n}\n\nstatic\nmt_array* vector_slice(mt_array* a, mt_range* r){\n long i,j;\n if(r->a.type!=mv_int || r->b.type!=mv_int){\n mf_type_error(\"Type error in a[r]: r is not an integer range.\");\n return NULL;\n }\n i = r->a.value.i;\n j = r->b.value.i;\n unsigned long n = a->shape[0];\n if(i<0 || j<0){\n mf_value_error(\"Value error in a[r]: range with negative values.\");\n return NULL;\n }\n if((unsigned long)i>=n || (unsigned long)j>=n){\n mf_value_error(\"Value error in a[r]: range is out of bounds.\");\n return NULL;\n }\n mt_array* b = mf_malloc(sizeof(mt_array));\n b->refcount = 1;\n b->size = a->size;\n a->data->refcount++;\n b->data = a->data;\n a->data = b->data;\n b->n = 1;\n b->base = (unsigned char*)((double*)a->base+a->stride[0]*i);\n b->shape[0] = j-i+1;\n b->stride[0] = a->stride[0];\n return b;\n}\n\nstatic\nint array_get(mt_object* x, int argc, mt_object* v){\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a[i]: a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n if(argc==1){\n if(a->n!=1){\n mf_value_error(\"Value error in a[i]: a is not a vector.\");\n return 1;\n }\n if(v[1].type!=mv_int){\n if(v[1].type==mv_range){\n mt_array* b = vector_slice(a,(mt_range*)v[1].value.p);\n if(b==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)b;\n return 0;\n }\n mf_type_error1(\"in a[i]: i (type: %s) is not an integer.\",&v[1]);\n return 1;\n }\n long index = v[1].value.i;\n unsigned long n = a->shape[0];\n if(index<0 || (unsigned long)index>=n){\n mf_value_error(\"Value error in a[i]: i is out of bounds.\");\n return 1;\n }\n double* b = (double*)a->base;\n double t = b[index*a->stride[0]];\n x->type = mv_float;\n x->value.f = t;\n return 0;\n }else{\n mf_argc_error(argc,1,1,\"Array.get\");\n return 1;\n }\n}\n\nstatic\nint la_idm(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"idm\");\n return 1;\n }\n if(v[1].type!=mv_int){\n mf_type_error1(\"in idm(n): n (type: %s) is not an integer.\",v+1);\n return 1;\n }\n long n = v[1].value.i;\n x->type = mv_array;\n x->value.p = (mt_basic*)matrix_identity(n);\n return 0;\n}\n\nstatic\nmt_array* diag(mt_array* v){\n if(v->n!=1){\n mf_value_error(\"Value error in diag(v): v is not a vector.\");\n return NULL;\n }\n unsigned long n = v->shape[0];\n mt_array* a = mf_new_array(n*n,mv_array_float);\n a->n = 2;\n a->plain = 1;\n a->shape[0] = n;\n a->shape[1] = n;\n a->stride[0] = 1;\n a->stride[1] = n;\n double* b = (double*)a->base;\n double* vb = (double*)v->base;\n long vs = v->stride[0];\n unsigned long i,j,nj;\n for(j=0; jtype = mv_array;\n x->value.p = (mt_basic*)a;\n return 0;\n}\n\nstatic\nmt_array* diag_slice(mt_array* a){\n if(a->n!=2 || a->shape[0]!=a->shape[1]){\n mf_value_error(\"Value error in a.diag(): a is not an quadratic matrix.\");\n return NULL;\n }\n if(a->stride[1]!=1){\n mf_ensure_plain(a);\n }\n mt_array* v = mf_malloc(sizeof(mt_array));\n v->refcount = 1;\n v->n = 1;\n a->data->refcount++;\n v->data = a->data;\n v->base = a->base;\n v->shape[0] = a->shape[0];\n v->stride[0] = (a->shape[0]+1)*a->stride[0];\n return v;\n}\n\nstatic\nint array_diag(mt_object* x, int argc, mt_object* v){\n if(argc!=0){\n mf_argc_error(argc,0,0,\"diag\");\n return 1;\n }\n if(v[0].type!=mv_array){\n mf_type_error1(\"in a.diag(): a (type: %s) is not an array.\",&v[0]);\n return 1;\n }\n mt_array* a = (mt_array*)v[0].value.p;\n mt_array* u = diag_slice(a);\n if(u==NULL) return 1;\n x->type = mv_array;\n x->value.p = (mt_basic*)u;\n return 0;\n}\n\nint mf_array_map(mt_array* a, mt_function* f){\n mt_object argv[2];\n argv[0].type = mv_null;\n double* ba = (double*)a->base;\n long size = a->size;\n long i;\n mt_object x;\n int e = 0;\n for(i=0; itype = mv_array;\n x->value.p = (mt_basic*)b;\n return 0;\n}\n\nstatic\nint mf_trace(mt_object* x, mt_array* a){\n if(a->n!=2 || a->shape[0]!=a->shape[1]){\n mf_value_error(\"Value error in trace(a): a is not a quadratic matrix.\");\n return 1;\n }\n double s = 0;\n long n = a->shape[0];\n double* ba = (double*)a->base;\n long i,m;\n m = a->stride[0]+a->stride[1];\n for(i=0; itype = mv_float;\n x->value.f = s;\n return 0;\n}\n\nstatic\nint la_trace(mt_object* x, int argc, mt_object* v){\n if(argc!=1){\n mf_argc_error(argc,1,1,\"trace\");\n return 1;\n }\n if(v[1].type!=mv_array){\n mf_type_error1(\"in la.trace(a): a (type: %s) is not an array.\",&v[1]);\n return 1;\n }\n mt_array* a = (mt_array*)v[1].value.p;\n if(mf_trace(x,a)) return 1;\n return 0;\n}\n\nmt_table* mf_la_load(){\n mt_map* m = mv_type_array->m;\n mf_insert_function(m,0,0,\"str\",array_str);\n mf_insert_function(m,0,0,\"list\",array_list);\n mf_insert_function(m,1,1,\"add\",array_add);\n mf_insert_function(m,1,1,\"radd\",array_radd);\n mf_insert_function(m,1,1,\"sub\",array_sub);\n mf_insert_function(m,1,1,\"mul\",array_mul);\n mf_insert_function(m,1,1,\"rmul\",array_rmul);\n mf_insert_function(m,0,0,\"neg\",array_neg);\n mf_insert_function(m,1,1,\"div\",array_div);\n mf_insert_function(m,1,1,\"pow\",array_pow);\n mf_insert_function(m,1,-1,\"get\",array_get);\n mf_insert_function(m,0,0,\"T\",array_T);\n mf_insert_function(m,0,0,\"plain\",array_plain);\n mf_insert_function(m,0,0,\"copy\",array_copy);\n mf_insert_function(m,0,0,\"diag\",array_diag);\n mf_insert_function(m,1,1,\"map\",array_map);\n\n mt_table* la = mf_table(NULL);\n la->name = mf_cstr_to_str(\"module la\");\n la->m = mf_empty_map();\n m = la->m;\n mf_insert_function(m,1,1,\"array\",la_array);\n mf_insert_function(m,1,1,\"vector\",la_vector);\n mf_insert_function(m,1,1,\"matrix\",la_matrix);\n mf_insert_function(m,1,1,\"idm\",la_idm);\n mf_insert_function(m,1,1,\"diag\",la_diag);\n mf_insert_function(m,1,1,\"trace\",la_trace);\n m->frozen = 1;\n return la;\n}\n", "meta": {"hexsha": "86ff9781726f1319affde781c1b59221b6d4f1e3", "size": 31817, "ext": "c", "lang": "C", "max_stars_repo_path": "modules/la/la.c", "max_stars_repo_name": "JohnBSmith/moss-c", "max_stars_repo_head_hexsha": "9c53633d58d7375bbfbd4c09a5c85209a2ec2615", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-29T20:07:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T20:07:03.000Z", "max_issues_repo_path": "modules/la/la.c", "max_issues_repo_name": "JohnBSmith/moss-c", "max_issues_repo_head_hexsha": "9c53633d58d7375bbfbd4c09a5c85209a2ec2615", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "modules/la/la.c", "max_forks_repo_name": "JohnBSmith/moss-c", "max_forks_repo_head_hexsha": "9c53633d58d7375bbfbd4c09a5c85209a2ec2615", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4260797342, "max_line_length": 90, "alphanum_fraction": 0.4949240972, "num_tokens": 10255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.3812195803163617, "lm_q1q2_score": 0.24559122472399728}} {"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n#ifndef setup_h\n#define setup_h\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#if PETSC_VERSION_LT(3,14,0)\n# define DMAddBoundary(a,b,c,d,e,f,g,h,i,j,k,l) DMAddBoundary(a,b,c,d,e,f,g,h,j,k,l)\n#endif\n\n#ifndef PHYSICS_STRUCT\n#define PHYSICS_STRUCT\ntypedef struct Physics_private *Physics;\nstruct Physics_private {\n CeedScalar nu; // Poisson's ratio\n CeedScalar E; // Young's Modulus\n};\n#endif\n\n// -----------------------------------------------------------------------------\n// Command Line Options\n// -----------------------------------------------------------------------------\n// Problem options\ntypedef enum {\n ELAS_LIN = 0, ELAS_HYPER_SS = 1, ELAS_HYPER_FS = 2\n} problemType;\nstatic const char *const problemTypes[] = {\"linElas\",\n \"hyperSS\",\n \"hyperFS\",\n \"problemType\",\"ELAS_\",0\n };\nstatic const char *const problemTypesForDisp[] = {\"Linear elasticity\",\n \"Hyper elasticity small strain\",\n \"Hyper elasticity finite strain\"\n };\n\n// Forcing function options\ntypedef enum {\n FORCE_NONE = 0, FORCE_CONST = 1, FORCE_MMS = 2\n} forcingType;\nstatic const char *const forcingTypes[] = {\"none\",\n \"constant\",\n \"mms\",\n \"forcingType\",\"FORCE_\",0\n };\nstatic const char *const forcingTypesForDisp[] = {\"None\",\n \"Constant\",\n \"Manufactured solution\"\n };\n\n// Multigrid options\ntypedef enum {\n MULTIGRID_LOGARITHMIC = 0, MULTIGRID_UNIFORM = 1, MULTIGRID_NONE = 2\n} multigridType;\nstatic const char *const multigridTypes [] = {\"logarithmic\",\n \"uniform\",\n \"none\",\n \"multigridType\",\"MULTIGRID\",0\n };\nstatic const char *const multigridTypesForDisp[] = {\"P-multigrid, logarithmic coarsening\",\n \"P-multigrind, uniform coarsening\",\n \"No multigrid\"\n };\n\ntypedef PetscErrorCode BCFunc(PetscInt, PetscReal, const PetscReal *, PetscInt,\n PetscScalar *, void *);\n// Note: These variables should be updated if additional boundary conditions\n// are added to boundary.c.\nBCFunc BCMMS, BCZero, BCClamp;\n\n// MemType Options\nstatic const char *const memTypes[] = {\"host\",\"device\",\"memType\",\n \"CEED_MEM_\",0\n };\n\n// -----------------------------------------------------------------------------\n// Structs\n// -----------------------------------------------------------------------------\n// Units\ntypedef struct Units_private *Units;\nstruct Units_private {\n // Fundamental units\n PetscScalar meter;\n PetscScalar kilogram;\n PetscScalar second;\n // Derived unit\n PetscScalar Pascal;\n};\n\n// Application context from user command line options\ntypedef struct AppCtx_private *AppCtx;\nstruct AppCtx_private {\n char ceedResource[PETSC_MAX_PATH_LEN]; // libCEED backend\n char meshFile[PETSC_MAX_PATH_LEN]; // exodusII mesh file\n PetscBool testMode;\n PetscBool viewSoln;\n PetscBool viewFinalSoln;\n problemType problemChoice;\n forcingType forcingChoice;\n multigridType multigridChoice;\n PetscScalar nuSmoother;\n PetscInt degree;\n PetscInt qextra;\n PetscInt numLevels;\n PetscInt *levelDegrees;\n PetscInt numIncrements; // Number of steps\n PetscInt bcClampCount;\n PetscInt bcClampFaces[16];\n PetscScalar bcClampMax[16][7];\n PetscInt bcTractionCount;\n PetscInt bcTractionFaces[16];\n PetscScalar bcTractionVector[16][3];\n PetscScalar forcingVector[3];\n PetscBool petscHaveCuda, setMemTypeRequest;\n CeedMemType memTypeRequested;\n};\n\n// Problem specific data\n// *INDENT-OFF*\ntypedef struct {\n CeedInt qdatasize;\n CeedQFunctionUser setupgeo, apply, jacob, energy, diagnostic;\n const char *setupgeofname, *applyfname, *jacobfname, *energyfname,\n *diagnosticfname;\n CeedQuadMode qmode;\n} problemData;\n// *INDENT-ON*\n\n// Data specific to each problem option\nextern problemData problemOptions[3];\n\n// Forcing function data\ntypedef struct {\n CeedQFunctionUser setupforcing;\n const char *setupforcingfname;\n} forcingData;\n\nextern forcingData forcingOptions[3];\n\n// Data for PETSc Matshell\ntypedef struct UserMult_private *UserMult;\nstruct UserMult_private {\n MPI_Comm comm;\n DM dm;\n Vec Xloc, Yloc, NBCs;\n CeedVector Xceed, Yceed;\n CeedOperator op;\n CeedQFunction qf;\n Ceed ceed;\n PetscScalar loadIncrement;\n CeedQFunctionContext ctxPhys, ctxPhysSmoother;\n CeedMemType memType;\n int (*VecGetArray)(Vec, PetscScalar **);\n int (*VecGetArrayRead)(Vec, const PetscScalar **);\n int (*VecRestoreArray)(Vec, PetscScalar **);\n int (*VecRestoreArrayRead)(Vec, const PetscScalar **);\n};\n\n// Data for Jacobian setup routine\ntypedef struct FormJacobCtx_private *FormJacobCtx;\nstruct FormJacobCtx_private {\n UserMult *jacobCtx;\n PetscInt numLevels;\n SNES snesCoarse;\n Mat *jacobMat, jacobMatCoarse;\n Vec Ucoarse;\n};\n\n// Data for PETSc Prolongation/Restriction Matshell\ntypedef struct UserMultProlongRestr_private *UserMultProlongRestr;\nstruct UserMultProlongRestr_private {\n MPI_Comm comm;\n DM dmC, dmF;\n Vec locVecC, locVecF;\n CeedVector ceedVecC, ceedVecF;\n CeedOperator opProlong, opRestrict;\n Ceed ceed;\n CeedMemType memType;\n int (*VecGetArray)(Vec, PetscScalar **);\n int (*VecGetArrayRead)(Vec, const PetscScalar **);\n int (*VecRestoreArray)(Vec, PetscScalar **);\n int (*VecRestoreArrayRead)(Vec, const PetscScalar **);\n};\n\n// libCEED data struct for level\ntypedef struct CeedData_private *CeedData;\nstruct CeedData_private {\n Ceed ceed;\n CeedBasis basisx, basisu, basisCtoF, basisEnergy, basisDiagnostic;\n CeedElemRestriction Erestrictx, Erestrictu, Erestrictqdi,\n ErestrictGradui, ErestrictEnergy, ErestrictDiagnostic,\n ErestrictqdDiagnostici;\n CeedQFunction qfApply, qfJacob, qfEnergy, qfDiagnostic;\n CeedOperator opApply, opJacob, opRestrict, opProlong, opEnergy,\n opDiagnostic;\n CeedVector qdata, qdataDiagnostic, gradu, xceed, yceed, truesoln;\n};\n\n// -----------------------------------------------------------------------------\n// Process command line options\n// -----------------------------------------------------------------------------\n// Process general command line options\nPetscErrorCode ProcessCommandLineOptions(MPI_Comm comm, AppCtx appCtx);\n\n// Process physics options\nPetscErrorCode ProcessPhysics(MPI_Comm comm, Physics phys, Units units);\n\n// -----------------------------------------------------------------------------\n// Setup DM\n// -----------------------------------------------------------------------------\nPetscErrorCode CreateBCLabel(DM dm, const char name[]);\n\n// Create FE by degree\nPetscErrorCode PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,\n PetscBool isSimplex, const char prefix[],\n PetscInt order, PetscFE *fem);\n\n// Read mesh and distribute DM in parallel\nPetscErrorCode CreateDistributedDM(MPI_Comm comm, AppCtx appCtx, DM *dm);\n\n// Setup DM with FE space of appropriate degree\nPetscErrorCode SetupDMByDegree(DM dm, AppCtx appCtx, PetscInt order,\n PetscBool boundary, PetscInt ncompu);\n\n// -----------------------------------------------------------------------------\n// libCEED Functions\n// -----------------------------------------------------------------------------\n// Destroy libCEED objects\nPetscErrorCode CeedDataDestroy(CeedInt level, CeedData data);\n\n// Utility function - essential BC dofs are encoded in closure indices as -(i+1)\nPetscInt Involute(PetscInt i);\n\n// Utility function to create local CEED restriction from DMPlex\nPetscErrorCode CreateRestrictionFromPlex(Ceed ceed, DM dm, CeedInt P,\n CeedInt height, DMLabel domainLabel, CeedInt value,\n CeedElemRestriction *Erestrict);\n\n// Utility function to get Ceed Restriction for each domain\nPetscErrorCode GetRestrictionForDomain(Ceed ceed, DM dm, CeedInt height,\n DMLabel domainLabel, PetscInt value, CeedInt P, CeedInt Q, CeedInt qdatasize,\n CeedElemRestriction *restrictq, CeedElemRestriction *restrictx,\n CeedElemRestriction *restrictqdi);\n\n// Set up libCEED for a given degree\nPetscErrorCode SetupLibceedFineLevel(DM dm, DM dmEnergy, DM dmDiagnostic,\n Ceed ceed, AppCtx appCtx,\n CeedQFunctionContext physCtx,\n CeedData *data, PetscInt fineLevel,\n PetscInt ncompu, PetscInt Ugsz,\n PetscInt Ulocsz, CeedVector forceCeed,\n CeedVector neumannCeed);\n\n// Set up libCEED multigrid level for a given degree\nPetscErrorCode SetupLibceedLevel(DM dm, Ceed ceed, AppCtx appCtx,\n CeedData *data, PetscInt level,\n PetscInt ncompu, PetscInt Ugsz,\n PetscInt Ulocsz, CeedVector fineMult);\n\n// Setup context data for Jacobian evaluation\nPetscErrorCode SetupJacobianCtx(MPI_Comm comm, AppCtx appCtx, DM dm, Vec V,\n Vec Vloc, CeedData ceedData, Ceed ceed,\n CeedQFunctionContext ctxPhys,\n CeedQFunctionContext ctxPhysSmoother,\n UserMult jacobianCtx);\n\n// Setup context data for prolongation and restriction operators\nPetscErrorCode SetupProlongRestrictCtx(MPI_Comm comm, AppCtx appCtx, DM dmC,\n DM dmF, Vec VF, Vec VlocC, Vec VlocF,\n CeedData ceedDataC, CeedData ceedDataF,\n Ceed ceed,\n UserMultProlongRestr prolongRestrCtx);\n\n// -----------------------------------------------------------------------------\n// Jacobian setup\n// -----------------------------------------------------------------------------\nPetscErrorCode FormJacobian(SNES snes, Vec U, Mat J, Mat Jpre, void *ctx);\n\n// -----------------------------------------------------------------------------\n// Solution output\n// -----------------------------------------------------------------------------\nPetscErrorCode ViewSolution(MPI_Comm comm, Vec U, PetscInt increment,\n PetscScalar loadIncrement);\n\nPetscErrorCode ViewDiagnosticQuantities(MPI_Comm comm, DM dmU,\n UserMult user, Vec U,\n CeedElemRestriction ErestrictDiagnostic);\n\n// -----------------------------------------------------------------------------\n// libCEED Operators for MatShell\n// -----------------------------------------------------------------------------\n// This function uses libCEED to compute the local action of an operator\nPetscErrorCode ApplyLocalCeedOp(Vec X, Vec Y, UserMult user);\n\n// This function uses libCEED to compute the non-linear residual\nPetscErrorCode FormResidual_Ceed(SNES snes, Vec X, Vec Y, void *ctx);\n\n// This function uses libCEED to apply the Jacobian for assembly via a SNES\nPetscErrorCode ApplyJacobianCoarse_Ceed(SNES snes, Vec X, Vec Y, void *ctx);\n\n// This function uses libCEED to compute the action of the Jacobian\nPetscErrorCode ApplyJacobian_Ceed(Mat A, Vec X, Vec Y);\n\n// This function uses libCEED to compute the action of the prolongation operator\nPetscErrorCode Prolong_Ceed(Mat A, Vec X, Vec Y);\n\n// This function uses libCEED to compute the action of the restriction operator\nPetscErrorCode Restrict_Ceed(Mat A, Vec X, Vec Y);\n\n// This function returns the computed diagonal of the operator\nPetscErrorCode GetDiag_Ceed(Mat A, Vec D);\n\n// This function calculates the strain energy in the final solution\nPetscErrorCode ComputeStrainEnergy(DM dmEnergy, UserMult user,\n CeedOperator opEnergy, Vec X,\n PetscReal *energy);\n\n// -----------------------------------------------------------------------------\n// Boundary Functions\n// -----------------------------------------------------------------------------\n// Note: If additional boundary conditions are added, an update is needed in\n// elasticity.h for the boundaryOptions variable.\n\n// BCMMS - boundary function\n// Values on all points of the mesh is set based on given solution below\n// for u[0], u[1], u[2]\nPetscErrorCode BCMMS(PetscInt dim, PetscReal loadIncrement,\n const PetscReal coords[], PetscInt ncompu,\n PetscScalar *u, void *ctx);\n\n// BCClamp - fix boundary values with affine transformation at fraction of load\n// increment\nPetscErrorCode BCClamp(PetscInt dim, PetscReal loadIncrement,\n const PetscReal coords[], PetscInt ncompu,\n PetscScalar *u, void *ctx);\n\n#endif //setup_h\n", "meta": {"hexsha": "f06355494f7e30fdea4e13c7ba29b5122b08f605", "size": 15075, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/solids/elasticity.h", "max_stars_repo_name": "rscohn2/libCEED", "max_stars_repo_head_hexsha": "0983a37fb2a235bf55920dd2b1098e5586f89fb8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/solids/elasticity.h", "max_issues_repo_name": "rscohn2/libCEED", "max_issues_repo_head_hexsha": "0983a37fb2a235bf55920dd2b1098e5586f89fb8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/solids/elasticity.h", "max_forks_repo_name": "rscohn2/libCEED", "max_forks_repo_head_hexsha": "0983a37fb2a235bf55920dd2b1098e5586f89fb8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.7590027701, "max_line_length": 116, "alphanum_fraction": 0.5674295191, "num_tokens": 3124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.4765796510636759, "lm_q1q2_score": 0.2438737209134001}} {"text": "/**\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"inout_aper.h\"\n#include \"aXe_grism.h\"\n#include \"spce_sect.h\"\n#include \"spc_back.h\"\n#include \"spce_PET.h\"\n#include \"spc_wl_calib.h\"\n#include \"aXe_errors.h\"\n#include \"fringe_conf.h\"\n#include \"spc_resp.h\"\n#include \"spce_pathlength.h\"\n#include \"aper_conf.h\"\n#include \"specmodel_utils.h\"\n#include \"model_utils.h\"\n#include \"spc_fluxcube.h\"\n#include \"fringe_conf.h\"\n#include \"dirimage_model.h\"\n\n\n#define MAX(x,y) (((x)>(y))?(x):(y))\n#define MIN(x,y) (((x)<(y))?(x):(y))\n#define SQR(x) ((x)*(x))\n\nint\ncompute_dirimage_model(char dirim_file[], char conf_file[], char tpass_file[],\n\t\t char specmod_file[], char objmod_file[], char aper_file[],\n\t\t const double model_scale, const double tel_area, const double lambda_psf,\n\t\t observation *obs, char map_file[])\n{\n object **oblist;\n dirobject **dirlist;\n spectral_models *spec_mod;\n object_models *obj_mod;\n\n interpolator *tpass;\n\n gsl_matrix *dirimage_matrix=NULL;\n\n px_point npixels;\n\n // load the object list\n fprintf (stdout, \"aXe_DIRIMAGE: Loading object aperture list...\");\n oblist = file_to_object_list_seq (aper_file, obs);\n fprintf (stdout,\"%d objects loaded.\\n\",object_list_size(oblist));\n\n // check whether highres models\n // are given\n if (strlen(specmod_file) > 0)\n // load the spectral models\n spec_mod = load_spectral_models(specmod_file);\n else\n // or set the struct to NULL\n spec_mod = NULL;\n\n // check whether direct emission models\n // are given\n if (strlen(objmod_file) > 0)\n obj_mod = load_object_models(objmod_file);\n else\n obj_mod = NULL;\n\n // get the sensitivity curve of the total passband\n tpass = get_filter_sensitivity(tpass_file, tel_area);\n\n // get the image dimensions\n npixels = get_npixel(obs);\n\n // create the list of direct objects to be simulated\n // the interpolation type is fixed to linear\n dirlist = oblist_to_dirlist2(dirim_file, conf_file, npixels, oblist,\n\t\t\t spec_mod, obj_mod, model_scale, 1);\n\n // determine the XOFF and YOFF values\n // for the various beams\n fill_xy_offsets(dirlist, conf_file);\n\n // create and fill the pixel matrix for the direct images\n dirimage_matrix = make_dirimage(oblist, dirlist, npixels, lambda_psf, tpass);\n\n // store the contamination image\n gsl_to_FITSimage (dirimage_matrix, map_file, 1, NULL);\n\n // check if memory must be released;\n // do it if necessary\n if (spec_mod != NULL)\n free_spectral_models(spec_mod);\n if (obj_mod != NULL)\n free_object_models(obj_mod);\n if (oblist !=NULL)\n free_oblist (oblist);\n\n // always release these\n // objects\n free_dirlist(dirlist);\n gsl_matrix_free(dirimage_matrix);\n free_interp(tpass);\n\n // return always '1'\n return 1;\n}\n\n\ngsl_matrix *\nmake_dirimage(object **oblist, dirobject **dirlist, const px_point npixels,\n\t const double lambda_psf, interpolator *tpass)\n{\n dirobject *actdir;\n beam actbeam;\n\n gsl_matrix *dirimage_matrix;\n\n double cps = 0.0;\n double sval = 0.0;\n double value = 0.0;\n\n int ii=0;\n int nx=0;\n int ny=0;\n\n d_point dpixel;\n\n // allocate memory for the image matrix\n dirimage_matrix = gsl_matrix_alloc(npixels.x, npixels.y);\n gsl_matrix_set_all(dirimage_matrix,0.0);\n\n // go over each beam model\n ii = 0;\n while (oblist[ii] != NULL)\n {\n\n // get the direct object for the actual model spectrum\n actdir = get_dirobject_from_list(dirlist, oblist[ii]->ID);\n\n // get the beam for the actual model spectrum\n actbeam = oblist[ii]->beams[0];\n\n // report onto the screen\n fprintf(stdout, \"aXe_DIRIMAGE: modelling object %i ...\", oblist[ii]->ID);\n\n // get the integrated direct image intensity in cps\n cps = get_cps_for_dirobject(tpass, actdir);\n\n // correct the direct image positions for\n // the offset values introduced by building\n // the direct image objects around the reference\n // position, which is shifted from the true\n // direct image position by XOFF and YOFF as\n // given in the aXe configuration file\n actdir->ix_min -= (int)floor(actdir->xy_off[actbeam.ID].x + 0.5);\n actdir->ix_max -= (int)floor(actdir->xy_off[actbeam.ID].x + 0.5);\n actdir->iy_min -= (int)floor(actdir->xy_off[actbeam.ID].y + 0.5);\n actdir->iy_max -= (int)floor(actdir->xy_off[actbeam.ID].y + 0.5);\n actbeam.refpoint.x -= actdir->xy_off[actbeam.ID].x;\n actbeam.refpoint.y -= actdir->xy_off[actbeam.ID].y;\n\n // go over each pixel in the direct object area\n for (nx=actdir->ix_min; nx<=actdir->ix_max; nx++)\n\t{\n\t // make sure to be inside the image\n\t if (nx < 0 || nx >= (int)dirimage_matrix->size1)\n\t // skip column if not\n\t continue;\n\t for (ny=actdir->iy_min; ny<=actdir->iy_max; ny++)\n\t {\n\t // make sure to be inside the image\n\t if (ny < 0 || ny >= (int)dirimage_matrix->size2)\n\t\t// skip element if not\n\t\tcontinue;\n\n\t // fill the dpixel structure\n\t dpixel.x = (double)nx;\n\t dpixel.y = (double)ny;\n\n\t // check whether there is\n\t // an image template\n\t if (actdir->dirim)\n\t\t// get the pixel intensity from the image template\n\t\tsval = get_diremission_value(actdir->dirim, dpixel.x - actbeam.refpoint.x, dpixel.y - actbeam.refpoint.y);\n\t else\n\t\t// get the Gaussian pixel intensity;\n\t\t//\n\t\t// do a subsampling over the pixel\n\t\t// to get a more appropriate value for the\n\t\t// emission val\n\t\tsval = get_sub_emodel_value(dpixel, actbeam, actdir->drzscale);\n\n\t // compute and set the new pixel values\n\t value = gsl_matrix_get(dirimage_matrix, nx, ny) + sval*cps;\n\t gsl_matrix_set(dirimage_matrix, nx, ny, value);\n\t }\n\t}\n\n // release the space for the various structures\n fprintf(stdout, \" Done\\n\");\n ii++;\n }\n\n // return the image matrix\n return dirimage_matrix;\n}\n\n\n\ndouble\nget_cps_for_dirobject(interpolator *tpass, dirobject *actdir)\n{\n interpolator *combine;\n\n double cps=0.0;\n\n // create aa new multiplicator\n // interpolator\n combine = combine_tpass_SED(tpass, actdir);\n\n // integrate over the interpolator\n cps = integrate_interpolator(combine);\n\n // release memory\n free_interp(combine);\n\n // return the cps value\n return cps;\n}\n\n\ndouble\nintegrate_interpolator(interpolator *combine)\n{\n double integral=0.0;\n\n int index;\n\n for (index=1; index < combine->nvals-1; index++)\n // add the increment\n integral += combine->yvals[index] * (combine->xvals[index+1] - combine->xvals[index-1]);\n\n // dont forget the start and end piece\n integral += combine->yvals[0] * (combine->xvals[1] - combine->xvals[0]);\n integral += combine->yvals[combine->nvals-1] * (combine->xvals[combine->nvals-1] - combine->xvals[combine->nvals-2]);\n\n // then return the half\n return integral/2.0;\n}\n\ninterpolator *\ncombine_tpass_SED(interpolator *tpass, dirobject *actdir)\n{\n interpolator *combine;\n\n int index=0;\n int n_additional=0;\n int act_index;\n\n gsl_vector *indep_data;\n\n // go over all SED data points\n for (index = 0; index < actdir->SED->npoints; index++)\n {\n // transform to Angstrom\n actdir->SED->wavelength[index] *= 10.0;\n\n // check whether the independent data point\n // falls in the area of the sensitivity\n if (actdir->SED->wavelength[index] < tpass->xmax\n\t && actdir->SED->wavelength[index] > tpass->xmin)\n\t// enhance the number\n\t// of additional data points\n\tn_additional += 1;\n }\n\n // allocate memory for the new independent value list\n indep_data = gsl_vector_alloc(tpass->nvals + n_additional);\n\n // go over all sensitivity data points and fill in\n // the independent values\n for (index = 0; index < tpass->nvals; index++)\n gsl_vector_set(indep_data, index, tpass->xvals[index]);\n\n // set the counter to the next free index\n act_index = tpass->nvals;\n\n // go over all SED data points\n for (index = 0; index < actdir->SED->npoints; index++)\n // check whether the independent data point\n // falls in the area of the sensitivity\n if (actdir->SED->wavelength[index] < tpass->xmax\n\t&& actdir->SED->wavelength[index] > tpass->xmin)\n {\n\t// fill in the additional independent data point\n\t// from the SED\n\tgsl_vector_set(indep_data, act_index, actdir->SED->wavelength[index]);\n\n\t// enhance the counter\n act_index += 1;\n }\n\n // sort the vector\n gsl_sort_vector(indep_data);\n\n\n // compose a new interpolator from the independent values\n combine = get_combined_tpass_SED(indep_data, tpass, actdir);\n\n // release memory in the weight vector\n gsl_vector_free(indep_data);\n\n // go over all SED data points\n for (index = 0; index < actdir->SED->npoints; index++)\n // transform to nm\n actdir->SED->wavelength[index] /= 10.0;\n\n // return the interpolator\n return combine;\n}\n\ninterpolator *\nget_combined_tpass_SED(gsl_vector *indep_data, interpolator *tpass, dirobject *actdir)\n{\n interpolator *combine;\n\n gsl_vector_int *indep_weight;\n\n int n_new=0;\n int index;\n int act_index;\n\n double *xvals_new;\n double *yvals_new;\n\n // allocat memory for the weight vector\n indep_weight = gsl_vector_int_alloc(indep_data->size);\n\n // set all the weights\n gsl_vector_int_set_all(indep_weight, 1);\n\n // go over the independent data\n for (index = 1; index < (int)indep_data->size; index++)\n // check whether the current entry is equal the previous one\n if (gsl_vector_get(indep_data, index) == gsl_vector_get(indep_data, index-1))\n // set the weight of the current entry to zero\n gsl_vector_int_set(indep_weight,index, 0);\n\n\n // initialize the\n // final number\n n_new = 0;\n\n // go over the weight array\n for (index=0; index < (int)indep_weight->size; index++)\n // just count the weights\n n_new += gsl_vector_int_get(indep_weight, index);\n\n // allocate memory for the interpolator data\n xvals_new = (double *)malloc(n_new * sizeof(double));\n yvals_new = (double *)malloc(n_new * sizeof(double));\n\n // go over the weight array\n act_index=0;\n for (index=0; index < (int)indep_weight->size; index++)\n // check for weight\n if (gsl_vector_int_get(indep_weight, index))\n {\n\t// take the independent value from the vector\n\txvals_new[act_index] = gsl_vector_get(indep_data, index);\n\n\t// compute the new dependent value bye multiplying\n\t// the brightness with the sensitivity\n\tyvals_new[act_index] = eval_interp(tpass, xvals_new[act_index])\n\t * get_flux_from_SED(actdir->SED, xvals_new[act_index]);\n\n\t// enhance the counter\n\tact_index++;\n }\n\n // create a new interpolator\n combine = create_interp(n_new, TPASS_INTERP_TYPE, xvals_new, yvals_new);\n\n\n // release memory in the weight vector\n gsl_vector_int_free(indep_weight);\n\n // return the interpolator\n return combine;\n}\n\n\n/*\n * Function: get_filter_sensitivity\n * The function reads in a total passband file from fits format\n * and stroes the data as an interpolation function. The dependent\n * data values are transformed from throughput to sensitivity,\n * and the interpolation function is returned.\n *\n * Parameters:\n * @param tpass_file - the full name of the total passband\n * @param tel_are - the collecting area of the telescope\n *\n * Returns:\n * @return tpass - the filter sensitivity\n */\ninterpolator *\nget_filter_sensitivity(const char tpass_file[], const double tel_area)\n{\n interpolator *tpass;\n\n double h_erg = 6.6260693E-27;\n double c_cm = 2.99792458E+10;\n\n double factor = 0.0;\n\n int index=0;\n\n fprintf(stdout, \"Load Total bandpass table :%s\\n\", tpass_file);\n tpass = create_interp_ftable(tpass_file, 2,\"WAVELENGTH\",\"THROUGHPUT\", TPASS_INTERP_TYPE);\n\n for (index=0; index < tpass->nvals; index++)\n {\n // compute the conversion factor\n factor = tel_area / (h_erg * c_cm / (1.0E-08 * tpass->xvals[index]));\n\n // apply the conversion factor\n tpass->yvals[index] = tpass->yvals[index] * factor;\n }\n\n // return the filter sensitivity\n return tpass;\n}\n", "meta": {"hexsha": "99c2c3a04edd345cbafbb91068d5b1cbb3ea2533", "size": 12081, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/dirimage_model.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/dirimage_model.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/dirimage_model.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": 27.7087155963, "max_line_length": 120, "alphanum_fraction": 0.6797450542, "num_tokens": 3389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.320821300824607, "lm_q1q2_score": 0.2431165759498954}} {"text": "/* ---------------------------------------------------------------- *\n * hod.h\t\t\t\t\t\t *\n * Martin Kilbinger, Henry J. McCracken, Jean Coupon 2008-2013 *\n * ---------------------------------------------------------------- */\n\n#ifndef __HOD_H\n#define __HOD_H\n\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 \"io.h\"\n#include \"errorlist.h\"\n#include \"config.h\"\n#include \"maths.h\"\n\n#include \"cosmo.h\"\n#include \"nofz.h\"\n#include \"halomodel.h\"\n\n/* errors */\n#define HOD_BASE -50000\n#define HOD_MSTAR_MAX HOD_BASE + 1\n#define HOD_NGAL_FIT HOD_BASE + 2\n\n#define GM_base -400000\n#define GM_nz_type GM_base + 1\n#define GM_pi_max GM_base + 2\n#define GM_SHMR GM_base + 3\n#define GM_SMF GM_base + 4\n#define GM_GGL GM_base + 5\n#define GM_MSTAR_MAX GM_base + 6\n#define GM_ETA GM_base + 7\n\n\n\n/* Limits for xi(r), 1- and 2-halo, in Mpc.h */\n#define RMIN1 0.001\n#define RMAX1 5.0\n#define RMIN2 0.1\n#define RMAX2 400.0\n\n#define RMIN RMIN1\n#define RMAX RMAX2\n#define NR 50\n\n#define MAXCHAR 1024\n#define NLINES 100\n\n#define NFIELD 100\n#define NCHAR 20\n\n/* GG: galaxy-galaxy stuff. GM: galaxy-dar matter stuff (lensing) */\n#define GG 0\n#define GM 1\n\n#define getDoubleValue(array,col) atof(array+NCHAR*(col-1))\n#define getIntValue(array,col) atoi(array+NCHAR*(col-1))\n#define getCharValue(array,col) array+NCHAR*(col-1)\n#define getLine(array,i) array+NFIELD*NCHAR*i\n\n#define Nhalodata_t 4\ntypedef enum {w_of_theta, wp_rp, deltaSigma, smf} halodata_t; \n#define shalodata_t(i) ( \\\n i==w_of_theta ? \"w_of_theta\" : \\\n i==wp_rp ? \"wp_rp\" : \\\n i==deltaSigma ? \"deltaSigma\" : \\\n i==smf ? \"smf\" : \\\n \"\")\n\n#define Nhalomode_t 3\ntypedef enum {galcorr_var, galcorr_cov, galcorr_log} halomode_t;\n#define shalomode_t(i) ( \\\n i==galcorr_var ? \"galcorr_var\" : \\\n i==galcorr_cov ? \"galcorr_cov\" : \\\n i==galcorr_log ? \"galcorr_log\" : \\\n \"\")\n\n#define Nngal_fit_t 5\ntypedef enum {ngal_log_fit, ngal_lin_fit, ngal_no_fit, ngal_lin_fit_only} ngal_fit_t;\n#define sngal_fit_t(i) ( \\\n i==ngal_log_fit ? \"ngal_log_fit\" : \\\n i==ngal_lin_fit ? \"ngal_lin_fit\" : \\\n i==ngal_no_fit ? \"ngal_no_fit\" : \\\n i==ngal_lin_fit_only ? \"ngal_lin_fit_only\" : \\\n \"\")\n\n#define Nintconst_t 2\ntypedef enum {constant, random_file} intconst_t;\n#define sintconst_t(i) ( \\\n i==constant ? \"constant\" : \\\n i==random_file ? \"random_file\" : \\\n \"\")\n\n\ntypedef struct { \n char WTHETA[500];\n char COVNAME[500];\n char DNDZ[500];\n char OUTFILE[500];\n int nbins; \n double ngal, ngalerr, area_deg, intconst, delta;\n double alpha_min,alpha_max,dalpha;\n double M1_min,M1_max,dM1;\n double Mmin_min,Mmin_max,dMmin;\n double Ngal_min,Ngal_max,dNgal;\n ngal_fit_t ngal_fit_type;\n} config_hm_info;\n\n\n/* ---------------------------------------------------------------- *\n * Global variables and functions *\n * ---------------------------------------------------------------- */\n\n\n#define ODD 0\n#define EVEN 1\n\n#define ABS(a) ((a) < 0 ? -(a) : (a))\n#define PARITY(a) (a)%2 ? ODD : EVEN\n#define FFTLog_SWAP(a,b) {FFTLog_TMP = (a); (a) = (b); (b) = FFTLog_TMP;}\n\n\n#define CHANGE(fct) int change_##fct(cosmo_hm*, cosmo_hm*)\nCHANGE(w_of_theta);\nCHANGE(Pthg);\nCHANGE(HOD);\nCHANGE(ngd);\nCHANGE(vc);\n#undef CHANGE\n\n\n/* ---------------------------------------------------------------- *\n * New types *\n * ---------------------------------------------------------------- */\n\n/* This structure contains w_theta input data */\ntypedef struct {\n int nbins, nbins_RR;\n double *th;\n double *w;\n double *werr; /* Error bars */\n double *wcov; /* Covariance matrix */\n double *th_RR; /* theta for random pairs (can be larger than for the data [even recommended]) */\n double *RR; /* Random pairs (for the integral constraint) */\n double ngal; /* Galaxy number density*/\n double ngal_err;\n} wt_t;\n\n\n\ntypedef struct Nz_hist\n{\n int nbins;\n double *z;\n double *n;\n double zmin;\n double zmax;\n double mean;\n double dz;\n double Norm;\n double max;\n} Nz_hist;\n\n\n/* ---------------------------------------------------------------- *\n * log-likelihood *\n * ---------------------------------------------------------------- */\n\ndouble chi2_hm(cosmo_hm *model, halodata_t halodata, halomode_t halomode, const wt_t* data, ngal_fit_t ngal_fit_type,\n\t double ngal, double ngalerr, intconst_t intconst_type, error **err);\n\n/* ---------------------------------------------------------------- *\n * w(theta) and wp(rp) *\n * ---------------------------------------------------------------- */\n\ndouble *woftheta(cosmo_hm *model, pofk_t pofk, double *theta, int Ntheta, int i_bin, int j_bin, error **err);\ndouble *woftheta_FFTLog_total(cosmo_hm *model, double ln_theta_min, double ln_delta_theta, int Ntheta,\n\t\t\t double **theta, int i_bin, int j_bin, error **err);\ndouble *wp(cosmo_hm *model, pofk_t pofk, const double *rp, int Nrp, double pi_max, int type, error **err);\ndouble int_for_wp(double logr, void *params, error **err);\n\n/* ---------------------------------------------------------------- *\n * Lensing functions (only for leauthaud11 model) *\n * ---------------------------------------------------------------- */\n\ndouble *DeltaSigma(cosmo_hm *model, pofk_t pofk, const double *r, int N, error **err);\ndouble int_for_Sigma(double logr, void *params, error **err);\n\n/* ---------------------------------------------------------------- *\n * Stellar mass function (only for leauthaud11 model) *\n * ---------------------------------------------------------------- */\n\ndouble *dNdlogM10stellar(cosmo_hm *model, double *log10Mstellar, int N, error **err);\ndouble *dNdlogM10stellar_c(cosmo_hm *model, double *log10Mstellar, int N, error **err);\ndouble *dNdlogM10stellar_s(cosmo_hm *model, double *log10Mstellar, int N, error **err);\n\n/* ---------------------------------------------------------------- *\n * HOD P(k) and xi(r) *\n * ---------------------------------------------------------------- */\n\ndouble *xiofr(cosmo_hm *model, pofk_t pofk, const double *r, int N, int type, error **err);\ndouble *xi_1hcs(cosmo_hm *model,double a, const double *r, int N, int type, error **err);\ndouble int_for_xi_1hcs(double logM, void *params, error **err);\ndouble *xi_1hss(cosmo_hm *model,double a, const double *r, int N, int type, error **err);\ndouble P1hss(double k, void *params);\ndouble int_for_P1hss(double logM, void *params, error **err);\ndouble concentration_sat(cosmo_hm *model, double Mh, double a, error **err);\ndouble *xi_2h(cosmo_hm *model,double a, const double *r, int N, int type, error **err);\ndouble *xi_P_NL(cosmo_hm *model, double a, const double *r, int N, error **err);\ndouble FFTLog_P_NL(double k, void *params);\ndouble P2h(double k, void *params);\ndouble int_for_P2h(double logM, void *params, error **err);\ndouble int_for_P2h_dm(double logM, void *params, error **err);\ndouble bias_r(double M, void *params);\n\n/* ---------------------------------------------------------------- *\n * HOD model functions *\n * ---------------------------------------------------------------- */\n\ndouble log10_fSHMR(double log10Mh, cosmo_hm *model);\ndouble log10_fSHMR_inv_minus_x(double log10Mstar, void *p);\ndouble log10_fSHMR_inv(double log10Mstar, cosmo_hm *model);\ndouble Ngal_c(cosmo_hm *model, double Mh, double Mstellar_min, double Mstellar_max);\ndouble int_for_Ngal_c(double Mstellar, void *params, error **err);\ndouble phi_c_Mstellar(cosmo_hm *model, double log10Mstellar, double Mh, error **err);\ndouble sigma_log_M(cosmo_hm *model, double log10Mstellar, error **err);\ndouble eta_cen(cosmo_hm *model, double Mh, error **err);\ndouble Ngal_s(cosmo_hm *model, double M, double Mstellar_min, double Mstellar_max);\ndouble Ngal(cosmo_hm *model, double M, double Mstellar_min, double Mstellar_max);\n\ndouble av_Mh_given_Mstar(cosmo_hm *model, double Mstellar, double a, error **err);\ndouble int_for_phi_c_Mh(double log10Mh, void *params, error **err);\ndouble int_for_phi_c_Mh_norm(double log10Mh, void *params, error **err); \n\n/* ---------------------------------------------------------------- *\n * Deduced quantities *\n * ---------------------------------------------------------------- */\ndouble Mstar_tot_c(cosmo_hm *model, double Mh, double Mstellar_min, double Mstellar_max, error **err);\ndouble int_for_Mstar_tot_c(double logMstar, void *params, error **err);\ndouble Mstar_tot_s(cosmo_hm *model, double Mh, double Mstellar_min, double Mstellar_max, error **err);\ndouble int_for_Mstar_tot_s(double logMstar, void *params, error **err);\ndouble av_gal_bias(cosmo_hm *model, double a, error **err);\ndouble int_for_av_gal_bias(double logM, void *intpar, error **err);\ndouble av_halo_mass(cosmo_hm *model, double a, error **err);\ndouble int_for_av_halo_mass(double logM, void *intpar, error **err);\ndouble mass_weighted_av_stellar_mass(cosmo_hm *model, double a, error **err);\ndouble int_for_mass_weighted_av_stellar_mass(double logM, void *params, error **err);\ndouble int_for_mass_denum_weighted_av_stellar_mass(double logM, void *params, error **err);\ndouble av_stellar_mass(cosmo_hm *model, double a, error **err);\ndouble int_for_av_stellar_mass(double logM, void *params, error **err);\ndouble av_frsat(cosmo_hm *model, double a, error **err);\ndouble int_for_av_frsat(double logM, void *intpar, error **err);\ndouble av_halo_bias(cosmo_hm *model, double a, error **err);\ndouble int_for_av_halo_bias(double logM, void *intpar, error **err);\ndouble dn_dlnM_integrand(double logM, void *intpar, error **err);\n\n/* ---------------------------------------------------------------- *\n * Physical quantities *\n * ---------------------------------------------------------------- */\n\ndouble vc(cosmo_hm *model,double zmin, double zmax, error **err);\ndouble int_for_vc(double z, void *params, error **err);\ndouble logM_lim(cosmo_hm *model, double a, double r, error **err);\ndouble ngal_triax(cosmo_hm *model, double a, double r, error **err);\ndouble ngal_den(cosmo_hm *model, double a, double logMlim, double Mstellar_min, double Mstellar_max, error **err);\ndouble int_for_ngal_den(double logM, void *params, error **err);\ndouble ngal_den_c(cosmo_hm *model, double a, double logMlim, double Mstellar_min, double Mstellar_max, error **err);\ndouble int_for_ngal_den_c(double logM, void *params, error **err);\ndouble ngal_den_s(cosmo_hm *model, double a, double logMlim, double Mstellar_min, double Mstellar_max, error **err);\ndouble int_for_ngal_den_s(double logM, void *params, error **err);\ndouble ngal_den_vol(cosmo_hm *model, error **err);\ndouble ngal_weighted(cosmo_hm *model, error **err);\n\n/* ---------------------------------------------------------------- *\n * FFTLog *\n * ---------------------------------------------------------------- */\n\ndouble xi_from_Pkr(gsl_function *ak, double r_prime, FFTLog_config *fc, error **err);\nvoid FFTLog(FFTLog_config *fc, const gsl_function *ar_in,double *k, double *ak_out, int dir, error **err);\nFFTLog_config *FFTLog_init(int N, double min, double max, double q, double mu);\nvoid FFTLog_free(FFTLog_config *fc);\nFFTLog_complex FFTLog_U_mu(double mu, FFTLog_complex z);\n\n/* ---------------------------------------------------------------- *\n * Utils *\n * ---------------------------------------------------------------- */\n\nvoid updateFrom_hm(cosmo_hm* avant, cosmo_hm* apres, error **err);\nint change_vc(cosmo_hm *avant, cosmo_hm *apres);\nint change_ngd(cosmo_hm *avant, cosmo_hm *apres);\nint change_HOD(cosmo_hm *avant, cosmo_hm *apres);\nint change_Pthg(cosmo_hm* avant, cosmo_hm* apres);\nint change_w_of_theta(cosmo_hm *avant, cosmo_hm *apres);\nwt_t *init_wt_t(double nlines, int wcov, error **err);\nvoid free_wt_t(wt_t **model);\nwt_t *read_wtheta(const char *data_file_name, intconst_t intconst_type, double delta, double intconst, const char *ran_file_name, error **err);\nint getStrings(char *line, char *strings, char *delimit, size_t *N, error **err);\nvoid read_config_hm_file(config_hm_info *config, char cname[], error **err);\nNz_hist *get_nz(redshift_t *nz_mk, int n_bin, error **err);\nvoid free_nz( Nz_hist *nz);\ndouble normalize(double *data, size_t Nbins, double binsize,error **err);\n\n/* ---------------------------------------------------------------- *\n * Obsolete stuff *\n * ---------------------------------------------------------------- */\n\ndouble *woftheta_total_OBSOLETE(cosmo_hm *model, double log_theta_min, double log_delta_theta, int Ntheta, error **err);\nnz_t *read_dndz_OBSOLETE(char *infile,error **err);\ndouble Ngal_mean(cosmo_hm *model, double a, error **err);\n\ndouble xir_mwolk(cosmo_hm *model, double a, double r, error **err);\nwt_t *read_wtheta_mwolk(const char *name, double delta, double intconst, error **err);\ndouble chi2_mwolk(cosmo_hm *model, const wt_t* data, ngal_fit_t ngal_fit_type,\n\t\t double ngal, double ngalerr, double area, error **err);\ndouble wp_mwolk(cosmo_hm *model, double rp, error **err);\ndouble compute_chisq_wp(cosmo_hm *model, const wt_t *wth, double ngd_obs, double ngd_err,\n\t\t\tngal_fit_t ngal_fit_type, double *ngd, int dologw, error **err);\n\n\n#endif\n", "meta": {"hexsha": "0d997b51b9bea7d3f919f9d13e743db9b98155c3", "size": 13815, "ext": "h", "lang": "C", "max_stars_repo_path": "src/nicaea_2.5/halomodel/include/hod.h", "max_stars_repo_name": "danielgruen/ccv", "max_stars_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-08-11T20:38:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-08T03:19:03.000Z", "max_issues_repo_path": "src/nicaea_2.5/halomodel/include/hod.h", "max_issues_repo_name": "danielgruen/ccv", "max_issues_repo_head_hexsha": "722db5bab850bccba3c7c003e0416cefa6d94c62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/nicaea_2.5/halomodel/include/hod.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": 41.6114457831, "max_line_length": 143, "alphanum_fraction": 0.5955845096, "num_tokens": 3650, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.241611911058417}} {"text": "/**\n * @file batchg_zgemm.c\n *\n * @brief BBLAS batchg_zgemm double _Complex routine.\n *\n * BBLAS is a software package provided by Univ. of Manchester,\n * Univ. of Tennessee.\n *\n * @version 1.0.0\n * @author Samuel D. Relton\n * @author Pedro V. Lara\n * @author Mawussi Zounon\n * @date 2016-06-03\n *\n **/\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n/**\n * Code generation\n * @precisions normal z -> c d s\n **/\n#endif\n\n#include \n#include \"bblas.h\"\n\n#define COMPLEX\n\n/**\n Purpose\n -------\n batchg_zgemm is a batch version of zgemm for groups \n of batched with different sizes.\n\tIt performs the matrix-matrix operations\n\n\tarrayC[i] = alpha[i]*op( arrayA[i] )*op( arrayB[i] ) + beta[i]*arrayC[i],\n\n\twhere op( X ) is one of\n\n\top( X ) = X or\n\top( X ) = X**T or\n\top( X ) = X**H,\n\n\talpha[i] and beta[i] are scalars, and arrayA[i], arrayB[i] and C are matrices, with\n\top( arrayA[i] ) an m by k matrix, op( arrayB[i] ) a k by n matrix and arrayC[i]\n\tan m by n matrix.\n\n\tGroup Batch Operations\n\t----------------------\n\t\n - all parameters that are arrays must have length at least group_count.\n\t- all parameters that are arrays must have all values set.\n\n\tParameters\n\t----------\n\t@param[in]\n\ttransA Array of enum BBLAS_TRANS.\n\t On entry, transA[i] specifies the form of op( arrayA[i] ) to be used in\n\t\t\t the matrix multiplication as follows:\n - = BblasNoTrans: op( arrayA[i] ) = arrayA[i].\n - = BblasTrans: op( arrayA[i] ) = arrayA[i]**T.\n - = BblasConjTrans: op( arrayA[i] ) = arrayA[i]**H.\n\n\t@param[in]\n\ttransB Array of enum BBLAS_TRANS.\n\t On entry, transB[i] specifies the form of op( arrayB[i] ) to be used in\n the matrix multiplication as follows:\n - = BblasNoTrans: op( arrayB[i] ) = arrayB[i].\n - = BblasTrans: op( arrayB[i] ) = arrayB[i]**T.\n - = BblasConjTrans: op( arrayB[i] ) = arrayB[i]**H.\n\n\t@param[in]\n\tM Array of int.\n Each element M[i] specifies the number of rows of the matrix\n op( arrayA[i] ) and of the matrix arrayC[i]. M[i] must be greater than zero.\n\n\t@param[in]\n\tN Array of int.\n Each element N[i] specifies the number of columns of the matrix\n op( arrayB[i] ) and the number of columns of the matrix arrayC[i].\n \t\t N[i] must be greater than zero.\n\n @param[in]\n K Array of int.\n\t Each element K[i] specifies the number of columns of the matrix\n op( arrayA[i] ) and the number of rows of the matrix op( arrayB[i] ).\n\t\t K[i] must be greater than zero.\n\n @param[in]\n alpha Array of complex_16.\n\n @param[in]\n arrayA Array of pointers.\n Each element arrayA[i] is a pointer to a COMPLEX_16 matrix of\n \t\t dimension lda[i] by Ka[i], where Ka[i] is K[i] when transA[i] = BblasNoTrans,\n \t\t and is M[i] otherwise.\n When using transA[i] = BblasNoTrans the leading M[i] by K[i]\n part of arrayA[i] must contain the matrix elements, otherwise\n the leading K[i] by M[i] part of arrayA[i] must contain the\n matrix elements.\n\n @param[in]\n lda Array of int.\n Each element lda[i] specifies the first dimension of arrayA[i] as declared\n in the calling (sub) program. When transA[i] = BblasNoTrans then\n lda[i] must be at least max( 1, M[i] ), otherwise lda[i] must be at\n least max( 1, K[i] ).\n\n @param[in]\n arrayB Array of pointers.\n \t\t Each element arrayB[i] is a pointer to a COMPLEX_16 matrix of\n \t\t dimension ldb[i] by Kb[i], where Kb[i] is N[i] when transB[i] = BblasNoTrans,\n \t\t and is K[i] otherwise.\n When using transB[i] = BblasNoTrans the leading K[i] by N[i]\n part of arrayB[i] must contain the matrix elements, otherwise\n the leading N[i] by K[i] part of arrayB[i] must contain the\n matrix elements.\n\n\n @param[in]\n ldb Array of int.\n \t\t Each element ldb[i] specifies the first dimension of arrayB[i] as declared\n in the calling (sub) program. When transB[i] = BblasNoTrans then\n ldb[i] must be at least max( 1, K[i] ), otherwise ldb[i] must be at\n least max( 1, N[i] ).\n\n @param[in]\n beta Array of complex_16.\n When beta[i] is set to zero arrayC[i] need not be set on input.\n\n @param[in,out]\n arrayC Array of pointers.\n\t Each element arrayC[i] is a pointer to a COMPLEX_16 matrix of\n \t dimension ldc[i] by N[i].\n \t Before entry, the leading M[i] by N[i] part of the arrayC[i] must\n contain a matrix C, except when beta is zero, in which\n case C need not be set on entry.\n On exit, the matrix arrayC[i] is overwritten by the M[i] by N[i] matrix\n ( alpha[i]*op( arrayA[i] )*op( arrayB[i] ) + beta[i]*arrayC[i] ).\n\n @param[in]\n ldc Array of int.\n \t Each element ldc[i] specifies the first dimension of arrayC[i] as declared\n \t in the calling (sub) program. The value ldc[i] must be at least\n \t max( 1, M[i] )\n\n @param[in]\n batch_count int\n The number of matrices to operate on.\n\n @param[in,out]\n info Array of int.\n Each element info[i] is the error return code of the ith group,\n these need not be set on entry.\n \t The error codes can be found in bblas_macros.h.\n **/\nvoid batchg_zgemm(\n const enum BBLAS_TRANS *transA, const enum BBLAS_TRANS *transB,\n const int *M, const int *N, const int *K,\n const BBLAS_Complex64_t *alpha,\n const BBLAS_Complex64_t **arrayA, const int *lda,\n const BBLAS_Complex64_t **arrayB,\n const int *ldb, const BBLAS_Complex64_t *beta,\n BBLAS_Complex64_t **arrayC, const int *ldc, \n\tconst int group_count, const int *group_size,\n int *info)\n{\n /* Local variables */\n int group_iter;\n int offset = 0;\n char func_name[15] = \"batchg_zgemm\";\n\n\t/* Check input arguments */\n if (group_count < 0)\n {\n\t xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1);\n return;\n }\n\n\t/* Check group_size and call fixed batch computation */\n\tfor (group_iter = 0; group_iter < group_count; group_iter++)\n\t{\n\t\tif (group_size[group_iter] < 0)\n\t\t{\n\t\t\txerbla_batch(func_name, BBLAS_ERR_GROUP_SIZE, group_iter);\n\t\t info[group_iter] = BBLAS_ERR_GROUP_SIZE;\n\t\t\tcontinue;\n\t\t}\n\n /* Call to bblas_zgemm_batchf */\n batchf_zgemm(\n transA[group_iter],\n transB[group_iter],\n M[group_iter],\n N[group_iter],\n K[group_iter],\n alpha[group_iter],\n arrayA+offset,\n lda[group_iter],\n arrayB+offset,\n ldb[group_iter],\n beta[group_iter],\n arrayC+offset,\n ldc[group_iter],\n group_size[group_iter],\n &info[group_iter]); \n\n offset += group_size[group_iter]; \n }\n}\n#undef COMPLEX\n", "meta": {"hexsha": "cfc95ef6777bf261340976ebd265602c33d65cee", "size": 7075, "ext": "c", "lang": "C", "max_stars_repo_path": "src/batchg_zgemm.c", "max_stars_repo_name": "mawussi/BBLAS-group", "max_stars_repo_head_hexsha": "3df5d3379b73d4716d4850aaa9f04e808d2c850a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T11:59:07.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-31T22:24:49.000Z", "max_issues_repo_path": "src/batchg_zgemm.c", "max_issues_repo_name": "sdrelton/bblas_api_test", "max_issues_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/batchg_zgemm.c", "max_forks_repo_name": "sdrelton/bblas_api_test", "max_forks_repo_head_hexsha": "117f3538b3ab43ade0ad53950ecac25c1a192bc7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3726415094, "max_line_length": 88, "alphanum_fraction": 0.5967491166, "num_tokens": 2003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6992544085240401, "lm_q2_score": 0.34510525748676846, "lm_q1q2_score": 0.24131637270244682}} {"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:10 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 6 */\n\n/*\n * This function contains 72 FP additions, 38 FP multiplications,\n * (or, 54 additions, 20 multiplications, 18 fused multiply/add),\n * 25 stack variables, and 48 memory accesses\n */\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_hc2hc_backward_6(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 + (6 * iostride);\n {\n\t fftw_real tmp71;\n\t fftw_real tmp75;\n\t fftw_real tmp80;\n\t fftw_real tmp82;\n\t fftw_real tmp74;\n\t fftw_real tmp76;\n\t fftw_real tmp69;\n\t fftw_real tmp70;\n\t fftw_real tmp77;\n\t fftw_real tmp81;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp69 = X[0];\n\t tmp70 = X[3 * iostride];\n\t tmp71 = tmp69 - tmp70;\n\t tmp75 = tmp69 + tmp70;\n\t {\n\t fftw_real tmp78;\n\t fftw_real tmp79;\n\t fftw_real tmp72;\n\t fftw_real tmp73;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp78 = Y[-2 * iostride];\n\t tmp79 = Y[-iostride];\n\t tmp80 = K1_732050807 * (tmp78 + tmp79);\n\t tmp82 = K1_732050807 * (tmp78 - tmp79);\n\t tmp72 = X[2 * iostride];\n\t tmp73 = X[iostride];\n\t tmp74 = tmp72 - tmp73;\n\t tmp76 = tmp72 + tmp73;\n\t }\n\t X[3 * iostride] = tmp71 + (K2_000000000 * tmp74);\n\t tmp77 = tmp71 - tmp74;\n\t X[iostride] = tmp77 - tmp80;\n\t X[5 * iostride] = tmp77 + tmp80;\n\t X[0] = tmp75 + (K2_000000000 * tmp76);\n\t tmp81 = tmp75 - tmp76;\n\t X[2 * iostride] = tmp81 + tmp82;\n\t X[4 * iostride] = tmp81 - tmp82;\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 + 5) {\n\t fftw_real tmp15;\n\t fftw_real tmp46;\n\t fftw_real tmp25;\n\t fftw_real tmp52;\n\t fftw_real tmp22;\n\t fftw_real tmp35;\n\t fftw_real tmp49;\n\t fftw_real tmp62;\n\t fftw_real tmp32;\n\t fftw_real tmp39;\n\t fftw_real tmp55;\n\t fftw_real tmp59;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp13;\n\t fftw_real tmp14;\n\t fftw_real tmp23;\n\t fftw_real tmp24;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp13 = X[0];\n\t tmp14 = Y[-3 * iostride];\n\t tmp15 = tmp13 + tmp14;\n\t tmp46 = tmp13 - tmp14;\n\t tmp23 = Y[0];\n\t tmp24 = X[3 * iostride];\n\t tmp25 = tmp23 - tmp24;\n\t tmp52 = tmp23 + tmp24;\n\t }\n\t {\n\t fftw_real tmp18;\n\t fftw_real tmp47;\n\t fftw_real tmp21;\n\t fftw_real tmp48;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp16;\n\t\t fftw_real tmp17;\n\t\t fftw_real tmp19;\n\t\t fftw_real tmp20;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp16 = X[2 * iostride];\n\t\t tmp17 = Y[-5 * iostride];\n\t\t tmp18 = tmp16 + tmp17;\n\t\t tmp47 = tmp16 - tmp17;\n\t\t tmp19 = Y[-4 * iostride];\n\t\t tmp20 = X[iostride];\n\t\t tmp21 = tmp19 + tmp20;\n\t\t tmp48 = tmp19 - tmp20;\n\t }\n\t tmp22 = tmp18 + tmp21;\n\t tmp35 = K866025403 * (tmp18 - tmp21);\n\t tmp49 = tmp47 + tmp48;\n\t tmp62 = K866025403 * (tmp47 - tmp48);\n\t }\n\t {\n\t fftw_real tmp28;\n\t fftw_real tmp54;\n\t fftw_real tmp31;\n\t fftw_real tmp53;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp26;\n\t\t fftw_real tmp27;\n\t\t fftw_real tmp29;\n\t\t fftw_real tmp30;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp26 = Y[-2 * iostride];\n\t\t tmp27 = X[5 * iostride];\n\t\t tmp28 = tmp26 - tmp27;\n\t\t tmp54 = tmp26 + tmp27;\n\t\t tmp29 = Y[-iostride];\n\t\t tmp30 = X[4 * iostride];\n\t\t tmp31 = tmp29 - tmp30;\n\t\t tmp53 = tmp29 + tmp30;\n\t }\n\t tmp32 = tmp28 + tmp31;\n\t tmp39 = K866025403 * (tmp31 - tmp28);\n\t tmp55 = tmp53 - tmp54;\n\t tmp59 = K866025403 * (tmp54 + tmp53);\n\t }\n\t X[0] = tmp15 + tmp22;\n\t {\n\t fftw_real tmp36;\n\t fftw_real tmp42;\n\t fftw_real tmp40;\n\t fftw_real tmp44;\n\t fftw_real tmp34;\n\t fftw_real tmp38;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp34 = tmp25 - (K500000000 * tmp32);\n\t tmp36 = tmp34 - tmp35;\n\t tmp42 = tmp35 + tmp34;\n\t tmp38 = tmp15 - (K500000000 * tmp22);\n\t tmp40 = tmp38 - tmp39;\n\t tmp44 = tmp38 + tmp39;\n\t {\n\t\t fftw_real tmp33;\n\t\t fftw_real tmp37;\n\t\t fftw_real tmp41;\n\t\t fftw_real tmp43;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp33 = c_re(W[1]);\n\t\t tmp37 = c_im(W[1]);\n\t\t Y[-3 * iostride] = (tmp33 * tmp36) - (tmp37 * tmp40);\n\t\t X[2 * iostride] = (tmp37 * tmp36) + (tmp33 * tmp40);\n\t\t tmp41 = c_re(W[3]);\n\t\t tmp43 = c_im(W[3]);\n\t\t Y[-iostride] = (tmp41 * tmp42) - (tmp43 * tmp44);\n\t\t X[4 * iostride] = (tmp43 * tmp42) + (tmp41 * tmp44);\n\t }\n\t }\n\t Y[-5 * iostride] = tmp25 + tmp32;\n\t {\n\t fftw_real tmp50;\n\t fftw_real tmp56;\n\t fftw_real tmp45;\n\t fftw_real tmp51;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp50 = tmp46 + tmp49;\n\t tmp56 = tmp52 - tmp55;\n\t tmp45 = c_re(W[2]);\n\t tmp51 = c_im(W[2]);\n\t X[3 * iostride] = (tmp45 * tmp50) + (tmp51 * tmp56);\n\t Y[-2 * iostride] = (tmp45 * tmp56) - (tmp51 * tmp50);\n\t }\n\t {\n\t fftw_real tmp60;\n\t fftw_real tmp66;\n\t fftw_real tmp64;\n\t fftw_real tmp68;\n\t fftw_real tmp58;\n\t fftw_real tmp63;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp58 = tmp46 - (K500000000 * tmp49);\n\t tmp60 = tmp58 - tmp59;\n\t tmp66 = tmp58 + tmp59;\n\t tmp63 = tmp52 + (K500000000 * tmp55);\n\t tmp64 = tmp62 + tmp63;\n\t tmp68 = tmp63 - tmp62;\n\t {\n\t\t fftw_real tmp57;\n\t\t fftw_real tmp61;\n\t\t fftw_real tmp65;\n\t\t fftw_real tmp67;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp57 = c_re(W[0]);\n\t\t tmp61 = c_im(W[0]);\n\t\t X[iostride] = (tmp57 * tmp60) + (tmp61 * tmp64);\n\t\t Y[-4 * iostride] = (tmp57 * tmp64) - (tmp61 * tmp60);\n\t\t tmp65 = c_re(W[4]);\n\t\t tmp67 = c_im(W[4]);\n\t\t X[5 * iostride] = (tmp65 * tmp66) + (tmp67 * tmp68);\n\t\t Y[0] = (tmp65 * tmp68) - (tmp67 * tmp66);\n\t }\n\t }\n }\n if (i == m) {\n\t fftw_real tmp1;\n\t fftw_real tmp6;\n\t fftw_real tmp4;\n\t fftw_real tmp5;\n\t fftw_real tmp9;\n\t fftw_real tmp11;\n\t fftw_real tmp12;\n\t fftw_real tmp10;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp1 = X[iostride];\n\t tmp6 = Y[-iostride];\n\t {\n\t fftw_real tmp2;\n\t fftw_real tmp3;\n\t fftw_real tmp7;\n\t fftw_real tmp8;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp2 = X[2 * iostride];\n\t tmp3 = X[0];\n\t tmp4 = tmp2 + tmp3;\n\t tmp5 = K1_732050807 * (tmp2 - tmp3);\n\t tmp7 = Y[-2 * iostride];\n\t tmp8 = Y[0];\n\t tmp9 = tmp7 + tmp8;\n\t tmp11 = K1_732050807 * (tmp7 - tmp8);\n\t }\n\t X[0] = K2_000000000 * (tmp1 + tmp4);\n\t tmp12 = (K2_000000000 * tmp1) - tmp4;\n\t X[2 * iostride] = tmp11 - tmp12;\n\t X[4 * iostride] = tmp12 + tmp11;\n\t X[3 * iostride] = K2_000000000 * (tmp6 - tmp9);\n\t tmp10 = (K2_000000000 * tmp6) + tmp9;\n\t X[iostride] = -(tmp5 + tmp10);\n\t X[5 * iostride] = tmp5 - tmp10;\n }\n}\n\nstatic const int twiddle_order[] =\n{1, 2, 3, 4, 5};\nfftw_codelet_desc fftw_hc2hc_backward_6_desc =\n{\n \"fftw_hc2hc_backward_6\",\n (void (*)()) fftw_hc2hc_backward_6,\n 6,\n FFTW_BACKWARD,\n FFTW_HC2HC,\n 146,\n 5,\n twiddle_order,\n};\n", "meta": {"hexsha": "54e69795aac0941016378d055efa4ff5b50eb46d", "size": 8619, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhb_6.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_6.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_6.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.5397350993, "max_line_length": 125, "alphanum_fraction": 0.5816219979, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.24086018274889492}} {"text": "/* interpolation/spline.c\n * \n * Copyright (C) 2001, 2007 Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\ngsl_spline *\ngsl_spline_alloc (const gsl_interp_type * T, size_t size)\n{\n gsl_spline * spline = (gsl_spline *) malloc (sizeof(gsl_spline));\n \n if (spline == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for spline struct\", \n GSL_ENOMEM);\n }\n \n spline->interp = gsl_interp_alloc (T, size);\n \n if (spline->interp == NULL)\n {\n free (spline); \n GSL_ERROR_NULL (\"failed to allocate space for interp\", GSL_ENOMEM);\n };\n \n spline->x = (double *) malloc (size * sizeof(double));\n\n if (spline->x == NULL)\n {\n gsl_interp_free(spline->interp);\n free(spline);\n GSL_ERROR_NULL (\"failed to allocate space for x\", GSL_ENOMEM);\n }\n\n spline->y = (double *) malloc (size * sizeof(double));\n\n if (spline->y == NULL)\n {\n free(spline->x);\n gsl_interp_free(spline->interp);\n free(spline);\n GSL_ERROR_NULL (\"failed to allocate space for y\", GSL_ENOMEM);\n }\n \n spline->size = size;\n\n return spline;\n}\n\nint\ngsl_spline_init (gsl_spline * spline, const double x_array[], const double y_array[], size_t size)\n{\n if (size != spline->size)\n {\n GSL_ERROR (\"data must match size of spline object\", GSL_EINVAL);\n }\n \n memcpy (spline->x, x_array, size * sizeof(double));\n memcpy (spline->y, y_array, size * sizeof(double));\n\n {\n int status = gsl_interp_init (spline->interp, x_array, y_array, size);\n return status;\n }\n}\n\nconst char *\ngsl_spline_name(const gsl_spline * spline)\n{\n return gsl_interp_name(spline->interp);\n}\n\nunsigned int\ngsl_spline_min_size(const gsl_spline * spline)\n{\n return gsl_interp_min_size(spline->interp);\n}\n\nvoid\ngsl_spline_free (gsl_spline * spline)\n{\n RETURN_IF_NULL (spline);\n gsl_interp_free (spline->interp);\n free (spline->x);\n free (spline->y);\n free (spline);\n}\n\nint\ngsl_spline_eval_e (const gsl_spline * spline, \n double x,\n gsl_interp_accel * a, double *y)\n{\n return gsl_interp_eval_e (spline->interp, \n spline->x, spline->y,\n x, a, y);\n}\n\ndouble\ngsl_spline_eval (const gsl_spline * spline,\n double x,\n gsl_interp_accel * a)\n{\n return gsl_interp_eval (spline->interp, \n spline->x, spline->y,\n x, a);\n}\n\n\nint\ngsl_spline_eval_deriv_e (const gsl_spline * spline,\n double x,\n gsl_interp_accel * a,\n double *dydx)\n{\n return gsl_interp_eval_deriv_e (spline->interp, \n spline->x, spline->y,\n x, a, dydx);\n}\n\ndouble\ngsl_spline_eval_deriv (const gsl_spline * spline,\n double x,\n gsl_interp_accel * a)\n{\n return gsl_interp_eval_deriv (spline->interp, \n spline->x, spline->y,\n x, a);\n}\n\n\nint\ngsl_spline_eval_deriv2_e (const gsl_spline * spline,\n double x,\n gsl_interp_accel * a,\n double * d2)\n{\n return gsl_interp_eval_deriv2_e (spline->interp, \n spline->x, spline->y,\n x, a, d2);\n}\n\ndouble\ngsl_spline_eval_deriv2 (const gsl_spline * spline,\n double x,\n gsl_interp_accel * a)\n{\n return gsl_interp_eval_deriv2 (spline->interp, \n spline->x, spline->y,\n x, a);\n}\n\n\nint\ngsl_spline_eval_integ_e (const gsl_spline * spline,\n double a, double b,\n gsl_interp_accel * acc,\n double * result)\n{\n return gsl_interp_eval_integ_e (spline->interp, \n spline->x, spline->y,\n a, b, acc, result);\n}\n\n\ndouble\ngsl_spline_eval_integ (const gsl_spline * spline,\n double a, double b,\n gsl_interp_accel * acc)\n{\n return gsl_interp_eval_integ (spline->interp, \n spline->x, spline->y,\n a, b, acc);\n}\n\n", "meta": {"hexsha": "3d8605d89fc6482f59f58b5661e5e55e7fefc9e2", "size": 5166, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/interpolation/spline.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/interpolation/spline.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/interpolation/spline.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.4923076923, "max_line_length": 98, "alphanum_fraction": 0.5644599303, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5117166047041654, "lm_q2_score": 0.46879062662624377, "lm_q1q2_score": 0.23988794777431954}} {"text": "// directdebye.c\n// Computes the Debye sum from raytracing data.\n// See man page for usage information.\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 \"hdfio.h\"\n#include \"miscprint.h\"\n#include \"parseargs.h\"\n#include \"rays.h\"\n\nint main(int argc, char **argv) {\n /* MPI initialization */\n int rank, nprocs;\n MPI_Init(&argc, &argv);\n MPI_Comm_size(MPI_COMM_WORLD, &nprocs);\n MPI_Comm_rank(MPI_COMM_WORLD, &rank);\n\n /* parse command line arguments */\n args_t *a = malloc(sizeof(args_t));\n parse_args(argc, argv, a);\n\n /* read the rays */\n unsigned int nrays; /* number of rays */\n ray_t *ray = NULL;\n ray = readrays(a->filename_in, &nrays);\n if (ray == NULL) {\n error_at_line(-1, errno, __FILE__, __LINE__, \"Problem reading ray file.\\n\");\n }\n\n /* pulse function */\n void *pfcn_intensity = NULL;\n pfcn_intensity = evaluator_create(a->pfcn_intensity_buffer);\n if (pfcn_intensity == NULL) {\n error_at_line(-1, EINVAL, __FILE__, __LINE__,\n \"Problem creating pulse evaluator function.\");\n }\n\n /* apodization function */\n void *pfcn_g = NULL;\n pfcn_g = evaluator_create(a->pfcn_g_buffer);\n if (pfcn_g == NULL) {\n error_at_line(-1, EINVAL, __FILE__, __LINE__,\n \"Problem creating apodization evaluator function.\");\n }\n\n /* root node prints some useful information */\n if (rank == 0) {\n print_args(a, nrays);\n }\n\n /* Before allocating what could potentially be a lot of memory, check to\n * see if it's even possible. */\n unsigned int i;\n a->efield_ss_out = 1;\n for (i = 0; i < 4; ++i) {\n a->efield_ss_out *= a->dim_efield_out[i];\n }\n\n long page_size = sysconf(_SC_PAGE_SIZE);\n // long pages_avail = sysconf(_SC_AVPHYS_PAGES);\n long pages_tot = sysconf(_SC_PHYS_PAGES);\n if (pages_tot * page_size < 8 * a->efield_ss_out * sizeof(complex double)) {\n error_at_line(-1, ENOMEM, __FILE__, __LINE__,\n \"Size of output arrays exceed avaliable memory.\\n\");\n }\n\n /* Allocate memory for the fields. The _rcv is memory for nodes. */\n complex double *efield_x = NULL;\n complex double *efield_x_rcv = NULL;\n complex double *efield_y = NULL;\n complex double *efield_y_rcv = NULL;\n complex double *efield_z = NULL;\n complex double *efield_z_rcv = NULL;\n\n double *efield_r = NULL;\n double *efield_r_rcv = NULL;\n\n /* The root node will be receiving all of the data, so it gets the whole\n * thing. Calloc here to pre-zero out everything. */\n if (rank == 0) {\n efield_x =\n (complex double *)calloc(a->efield_ss_out, sizeof(complex double));\n efield_y =\n (complex double *)calloc(a->efield_ss_out, sizeof(complex double));\n efield_z =\n (complex double *)calloc(a->efield_ss_out, sizeof(complex double));\n efield_r = (double *)calloc(4 * (a->efield_ss_out), sizeof(double));\n }\n\n /* The root node and all the other nodes also get this little chunk to\n * work on. The root node really has nothing better to do while waiting\n * for information so there's no real waste. */\n efield_x_rcv = (complex double *)calloc(a->efield_ss_out / nprocs,\n sizeof(complex double));\n efield_y_rcv = (complex double *)calloc(a->efield_ss_out / nprocs,\n sizeof(complex double));\n efield_z_rcv = (complex double *)calloc(a->efield_ss_out / nprocs,\n sizeof(complex double));\n efield_r_rcv =\n (double *)calloc(4 * (a->efield_ss_out / nprocs), sizeof(double));\n\n /* Catch some possible malloc errors*/\n if (errno) {\n fprintf(stderr, \"Node %d\\n\", rank);\n error_at_line(-1, errno, __FILE__, __LINE__, \"Error allocating memory.\");\n }\n\n unsigned int n;\n double w;\n /* precompute some ray information */\n for (n = 0; n < nrays; ++n, ++ray) {\n w = 2 * M_PI * GSL_CONST_MKSA_SPEED_OF_LIGHT * 1000 / ray->lambda;\n /* ray intensity for gaussian pulse */\n ray->intensity *= evaluator_evaluate_x(pfcn_intensity, w);\n if (isnan(ray->intensity)) {\n error_at_line(-1, errno, __FILE__, __LINE__,\n \"Error with intensity function: got nan.\");\n }\n\n /* analytic apodization factor for parabola */\n ray->g *= evaluator_evaluate_x(pfcn_g, acos(ray->p0[2] / a->fs_radius));\n if (isnan(ray->g)) {\n error_at_line(-1, errno, __FILE__, __LINE__,\n \"Error with apodization function: got nan.\");\n }\n\n /* all of the intensity information is stored in ray->g in order to\n * save a few multiplications in the inner loop */\n ray->g =\n (1.0 / (a->fs_radius * ray->lambda * 0.001)) * ray->g * ray->intensity;\n\n ray->e0[0] /= ray->lambda;\n ray->e0[1] /= ray->lambda;\n ray->e0[2] /= ray->lambda;\n }\n ray -= nrays;\n\n /* precompute the position vectors in the efield we'll be dealing with */\n if (rank == 0) {\n double dr[4];\n\n /* get the spacings of the electric field */\n for (i = 0; i < 4; ++i) {\n if (a->dim_efield_out[i] == 1) {\n dr[i] = (a->dim_efield_ub[i] - a->dim_efield_lb[i]) /\n ((double)a->dim_efield_out[i]);\n } else {\n dr[i] = (a->dim_efield_ub[i] - a->dim_efield_lb[i]) /\n ((double)a->dim_efield_out[i] - 1);\n }\n }\n\n /* set them */\n unsigned int r_i[4] = {};\n for (r_i[0] = 0; r_i[0] < a->dim_efield_out[0]; r_i[0]++) {\n for (r_i[1] = 0; r_i[1] < a->dim_efield_out[1]; r_i[1]++) {\n for (r_i[2] = 0; r_i[2] < a->dim_efield_out[2]; r_i[2]++) {\n for (r_i[3] = 0; r_i[3] < a->dim_efield_out[3]; r_i[3]++) {\n *efield_r++ = a->dim_efield_lb[0] + dr[0] * (double)r_i[0];\n *efield_r++ = a->dim_efield_lb[1] + dr[1] * (double)r_i[1];\n *efield_r++ = a->dim_efield_lb[2] + dr[2] * (double)r_i[2];\n *efield_r++ = a->dim_efield_lb[3] + dr[3] * (double)r_i[3];\n }\n }\n }\n }\n efield_r -= 4 * a->efield_ss_out;\n }\n\n /* send this spacing information out to everyone */\n MPI_Scatter(efield_r, 4 * (a->efield_ss_out / nprocs), MPI_DOUBLE,\n efield_r_rcv, 4 * (a->efield_ss_out / nprocs), MPI_DOUBLE, 0,\n MPI_COMM_WORLD);\n\n /* Main loop over ray data. This should be fast as possible. */\n /* pre-computing the three efield_r_rcv lines doesn't appear to have a *\n * significant effect on performance */\n complex double tmp;\n for (i = 0; i < a->efield_ss_out / nprocs; ++i) {\n for (n = 0; n < nrays; ++n, ++ray) {\n tmp = -1.0i * ray->g *\n cexp(2.0i * M_PI *\n ((*(efield_r_rcv + 0) - ray->p0[0]) * ray->e0[0] +\n (*(efield_r_rcv + 1) - ray->p0[1]) * ray->e0[1] +\n (*(efield_r_rcv + 2) - ray->p0[2]) * ray->e0[2] - ray->OPL -\n *(efield_r_rcv + 3) * GSL_CONST_MKSA_SPEED_OF_LIGHT * 1000.0 /\n ray->lambda +\n a->temporal_offset * GSL_CONST_MKSA_SPEED_OF_LIGHT * 1000.0 /\n ray->lambda));\n /* three polarization components */\n efield_x_rcv[i] += ray->pol[0] * tmp;\n efield_y_rcv[i] += ray->pol[1] * tmp;\n efield_z_rcv[i] += ray->pol[2] * tmp;\n }\n ray -= nrays;\n efield_r_rcv += 4;\n }\n efield_r_rcv -= 4 * i;\n\n /* gather all data from nodes */\n MPI_Gather(efield_x_rcv, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX,\n efield_x, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX, 0,\n MPI_COMM_WORLD);\n MPI_Gather(efield_y_rcv, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX,\n efield_y, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX, 0,\n MPI_COMM_WORLD);\n MPI_Gather(efield_z_rcv, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX,\n efield_z, a->efield_ss_out / nprocs, MPI_DOUBLE_COMPLEX, 0,\n MPI_COMM_WORLD);\n\n /* write electric field information to HDF file */\n if (rank == 0) {\n write_efield(a, efield_x, efield_y, efield_z);\n }\n\n /* clean up bit */\n free(efield_x);\n free(efield_y);\n free(efield_z);\n free(a);\n\n free(efield_x_rcv);\n free(efield_y_rcv);\n free(efield_z_rcv);\n free(efield_r_rcv);\n if (rank == 0) free(efield_r);\n free(ray);\n evaluator_destroy(pfcn_intensity);\n evaluator_destroy(pfcn_g);\n MPI_Finalize();\n return 0;\n}\n", "meta": {"hexsha": "2fe5d28d1bae9678945a0732e27f7498e6ad3cd9", "size": 8435, "ext": "c", "lang": "C", "max_stars_repo_path": "directdebye.c", "max_stars_repo_name": "AaronWebster/directdebye", "max_stars_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "directdebye.c", "max_issues_repo_name": "AaronWebster/directdebye", "max_issues_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "directdebye.c", "max_forks_repo_name": "AaronWebster/directdebye", "max_forks_repo_head_hexsha": "ddc61f250ed2c7ad185dcaf78def714231328ef4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4285714286, "max_line_length": 80, "alphanum_fraction": 0.6042679312, "num_tokens": 2563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.3702253925955867, "lm_q1q2_score": 0.23983134452929497}} {"text": "/*\n * vbHmmPcFret.c\n * Model-specific core functions for VB-HMM-PC-FRET.\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 \"vbHmmPcFret.h\"\n#include \n#include \n#include \n#include \"rand.h\"\n\n#ifdef _OPENMP\n#include \"omp.h\"\n#endif\n\n//#define DEBUG\n\n//// Uncomment one/both of the following defenitions to activate constraint on I and K.\n//#define INTENSITY_CAP\n#ifdef INTENSITY_CAP\n#define maxIntensityRatio 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_pcFret(){\n commonFunctions funcs;\n funcs.newModelParameters = newModelParameters_pcFret;\n funcs.freeModelParameters = freeModelParameters_pcFret;\n funcs.newModelStats = newModelStats_pcFret;\n funcs.freeModelStats = freeModelStats_pcFret;\n funcs.initializeVbHmm = initializeVbHmm_pcFret;\n funcs.pTilde_z1 = pTilde_z1_pcFret;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pcFret;\n funcs.pTilde_xn_zn = pTilde_xn_zn_pcFret;\n funcs.calcStatsVars = calcStatsVars_pcFret;\n funcs.maximization = maximization_pcFret;\n funcs.varLowerBound = varLowerBound_pcFret;\n funcs.reorderParameters = reorderParameters_pcFret;\n funcs.outputResults = outputResults_pcFret;\n setFunctions( funcs );\n}\n\n//void setGFunctions_pcFret(){\n// gCommonFunctions funcs;\n// funcs.newModelParameters = newModelParameters_pcFret;\n// funcs.freeModelParameters = freeModelParameters_pcFret;\n// funcs.newModelStats = newModelStats_pcFret;\n// funcs.freeModelStats = freeModelStats_pcFret;\n// funcs.newModelStatsG = newModelStatsG_pcFret;\n// funcs.freeModelStatsG = freeModelStatsG_pcFret;\n// funcs.initializeVbHmmG = initializeVbHmmG_pcFret;\n// funcs.pTilde_z1 = pTilde_z1_pcFret;\n// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pcFret;\n// funcs.pTilde_xn_zn = pTilde_xn_zn_pcFret;\n// funcs.calcStatsVarsG = calcStatsVarsG_pcFret;\n// funcs.maximizationG = maximizationG_pcFret;\n// funcs.varLowerBoundG = varLowerBoundG_pcFret;\n// funcs.reorderParametersG = reorderParametersG_pcFret;\n// funcs.outputResultsG = outputResultsG_pcFret;\n// setGFunctions( funcs );\n// isGlobalAnalysis = 1;\n//}\n\n\nvoid outputResults_pcFret( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n outputPcFretResults( xn, gv, iv, logFP );\n}\n\n//void outputResultsG_pcFret( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n// outputPcFretResultsG( xns, gv, ivs, logFP );\n//}\n\n\nvoid *newModelParameters_pcFret( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n int i;\n pcFretParameters *p = (void*)malloc( sizeof(pcFretParameters) );\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->aIArr = (double*)malloc( sNo * sizeof(double) );\n p->bIArr = (double*)malloc( sNo * sizeof(double) );\n p->uEArr = (double*)malloc( sNo * sizeof(double) );\n p->vEArr = (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 p->avgI = (double *)malloc( sNo * sizeof(double) );\n p->avgLnI = (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_pcFret( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n pcFretParameters *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->aIArr );\n free( gp->bIArr );\n free( gp->uEArr );\n free( gp->vEArr );\n\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->avgI );\n free( gp->avgLnI );\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_pcFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n pcFretStats *s = (pcFretStats*)malloc( sizeof(pcFretStats) );\n \n int i;\n s->Ni = (double *)malloc( sNo * sizeof(double) );\n s->Ci = (double *)malloc( sNo * sizeof(double) );\n s->Di = (double *)malloc( sNo * sizeof(double) );\n s->Ai = (double *)malloc( sNo * sizeof(double) );\n s->Mi = (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 \n return s;\n \n// } else {\n//\n// return NULL;\n//\n// }\n}\n\nvoid freeModelStats_pcFret( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n pcFretStats *gs = *s;\n int i;\n free( gs->Ni );\n free( gs->Ci );\n free( gs->Di );\n free( gs->Ai );\n free( gs->Mi );\n for( i = 0 ; i < sNo ; i++ )\n { free( gs->Nij[i] ); }\n free( gs->Nij );\n\n free( gs );\n *s = NULL;\n// }\n}\n\n//void *newModelStatsG_pcFret( xns, gv, ivs)\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// int sNo = gv->sNo;\n// pcFretGlobalStats *gs = (pcFretGlobalStats*)malloc( sizeof(pcFretGlobalStats) );\n//\n// return gs;\n//}\n\n//void freeModelStatsG_pcFret( gs, xns, gv, ivs )\n//void **gs;\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// int sNo = gv->sNo;\n// pcFretGlobalStats *ggs = *gs;\n//\n// free( *gs );\n// *gs = NULL;\n//}\n\n\nvoid initializeVbHmm_pcFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcFretData *d = xn->data;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n pcFretParameters *p = gv->params;\n \n int i, j;\n size_t totalC = 0;\n for( i = 0 ; i < dLen ; i++ ){\n totalC += d->dCounts[i] + d->aCounts[i];\n }\n double meanI = (double)totalC / (double)dLen;\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] = 100.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( 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 // hyper parameter 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_pcFret( xn, gv, iv );\n \n calcStatsVars_pcFret( xn, gv, iv );\n maximization_pcFret( xn, gv, iv );\n}\n\n//void initializeVbHmmG_pcFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid initialize_indVars_pcFret( 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_pcFret( 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 = (pcFretData*)malloc( sizeof(pcFretData) );\n pcFretData *d = (pcFretData*)xn->data;\n d->binSize = 0.0;\n d->dCounts = NULL;\n d->aCounts = NULL;\n return xn;\n}\n\nvoid freeXnDataSet_pcFret( xn )\nxnDataSet **xn;\n{\n pcFretData *d = (pcFretData*)(*xn)->data;\n free( d->dCounts );\n free( d->aCounts );\n free( (*xn)->data );\n free( (*xn)->name );\n free( *xn );\n *xn = NULL;\n}\n\n\n\ndouble pTilde_z1_pcFret( i, params )\nint i;\nvoid *params;\n{\n pcFretParameters *p = (pcFretParameters*)params;\n return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1_pcFret( i, j, params )\nint i, j;\nvoid *params;\n{\n pcFretParameters *p = (pcFretParameters*)params;\n return exp( p->avgLnA[i][j] );\n}\n\ndouble pTilde_xn_zn_pcFret( xn, n, i, params )\nxnDataSet *xn;\nsize_t n;\nint i;\nvoid *params;\n{\n pcFretParameters *p = (pcFretParameters*)params;\n pcFretData *d = (pcFretData*)xn->data;\n return exp( d->dCounts[n]*p->avgLnE[i][0] + d->aCounts[n]*p->avgLnE[i][1] + (d->dCounts[n]+d->aCounts[n])*p->avgLnI[i] - p->avgI[i] ) / gsl_sf_fact( d->dCounts[n] ) / gsl_sf_fact( d->aCounts[n] );\n}\n\n\nvoid calcStatsVars_pcFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcFretData *d = (pcFretData*)xn->data;\n pcFretStats *s = (pcFretStats*)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, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;\n double *Mi = s->Mi, **Nij = s->Nij;\n size_t n;\n int i, j;\n\n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] = 1e-10;\n Ci[i] = 1e-10;\n Di[i] = 1e-10;\n Ai[i] = 1e-10;\n Mi[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 Di[i] += gmMat[n][i] * (double)d->dCounts[n];\n Ai[i] += gmMat[n][i] * (double)d->aCounts[n];\n for( j = 0 ; j < sNo ; j++ ){\n Mi[i] += xiMat[n][i][j];\n Nij[i][j] += xiMat[n][i][j];\n }\n }\n Ci[i] = Di[i] + Ai[i];\n }\n\n//#ifdef DEBUG\n//#pragma omp critical\n//{\n// for( n = 0 ; n < 20 ; n++ ){\n// for( i = 0 ; i < sNo ; i++ ){\n// fprintf(logFP, \"%g,\", gmMat[n][i]);\n// }\n// fprintf(logFP, \"; \");\n// }\n// fprintf(logFP, \"\\n\");\n// for( i = 0 ; i < sNo ; i++ ){\n// fprintf(logFP, \"Ni(%d)=%g, \", i, Ni[i]);\n// fprintf(logFP, \"Ti(%d)=%g, \", i, Ti[i]);\n// fprintf(logFP, \"Mi(%d)=%g, \", i, Mi[i]);\n// for( j = 0 ; j < sNo ; j++ ){\n// if( j != i )\n// fprintf(logFP, \"Nij(%d,%d)=%g, \", i, j, Nij[i][j]);\n// }\n// fprintf(logFP, \"\\n\");\n// }\n//}\n//#endif\n}\n\n//void calcStatsVarsG_pcFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid maximization_pcFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcFretParameters *p = (pcFretParameters*)gv->params;\n pcFretStats *s = (pcFretStats*)iv->stats;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *uEArr = p->uEArr, *vEArr = p->vEArr;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n double *avgE = p->avgE, **avgLnE = p->avgLnE;\n double *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;\n double *Mi = s->Mi, **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] + Mi[i] );\n avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Mi[i] );\n }\n\n avgI[i] = (Ci[i] + aIArr[i]) / (Ni[i] + bIArr[i]);\n avgLnI[i] = gsl_sf_psi( Ci[i] + aIArr[i] ) - log( Ni[i] + bIArr[i] );\n#ifdef INTENSITY_CAP\n size_t n, totalC = 0;\n pcFretData *pc = xnWv->data;\n for( n = 0 ; n < xnWv->N ; n++ ){\n totalC += pc->dCounts[n] + pc->aCounts[n];\n }\n double meanI = (double)totalC / (double)xnWv->N;\n avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );\n avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );\n#endif\n \n avgE[i] = ( uEArr[i] + Ai[i] ) / ( uEArr[i] + vEArr[i] + Ci[i] );\n // ln(1-E) for donor\n avgLnE[i][0] = gsl_sf_psi( vEArr[i] + Di[i] ) - gsl_sf_psi( uEArr[i] + vEArr[i] + Ci[i] );\n // ln(E) for acceptor\n avgLnE[i][1] = gsl_sf_psi( uEArr[i] + Ai[i] ) - gsl_sf_psi( uEArr[i] + vEArr[i] + Ci[i] );\n }\n}\n\n//void maximizationG_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\ndouble varLowerBound_pcFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcFretParameters *p = (pcFretParameters*)gv->params;\n pcFretStats *s = (pcFretStats*)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, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *uEArr = p->uEArr, *vEArr = p->vEArr;\n double *avgLnPi = p->avgLnPi, **avgLnA = p->avgLnA;\n double *avgI = p->avgI, *avgLnI = p->avgLnI, **avgLnE = p->avgLnE;\n double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;\n double *Mi = s->Mi, **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 lnpI = 0.0;\n double lnpE = 0.0;\n double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);\n double lnqA = 0.0;\n double lnqI = 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 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 lnqI += (Ci[i] + aIArr[i]) * log(Ni[i] + bIArr[i]) - gsl_sf_lngamma(Ci[i] + aIArr[i]);\n lnqI += (Ci[i] + aIArr[i] - 1.0) * avgLnI[i] - (Ni[i] + bIArr[i]) * avgI[i];\n\n lnqE += gsl_sf_lngamma(uEArr[i] + vEArr[i] + Ci[i]);\n lnqE -= gsl_sf_lngamma(uEArr[i] + Ai[i]);\n lnqE -= gsl_sf_lngamma(vEArr[i] + Di[i]);\n lnqE += (uEArr[i] + Ai[i] - 1.0) * avgLnE[i][1];\n lnqE += (vEArr[i] + Di[i] - 1.0) * avgLnE[i][0];\n\n lnpA += gsl_sf_lngamma(sumUAArr[i]);\n lnqA += gsl_sf_lngamma(sumUAArr[i] + Mi[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]+Mi[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 + lnpI + lnpE;\n val -= lnqPi + lnqA + lnqI + lnqE;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n\n//#ifdef DEBUG\n//#pragma omp critical\n//{\n// FILE *logFP = stderr;\n// if( val > 100000 ){\n// fprintf(logFP, \" > %g; %g; %g; %g;\", lnpPi, lnpA, lnpI, lnpE);\n// fprintf(logFP, \" %g; %g; %g; %g; %g\\n\", lnqPi, lnqA, lnqI, lnqE, lnpX);\n// }\n//}\n//#endif\n\n return val;\n}\n\n//double varLowerBoundG_pcFret( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid reorderParameters_pcFret( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcFretParameters *p = (pcFretParameters*)gv->params;\n pcFretStats *s = (pcFretStats*)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;\n double **avgLnA = p->avgLnA;\n double *avgI = p->avgI, *avgLnI = p->avgLnI, *avgE = p->avgE, **avgLnE = p->avgLnE;\n double *Ni = s->Ni, *Ci = s->Ci, *Di = s->Di, *Ai = s->Ai;\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]] = 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]] = 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]] = Ci[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ci[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Di[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Di[i] = store[i]; }\n\n for( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ai[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ai[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_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid outputPcFretResults( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n pcFretParameters *p = (pcFretParameters*)gv->params;\n int sNo = gv->sNo;\n int i, j;\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, \" 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, \"I, E, 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\", p->avgI[i], p->avgE[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//void outputPcFretResultsG( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n//}\n\n//\n", "meta": {"hexsha": "cb35305656d9e37bfb3830105b33767a0c0d7006", "size": 23198, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmmPcFret.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/vbHmmPcFret.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/vbHmmPcFret.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.463803681, "max_line_length": 200, "alphanum_fraction": 0.5020260367, "num_tokens": 8720, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.4263215925474903, "lm_q1q2_score": 0.23966797489595806}} {"text": "/**\n *\n * @file core_dgbtype2cb.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 Azzam Haidar\n * @date 2012-12-15\n * @generated d Tue Jan 7 11:44:50 2014\n *\n **/\n#include \n#include \"common.h\"\n\n//#define AU(m,n) &(A[(m) + LDA*(n)])\n//#define AL(m,n) &(A[(m) + LDA*(n)])\n#define AL(m_, n_) (A + NB + LDA * (n_) + ((m_)-(n_)))\n#define AU(m_, n_) (A + NB + LDA * (n_) + ((m_)-(n_)+NB))\n#define VQ(m) (VQ + (m))\n#define VP(m) (VP + (m))\n#define TAUQ(m) (TAUQ + (m))\n#define TAUP(m) (TAUP + (m))\n\n/***************************************************************************//**\n *\n * @ingroup CORE_double\n *\n * CORE_dgbtype2cb is a kernel that will operate on a region (triangle) of data\n * bounded by st and ed. This kernel apply the right update remaining from the\n * type1 and this later will create a bulge so it eliminate the first column of\n * the created bulge and do the corresponding Left update.\n *\n * All detail are available on technical report or SC11 paper.\n * Azzam Haidar, Hatem Ltaief, and Jack Dongarra. 2011.\n * Parallel reduction to condensed forms for symmetric eigenvalue problems\n * using aggregated fine-grained and memory-aware kernels. In Proceedings\n * of 2011 International Conference for High Performance Computing,\n * Networking, Storage and Analysis (SC '11). ACM, New York, NY, USA, ,\n * Article 8 , 11 pages.\n * http://doi.acm.org/10.1145/2063384.2063394\n *\n *******************************************************************************\n *\n * @param[in] N\n * The order of the matrix A.\n *\n * @param[in] NB\n * The size of the band.\n *\n * @param[in, out] A\n * A pointer to the matrix A of size (3*NB+1)-by-N.\n *\n * @param[in] LDA\n * The leading dimension of the matrix A. LDA >= max(1,3*NB+1)\n *\n * @param[in, out] V\n * double array, dimension N if eigenvalue only\n * requested or (LDV*blkcnt*Vblksiz) if Eigenvectors requested\n * The Householder reflectors of the previous type 1 are used here\n * to continue update then new one are generated to eliminate the\n * bulge and stored in this array.\n *\n * @param[in, out] TAU\n * double array, dimension (N).\n * The scalar factors of the Householder reflectors of the previous\n * type 1 are used here to continue update then new one are generated\n * to eliminate the bulge and stored in this array.\n *\n * @param[in] st\n * A pointer to the start index where this kernel will operate.\n *\n * @param[in] ed\n * A pointer to the end index where this kernel will operate.\n *\n * @param[in] sweep\n * The sweep number that is eliminated. it serve to calculate the\n * pointer to the position where to store the Vs and Ts.\n *\n * @param[in] Vblksiz\n * constant which correspond to the blocking used when applying the Vs.\n * it serve to calculate the pointer to the position where to store the\n * Vs and Ts.\n *\n * @param[in] WANTZ\n * constant which indicate if Eigenvalue are requested or both\n * Eigenvalue/Eigenvectors.\n *\n * @param[in] WORK\n * Workspace of size nb.\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 * TYPE 2-BAND-bidiag Lower/Upper columnwise-Householder\n ***************************************************************************/\nvoid\nCORE_dgbtype2cb(PLASMA_enum uplo, int N, int NB,\n double *A, int LDA,\n double *VQ, double *TAUQ,\n double *VP, double *TAUP,\n int st, int ed, int sweep, int Vblksiz, int WANTZ,\n double *WORK)\n{\n double ctmp;\n int i, J1, J2, len, lem, LDX;\n int blkid, vpos, taupos, tpos;\n\n LDX = LDA-1;\n J1 = ed+1;\n J2 = min(ed+NB,N-1);\n lem = ed-st+1;\n len = J2-J1+1;\n\n if( uplo == PlasmaUpper ) {\n /* ========================\n * UPPER CASE\n * ========================*/\n if( len > 0 ) {\n if( WANTZ == 0 ) {\n vpos = ((sweep+1)%2)*N + st;\n taupos = ((sweep+1)%2)*N + st;\n } else {\n findVTpos(N, NB, Vblksiz, sweep, st,\n &vpos, &taupos, &tpos, &blkid);\n }\n /* Apply remaining Left commming from type1/3_upper */\n ctmp = (*TAUQ(taupos));\n LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaLeft),\n lem, len, VQ(vpos), ctmp, AU(st, J1), LDX, WORK);\n }\n\n if( len > 1 ) {\n if( WANTZ == 0 ) {\n vpos = ((sweep+1)%2)*N + J1;\n taupos = ((sweep+1)%2)*N + J1;\n } else {\n findVTpos(N,NB,Vblksiz,sweep,J1, &vpos, &taupos, &tpos, &blkid);\n }\n\n /* Remove the top row of the created bulge */\n *VP(vpos) = 1.;\n for(i=1; i 0 ) {\n if( WANTZ == 0 ) {\n vpos = ((sweep+1)%2)*N + st;\n taupos = ((sweep+1)%2)*N + st;\n } else {\n findVTpos(N, NB, Vblksiz, sweep, st,\n &vpos, &taupos, &tpos, &blkid);\n }\n /* Apply remaining Right commming from type1/3_lower */\n ctmp = (*TAUP(taupos));\n LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaRight),\n len, lem, VP(vpos), ctmp, AL(J1, st), LDX, WORK);\n }\n if( len > 1 ) {\n if( WANTZ == 0 ) {\n vpos = ((sweep+1)%2)*N + J1;\n taupos = ((sweep+1)%2)*N + J1;\n } else {\n findVTpos(N,NB,Vblksiz,sweep,J1, &vpos, &taupos, &tpos, &blkid);\n }\n\n /* Remove the first column of the created bulge */\n *VQ(vpos) = 1.;\n memcpy(VQ(vpos+1), AL(J1+1, st), (len-1)*sizeof(double));\n memset(AL(J1+1, st), 0, (len-1)*sizeof(double));\n /* Eliminate the col at st */\n LAPACKE_dlarfg_work(len, AL(J1, st), VQ(vpos+1), 1, TAUQ(taupos) );\n /*\n * Apply left on A(J1:J2,st+1:ed)\n * We decrease len because we start at col st+1 instead of st.\n * col st is the col that has been revomved;\n */\n lem = lem-1;\n ctmp = (*TAUQ(taupos));\n LAPACKE_dlarfx_work(LAPACK_COL_MAJOR, lapack_const(PlasmaLeft),\n len, lem, VQ(vpos), ctmp, AL(J1, st+1), LDX, WORK);\n }\n }\n /* end of uplo case */\n return;\n}\n/***************************************************************************/\n#undef AU\n#undef AL\n#undef VQ\n#undef VP\n#undef TAUQ\n#undef TAUP\n", "meta": {"hexsha": "ead017677a2cd61a6f53814f18ccf69044b1be01", "size": 8025, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_dgbtype2cb.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_dgbtype2cb.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_dgbtype2cb.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4772727273, "max_line_length": 83, "alphanum_fraction": 0.4819937695, "num_tokens": 2201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.2395921560269409}} {"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\n\nvoid VVerlet_Step(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss\n\t\t\t\t\tvoid (*derivmethod) (double *y, double *ans, double t,int N)) {\n\tdouble temp_vec[N], abl[N];\n\tint i,j;\n\tfor (j = 0; j < DIM; j++ )\t\t// heavy particle outside parallel region\n\t{\t\n\n\t\tv[j] = v[j] + 0.5 * a[j] * MAXSTEPSIZE;\n\t\tx[j] = x[j] + v[j] * MAXSTEPSIZE;\n\t\ttemp_vec[j] = x[j];\t\t\t\t\t//temp_vec zur abl- berechnung\n\t\ttemp_vec[DIM + j] = v[j] * mass;\n\t}\n\t#pragma omp parallel for \t\t\t//parallelisiere über Osszillatoren\n\tfor (i= 0 ; i < OSSZI; i++)\n\t{\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\tv[DIM + j + i*DIM] = v[DIM + j + i*DIM] + 0.5 * a[DIM + j + i*DIM] * MAXSTEPSIZE;\n\t\t\tx[DIM + j + i*DIM] = x[DIM + j + i*DIM] + v[DIM + j + i*DIM] * MAXSTEPSIZE;\n\t\t\ttemp_vec[2*DIM + i * 2*DIM + j] = x[DIM + j + i*DIM];\t//temp_vec zur abl- berechnung\n\t\t\ttemp_vec[3*DIM + i * 2*DIM + j] = v[DIM + j + i*DIM] ;\n\t\t}\n\t}\n\n\tderivmethod(temp_vec, abl, *t, N); //bilde Ableitung zu t\n\t\t\t\t\t\t\t\t\t\t// gehe wieder in x-v Form für a\n\tfor (j = 0; j < DIM; j++ )\n\t{\n\t\ta[j] = abl[DIM + j] / mass;\n\t\tv[j] = v[j] + 0.5 * a[j] * MAXSTEPSIZE;\n\t}\n\n\t#pragma omp parallel for \n\tfor (i= 0 ; i < OSSZI; i++)\n\t{\n\t\tfor (j = 0; j < DIM; j++ )\n\t\t{\n\t\t\ta[DIM +j + i*DIM] = abl[3*DIM + j + i * 2*DIM]/massq[i];\n\t\t\tv[DIM +j + i*DIM] = v[DIM +j + i*DIM]\\\n\t\t\t\t\t\t\t\t\t+ 0.5 * a[DIM +j + i*DIM] * MAXSTEPSIZE;\n\t\t}\n\t}\n\t//#pragma omp parallel for \n\t//for (i= 0 ; i < N/2; i++)\n\t//{\n\t//\tv[i] = v[i] + 0.5 * a[i] * MAXSTEPSIZE;\n\t//}\t\n\tUpdate_Lattice_Position(lattice_position, x, LATTICE_SPACING);\t\n\t*t = *t + MAXSTEPSIZE;\t\n}\n\nvoid VVerlet_Step_deriv(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t, //mach einzelnen update Schritt nach Velocity-Verlet ohne Hinderniss\n\t\t\t\t\tvoid (*derivmethod) (double *y, double *ans, double t,int N)) {\n\n\tint i,j;\n\tSETNUMTHREADS\n\tdouble sum[DIM];\n\t#pragma omp parallel \t\t\t// Values for Bath particles parralized///////////////////\n\t{\n\t\tint ID = omp_get_thread_num();\n\t\tint MAX_THREADS = omp_get_num_threads();\n\t\t\n\t\tif (MAX_THREADS < DIM) // Catch case : not enough threads\n\t\t{\tfor (j= 0; j0\n\t\t)\n\t{\t\n\t\t#pragma omp parallel for\n\t\tfor (int target_i = 0; target_i < number_targets; target_i++)\n\t\t{\n\t\t\tdouble lower_t; \t\t\t\t\t\t// lower search bound\n\t\t\tdouble upper_t;\n\t\t\tint signold; int signnew;\n\t\t\tlower_t = 0.0; \t\t\t\t\t\t\t// lower search bound\n\t\t\tupper_t = MAXSTEPSIZE;\t\t\t\t\t// upper search bound\n\t\t\tdouble steps = 500.0;\n\t\t\tint root_flag = 1;\t\t\t\t\t\t// set to one if root found and also one at fitst loop\n\t\t\tint root_loop = 0;\t\t\t\t\t\t// number of current loop\n\t\t\tint root_loop_max = 3;\n\t\t\twhile ((root_flag == 1)\t&&\t(root_loop < root_loop_max))\n\t\t\t{\n\t\t\t\troot_flag = 0;\n\t\t\t\troot_loop += 1;\n\t\t\t// get sign lower bound before loop\n\t\t\t\tdouble eval_value = 0.0;\n\t\t\t\tfor(i = 0; i< DIM; i++)\n\t\t\t\t{\n\t\t\t\t\tdouble v_temp = v[i] + 0.5 * a[i] * lower_t;\n\t\t\t\t\tdouble x_temp = x[i] + v_temp * lower_t;\n\t\t\t\t\teval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0);\t\t// f = sum (x-R)^2\n\t\t\t\t}\n\t\t\t\teval_value = eval_value - pow(TARGET_LENGTH , 2.0);\n\t\t\t\tif (eval_value > 0)\n\t\t\t\t{\n\t\t\t\t\tsignold = 1;\n\t\t\t\t}else\n\t\t\t\t{\n\t\t\t\t\tsignold = -1;\n\t\t\t\t}\n\t\t\t\tdouble dt = (upper_t - lower_t)/ steps;\n\t\t\t// check all signs in intervall till first change\n\t\t\t\tfor (double t_check = lower_t; t_check < upper_t; t_check += dt)\n\t\t\t\t{\n\t\t\t\t\teval_value = 0.0;\n\t\t\t\t\tfor(i = 0; i< DIM; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble v_temp = v[i] + 0.5 * a[i] * t_check;\n\t\t\t\t\t\tdouble x_temp = x[i] + v_temp * t_check;\n\t\t\t\t\t\teval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0);\t\t// f = sum (x-R)^2\n\t\t\t\t\t}\n\t\t\t\t\teval_value = eval_value - pow(TARGET_LENGTH , 2.0);\n\t\t\t\t\t//printf(\"%2.2e\\n\", eval_value);\n\t\t\t\t\tif (eval_value > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsignnew = 1;\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tsignnew = -1;\n\t\t\t\t\t}\n\t\t\t\t\tif (signnew != signold)\t\t\t\t// at first sign change adjust intervall\n\t\t\t\t\t{\n\t\t\t\t\t\tlower_t = t_check - dt;\n\t\t\t\t\t\tsteps = 10000.0;\t\t\t\t// refine only 4 orders of magnitude per loop\n\t\t\t\t\t\tupper_t = t_check;\n\t\t\t\t\t\troot_flag = 1;\t\t\t\t\t// redo loop to refine root\n\t\t\t\t\t\tlower_t_global[target_i] = lower_t;\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tsignold = signnew;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}// collision detection end--------------------------------------------------------------------------------------------------\n\tdouble minimum_t = MAXSTEPSIZE;\n\tfor (i=0; i < number_targets; i++)\t\t\t\t//find smallest reflection time\n\t{\n\t\tif(lower_t_global[i] < minimum_t)\n\t\t{\n\t\t\treflec_flag = 1;\n\t\t\ttarget_nr_hit = i;\n\t\t\tminimum_t = lower_t_global[i];\n\t\t}\n\t}\n\tif (reflec_flag ==1 )\n\t{\n\t\tif (TARGET_FLAG)\t\t\t\t// check for first contact\n\t\t{\n\t\t\ttime_first_contact += *t + minimum_t;\n\t\t\tTARGET_FLAG = 0;// no need to test again after 1st contact\n\t\t}\n\t\tcontact_stepsize = minimum_t;\t\t\t\t// pick lower boud so particle is JUST outside the boundary - Else zero search converges badly\n\t}else\n\t{\n\t\tcontact_stepsize = MAXSTEPSIZE;\n\t}\n\n\t#pragma omp parallel \t\t\t\t\t\t\t// Values for Bath particles parralized//\n\t{\n\t\tint ID = omp_get_thread_num();\n\t\tint MAX_THREADS = omp_get_num_threads();\n\t\t\n\t\tif (MAX_THREADS < DIM) \t\t\t\t\t\t// Catch case : not enough threads\n\t\t{\tfor (j= 0; j0\n\t\t)\n\t{\t\n\t\t#pragma omp parallel for\n\t\tfor (int target_i = 0; target_i < number_targets; target_i++)\n\t\t{\n\t\t\tdouble lower_t; \t\t\t\t\t\t// lower search bound\n\t\t\tdouble upper_t;\n\t\t\tint signold; int signnew;\n\t\t\tlower_t = 0.0; \t\t\t\t\t\t\t// lower search bound\n\t\t\tupper_t = MAXSTEPSIZE;\t\t\t\t\t// upper search bound\n\t\t\tdouble steps = 500.0;\n\t\t\tint root_flag = 1;\t\t\t\t\t\t// set to one if root found and also one at fitst loop\n\t\t\tint root_loop = 0;\t\t\t\t\t\t// number of current loop\n\t\t\tint root_loop_max = 3;\n\t\t\twhile ((root_flag == 1)\t&&\t(root_loop < root_loop_max))\n\t\t\t{\n\t\t\t\troot_flag = 0;\n\t\t\t\troot_loop += 1;\n\t\t\t// get sign lower bound before loop\n\t\t\t\tdouble eval_value = 0.0;\n\t\t\t\tfor(i = 0; i< DIM; i++)\n\t\t\t\t{\n\t\t\t\t\tdouble v_temp = v[i] + 0.5 * a[i] * lower_t;\n\t\t\t\t\tdouble x_temp = x[i] + v_temp * lower_t;\n\t\t\t\t\teval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0);\t\t// f = sum (x-R)^2\n\t\t\t\t}\n\t\t\t\teval_value = eval_value - pow(TARGET_LENGTH , 2.0);\n\t\t\t\tif (eval_value > 0)\n\t\t\t\t{\n\t\t\t\t\tsignold = 1;\n\t\t\t\t}else\n\t\t\t\t{\n\t\t\t\t\tsignold = -1;\n\t\t\t\t}\n\t\t\t\tdouble dt = (upper_t - lower_t)/ steps;\n\t\t\t// check all signs in intervall till first change\n\t\t\t\tfor (double t_check = lower_t; t_check < upper_t; t_check += dt)\n\t\t\t\t{\n\t\t\t\t\teval_value = 0.0;\n\t\t\t\t\tfor(i = 0; i< DIM; i++)\n\t\t\t\t\t{\n\t\t\t\t\t\tdouble v_temp = v[i] + 0.5 * a[i] * t_check;\n\t\t\t\t\t\tdouble x_temp = x[i] + v_temp * t_check;\n\t\t\t\t\t\teval_value += pow( (x_temp - target_vec[i + DIM * target_i]) , 2.0);\t\t// f = sum (x-R)^2\n\t\t\t\t\t}\n\t\t\t\t\teval_value = eval_value - pow(TARGET_LENGTH , 2.0);\n\t\t\t\t\t//printf(\"%2.2e\\n\", eval_value);\n\t\t\t\t\tif (eval_value > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsignnew = 1;\n\t\t\t\t\t}else\n\t\t\t\t\t{\n\t\t\t\t\t\tsignnew = -1;\n\t\t\t\t\t}\n\t\t\t\t\tif (signnew != signold)\t\t\t\t// at first sign change adjust intervall\n\t\t\t\t\t{\n\t\t\t\t\t\tlower_t = t_check - dt;\n\t\t\t\t\t\tsteps = 10000.0;\t\t\t\t// refine only 4 orders of magnitude per loop\n\t\t\t\t\t\tupper_t = t_check;\n\t\t\t\t\t\troot_flag = 1;\t\t\t\t\t// redo loop to refine root\n\t\t\t\t\t\tlower_t_global[target_i] = lower_t;\t\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tsignold = signnew;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}// collision detection end--------------------------------------------------------------------------------------------------\n\tdouble minimum_t = MAXSTEPSIZE;\n\tfor (i=0; i < number_targets; i++)\t\t\t\t//find smallest reflection time\n\t{\n\t\tif(lower_t_global[i] < minimum_t)\n\t\t{\n\t\t\treflec_flag = 1;\n\t\t\ttarget_nr_hit = i;\n\t\t\tminimum_t = lower_t_global[i];\n\t\t}\n\t}\n\tif (reflec_flag ==1 )\n\t{\n\t\tif (TARGET_FLAG)\t\t\t\t// check for first contact\n\t\t{\n\t\t\ttime_first_contact += *t + minimum_t;\n\t\t\tTARGET_FLAG = 0;// no need to test again after 1st contact\n\t\t}\n\t\tcontact_stepsize = minimum_t;\t\t\t\t// pick lower boud so particle is JUST outside the boundary - Else zero search converges badly\n\t}else\n\t{\n\t\tcontact_stepsize = MAXSTEPSIZE;\n\t}\n\n\t#pragma omp parallel \t\t\t\t\t\t\t// Values for Bath particles parralized//\n\t{\n\t\tint ID = omp_get_thread_num();\n\t\tint MAX_THREADS = omp_get_num_threads();\n\t\t\n\t\tif (MAX_THREADS < DIM) \t\t\t\t\t\t// Catch case : not enough threads\n\t\t{\tfor (j= 0; j0\n\t\t)\n\t{\n\t\tdouble N_CHECK = 1000.0;\t\t\n\t\t#pragma omp parallel for\n\t\tfor (int target_i = 0; target_i < number_targets; target_i++)\t// check for all targets in increments of LASTSTEPSIZE/N_CHECK for contact\n\t\t{\n\t\t\tdouble dh = LASTSTEPSIZE / N_CHECK;\n\t\t\tfor (double h_check = 0.0; h_check < LASTSTEPSIZE; h_check += dh)\n\t\t\t{\n\t\t\t\tdouble r_check = 0.0;\n\t\t\t\tfor (int j = 0; j < DIM; j++)\n\t\t\t\t{\n\t\t\t\t\tdouble v_temp = v[j] + 0.5 * a[j] * h_check;\n\t\t\t\t\tdouble x_temp = x[j] + v_temp * h_check;\n\t\t\t\t\tif(VIRTUAL_FLAG)\n\t\t\t\t\t{\n\t\t\t\t\t\tv_temp = VIRTUAL_V[j] + 0.5 * a[j] * h_check;\n\t\t\t\t\t\tx_temp = VIRTUAL_X[j] + v_temp * h_check;\n\t\t\t\t\t} \n\t\t\t\t\tr_check += pow( (x_temp - target_vec[j + target_i * DIM] ) ,2.0 );\n\t\t\t\t}\n\t\t\t\tr_check = sqrt(r_check);\n\t\t\t\tif (r_check < TARGET_LENGTH)\n\t\t\t\t{\n\t\t\t\t\treflec_flag = 1;\n\t\t\t\t\ttarget_nr_hit = target_i;\n\t\t\t\t\tcontact_stepsize = h_check - dh;\n\t\t\t\t\tif (TARGET_FLAG)\t\t\t\t// check for first contact\n\t\t\t\t\t{\n\t\t\t\t\t\ttime_first_contact += *t + contact_stepsize;\n\t\t\t\t\t\tTARGET_FLAG = 0;// no need to test again after 1st contact\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t\tbreak;\n\t\t\t\t} \n\t\t\t}\t\n\t\t}\n\t}\n\t//-------------------------------------------------------------------------------------------------------------------\n\t#pragma omp parallel \t\t\t\t\t\t\t// Values for Bath particles parralized//\n\t{\n\t\tint ID = omp_get_thread_num();\n\t\tint MAX_THREADS = omp_get_num_threads();\n\t\t\n\t\tif (MAX_THREADS < DIM) \t\t\t\t\t\t// Catch case : not enough threads\n\t\t{\tfor (j= 0; j= 0)\t\t\t\t\t\t\t\t\t\t\t\t\t// minimize rounoff err by case split\n\t\t\t{\n\t\t\t\troot1 = (-b - sqrt(b*b - 4.0 * aa * c)) / (2.0 * aa);\n\t\t\t\troot2 = 2.0 * c /(-b - sqrt(b*b - 4.0 * aa * c) );\n\t\t\t}else\n\t\t\t{\n\t\t\t\troot1 = 2.0 * c /(-b + sqrt(b*b - 4.0 * aa * c) );\n\t\t\t\troot2 = (-b + sqrt(b*b - 4.0 * aa * c)) / (2.0 * aa);\n\t\t\t}\n\t\t\tif( (root1 > 0) && (root1 < contact_stepsize) )\n\t\t\t{\n\t\t\t\tcontact_stepsize = 0.995 * root1;\n\t\t\t\treflec_flag = 1;\n\t\t\t}\n\t\t\tif( (root2 > 0) && (root2 < contact_stepsize) )\n\t\t\t{\n\t\t\t\tcontact_stepsize = 0.995 * root2;\n\t\t\t\treflec_flag = 1;\n\t\t\t}\n\t\t}\n\t}\n\t// contact time end ||||||||||||||||||||||||||||||||||||<\n\n\t#pragma omp parallel for\n\tfor (i= 0 ; i < N/2; i++)\t// Erstes Halbupdate ////\n\t{\n\t\tdouble v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize;\t\t//vnext = v + a/2 *dt\n\t\tx[i] = x[i] + v_temp * contact_stepsize;\t\t\t\t\t\t\t//xnext = x + vnext *dt\n\n\t}\n\tif(VIRTUAL_FLAG)\n\t{\n\t\tdouble v_temp = VIRTUAL_V[0] = VIRTUAL_V[0] + 0.5 * a[0] * contact_stepsize;\t// virtual particle\n\t\tVIRTUAL_X[0] = VIRTUAL_X[0] + v_temp * contact_stepsize;\t\n\t}\n\tfor (i = 0 ; i < OSSZI; i++)\n\t{ \n\t\tdouble coup = coupling[i];\n\t\tdouble om = ommega[i];\n\t\tdouble a_temp = a[1 + i] = -coup * (x[1 + i] - x[0])/massq[i]; \t\n\t\tv[1 + i] = v[1 + i]\\\n\t\t\t\t\t+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////\n\t}\n\t#pragma omp parallel for reduction(+:sum) \t\t\t// berechne die Summe gamma_i *q_i - gamma_i^2/ommega_i^2 * x\n\tfor (i = 0 ; i < OSSZI; i++)\n\t{ \n\t\tdouble coup = coupling[i];\t\n\t\tsum += coup * (x[1 + i] - x[0]); \n\t}\n\ta[0] = sum /mass;\n\tv[0] = v[0] + 0.5 * a[0] * contact_stepsize;\n\tif(VIRTUAL_FLAG)\n\t{\n\t\tVIRTUAL_V[0] = VIRTUAL_V[0] + 0.5 * a[0] * contact_stepsize;\t\n\t}\n\t*t = *t + contact_stepsize;\n\tif(reflec_flag)\n\t{\n\t\tLASTSTEPSIZE = LASTSTEPSIZE - contact_stepsize;\n\t\tif(REFLECTALL_FLAG)\t\t\t\t\t\t\t\t// reflect whole bath if flag is set\n\t\t{\n\t\t\tfor (i = 0 ; i < OSSZI; i++)\n\t\t\t{ \n\t\t\t\tdouble v_rel = v[1 + i] - v[0];\n\t\t\t\tv[1 + i] = - v[0] + v_rel;\t\t\t\t\t\t//keep relative velocity after reflection of heavy particle the same\n\t\t\t}\n\t\t}\n\t\tif(VIRTUAL_FLAG)\n\t\t{\n\t\t\tVIRTUAL_V[0] = -VIRTUAL_V[0];\t\t\t\t\t\t\t\t\t\t// reflect heavy\n\t\t}else\n\t\t{\n\t\t\tv[0] = -v[0];\t\t\t\t\t\t\t\t\t\t// reflect heavy\n\t\t}\n\t}\n\telse\n\t{\n\t\tLASTSTEPSIZE = MAXSTEPSIZE;\n\t}\t\n}\n\nvoid VVerlet_Step_deriv_Box_Ramp(const int N, double x[N/2] , double v[N/2], double a[N/2], double *t, \n\t\t\t\t\tvoid (*derivmethod) (double *y, double *ans, double t,int N)) {\n\t//macht einzelnen update schritt in Box der Länge Lattice_Spacting\n\t// use fully mobile Kupferman bath that is coupling U = sum gamma_i (q_i-X)^2\n\n\tint i,j;\n\tSETNUMTHREADS\n\tdouble sum = 0.0;\n\tdouble contact_stepsize = LASTSTEPSIZE;\n\tint reflec_flag = 0;\n\t\n\n\n\t#pragma omp parallel for\n\tfor (i= 0 ; i < N/2; i++)\t// Erstes Halbupdate ////\n\t{\n\t\tdouble v_temp = v[i] = v[i] + 0.5 * a[i] * contact_stepsize;\t\t//vnext = v + a/2 *dt\n\t\tx[i] = x[i] + v_temp * contact_stepsize;\t\t\t\t\t\t\t//xnext = x + vnext *dt\n\t}\n\tfor (i = 0 ; i < OSSZI; i++)\n\t{ \n\t\tdouble coup = coupling[i];\n\t\tdouble om = ommega[i];\n\t\tdouble a_temp = a[1 + i] = -coup * (x[1 + i] - x[0])/massq[i]; \t\n\t\tv[1 + i] = v[1 + i]\\\n\t\t\t\t\t+ 0.5 * a_temp * contact_stepsize; // Zweites Halbupdate ////\n\t}\n\t#pragma omp parallel for reduction(+:sum) \t\t\t// berechne die Summe gamma_i *q_i - gamma_i^2/ommega_i^2 * x\n\tfor (i = 0 ; i < OSSZI; i++)\n\t{ \n\t\tdouble coup = coupling[i];\t\n\t\tsum += coup * (x[1 + i] - x[0]); \n\t}\n\ta[0] = sum /mass;\n\t\n\tif(x[0] < -(LATTICE_SPACING/2.0 - L_BALL) )\t\t\t//left wall;\n\t{\n\t\tdouble height_ramp = 2*KBOLTZ*TEMP;\n\t\ta[0] += height_ramp/L_BALL/mass;\n\t}\n\tif(x[0] > (LATTICE_SPACING/2.0 - L_BALL) )\t\t\t//right wall;\n\t{\n\t\tdouble height_ramp = 2*KBOLTZ*TEMP;\n\t\ta[0] += -height_ramp/L_BALL/mass;\n\t}\n\tv[0] = v[0] + 0.5 * a[0] * contact_stepsize;\n\t\n\t*t = *t + contact_stepsize;\t\n}\n\n", "meta": {"hexsha": "9b3242e960051ec98789583267a3eea0985d6348", "size": 35168, "ext": "c", "lang": "C", "max_stars_repo_path": "steppmethods.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": "steppmethods.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": "steppmethods.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": 30.7681539808, "max_line_length": 173, "alphanum_fraction": 0.5694096906, "num_tokens": 12477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6039318337259583, "lm_q2_score": 0.39606816627404173, "lm_q1q2_score": 0.23919817393835976}} {"text": "/******************************************************************************\n * *\n * DECS.H *\n * *\n * GLOBAL MACROS, FUNCTION DEFINITIONS, INCLUDES, AND DECLARATIONS *\n * *\n ******************************************************************************/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"constants.h\"\n#include \"params.h\"\n\n/*******************************************************************************\n PRE-PROCESSOR MAGIC :\n*******************************************************************************/\n#define XSTR(x) STR(x)\n#define STR(x) #x\n\n/*******************************************************************************\n CONSTANTS :\n*******************************************************************************/\n\n#ifndef M_PI\n#define M_PI 3.14159265358979323846264338327\n#endif\n#ifndef M_PI_2\n#define M_PI_2 1.57079632679489661923132169164\n#endif\n#ifndef M_SQRT2\n#define M_SQRT2 1.4142135623730950488016887242\n#endif\n\n/*******************************************************************************\n COMPILE-TIME PARAMETERS :\n*******************************************************************************/\n\n// Number of active zones on each MPI process\n#define N1 (N1TOT / N1CPU)\n#define N2 (N2TOT / N2CPU)\n#define N3 (N3TOT / N3CPU)\n\n// Max size for 1D slice is NMAX\n#define N12 (N1 > N2 ? N1 : N2)\n#define NMAX (N12 > N3 ? N12 : N3)\n\n#define NDIM (4) // Number of total dimensions\n#define NPG (5) // Number of positions on grid for grid functions\n#define NG (3) // Number of ghost zones\n#define N123G \\\n ((N1 + 2 * NG) * (N2 + 2 * NG) * \\\n (N3 + 2 * NG)) // total number of cells on a cpu\n\n// Fixup parameters\n// rho_flor = RHOMIN / pow(r, -FLOOR_POWER)\n#define FLR_POWER1 (2.)\n#define FLR_POWER2 (2.)\n#define FLR_R0 (50.) // TODO change this?\n#define RHOMINLIMIT (1.e-17)\n#define UUMINLIMIT (1.e-3 * RHOMINLIMIT)\n#define RHOMIN (1.e-5)\n#define UUMIN (1.e-3 * RHOMIN)\n#define BSQORHOMAX (50.)\n#define BSQOUMAX (2500.)\n#define RHOEPS (0.9)\n#define UORHOMAX (50.)\n#define COLD_FLOORS (1)\n#define ATM_THRESH (0.1)\n\n// Numerical convenience to represent a small (<< 1) non-zero quantity\n#define SMALL (1.e-20)\n#define ABSURDLY_LARGE (1.e100)\n\n// Maximum value of gamma, the Lorentz factor\n#define GAMMAMAX (50.)\n\n// Maximum fractional increase in timestep per timestep\n#define SAFE (1.3)\n\n// Superphoton diagnostics\n#define MAXNSCATT (3)\n\n// Chosen to give some wiggle room\n// in scattering stability criterion\n#define SCATT_BIAS_SAFETY (0.75) // (0.9/RAD_SCATT_TYPES)\n\n//#define NUMIN (1.e10)\n//#define NUMAX (1.e25)\n//#define NU_BINS_SPEC (200)\n//#define NTH (8)\n//#define NPHI (8)\n\n// Whether to move polar axis slightly off of coordinate singularity\n#define COORDSINGFIX 1\n#define SINGSMALL (1.E-20)\n\n// Whether to record a representative sample of superphoton positions\n#define TRACK_PH (0)\n\n// I/O format strings\n#define FMT_DBL_OUT \"%28.18e\"\n#define FMT_INT_OUT \"%10d\"\n#define STRLEN (2048)\n\n// Reconstruction algorithms\n#define LINEAR (0)\n#define PPM (1)\n#define WENO (2)\n#define MP5 (3)\n\n// Primitive and conserved variables\n#define RHO (0)\n#define UU (1)\n#define U1 (2)\n#define U2 (3)\n#define U3 (4)\n#define B1 (5)\n#define B2 (6)\n#define B3 (7)\n#define NVAR_BASE (B3 + 1)\n\n// Passive variables (if present)\n#define PASSIVE_START (NVAR_BASE)\n#define PASSIVE_STOP (NVAR_BASE + NVAR_PASSIVE)\n#define PASSTYPE_INTRINSIC (0)\n#define PASSTYPE_NUMBER (1)\n#if EOS == EOS_TYPE_TABLE\n#define YE (PASSIVE_START)\n#define YE_EM (YE + 1)\n#if METRIC == MKS\n#define ATM (YE + 2)\n#define IS_ATM (0.0)\n#define NOT_ATM (1.0)\n#endif // METRIC\n#endif // EOS_TYPE_TABLE\n\n#if ELECTRONS\n#define KEL (B3 + NVAR_PASSIVE + 1)\n#define KTOT (B3 + NVAR_PASSIVE + 2)\n#define NVAR (NVAR_BASE + NVAR_PASSIVE + 2)\n#else\n#define NVAR (NVAR_BASE + NVAR_PASSIVE)\n#endif\n\n// NETRINOS\n#define RATYPE_NONE (0)\n#define RADTYPE_LIGHT (1)\n#define RADTYPE_NEUTRINOS (2)\n#define RAD_TYPE_START (0)\n#define TYPE_TRACER (-1)\n#if RADIATION == RADTYPE_NEUTRINOS\n#define RAD_NUM_TYPES (3)\n#define NU_ELECTRON (0)\n#define ANTINU_ELECTRON (1)\n#define NU_HEAVY (2)\n#if MULTISCATT_TEST\n#define RAD_SCATT_TYPES (3)\n#else\n#define RAD_SCATT_TYPES (4) // TODO: Should be 5, including electrons\n#define RSCATT_TYPE_P (0)\n#define RSCATT_TYPE_N (1)\n#define RSCATT_TYPE_A (2)\n#define RSCATT_TYPE_ALPHA (3)\n#define RSCATT_TYPE_E (4) // TOOD: implement me\n#endif\n#define NRADCOMP (2)\n#define RADG_YE (4)\n#define RADG_YE_EM (5)\n#elif RADIATION == RADTYPE_LIGHT\n#define RAD_NUM_TYPES (1)\n#define RAD_SCATT_TYPES (1)\n#define NRADCOMP (0)\n#define PHOTON (0)\n#else\n#define RAD_NUM_TYPES (0)\n#define RAD_SCATT_TYPES (0)\n#define NRADCOMP (0)\n#endif\n#define DLEPTON_THRESH (1e-10)\n\n// EOS\n#define EOS_TYPE_GAMMA (0)\n#define EOS_TYPE_POLYTROPE (1)\n#define EOS_TYPE_TABLE (2)\n#if EOS == EOS_TYPE_GAMMA\n#define EOS_NUM_EXTRA (0)\n#define POLYTROPE_FALLBACK (0)\n#elif EPS == EOS_TYPE_POLYTROPE\n#define EOS_NUM_EXTRA (0)\n#define POLYTROPE_FALLBACK (0)\n#elif EOS == EOS_TYPE_TABLE\n#if GAMMA_FALLBACK\n#define POLYTROPE_FALLBACK (0)\n// #define POLYTROPE_FALLBACK (1)\n#else\n#define POLYTROPE_FALLBACK (1)\n#endif // GAMMA_FALLBACK\n#define EOS_NUM_EXTRA (3)\n#define EOS_LRHO (0)\n#define EOS_LT (1)\n#define EOS_YE (2)\n// mass fractions\n#define NUM_MASS_FRACTIONS (4)\n#define MF_XA (0)\n#define MF_XH (1)\n#define MF_XN (2)\n#define MF_XP (3)\n#endif // EOS\n\n// Centering of grid functions\n#define FACE1 (0)\n#define FACE2 (1)\n#define FACE3 (2)\n#define CORN (3)\n#define CENT (4)\n#define FACESTART (FACE1)\n#define FACEEND (FACE3 + 1)\n#define PGSTART (FACE1)\n#define PGEND (NPG)\n\n// Slope limiter\n#define MC (0)\n#define VANL (1)\n#define MINM (2)\n\n// Fluid and radiation boundaries\n#define BC_OUTFLOW (0)\n#define BC_PERIODIC (1)\n#define BC_POLAR (2)\n#define BC_PROB (3)\n#define BC_ESCAPE (4)\n#define BC_CAMERA (5)\n#define BC_EQUILIB (6)\n\n// Metric\n#define MINKOWSKI (0)\n#define SPHERICAL (1)\n#define MKS (2)\n\n// Diagnostic calls\n#define DIAG_INIT (0)\n#define DIAG_DUMP (1)\n#define DIAG_LOG (2)\n#define DIAG_FINAL (3)\n\n// Types of restarts\n#define RESTART_TEMP (0)\n#define RESTART_PERM (1)\n\n// Failure modes\n#define FAIL_UTOPRIM (0)\n#define FAIL_VCHAR_DISCR (1)\n#define FAIL_COEFF_NEG (2)\n#define FAIL_COEFF_SUP (3)\n#define FAIL_GAMMA (4)\n#define FAIL_METRIC (5)\n\n// Geodesic integration and interpolation\n#define PUSH_FAIL (0)\n#define PUSH_SUCCESS (1)\n#define SPH_INTERP_FAIL (0)\n#define SPH_INTERP_SUCCESS (1)\n\n// Root finding\n#define ROOT_SUCCESS (1)\n#define ROOT_FAIL (0)\n#define FCOUNT_NBINS (6)\n#define FCOUNT_MORE (FCOUNT_NBINS - 1)\n\n// Timers\n#define TIMER_UPDATE (0)\n#define TIMER_FLUXCALC (1)\n#define TIMER_FIXUP (2)\n#define TIMER_BOUND (3)\n#define TIMER_DIAG (4)\n#define TIMER_OUT (5)\n#define TIMER_ELECTRON (6)\n#define TIMER_MAKE (7)\n#define TIMER_PUSH (8)\n#define TIMER_INTERACT (9)\n#define TIMER_MICRO (10)\n#define TIMER_ALL (11)\n#define NUM_TIMERS (12)\n\n// Units\n#define NEED_UNITS (RADIATION || EOS == EOS_TYPE_TABLE)\n\n/*******************************************************************************\n GLOBAL ARRAYS\n*******************************************************************************/\ntypedef double grid_prim_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NVAR];\ntypedef double grid_double_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\ntypedef double grid_radtype_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]\n [RAD_NUM_TYPES];\ntypedef double grid_fourvector_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]\n [NDIM];\ntypedef double grid_radg_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]\n [NDIM + NRADCOMP];\ntypedef double grid_tensor_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG][NDIM]\n [NDIM];\ntypedef int grid_int_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\ntypedef double grid_eosvar_type[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG]\n [EOS_NUM_EXTRA];\ntypedef void (*passive_init_ftype)(int, int, int, double *, double *);\ntypedef double (*hc_ftype)(double, double);\n\nextern grid_prim_type P; // Primitive variables\nextern grid_prim_type F1; // X1 fluxes\nextern grid_prim_type F2; // X2 fluxes\nextern grid_prim_type F3; // X3 fluxes\nextern grid_prim_type Ph; // Half-step primitives\nextern grid_prim_type Psave; // Half-step primitives\nextern grid_int_type pflag; // Failure points\nextern grid_int_type fail_save;\nextern grid_int_type fixup_required;\nextern grid_fourvector_type jcon;\nextern grid_eosvar_type extra; // extra variables needed by EOS\n#if RADIATION\nextern grid_radg_type radG; // Radiation four-force\nextern grid_radg_type radG_int; // ...integrated\nextern grid_radg_type radG_buf; // ...buffer for communication\nextern grid_tensor_type Rmunu; // Radiation stress-energy tensor\nextern grid_int_type Nsph;\nextern grid_double_type nph;\n\nextern struct of_photon **photon_lists;\nextern struct of_photon **photon_mpi_lists;\n\n#if DIAGNOSTICS_USE_RADTYPES\n#define NULNU_IDX0 (RAD_NUM_TYPES)\n#else\n#define NULNU_IDX0 (MAXNSCATT + 1)\n#endif\nextern double nuLnu[NULNU_IDX0][NTH][NPHI][NU_BINS_SPEC];\n\n#if RADIATION == RADTYPE_NEUTRINOS\nextern double rad_type_counts[RAD_NUM_TYPES];\nextern double lepton_tot, lepton_last, dlepton_tot, dlepton_perc;\nextern double lepton_gas, lepton_rad;\nextern double lepton_lost, lepton_lost_step, lepton_lost_local;\n#endif\n\nextern double Jrad[MAXNSCATT + 2][N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\nextern double Jrad_buf[MAXNSCATT + 2][N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\nextern double dtau_avg[RAD_SCATT_TYPES + 1][N1 + 2 * NG][N2 + 2 * NG]\n [N3 + 2 * NG];\nextern double en_int_avg[RAD_SCATT_TYPES + 1][N1 + 2 * NG][N2 + 2 * NG]\n [N3 + 2 * NG];\nextern grid_int_type Nem, Nabs, Nsc;\nextern grid_radtype_type Nem_phys, Nabs_phys, radtype_buf;\n\nextern grid_int_type Nsuper;\nextern grid_double_type Esuper;\nextern grid_prim_type psupersave;\n#endif // RADIATION\n\n// Default initialization is 0, which in this case is\n// PASSTYPE_INTRINSIC, i.e., volume densities.\nextern int passive_type[NVAR_PASSIVE];\nextern char passive_name[NVAR_PASSIVE][STRLEN];\nextern passive_init_ftype do_passive_fixup[NVAR_PASSIVE];\n\n#if ELECTRONS\nextern grid_double_type Qvisc, Qcoul;\n#endif // ELECTRONS\n\n/*******************************************************************************\n GLOBAL VARIABLES SECTION\n*******************************************************************************/\n// Command line arguments\nextern char outputdir[STRLEN], dumpdir[STRLEN], restartdir[STRLEN];\nextern char xmfdir[STRLEN];\n#if RADIATION && TRACERS\nextern char tracerdir[STRLEN];\n#endif\nextern char init_from_grmhd[STRLEN];\nextern char metric[STRLEN], reconstruction[STRLEN];\nextern char eos[STRLEN], nulnutype[STRLEN];\nextern int tracers;\n\n// path for eos\n#if EOS == EOS_TYPE_TABLE\nextern char eospath[STRLEN];\n#endif\n\n// opacity table paths\n#if RADIATION\n#if (RADIATION == RADTYPE_NEUTRINOS)\n#if BURROWS_OPACITIES\nextern char opac_param_file[STRLEN];\nextern char opac_file[STRLEN];\n#endif // BURROWS\n#if HDF5_OPACITIES\nextern char opac_file[STRLEN];\n#endif // hdf5\n#endif // neutrinos\n#endif // radiation\n\n// Physics parameters\nextern double a;\n#if EOS == EOS_TYPE_GAMMA || GAMMA_FALLBACK\nextern double gam;\n#endif\n#if EOS == EOS_TYPE_POLYTROPE\nextern double poly_K, poly_gam;\n#endif\n#if POLYTROPE_FALLBACK\nextern double rho_poly_thresh;\n#endif\nextern double M_unit;\nextern double Reh;\nextern double Risco;\n#if NEED_UNITS\nextern double mbh, Mbh, L_unit, T_unit, M_unit, RHO_unit, U_unit, B_unit;\n#endif\n#if EOS == EOS_TYPE_TABLE\nextern double TEMP_unit;\n#endif\n#if RADIATION\nextern double Ne_unit, Thetae_unit, kphys_to_num;\nextern double tp_over_te, thetae_max, sigma_max, kdotk_tol;\n#endif\n\n// Numerical parameters\nextern double Rin, Rout, Rout_vis, hslope;\nextern double poly_norm, poly_xt, poly_alpha, mks_smooth;\n#if RADIATION\nextern double Rout_rad;\nextern double nph_per_proc;\nextern double tune_emiss, t_tune_emiss, dt_tune_emiss;\nextern double tune_scatt, t_tune_scatt, dt_tune_scatt;\nextern int made_tune_proc, abs_tune_proc, scatt_tune_proc;\nextern double numin, numax;\nextern double kappa;\nextern double startx_rad[NDIM], stopx_rad[NDIM];\nextern double wgtC;\nextern int step_made, step_abs, step_scatt, step_lost, step_rec, step_tot;\nextern int tracer_tot, tracer_tot_all, ntcr_per_proc;\nextern int step_sent, step_rcvd, step_fail;\nextern int step_made_all, step_abs_all, step_scatt_all, step_lost_all;\nextern int step_rec_all, step_sent_all, step_rcvd_all, step_tot_all;\nextern int step_fail_all;\nextern int step_tot_max, step_tot_min;\nextern double load_imbalance;\nextern double Nph_to_track;\nextern double sim_vol;\n#if FLATEMISS\nextern double cnu_flat;\n#endif // FLATEMISS\n#if MULTISCATT_TEST\nextern double ms_theta_nu0, ms_delta0;\n#endif // MULTISCATT_TEST\n#endif // RADIATION\n#if ELECTRONS\nextern double tptemin, tptemax;\n#endif\nextern double cour;\n#if RADIATION\nextern double cour_cool;\n#endif\nextern double dV, dx[NDIM], startx[NDIM], stopx[NDIM], startx_proc[NDIM],\n stopx_proc[NDIM];\nextern double x1Min, x1Max, x2Min, x2Max, x3Min, x3Max;\nextern double dt, dtsave;\nextern double t, tf;\nextern int nstep;\nextern int is_restart;\n\n// Output parameters\nextern double DTd;\nextern double DTl;\nextern double DTr;\nextern int DNr;\nextern int DTp;\nextern int DTf;\nextern double DTw;\nextern int dump_cnt;\nextern int rdump_cnt;\nextern double tdump, trestart, tlog;\nextern double root_fcount[FCOUNT_NBINS];\n\n// Global flags\nextern int failed;\nextern int lim;\n\n// Diagnostics\nextern double mdot, mdot_eh;\nextern double edot, edot_eh;\nextern double ldot, ldot_eh;\nextern int icurr, jcurr, kcurr;\n\n// Parallelism\nextern int nthreads;\n\n// Electrons\n#if ELECTRONS\nextern double game, gamp;\nextern double fel0;\n#endif\n\n// Set global variables that indicate current local metric, etc.\nstruct of_geom {\n double gcon[NDIM][NDIM];\n double gcov[NDIM][NDIM];\n double g;\n double alpha;\n};\n\nstruct of_state {\n double ucon[NDIM];\n double ucov[NDIM];\n double bcon[NDIM];\n double bcov[NDIM];\n};\n\n#if RADIATION\n// WARNING: if you change struct_of_photon, be sure to change\n// the the photon hdf5 and MPI types in io.c and mpi.c\n#define NSUP 3\nstruct of_photon {\n // NSUP >=3 X^{\\mu}, K^{\\mu}, K_{\\mu} so photon data always available anywhere\n // between n and n+1\n double X[NSUP][NDIM];\n double Kcov[NSUP][NDIM];\n double Kcon[NSUP][NDIM];\n double w;\n double KdotKprev;\n // radiation type. For neutrinos, flavor. Always active.\n // Not always important.\n // TODO: make sure to always set type when it's needed.\n int type;\n int nscatt;\n int origin[NDIM];\n double t0;\n int is_tracked;\n struct of_photon *next;\n};\n\n#define PH_ELEM (11)\nstruct of_track_photon {\n double X1;\n double X2;\n double X3;\n int nscatt;\n};\nstruct of_microphysics {\n#if RADIATION == RADTYPE_NEUTRINOS\n double rho;\n double T;\n double Ye;\n double Abar, Zbar;\n double Xi[NUM_MASS_FRACTIONS];\n#if BURROWS_OPACITIES || HDF5_OPACITIES\n double jgrp[RAD_NUM_TYPES][NU_BINS + 1];\n double alphagrp[RAD_NUM_TYPES][NU_BINS + 1];\n#endif\n#else // RADTYPE_LIGHT\n double Thetae;\n double Ne;\n#endif\n // needed for Bk-angle (which isn't really needed for neutrinos, but\n // this is the easy engineering solution)\n double B;\n};\ntypedef double (*dsdom_ftype)(\n double, double, const struct of_microphysics *, int, int);\n#endif // RADIATION\n\n#if EOS == EOS_TYPE_TABLE\nstruct of_adiabat {\n double s, ye;\n double lrho_min, lrho_max;\n int imin, imax;\n double hm1_min, hm1_max;\n double *lT;\n};\n#endif\n\n#if EOS == EOS_TYPE_TABLE || HDF_OPACITIES || BURROWS_OPACITIES\nstruct of_tablebounds {\n int Nrho, NT, NYe;\n double lrho_min, lrho_max, dlrho;\n double lT_min, lT_max, dlT;\n double Ye_min, Ye_max, dYe;\n};\n#endif\n\n// More grid functions. Axisymmetry assumed.\nextern double conn[N1 + 2 * NG][N2 + 2 * NG][NDIM][NDIM][NDIM];\nextern struct of_geom ggeom[N1 + 2 * NG][N2 + 2 * NG][NPG];\n#if RADIATION\n// extern double dt_light, dt_light_min;\nextern double dt_light[N1 + 2 * NG][N2 + 2 * NG], dt_light_min;\nextern struct of_microphysics m_grd[N1 + 2 * NG][N2 + 2 * NG][N3 + 2 * NG];\nextern grid_fourvector_type Ucon_grd, Ucov_grd, Bcon_grd, Bcov_grd;\n#endif\n\n// MPI-specific stuff\nextern int global_start[NDIM];\nextern int global_stop[NDIM];\n\n/*******************************************************************************\n MACROS\n*******************************************************************************/\n#define ILOOP for (int i = 0 + NG; i < N1 + NG; i++)\n#define ILOOPALL for (int i = 0; i < N1 + 2 * NG; i++)\n#define JLOOP for (int j = 0 + NG; j < N2 + NG; j++)\n#define JLOOPALL for (int j = 0; j < N2 + 2 * NG; j++)\n#define KLOOP for (int k = 0 + NG; k < N3 + NG; k++)\n#define KLOOPALL for (int k = 0; k < N3 + 2 * NG; k++)\n#define ZLOOP \\\n for (int i = 0 + NG; i < N1 + NG; i++) \\\n for (int j = 0 + NG; j < N2 + NG; j++) \\\n for (int k = 0 + NG; k < N3 + NG; k++)\n#define ZLOOPALL ILOOPALL JLOOPALL KLOOPALL\n#define ISLOOP(istart, istop) for (int i = istart + NG; i <= istop + NG; i++)\n#define JSLOOP(jstart, jstop) for (int j = jstart + NG; j <= jstop + NG; j++)\n#define KSLOOP(kstart, kstop) for (int k = kstart + NG; k <= kstop + NG; k++)\n#define ZSLOOP(istart, istop, jstart, jstop, kstart, kstop) \\\n for (int i = istart + NG; i <= istop + NG; i++) \\\n for (int j = jstart + NG; j <= jstop + NG; j++) \\\n for (int k = kstart + NG; k <= kstop + NG; k++)\n// Loop over faces\n#define FACELOOP for (int face = FACESTART; face < FACEEND; face++)\n// Loop over all locations\n#define LOCLOOP for (int loc = PGSTART; loc < PGEND; loc++)\n// Loop over primitive variables\n#define PLOOP for (int ip = 0; ip < NVAR; ip++)\n#define BASELOOP for (int ip = 0; ip < NVAR_BASE; ip++)\n\n// Loop over spacetime indices\n#define DLOOP1 for (int mu = 0; mu < NDIM; mu++)\n#define DLOOP2 \\\n for (int mu = 0; mu < NDIM; mu++) \\\n for (int nu = 0; nu < NDIM; nu++)\n#define DLOOP3 \\\n for (int mu = 0; mu < NDIM; mu++) \\\n for (int nu = 0; nu < NDIM; nu++) \\\n for (int sigma = 0; sigma < NDIM; sigma++)\n// spacelike indices\n#define SDLOOP for (int mu = 1; mu < NDIM; mu++)\n\n// Loop over extra variables\n// TODO: Figure out how to make this conditionally defined. ~JMM\n#define EOS_ELOOP for (int e = 0; e < EOS_NUM_EXTRA; e++)\n\n// Loop over passive scalars\n#define PASSLOOP for (int ipass = PASSIVE_START; ipass < PASSIVE_STOP; ipass++)\n#define PASSELEM(ipass) (ipass - PASSIVE_START)\n#define PASSTYPE(ipass) (passive_type[PASSELEM(ipass)])\n#define PASSNAME(ipass) (passive_name[PASSELEM(ipass)])\n\n#define TYPELOOP for (int itp = RAD_TYPE_START; itp < RAD_NUM_TYPES; itp++)\n#define SCATTLOOP for (int iscatt = 0; iscatt < RAD_SCATT_TYPES; iscatt++)\n#define JRADLOOP for (int n = 0; n < MAXNSCATT + 2; n++)\n#define NULOOP for (int inu = 0; inu < NU_BINS + 1; inu++)\n\n#define MY_MIN(fval1, fval2) (((fval1) < (fval2)) ? (fval1) : (fval2))\n#define MY_MAX(fval1, fval2) (((fval1) > (fval2)) ? (fval1) : (fval2))\n#define MY_SIGN(fval) (((fval) < 0.) ? -1. : 1.)\n\n#define delta(i, j) ((i == j) ? 1. : 0.)\n#define dot(a, b) (a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3])\n\n/*******************************************************************************\n FUNCTION DECLARATIONS\n*******************************************************************************/\n\n// bounds.c\nvoid bound_prim(grid_prim_type prim);\nvoid fix_flux(grid_prim_type F1, grid_prim_type F2, grid_prim_type F3);\n#if RADIATION\nvoid bound_superphotons(grid_prim_type P, double t, double dt);\nvoid polar_fix(double X[NDIM], struct of_photon *ph);\nint rad_error_check(struct of_photon **ph);\n// int rad_boundary_transport(double X[NDIM], double Kcov[NDIM]);\nvoid bound_rad_transport(\n double X[NDIM], struct of_photon *ph, int is_transported);\nint bound_rad_isactive(double X[NDIM], struct of_photon *ph);\nint rad_mpi_transport(struct of_photon **ph, struct of_photon **prev,\n struct of_photon **head, double X[NDIM], int active);\n#endif\n\n// coord.c\nvoid coord(int i, int j, int k, int loc, double X[NDIM]);\ndouble r_of_X(const double X[NDIM]);\ndouble th_of_X(const double X[NDIM]);\nvoid jac_harm_to_bl(\n const double X[NDIM], double Jcov[NDIM][NDIM], double Jcon[NDIM][NDIM]);\nvoid jac_bl_to_cart(\n const double X[NDIM], double Jcov[NDIM][NDIM], double Jcon[NDIM][NDIM]);\nvoid jac_harm_to_cart(\n const double X[NDIM], double Jcov[NDIM][NDIM], double Jcon[NDIM][NDIM]);\nvoid set_dxdX(double X[NDIM], double dxdX[NDIM][NDIM]);\nvoid bl_coord(const double X[NDIM], double *r, double *th);\nint bl_i_of_r(double r);\nvoid cart_coord(const double X[NDIM], double Xcart[NDIM]);\nvoid set_gcov(double X[NDIM], double gcov[NDIM][NDIM]);\nvoid set_metric(double X[NDIM], struct of_geom *g);\nvoid set_points();\nvoid zero_arrays(void);\nvoid set_grid(void);\nvoid cart_to_sph(const double X[NDIM], double *r, double *th, double *ph);\n\n// current.c\nvoid current_calc();\n\n// diag.c\nvoid reset_log_variables();\nvoid reset_dump_variables();\nvoid diag(int call_code);\nvoid fail(int fail_type);\nvoid area_map(int i, int j, int k, grid_prim_type prim);\nvoid diag_flux(grid_prim_type F1, grid_prim_type F2, grid_prim_type F3);\ndouble flux_ct_divb(int i, int j, int k);\n#if RADIATION\nvoid record_superphoton(double X[NDIM], struct of_photon *ph);\nvoid bin_all_superphotons();\nvoid report_load_imbalance();\n#if RADIATION == RADTYPE_NEUTRINOS\nvoid print_rad_types();\nvoid count_leptons(grid_prim_type P, double dt, int nstep);\n#endif\n#endif\n\n// electrons.c\n#if ELECTRONS\nvoid init_electrons();\nvoid heat_electrons(\n grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt);\ndouble get_fel(int i, int j, int k, double p[NVAR]);\n#if RADIATION\nvoid coulomb(\n grid_prim_type Pi, grid_prim_type Ps, grid_prim_type Pf, double Dt);\nvoid apply_rad_force_e(\n grid_prim_type Prh, grid_prim_type Pr, grid_radg_type radG, double Dt);\n#endif // RADIATION\nvoid fixup_electrons(grid_prim_type p);\n#endif\n\n// emissivity.c\n#if RADIATION\ndouble jnu(double nu, int type, const struct of_microphysics *m, double theta);\ndouble Jnu(double nu, int type, const struct of_microphysics *m);\ndouble get_J(struct of_microphysics *m);\nvoid init_emissivity();\n#endif\n\n// eos.c\nvoid init_EOS();\ndouble EOS_bad_eos_error();\ndouble EOS_get_gamma(const double *extra);\ndouble EOS_pressure_rho0_u(double rho, double u, const double *extra);\ndouble EOS_pressure_rho0_w(double rho, double w, double gamma,\n const struct of_geom *geom, double *extra);\ndouble EOS_enthalpy_rho0_u(double rho, double u, const double *extra);\ndouble EOS_sound_speed_rho0_u(double rho, double u, const double *extra);\nvoid EOS_set_floors(double scale, double rho, double u, double bsq,\n double *rhoflr, double *uflr, const double *extra);\ndouble EOS_entropy_rho0_u(double rho, double u, const double *extra);\ndouble EOS_adiabatic_constant(double rho, double u, const double *extra);\ndouble EOS_temperature(double rho, double u, const double *extra);\ndouble EOS_u_press(double press, double rho, double *extra);\n#if RADIATION\ndouble EOS_u_N_Theta(double rho, double N, double Theta, double *extra);\ndouble EOS_pressure_N_Theta(double N, double Theta);\ndouble EOS_Theta_unit();\n#endif // RADIATION\n\n// eos_gamma.c\n#if EOS == EOS_TYPE_GAMMA || GAMMA_FALLBACK\ndouble EOS_Gamma_pressure_rho0_u(double rho, double u);\ndouble EOS_Gamma_pressure_rho0_w(double rho, double w);\ndouble EOS_Gamma_entropy_rho0_u(double rho, double u);\ndouble EOS_Gamma_enthalpy_rho0_u(double rho, double u);\ndouble EOS_Gamma_adiabatic_constant_rho0_u(double rho, double u);\ndouble EOS_Gamma_sound_speed_rho0_u(double rho, double u);\nvoid EOS_Gamma_set_floors(double scale, double rho, double u, double bsq,\n double *rhoflr, double *uflr);\ndouble EOS_Gamma_rho_floor(double scale, double bsq);\ndouble EOS_Gamma_u_floor(double scale, double bsq);\ndouble EOS_Gamma_u_scale(double rho);\ndouble EOS_Gamma_u_press(double press);\ndouble EOS_Gamma_temp(double rho, double u);\n#if RADIATION\ndouble EOS_Gamma_Theta_unit();\n#endif // RADIATION\n#endif // EOS_TYPE_GAMMA\n\n// eos_poly.c\n#if EOS == EOS_TYPE_POLYTROPE || POLYTROPE_FALLBACK\ndouble EOS_Poly_pressure_rho0_u(double rho, double u, double K, double Gam);\ndouble EOS_Poly_pressure_rho0_w(double rho, double w, double K, double Gam);\ndouble EOS_Poly_enthalpy_rho0_u(double rho, double u, double K, double Gam);\ndouble EOS_Poly_entropy_rho0_u(double rho, double u, double K, double Gam);\ndouble EOS_Poly_sound_speed_rho0_u(double rho, double u, double K, double Gam);\nvoid EOS_Poly_set_floors(double scale, double rho, double u, double bsq,\n double *rhoflr, double *uflr);\ndouble EOS_Poly_rho_floor(double scale, double bsq);\ndouble EOS_Poly_u_floor(double scale, double bsq);\ndouble EOS_Poly_adiabatic_constant(double rho, double u, double K, double Gam);\n#endif // EOS_TYPE_POLY\n\n// eos_stellar_collapse.c\n#if EOS == EOS_TYPE_TABLE\nvoid EOS_SC_init(char *name);\nvoid EOS_SC_fill(double *restrict p, double *restrict eos);\ndouble EOS_SC_pressure_rho0_u(double lrho, double lT, double ye);\ndouble EOS_SC_pressure_rho0_w(double rho, double w, double ye, double *lTold);\ndouble EOS_SC_specific_enthalpy_rho0_u(double lrho, double lT, double ye);\ndouble EOS_SC_sound_speed(double lrho, double lT, double ye);\ndouble EOS_SC_entropy(double lrho, double lT, double ye);\ndouble EOS_SC_gamma(double lrho, double lT, double ye);\ndouble EOS_SC_temperature(double lT);\ndouble EOS_SC_get_u_of_T(double rho, double T, double ye);\ndouble EOS_SC_u_press(double press, double rho, double ye, double *lTold);\nvoid EOS_SC_mass_fractions(double Xi[NUM_MASS_FRACTIONS], const double *extra);\nvoid EOS_SC_avg_ions(double *Abar, double *Zbar, const double *extra);\nvoid EOS_SC_set_floors(double scale, double rho, double u, double ye,\n double bsqr, double *rhoflr, double *uflr);\ndouble EOS_SC_rho_floor(double scale, double bsq);\ndouble EOS_SC_u_floor(double scale, double bsq, double ye);\ndouble EOS_SC_get_min_lrho();\ndouble EOS_SC_get_min_rho();\ndouble EOS_SC_get_min_lT();\ndouble EOS_SC_get_minu(double rho, double ye, double scale);\nvoid EOS_SC_get_polytrope(\n double lrho, double lT, double ye, double *poly_K, double *poly_gamma);\ndouble EOS_SC_hm1_min_adiabat(const struct of_adiabat *a);\nint EOS_SC_find_adiabat_1d(double s, double ye, struct of_adiabat *a);\nvoid EOS_SC_print_adiabat(const struct of_adiabat *a);\nvoid EOS_SC_adiabat_free(struct of_adiabat *a);\nvoid EOS_SC_isoentropy_hm1(double hm1, const struct of_adiabat *a,\n double *lrho_guess, double *rho, double *u);\nvoid do_ye_fixup(\n int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);\nvoid do_ye_em_fixup(\n int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);\nvoid do_atm_fixup(\n int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);\nvoid EOS_SC_get_bounds(struct of_tablebounds *b);\nvoid EOS_SC_print_table_mins();\n#endif // EOS_TYPE_TABLE\n\n// estimate_thetae.c\n#if RADIATION\ndouble get_Thetae_est(int i, int j, int k);\nvoid estimate_Thetae(\n grid_prim_type P, grid_eosvar_type extra, double t, double dt);\n#endif\n\n// fixup.c\nvoid fixup(grid_prim_type pv, grid_eosvar_type extra);\ndouble get_scale(int i, int j, int k);\nvoid fixup1zone(\n int i, int j, int k, double pv[NVAR], double extra[EOS_NUM_EXTRA]);\nvoid fixup_utoprim(grid_prim_type pv, grid_eosvar_type extra);\n\n// interact.c\n#if RADIATION\nvoid interact(grid_prim_type P, grid_eosvar_type extra, double t, double dt);\n#endif\n\n// input.c\nvoid init_params(char *pfname);\nvoid set_param(char *key, void *data);\n\n// io.c\n// void set_core_params();\n// void set_param(char *key, void *data);\n// void read_params(char *pfname);\nvoid init_io();\nvoid init_fluid_restart();\n#if RADIATION\nvoid track_ph();\n#if TRACERS\nvoid dump_tracers();\n#endif\n#endif\nvoid dump_grid();\nvoid dump();\nvoid restart_write(int restart_type);\nvoid restart_read(char *fname);\nint restart_init();\n\n// make_superphotons.c\n#if RADIATION\nvoid make_superphotons(\n grid_prim_type Prad, grid_eosvar_type extra, double t, double dt);\nvoid set_weight(grid_prim_type Prad, grid_eosvar_type extra);\nvoid get_dnz(grid_prim_type Prad, grid_eosvar_type extra);\n#endif\n\n// metric.c\ndouble gcon_func(double lgcov[][NDIM], double lgcon[][NDIM]);\nvoid conn_func(double *X, struct of_geom *geom, double conn[][NDIM][NDIM]);\nvoid lower(double ucon[NDIM], double gcov[NDIM][NDIM], double ucov[NDIM]);\nvoid raise(double ucov[NDIM], double gcon[NDIM][NDIM], double ucon[NDIM]);\nstruct of_geom *get_geometry(int ii, int jj, int kk, int loc);\nvoid blgset(int i, int j, struct of_geom *geom);\ndouble bl_gdet_func(double r, double th);\nvoid bl_gcov_func(double r, double th, double gcov[][NDIM]);\nvoid bl_gcon_func(double r, double th, double gcon[][NDIM]);\ndouble MINOR(double m[16], int r0, int r1, int r2, int c0, int c1, int c2);\nvoid adjoint(double m[16], double adjOut[16]);\ndouble determinant(double m[16]);\ndouble invert(double *m, double *invOut);\n\n// mpi.c\nvoid init_mpi();\nvoid sync_mpi_boundaries_X1L(grid_prim_type Pr);\nvoid sync_mpi_boundaries_X1R(grid_prim_type Pr);\nvoid sync_mpi_boundaries_X2L(grid_prim_type Pr);\nvoid sync_mpi_boundaries_X2R(grid_prim_type Pr);\nvoid sync_mpi_boundaries_X3L(grid_prim_type Pr);\nvoid sync_mpi_boundaries_X3R(grid_prim_type Pr);\n#if RADIATION\nvoid sync_radG();\nvoid sync_Jrad();\nvoid sync_radtype_vec(grid_radtype_type v);\nvoid sync_mpi_photons(\n struct of_photon **ph_mpi, grid_prim_type P, double t, double dt);\nvoid mpi_reduce_nuLnu();\n#endif\nint mpi_nprocs();\ndouble mpi_max(double f);\ndouble mpi_min(double f);\nint mpi_max_int(int f);\ndouble mpi_reduce(double f);\nint mpi_reduce_int(int f);\nvoid mpi_dbl_allreduce_array(double *A, int size);\nint mpi_io_proc();\nvoid mpi_int_broadcast(int *val);\nvoid mpi_int_broadcast_array(int *val, int size);\nvoid mpi_int_broadcast_proc(int *val, int root);\nvoid mpi_dbl_broadcast(double *val);\nvoid mpi_allgather_int1(int *buffer, int element);\nint mpi_accumulate_int(int my_val);\ndouble mpi_io_reduce(double val);\ndouble mpi_io_max(double val);\nint mpi_myrank();\nvoid mpi_sync_output();\nvoid mpi_barrier();\nint mpi_is_periodic(int dir);\n\n// opac_emis_neutrino.c\n#if RADIATION\n#if RADIATION == RADTYPE_NEUTRINOS && BURROWS_OPACITIES\nvoid init_opac_emis_burrows();\nvoid fill_opac_emis_burrows(struct of_microphysics *m);\ndouble jnu_burrows(double nu, int type, const struct of_microphysics *m);\ndouble Jnu_burrows(double nu, int type, const struct of_microphysics *m);\ndouble int_jnudnudOmega_burrows(const struct of_microphysics *m);\ndouble alpha_nu_burrows(double nu, int type, const struct of_microphysics *m);\nvoid test_opac_emis();\n#if EOS == EOS_TYPE_TABLE\nvoid opac_emis_to_hdf(const char *name, const struct of_tablebounds *b);\n#endif // EOS\n#endif // Burrows opacities\n#if RADIATION == RADTYPE_NEUTRINOS && HDF5_OPACITIES\nvoid init_opac_emis_hdf(char *name);\nvoid fill_opac_emis_hdf(struct of_microphysics *m);\ndouble jnu_hdf(double nu, int type, const struct of_microphysics *m);\ndouble Jnu_hdf(double nu, int type, const struct of_microphysics *m);\ndouble int_jnudnudOmega_hdf(const struct of_microphysics *m);\ndouble alpha_nu_hdf(double nu, int type, const struct of_microphysics *m);\n#endif // HDF opacities\n#endif // RADIATION\n\n// passive.c\n//#if NVAR_PASSIVE > 0\nvoid fixup_passive(\n int i, int j, int k, double pv[NVAR], double pv_prefloor[NVAR]);\nvoid init_passives();\nvoid name_passives();\n//#endif\n\n// phys.c\nvoid primtoflux(double *pr, struct of_state *q, int dir, int magnetic,\n struct of_geom *geom, double *flux);\nvoid bcon_calc(double *pr, double *ucon, double *ucov, double *bcon);\nvoid mhd_calc(double *pr, int dir, int magnetic, struct of_state *q,\n double *extra, double *mhd);\nvoid source(double *ph, struct of_geom *geom, int ii, int jj, double *dU,\n double Dt, double *extra);\ndouble bsq_calc(double *pr, struct of_geom *geom);\nvoid get_state(double *pr, struct of_geom *geom, struct of_state *q);\nvoid ucon_calc(double *pr, struct of_geom *geom, double *ucon);\nint mhd_gamma_calc(double *pr, struct of_geom *geom, double *gamma);\nvoid mhd_vchar(double *pr, struct of_state *q, struct of_geom *geom, int js,\n double *vmax, double *vmin);\n\n// problem.c\nvoid set_problem_params();\nvoid init_prob();\nvoid bound_gas_prob_x1l(int i, int j, int k, grid_prim_type P);\nvoid bound_gas_prob_x1r(int i, int j, int k, grid_prim_type P);\nvoid bound_gas_prob_x2l(int i, int j, int k, grid_prim_type P);\nvoid bound_gas_prob_x2r(int i, int j, int k, grid_prim_type P);\nvoid bound_gas_prob_x3l(int i, int j, int k, grid_prim_type P);\nvoid bound_gas_prob_x4r(int i, int j, int k, grid_prim_type P);\n\n// push_superphotons.c\n#if RADIATION\nint push_X_K(double X[NDIM], double Kcov[NDIM], double Kcon[NDIM],\n grid_prim_type P, grid_prim_type Prad, double KdotKprev, int type,\n double dtpush);\nint push_superphoton(\n struct of_photon *ph, grid_prim_type P, grid_prim_type Prad, double dtpush);\nvoid push_superphotons(grid_prim_type P, grid_prim_type Prad, double dt);\n#endif\n\n// rad_utils.c\n#if RADIATION\nvoid init_rad(grid_prim_type Prad);\nvoid init_superphoton_resolution();\nvoid update_superphoton_resolution(grid_prim_type Prad, grid_eosvar_type extra);\ndouble linear_interp_log(double x, double *table, double lmin, double dl);\nvoid list_remove(struct of_photon **ph, struct of_photon **ph_head,\n struct of_photon **ph_prev);\ndouble get_Thetae(double P[NVAR]);\ndouble scatterer_dimensionless_temp(\n int radtype, int interaction, const struct of_microphysics *m);\ndouble scatterer_number_density(\n int radtype, int interaction, const struct of_microphysics *m);\nvoid precompute_microphysics();\nvoid get_fluid_zone(int i, int j, int k, grid_prim_type Prad,\n grid_eosvar_type extra, struct of_microphysics *m, double Ucon[NDIM],\n double Ucov[NDIM], double Bcon[NDIM], double Bcov[NDIM]);\nint is_null(double Kcov[NDIM], double Kcon[NDIM], double K0, double KdotKprev,\n double *KdotK);\nvoid set_Rmunu();\n// int is_null(struct of_photon *ph, double *KdotK);\nvoid Xtoijk(double X[NDIM], int *i, int *j, int *k);\nvoid copy_photon(struct of_photon *ph, struct of_photon *phc);\nvoid print_ph_diag(struct of_photon *ph);\nint get_X_K_interp(struct of_photon *ph, double t_interp, grid_prim_type P,\n double X[NDIM], double Kcov[NDIM], double Kcon[NDIM]);\nint to_be_pushed(double t, double dt, struct of_photon *ph);\ndouble get_dtpush(struct of_photon *ph, double dt);\nvoid swap_ph(struct of_photon **donor, struct of_photon **recipient);\nvoid get_nuLnu_bin(double X[NDIM], int *thbin, int *phibin);\nvoid bin_superphoton_direction(const struct of_photon *ph);\ndouble get_min_dt_cool(grid_prim_type P, grid_eosvar_type extra);\nvoid set_cooling_time(\n grid_double_type tau_cool, grid_prim_type P, grid_eosvar_type extra);\n#if RADIATION == RADTYPE_NEUTRINOS\nvoid record_lepton_flux(const struct of_photon *ph);\nvoid check_nu_type(const char *location);\nint get_lepton_sign(const struct of_photon *ph);\n#endif // NEUTRINOS\n#endif // RADIATION\n\n// radiation.c\n#if RADIATION\ndouble Bnu_inv(double nu, const struct of_microphysics *m); // TODO?\ndouble jnu_inv(\n double nu, int type, const struct of_microphysics *m, double theta);\ndouble alpha_inv_scatt(\n double nu, int type, int interaction, const struct of_microphysics *m);\ndouble alpha_inv_abs(\n double nu, int type, const struct of_microphysics *m, double theta);\ndouble get_fluid_nu(double X[NDIM], double Kcov[NDIM], double Ucon[NDIM]);\ndouble get_bk_angle(double X[NDIM], double K[NDIM], double Ucov[NDIM],\n double Bcov[NDIM], double B);\n#endif\n\n// random.c\nvoid init_random(int seed);\ndouble get_rand();\ndouble get_chisq(double nu);\ndouble get_gaussian(double mu, double sigma);\nvoid get_ran_dir_3d(double *nx, double *ny, double *nz);\n\n// reconstruction.c\nvoid reconstruct(double ptmp[NMAX + 2 * NG][NVAR], int N,\n double p_l[NMAX + 2 * NG][NVAR], double p_r[NMAX + 2 * NG][NVAR]);\n\n// root_finding.c\n// counts root_finding iterations\nvoid initialize_root_fcounts();\nvoid print_root_fcounts();\n// solves for f(x,params) - ytarget = 0\nint find_root(double (*f)(const double, const void *), const void *params,\n const double ytarget, double xguess, const double xmin, const double xmax,\n const double xtol, const double ytol, double *xroot);\n\n// scattering.c\n#if RADIATION\nint scatt_temp_too_small(const struct of_microphysics *m);\nint scatter_superphoton(grid_prim_type P, grid_eosvar_type extra,\n struct of_photon *ph, double X[NDIM], double Kcov[NDIM], double Kcon[NDIM],\n int interaction);\nvoid init_all_hotcross();\ndouble total_cross_lkup(\n double w, int type, int interaction, const struct of_microphysics *m);\n#endif\n\n// step.c\nvoid step();\n\n// tetrads.c\n#if RADIATION\nvoid coord_to_tetrad(\n double Ecov[NDIM][NDIM], double Kcoord[NDIM], double Ktetrad[NDIM]);\nvoid tetrad_to_coord(\n double Econ[NDIM][NDIM], double Ktetrad[NDIM], double Kcoord[NDIM]);\nvoid make_tetrad(int i, int j, int k, double Ucon[NDIM], double trial[NDIM],\n double Gcov[NDIM][NDIM], double Econ[NDIM][NDIM], double Ecov[NDIM][NDIM]);\nvoid normalize_null(double Gcov[NDIM][NDIM], double K[NDIM]);\nvoid normalize_null_cov(double Gcon[NDIM][NDIM], double K[NDIM]);\n#endif\n\n// timing.c\nvoid time_set(int n, double val);\ndouble time_read(int n);\nvoid time_init();\nvoid timer_start(int timerCode);\nvoid timer_stop(int timerCode);\ndouble get_time_per_step(int timerCode);\nvoid report_performance();\nvoid timers_reset();\n\n// tracers.c\n#if RADIATION && TRACERS\ndouble get_total_tracer_mass();\nint tracer_max_id(long unsigned int ntracers);\nint count_tracers_local();\nvoid lagrange_interp_grid_3d(\n double v_interp[], double X[NDIM], double *v, int size);\nvoid lagrange_interp_prim_3d(\n double P_interp[NVAR], double X[NDIM], grid_prim_type P);\nvoid push_tracers(double X[NDIM], double Kcov[NDIM], double Kcon[NDIM],\n grid_prim_type P, grid_prim_type Ph, double dt);\nint tracer_get_id(struct of_photon *ph);\ndouble tracer_get_mass(struct of_photon *ph);\nvoid tracer_get_X_u(struct of_photon *ph, double t_interp, double X[NDIM],\n double ucov[NDIM], double ucon[NDIM]);\nvoid set_tracer(struct of_photon *ph, int id, int nstep, double t,\n double X[NDIM], double mass, grid_prim_type P);\nvoid make_tracer(struct of_photon **head, int id, int nstep, double t,\n double X[NDIM], double mass, grid_prim_type P);\nvoid sample_tracers_in_cell(struct of_photon **head, int nstep, int i, int j,\n int k, int *last_id, int ntracers_per_cell, double t, grid_prim_type P);\nvoid sample_all_tracers(long unsigned int ntracers_tot, int nstep, double t,\n grid_int_type tcrs_in_cell, grid_prim_type P);\nvoid prune_tracers();\n#endif\n\n// util.c\ndouble find_min(const double *array, int size);\ndouble find_max(const double *array, int size);\ndouble find_median(double *array, int size);\ndouble interp_1d(double x, const double xmin, const double xmax, const int imin,\n const int imax, const double *restrict tab_x, const double *restrict tab_y);\nint find_index(double value, const double *array, int size);\nvoid * safe_malloc(size_t size);\nvoid safe_system(const char *command);\nvoid safe_fscanf(FILE *stream, const char *format, ...);\nint is_practically_nan(double v);\n#if NEED_UNITS\nvoid set_units();\n#endif\n\n// utop.c\nint Utoprim(double U[NVAR], struct of_geom *geom, double prim[NVAR]);\n\n// xdmf_output.c\nvoid write_xml_file(int dump_id, double t, const char *vnams[NVAR]);\n", "meta": {"hexsha": "c61882d857f3de07fdcb756f1e60d849d907706f", "size": 40613, "ext": "h", "lang": "C", "max_stars_repo_path": "core/decs.h", "max_stars_repo_name": "soumide1102/nubhlight", "max_stars_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_stars_repo_licenses": ["BSD-3-Clause"], "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/decs.h", "max_issues_repo_name": "soumide1102/nubhlight", "max_issues_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_issues_repo_licenses": ["BSD-3-Clause"], "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/decs.h", "max_forks_repo_name": "soumide1102/nubhlight", "max_forks_repo_head_hexsha": "85046add8b7e2c1419538864eb54205d33078772", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.2436762226, "max_line_length": 82, "alphanum_fraction": 0.6981508384, "num_tokens": 11676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.23914545451109062}} {"text": "/*\n# Program to run a Monte Carlo radiation transfer through the 2D\n# simulations of GRB jets.\n#\n# Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State \n# ver 0.1 July 8, 2015\n# ver 1.1 July 20, 2015: added record of number of scatterings, included\n# \tall terms in weight. Should now give correct light curves.\n# ver 1.2 July 21, 2015: added parameter file to keep track of input\n# \tparams of each simulation\n\n# ver 2.0 July 22, 2015: corrected the problem that arises when there is\n# \tno scattering in the time span of one frame. Fixed output arrays dimension.\n\n# ver 2.1 July 25, 2015: fixed bug that did not make the number of\n# \tscattering grow with the number of photons.\n\n# ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to\n# \tspeed things up. Gained about factor 2\n\n# ver 3.1 July 29, 2015: added radial spread of photon injection points\n# ver 3.2 July 31, 2015: added Gamma to the weight of photons!!!\n\n# ver 4.0 Aug 5, 2015: try to speed up by inverting cycle\n# ver 4.1 Aug 8, 2015: add spherical test as an option\n# ver 4.2 Aug 9, 2015: saving files appending rather than re-writing\n# ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature\n# ver 4.4 Aug 13, 2015: added cylindrical test\n# ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test\n# ver 4.6 Aug 21, 2015: corrected mean free path for large radii\n\n# ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings\n# ver 5.1 Aug 25, 2015: cleaned-up coding\n# ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections\n * \n * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path\n so you just need to supply the sub directory of MC_XXX as a command line argument\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \"mclib.h\"\n#include \"mclib_3d.h\"\n#include \n\n\n#define THISRUN \"Science\"\n#define FILEPATH \"/Users/Tylerparsotan/Documents/Box\\ Sync/RIKEN_HYDRO_DATA/JP_HYDRODATA/\"\n#define FILEROOT \"u\"\n#define MC_PATH \"PHOTON_TEST/\"\n//#define MC_PATH \"MC_16OI/Single_Photon_Cy_mc_total/\"\n#define MCPAR \"riken_mc.par\"\n\nint main(int argc, char **argv)\n{\n //compile each time a macro is changed\n \n\t// Define variables\n\tchar flash_prefix[200]=\"\";\n\tchar mc_file[200]=\"\" ;\n char this_run[200]=THISRUN;\n char *cyl=\"Cylindrical\";\n char *sph=\"Spherical\";\n char spect;//type of spectrum\n char restrt;//restart or not\n double fps, theta_jmin, theta_jmax ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians\n double inj_radius_small, inj_radius_large, ph_weight_suggest ;//radius at chich photons are injected into sim\n int frm0_small, frm0_large,last_frm, frm2_small, frm2_large, j=0, min_photons, max_photons ;//frame starting from, last frame of sim, frame of last injection\n \n int num_thread=0, angle_count=0;\n int half_threads=floor((num_thread/2));\n int num_angles=0;\n int dim_switch=0;\n double *thread_theta=NULL; //saves ranges of thetas for each thread to go through\n double delta_theta=0;\n \n //new muliple threads injecting and propagating photons\n const gsl_rng_type *rng_t;\n gsl_rng **rng;\n gsl_rng_env_setup();\n rng_t = gsl_rng_ranlxs0;\n\n \n //want to break up simulation by angle and injection frame & have each thread save data in its own folder \n //have each thread check if its directory is made and if its restarting (delete evrything) or if its continuing with a previous simulation\n //the angle and the injection frames will be the names of mc_dir, therefore read mc.par first in MC_XXX directory\n \n //make strings of proper directories etc.\n\tsnprintf(flash_prefix,sizeof(flash_prefix),\"%s%s\",FILEPATH,FILEROOT );\n\t//snprintf(mc_dir,sizeof(flash_prefix),\"%s%s\",FILEPATH,MC_PATH);\n //snprintf(mc_file,sizeof(flash_prefix),\"%s%s\",mc_dir, MCPAR);\n snprintf(mc_file,sizeof(flash_prefix),\"%s%s%s\",FILEPATH, MC_PATH,MCPAR);\n\n \n //printf(\">> mc.py: Reading mc.par\\n\");\n \n readMcPar(mc_file, &fps, &theta_jmin, &theta_jmax, &delta_theta, &inj_radius_small,&inj_radius_large, &frm0_small , &frm0_large ,&last_frm ,&frm2_small, &frm2_large, &ph_weight_suggest, &min_photons, &max_photons, &spect, &restrt, &num_thread, &dim_switch); //thetas that comes out is in degrees\n \n //printf(\"small: %d large: %d weights: %e, %c\\n\", min_photons, max_photons, ph_weight_suggest, restrt);\n if (num_thread==0)\n {\n num_thread=omp_get_max_threads(); //if user specifies 0 in mc.par, default to max number of threads possible\n }\n \n half_threads=floor((num_thread/2));\n //thread_theta=malloc(((half_threads)+1)*sizeof(double) );\n \n \n rng = (gsl_rng **) malloc((num_thread ) * sizeof(gsl_rng *)); \n rng[0] = gsl_rng_alloc (rng_t); //initalize first random number generator to seed the others with random numbers\n \n for(j=1;j> Thread %d in MCRaT: I am working on path: %s \\n\",omp_get_thread_num(), mc_dir );\n \n if ((theta_jmin_thread >= 0) && (theta_jmax_thread <= (2*M_PI/180) )) //if within small angle (0-2 degrees) use _small inj_radius and frm2\n {\n inj_radius=inj_radius_small;\n frm2=frm2_small;\n frm0=frm0_small;\n }\n else\n {\n inj_radius=inj_radius_large;\n frm2=frm2_large;\n frm0=frm0_large;\n }\n printf(\"Thread %d: %0.1lf, %0.1lf \\n %d %e %d\\n\", omp_get_thread_num(), theta_jmin_thread*180/M_PI, theta_jmax_thread*180/M_PI, frm2, inj_radius, frm0 );\n\n //want to also have another set of threads that each has differing ranges of frame injections therefore do nested parallelism here so each thread can read its own checkpoint file\n //#pragma omp parallel num_threads(2) firstprivate(restrt)\n {\n char flash_file[200]=\"\";\n char log_file[200]=\"\";\n FILE *fPtr=NULL; //pointer to log file for each thread\n double *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL;\n double *phiPtr=NULL, *velzPtr=NULL, *zPtr=NULL;\n double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files\n int num_ph=0, array_num=0, ph_scatt_index=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter\n double dt_max=0, thescatt=0, accum_time=0; \n double gamma_infinity=0, time_now=0, time_step=0, avg_scatt=0; //gamma_infinity not used?\n double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0, ph_vzPtr=0;// *ph_cosanglePtr=NULL ;\n double min_r=0, max_r=0;\n int frame=0, scatt_frame=0, frame_scatt_cnt=0, scatt_framestart=0, framestart=0;\n struct photon *phPtr=NULL; //pointer to array of photons \n \n \n //if (omp_get_thread_num()==0)\n //{\n //printf( \"A:%d Im Thread: %d with ancestor %d working in %s\\n\", omp_get_num_threads(), omp_get_thread_num(), omp_get_ancestor_thread_num(1), mc_dir);\n //}\n \n if (restrt=='c')\n {\n printf(\">> mc.py: Reading checkpoint\\n\");\n //#pragma omp critical\n {\n readCheckpoint(mc_dir, &phPtr, frm0, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now);\n \n /*\n for (i=0;ip0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt );\n }\n */\n if (restrt=='c')\n {\n printf(\">> Thread %d with ancestor %d: Starting from photons injected at frame: %d out of %d\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1),framestart, frm2);\n printf(\">> Thread %d with ancestor %d: Continuing scattering %d photons from frame: %d\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1),num_ph, scatt_framestart);\n printf(\">> Thread %d with ancestor %d: The time now is: %e\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1),time_now);\n }\n else\n {\n printf(\">> Thread %d with ancestor %d: Continuing simulation by injecting photons at frame: %d out of %d\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1),framestart, frm2); //starting with new photon injection is same as restarting sim\n }\n }\n }\n else if (stat(mc_dir, &st) == -1)\n {\n mkdir(mc_dir, 0777); //make the directory with full permissions\n \n framestart=frm0; //if restarting then start from parameters given in mc.par file\n scatt_framestart=frm0;\n }\n else \n {\n //remove everything from MC directory to ensure no corruption of data if theres other files there besides the mc.par file\n //for a checkpoint implementation, need to find the latest checkpoint file and read it and not delete the files\n #pragma omp critical\n {\n printf(\">> Thread %d with ancestor %d: Cleaning directory \\n\",omp_get_thread_num(), omp_get_ancestor_thread_num(1));\n dirp = opendir(mc_dir);\n while ((entry = readdir(dirp)) != NULL) \n {\n if (entry->d_type == DT_REG) { /* If the entry is a regular file */\n file_count++; //count how many files are in dorectory\n }\n }\n printf(\"File count %d\\n\", file_count);\n \n if (file_count>0)\n {\n for (i=0;i<=last_frm;i++)\n {\n \n snprintf(mc_filename,sizeof(mc_filename),\"%s%s%d%s\", mc_dir,\"mcdata_\",i,\"_P0.dat\");\n if(( access( mc_filename, F_OK ) != -1 ) )\n {\n snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s%d%s\",\"exec rm \", mc_dir,\"mcdata_\",i,\"_*.dat\"); //prepares string to remove *.dat in mc_dir\n printf(\"%s\\n\",mc_operation);\n system(mc_operation);\n \n //snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s%d%s\",\"exec rm \", mc_dir,\"mcdata_\",i,\"_*\");\n //system(mc_operation);\n }\n }\n //snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s\",\"exec rm \", mc_dir,\"mcdata_PW_*.dat\"); //prepares string to remove *.dat in mc_dir\n //system(mc_operation);\n \n snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s\",\"exec rm \", mc_dir,\"mcdata_PW.dat\"); //prepares string to remove *.dat in mc_dir\n system(mc_operation);\n \n //snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s\",\"exec rm \", mc_dir,\"mc_chkpt_*.dat\"); //prepares string to remove *.dat in mc_dir\n //system(mc_operation);\n \n snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s\",\"exec rm \", mc_dir,\"mc_output_*.log\"); //prepares string to remove *.log in mc_dir\n system(mc_operation);\n \n }\n }\n framestart=frm0; //if restarting then start from parameters given in mc.par file\n scatt_framestart=frm0;\n \n }\n \n dt_max=1.0/fps;\n //#pragma omp barrier\n \n snprintf(log_file,sizeof(log_file),\"%s%s\",mc_dir,\"mc_output.log\" );\n printf(\"%s\\n\",log_file);\n fPtr=fopen(log_file, \"w\");\n \n fprintf(fPtr, \"%d Im Thread: %d with ancestor %d Starting on Frame: %d scatt_framestart: %d\\n\", omp_get_num_threads(), omp_get_thread_num(), omp_get_ancestor_thread_num(1), framestart, scatt_framestart);\n fflush(fPtr);\n //fclose(fPtr);\n //#pragma omp barrier\n //exit(0);\n //loop over frames \n //for a checkpoint implementation, start from the last saved \"frame\" value and go to the saved \"frm2\" value\n \n //#pragma omp for \n for (frame=framestart;frame<=frm2;frame++)\n {\n if (restrt=='r')\n {\n time_now=frame/fps; //for a checkpoint implmentation, load the saved \"time_now\" value when reading the ckeckpoint file otherwise calculate it normally\n }\n \n //printf(\">> mc.py: Working on Frame %d\\n\", frame);\n fprintf(fPtr,\"%d Im Thread: %d with ancestor %d Working on Frame: %d\\n\", omp_get_num_threads(), omp_get_thread_num(), omp_get_ancestor_thread_num(1), frame);\n fflush(fPtr);\n \n if (restrt=='r')\n {\n \n //exit(0);\n //read in FLASH file\n //for a checkpoint implmentation, dont need to read the file yet\n if (dim_switch==0)\n {\n //put proper number at the end of the flash file \n modifyFlashName(flash_file, flash_prefix, frame, dim_switch);\n fprintf(fPtr,\">> Im Thread: %d with ancestor %d: Opening FLASH file %s\\n\",omp_get_thread_num(), omp_get_ancestor_thread_num(1), flash_file);\n fflush(fPtr);\n \n #pragma omp critical\n {\n readAndDecimate(flash_file, inj_radius, fps, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fPtr);\n }\n }\n else\n {\n read_hydro(FILEPATH, frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 1, min_r, max_r, fps, fPtr);\n }\n \n //check for run type\n if(strcmp(cyl, this_run)==0)\n {\n //printf(\"In cylindrical prep\\n\");\n cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num);\n }\n else if (strcmp(sph, this_run)==0)\n {\n sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num );\n }\n \n //determine where to place photons and how many should go in a given place\n //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data \n fprintf(fPtr,\">> Thread: %d with ancestor %d: Injecting photons\\n\",omp_get_thread_num(), omp_get_ancestor_thread_num(1));\n fflush(fPtr);\n \n if (dim_switch==0)\n {\n photonInjection(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, szxPtr, szyPtr,rPtr,thetaPtr, tempPtr, velxPtr, velyPtr,rng[omp_get_thread_num()] ); \n }\n else\n {\n photonInjection3D(&phPtr, &num_ph, inj_radius, ph_weight_suggest, min_photons, max_photons,spect, array_num, fps, theta_jmin_thread, theta_jmax_thread, xPtr, yPtr, zPtr, szxPtr, szyPtr,rPtr,thetaPtr, phiPtr, tempPtr, velxPtr, velyPtr, velzPtr, rng[omp_get_thread_num()] ); \n }\n \n //printf(\"%d\\n\",num_ph); //num_ph is one more photon than i actually have\n /*\n for (i=0;ir0, (phPtr+i)->r1, (phPtr+i)->r2 );\n */\n }\n \n //scatter photons all the way thoughout the jet\n //for a checkpoint implmentation, start from the last saved \"scatt_frame\" value eh start_frame=frame or start_frame=cont_frame\n if (restrt=='r')\n {\n scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incrememnted by one the inner loop starts at that new value and not the one read by readCheckpoint()\n }\n \n for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame++)\n {\n fprintf(fPtr,\">>\\n\");\n fprintf(fPtr,\">> Thread %d with ancestor %d : Working on photons injected at frame: %d out of %d\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1),frame, frm2);\n fprintf(fPtr,\">> Thread %d with ancestor %d: %s - Working on frame %d\\n\",omp_get_thread_num(), omp_get_ancestor_thread_num(1), THISRUN, scatt_frame);\n fprintf(fPtr,\">> Thread %d with ancestor %d: Opening file...\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1));\n fflush(fPtr);\n \n \n \n \n if (dim_switch==0)\n {\n //put proper number at the end of the flash file\n modifyFlashName(flash_file, flash_prefix, scatt_frame, dim_switch);\n #pragma omp critical\n {\n phMinMax(phPtr, num_ph, &min_r, &max_r);\n readAndDecimate(flash_file, inj_radius, fps, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fPtr);\n }\n }\n else\n {\n phMinMax(phPtr, num_ph, &min_r, &max_r);\n \n read_hydro(FILEPATH, scatt_frame, inj_radius, &xPtr, &yPtr, &zPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &phiPtr, &velxPtr, &velyPtr, &velzPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num, 0, min_r, max_r, fps, fPtr);\n }\n \n //check for run type\n if(strcmp(cyl, this_run)==0)\n {\n //printf(\"In cylindrical prep\\n\");\n cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num);\n }\n else if (strcmp(sph, this_run)==0)\n {\n sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num );\n }\n //printf(\"The result of read and decimate are arrays with %d elements\\n\", array_num);\n \n fprintf(fPtr,\">> Thread %d with ancestor %d: propagating and scattering %d photons\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1),num_ph);\n fflush(fPtr);\n \n frame_scatt_cnt=0;\n while (time_now<((scatt_frame+1)/fps))\n {\n //if simulation time is less than the simulation time of the next frame, keep scattering in this frame\n //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path\n //and choose the photon with the smallest mfp and calculate the timestep\n \n ph_scatt_index=findNearestPropertiesAndMinMFP(phPtr, num_ph, array_num, &time_step, xPtr, yPtr, zPtr, velxPtr, velyPtr, velzPtr, dens_labPtr, tempPtr,\\\n &ph_dens_labPtr, &ph_vxPtr, &ph_vyPtr, &ph_vzPtr, &ph_tempPtr, rng[omp_get_thread_num()], dim_switch);\n \n //printf(\"In main: %e, %d, %e, %e\\n\", *(ph_num_scatt+ph_scatt_index), ph_scatt_index, time_step, time_now);\n printf(\"In main: %e, %d, %e, %e\\n\",((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now);\n \n if (time_stepnum_scatt)+=1;\n frame_scatt_cnt+=1;\n time_now+=time_step;\n \n updatePhotonPosition(phPtr, num_ph, time_step);\n \n //scatter the photon\n //printf(\"Passed Parameters: %e, %e, %e\\n\", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr));\n\n photonScatter( (phPtr+ph_scatt_index), (ph_vxPtr), (ph_vyPtr), ph_vzPtr, (ph_tempPtr), rng[omp_get_thread_num()] , dim_switch, fPtr);\n \n \n //if (frame_scatt_cnt%1000 == 0)\n {\n fprintf(fPtr,\"Scattering Number: %d\\n\", frame_scatt_cnt);\n fprintf(fPtr,\"The local temp is: %e\\n\", (ph_tempPtr));\n fprintf(fPtr,\"Average photon energy is: %e\\n\", averagePhotonEnergy(phPtr, num_ph)); //write function to average over the photons p0 and then do (*3e10/1.6e-9)\n fflush(fPtr);\n }\n \n }\n else\n {\n time_now+=dt_max;\n \n //for each photon update its position based on its momentum\n \n updatePhotonPosition(phPtr, num_ph, dt_max);\n }\n \n //printf(\"In main 2: %e, %d, %e, %e\\n\", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now);\n\n }\n \n //get scattering statistics\n phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt);\n \n fprintf(fPtr,\"The number of scatterings in this frame is: %d\\n\", frame_scatt_cnt);\n fprintf(fPtr,\"The last time step was: %lf.\\nThe time now is: %lf\\n\", time_step,time_now);\n fprintf(fPtr,\"The maximum number of scatterings for a photon is: %d\\nThe minimum number of scattering for a photon is: %d\\n\", max_scatt, min_scatt);\n fprintf(fPtr,\"The average number of scatterings thus far is: %lf\\n\", avg_scatt);\n fflush(fPtr);\n \n printPhotons(phPtr, num_ph, scatt_frame , frame, mc_dir);\n exit(0);\n //for a checkpoint implmentation,save the checkpoint file here after every 5 frames or something\n //save the photons data, the scattering number data, the scatt_frame value, and the frame value\n //WHAT IF THE PROGRAM STOPS AFTER THE LAST SCATT_FRAME, DURING THE FIRST SCATT_FRAME OF NEW FRAME VARIABLE - save restrt variable as 'r'\n fprintf(fPtr, \">> Thread %d with ancestor %d: Making checkpoint file\\n\", omp_get_thread_num(), omp_get_ancestor_thread_num(1));\n fflush(fPtr);\n saveCheckpoint(mc_dir, frame, scatt_frame, num_ph, time_now, phPtr, last_frm);\n \n free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr);\n free(gammaPtr);free(dens_labPtr);free(tempPtr);\n xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL;\n szxPtr=NULL; szyPtr=NULL; tempPtr=NULL;\n }\n restrt='r';//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file\n free(phPtr); \n phPtr=NULL;\n \n } \n \n \n }//end omp parallel inner section\n \n //merge files from each worker thread within a directory\n //dirFileMerge(mc_dir, frm0, last_frm);\n \n } //end omp parallel section\n \n //gsl_rng_free (rand);\n //free rand number generator\n for (j=0;j\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"MZC3D64.h\"\n#include \"MZC2D64.h\"\n#include \"sph_data_types.h\"\n#include \"sph_linked_list.h\"\n\n#define dbg false\n\nint safe_free_box(linkedListBox *box){\n\tkh_destroy(0, box->hbegin);\n\tkh_destroy(1, box->hend);\n\tfree(box);\n\n\treturn 0;\n}\n\nint compare_int64_t(const void *p,const void *q){\n\tint64_t *data1,*data2;\n\tdata1 = (int64_t*)p;\n\tdata2 = (int64_t*)q;\n\n\tif(data1[0] < data2[0]) // data[0] is the hash value, \n\t\treturn -1; // data[1] is the corresponding \n\telse if(data1[0] == data2[0]) // in the unsorted array\n\t\treturn 0;\n\telse\n\t\treturn 1;\n}\n\n#define safe_check_alloc(ptr,N,dtype) { \\\n (ptr) = (dtype*)malloc((N)*sizeof(dtype));\\\n if((ptr)==NULL){ \\\n success=0; \\\n goto finishlabel; \\\n } \\\n }\n\n#define safe_check__aligned_alloc(ptr,alignment,N,dtype) { \\\n (ptr) = (dtype*)aligned_alloc(alignment,(N)*sizeof(dtype));\\\n if((ptr)==NULL){ \\\n success=0; \\\n goto finishlabel; \\\n } \\\n }\n\n#define safe_free(ptr) { \\\n if(ptr != NULL)\\\n free(ptr); \\\n }\n\n/*\n * Function SPHparticle_SoA_malloc:\n * Easily allocate the SPHparticle array\n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particle struct reference\n */\nint SPHparticle_SoA_malloc(int N,SPHparticle **lsph){\n int success=1;\n //const int alignment = 32;\n (*lsph) = (SPHparticle*)malloc(1*sizeof(SPHparticle));\n if(lsph==NULL){\n success = 0;\n goto finishlabel;\n }\n (*lsph)->x = NULL; (*lsph)->y = NULL; (*lsph)->z = NULL;\n (*lsph)->ux = NULL; (*lsph)->uy = NULL; (*lsph)->uz = NULL;\n (*lsph)->Fx = NULL; (*lsph)->Fy = NULL; (*lsph)->Fz = NULL;\n (*lsph)->nu = NULL; (*lsph)->rho= NULL; \n (*lsph)->id = NULL; (*lsph)->hash= NULL; \n\n safe_check_alloc((*lsph)->x , N ,double);\n safe_check_alloc((*lsph)->y , N ,double);\n safe_check_alloc((*lsph)->z , N ,double);\n safe_check_alloc((*lsph)->ux , N ,double);\n safe_check_alloc((*lsph)->uy , N ,double);\n safe_check_alloc((*lsph)->uz , N ,double);\n safe_check_alloc((*lsph)->Fx , N ,double);\n safe_check_alloc((*lsph)->Fy , N ,double);\n safe_check_alloc((*lsph)->Fz , N ,double);\n safe_check_alloc((*lsph)->nu , N ,double);\n safe_check_alloc((*lsph)->rho , N ,double);\n safe_check_alloc((*lsph)->id , N ,int64_t);\n safe_check_alloc((*lsph)->hash,2*N,int64_t);\n\n // SPHparticle_SoA_malloc((*lsph)->x , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->y , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->z , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->ux , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->uy , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->uz , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->Fx , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->Fy , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->Fz , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->nu , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->rho , 32, N ,double);\n // SPHparticle_SoA_malloc((*lsph)->id , 32, N ,int64_t);\n // SPHparticle_SoA_malloc((*lsph)->hash, 32,2*N,int64_t);\n \n\nfinishlabel:\n\n if(success)\n return 0;\n else{\n if(*lsph==NULL)\n return 1;\n\n safe_free((*lsph)->x); safe_free((*lsph)->y); safe_free((*lsph)->z);\n safe_free((*lsph)->ux); safe_free((*lsph)->uy); safe_free((*lsph)->uz);\n safe_free((*lsph)->Fx); safe_free((*lsph)->Fy); safe_free((*lsph)->Fz);\n safe_free((*lsph)->nu); safe_free((*lsph)->rho); \n safe_free((*lsph)->id); safe_free((*lsph)->hash); \n\n return 1;\n }\n}\n\n\n/*\n * Function SPHparticleSOA_safe_free:\n * Easily free the SPHparticle array\n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particle struct reference\n */\nint SPHparticleSOA_safe_free(int N,SPHparticle **lsph){\n\t\n if(*lsph==NULL)\n return 1;\n\n safe_free((*lsph)->x); safe_free((*lsph)->y); safe_free((*lsph)->z);\n safe_free((*lsph)->ux); safe_free((*lsph)->uy); safe_free((*lsph)->uz);\n safe_free((*lsph)->Fx); safe_free((*lsph)->Fy); safe_free((*lsph)->Fz);\n safe_free((*lsph)->nu); safe_free((*lsph)->rho); \n safe_free((*lsph)->id); safe_free((*lsph)->hash); \n\n free((*lsph));\n\n return 0;\n}\n\n/*\n * Function gen_unif_rdn_pos:\n * Generate particles positions uniformely in a [0,1]^3 box\n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particles array\n * seed : seed for the PRNG\n */\nint gen_unif_rdn_pos(int64_t N, int seed, SPHparticle *lsph){\n\n\tconst gsl_rng_type *T=NULL;\n\tgsl_rng *r=NULL;\n\n\tif(lsph==NULL)\n\t\treturn 1;\n\n\tgsl_rng_env_setup(); // Initialize environment for PRNG generator\n\n\tT = gsl_rng_default; // Set generator type as default type\n\tr = gsl_rng_alloc(T); // allocate state for it\n\tgsl_rng_set(r,seed); // set seed accordingly\n\n\tfor(int64_t i=0;ix[i] = gsl_rng_uniform(r); // Generate a uniform value for X component between 0 and 1\n\t\tlsph->y[i] = gsl_rng_uniform(r); // Generate a uniform value for Y component between 0 and 1\n\t\tlsph->z[i] = gsl_rng_uniform(r); // Generate a uniform value for Z component between 0 and 1\n\n\t\tlsph->ux[i] = 0.0; lsph->Fx[i] = 0.0; // set velocity and force components as zero\n\t\tlsph->uy[i] = 0.0; lsph->Fy[i] = 0.0; // as they will not be needed\n lsph->uz[i] = 0.0; lsph->Fz[i] = 0.0;\n\n\t\tlsph->nu[i] = 1.0/N; // set each particle mass as to the total mass be 1\n\t\tlsph->rho[i] = 0.0; // initialize density to zero\n\t\tlsph->id[i] = (int64_t) i; // set the particle's id\n\t\tlsph->hash[2*i+0] = (int64_t) 0; // initialize particle's hash value as zero\n\t\tlsph->hash[2*i+1] = (int64_t) i; // set particle's index position by the position in current array\n\t}\n\n\tgsl_rng_free(r); // release the PRNG\n\n\treturn 0;\n}\n\n/*\n * Function gen_unif_rdn_pos_box:\n * Generate particles positions uniformely in a \n * [Xmin,Xmax]x[Ymin,Ymax]x[Zmin,Zmax] box\n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particles array\n * seed : seed for the PRNG\n * box : Cell Linked List box\n */\nint gen_unif_rdn_pos_box(int64_t N, int seed, linkedListBox *box,SPHparticle *lsph){\n\n const gsl_rng_type *T=NULL;\n gsl_rng *r=NULL;\n\n if(lsph==NULL)\n return 1;\n\n\tgsl_rng_env_setup(); // Initialize environment for PRNG generator\n\n\tT = gsl_rng_default; // Set generator type as default type\n\tr = gsl_rng_alloc(T); // allocate state for it\n\tgsl_rng_set(r,seed); // set seed accordingly\n\n for(int64_t i=0;ix[i] = gsl_rng_uniform(r)*(box->Xmax-box->Xmin) // Generate a uniform value for X \n + box->Xmin; // component between Xmin and Xmax\n lsph->y[i] = gsl_rng_uniform(r)*(box->Ymax-box->Ymin) // Generate a uniform value for Y\n + box->Ymin; // component between Ymin and Ymax\n lsph->z[i] = gsl_rng_uniform(r)*(box->Zmax-box->Zmin) // Generate a uniform value for Z \n + box->Zmin; // component between Zmin and Zmax\n\n\t\tlsph->ux[i] = 0.0; lsph->Fx[i] = 0.0; // set velocity and force components as zero\n\t\tlsph->uy[i] = 0.0; lsph->Fy[i] = 0.0; // as they will not be needed\n lsph->uz[i] = 0.0; lsph->Fz[i] = 0.0;\n\n\t\tlsph->nu[i] = 1.0/N; // set each particle mass as to the total mass be 1\n\t\tlsph->rho[i] = 0.0; // initialize density to zero\n\t\tlsph->id[i] = (int64_t) i; // set the particle's id\n\t\tlsph->hash[2*i+0] = (int64_t) 0; // initialize particle's hash value as zero\n\t\tlsph->hash[2*i+1] = (int64_t) i; // set particle's index position by the position in current array\n }\n\n gsl_rng_free(r);\n\n return 0;\n}\n\n/*\n * Function compute_hash_MC3D:\n * Compute the Morton Z hashes for all particles based on \n * the parameters given by the Cell Linked List box\n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particles array\n * box : Box of cell linked lists\n */\nint compute_hash_MC3D(int64_t N, SPHparticle *lsph, linkedListBox *box){\n\n\tif(lsph==NULL)\n\t\treturn 1;\n\n\tif(box==NULL)\n\t\treturn 1;\n\n\tconst double etax = box->Nx/(box->Xmax - box->Xmin);\n\tconst double etay = box->Ny/(box->Ymax - box->Ymin);\n\tconst double etaz = box->Nz/(box->Zmax - box->Zmin);\n\n\tfor(int64_t i=0;ix[i] - box->Xmin)); // Compute cell index in the X direction\n\t\tky = (uint32_t)(etay*(lsph->y[i] - box->Ymin)); // Compute cell index in the Y direction\n\t\tkz = (uint32_t)(etaz*(lsph->z[i] - box->Zmin)); // Compute cell index in the Z direction\n\n\t\tif((kx<0)||(ky<0)||(kz<0)) // The can't be negative indexes\n\t\t\treturn 1;\n\t\telse if((kx>=box->Nx)||(ky>=box->Nx)||(kz>=box->Nx)) // Nor indexes greater than the upper bounds\n\t\t\treturn 1;\n\t\telse{\n\t\t\tlsph->hash[2*i+0] = ullMC3Dencode(kx,ky,kz); // If ok, compute the corresponding Morton Z hash\n lsph->hash[2*i+1] = i;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\n/*\n * To swap two arrays, copy data from the original array into \n * a swap buffer in the right order, and then overrite the original array. \n */\n#define swap_loop(N,lsph,temp_swap,member,type) for(int64_t i=0;i<(N);i+=1) \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t (temp_swap)[i] = (lsph)->member[(lsph)->hash[2*i+1]];\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t memcpy((lsph)->member,temp_swap,(N)*sizeof(type))\n\n/*\n * Function reorder_lsph_SoA:\n * reorder the array according to the indexes reordered according to \n * their hashes. \n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particles array\n * swap_arr : buffer for reordering data in the array\n */\nint reorder_lsph_SoA(int N, SPHparticle *lsph, void *swap_arr){\n\n\tint64_t *int64_temp_swap = (int64_t *)swap_arr;\n\tswap_loop(N,lsph,int64_temp_swap,id ,int64_t);\n\tdouble *double_temp_swap = (double *)swap_arr;\n\tswap_loop(N,lsph,double_temp_swap,nu ,double);\n\tswap_loop(N,lsph,double_temp_swap,rho,double);\n\tswap_loop(N,lsph,double_temp_swap,x ,double);\n\tswap_loop(N,lsph,double_temp_swap,y ,double);\n\tswap_loop(N,lsph,double_temp_swap,z ,double);\n\tswap_loop(N,lsph,double_temp_swap,ux ,double);\n\tswap_loop(N,lsph,double_temp_swap,uy ,double);\n\tswap_loop(N,lsph,double_temp_swap,uz ,double);\n\tswap_loop(N,lsph,double_temp_swap,Fx ,double);\n\tswap_loop(N,lsph,double_temp_swap,Fy ,double);\n\tswap_loop(N,lsph,double_temp_swap,Fz ,double);\n\n\treturn 0;\n}\n\n/*\n * Function setup_interval_hashtables:\n * Setup the information where each cell begins and ends in the SPH\n * Array in a pair of hash tables for quick consultation. \n * This effectively completes the creation of the implicit \n * cell linked list structure initiated by sorting the array \n * according to hashes. \n * \n * Arguments:\n * N : Number of Particles\n * lsph : SoA Particles array\n * box : Box of cell linked lists\n */\nint setup_interval_hashtables(int64_t N,SPHparticle *lsph,linkedListBox *box){\n\n\tint ret;\n\tint64_t hash0 = lsph->hash[2*0]; // Store the first hash in hash0\n\tkhiter_t kbegin,kend;\n\n\tif(lsph==NULL)\n\t\treturn 1;\n\n\tif(box==NULL)\n\t\treturn 1;\n\n\tkbegin = kh_put(0, box->hbegin, lsph->hash[2*0], &ret); // Insert start hash as first value\n\tkh_value(box->hbegin, kbegin) = (int64_t)0; // Set the start index of first cell as 0\n\tfor(int64_t i=0;ihash[i] = lsph->hash[2*i]; // Clean the first half of the array only to contain hashes\n\t\tif(lsph->hash[i] == hash0) // If the the particle hash is the same as the previous\n\t\t\tcontinue; // skip because they are in the same cell\n\t\thash0 = lsph->hash[i]; // otherwise, store the new hash in hash0\n\t\t\n\t\tkend = kh_put(1, box->hend , lsph->hash[i-1], &ret); // If so, insert the previous hash as an cell end\n\t\tkh_value(box->hend , kend) = i; // and set this index as the upper index of that cell\n\t\t\n\t\tkbegin = kh_put(0, box->hbegin, lsph->hash[i ], &ret); // and then insert this new hash as the begining\n\t\tkh_value(box->hbegin, kbegin) = i; // of a new cell in with the lower index as this index\n\t}\n\tkend = kh_put(1, box->hend , lsph->hash[2*(N-1)], &ret); // finally set the last hash for the end of the last cell,\n\tkh_value(box->hend , kend) = N; // and the number of particles as the index of the last cell\n\n\treturn 0;\n}\n\n/*\n * Function neighbour_hash_3d:\n * Find the hashes of all valid cells that neighbor cell with\n * int hash. \n * \n * Arguments:\n * hash : Hash of the central cell \n * nblist : Array for hashes of the neighbor cells\n * width : Width of the neighborhood \n * box : Box of cell linked lists\n */\nint neighbour_hash_3d(int64_t hash,int64_t *nblist,int width, linkedListBox *box){\n\tint idx=0,kx=0,ky=0,kz=0;\n\n\tkx = ullMC3DdecodeX(hash); // To find a given cell's neighbors, start by first \n\tky = ullMC3DdecodeY(hash); // recovering the integer index of that cell in \n\tkz = ullMC3DdecodeZ(hash); // the overall box domain\n\n\tfor(int ix=-width;ix<=width;ix+=1){ // iterate over all cells surrounding the original cell\n\t\tfor(int iy=-width;iy<=width;iy+=1){ // as long as they are within width of the original cell\n\t\t\tfor(int iz=-width;iz<=width;iz+=1){ \n\t\t\t\tif((kx+ix<0)||(ky+iy<0)||(kz+iz<0)) // if the cell is off bounds for having lower index then 0\n\t\t\t\t\tnblist[idx++] = -1; // annotate the cell as invalid\n\t\t\t\telse if( (kx+ix>=box->Nx)||(ky+iy>=box->Ny)||(kz+iz>=box->Nz) ) // or if it is off bounds for having higher index then\n\t\t\t\t\tnblist[idx++] = -1; // the maximum, also annotate as invalid\n\t\t\t\telse if( kh_get(0, box->hbegin, ullMC3Dencode(kx+ix,ky+iy,kz+iz)) == kh_end(box->hbegin) ) // Also, if no corresponding hash\n\t\t\t\t\tnblist[idx++] = -1; // is not found in the hash table, also annotate as invalid\n\t\t\t\telse // at last, if it has no problems\n\t\t\t\t\tnblist[idx++] = ullMC3Dencode(kx+ix,ky+iy,kz+iz); // annotate the hash of the corresponding cell\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\n/*\n * Function count_box_pairs:\n * Count the number of valid cell pairs\n * \n * Arguments:\n * box : Box of cell linked lists\n */\nint count_box_pairs(linkedListBox *box){\n int64_t pair_count = 0; // initialize the number of pairs as zero\n\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // iterate over the cells\n int64_t node_hash=-1; \n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // check if the cell is valid\n node_hash = kh_key(box->hbegin, kbegin); // get the hash of that cell\n \n neighbour_hash_3d(node_hash,nblist,box->width,box); // fetch the list of neighbors\n for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and iterate over those neighbors\n if(nblist[j]>=0){ // if the neighbor is valid\n pair_count += 1; // count it as a valid for a pair\n }\n }\n }\n }\n\n return pair_count;\n}\n\n/*\n * Function setup_box_pairs:\n * Pre-compute indexes for all valid cell pairs. \n * \n * Arguments:\n * box : Box of cell linked lists\n * Returns:\n * node_begin : Array for receiver cell begin indexes\n * node_end : Array for receiver cell end indexes\n * nb_begin : Array for sender cell begin indexes\n * nb_end : Array for sender cell end indexes\n */\nint setup_box_pairs(linkedListBox *box,\n int64_t *node_begin,int64_t *node_end,\n int64_t *nb_begin,int64_t *nb_end)\n{\n int64_t pair_count = 0,particle_pair_count = 0;\n\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // iterate over the cells\n int64_t node_hash=-1;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // check if the cell is valid\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // get the iterator for the end index\n\n node_hash = kh_key(box->hbegin, kbegin); // and also get the corresponding hash\n\n neighbour_hash_3d(node_hash,nblist,box->width,box); // fetch the list of neighbors\n for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and iterate over those neighbors\n if(nblist[j]>=0){ // check if the neighbor is valid\n node_begin[pair_count] = kh_value(box->hbegin, kbegin); // get the cell's begin index\n node_end[pair_count] = kh_value(box->hend, kend); // get the cell's end index\n nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // get the neighbor's begin index\n nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // get the neighbor's end index\n\n particle_pair_count += (nb_end[pair_count]-nb_begin[pair_count])* // just for bookeeping/profiling, \n (node_end[pair_count]-node_begin[pair_count]); // annotate the number of particle pairs\n pair_count += 1; // that are part of the computation\n }\n }\n }\n }\n\n if(dbg)\n printf(\"particle_pair_count = %ld\\n\",particle_pair_count);\n\n return pair_count;\n}\n\n/*\n * Function setup_unique_box_pairs:\n * Pre-compute indexes for all valid unique cell pairs. \n * by unique means that if [node_begin,node_end)x[nb_begin,nb_end)\n * is in the list, [nb_begin,nb_end)x[node_begin,node_end) is not. \n * \n * Arguments:\n * box : Box of cell linked lists\n * Returns:\n * node_begin : Array for receiver cell begin indexes\n * node_end : Array for receiver cell end indexes\n * nb_begin : Array for sender cell begin indexes\n * nb_end : Array for sender cell end indexes\n */\nint setup_unique_box_pairs(linkedListBox *box,\n int64_t *node_begin,int64_t *node_end,\n int64_t *nb_begin,int64_t *nb_end)\n{\n int64_t pair_count = 0, particle_pair_count = 0;\n\n for (khint32_t kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // iterate over the cells\n int64_t node_hash=-1;\n int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)];\n\n if (kh_exist(box->hbegin, kbegin)){ // check if the cell is valid\n khint32_t kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // get the iterator for the end index\n\n node_hash = kh_key(box->hbegin, kbegin); // and also get the corresponding hash\n\n neighbour_hash_3d(node_hash,nblist,box->width,box); // fetch the list of neighbors\n for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and iterate over those neighbors\n if(nblist[j]>=0){ // check if the neighbor is valid\n if(kh_value(box->hbegin, kbegin) <= // and if the node_index is smaller\n kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) )) // then the neighbor index\n {\n node_begin[pair_count] = kh_value(box->hbegin, kbegin); // get the cell's begin index\n node_end[pair_count] = kh_value(box->hend, kend); // get the cell's end index\n nb_begin[pair_count] = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // get the neighbor's begin index\n nb_end[pair_count] = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // get the neighbor's end index\n\n particle_pair_count += (nb_end[pair_count]-nb_begin[pair_count])* // just for bookeeping/profiling, \n (node_end[pair_count]-node_begin[pair_count]); // annotate the number of particle pairs\n pair_count += 1; // that are part of the computation\n }\n }\n }\n }\n }\n\n if(dbg)\n printf(\"particle_pair_count = %ld\\n\",particle_pair_count);\n\n return pair_count;\n}\n\n/*\n * Function print_sph_particles_density:\n * Write in disk the density values for the computed SPH particles. \n * \n * Arguments:\n * prefix : prefix for the file name \n * is_cll : boolean defined naive or cell linked list case\n * N : Number of SPH particles\n * h : smoothing length \n * seed : seed utilized for the PRNG\n * runs : Number of runs executed\n * lsph : Array of SPH particles\n * box : Box of cell linked lists\n * Returns:\n * 0 : Error code\n * fp : Written file with particle densities\n */\nint print_sph_particles_density(const char *prefix, bool is_cll, int64_t N, double h, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlong int seed, int runs, SPHparticle *lsph, linkedListBox *box){\n\tFILE *fp;\n\tchar filename[2048+1];\n\n\tif(is_cll){\n\t\tsprintf(filename,\n\t\t\t\t\t\t\"data/cd3d(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv\",\n\t\t\t\t\t\tprefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax);\n\n\t\tfp = fopen(filename,\"w\");\n\t\tfprintf(fp,\"id,x,y,z,rho\\n\");\n\t\tfor(int64_t i=0;iid[i],lsph->x[i],lsph->y[i],lsph->z[i],lsph->rho[i]);\n\t\tfclose(fp);\n\t} \n\telse{\n\t\tsprintf(filename,\n\t\t\t\t\t\t\"data/cd3d(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv\",\n\t\t\t\t\t\tprefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax);\n\n\t\tfp = fopen(filename,\"w\");\n\t\tfprintf(fp,\"id,x,y,z,rho\\n\");\n\t\tfor(int64_t i=0;iid[i],lsph->x[i],lsph->y[i],lsph->z[i],lsph->rho[i]);\n\t\tfclose(fp);\n\t}\n\t\n\n\treturn 0;\n}\n\n/*\n * Function print_sph_particles_density:\n * Write in disk the density values for the computed SPH particles. \n * \n * Arguments:\n * prefix : prefix for the file name \n * is_cll : boolean defined naive or cell linked list case\n * N : Number of SPH particles\n * h : smoothing length \n * seed : seed utilized for the PRNG\n * runs : Number of runs executed\n * lsph : Array of SPH particles\n * box : Box of cell linked lists\n * times : timings for each of the processing steps\n * Returns:\n * 0 : Error code\n * fp : Written file with particle densities\n */\nint print_time_stats(const char *prefix, bool is_cll, int64_t N, double h, \n\t\t\t\t\t\t\t\t\t\t long int seed, int runs, SPHparticle *lsph, linkedListBox *box,double *times){\n FILE *fp;\n\tchar filename[1024+1];\n\n\tif(is_cll){\n const int COMPUTE_BLOCKS = 5;\n double t[COMPUTE_BLOCKS], dt[COMPUTE_BLOCKS], total_time, dtotal_time;\n \tsprintf(filename,\n\t\t\t\t\t\t\"data/times-(%s,runs=%d)-P(seed=%ld,N=%ld,h=%lg)-B(Nx=%d,Ny=%d,Nz=%d)-D(%lg,%lg,%lg,%lg,%lg,%lg).csv\",\n\t\t\t\t\t\tprefix,runs,seed,N,h,box->Nx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax);\n\n \tfp = fopen(filename,\"w\");\n\t\tfprintf(fp,\"id,compute_hash_MC3D,sorting,reorder_lsph_SoA,setup_interval_hashtables,compute_density\\n\");\n\t\tfor(int run=0;runNx,box->Ny,box->Nz,box->Xmin,box->Ymin,box->Zmin,box->Xmax,box->Ymax,box->Zmax);\n\n \tfp = fopen(filename,\"w\");\n\t\tfprintf(fp,\"id,compute_density\\n\");\n\t\tfor(int run=0;run\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tdsearch_gridsearch.h\"\n#ifdef TDSEARCH_USE_INTEL\n#include \n#else\n#include \n#endif \n#include \"tdsearch_greens.h\"\n#include \"sacio.h\"\n#include \"parmt_utils.h\"\n#include \"iscl/array/array.h\"\n#include \"iscl/memory/memory.h\"\n#include \"iscl/os/os.h\"\n#include \"iscl/signal/convolve.h\"\n\n#define NTSTAR 12 /*!< Default number of t*'s in the grid search. */\n#define TSTAR0 0.1 /*!< Default first t* in grid search. */\n#define TSTAR1 1.2 /*!< Default last t* in grid search. */\n#define NDEPTH 12 /*!< Default number of depths in grid search. */\n#define DEPTH0 0.0 /*!< First depth in grid search (km). */\n#define DEPTH1 3.0 /*!< Last depth in grid search (km). */\n#define DOUBLE_PAGE_SIZE sysconf(_SC_PAGE_SIZE)/sizeof(double)\n#define PAGE_SIZE sysconf(_SC_PAGE_SIZE)\n#define LDG 6\n\n/*!\n * @brief Sets the default grid search parameters.\n *\n * @param[out] tds On exit contains the default grid search settings such\n * as the t* range, depth range, and toggles off the max\n * time shift.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_setDefaults(struct tdSearch_struct *tds)\n{\n int ierr;\n memset(tds, 0, sizeof(struct tdSearch_struct));\n tds->maxShiftTime = DBL_MAX;\n ierr = tdsearch_gridSearch_defineTstarGrid(NTSTAR, TSTAR0, TSTAR1, tds);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to set t* grid\\n\", __func__);\n return -1;\n } \n ierr = tdsearch_gridSearch_defineDepthGrid(NDEPTH, DEPTH0, DEPTH1, tds);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to set depth grid\\n\", __func__);\n return -1;\n }\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Frees memory on the grid-search structure.\n *\n * @param[out] tds On exit all memory has been freed and parameters set to\n * 0 or NULL.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_free(struct tdSearch_struct *tds)\n{\n memory_free64f(&tds->G);\n memory_free64f(&tds->Gxc);\n memory_free64f(&tds->tstar);\n memory_free64f(&tds->depths);\n memory_free64f(&tds->synthetic);\n memory_free64f(&tds->xcorr);\n memory_free32i(&tds->lags);\n memory_free32i(&tds->grnsMatrixPtr);\n memory_free32i(&tds->grnsXCMatrixPtr);\n memset(tds, 0, sizeof(struct tdSearch_struct));\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Defines the t* grid in grid search. \n *\n * @param[in] ntstars Number of t*'s in grid search (> 0).\n * @param[in] tstar0 First t* in grid search (>= 0).\n * @param[in] tstar1 Final t* in grid search (>= tstar0).\n *\n * @param[out] tds Grid search structure with t* grid.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_defineTstarGrid(const int ntstars, const double tstar0,\n const double tstar1,\n struct tdSearch_struct *tds)\n{\n int ierr;\n tds->ntstar = 0;\n if (ntstars < 1 || tstar0 < 0.0 || tstar0 > tstar1)\n {\n if (ntstars < 1)\n {\n fprintf(stderr, \"%s: Error no t*'s %d in search\\n\", __func__, ntstars);\n }\n if (tstar0 < 0.0)\n {\n fprintf(stderr, \"%s: Error tstar0 %f must be non-negative\\n\",\n __func__, tstar0);\n }\n if (tstar0 > tstar1)\n {\n fprintf(stderr, \"%s: Error tstar0 %f > tstar1 %f\\n\",\n __func__, tstar0, tstar1);\n }\n return -1;\n }\n tds->ntstar = ntstars;\n memory_free64f(&tds->tstar);\n tds->tstar = array_linspace64f(tstar0, tstar1, ntstars, &ierr);\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Defines the depth grid in grid search. \n *\n * @param[in] ndepths Number of depths in grid search (> 0).\n * @param[in] depth0 First depth (km) in grid search (>= 0).\n * @param[in] depth1 Final depth (km) in grid search (>= depth0).\n *\n * @param[out] tds Grid search structure with depth grid.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_defineDepthGrid(const int ndepths, const double depth0,\n const double depth1,\n struct tdSearch_struct *tds)\n{\n int ierr;\n tds->ndepth = 0;\n if (ndepths < 1 || depth0 < 0.0 || depth0 > depth1)\n { \n if (ndepths < 1)\n {\n fprintf(stderr, \"%s: Error no depthss %d in search\\n\",\n __func__, ndepths);\n }\n if (depth0 < 0.0)\n {\n fprintf(stderr, \"%s: Error depth0 %f must be non-negative\\n\",\n __func__, depth0);\n }\n if (depth0 > depth1)\n {\n fprintf(stderr, \"%s: Error depth0 %f > depth1 %f\\n\",\n __func__, depth0, depth1);\n }\n return -1; \n }\n tds->ndepth = ndepths;\n memory_free64f(&tds->depths);\n tds->depths = array_linspace64f(depth0, depth1, ndepths, &ierr);\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Reads the grid search parameters from the ini file.\n *\n * @param[in] iniFile Name of ini file with parameters.\n *\n * @param[out] tds On successful exit contains the grid search parameters.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_initializeFromFile(const char *iniFile,\n struct tdSearch_struct *tds)\n{\n double depth0, depth1, tstar0, tstar1;\n dictionary *ini;\n int ierr, ndepth, ntstar;\n // Set the defaults\n ierr = 0;\n tdsearch_gridSearch_setDefaults(tds);\n // Verify the file exists\n if (!os_path_isfile(iniFile))\n { \n fprintf(stderr, \"%s: Error ini file %s doesn't exist\\n\", __func__, iniFile);\n return -1; \n } \n ini = iniparser_load(iniFile);\n // Unpack the parameter file\n tds->maxShiftTime\n = iniparser_getdouble(ini, \"tdSearch:gridSearch:maxShiftTime\\0\", DBL_MAX);\n if (tds->maxShiftTime < DBL_MAX)\n {\n if (tds->maxShiftTime <= 0.0)\n {\n fprintf(stderr, \"%s: Max shift time must be positive\\n\", __func__);\n ierr = 1;\n goto ERROR;\n }\n }\n // Number of t*'s\n ntstar = iniparser_getint(ini, \"tdSearch:gridSearch:ntstar\\0\", NTSTAR);\n if (ntstar < 1)\n {\n fprintf(stderr, \"%s: number of t*'s must be positive\\n\", __func__);\n ierr = 1;\n goto ERROR;\n }\n // Number of depths\n ndepth = iniparser_getint(ini, \"tdSearch:gridSearch:ndepths\\0\", NDEPTH);\n if (ndepth < 1)\n {\n fprintf(stderr, \"%s: number of depths must be positive\\n\", __func__);\n ierr = 1;\n goto ERROR;\n }\n // Depth grid search range\n depth0 = iniparser_getdouble(ini, \"tdSearch:gridSearch:depth0\\0\", DEPTH0);\n depth1 = iniparser_getdouble(ini, \"tdSearch:gridSearch:depth1\\0\", DEPTH1);\n if (depth0 >= depth1)\n {\n fprintf(stderr, \"%s: depth0 >= depth1 is invalid\\n\", __func__);\n ierr = 1;\n goto ERROR;\n }\n // t* grid search range\n tstar0 = iniparser_getdouble(ini, \"tdSearch:gridSearch:tstar0\\0\", TSTAR0);\n tstar1 = iniparser_getdouble(ini, \"tdSearch:gridSearch:tstar1\\0\", TSTAR1);\n if (tstar0 >= tstar1)\n {\n fprintf(stderr, \"%s: tstar0 >= tstar1 is invalid\\n\", __func__);\n ierr = 1;\n goto ERROR;\n }\n // Create the grid\n ierr = tdsearch_gridSearch_defineTstarGrid(ntstar,\n tstar0, tstar1,\n tds);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error defining t* grid\\n\", __func__);\n goto ERROR;\n }\n ierr = tdsearch_gridSearch_defineDepthGrid(ndepth,\n depth0, depth1,\n tds);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error defining depth grid\\n\", __func__);\n goto ERROR; \n }\nERROR:;\n iniparser_freedict(ini);\n return ierr;\n}\n//============================================================================//\n/*!\n * @brief Returns the number of depths in the grid search. \n *\n * @param[in] tds Holds the number of t*'s.\n *\n * @result The number of t*'s in the grid search.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_getNumberOfTstars(const struct tdSearch_struct tds)\n{\n return tds.ntstar;\n}\n//============================================================================//\n/*!\n * @brief Returns the number of depths in the grid search.\n *\n * @param[in] tds Holds the number of depths.\n *\n * @result The number of depths in the grid search.\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_getNumberOfDepths(const struct tdSearch_struct tds)\n{\n return tds.ndepth;\n}\n//============================================================================//\n/*!\n * @brief Convenience utility for computing the index corresponding to the \n * 2D row major depth x t* grid.\n *\n * @param[in] it The t* index [0,ntstar-1].\n * @param[in] id The depth indx [0,ndepth-1].\n * @param[in] ntstar The number of t*'s in the grid search.\n *\n * @result The grid search index (= id*ntstar + it).\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_gridToIndex2(const int it, const int id,\n const int ntstar)\n{\n int idt;\n idt = id*ntstar + it;\n return idt;\n}\n//============================================================================//\n/*!\n * @brief Convenience utility for computing the index corresponding to the \n * 2D row major depth x t* grid.\n *\n * @param[in] it The t* index [0,ntstar-1].\n * @param[in] id The depth indx [0,ndepth-1].\n * @param[in] tds Grid search structure holding the number of ntstar's\n * in the grid search.\n *\n * @result The grid search index (= id*tds.ntstar + it).\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_gridToIndex(const int it, const int id,\n const struct tdSearch_struct tds)\n{\n int idt, ntstar;\n ntstar = tdsearch_gridSearch_getNumberOfTstars(tds);\n idt = tdsearch_gridSearch_gridToIndex2(it, id, ntstar);\n return idt;\n}\n//============================================================================//\n/*!\n * @brief Computes the forward modeling matrix, G, so that estimates, e, can\n * can be efficiently generated via \\f$ G m = e \\f$ for any moment\n * tensor, m. The columns of G represent cross-correlations of the\n * Green's functions corresponding to the \\f$ m_{ij} \\f$ moment tensor\n * component so that the estimate, e, is a cross-correlogram.\n *\n * @param[in] iobs Observation index in the range [0,nobs-1].\n * @param[in] data Structure containing the data.\n * @param[in] grns Structure containing the Green's functions.\n *\n * @param[in,out] tds On input contains the initialized tds structure.\n * @param[in,out] tds On exit the forward modeling matrix G has been set.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdsearch_gridSearch_setForwardModelingMatrices(\n const int iobs, \n const struct tdSearchData_struct data,\n const struct tdSearchGreens_struct grns,\n struct tdSearch_struct *tds)\n{\n double *G, *Gxc, *work;\n int *grnsMatrixPtr, *grnsXCMatrixPtr, indices[6],\n i, idep, idt, ierr, indx, it, jndx, kndx,\n lxc, lxcMax, lxc0, ntstar, ndepth, npgrns, npts;\n // Reset pointers\n memory_free64f(&tds->G);\n memory_free64f(&tds->Gxc); \n memory_free32i(&tds->grnsMatrixPtr);\n memory_free32i(&tds->grnsXCMatrixPtr);\n // Check sizes\n ndepth = grns.ndepth;\n ntstar = grns.ntstar;\n if (ndepth != tds->ndepth || ntstar != tds->ntstar)\n {\n if (ndepth != tds->ndepth)\n {\n fprintf(stderr, \"%s: Error ndepth %d != tds->ndepth %d\\n\",\n __func__, ndepth, tds->ndepth);\n }\n if (ntstar != tds->ntstar)\n {\n fprintf(stderr, \"%s: Error ntstar %d != tds->ntstar %d\\n\",\n __func__, ntstar, tds->ntstar);\n }\n return -1;\n }\n npts = data.obs[iobs].npts;\n if (npts < 1)\n {\n fprintf(stderr, \"%s: Error data has no points\\n\", __func__);\n return -1;\n }\n tds->dnorm = cblas_dnrm2(npts, data.obs[iobs].data, 1);\n if (fabs(tds->dnorm) < DBL_EPSILON)\n {\n fprintf(stderr, \"%s: Error - data is identically zero\\n\", __func__);\n return -1;\n } \n tds->npts = npts;\n sacio_getFloatHeader(SAC_FLOAT_DELTA, data.obs[iobs].header, &tds->dt);\n // Set the Green's functions forward modeling matrix size\n lxcMax = 0;\n grnsMatrixPtr = memory_calloc32i(ndepth*ntstar+1);\n grnsXCMatrixPtr = memory_calloc32i(ndepth*ntstar+1);\n grnsMatrixPtr[0] = 0;\n grnsXCMatrixPtr[0] = 0;\n for (idep=0; idepnptsGrns = grnsMatrixPtr[ndepth*ntstar];\n G = memory_calloc64f(LDG*grnsMatrixPtr[ndepth*ntstar]);\n Gxc = memory_calloc64f(LDG*grnsXCMatrixPtr[ndepth*ntstar]);\n work = memory_calloc64f(lxcMax);\n for (idep=0; idepG = G;\n tds->Gxc = Gxc;\n tds->grnsMatrixPtr = grnsMatrixPtr;\n tds->grnsXCMatrixPtr = grnsXCMatrixPtr;\n memory_free64f(&work);\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Sets the moment tensor on the tdSearch structure.\n *\n * @param[in] m6 moment tensor in NED system packed: \n * \\f$ \\{ m_{xx}, m_{yy}, m_{zz}, \n * m_{xy}, m_{xz}, m_{yz} \\} \\f$.\n *\n * @param[out] tds On successful exit contains the moment tensor.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n * @author Ben Baker, ISTI\n *\n */\nint tdSearch_gridSearch_setMomentTensor(const double *__restrict__ m6,\n struct tdSearch_struct *tds)\n{\n tds->lhaveMT = false;\n array_zeros64f_work(8, tds->mt); // NOTE - this is padded\n if (m6 == NULL)\n {\n fprintf(stderr, \"%s: Error moment tensor cannot be NULL\\n\", __func__);\n return -1;\n }\n array_copy64f_work(6, m6, tds->mt);\n tds->lhaveMT = true;\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Sets the moment tensor elements on the grid search structure.\n *\n * @param[in] m11 m11 moment tensor in Newton meters.\n * @param[in] m22 m22 moment tensor in Newton meters.\n * @param[in] m33 m33 moment tensor in Newton meters.\n * @param[in] m12 m12 moment tensor in Newton meters.\n * @param[in] m13 m13 moment tensor in Newton meters.\n * @param[in] m23 m23 moment tensor in Newton meters.\n * @param[in] basis The appropriate moment tensor basis.\n * @param[in] basis CE_USE indicates the moment tensor is in up, south\n * east coordinates like what one would obtain from\n * the GCMT catalog.\n * @param[in] basis CE_NED indicates the moment tensor is in north, east,\n * down coordinates and is consistent with Programs in\n * Seismology.\n *\n * @param[in,out] tds On input contains the initialized grid search \n * structure.\n * @param[in,out] tds On exit contains the input moment tensor.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n */\nint tdSearch_gridSearch_setMomentTensorFromElements(\n const double m11, const double m22, const double m33,\n const double m12, const double m13, const double m23,\n const enum compearthCoordSystem_enum basis,\n struct tdSearch_struct *tds)\n{\n double mt[6], mtNED[6];\n int ierr;\n tds->lhaveMT = false;\n mt[0] = m11;\n mt[1] = m22;\n mt[2] = m33;\n mt[3] = m12;\n mt[4] = m13;\n mt[5] = m23;\n ierr = compearth_convertMT(1, basis, CE_NED, mt, mtNED);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set moment tensor\\n\", __func__);\n return -1;\n }\n ierr = tdSearch_gridSearch_setMomentTensor(mtNED, tds);\n if (ierr != 0)\n {\n printf(\"%s: Failed to set moment tensor\\n\", __func__);\n return -1;\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Sets the moment tensor information from an event structure.\n *\n * @param[in] event Contains the event on which the moment tensor is defined.\n * @param[in,out] tds On input this is the initialized grid search structure.\n * @param[in,out] tds On exit contains the given moment tensor.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n */\nint tdSearch_gridSearch_setMomentTensorFromEvent(\n const struct tdSearchEventParms_struct event,\n struct tdSearch_struct *tds)\n{\n int ierr;\n ierr = tdSearch_gridSearch_setMomentTensorFromElements(\n event.m11, event.m22, event.m33,\n event.m12, event.m13, event.m23,\n event.basis, tds);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Error setting moment tensor\\n\", __func__);\n return -1;\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Computes the cross-correlations between the data and synthetics\n * at each (t*,depth) in the grid search.\n *\n * @param[in,out] tds On input contains the initialized grid search \n * structure with the Green's functions and source\n * properties.\n * @param[in,out] tds On exit contains the result of the cross-correlations\n * and lags at each (t*,depth) in the grid search.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n */\nint tdSearch_gridSearch_performGridSearch(struct tdSearch_struct *tds)\n{\n double *u, *ud, dnorm, unorm;\n int id, idt, indx, iopt, it, jndx, l1, l2, lxc, maxlags,\n ndepth, ndt, nlag, npgrns, nrows, ntstar;\n const int ncols = 6;\n enum isclError_enum ierr;\n tds->itopt =-1;\n tds->idopt =-1;\n ndepth = tds->ndepth;\n ntstar = tds->ntstar;\n ndt = ntstar*ndepth;\n dnorm = tds->dnorm;\n memory_free64f(&tds->xcorr);\n memory_free64f(&tds->synthetic);\n memory_free32i(&tds->lags);\n // Some easy checks\n if (!tds->lhaveMT)\n {\n fprintf(stderr, \"%s: Error moment tensor not set\\n\", __func__);\n return -1;\n }\n if (tds->G == NULL || tds->Gxc == NULL ||\n tds->grnsMatrixPtr == NULL || tds->grnsXCMatrixPtr == NULL)\n {\n fprintf(stderr, \"%s: You need to set the forward modeling matrices\\n\", __func__);\n return -1;\n }\n maxlags =-1;\n if (tds->maxShiftTime < DBL_MAX)\n {\n maxlags = (int) (tds->maxShiftTime/tds->dt + 0.5);\n }\n // Set output space\n tds->xcorr = memory_calloc64f(ndt);\n tds->lags = memory_calloc32i(ndt);\n // Compute the cross-correlation\n nrows = tds->grnsXCMatrixPtr[ndt];\n ud = memory_calloc64f(nrows);\n cblas_dgemv(CblasRowMajor, CblasNoTrans,\n nrows, ncols, 1.0, tds->Gxc, LDG,\n tds->mt, 1, 0.0, ud, 1);\n // Compute the synthetics\n nrows = tds->grnsMatrixPtr[ndt]; \n u = memory_calloc64f(nrows);\n cblas_dgemv(CblasRowMajor, CblasNoTrans,\n nrows, ncols, 1.0, tds->G, LDG,\n tds->mt, 1, 0.0, u, 1);\n // Now do the grid search\n for (id=0; idgrnsMatrixPtr[idt];\n jndx = tds->grnsXCMatrixPtr[idt];\n lxc = tds->grnsXCMatrixPtr[idt+1]\n - tds->grnsXCMatrixPtr[idt];\n npgrns = tds->grnsMatrixPtr[idt+1]\n - tds->grnsMatrixPtr[idt];\n unorm = cblas_dnrm2(npgrns, &u[indx], 1);\n if (maxlags < 0)\n {\n iopt = array_argmax64f(lxc, &ud[jndx], &ierr);\n }\n else\n {\n l1 = MAX(0, npgrns - maxlags);\n l2 = MIN(lxc-1, npgrns + maxlags);\n nlag = l2 - l1 + 1;\n iopt = l1 + array_argmax64f(nlag, &ud[jndx+l1], &ierr);\n /*\nfor (int k=0; kxcorr[idt] = ud[jndx+iopt]/(dnorm*unorm);\n // Compute the lag where the times range from [-npts+1:npgrns-1]\n tds->lags[idt] =-npgrns + 1 + iopt;\n //printf(\"%f %f %f %d\\n\", tds->depths[id], tds->tstar[it], xc, idelay);\n }\n //printf(\"\\n\");\n }\n tds->synthetic = u;\n memory_free64f(&ud);\n // Compute the optimum indices\n iopt = array_argmax64f(ndt, tds->xcorr, &ierr);\n tds->idopt = iopt/tds->ntstar;\n tds->itopt = iopt - tds->idopt*tds->ntstar;\n if (tdsearch_gridSearch_gridToIndex(tds->itopt, tds->idopt, *tds) != iopt)\n {\n fprintf(stdout, \"%s: Switching to slow optimum computation\\n\", __func__);\n for (id=0; ididopt = id;\n tds->itopt = it;\n } \n }\n }\n }\n return 0;\n}\n//============================================================================//\n/*!\n * @brief Writes a map of the max of the cross-correlograms as a function\n * of t* and depth in a format useful for Gnpulot as well as a\n * corresponding Gnuplot plotting script.\n *\n * @param[in] dirnm Directory where the heat map is to be written.\n * @param[in] froot The root name of the heat map.\n * @param[in] tds Grid search structure with the tabulated \n * cross-correlogram maximums.\n *\n * @result 0 indicates success.\n *\n * @ingroup tdsearch_gridsearch\n *\n */\nint tdsearch_gridSearch_writeHeatMap(const char *dirnm, const char *froot,\n const struct tdSearch_struct tds)\n{\n FILE *ofl;\n char fname[PATH_MAX], fgnu[PATH_MAX], cmd[256];\n int id, idt, it;\n memset(fname, 0, PATH_MAX*sizeof(char));\n if (!tds.xcorr || !tds.lags)\n {\n fprintf(stderr, \"%s: Error gridsearch likely not performed\\n\", __func__);\n return -1;\n }\n if (!tds.tstar || !tds.depths)\n {\n fprintf(stderr, \"%s: Error tds likely not initialized\\n\", __func__);\n return -1;\n }\n if (dirnm != NULL)\n {\n sprintf(fname, \"%s/%s.surf_txt\", dirnm, froot);\n }\n else\n {\n sprintf(fname, \"./%s.surf_txt\", froot);\n }\n ofl = fopen(fname, \"w\");\n for (id=0; id= tds.ntstar || id < 0 || id >= tds.ndepth)\n {\n fprintf(stderr, \"%s: Invalid (t*,depth) index (%d,%d)\\n\", __func__, it, id);\n return - 1;\n }\n if (tds.synthetic == NULL || tds.lags == NULL)\n {\n if (tds.synthetic == NULL)\n {\n fprintf(stderr, \"%s: Error tds.synethetic is NULL\\n\", __func__);\n }\n if (tds.lags == NULL)\n {\n fprintf(stderr, \"%s: Error tds.lags is NULL\\n\", __func__);\n }\n return -1;\n }\n idt = tdsearch_gridSearch_gridToIndex(it, id, tds);\n igrns = tdsearch_greens_getGreensFunctionIndex(G11_GRNS, iobs,\n it, id, grns);\n if (idt < 0 || igrns < 0)\n {\n fprintf(stderr, \"%s: Failed getting an index\\n\", __func__);\n return -1;\n }\n // Copy header\n sacio_copyHeader(grns.grns[igrns].header, &synth->header); \n // Copy corresponding synthetic\n synth->npts = grns.grns[igrns].npts;\n synth->data = sacio_malloc64f(synth->npts);\n npGrns = tds.grnsMatrixPtr[idt+1] - tds.grnsMatrixPtr[idt];\n if (npGrns != synth->npts)\n {\n fprintf(stderr, \"%s: Size mismatch\\n\", __func__);\n sacio_free(synth);\n return -1; \n }\n array_copy64f_work(npGrns, &tds.synthetic[tds.grnsMatrixPtr[idt]],\n synth->data);\n // Get the component inline with the estimate\n sacio_setCharacterHeader(SAC_CHAR_KCMPNM, data.obs[iobs].header.kcmpnm,\n &synth->header);\n // Fix the timing\n ierr = sacio_getEpochalStartTime(synth->header, &epoch);\n if (ierr != 0)\n {\n fprintf(stderr, \"%s: Failed to get start time\\n\", __func__);\n return -1;\n }\n epoch = epoch + (double) tds.lags[idt]*tds.dt;\n sacio_setEpochalStartTime(epoch, &synth->header);\n return 0;\n}\n//============================================================================//\n", "meta": {"hexsha": "948426cd5a62b2a8902fa9c4916dd6bf5a396d31", "size": 31156, "ext": "c", "lang": "C", "max_stars_repo_path": "src/gridsearch.c", "max_stars_repo_name": "bakerb845/tdsearch", "max_stars_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "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/gridsearch.c", "max_issues_repo_name": "bakerb845/tdsearch", "max_issues_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "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/gridsearch.c", "max_forks_repo_name": "bakerb845/tdsearch", "max_forks_repo_head_hexsha": "fc65471b097aa6a92fcaf558dfa50622345c4025", "max_forks_repo_licenses": ["Intel"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3219251337, "max_line_length": 89, "alphanum_fraction": 0.54358711, "num_tokens": 8594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6150878696277513, "lm_q2_score": 0.3849121444839335, "lm_q1q2_score": 0.23675479094447188}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"locate.h\"\n#if HAVE_LIBGSL\n#include \n#endif\n\n// include DISORT.MXD\n\n/* nlyr = number of atmospheric layers */\n/* nlev_c = number of atmospheric levels on common z grid */\n/* zd_c = atmospheric levels on common z grid */\n/* nzout = number of output levels = number of black clouds */\n/* zout = vertical level heights in km above surface */\n\nint c_tzs (int nlyr,\n float* dtauc,\n int nlev_c,\n float* zd_c,\n int nzout,\n float* zout,\n float* ssalb,\n float* temper,\n float wvnmlo,\n float wvnmhi,\n int usrtau,\n int ntau,\n float* utau,\n int usrang,\n int numu,\n float* umu,\n int nphi,\n float* phi,\n float albedo,\n double btemp,\n float ttemp,\n float temis,\n int planck,\n int* prnt,\n char* header, // int prndis[7]; char header[127]\n float* rfldir,\n float* rfldn,\n float* flup,\n float* dfdt,\n float* uavg,\n float*** uu,\n int quiet) {\n /* .. Internal variables */\n int lc, j, iu, lu;\n double* tauc = NULL;\n double tau1 = 0, tau2 = 0, etau1 = 0, etau2 = 0, etaumu = 0, ei1 = 0, ei2 = 0, *rad = NULL;\n double *radem = NULL, *pkag = NULL, *etau = NULL, rademtot = 0.0;\n double radrefl, radrefl1, radrefl2, radrefl11, radrefl22;\n double *b0 = NULL, *b1 = NULL;\n double *coeff1 = NULL, *coeff2 = NULL;\n double sqtau1 = 0.0, sqtau2 = 0.0, mu = 0.0, cutau1 = 0.0, tauetau1;\n int * nlayers = NULL, maxnlyr = 0;\n float * alb = NULL, *bplanck = NULL;\n\n /* nlyr = number of layers */\n /* nlyr + 1 = number of levels */\n\n /* initialise */\n\n if ((rad = (double*)calloc (ntau, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((nlayers = (int*)calloc (ntau, sizeof (int))) == NULL)\n return ASCII_NO_MEMORY;\n\n if ((alb = (float*)calloc (ntau, sizeof (float))) == NULL)\n return ASCII_NO_MEMORY;\n if ((bplanck = (float*)calloc (ntau, sizeof (float))) == NULL)\n return ASCII_NO_MEMORY;\n\n if (prnt[0] && strlen (header) != 0) {\n fprintf (stderr, \"**************\\n TZS: %s\\n*****************\\n\", header);\n }\n\n /* Initialise everything to 0. */\n for (iu = 0; iu < numu; iu++) {\n for (lu = 0; lu < nzout; lu++) {\n for (j = 0; j < nphi; j++) {\n uu[j][lu][iu] = 0.;\n }\n }\n }\n for (lu = 0; lu < nzout; lu++) {\n dfdt[lu] = 0.;\n flup[lu] = 0.;\n rfldir[lu] = 0.;\n rfldn[lu] = 0.;\n uavg[lu] = 0.;\n }\n\n /* Layers: 0...NLYR-1 (# layers = NLYR) */\n /* Levels: 0...NLYR (# levels = NLYR+1) */\n /* LC = 0...NYR-1 */\n /* LC = 0 : TOA */\n /* -------------------------------------------------- Level LC, TAUC(LC), TEMPER(LC) */\n /* */\n /* Layer LC */\n /* */\n /* -------------------------------------------------- Level LC+1 , TAUC(LC+1) , TEMPER(LC+1) */\n\n /* Planck radiation from surface with emissivity=1-ALBEDO and temperature BTEMP */\n /* BPLANCK = (1-ALBEDO)*PLKAVG2( WVNMLO, WVNMHI, BTEMP ) */\n\n /* Max number of layers counted from TOA used for all UTAU */\n maxnlyr = -1;\n\n /* Loop over user defined tau = black cloud top heights: */\n /* determine layer number corresponding to user tau */\n /* Rem.: NTAU = NZOUT checked in CHEKIN_TZS */\n\n if (ntau != nzout) {\n errmsg_tzs (\"TZS--nzout != ntau\", TZS_ERROR);\n }\n\n for (lu = 0; lu < ntau; lu++) {\n\n /* zd_c[0] = TOA */\n /* zd_c[nlyr+1] = SUR */\n /* locate gives back lc such that zd_c(lc) >= zout(lu) > zd_lc[lc+1] */\n lc = flocate (zd_c, nlev_c, zout[lu]);\n\n // fprintf(stderr,\"lc = %d zd_c[lc] = %f zd_c[lc+1] = %f zout[lu] = %f\\n\",lc,zd_c[lc],zd_c[lc+1],zout[lu]);\n\n if (lc == -1 || lc == nlev_c) {\n errmsg_tzs (\"TZS--Zout outside atmospheric levels\", TZS_ERROR);\n }\n\n /* Check real presence of this level in tauc ( max diff = 1mm ) */\n /* Determine layer above given user level and store layer index w.r.t. zd_c in nlayers */\n /* nlayers contains the layer index whose bottom is at zout[lu] */\n\n if (fabs (zd_c[lc + 1] - zout[lu]) <= 1.e-6) {\n\n /* check lower boundary */\n\n /* nlevel = nlayers[lu] = LC+1-1 */\n /* nlayer = nlevel - 1 */\n nlayers[lu] = lc;\n\n } else if (fabs (zd_c[lc] - zout[lu]) <= 1.e-6) {\n\n /* check upper boundary */\n\n /* nlevel = nlayers[lu] = LC */\n /* nlayer = nlevel - 1 */\n nlayers[lu] = (int)fmax (lc - 1, 0);\n /* nlayers could be -1 when black cloud is at TOA */\n\n } else {\n\n /* zout_interpolate */\n\n // fprintf(stderr,\"%d4 %4d %9.3f %9.3f %9.3f %9.3f %9.3f\\n\",\n //\t lc,nlev_c,zd_c[lc+1],zd_c[lc],zout[lu],fabs(zd_c[lc+1]-zout[lu]),fabs(zd_c[lc]-zout[lu]));\n errmsg_tzs (\"TZS--User height is not contained in atmospheric levels: use zout_interpolate!\", TZS_ERROR);\n }\n\n // fprintf(stderr,\"nlev_c = %4d zout[lu] = %9.3f zd_c[nlayers[lu]] = %9.3f zd_c[nlayers[lu]+1] = %9.3f lu = %4d\\n\",\n //\t nlev_c,zout[lu],zd_c[nlayers[lu]],zd_c[nlayers[lu]+1],lu);\n //\n // fprintf(stderr,\"lu = %4d maxnlyr = %4d nlayers[lu] = %4d\\n\",lu,maxnlyr,nlayers[lu]);\n\n maxnlyr = (int)fmax (maxnlyr, nlayers[lu]);\n }\n\n /* Above we defined layer indices, now we add +1 because we want the number of layers */\n maxnlyr += 1;\n\n // fprintf(stderr,\"%s %4d\\n\",\"Max # layers = \",maxnlyr);\n\n if (maxnlyr < 0) {\n errmsg_tzs (\"TZS--wrong zout\", TZS_ERROR);\n }\n\n if ((radem = (double*)calloc (maxnlyr, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((tauc = (double*)calloc (maxnlyr + 1, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((pkag = (double*)calloc (maxnlyr + 1, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((etau = (double*)calloc (maxnlyr + 1, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n\n if ((b0 = (double*)calloc (maxnlyr, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((b1 = (double*)calloc (maxnlyr, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((coeff1 = (double*)calloc (maxnlyr, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n if ((coeff2 = (double*)calloc (maxnlyr, sizeof (double))) == NULL)\n return ASCII_NO_MEMORY;\n\n /* calculate cumulative optical depth tauc[lc] up to level lc and */\n /* Planck radiation for every level (not layer!) from 0 to MAXNLYR */\n /* Remark: layer 1 is the first layer from above=TOA?? */\n /* level 0 is the first level from above=TOA, level 0 = TOA */\n\n /* lc = level count */\n lc = 0;\n tauc[lc] = 0.0;\n pkag[lc] = (double)c_planck_func1 (wvnmlo, wvnmhi, temper[lc]);\n\n // fprintf(stderr,\"lc = %d maxnlyr = %d pkag[lc] = %f tauc[lc] = %13.6e dtauc[lc-1] = %13.6e temper[lc] = %9.3f\\n\",lc,maxnlyr,pkag[lc],tauc[lc],dtauc[lc-1],temper[lc]);\n\n for (lc = 1; lc <= maxnlyr; lc++) {\n /* We work here with atmospheric optical thickness as it is provided by the user. */\n /* If you want to use aborption optical thickness the you have to define it in */\n /* the uvspec input file. */\n tauc[lc] = tauc[lc - 1] + ((double)dtauc[lc - 1]);\n\n pkag[lc] = (double)c_planck_func1 (wvnmlo, wvnmhi, temper[lc]);\n\n // fprintf(stderr,\"lc = %d maxnlyr = %d pkag[lc] = %f tauc[lc] = %13.6e dtauc[lc-1] = %13.6e temper[lc] = %9.3f\\n\",lc,maxnlyr,pkag[lc],tauc[lc],dtauc[lc-1],temper[lc]);\n }\n\n /* Print input information */\n if (prnt[0]) {\n\n prtinp_tzs (nlyr,\n maxnlyr,\n dtauc,\n ssalb,\n temper,\n wvnmlo,\n wvnmhi,\n ntau,\n utau,\n numu,\n umu,\n nphi,\n phi,\n albedo,\n btemp,\n ttemp,\n temis,\n tauc,\n nlev_c,\n zd_c,\n nzout,\n zout);\n }\n\n /* check input dimensions and variables */\n chekin_tzs (nlyr,\n maxnlyr,\n dtauc,\n nlev_c,\n zd_c,\n nzout,\n zout,\n ssalb,\n temper,\n wvnmlo,\n wvnmhi,\n usrtau,\n ntau,\n utau,\n usrang,\n numu,\n umu,\n nphi,\n phi,\n albedo,\n btemp,\n ttemp,\n temis,\n planck,\n tauc,\n quiet);\n\n for (lu = 0; lu < ntau; lu++) {\n // fprintf(stderr,\"lu = %4d nlayers[lu] = %4d nlyr = %4d\\n\",lu,nlayers[lu],nlyr);\n /* check layer bottom level */\n if (nlayers[lu] + 1 == nlyr) {\n /* real surface albedo = 1 - emissivity */\n alb[lu] = albedo;\n /* Planck radiation from surface with emissivity=1-ALBEDO and temperature BTEMP */\n bplanck[lu] = (1 - alb[lu]) * c_planck_func1 (wvnmlo, wvnmhi, btemp);\n // fprintf(stderr,\"%4d %4d %12.10f %12.9f %12.8f\\n\",lu, nlayers[lu]+1,alb[lu],bplanck[lu],btemp);\n } else {\n /* Real surface albedo = 1 - emissivity ==> emissivity=1 (black cloud) */\n alb[lu] = 0.0;\n /* Planck radiation of bottom level with emissivity=1 (black cloud) */\n /* and temperature temper( nlayers[lu]+1 ) of bottom level */\n bplanck[lu] = (float)pkag[nlayers[lu] + 1];\n }\n }\n\n if (prnt[0]) {\n fprintf (stderr, \"\\n%4d %s\", ntau, \" User optical depths :\");\n for (lu = 0; lu < ntau; lu++)\n fprintf (stderr, \"%14.8f\", utau[lu]);\n fprintf (stderr, \"\\n\");\n\n fprintf (stderr, \"\\n%4d %s\", ntau, \" User level numbers :\");\n for (lu = 0; lu < ntau; lu++)\n fprintf (stderr, \"%4d\", nlayers[lu] + 1);\n fprintf (stderr, \"\\n\");\n\n fprintf (stderr, \"\\n%4d %s\", ntau, \" User levels / km :\");\n for (lu = 0; lu < ntau; lu++)\n fprintf (stderr, \"%14.8f\", zout[lu]);\n fprintf (stderr, \"\\n\");\n\n fprintf (stderr, \"\\n%4d %s\", ntau, \" User levels / km :\");\n for (lu = 0; lu < ntau; lu++)\n fprintf (stderr, \"%14.8f\", zd_c[nlayers[lu] + 1]);\n fprintf (stderr, \"\\n\");\n }\n\n /* loop from TOA to lowest layer/level needed for calculations */\n for (lc = 0; lc < maxnlyr; lc++) {\n /* assume linear variation of Planck radiation from one level */\n /* to the next one: Planck=b0+tauc*b1 */\n b1[lc] = 0.;\n\n /* CE: this threshold was commented out, but it seems that it is needed because otherwise we get \n negative emissions in some layers */\n if (dtauc[lc] > 1.e-4)\n b1[lc] = (pkag[lc + 1] - pkag[lc]) / dtauc[lc];\n /* In case of thin atmosphere but high temperature variation from one level to the next, dtauc is very small */\n /* but Planck varies sensibly, so we have to take care. The threshold 1.e10 is not crucial because thin */\n /* atmospheric layers emit few radiation. */\n if (fabs (b1[lc]) > 1.e10) {\n /* set b0 to average Planck emission, also not crucial */\n b0[lc] = 0.5 * (pkag[lc + 1] + pkag[lc]);\n b1[lc] = 0.0;\n } else {\n b0[lc] = pkag[lc] - tauc[lc] * b1[lc];\n }\n\n /* Compute coefficients like this even if coeff1[lc]=pkag[lc+1] and coeff2[lc]=pkag[lc] */\n coeff1[lc] = b0[lc] + tauc[lc + 1] * b1[lc];\n coeff2[lc] = b0[lc] + tauc[lc] * b1[lc];\n\n // fprintf(stderr,\" LC %d Deltatau %e DIFFCOEFF1 %e COEFF1 %e pkag[lc+1] = %e\\n\",lc,dtauc[lc],coeff1[lc]-pkag[lc+1],coeff1[lc],pkag[lc+1]);\n // fprintf(stderr,\" LC %d Deltatau %e DIFFCOEFF2 %e COEFF2 %e pkag[lc] = %e\\n\",lc,dtauc[lc],coeff2[lc]-pkag[lc],coeff2[lc],pkag[lc]);\n }\n\n /* Loop over UMUs */\n for (iu = 0; iu < numu; iu++) {\n\n /* Double precision UMU */\n mu = (double)umu[iu];\n\n // /* loop from TOA to lowest layer/level needed for calculations */\n // for (lc=0;lc<=maxnlyr;lc++){\n // /* Initialise ETAU = Attenuation factors from TOA to levels LC in direction MU */\n // etau[lc]=exp(-tauc[lc]/mu);\n // }\n\n /* Emission of atmosphere: */\n /* *********************** */\n\n /* Initialise ETAU = Attenuation factors from TOA to level LC in direction MU */\n lc = 0;\n etau[lc] = exp (-tauc[lc] / mu);\n\n /* loop from TOA to lowest layer/level needed for calculations */\n\n for (lc = 0; lc < maxnlyr; lc++) {\n\n /* Initialise ETAU = Attenuation factors from TOA to level LC+1 in direction MU */\n etau[lc + 1] = exp (-tauc[lc + 1] / mu);\n\n /* Attenuation factors from TOA to levels LC+1 resp. LC: */\n /* ETAU[lc+1] */\n /* ETAU[lc] */\n\n /* Radiation emitted from layer LC (between levels LC and LC+1) towards TOA */\n radem[lc] = etau[lc] * coeff2[lc] - etau[lc + 1] * coeff1[lc] + b1[lc] * mu * (etau[lc] - etau[lc + 1]);\n }\n\n /* Loop over user defined tau = black cloud top heights */\n for (lu = 0; lu < ntau; lu++) {\n\n // fprintf(stderr,\"lu = %4d %4d\\n\",lu,nlayers[lu]);\n\n /* Initialise RAD to 0. */\n rad[lu] = 0.;\n /* Initialise TAU1 */\n /* to optical thickness from TOA up to bottom of layer nlayers[lu] */\n /* TAU1 = TAUC(NLYR) */\n tau1 = tauc[nlayers[lu] + 1];\n /* Initialise ETAU1 */\n etau1 = exp (-tau1);\n tauetau1 = tau1 * etau1;\n /* Initialise EI1 */\n\n#if HAVE_LIBGSL\n /* exponential integral does not converge for values larger about 600*/\n /* the integral for this case becomes 0*/\n if (tau1 > 500.0)\n ei1 = 0.0;\n else\n ei1 = gsl_sf_expint_Ei (-tau1);\n /* fprintf(stderr, \"lu %d tau1 %g ei1 %g\\n\",lu, tau1, ei1); */\n#endif\n#if !HAVE_LIBGSL\n fprintf (stderr, \"libRadtran was built without the gsl-library. Thus \\n\");\n fprintf (stderr, \"tzs may not be used. Please install gsl on your system\\n\");\n fprintf (stderr, \"and rebuild libRadtran.\\n\");\n exit (0);\n#endif\n\n /* Initialise SQTAU1 */\n sqtau1 = tau1 * tau1;\n /* Initialise CUTAU1 */\n cutau1 = tau1 * sqtau1;\n /* initialise RADREFL11 */\n radrefl11 = -2.0 * etau1 + tauetau1 - tau1 * tauetau1 - cutau1 * ei1;\n\n /* Attenuation factor due to full atmospheric absorption in direction MU */\n etaumu = etau[nlayers[lu] + 1];\n\n /* total atmospheric emission i.e. intergral from TOA to bottom */\n rademtot = 0.0;\n\n /* Contribution from surface + atmosphere */\n for (lc = 0; lc <= nlayers[lu]; lc++) {\n\n if (alb[lu] > 0.0) {\n\n /* Reflection from surface: */\n /* ************************ */\n tau2 = tau1;\n etau2 = etau1;\n ei2 = ei1;\n sqtau2 = sqtau1;\n radrefl22 = radrefl11;\n radrefl2 = etau2 * coeff2[lc] * (1. - tau2) - coeff2[lc] * sqtau2 * ei2;\n\n if (lc == nlayers[lu]) {\n radrefl1 = coeff1[lc];\n radrefl11 = -2.0;\n } else {\n tau1 = tauc[nlayers[lu] + 1] - tauc[lc + 1];\n etau1 = exp (-tau1);\n tauetau1 = tau1 * etau1;\n\n#if HAVE_LIBGSL\n /* exponential integral does not converge for values larger about 600*/\n /* the integral for this case becomes 0*/\n if (tau1 > 500.0)\n ei1 = 0.0;\n else\n ei1 = gsl_sf_expint_Ei (-tau1);\n#endif\n\n sqtau1 = tau1 * tau1;\n cutau1 = tau1 * sqtau1;\n\n radrefl11 = -2.0 * etau1 + tauetau1 - tau1 * tauetau1 - cutau1 * ei1;\n\n radrefl1 = etau1 * coeff1[lc] * (1. - tau1) - coeff1[lc] * sqtau1 * ei1;\n }\n\n radrefl = radrefl1 - radrefl2;\n\n /* fprintf(stderr,\"%s %4d %4d %13.6e\\n\",\"LC NLAYERS RADREFL[lc]\",lc,nlayers[lu],radrefl); */\n /* fprintf(stderr,\"%s %4d %13.6e\\n\",\"LC RADREFL1\",lc,radrefl1); */\n /* fprintf(stderr,\"%s %4d %13.6e\\n\",\"LC RADREFL2\",lc,radrefl2); */\n /* fprintf(stderr,\"%s %4d %13.6e %13.6e\\n\",\"LC COEFF1 COEFF2\",lc,coeff1[lc],coeff2[lc]); */\n /* fprintf(stderr,\"%s %4d %13.6e %13.6e %13.6e %13.6e\\n\",\"LC TAU1 TAU2 SQTAU1 SQTAU2\",lc,tau1,tau2,sqtau1,sqtau2); */\n /* fprintf(stderr,\"%s %4d %13.6e %13.6e\\n\",\"LC EI1 EI2\",lc,ei1,ei2); */\n\n radrefl += b1[lc] / 3. * (radrefl11 - radrefl22);\n\n //\t fprintf(stderr,\"%s %4d %13.6e\\n\",\"LC RADREFL[lc]\",lc,radrefl);\n //\t fprintf(stderr,\"%s %4d %13.6e\\n\",\"LC B1[lc]\",lc,b1[lc]);\n //\t fprintf(stderr,\"%s %4d %13.6e\\n\",\"LC RADREFL11\",lc,radrefl11);\n //\t fprintf(stderr,\"%s %4d %13.6e\\n\",\"LC RADREFL22\",lc,radrefl22);\n\n /* RAD[lu] = RAD[lu]+RADEM[lc]+ALBEDO*ETAUMU*RADREFL */\n rad[lu] += radrefl;\n }\n\n /* emission of atmosphere */\n rademtot += radem[lc];\n }\n\n /* fprintf(stderr,\"lu = %4d rad[lu] refl = %13.6e\\n\",lu,rad[lu]); */\n\n /* after computation of radiance reflected at the surface we multiply by the albedo and the extinction from bottom to TOA */\n /* RAD[lu] = RAD[lu]+RADEM[lc]+ALBEDO*ETAUMU*RADREFL */\n rad[lu] *= alb[lu] * etaumu;\n\n /* fprintf(stderr,\"lu = %4d rad[lu] refl attenuated = %13.6e\\n\",lu,rad[lu]); */\n\n /* Contribution from atmospheric emission of all levels */\n rad[lu] += rademtot;\n\n /* fprintf(stderr,\"lu = %4d rad[lu] refl attenuated + emission = %13.6e\\n\",lu,rad[lu]); */\n\n /* contribution from surface emission (bottom): */\n /* ******************************************** */\n rad[lu] += bplanck[lu] * etaumu;\n\n /* fprintf(stderr,\"lu = %4d rad[lu] refl attenuated + emission + surface = %13.6e\\n\",lu,rad[lu]); */\n\n /* isotropic radiance */\n for (j = 0; j < nphi; j++) {\n uu[j][lu][iu] = (float)rad[lu];\n }\n uavg[lu] = (float)rad[lu];\n /* End loop over user tau */\n }\n\n /* End loop over user umu */\n }\n\n free (radem);\n free (tauc);\n free (pkag);\n free (etau);\n free (b0);\n free (b1);\n free (coeff1);\n free (coeff2);\n\n return 0;\n}\n\n/*============================= errmsg_tzs() ===============================*/\n\n/*\n * Print out a warning or error message; abort if type == TZS_ERROR\n */\n\n#define MAX_WARNINGS 100\n\nvoid errmsg_tzs (char* messag, int type) {\n static int warning_limit = FALSE, num_warnings = 0;\n\n if (type == TZS_ERROR) {\n fprintf (stderr, \"\\n ******* ERROR >>>>>> %s\\n\", messag);\n exit (1);\n }\n\n if (warning_limit)\n return;\n\n if (++num_warnings <= MAX_WARNINGS) {\n fprintf (stderr, \"\\n ******* WARNING >>>>>> %s\\n\", messag);\n } else {\n fprintf (stderr, \"\\n\\n >>>>>> TOO MANY WARNING MESSAGES -- They will no longer be printed <<<<<<<\\n\\n\");\n warning_limit = TRUE;\n }\n\n return;\n}\n\n#undef MAX_WARNINGS\n\nvoid prtinp_tzs (int nlyr,\n int maxnlyr,\n float* dtauc,\n float* ssalb,\n float* temper,\n float wvnmlo,\n float wvnmhi,\n int ntau,\n float* utau,\n int numu,\n float* umu,\n int nphi,\n float* phi,\n float albedo,\n double btemp,\n float ttemp,\n float temis,\n double* tauc,\n int nlev_c,\n float* zd_c,\n int nzout,\n float* zout) {\n /* print values of input variables */\n /* */\n /* Called by- TZS */\n /* --------------------------------------------------------------------*/\n\n /* .. Local Scalars .. */\n int lc, lu;\n\n fprintf (stderr, \"\\n%s%4d\\n\", \" No. computational layers = \", nlyr);\n fprintf (stderr, \"\\n%s%4d\\n\", \" No. computational layers needed = \", maxnlyr);\n\n fprintf (stderr, \"\\n%4d %s\", ntau, \" User optical depths :\");\n for (lu = 0; lu < ntau; lu++)\n fprintf (stderr, \"%13.6e\", utau[lu]);\n fprintf (stderr, \"\\n\");\n\n fprintf (stderr, \"\\n%4d %s\", numu, \" User polar angle cosines :\");\n for (lu = 0; lu < numu; lu++)\n fprintf (stderr, \"%9.5f\", umu[lu]);\n fprintf (stderr, \"\\n\");\n\n fprintf (stderr, \"\\n%4d %s\", nphi, \" User azimuthal angles :\");\n for (lu = 0; lu < nphi; lu++)\n fprintf (stderr, \"%9.2f\", phi[lu]);\n fprintf (stderr, \"\\n\");\n\n fprintf (stderr,\n \"%s%14.4f%14.4f\\n%s%10.2f%s%8.4f\\n%s%8.4f\\n\",\n \" Thermal emission in wavenumber interval :\",\n wvnmlo,\n wvnmhi,\n \" Bottom temperature = \",\n btemp,\n \" Top temperature = \",\n ttemp,\n \" Top emissivity = \",\n temis);\n\n fprintf (stderr, \"%s%8.4f\\n\", \" Bottom albedo (Lambertian) =\", albedo);\n\n /* Print layer variables */\n\n fprintf (stderr,\n \"\\n%s\\n%s\\n%s\\n\",\n \" Layer Total Single\",\n \" Optical Optical Scattering\",\n \" Depth Depth Albedo Temperature\");\n\n for (lc = 0; lc < maxnlyr; lc++) {\n fprintf (stderr, \"%4d%13.6e%13.6e%14.3f%14.3f\\n\", lc, dtauc[lc], tauc[lc], ssalb[lc], temper[lc]);\n }\n\n fprintf (stderr, \"%4d%13.6e%13.6e%14.3f%14.3f\\n\", maxnlyr, 0.0, tauc[maxnlyr], 0.0, temper[maxnlyr]);\n\n fprintf (stderr,\n \"\\n%s\\n%s\\n%s\\n\",\n \" Layer Single\",\n \" Optical Scattering\",\n \" Depth Albedo Temperature\");\n\n for (lc = 0; lc < nlyr; lc++) {\n fprintf (stderr, \"%4d%13.6e%14.3f%14.3f\\n\", lc, dtauc[lc], ssalb[lc], temper[lc]);\n }\n\n fprintf (stderr, \"%4d%13.6e%14.3f%14.3f\\n\", nlyr, -1.0, -1.0, temper[nlyr]);\n\n fprintf (stderr, \"\\n%s\\n%s\\n%s\\n\", \" Atmospheric\", \" Level\", \" [km]\");\n\n for (lc = 0; lc < nlev_c; lc++) {\n fprintf (stderr, \"%4d %8.3f\\n\", lc, zd_c[lc]);\n }\n\n fprintf (stderr, \"\\n%s\\n%s\\n%s\\n\", \" Output\", \" Level\", \" [km]\");\n\n for (lc = 0; lc < nzout; lc++) {\n fprintf (stderr, \"%4d %8.3f\\n\", lc, zout[lc]);\n }\n}\n\nvoid chekin_tzs (int nlyr,\n int maxnlyr,\n float* dtauc,\n int nlev_c,\n float* zd_c,\n int nzout,\n float* zout,\n float* ssalb,\n float* temper,\n float wvnmlo,\n float wvnmhi,\n int usrtau,\n int ntau,\n float* utau,\n int usrang,\n int numu,\n float* umu,\n int nphi,\n float* phi,\n float albedo,\n double btemp,\n float ttemp,\n float temis,\n int planck,\n double* tauc,\n int quiet) {\n /* Checks the input dimensions and variables */\n int inperr = FALSE;\n int lc, j, iu, lu;\n\n if (planck == FALSE)\n inperr = c_write_bad_var (VERBOSE, \"planck\");\n\n if (nlyr < 1)\n inperr = c_write_bad_var (VERBOSE, \"NLYR\");\n\n if (maxnlyr < 1)\n inperr = c_write_bad_var (VERBOSE, \"MAXNLYR\");\n\n if (nlyr + 1 != nlev_c)\n inperr = c_write_bad_var (VERBOSE, \"NLYR/NLEV_C\");\n\n for (lc = 0; lc < nlyr; lc++) {\n if (dtauc[lc] < 0.) {\n inperr = c_write_bad_var (VERBOSE, \"dtauc\");\n }\n if (zd_c[lc] < 0.) {\n inperr = c_write_bad_var (VERBOSE, \"zd\");\n }\n if (ssalb[lc] < 0.0 || ssalb[lc] > 1.0) {\n inperr = c_write_bad_var (VERBOSE, \"ssalb\");\n }\n if (temper[lc] < 0.) {\n inperr = c_write_bad_var (VERBOSE, \"temper\");\n }\n }\n\n if (usrtau) {\n if (ntau < 1) {\n inperr = c_write_bad_var (VERBOSE, \"ntau\");\n }\n if (nzout < ntau)\n inperr = c_write_bad_var (VERBOSE, \"ntau/nzout\");\n for (lu = 0; lu < ntau; lu++) {\n /* Do a relative check to see if we are just beyond the bottom boundary */\n /* This might happen due to numerical rounding off problems. ak20110224*/\n\n // fprintf(stderr,\"lu = %d utau = %13.6e tauc[maxnlyr] = %13.6e zout = %f\\n\",lu,utau[lu],tauc[maxnlyr],zout[lu]);\n if (fabs (utau[lu] - tauc[maxnlyr]) <= 1.e-6 * tauc[maxnlyr]) {\n utau[lu] = tauc[maxnlyr];\n }\n // fprintf(stderr,\"lu = %d utau = %13.6e tauc[maxnlyr] = %13.6e zout = %f\\n\",lu,utau[lu],tauc[maxnlyr],zout[lu]);\n\n // if(utau[lu] < 0. || utau[lu] > tauc[maxnlyr]) {\n if (utau[lu] < 0. || (utau[lu] - tauc[maxnlyr]) > 1.e-6 * tauc[maxnlyr]) {\n fprintf (stderr,\n \"WARNING: lu = %d utau = %13.6e tauc[maxnlyr] = %13.6e zout = %f\\n\",\n lu,\n utau[lu],\n tauc[maxnlyr],\n zout[lu]);\n inperr = c_write_bad_var (VERBOSE, \"utau\");\n }\n if (zout[lu] < 0.0)\n inperr = c_write_bad_var (VERBOSE, \"zout\");\n }\n } else {\n ntau = 1;\n utau = (float*)calloc (1, sizeof (float));\n utau[0] = 0.;\n nzout = 1;\n zout = (float*)calloc (1, sizeof (float));\n zout[0] = zd_c[0];\n }\n\n if (usrang) {\n if (numu < 0) {\n inperr = c_write_bad_var (VERBOSE, \"numu\");\n }\n for (iu = 0; iu < numu; iu++) {\n if (umu[iu] < -1. || umu[iu] > 1. || umu[iu] == 0.) {\n inperr = c_write_bad_var (VERBOSE, \"umu\");\n }\n if (iu >= 1) {\n if (umu[iu] < umu[iu - 1]) {\n inperr = c_write_bad_var (VERBOSE, \"umu\");\n }\n }\n }\n if (nphi <= 0)\n inperr = c_write_bad_var (VERBOSE, \"nphi\");\n\n for (j = 0; j < nphi; j++) {\n if (phi[j] < 0. || phi[j] > 360.) {\n inperr = c_write_bad_var (VERBOSE, \"phi\");\n }\n }\n } else {\n numu = 1;\n umu = (float*)calloc (1, sizeof (float));\n umu[0] = 1.;\n nphi = 1;\n phi = (float*)calloc (1, sizeof (float));\n phi[0] = 0.;\n }\n\n if (albedo < 0. || albedo > 1.)\n inperr = c_write_bad_var (VERBOSE, \"albedo\");\n\n if (wvnmlo < 0.0 || wvnmhi <= wvnmlo)\n inperr = c_write_bad_var (VERBOSE, \"wvnmlo,hi\");\n\n if (temis < 0. || temis > 1.)\n inperr = c_write_bad_var (VERBOSE, \"temis\");\n\n if (btemp < 0.0)\n inperr = c_write_bad_var (VERBOSE, \"btemp\");\n\n if (ttemp < 0.0)\n inperr = c_write_bad_var (VERBOSE, \"ttemp\");\n\n if (inperr)\n c_errmsg (\"TZS--input and/or dimension errors\", TZS_ERROR);\n\n if (!quiet) {\n for (lc = 1; lc <= nlyr; lc++) {\n if (fabs (temper[lc] - temper[lc - 1]) > 10.) {\n c_errmsg (\"check_inputs--vertical temperature step may be too large for good accuracy\", TZS_WARNING);\n }\n }\n }\n}\n", "meta": {"hexsha": "9d75e2379bffd64903be54233468c60b25a3e01a", "size": 28814, "ext": "c", "lang": "C", "max_stars_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/c_tzs.c", "max_stars_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_stars_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/c_tzs.c", "max_issues_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_issues_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ubuntu20/projects/libRadtran-2.0.4/libsrc_c/c_tzs.c", "max_forks_repo_name": "AmberCrafter/docker-compose_libRadtran", "max_forks_repo_head_hexsha": "0182f991db6a13e0cacb3bf9f43809e6850593e4", "max_forks_repo_licenses": ["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.354601227, "max_line_length": 178, "alphanum_fraction": 0.4672381481, "num_tokens": 9004, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.32082131381216084, "lm_q1q2_score": 0.23552119484775044}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"userFunc.h\"\n\n#define G 6.67384e-8 /* 2010 CODATA value in CGS units */\n#define C 2.99792458e10 /* Exact value in CGS units */\n#define ALPHAMIN 1.0e-3 /* Minimum alpha allowed for numerical reasons */\n#define YR (365.25*24.0*3600.0) /* 1 yr in sec */\n#define MYR (1.0e6*YR) /* 1 Myr in seconds */\n#define MSUN 1.9886e33 /* Solar mass in g */\n\n/**************************************************************************/\n/* This defines userFunc routines for the Krumholz & Kruijssen CMZ */\n/* disk model including feedback */\n/**************************************************************************/\n\n/* Define the parameters to be used here */\ntypedef struct {\n double eta;\n double sigmath;\n double shapefac;\n double zetad;\n double alphacoef;\n double epsff0;\n long tctr;\n double p_per_sn;\n double e_per_sn;\n double star_rad_var;\n double col_min;\n double sigma_max;\n double col_floor;\n double en_wind;\n void *wksp; /* This a placeholder for the extra memory stored at\n\t\t the end of the parameters for temporary workspace\n\t\t and to store the SF history. The size of storage\n\t\t here will be (nbin_SB99+5)*grd->nr; we implement\n\t\t pointers to this data via macro, below */\n} paramType;\n\n#define MSRC_TMP(p) ((double *) &(((paramType *) (p))->wksp))\n#define PDOT(p,g) ((double *) &(((paramType *) (p))->wksp) + (g)->nr)\n#define EDOT(p,g) ((double *) &(((paramType *) (p))->wksp) + 2*(g)->nr)\n#define MDOT(p,g) ((double *) &(((paramType *) (p))->wksp) + 3*(g)->nr)\n#define SIGMASTAR(p,g) ((double *) &(((paramType *) (p))->wksp) + 4*(g)->nr)\n\n/* Declare some utility functions to compute the SFR, mass loss rate,\n and momentum and energy injection rate per unit area */\nvoid injection_rate(double *mstar, double p_per_sn, double e_per_sn,\n\t\t double *pdot_tot, double *edot_tot, double *mdot_tot);\nvoid sfrwind(const grid *grd, const double *col, const double *pres,\n\t void *params, double *sigma_SFR, double *sigma_wind);\n\n/* Data from starburst99 */\nconst int nbin_SB99 = 1000; /* Number of output times */\nconst double dt_SB99 = 0.05; /* Output time interval in Myr */\n\n/* Supernova rate, expressed as log SNe / year / 10^6 Msun of stars, for stellar populations of different ages */\nconst double snr_SB99[1000] =\n { -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -3.64, -3.33, -3.32, -3.31, -3.31, -3.28, -3.30, -3.27, -3.29, -3.28, -3.28, -3.25, -3.25, -3.27, -3.26, -3.24, -3.27, -3.24, -3.26, -3.24, -3.26, -3.26, -3.26, -3.25, -3.25, -3.25, -3.25, -3.25, -3.25, -3.22, -3.22, -3.24, -3.24, -3.22, -3.22, -3.24, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.24, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.26, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.27, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.28, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.29, -3.30, -3.30, -3.30, -3.33, -3.33, -3.33, -3.34, -3.34, -3.34, -3.34, -3.35, -3.35, -3.35, -3.35, -3.35, -3.35, -3.36, -3.36, -3.36, -3.36, -3.36, -3.37, -3.37, -3.37, -3.37, -3.37, -3.37, -3.38, -3.38, -3.38, -3.38, -3.38, -3.38, -3.39, -3.39, -3.39, -3.39, -3.39, -3.39, -3.40, -3.40, -3.40, -3.40, -3.40, -3.40, -3.40, -3.41, -3.41, -3.41, -3.41, -3.41, -3.41, -3.42, -3.42, -3.42, -3.42, -3.42, -3.42, -3.42, -3.42, -3.43, -3.43, -3.43, -3.43, -3.43, -3.43, -3.43, -3.44, -3.44, -3.44, -3.44, -3.44, -3.44, -3.44, -3.44, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.45, -3.46, -3.46, -3.46, -3.46, -3.46, -3.46, -3.46, -3.46, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.47, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.48, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.49, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.50, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.51, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.52, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.53, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.54, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.55, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.56, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.57, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.58, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.59, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.60, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.61, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.62, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.63, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.64, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.65, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.66, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.70, -3.68, -3.67, -3.67, -3.67, -3.67, -3.67, -3.67, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.68, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.69, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.70, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.71, -3.72, -3.72, -3.72, -3.72, -3.72, -3.72, -3.72, -3.74, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00, -30.00 };\n\n/* Luminosity of stellar populations of different ages, expressed as log of the luminosity in erg/s per 10^6 Msun worth of stars */\nconst double lum_SB99[1000] =\n { 42.496, 42.497, 42.498, 42.500, 42.501, 42.503, 42.505, 42.506, 42.508, 42.510, 42.512, 42.513, 42.515, 42.517, 42.519, 42.520, 42.522, 42.524, 42.526, 42.528, 42.530, 42.531, 42.533, 42.535, 42.537, 42.539, 42.541, 42.543, 42.545, 42.547, 42.549, 42.551, 42.553, 42.556, 42.558, 42.560, 42.562, 42.564, 42.567, 42.569, 42.572, 42.574, 42.576, 42.579, 42.582, 42.584, 42.587, 42.590, 42.593, 42.595, 42.598, 42.601, 42.603, 42.606, 42.609, 42.611, 42.614, 42.618, 42.619, 42.619, 42.616, 42.612, 42.607, 42.602, 42.593, 42.579, 42.566, 42.554, 42.541, 42.529, 42.517, 42.505, 42.493, 42.482, 42.471, 42.460, 42.450, 42.440, 42.431, 42.422, 42.413, 42.405, 42.396, 42.388, 42.380, 42.372, 42.364, 42.357, 42.349, 42.341, 42.334, 42.326, 42.319, 42.312, 42.304, 42.297, 42.289, 42.282, 42.274, 42.266, 42.258, 42.250, 42.243, 42.236, 42.228, 42.221, 42.214, 42.207, 42.200, 42.193, 42.187, 42.180, 42.174, 42.167, 42.161, 42.155, 42.149, 42.143, 42.136, 42.130, 42.124, 42.118, 42.113, 42.107, 42.101, 42.095, 42.089, 42.084, 42.078, 42.072, 42.067, 42.061, 42.055, 42.050, 42.044, 42.038, 42.033, 42.027, 42.021, 42.015, 42.010, 42.004, 41.999, 41.994, 41.988, 41.983, 41.978, 41.973, 41.967, 41.962, 41.957, 41.952, 41.947, 41.943, 41.937, 41.932, 41.927, 41.922, 41.917, 41.913, 41.908, 41.903, 41.898, 41.894, 41.889, 41.884, 41.879, 41.874, 41.870, 41.865, 41.860, 41.855, 41.851, 41.846, 41.841, 41.837, 41.833, 41.829, 41.824, 41.821, 41.817, 41.813, 41.809, 41.805, 41.801, 41.797, 41.794, 41.790, 41.786, 41.783, 41.779, 41.776, 41.772, 41.768, 41.765, 41.762, 41.758, 41.755, 41.751, 41.748, 41.745, 41.742, 41.738, 41.735, 41.732, 41.729, 41.726, 41.723, 41.719, 41.716, 41.713, 41.710, 41.707, 41.704, 41.701, 41.698, 41.695, 41.693, 41.690, 41.687, 41.684, 41.681, 41.679, 41.676, 41.673, 41.671, 41.667, 41.665, 41.662, 41.659, 41.656, 41.654, 41.651, 41.648, 41.645, 41.642, 41.639, 41.636, 41.634, 41.631, 41.628, 41.625, 41.622, 41.620, 41.617, 41.614, 41.611, 41.608, 41.606, 41.603, 41.599, 41.597, 41.594, 41.591, 41.588, 41.586, 41.583, 41.580, 41.578, 41.575, 41.572, 41.569, 41.566, 41.564, 41.561, 41.559, 41.556, 41.553, 41.551, 41.548, 41.545, 41.543, 41.540, 41.538, 41.535, 41.533, 41.530, 41.528, 41.525, 41.523, 41.521, 41.518, 41.516, 41.513, 41.511, 41.509, 41.506, 41.504, 41.502, 41.499, 41.497, 41.495, 41.492, 41.490, 41.488, 41.486, 41.484, 41.482, 41.480, 41.478, 41.475, 41.473, 41.471, 41.469, 41.467, 41.464, 41.462, 41.460, 41.458, 41.456, 41.454, 41.452, 41.450, 41.448, 41.445, 41.444, 41.442, 41.440, 41.438, 41.436, 41.434, 41.432, 41.430, 41.428, 41.426, 41.425, 41.423, 41.421, 41.419, 41.417, 41.416, 41.414, 41.412, 41.410, 41.409, 41.407, 41.406, 41.404, 41.402, 41.401, 41.399, 41.397, 41.396, 41.394, 41.392, 41.391, 41.390, 41.388, 41.387, 41.385, 41.384, 41.382, 41.381, 41.379, 41.378, 41.376, 41.375, 41.374, 41.373, 41.371, 41.370, 41.368, 41.367, 41.365, 41.364, 41.363, 41.361, 41.360, 41.359, 41.357, 41.356, 41.355, 41.353, 41.352, 41.351, 41.349, 41.348, 41.347, 41.346, 41.344, 41.343, 41.342, 41.340, 41.339, 41.338, 41.336, 41.335, 41.334, 41.332, 41.331, 41.330, 41.329, 41.328, 41.326, 41.325, 41.324, 41.323, 41.322, 41.320, 41.319, 41.318, 41.317, 41.315, 41.314, 41.313, 41.312, 41.311, 41.309, 41.308, 41.307, 41.306, 41.305, 41.304, 41.303, 41.302, 41.301, 41.300, 41.298, 41.297, 41.296, 41.295, 41.294, 41.292, 41.291, 41.290, 41.289, 41.288, 41.287, 41.286, 41.285, 41.284, 41.283, 41.282, 41.281, 41.279, 41.279, 41.277, 41.277, 41.276, 41.274, 41.273, 41.272, 41.271, 41.270, 41.269, 41.268, 41.267, 41.266, 41.265, 41.264, 41.263, 41.262, 41.261, 41.259, 41.259, 41.258, 41.257, 41.256, 41.254, 41.253, 41.252, 41.252, 41.251, 41.249, 41.248, 41.247, 41.246, 41.245, 41.244, 41.243, 41.242, 41.241, 41.240, 41.239, 41.238, 41.238, 41.236, 41.235, 41.234, 41.233, 41.232, 41.232, 41.231, 41.230, 41.230, 41.229, 41.227, 41.227, 41.225, 41.225, 41.224, 41.223, 41.222, 41.221, 41.220, 41.219, 41.218, 41.218, 41.217, 41.216, 41.215, 41.214, 41.213, 41.212, 41.211, 41.211, 41.209, 41.208, 41.208, 41.207, 41.206, 41.205, 41.204, 41.203, 41.203, 41.202, 41.201, 41.200, 41.199, 41.198, 41.198, 41.197, 41.196, 41.195, 41.194, 41.193, 41.192, 41.191, 41.191, 41.190, 41.189, 41.188, 41.187, 41.187, 41.186, 41.185, 41.184, 41.184, 41.183, 41.182, 41.181, 41.180, 41.180, 41.179, 41.178, 41.177, 41.176, 41.175, 41.175, 41.174, 41.173, 41.172, 41.171, 41.171, 41.170, 41.169, 41.168, 41.167, 41.166, 41.165, 41.165, 41.164, 41.163, 41.162, 41.162, 41.161, 41.160, 41.159, 41.159, 41.158, 41.157, 41.156, 41.156, 41.155, 41.154, 41.153, 41.152, 41.151, 41.150, 41.150, 41.149, 41.148, 41.147, 41.146, 41.146, 41.145, 41.144, 41.143, 41.143, 41.141, 41.141, 41.140, 41.139, 41.139, 41.138, 41.137, 41.136, 41.136, 41.135, 41.134, 41.134, 41.133, 41.118, 41.131, 41.130, 41.130, 41.129, 41.128, 41.128, 41.127, 41.126, 41.125, 41.125, 41.124, 41.123, 41.122, 41.121, 41.120, 41.119, 41.119, 41.118, 41.117, 41.116, 41.115, 41.114, 41.113, 41.113, 41.112, 41.111, 41.111, 41.110, 41.109, 41.108, 41.107, 41.107, 41.106, 41.105, 41.104, 41.104, 41.103, 41.102, 41.101, 41.100, 41.099, 41.099, 41.098, 41.097, 41.096, 41.095, 41.095, 41.094, 41.093, 41.093, 41.092, 41.091, 41.090, 41.089, 41.088, 41.088, 41.087, 41.086, 41.085, 41.085, 41.084, 41.084, 41.083, 41.082, 41.082, 41.081, 41.080, 41.079, 41.079, 41.078, 41.077, 41.076, 41.076, 41.075, 41.074, 41.073, 41.073, 41.072, 41.071, 41.070, 41.070, 41.069, 41.068, 41.068, 41.067, 41.066, 41.065, 41.065, 41.064, 41.063, 41.063, 41.062, 41.061, 41.060, 41.060, 41.059, 41.058, 41.058, 41.057, 41.056, 41.055, 41.055, 41.054, 41.053, 41.053, 41.052, 41.051, 41.050, 41.050, 41.049, 41.048, 41.048, 41.047, 41.046, 41.045, 41.045, 41.044, 41.043, 41.043, 41.042, 41.041, 41.041, 41.040, 41.040, 41.039, 41.038, 41.037, 41.036, 41.036, 41.035, 41.035, 41.034, 41.033, 41.033, 41.032, 41.031, 41.030, 41.030, 41.029, 41.028, 41.028, 41.027, 41.027, 41.026, 41.025, 41.024, 41.024, 41.023, 41.023, 41.022, 41.021, 41.020, 41.020, 41.019, 41.018, 41.017, 41.017, 41.016, 41.016, 41.015, 41.014, 41.014, 41.013, 41.012, 41.012, 41.011, 41.010, 41.010, 41.009, 41.008, 41.008, 41.007, 41.007, 41.006, 41.005, 41.005, 41.004, 41.003, 41.003, 41.002, 41.001, 41.000, 41.000, 40.999, 40.999, 40.998, 40.998, 40.997, 40.997, 40.996, 40.996, 40.995, 40.994, 40.994, 40.993, 40.993, 40.992, 40.992, 40.991, 40.990, 40.990, 40.989, 40.988, 40.988, 40.987, 40.986, 40.985, 40.985, 40.984, 40.984, 40.983, 40.983, 40.982, 40.981, 40.981, 40.980, 40.979, 40.979, 40.978, 40.978, 40.977, 40.976, 40.976, 40.975, 40.975, 40.974, 40.973, 40.973, 40.972, 40.971, 40.971, 40.970, 40.970, 40.969, 40.969, 40.968, 40.967, 40.967, 40.966, 40.966, 40.965, 40.964, 40.964, 40.963, 40.962, 40.962, 40.962, 40.961, 40.960, 40.942, 40.959, 40.958, 40.958, 40.957, 40.957, 40.956, 40.955, 40.955, 40.954, 40.954, 40.953, 40.953, 40.952, 40.951, 40.951, 40.950, 40.949, 40.949, 40.948, 40.948, 40.947, 40.946, 40.946, 40.945, 40.945, 40.944, 40.943, 40.943, 40.942, 40.942, 40.941, 40.941, 40.940, 40.939, 40.939, 40.938, 40.938, 40.937, 40.937, 40.936, 40.935, 40.935, 40.934, 40.934, 40.933, 40.933, 40.932, 40.931, 40.931, 40.930, 40.929, 40.929, 40.928, 40.928, 40.928, 40.927, 40.926, 40.926, 40.925, 40.925, 40.924, 40.923, 40.923, 40.922, 40.922, 40.921, 40.921, 40.920, 40.920, 40.919, 40.919, 40.918, 40.918, 40.917, 40.916, 40.916, 40.915, 40.915, 40.914, 40.914, 40.913, 40.912, 40.912, 40.911, 40.911, 40.911, 40.910, 40.909, 40.909, 40.908, 40.907, 40.907, 40.906, 40.906, 40.905, 40.905, 40.904, 40.904, 40.903, 40.902, 40.902, 40.901, 40.901, 40.900, 40.899, 40.899, 40.899, 40.898, 40.898, 40.897, 40.897, 40.897, 40.896, 40.895, 40.895, 40.894, 40.894, 40.893, 40.893, 40.892, 40.892, 40.891, 40.891, 40.890, 40.890, 40.889, 40.889, 40.888, 40.888, 40.887, 40.887, 40.886, 40.886, 40.885, 40.884, 40.884, 40.883, 40.883, 40.882, 40.881, 40.881, 40.880, 40.880, 40.879, 40.879, 40.878, 40.877 };\n\n/* Wind momentum flux, expressed as log of the momentum in dyne per 10^6 Msun worth of stars */\nconst double pdot_wind_SB99[1000] =\n { 31.689, 31.695, 31.700, 31.705, 31.709, 31.714, 31.718, 31.723, 31.728, 31.732, 31.737, 31.741, 31.746, 31.750, 31.755, 31.759, 31.764, 31.768, 31.773, 31.778, 31.782, 31.787, 31.792, 31.796, 31.801, 31.805, 31.809, 31.814, 31.818, 31.822, 31.826, 31.829, 31.833, 31.836, 31.838, 31.841, 31.842, 31.843, 31.844, 31.843, 31.842, 31.839, 31.835, 31.830, 31.822, 31.812, 31.803, 31.821, 31.844, 31.868, 31.893, 31.929, 31.982, 32.001, 32.016, 32.012, 32.033, 32.064, 32.168, 32.222, 32.272, 32.308, 32.325, 32.339, 32.340, 32.336, 32.332, 32.329, 32.329, 32.295, 32.251, 32.214, 32.183, 32.160, 32.140, 32.118, 32.088, 32.011, 31.980, 31.946, 31.916, 31.885, 31.868, 31.842, 31.808, 31.805, 31.747, 31.751, 31.724, 31.707, 31.702, 31.673, 31.674, 31.630, 31.612, 31.595, 31.552, 31.545, 31.543, 31.526, 31.508, 31.494, 31.476, 31.421, 31.395, 31.389, 31.375, 31.373, 31.385, 31.157, 31.352, 31.337, 31.317, 31.352, 31.273, 31.245, 31.226, 31.185, 31.173, 31.125, 31.050, 31.063, 31.102, 31.113, 31.140, 31.160, 31.155, 31.046, 31.019, 31.004, 30.984, 30.981, 30.978, 30.979, 30.964, 30.954, 30.947, 30.937, 30.894, 30.895, 30.893, 30.896, 30.895, 30.895, 30.897, 30.898, 30.896, 30.895, 30.900, 30.903, 30.905, 30.905, 30.907, 30.909, 30.910, 30.914, 30.916, 30.911, 30.907, 30.892, 30.878, 30.859, 30.839, 30.818, 30.799, 30.777, 30.759, 30.739, 30.720, 30.699, 30.681, 30.664, 30.642, 30.624, 30.608, 30.585, 30.570, 30.549, 30.533, 30.514, 30.499, 30.478, 30.461, 30.444, 30.431, 30.414, 30.396, 30.383, 30.362, 30.351, 30.336, 30.315, 30.304, 30.285, 30.277, 30.260, 30.242, 30.235, 30.213, 30.203, 30.191, 30.179, 30.160, 30.149, 30.138, 30.124, 30.113, 30.094, 30.082, 30.073, 30.063, 30.043, 30.033, 30.023, 30.012, 29.999, 29.983, 29.972, 29.962, 29.951, 29.941, 29.930, 29.913, 29.903, 29.891, 29.878, 29.871, 29.861, 29.854, 29.846, 29.841, 29.821, 29.813, 29.798, 29.786, 29.775, 29.758, 29.745, 29.722, 29.700, 29.689, 29.650, 29.644, 29.604, 29.584, 29.571, 29.557, 29.544, 29.532, 29.520, 29.509, 29.500, 29.491, 29.482, 29.474, 29.464, 29.456, 29.447, 29.437, 29.429, 29.422, 29.415, 29.408, 29.401, 29.394, 29.387, 29.380, 29.373, 29.366, 29.360, 29.353, 29.346, 29.340, 29.333, 29.326, 29.320, 29.313, 29.307, 29.300, 29.293, 29.287, 29.281, 29.274, 29.268, 29.261, 29.255, 29.249, 29.242, 29.236, 29.230, 29.224, 29.217, 29.211, 29.205, 29.198, 29.192, 29.186, 29.180, 29.174, 29.168, 29.162, 29.156, 29.150, 29.144, 29.138, 29.131, 29.125, 29.119, 29.113, 29.107, 29.101, 29.096, 29.090, 29.084, 29.078, 29.072, 29.066, 29.061, 29.055, 29.049, 29.044, 29.038, 29.032, 29.026, 29.021, 29.015, 29.009, 29.004, 28.999, 28.993, 28.988, 28.982, 28.977, 28.972, 28.966, 28.961, 28.956, 28.951, 28.945, 28.941, 28.936, 28.930, 28.925, 28.920, 28.915, 28.910, 28.905, 28.900, 28.895, 28.889, 28.884, 28.879, 28.874, 28.868, 28.863, 28.858, 28.853, 28.848, 28.842, 28.837, 28.832, 28.827, 28.822, 28.817, 28.812, 28.807, 28.802, 28.797, 28.792, 28.787, 28.782, 28.777, 28.772, 28.768, 28.764, 28.758, 28.753, 28.749, 28.744, 28.739, 28.735, 28.730, 28.726, 28.721, 28.716, 28.712, 28.708, 28.703, 28.699, 28.694, 28.690, 28.685, 28.680, 28.677, 28.672, 28.667, 28.663, 28.659, 28.655, 28.651, 28.647, 28.642, 28.638, 28.634, 28.630, 28.626, 28.622, 28.618, 28.614, 28.609, 28.606, 28.602, 28.598, 28.594, 28.590, 28.587, 28.582, 28.578, 28.575, 28.571, 28.567, 28.563, 28.560, 28.556, 28.552, 28.548, 28.545, 28.541, 28.537, 28.534, 28.530, 28.527, 28.524, 28.519, 28.516, 28.513, 28.509, 28.506, 28.502, 28.499, 28.495, 28.491, 28.488, 28.484, 28.481, 28.478, 28.475, 28.472, 28.469, 28.465, 28.461, 28.458, 28.455, 28.447, 28.448, 28.445, 28.442, 28.439, 28.435, 28.433, 28.429, 28.426, 28.422, 28.419, 28.416, 28.413, 28.407, 28.406, 28.404, 28.400, 28.397, 28.395, 28.392, 28.386, 28.383, 28.385, 28.377, 28.374, 28.374, 28.369, 28.365, 28.366, 28.362, 28.360, 28.354, 28.355, 28.350, 28.347, 28.341, 28.342, 28.339, 28.339, 28.334, 28.331, 28.328, 28.326, 28.324, 28.321, 28.318, 28.315, 28.312, 28.310, 28.307, 28.305, 28.410, 28.373, 28.447, 28.424, 28.464, 28.443, 28.488, 28.484, 28.489, 28.487, 28.488, 28.486, 28.492, 28.488, 28.493, 28.491, 28.488, 28.485, 28.482, 28.486, 28.480, 28.482, 28.483, 28.478, 28.476, 28.478, 28.476, 28.475, 28.476, 28.469, 28.471, 28.466, 28.466, 28.470, 28.468, 28.462, 28.460, 28.462, 28.459, 28.456, 28.453, 28.454, 28.455, 28.453, 28.449, 28.448, 28.444, 28.444, 28.440, 28.441, 28.437, 28.435, 28.433, 28.436, 28.434, 28.431, 28.429, 28.426, 28.425, 28.423, 28.421, 28.417, 28.416, 28.415, 28.412, 28.409, 28.408, 28.405, 28.405, 28.401, 28.400, 28.397, 28.394, 28.394, 28.390, 28.388, 28.384, 28.383, 28.380, 28.376, 28.375, 28.372, 28.371, 28.371, 28.368, 28.366, 28.363, 28.363, 28.361, 28.359, 28.358, 28.358, 28.353, 28.354, 28.352, 28.351, 28.350, 28.350, 28.136, 28.349, 28.348, 28.346, 28.346, 28.346, 28.345, 28.343, 28.340, 28.340, 28.340, 28.339, 28.339, 28.336, 28.334, 28.333, 28.332, 28.331, 28.329, 28.329, 28.328, 28.328, 28.325, 28.323, 28.324, 28.321, 28.319, 28.318, 28.318, 28.317, 28.316, 28.315, 28.314, 28.312, 28.311, 28.310, 28.310, 28.307, 28.306, 28.305, 28.304, 28.303, 28.301, 28.301, 28.300, 28.299, 28.298, 28.297, 28.298, 28.294, 28.293, 28.294, 28.293, 28.291, 28.291, 28.289, 28.289, 28.288, 28.286, 28.285, 28.283, 28.284, 28.283, 28.283, 28.282, 28.280, 28.279, 28.277, 28.278, 28.276, 28.274, 28.273, 28.273, 28.273, 28.273, 28.270, 28.269, 28.269, 28.267, 28.266, 28.265, 28.266, 28.265, 28.263, 28.261, 28.261, 28.261, 28.259, 28.259, 28.258, 28.256, 28.256, 28.254, 28.254, 28.251, 28.253, 28.252, 28.252, 28.250, 28.249, 28.246, 28.248, 28.245, 28.245, 28.244, 28.244, 28.240, 28.239, 28.239, 28.238, 28.239, 28.238, 28.237, 28.234, 28.235, 28.234, 28.235, 28.235, 28.233, 28.229, 28.230, 28.226, 28.229, 28.229, 28.226, 28.225, 28.224, 28.225, 28.224, 28.223, 28.223, 28.220, 28.219, 28.218, 28.220, 28.218, 28.217, 28.216, 28.213, 28.213, 28.214, 28.212, 28.214, 28.209, 28.214, 28.208, 28.210, 28.205, 28.205, 28.206, 28.208, 28.203, 28.203, 28.202, 28.202, 28.201, 28.201, 28.201, 28.200, 28.198, 28.194, 28.193, 28.193, 28.199, 28.196, 28.196, 28.195, 28.193, 28.195, 28.189, 28.189, 28.188, 28.188, 28.186, 28.189, 28.186, 28.188, 28.187, 28.188, 28.181, 28.181, 28.181, 28.178, 28.178, 28.178, 28.176, 28.176, 28.176, 28.174, 28.175, 28.174, 28.173, 28.173, 28.172, 28.170, 28.170, 28.172, 28.171, 28.168, 28.168, 28.169, 28.167, 28.168, 28.167, 28.167, 28.164, 28.166, 28.162, 28.165, 28.165, 28.158, 28.157, 28.157, 28.155, 28.159, 28.156, 28.155, 28.156, 28.160, 28.151, 28.155, 28.149, 28.149, 28.155, 28.148, 28.148, 28.152, 28.145, 28.150, 28.150, 28.146, 28.146, 28.144, 28.143, 28.143, 28.142, 28.143, 28.142, 28.142, 28.142, 28.142, 28.136, 28.141, 28.139, 28.138, 28.135, 28.135, 28.138, 28.135, 28.129, 27.728, 28.133, 28.132, 28.132, 28.129, 28.131, 28.131, 28.129, 28.123, 28.122, 28.124, 28.121, 28.119, 28.123, 28.118, 28.125, 28.125, 28.116, 28.119, 28.119, 28.113, 28.114, 28.114, 28.114, 28.115, 28.112, 28.113, 28.110, 28.113, 28.108, 28.114, 28.106, 28.106, 28.112, 28.110, 28.112, 28.111, 28.111, 28.109, 28.102, 28.102, 28.098, 28.108, 28.109, 28.100, 28.107, 28.102, 28.106, 28.105, 28.105, 28.096, 28.095, 28.091, 28.095, 28.092, 28.092, 28.092, 28.098, 28.089, 28.091, 28.098, 28.098, 28.090, 28.090, 28.086, 28.086, 28.096, 28.087, 28.092, 28.092, 28.092, 28.092, 28.088, 28.087, 28.084, 28.082, 28.084, 28.088, 28.088, 28.088, 28.088, 28.088, 28.076, 28.087, 28.087, 28.079, 28.087, 28.073, 28.078, 28.083, 28.083, 28.073, 28.081, 28.072, 28.080, 28.071, 28.073, 28.073, 28.072, 28.076, 28.080, 28.072, 28.066, 28.073, 28.078, 28.078, 28.071, 28.071, 28.071, 28.066, 28.066, 28.065, 28.056, 28.069, 28.053, 28.051, 28.061, 28.049, 28.049, 28.049, 28.051, 28.048, 28.048, 28.041, 28.041, 28.041, 28.040, 28.040, 28.041, 28.039, 28.039, 28.026, 28.035, 28.026, 28.026, 28.025, 28.025, 28.032, 28.023, 28.031, 28.021, 28.021, 28.021, 28.020, 28.017, 28.015, 28.017, 28.016 };\n\n/* Wind energy flux, expressed as log of the power in erg/s per 10^6 Msun worth of stars */\nconst double edot_wind_SB99[1000] =\n { 39.937, 39.941, 39.944, 39.948, 39.951, 39.953, 39.957, 39.960, 39.963, 39.966, 39.969, 39.972, 39.975, 39.977, 39.980, 39.983, 39.986, 39.989, 39.991, 39.994, 39.997, 39.999, 40.002, 40.004, 40.006, 40.008, 40.010, 40.012, 40.013, 40.014, 40.015, 40.016, 40.016, 40.016, 40.015, 40.014, 40.012, 40.009, 40.006, 40.001, 39.995, 39.988, 39.980, 39.970, 39.958, 39.943, 39.929, 39.937, 39.949, 39.960, 39.971, 39.991, 40.022, 40.026, 40.026, 40.012, 40.012, 40.011, 40.116, 40.169, 40.215, 40.250, 40.273, 40.298, 40.303, 40.295, 40.288, 40.278, 40.272, 40.243, 40.208, 40.179, 40.154, 40.132, 40.113, 40.087, 40.055, 39.949, 39.898, 39.849, 39.803, 39.750, 39.722, 39.691, 39.649, 39.644, 39.587, 39.595, 39.564, 39.545, 39.541, 39.510, 39.512, 39.453, 39.429, 39.418, 39.393, 39.385, 39.379, 39.350, 39.323, 39.296, 39.260, 39.211, 39.181, 39.169, 39.145, 39.138, 39.146, 38.963, 39.105, 39.091, 39.070, 39.126, 39.017, 38.986, 38.962, 38.918, 38.901, 38.856, 38.788, 38.790, 38.812, 38.819, 38.833, 38.843, 38.837, 38.762, 38.743, 38.723, 38.701, 38.690, 38.684, 38.683, 38.670, 38.663, 38.656, 38.650, 38.629, 38.629, 38.627, 38.629, 38.629, 38.630, 38.633, 38.635, 38.635, 38.635, 38.639, 38.642, 38.645, 38.646, 38.649, 38.650, 38.655, 38.659, 38.662, 38.659, 38.653, 38.638, 38.621, 38.602, 38.580, 38.557, 38.537, 38.514, 38.494, 38.473, 38.453, 38.432, 38.413, 38.396, 38.374, 38.356, 38.341, 38.320, 38.306, 38.285, 38.271, 38.253, 38.239, 38.219, 38.204, 38.188, 38.175, 38.160, 38.142, 38.130, 38.111, 38.101, 38.087, 38.068, 38.058, 38.041, 38.033, 38.017, 38.001, 37.994, 37.975, 37.965, 37.954, 37.942, 37.926, 37.915, 37.905, 37.892, 37.883, 37.865, 37.854, 37.845, 37.835, 37.818, 37.808, 37.798, 37.789, 37.776, 37.762, 37.751, 37.741, 37.731, 37.721, 37.711, 37.695, 37.685, 37.673, 37.660, 37.653, 37.643, 37.635, 37.627, 37.620, 37.601, 37.593, 37.578, 37.566, 37.555, 37.537, 37.525, 37.503, 37.482, 37.471, 37.436, 37.429, 37.393, 37.373, 37.360, 37.347, 37.334, 37.322, 37.310, 37.299, 37.289, 37.279, 37.270, 37.261, 37.251, 37.242, 37.233, 37.223, 37.214, 37.206, 37.198, 37.191, 37.183, 37.175, 37.167, 37.160, 37.152, 37.145, 37.137, 37.129, 37.122, 37.114, 37.107, 37.099, 37.091, 37.084, 37.077, 37.069, 37.061, 37.054, 37.047, 37.039, 37.032, 37.024, 37.017, 37.009, 37.002, 36.995, 36.987, 36.980, 36.973, 36.965, 36.957, 36.950, 36.943, 36.936, 36.928, 36.921, 36.914, 36.906, 36.899, 36.891, 36.884, 36.877, 36.869, 36.862, 36.855, 36.847, 36.839, 36.832, 36.825, 36.817, 36.810, 36.803, 36.796, 36.789, 36.782, 36.775, 36.769, 36.762, 36.755, 36.748, 36.741, 36.735, 36.728, 36.720, 36.715, 36.708, 36.701, 36.695, 36.688, 36.682, 36.675, 36.668, 36.663, 36.656, 36.650, 36.643, 36.637, 36.631, 36.624, 36.618, 36.612, 36.606, 36.599, 36.593, 36.587, 36.581, 36.575, 36.569, 36.563, 36.557, 36.550, 36.545, 36.539, 36.533, 36.527, 36.520, 36.515, 36.509, 36.503, 36.497, 36.491, 36.486, 36.480, 36.474, 36.468, 36.463, 36.456, 36.451, 36.445, 36.440, 36.434, 36.429, 36.423, 36.417, 36.412, 36.406, 36.400, 36.395, 36.390, 36.383, 36.378, 36.373, 36.368, 36.362, 36.357, 36.352, 36.346, 36.341, 36.336, 36.330, 36.325, 36.320, 36.314, 36.309, 36.304, 36.299, 36.294, 36.288, 36.283, 36.278, 36.273, 36.268, 36.263, 36.258, 36.253, 36.248, 36.242, 36.238, 36.233, 36.228, 36.223, 36.219, 36.213, 36.208, 36.203, 36.199, 36.194, 36.189, 36.184, 36.180, 36.175, 36.170, 36.165, 36.160, 36.155, 36.151, 36.146, 36.142, 36.136, 36.133, 36.126, 36.122, 36.118, 36.113, 36.109, 36.104, 36.099, 36.095, 36.090, 36.085, 36.080, 36.076, 36.072, 36.067, 36.063, 36.059, 36.054, 36.049, 36.045, 36.039, 36.036, 36.030, 36.027, 36.022, 36.019, 36.013, 36.009, 36.005, 36.000, 35.996, 35.991, 35.987, 35.982, 35.979, 35.973, 35.969, 35.965, 35.960, 35.957, 35.952, 35.948, 35.944, 35.940, 35.936, 35.930, 35.926, 35.922, 35.917, 35.914, 35.909, 35.905, 35.901, 35.897, 35.893, 35.890, 35.884, 35.879, 35.875, 35.870, 35.867, 35.863, 35.859, 35.855, 35.851, 35.846, 35.842, 35.838, 35.834, 35.830, 35.824, 35.822, 35.978, 35.924, 36.029, 35.997, 36.053, 36.025, 36.084, 36.079, 36.087, 36.083, 36.086, 36.083, 36.091, 36.086, 36.094, 36.091, 36.087, 36.084, 36.080, 36.087, 36.079, 36.082, 36.084, 36.076, 36.075, 36.078, 36.076, 36.075, 36.076, 36.067, 36.069, 36.062, 36.062, 36.068, 36.064, 36.057, 36.053, 36.056, 36.052, 36.048, 36.043, 36.045, 36.047, 36.043, 36.039, 36.038, 36.031, 36.032, 36.028, 36.029, 36.023, 36.020, 36.019, 36.022, 36.020, 36.016, 36.015, 36.010, 36.009, 36.007, 36.004, 35.999, 35.997, 35.997, 35.992, 35.989, 35.988, 35.985, 35.985, 35.980, 35.978, 35.975, 35.971, 35.970, 35.965, 35.962, 35.958, 35.957, 35.953, 35.948, 35.947, 35.944, 35.943, 35.942, 35.940, 35.937, 35.933, 35.934, 35.932, 35.930, 35.928, 35.929, 35.923, 35.924, 35.922, 35.921, 35.921, 35.921, 35.395, 35.919, 35.917, 35.916, 35.914, 35.913, 35.912, 35.911, 35.907, 35.907, 35.906, 35.905, 35.906, 35.902, 35.900, 35.898, 35.897, 35.896, 35.893, 35.894, 35.892, 35.892, 35.888, 35.886, 35.887, 35.885, 35.880, 35.880, 35.879, 35.879, 35.878, 35.877, 35.874, 35.873, 35.872, 35.870, 35.871, 35.868, 35.866, 35.866, 35.864, 35.862, 35.860, 35.860, 35.859, 35.858, 35.858, 35.856, 35.857, 35.852, 35.852, 35.852, 35.852, 35.848, 35.850, 35.847, 35.847, 35.846, 35.842, 35.842, 35.839, 35.841, 35.839, 35.840, 35.839, 35.837, 35.836, 35.834, 35.835, 35.831, 35.831, 35.829, 35.830, 35.830, 35.829, 35.825, 35.825, 35.824, 35.822, 35.821, 35.821, 35.822, 35.821, 35.819, 35.817, 35.816, 35.815, 35.814, 35.813, 35.813, 35.810, 35.811, 35.808, 35.808, 35.805, 35.807, 35.806, 35.806, 35.803, 35.803, 35.800, 35.802, 35.799, 35.798, 35.798, 35.798, 35.792, 35.791, 35.791, 35.791, 35.792, 35.790, 35.790, 35.786, 35.788, 35.787, 35.789, 35.788, 35.786, 35.781, 35.781, 35.777, 35.781, 35.781, 35.777, 35.777, 35.775, 35.777, 35.776, 35.774, 35.775, 35.772, 35.770, 35.769, 35.772, 35.769, 35.769, 35.768, 35.764, 35.763, 35.766, 35.763, 35.766, 35.759, 35.766, 35.758, 35.762, 35.755, 35.755, 35.757, 35.760, 35.753, 35.753, 35.753, 35.753, 35.752, 35.752, 35.752, 35.752, 35.748, 35.743, 35.742, 35.742, 35.751, 35.747, 35.747, 35.747, 35.744, 35.747, 35.739, 35.739, 35.738, 35.738, 35.736, 35.740, 35.735, 35.739, 35.739, 35.740, 35.730, 35.731, 35.731, 35.727, 35.727, 35.727, 35.725, 35.725, 35.725, 35.723, 35.724, 35.723, 35.723, 35.723, 35.721, 35.719, 35.719, 35.722, 35.721, 35.717, 35.717, 35.719, 35.717, 35.719, 35.717, 35.717, 35.714, 35.717, 35.712, 35.717, 35.716, 35.705, 35.705, 35.705, 35.703, 35.710, 35.705, 35.705, 35.706, 35.712, 35.700, 35.706, 35.697, 35.697, 35.706, 35.697, 35.697, 35.703, 35.694, 35.701, 35.700, 35.696, 35.696, 35.693, 35.693, 35.693, 35.692, 35.693, 35.692, 35.692, 35.692, 35.692, 35.684, 35.692, 35.689, 35.688, 35.683, 35.683, 35.688, 35.685, 35.677, 34.086, 35.682, 35.683, 35.682, 35.679, 35.682, 35.682, 35.679, 35.671, 35.671, 35.674, 35.670, 35.668, 35.675, 35.667, 35.678, 35.679, 35.666, 35.670, 35.671, 35.663, 35.665, 35.666, 35.666, 35.667, 35.663, 35.666, 35.662, 35.667, 35.660, 35.669, 35.658, 35.659, 35.668, 35.664, 35.667, 35.668, 35.668, 35.665, 35.656, 35.656, 35.651, 35.665, 35.667, 35.655, 35.666, 35.658, 35.664, 35.664, 35.664, 35.650, 35.651, 35.644, 35.651, 35.647, 35.647, 35.647, 35.657, 35.644, 35.647, 35.657, 35.658, 35.647, 35.647, 35.642, 35.642, 35.657, 35.645, 35.652, 35.652, 35.653, 35.653, 35.648, 35.646, 35.642, 35.640, 35.643, 35.649, 35.649, 35.649, 35.650, 35.650, 35.634, 35.650, 35.650, 35.639, 35.651, 35.631, 35.638, 35.645, 35.645, 35.632, 35.644, 35.631, 35.643, 35.631, 35.634, 35.634, 35.633, 35.639, 35.644, 35.634, 35.626, 35.636, 35.644, 35.644, 35.635, 35.635, 35.635, 35.627, 35.628, 35.628, 35.614, 35.633, 35.610, 35.607, 35.623, 35.606, 35.606, 35.606, 35.609, 35.606, 35.606, 35.596, 35.596, 35.596, 35.596, 35.595, 35.597, 35.595, 35.594, 35.577, 35.589, 35.577, 35.577, 35.576, 35.576, 35.587, 35.575, 35.586, 35.573, 35.573, 35.573, 35.572, 35.570, 35.567, 35.571, 35.570 };\n\n/* Cumulative mass lost, expressed as log of the mass in Msun per 10^6\n Msun of stars */\nconst double mass_return_SB99[1000] =\n { 1.743, 2.225, 2.451, 2.600, 2.713, 2.803, 2.879, 2.944, 3.001, 3.053, 3.099, 3.142, 3.181, 3.218, 3.252, 3.284, 3.314, 3.343, 3.370, 3.396, 3.421, 3.445, 3.468, 3.491, 3.512, 3.533, 3.553, 3.572, 3.591, 3.610, 3.628, 3.645, 3.662, 3.679, 3.695, 3.711, 3.727, 3.742, 3.756, 3.771, 3.785, 3.799, 3.812, 3.825, 3.837, 3.849, 3.860, 3.872, 3.885, 3.898, 3.913, 3.928, 3.946, 3.965, 3.985, 4.004, 4.024, 4.053, 4.088, 4.123, 4.159, 4.196, 4.230, 4.261, 4.296, 4.333, 4.366, 4.396, 4.425, 4.450, 4.472, 4.491, 4.508, 4.523, 4.537, 4.551, 4.563, 4.575, 4.586, 4.596, 4.606, 4.616, 4.626, 4.635, 4.645, 4.654, 4.663, 4.672, 4.682, 4.691, 4.700, 4.709, 4.718, 4.726, 4.734, 4.742, 4.749, 4.756, 4.763, 4.770, 4.777, 4.783, 4.789, 4.795, 4.800, 4.806, 4.812, 4.817, 4.822, 4.828, 4.833, 4.837, 4.842, 4.846, 4.850, 4.854, 4.858, 4.862, 4.866, 4.870, 4.873, 4.877, 4.880, 4.884, 4.887, 4.891, 4.894, 4.897, 4.900, 4.904, 4.907, 4.910, 4.913, 4.917, 4.920, 4.923, 4.926, 4.929, 4.932, 4.935, 4.938, 4.941, 4.943, 4.946, 4.949, 4.951, 4.954, 4.956, 4.959, 4.961, 4.964, 4.966, 4.968, 4.971, 4.973, 4.975, 4.978, 4.980, 4.982, 4.984, 4.986, 4.988, 4.990, 4.992, 4.995, 4.996, 4.998, 5.000, 5.002, 5.004, 5.006, 5.008, 5.010, 5.011, 5.013, 5.014, 5.016, 5.017, 5.019, 5.020, 5.022, 5.023, 5.025, 5.026, 5.027, 5.028, 5.030, 5.031, 5.032, 5.033, 5.035, 5.036, 5.037, 5.038, 5.039, 5.040, 5.041, 5.043, 5.044, 5.045, 5.046, 5.047, 5.048, 5.049, 5.050, 5.051, 5.052, 5.053, 5.054, 5.055, 5.056, 5.057, 5.058, 5.059, 5.060, 5.061, 5.062, 5.062, 5.063, 5.064, 5.065, 5.066, 5.067, 5.068, 5.069, 5.070, 5.071, 5.072, 5.072, 5.073, 5.074, 5.075, 5.076, 5.077, 5.078, 5.079, 5.079, 5.080, 5.081, 5.082, 5.083, 5.084, 5.085, 5.085, 5.086, 5.087, 5.088, 5.089, 5.090, 5.090, 5.091, 5.092, 5.093, 5.094, 5.094, 5.095, 5.096, 5.097, 5.098, 5.098, 5.099, 5.100, 5.101, 5.101, 5.102, 5.103, 5.104, 5.104, 5.105, 5.106, 5.107, 5.107, 5.108, 5.109, 5.109, 5.110, 5.111, 5.111, 5.112, 5.113, 5.114, 5.114, 5.115, 5.116, 5.116, 5.117, 5.117, 5.118, 5.119, 5.119, 5.120, 5.121, 5.121, 5.122, 5.122, 5.123, 5.124, 5.124, 5.125, 5.125, 5.126, 5.127, 5.127, 5.128, 5.128, 5.129, 5.130, 5.130, 5.131, 5.131, 5.132, 5.132, 5.133, 5.133, 5.134, 5.135, 5.135, 5.136, 5.136, 5.137, 5.137, 5.138, 5.138, 5.139, 5.139, 5.140, 5.140, 5.141, 5.141, 5.142, 5.142, 5.143, 5.143, 5.144, 5.144, 5.145, 5.145, 5.146, 5.146, 5.147, 5.147, 5.148, 5.148, 5.149, 5.149, 5.150, 5.150, 5.151, 5.151, 5.152, 5.152, 5.152, 5.153, 5.153, 5.154, 5.154, 5.155, 5.155, 5.156, 5.156, 5.156, 5.157, 5.157, 5.158, 5.158, 5.159, 5.159, 5.160, 5.160, 5.160, 5.161, 5.161, 5.162, 5.162, 5.162, 5.163, 5.163, 5.164, 5.164, 5.164, 5.165, 5.165, 5.166, 5.166, 5.166, 5.167, 5.167, 5.168, 5.168, 5.168, 5.169, 5.169, 5.170, 5.170, 5.170, 5.171, 5.171, 5.171, 5.172, 5.172, 5.172, 5.173, 5.173, 5.174, 5.174, 5.174, 5.175, 5.175, 5.175, 5.176, 5.176, 5.176, 5.177, 5.177, 5.177, 5.178, 5.178, 5.179, 5.179, 5.179, 5.180, 5.180, 5.180, 5.181, 5.181, 5.181, 5.182, 5.182, 5.182, 5.183, 5.183, 5.183, 5.184, 5.184, 5.184, 5.184, 5.185, 5.185, 5.185, 5.186, 5.186, 5.186, 5.187, 5.187, 5.187, 5.188, 5.188, 5.188, 5.189, 5.189, 5.189, 5.189, 5.190, 5.190, 5.190, 5.191, 5.191, 5.191, 5.192, 5.192, 5.192, 5.192, 5.193, 5.193, 5.193, 5.194, 5.194, 5.194, 5.194, 5.195, 5.195, 5.195, 5.196, 5.196, 5.196, 5.196, 5.197, 5.197, 5.197, 5.198, 5.198, 5.198, 5.198, 5.199, 5.199, 5.199, 5.199, 5.200, 5.200, 5.200, 5.201, 5.201, 5.201, 5.201, 5.202, 5.202, 5.202, 5.202, 5.203, 5.203, 5.203, 5.203, 5.204, 5.204, 5.204, 5.204, 5.205, 5.205, 5.205, 5.205, 5.206, 5.206, 5.206, 5.206, 5.207, 5.207, 5.207, 5.207, 5.208, 5.208, 5.208, 5.208, 5.209, 5.209, 5.209, 5.209, 5.210, 5.210, 5.210, 5.210, 5.211, 5.211, 5.211, 5.211, 5.212, 5.212, 5.212, 5.212, 5.213, 5.213, 5.213, 5.213, 5.213, 5.214, 5.214, 5.214, 5.214, 5.215, 5.215, 5.215, 5.215, 5.215, 5.216, 5.216, 5.216, 5.216, 5.217, 5.217, 5.217, 5.217, 5.217, 5.218, 5.218, 5.218, 5.218, 5.219, 5.219, 5.219, 5.219, 5.219, 5.220, 5.220, 5.220, 5.220, 5.220, 5.221, 5.221, 5.221, 5.221, 5.222, 5.222, 5.222, 5.222, 5.222, 5.223, 5.223, 5.223, 5.223, 5.223, 5.224, 5.224, 5.224, 5.224, 5.224, 5.225, 5.225, 5.225, 5.225, 5.225, 5.226, 5.226, 5.226, 5.226, 5.226, 5.227, 5.227, 5.227, 5.227, 5.227, 5.228, 5.228, 5.228, 5.228, 5.228, 5.229, 5.229, 5.229, 5.229, 5.229, 5.230, 5.230, 5.230, 5.230, 5.230, 5.231, 5.231, 5.231, 5.231, 5.231, 5.232, 5.232, 5.232, 5.232, 5.232, 5.233, 5.233, 5.233, 5.233, 5.233, 5.234, 5.234, 5.234, 5.234, 5.234, 5.234, 5.235, 5.235, 5.235, 5.235, 5.235, 5.236, 5.236, 5.236, 5.236, 5.236, 5.237, 5.237, 5.237, 5.237, 5.237, 5.237, 5.238, 5.238, 5.238, 5.238, 5.238, 5.239, 5.239, 5.239, 5.239, 5.239, 5.239, 5.240, 5.240, 5.240, 5.240, 5.240, 5.241, 5.241, 5.241, 5.241, 5.241, 5.241, 5.242, 5.242, 5.242, 5.242, 5.242, 5.242, 5.243, 5.243, 5.243, 5.243, 5.243, 5.243, 5.244, 5.244, 5.244, 5.244, 5.244, 5.245, 5.245, 5.245, 5.245, 5.245, 5.245, 5.246, 5.246, 5.246, 5.246, 5.246, 5.246, 5.247, 5.247, 5.247, 5.247, 5.247, 5.247, 5.248, 5.248, 5.248, 5.248, 5.248, 5.248, 5.248, 5.249, 5.249, 5.249, 5.249, 5.249, 5.249, 5.250, 5.250, 5.250, 5.250, 5.250, 5.250, 5.251, 5.251, 5.251, 5.251, 5.251, 5.251, 5.252, 5.252, 5.252, 5.252, 5.252, 5.252, 5.252, 5.253, 5.253, 5.253, 5.253, 5.253, 5.253, 5.254, 5.254, 5.254, 5.254, 5.254, 5.254, 5.254, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255, 5.255 };\n\n/* H ionizing luminosity corresponding to constant star formation at 1\n Msun/yr, expressed in photons / sec (derived from a slug\n calculation at an age of 50 Myr */\nconst double qH0perSFR = 1.57e53;\n\n/* H ionizing luminosity, expressed as log_10 photons per second per 10^6 Msun worth of stars */\nconst double qH0_SB99[1000] =\n { 52.615, 52.615, 52.613, 52.613, 52.613, 52.613, 52.613, 52.614, 52.614, 52.615, 52.615, 52.616, 52.615, 52.614, 52.615, 52.614, 52.614, 52.614, 52.613, 52.612, 52.608, 52.600, 52.603, 52.605, 52.608, 52.609, 52.611, 52.612, 52.615, 52.612, 52.610, 52.596, 52.596, 52.600, 52.601, 52.600, 52.600, 52.600, 52.599, 52.591, 52.586, 52.579, 52.565, 52.550, 52.545, 52.537, 52.525, 52.509, 52.492, 52.467, 52.451, 52.433, 52.407, 52.390, 52.363, 52.341, 52.295, 52.270, 52.303, 52.342, 52.366, 52.385, 52.393, 52.403, 52.401, 52.385, 52.363, 52.351, 52.335, 52.317, 52.303, 52.289, 52.270, 52.247, 52.219, 52.199, 52.186, 52.141, 52.104, 52.089, 52.070, 52.047, 52.037, 52.019, 51.997, 51.984, 51.968, 51.943, 51.923, 51.903, 51.890, 51.865, 51.850, 51.815, 51.769, 51.750, 51.744, 51.720, 51.702, 51.676, 51.672, 51.657, 51.602, 51.570, 51.540, 51.524, 51.496, 51.470, 51.446, 51.422, 51.397, 51.376, 51.359, 51.349, 51.323, 51.285, 51.267, 51.245, 51.226, 51.203, 51.177, 51.150, 51.134, 51.118, 51.095, 51.078, 51.052, 51.031, 51.013, 50.990, 50.970, 50.951, 50.932, 50.911, 50.892, 50.874, 50.856, 50.837, 50.820, 50.800, 50.783, 50.767, 50.745, 50.727, 50.708, 50.690, 50.673, 50.655, 50.640, 50.622, 50.600, 50.583, 50.565, 50.556, 50.541, 50.520, 50.505, 50.491, 50.478, 50.457, 50.442, 50.428, 50.412, 50.395, 50.383, 50.366, 50.354, 50.340, 50.323, 50.312, 50.298, 50.282, 50.272, 50.257, 50.248, 50.237, 50.219, 50.208, 50.198, 50.186, 50.172, 50.160, 50.154, 50.140, 50.128, 50.112, 50.102, 50.087, 50.077, 50.063, 50.054, 50.038, 50.031, 50.019, 50.010, 49.999, 49.993, 49.978, 49.972, 49.956, 49.946, 49.938, 49.926, 49.918, 49.908, 49.899, 49.888, 49.875, 49.869, 49.855, 49.847, 49.835, 49.828, 49.816, 49.804, 49.797, 49.785, 49.770, 49.768, 49.755, 49.748, 49.736, 49.727, 49.721, 49.713, 49.701, 49.694, 49.684, 49.677, 49.666, 49.655, 49.649, 49.638, 49.630, 49.624, 49.613, 49.602, 49.596, 49.587, 49.576, 49.567, 49.560, 49.549, 49.541, 49.531, 49.524, 49.515, 49.510, 49.499, 49.490, 49.479, 49.477, 49.464, 49.453, 49.450, 49.443, 49.431, 49.427, 49.419, 49.411, 49.404, 49.402, 49.391, 49.383, 49.373, 49.370, 49.361, 49.353, 49.344, 49.341, 49.330, 49.322, 49.313, 49.310, 49.302, 49.290, 49.283, 49.280, 49.271, 49.259, 49.253, 49.245, 49.240, 49.233, 49.222, 49.220, 49.209, 49.200, 49.197, 49.188, 49.180, 49.177, 49.166, 49.158, 49.153, 49.149, 49.146, 49.138, 49.132, 49.125, 49.120, 49.114, 49.106, 49.100, 49.097, 49.090, 49.082, 49.077, 49.068, 49.063, 49.055, 49.052, 49.044, 49.039, 49.031, 49.025, 49.024, 49.012, 49.006, 49.002, 48.998, 48.988, 48.985, 48.978, 48.972, 48.967, 48.955, 48.950, 48.949, 48.941, 48.936, 48.929, 48.922, 48.916, 48.912, 48.908, 48.902, 48.896, 48.887, 48.882, 48.880, 48.874, 48.869, 48.860, 48.855, 48.849, 48.846, 48.846, 48.837, 48.837, 48.830, 48.823, 48.821, 48.814, 48.811, 48.804, 48.800, 48.795, 48.789, 48.787, 48.783, 48.778, 48.776, 48.762, 48.766, 48.758, 48.752, 48.749, 48.747, 48.736, 48.735, 48.731, 48.726, 48.720, 48.715, 48.714, 48.709, 48.705, 48.697, 48.695, 48.691, 48.682, 48.681, 48.675, 48.670, 48.664, 48.660, 48.655, 48.649, 48.645, 48.643, 48.638, 48.633, 48.629, 48.624, 48.618, 48.613, 48.607, 48.603, 48.603, 48.597, 48.591, 48.587, 48.583, 48.579, 48.576, 48.569, 48.567, 48.564, 48.557, 48.554, 48.549, 48.544, 48.541, 48.539, 48.533, 48.530, 48.526, 48.525, 48.523, 48.519, 48.513, 48.508, 48.504, 48.499, 48.495, 48.495, 48.491, 48.487, 48.482, 48.481, 48.473, 48.472, 48.464, 48.461, 48.465, 48.458, 48.454, 48.452, 48.445, 48.441, 48.437, 48.432, 48.427, 48.426, 48.419, 48.417, 48.419, 48.415, 48.409, 48.403, 48.399, 48.391, 48.389, 48.384, 48.386, 48.382, 48.377, 48.370, 48.367, 48.364, 48.361, 48.357, 48.353, 48.352, 48.342, 48.343, 48.337, 48.333, 48.329, 48.322, 48.323, 48.315, 48.313, 48.309, 48.305, 48.303, 48.298, 48.293, 48.289, 48.284, 48.284, 48.281, 48.280, 48.277, 48.273, 48.267, 48.270, 48.263, 48.260, 48.256, 48.250, 48.246, 48.244, 48.241, 48.239, 48.236, 48.238, 48.231, 48.229, 48.221, 48.219, 48.216, 48.212, 48.210, 48.206, 48.201, 48.197, 48.198, 48.194, 48.188, 48.190, 48.184, 48.178, 48.175, 48.174, 48.170, 48.164, 48.161, 48.155, 48.157, 48.156, 48.148, 48.151, 48.141, 48.136, 48.133, 48.129, 48.126, 48.122, 48.120, 48.113, 48.113, 48.109, 48.106, 48.103, 48.098, 48.095, 48.091, 48.087, 48.084, 48.076, 48.073, 48.071, 48.068, 48.065, 48.060, 48.056, 48.059, 48.050, 48.047, 48.042, 48.039, 48.033, 48.030, 48.024, 48.024, 48.020, 48.017, 48.011, 48.008, 48.005, 48.003, 48.001, 47.999, 47.993, 47.991, 47.988, 47.989, 47.985, 47.981, 47.978, 47.976, 47.972, 47.968, 47.966, 47.960, 47.954, 47.952, 47.949, 47.944, 47.948, 47.941, 47.938, 47.934, 47.932, 47.928, 47.924, 47.917, 47.914, 47.912, 47.912, 47.906, 47.903, 47.902, 47.898, 47.894, 47.891, 47.888, 47.886, 47.884, 47.878, 47.876, 47.869, 47.867, 47.864, 47.861, 47.857, 47.854, 47.853, 47.847, 47.844, 47.845, 47.841, 47.842, 47.831, 47.827, 47.822, 47.819, 47.812, 47.812, 47.809, 47.806, 47.801, 47.799, 47.797, 47.794, 47.788, 47.786, 47.783, 47.778, 47.774, 47.771, 47.768, 47.761, 47.762, 47.759, 47.753, 47.751, 47.751, 47.746, 47.744, 47.740, 47.734, 47.731, 47.729, 47.723, 47.722, 47.715, 47.712, 47.710, 47.704, 47.707, 47.701, 47.703, 47.695, 47.689, 47.685, 47.685, 47.679, 47.678, 47.680, 47.670, 47.671, 47.668, 47.665, 47.663, 47.662, 47.660, 47.656, 47.651, 47.652, 47.650, 47.647, 47.643, 47.637, 47.636, 47.632, 47.634, 47.626, 47.624, 47.619, 47.618, 47.611, 47.614, 47.613, 47.614, 47.600, 47.602, 47.597, 47.594, 47.592, 47.589, 47.586, 47.588, 47.576, 47.577, 47.572, 47.572, 47.568, 47.566, 47.571, 47.557, 47.556, 47.552, 47.551, 47.546, 47.551, 47.544, 47.540, 47.533, 47.527, 47.528, 47.525, 47.523, 47.516, 47.514, 47.508, 47.508, 47.508, 47.503, 47.500, 47.495, 47.499, 47.495, 47.490, 47.494, 47.486, 47.477, 47.474, 47.470, 47.468, 47.465, 47.462, 47.457, 47.452, 47.449, 47.450, 47.444, 47.444, 47.442, 47.437, 47.437, 47.434, 47.428, 47.426, 47.424, 47.415, 47.416, 47.411, 47.408, 47.402, 47.403, 47.399, 47.389, 47.391, 47.388, 47.377, 47.380, 47.380, 47.377, 47.373, 47.370, 47.367, 47.364, 47.361, 47.359, 47.356, 47.351, 47.344, 47.344, 47.340, 47.338, 47.332, 47.333, 47.331, 47.320, 47.320, 47.319, 47.317, 47.308, 47.306, 47.306, 47.302, 47.295, 47.298, 47.294, 47.292, 47.294, 47.292, 47.284, 47.286, 47.283, 47.280, 47.273, 47.275, 47.280, 47.271, 47.272, 47.264, 47.263, 47.265, 47.263, 47.264, 47.258, 47.253, 47.248, 47.250, 47.242, 47.239, 47.237, 47.230, 47.232, 47.229, 47.222, 47.223, 47.218, 47.225, 47.216, 47.213, 47.210, 47.208, 47.205, 47.199, 47.201, 47.195, 47.193, 47.193, 47.198, 47.188, 47.181, 47.181, 47.178, 47.174, 47.171, 47.171, 47.169, 47.166, 47.168, 47.171, 47.169, 47.154, 47.149, 47.146, 47.143, 47.140, 47.133, 47.134, 47.131, 47.136, 47.122, 47.127, 47.125, 47.120, 47.113, 47.111, 47.111, 47.106, 47.103, 47.107, 47.104, 47.100, 47.100, 47.093, 47.090, 47.087, 47.086, 47.090, 47.081, 47.074, 47.072, 47.075, 47.072, 47.078, 47.065, 47.057, 47.067, 47.065, 47.056, 47.049, 47.044, 47.041, 47.039, 47.039, 47.036, 47.034, 47.028, 47.026, 47.025, 47.022, 47.016, 47.016, 47.016, 47.010, 47.009, 47.006, 47.004, 47.002, 46.997, 46.987, 46.982, 46.979, 46.977, 46.977, 46.974, 46.972, 46.974, 46.972, 46.965, 46.963, 46.964, 46.961, 46.960, 46.952, 46.952, 46.945, 46.943, 46.939, 46.938, 46.935, 46.933, 46.934, 46.929, 46.923, 46.922, 46.923, 46.918, 46.916, 46.913, 46.911, 46.911, 46.905, 46.903, 46.898, 46.894, 46.891, 46.888, 46.887, 46.885, 46.883, 46.876, 46.872, 46.872, 46.866, 46.864, 46.862, 46.860, 46.858, 46.854, 46.850, 46.845, 46.843, 46.840, 46.836, 46.829, 46.827, 46.826, 46.829, 46.825, 46.826, 46.824, 46.824, 46.822, 46.819, 46.831, 46.828, 46.814, 46.812, 46.808, 46.807, 46.807, 46.799, 46.800, 46.800, 46.799, 46.800, 46.795, 46.793, 46.787, 46.786, 46.788, 46.786, 46.792, 46.781, 46.777, 46.775, 46.773, 46.770, 46.772, 46.764, 46.758, 46.760, 46.758, 46.756, 46.749, 46.756, 46.750, 46.772, 46.760, 46.745 };\n\nvoid\nuserEOS(const double t, const double dt, const grid *grd, \n\tconst double *col, const double *pres, const double *eInt,\n\tvoid *params,\n\tdouble *gamma, double *delta) {\n fprintf(stderr, \n\t \"Warning: userEOS function called but not implemented!\\n\");\n return;\n}\n\nvoid\nuserAlpha(const double t, const double dt, const grid *grd, \n\t const double *col, const double *pres, const double *eInt,\n\t const double *gamma, const double *delta,\n\t void *params,\n\t double *alpha) {\n\n gsl_poly_complex_workspace *wksp;\n double coef[6], sol[10];\n double omega, kappa, T1, sigma, kcrit, J, Q, d, tfast, tgrowth;\n unsigned long i, j;\n const int m=2;\n gsl_complex nu2, nu;\n double alphacoef = ((paramType *) params)->alphacoef;\n\n /* Allocate workspace */\n wksp = gsl_poly_complex_workspace_alloc(6);\n\n /* Store the coefficiencts of the dispersion relation polynomial\n that don't change */\n coef[2] = -8.0;\n coef[3] = coef[4] = 0.0;\n\n /* Loop over cells */\n for (i=0; inr; i++) {\n\n /* Handle negative column densities, which may arise if the time\n step overshoots. We just need to make sure the code doesn't\n barf here, as the negative column densities will be fixed by\n the iterative solver. */\n if (col[i] <= 0.0) {\n alpha[i] = ALPHAMIN;\n continue;\n }\n\n /* The various quantities needed for the stability analysis */\n sigma = sqrt(pres[i]/col[i]);\n omega = grd->vphi_g[i+1]/grd->r_g[i+1];\n kappa = sqrt(2.0*(1.0+grd->beta_g[i+1]))*omega;\n T1 = -(2.0*m*omega/(kappa*grd->r_g[i+1])) * \n (2.0*m*omega/(kappa*grd->r_g[i+1])) * (grd->beta_g[i+1]-1);\n kcrit = kappa*kappa / (2.0*M_PI*G*col[i]);\n Q = kappa*sigma / (M_PI*G*col[i]);\n if (Q < 0)\n printf(\"Q < 0! kappa = %f, sigma = %f, col = %f\\n\", kappa, sigma, col[i]);\n J = sqrt(T1)/kcrit;\n \n /* Coefficients of the disperison relation polynomial */\n coef[0] = -Q*Q*Q*Q;\n coef[1] = 6.0*Q*Q;\n coef[5] = 16.0*J*J;\n\n /* Find roots, giving minima and maxima of D; note that we test\n to make sure that the leading coefficient isn't too small,\n which makes the problem ill-conditioned as causes the solver\n to hang. If we detect this happening, we just drop the leading\n coefficient and solve a 4th order polynomial instead of a 5th. */\n if (coef[5] > 1e-30) {\n gsl_poly_complex_solve(coef, 6, wksp, sol);\n } else {\n gsl_poly_complex_solve(coef, 5, wksp, sol);\n }\n\n /* For each root, compute the growth time of the instability */\n tfast = 1.0e30;\n for (j=0; j<5; j++) {\n\n /* Skip roots with negative real part, or imaginary part that is\n\t greater than roundoff */\n if ((sol[2*j] < 0) || (fabs(sol[2*j+1]) > 1.0e-6)) continue;\n\n /* Compute D */\n d = (Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j]) *\n\t(Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j] - \n\t 4.0*J*J*sol[2*j]*sol[2*j]);\n\n /* Ignore stable roots */\n if (d > 0) continue;\n\n /* Get frequency and growth time */\n GSL_SET_COMPLEX(&nu2, \n\t\t 1.0 + 0.5*(Q*Q/(4.0*sol[2*j]*sol[2*j]) - 1.0/sol[2*j]),\n\t\t 0.5 * sqrt(-d));\n nu = gsl_complex_sqrt(nu2);\n tgrowth = 1.0 / (GSL_IMAG(nu)*kappa) / (2.0*M_PI/omega);\n\n /* Store minimum growth time */\n if (tgrowth < tfast) tfast = tgrowth;\n }\n\n /* Now check for gravitational instability */\n if (Q < 1) {\n GSL_SET_COMPLEX(&nu, 0.0, sqrt(1.0/(Q*Q)-1.0));\n tgrowth = 1.0 / (GSL_IMAG(nu)*kappa) / (2.0*M_PI/omega);\n if (tgrowth < tfast) tfast = tgrowth;\n }\n\n /* Compute alpha based on the fastest growing mode timescale */\n alpha[i] = alphacoef * exp(-tfast+1.0);\n if (alpha[i] > 1.0) alpha[i] = 1.0;\n if (alpha[i] < ALPHAMIN) alpha[i] = ALPHAMIN;\n }\n\n /* Free workspace */\n gsl_poly_complex_workspace_free(wksp);\n}\n\nvoid\nuserMassSrc(const double t, const double dt, const grid *grd,\n\t const double *col, const double *pres, const double *eInt,\n\t const double *gamma, const double *delta,\n\t void *params,\n\t double *massSrc) {\n /* Estimate Mdot, including effects of star formation and mass ejection */\n\n long i;\n double *sigma_sfr, *sigma_wind;\n double col_floor = ((paramType *) params)->col_floor;\n\n /* Allocate memory to hold results */\n sigma_sfr = calloc(grd->nr, sizeof(double));\n sigma_wind = calloc(grd->nr, sizeof(double));\n\n /* Get SFR and wind mass flux */\n sfrwind(grd, col, pres, params, sigma_sfr, sigma_wind);\n\n /* Compute mass source term */\n for (i=0; inr; i++) massSrc[i] = -sigma_sfr[i] - sigma_wind[i];\n\n /* Apply absolute floor */\n if (col_floor > 0) {\n for (i=0; inr; i++) {\n massSrc[i] += col_floor / (grd->r_g[i+1]/grd->vphi_g[i+1]) *\n\texp(col_floor/col[i]) / (1.0 + exp(SQR(col[i]/col_floor)));\n }\n }\n \n /* Free memory */\n free(sigma_sfr);\n free(sigma_wind);\n}\n\n\nvoid\nuserIntEnSrc(const double t, const double dt, const grid *grd,\n\t const double *col, const double *pres, const double *eInt,\n\t const double *gamma, const double *delta,\n\t void *params, double *intEnSrc) {\n /* Cooling rate = eta Sigma sigma^2 Omega = eta P vphi/r; heating\n rate from star formation = pdot * sigma / area */\n long i;\n double eta = ((paramType *) params)->eta;\n double sigmath = ((paramType *) params)->sigmath;\n double shapefac = ((paramType *) params)->shapefac;\n double zetad = ((paramType *) params)->zetad;\n double sigma_max = ((paramType *) params)->sigma_max;\n double col_min = ((paramType *) params)->col_min;\n double *pdot = PDOT(params, grd);\n double sigma2, sigmaNT, rhostar, a, b, c, h;\n\n for (i=0; inr; i++) {\n /* Gas velocity dispersion */\n sigma2 = pres[i]/col[i];\n if (sigma2 > SQR(sigmath)) {\n sigmaNT = sqrt(sigma2 - SQR(sigmath));\n /* Stellar density */\n rhostar = shapefac * SQR(grd->vphi_g[i+1]) * \n\t(1.0+2.0*grd->beta_g[i+1]) / \n\t(4.0*M_PI*G*SQR(grd->r_g[i+1]));\n /* Get scale height from OML model */\n if (rhostar > 0.0) {\n\ta = 2.0*M_PI*zetad*G*rhostar*col[i];\n\tb = M_PI/2.0*G*SQR(col[i]);\n\tc = -pres[i];\n\th = (-b + sqrt(b*b-4.0*a*c))/(2.0*a);\n } else {\n\th = pres[i] / (M_PI/2.0*G*SQR(col[i]));\n }\n /* Cooling rate = eta Sigma sigmaNT^2 / (h/sigmaNT) */\n intEnSrc[i] = -eta * col[i] * SQR(sigmaNT) / (h/sigmaNT);\n } else {\n intEnSrc[i] = 0.0;\n }\n\n /* Heating rate = pdot/area * sigma */\n intEnSrc[i] += pdot[i] * sqrt(sigma2) * exp(-col_min/col[i]);\n\n /* Extra cooling in hot cells */\n intEnSrc[i] -= col[i] * SQR(sigmaNT) /\n (grd->r_g[i+1]/grd->vphi_g[i+1]) *\n exp(sigmaNT/sigma_max) / (1.0 + exp(SQR(sigma_max/sigmaNT)));\n }\n}\n\nvoid\nuserIBC(const double t, const double dt, const grid *grd,\n\tconst double *col, const double *pres, const double *eInt,\n\tconst double *gamma, const double *delta,\n\tconst pres_bc_type ibc_pres, const enth_bc_type ibc_enth,\n\tvoid *params, \n\tdouble *ibc_pres_val, double *ibc_enth_val) {\n fprintf(stderr, \n\t \"Warning: userIBC function called but not implemented!\\n\");\n return;\n}\n\nvoid\nuserOBC(const double t, const double dt, const grid *grd,\n\tconst double *col, const double *pres, const double *eInt,\n\tconst double *gamma, const double *delta,\n\tconst pres_bc_type obc_pres, const enth_bc_type obc_enth,\n\tvoid *params, \n\tdouble *obc_pres_val, double *obc_enth_val) {\n fprintf(stderr, \n\t \"Warning: userOBC function called but not implemented!\\n\");\n return;\n}\n\nvoid\nuserPreTimestep(const double t, const double dt,\n\t\tconst grid *grd, double *col, double *pres,\n\t\tdouble *eInt, double *mBnd, double *eBnd,\n\t\tdouble *mSrc, double *eSrc,\n\t\tvoid *params, const unsigned long nUserOut,\n\t\tdouble *userOut) {\n /* We do two things before a time step: (1) record the stellar mass\n at the start of the time step so we can back out the mass lost\n during it; (2) compute and store the current momentum and energy\n injection rate from the stellar population */\n long i, j;\n double p_per_sn = ((paramType *) params)->p_per_sn;\n double e_per_sn = ((paramType *) params)->e_per_sn;\n double star_rad_var = ((paramType *) params)->star_rad_var;\n double *msrc_tmp = MSRC_TMP(params);\n double *pdot = PDOT(params, grd);\n double *edot = EDOT(params, grd);\n double *mdot = MDOT(params, grd);\n double *pdot_tmp, *pdot_tmp1, *edot_tmp, *edot_tmp1,\n *mdot_tmp, *mdot_tmp1;\n double pdot_tot, norm;\n double *Sigmastar = SIGMASTAR(params, grd);\n\n /* Record cumulative mass source term up to this point */\n for (i=0; inr; i++) msrc_tmp[i] = mSrc[i];\n\n /* Compute pdot and edot from star formation */\n pdot_tmp = calloc(grd->nr, sizeof(double));\n edot_tmp = calloc(grd->nr, sizeof(double));\n mdot_tmp = calloc(grd->nr, sizeof(double));\n pdot_tmp1 = calloc(grd->nr, sizeof(double));\n edot_tmp1 = calloc(grd->nr, sizeof(double));\n mdot_tmp1 = calloc(grd->nr, sizeof(double));\n for (i=0; inr; i++)\n injection_rate(Sigmastar+i*nbin_SB99, p_per_sn, e_per_sn,\n\t\t pdot_tmp+i, edot_tmp+i, mdot_tmp+i);\n\n /* Initialize to 0 */\n for (i=0; inr; i++) pdot[i] = edot[i] = mdot[i] = 0.0;\n \n /* Loop over cells to do convolution, being careful to ensure that\n the area-integrated momentum and energy added stays constant */\n for (j=0; jnr; j++) {\n pdot_tot = 0.0;\n for (i=0; inr; i++) {\n pdot_tmp1[i] = exp(-SQR(grd->r_g[i+1]-grd->r_g[j+1]) /\n\t\t\t (2.0*SQR(star_rad_var*grd->r_g[j+1])))\n\t* pdot_tmp[j];\n pdot_tot += pdot_tmp1[i] * grd->area[i];\n edot_tmp1[i] = exp(-SQR(grd->r_g[i+1]-grd->r_g[j+1]) /\n\t\t\t (2.0*SQR(star_rad_var*grd->r_g[j+1])))\n\t* edot_tmp[j];\n mdot_tmp1[i] = exp(-SQR(grd->r_g[i+1]-grd->r_g[j+1]) /\n\t\t\t (2.0*SQR(star_rad_var*grd->r_g[j+1])))\n\t* mdot_tmp[j];\n }\n norm = pdot_tmp[j]*grd->area[j] / (pdot_tot + SMALL);\n for (i=0; inr; i++) {\n pdot[i] += norm * pdot_tmp1[i];\n edot[i] += norm * edot_tmp1[i];\n mdot[i] += norm * mdot_tmp1[i];\n }\n }\n\n /* Free memory */\n free(pdot_tmp);\n free(pdot_tmp1);\n free(edot_tmp);\n free(edot_tmp1);\n free(mdot_tmp);\n free(mdot_tmp1);\n}\n\nvoid\nuserPostTimestep(const double t, const double dt,\n\t\t const grid *grd, double *col, double *pres,\n\t\t double *eInt, double *mBnd, double *eBnd,\n\t\t double *mSrc, double *eSrc,\n\t\t void *params, const unsigned long nUserOut,\n\t\t double *userOut) {\n long i, j;\n long *tctr = &(((paramType *) params)->tctr);\n double *msrc_tmp = MSRC_TMP(params);\n double *Sigmastar = SIGMASTAR(params, grd);\n double *pdot = PDOT(params, grd);\n double *edot = EDOT(params, grd);\n double *mdot = MDOT(params, grd);\n double *Sigmastar_tot = userOut;\n double *Sigmawind_tot = userOut + grd->nr;\n double *pdot_save = userOut + 2*grd->nr;\n double *edot_save = userOut + 3*grd->nr;\n double *sigma_sfr = userOut + 4*grd->nr;\n double *sigma_wind = userOut + 5*grd->nr;\n double *sigma_sfr_obs = userOut + 6*grd->nr;\n double *mdot_save = userOut + 7*grd->nr;\n double d2qdtdA;\n\n /* Safety check */\n assert(nUserOut == 8);\n \n /* Shift bins of star formation history if needed */\n while (t/(dt_SB99*MYR) >= *tctr+1) {\n for (i=0; inr; i++) {\n for (j=nbin_SB99-1; j>0; j--) {\n\tSigmastar[j+i*nbin_SB99] = Sigmastar[j-1+i*nbin_SB99];\n }\n Sigmastar[i*nbin_SB99] = 0.0;\n }\n (*tctr)++;\n }\n\n /* Figure out the current SFR and mass loss rate; we will use these\n to partition the change in mass between new stars and wind */\n sfrwind(grd, col, pres, params, sigma_sfr, sigma_wind);\n\n /* Record stars formed during this timestep in the youngest bin;\n also add to source terms we're tracking */\n for (i=0; inr; i++) {\n Sigmastar[i*nbin_SB99] += (-mSrc[i] + msrc_tmp[i]) *\n sigma_sfr[i] / (sigma_sfr[i] + sigma_wind[i] + SMALL);\n }\n\n /* Save cumulative surface densities of stars formed and wind mass\n lost, and instantaneous momentum injection rate */\n for (i=0; inr; i++) {\n Sigmastar_tot[i] += (-mSrc[i] + msrc_tmp[i]) *\n sigma_sfr[i] / (sigma_sfr[i] + sigma_wind[i] + SMALL);\n Sigmawind_tot[i] += (-mSrc[i] + msrc_tmp[i]) *\n sigma_wind[i] / (sigma_sfr[i] + sigma_wind[i] + SMALL);\n pdot_save[i] = pdot[i];\n edot_save[i] = edot[i];\n mdot_save[i] = mdot[i];\n }\n\n /* Save \"observed\" SFR at this time, i.e., SFR that would be\n inferred from Halpha or similar ionization-based tracer */\n for (i=0; inr; i++) {\n d2qdtdA = 0.0;\n for (j=0; j -29.0) && (Sigmastar[i] > 0.0)) {\n snr += pow(10.0, snr_SB99[i]) * Sigmastar[i]/(1.0e6*MSUN)/YR;\n }\n }\n pdot_sn = snr*p_per_sn;\n edot_sn = snr*e_per_sn;\n\n /* Get wind momentum and energy input rate */\n for (i=0; ishapefac;\n double zetad = ((paramType *) params)->zetad;\n double epsff0 = ((paramType *) params)->epsff0;\n double sigmath = ((paramType *) params)->sigmath;\n double col_min = ((paramType *) params)->col_min;\n double en_wind = ((paramType *) params)->en_wind;\n double *pdot = PDOT(params, grd);\n double *edot = EDOT(params, grd);\n double *mdot = MDOT(params, grd);\n double rhostar, a, b, c, h;\n double rhog, tff, alphavir, epsff;\n double pdotEdd, xcrit, sigma2, mach2, r, sigma_surf2, zeta, vwind;\n\n /* Loop over cells */\n for (i=0; inr; i++) {\n\n /* Stellar density */\n rhostar = shapefac * SQR(grd->vphi_g[i+1]) * \n (1.0+2.0*grd->beta_g[i+1]) / \n (4.0*M_PI*G*SQR(grd->r_g[i+1]));\n \n /* Get scale height from OML model */\n if (rhostar > 0.0) {\n a = 2.0*M_PI*zetad*G*rhostar*col[i];\n b = M_PI/2.0*G*SQR(col[i]);\n c = -pres[i];\n h = (-b + sqrt(b*b-4.0*a*c))/(2.0*a);\n } else {\n h = pres[i] / (M_PI/2.0*G*SQR(col[i]));\n }\n \n /* Gas density and free-fall time */\n rhog = col[i]/(2*h);\n tff = sqrt(3*M_PI/(32*G*rhog));\n \n /* Virial ratio */\n alphavir = pres[i]/(M_PI/2.0*G*col[i]*col[i]*h);\n /*alphavir = tff/(h/sqrt(pres[i]/col[i]));*/\n \n /* epsff */\n epsff = exp(alphavir*log(epsff0));\n /*epsff = exp(sqrt(alphavir)*log(epsff0));*/\n\n /* SFR */\n sigma_SFR[i] = epsff * col[i] / tff;\n\n /* Compute wind using either momentum or energy prescription */\n if (en_wind <= 0.0) {\n\n /* Momentum case */\n \n /* Eddington momentum injection rate */\n /*pdotEdd = 2.0*M_PI*G*col[i]*(col[i]+rhostar*h);*/\n pdotEdd = 2.0*M_PI*G*col[i]*(col[i]+rhostar*grd->r_g[i+1]/shapefac);\n \n /* xcrit */\n xcrit = log(pdot[i]/pdotEdd);\n\n /* Dispersion of surface densities */\n sigma2 = pres[i]/col[i];\n mach2 = sigma2 / SQR(sigmath);\n r = 0.5 * (3.0-2.5)/(2.0-2.5) * (1.0-pow(mach2, 2.0-2.5)) /\n\t(1.0-pow(mach2, 3.0-2.5));\n sigma_surf2 = log(1.0 + r*mach2/4.0);\n\n /* zeta */\n zeta = 0.5*(1.0-erf((-2.0*xcrit+sigma_surf2) / sqrt(8.0*sigma_surf2)));\n\n /* Wind mass flux per unit area, which we take to be zeta *\n\t Sigma_gas / t_dyn, where t_dyn = h / sigma */\n sigma_wind[i] = zeta * col[i] * sqrt(sigma2)/h * exp(-col_min/col[i]);\n\n } else {\n\n /* Energy case */\n\n /* Thermal velocity of hot gas, assuming complete thermalization */\n vwind = sqrt(2.0*edot[i]/(mdot[i]+SMALL));\n\n /* Wind mass launch rate, using Martin 2005 entrainment model */\n sigma_wind[i] = sqrt(3.0*mdot[i]*rhog*vwind);\n\n /*if ((i==285) && (sigma_wind[i] > 1e-16))\n\tprintf(\"sigma_sfr = %e, sigma_wind = %e\\n\", sigma_wind[i], sigma_SFR[i]);*/\n\n }\n }\n}\n\nvoid\nuserCheckRead(\n\t FILE *fp, grid *grd, const unsigned long nOut,\n\t double *tOut, double *colOut,\n\t double *presOut, double *eIntOut, double *mBndOut,\n\t double *eBndOut, double *mSrcOut, double *eSrcOut,\n\t const unsigned long nUserOut, double *userOut,\n\t void *params\n\t ) {\n long *tctr = &(((paramType *) params)->tctr);\n double *Sigmastar = SIGMASTAR(params, grd);\n\n /* Read counter and the age-dependent stellar surface densities */\n fread(tctr, sizeof(long), 1, fp);\n fread(Sigmastar, nbin_SB99*grd->nr, sizeof(double), fp);\n}\n\nvoid\nuserCheckWrite(\n\t FILE *fp,\n\t const grid *grd, const unsigned long nOut,\n\t const double *tOut, const double *colOut,\n\t const double *presOut, const double *eIntOut,\n\t const double *mBndOut, const double *eBndOut,\n\t const double *mSrcOut, const double *eSrcOut,\n\t const unsigned long nUserOut, const double *userOut,\n\t const void *params\n\t ) {\n long *tctr = &(((paramType *) params)->tctr);\n double *Sigmastar = SIGMASTAR(params, grd);\n\n /* Write the counter and the age-dependent stellar surface densities */\n fwrite(tctr, sizeof(long), 1, fp);\n fwrite(Sigmastar, nbin_SB99*grd->nr, sizeof(double), fp); \n}\n", "meta": {"hexsha": "41f43d72dec906e21d51bf4e0a63fd8c4c971bd6", "size": 68764, "ext": "c", "lang": "C", "max_stars_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk2.c", "max_stars_repo_name": "franciscaconcha/amuse-vader", "max_stars_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk2.c", "max_issues_repo_name": "franciscaconcha/amuse-vader", "max_issues_repo_head_hexsha": "646b3136c39da7152c82a032f8151555ec1e3d44", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/amuse/community/vader/src/prob/userFunc_cmzdisk2.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": 107.6118935837, "max_line_length": 8006, "alphanum_fraction": 0.5923157466, "num_tokens": 37948, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672181749421, "lm_q2_score": 0.290980853917813, "lm_q1q2_score": 0.23513208916753633}} {"text": "/**\n * Set of routines to handle absolute flux calibration of a spectrum\n * structure.\n * The response curves can be in ASCII or (preferably) in FITS\n * binary format (first extension). ASCI format is simply three\n * space separated colums (WAVELENGTH, THROUGHPUT, ERROR). The FITS\n * binary table must contain three columns with names WAVELENGTH,\n * SENSITIVITY, ERROR. The throughput should be DN/s per Erg/cm^2/s/A.\n */\n\n\n#include \n#include \n#include \n#include \n\n#include \"aXe_grism.h\"\n#include \"disp_conf.h\"\n#include \"fringe_conf.h\"\n#include \"spc_wl_calib.h\"\n#include \"spc_resp.h\"\n\n#define MIN(x,y) (((x)<(y))?(x):(y))\n#define MAX(x,y) (((x)>(y))?(x):(y))\n\n/**\n * Function: get_response_function_from_FITS\n * This function reads a FITS table, reads the WAVELENGTH,\n * SENSITIVITY, and ERROR columns and returns a spectrum\n * structure which has been populated with this throughput.\n *\n * Parameters:\n * @param filename - a pointer to a char array containing the\n * name of an existing FITS file\n * @param hdunum - the extension number to read (2 for STSDAS tables)\n *\n * Returns:\n * @return res - a pointer to a newly allocated spectrum structure\n */\nspectrum *get_response_function_from_FITS(char filename[], int hdunum)\n{\n fitsfile *input;\n int f_status = 0;\n int hdutype, anynul;\n double *lambda, *resp, *error;\n double tmp;\n long numrows;\n int colnum, i;\n spectrum *res;\n\n // Open the file for reading\n fits_open_file (&input, filename, READONLY, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not open\" \" file: %s\",\n filename);\n }\n /* Move to first hdu */\n fits_movabs_hdu (input, hdunum, &hdutype, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not read extention %d from file: %s\",\n hdunum, filename);\n }\n\n /* Get number of rows */\n fits_get_num_rows (input, &numrows, &f_status);\n if (f_status) {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not determine the number of rows in\"\n \" table %s\",filename);\n }\n\n /* Allocate temporary memory space */\n lambda = (double *) malloc(numrows*sizeof(double));\n if (!lambda) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n \"Memory allocation failed\");\n }\n resp = (double *) malloc(numrows*sizeof(double));\n if (!resp) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n \"Memory allocation failed\");\n }\n error = (double *) malloc(numrows*sizeof(double));\n if (!error) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n \"Memory allocation failed\");\n }\n\n /**************************/\n /* Read the WAVELENGTH column */\n /**************************/\n /* Get column number */\n fits_get_colnum (input, CASEINSEN, \"WAVELENGTH\", &colnum, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not determine WAVELENGTH column number in \"\n \" table %s\",filename);\n }\n\n /* Read the data */\n fits_read_col (input, TDOUBLE, colnum, 1, 1, numrows, NULL, lambda,\n &anynul, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not read content of WAVELENGTH column \"\n \" from BINARY table %s\",filename);\n }\n\n /**************************/\n /* Read the SENSITIVITY column */\n /**************************/\n /* Get column number */\n fits_get_colnum (input, CASEINSEN, \"SENSITIVITY\", &colnum, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not determine SENSITIVITY column number in \"\n \" table %s\",filename);\n }\n /* Read the data */\n fits_read_col (input, TDOUBLE, colnum, 1, 1, numrows, NULL, resp,\n &anynul, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not read content of SENSITIVITY column \"\n \" from BINARY table %s\",filename);\n }\n /**************************/\n /* Read the ERROR column */\n /**************************/\n /* Get column number */\n fits_get_colnum (input, CASEINSEN, \"ERROR\", &colnum, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not determine ERROR column number in \"\n \" table %s\",filename);\n }\n /* Read the data */\n fits_read_col (input, TDOUBLE, colnum, 1, 1, numrows, NULL, error,\n &anynul, &f_status);\n if (f_status)\n {\n ffrprt (stderr, f_status);\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_response_function_fromFITS: \"\n \"Could not read content of ERROR column \"\n \" from BINARY table %s\",filename);\n }\n\n\n /* Allocate memory */\n res = (spectrum *) malloc(sizeof(spectrum));\n if(!res) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n \"Memory allocation failed\");\n }\n res->spec = (spc_entry *) malloc(numrows*sizeof(spc_entry));\n if(!(res->spec)) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n \"Memory allocation failed\");\n }\n\n for (i=0;ispec[i].lambda_mean = lambda[i];\n res->spec[i].flux = resp[i];\n res->spec[i].ferror = error[i];\n }\n\n res->spec_len=i;\n\n // define the minimum and maximum wavelength\n res->lambdamin=res->spec[0].lambda_mean;\n res->lambdamax=res->spec[numrows-1].lambda_mean;\n\n // check whether the wavelength is raising.\n // switch minimum and maximum for falling spectrum\n if (res->lambdamin > res->lambdamax)\n {\n tmp = res->lambdamin;\n res->lambdamin = res->lambdamax;\n res->lambdamax = tmp;\n }\n\n fits_close_file(input,&f_status);\n if (f_status) {\n aXe_message (aXe_M_ERROR, __FILE__, __LINE__,\n \"Could not close %s\",filename);\n }\n\n free(lambda);\n free(resp);\n free(error);\n\n return res;\n}\n\n/**\n * Function: apply_response_function\n * This function applies a thoughput curve to a given spectrum\n * by dividing the count attribute of the spectrum. The flux\n * and ferror attributes of the spectrum are populated.\n * gsl spline interpolation is used to compute the throughput\n * curve at the needed spectral wavelengths.\n *\n * Parameters:\n * @param spec - a pointer to an existing spectrum array\n * @param resp - a pointer to a spectrum structure containing\n * a throughput curve previously loaded\n * @param exptime - the exposure time\n * @param gain - the gain\n *\n * Returns\n * @return -\n */\nvoid\napply_response_function(spectrum *spec, spectrum *resp, const int quant_cont)\n{\n gsl_interp_accel *acc1 = gsl_interp_accel_alloc();\n gsl_spline *spline1 = gsl_spline_alloc (gsl_interp_cspline, resp->spec_len);\n\n gsl_interp_accel *acc2 = gsl_interp_accel_alloc();\n gsl_spline *spline2 = gsl_spline_alloc (gsl_interp_cspline, resp->spec_len);\n\n double *x1,*y1, *x2, *y2;\n int i,j;\n double r1, r2, fr, fr1, fr2;\n double min_l, max_l;\n // test\n // int nguess;\n // double tval=0.0;\n\n if ((int) resp->spec_len <= 0){\n aXe_message(aXe_M_ERROR, __FILE__, __LINE__,\n \"apply_response_function: response spec length invalid: %i\", resp->spec_len);\n gsl_spline_free(spline1);\n gsl_interp_accel_free(acc1);\n gsl_spline_free(spline2);\n gsl_interp_accel_free(acc2);\n return;\n }\n if ( spec==NULL)\n {\n aXe_message (aXe_M_WARN4, __FILE__, __LINE__,\n \"apply_response_function: spectra empty.\");\n gsl_spline_free(spline1);\n gsl_interp_accel_free(acc1);\n gsl_spline_free(spline2);\n gsl_interp_accel_free(acc2);\n return;\n }\n\n x1 = malloc((double)(resp->spec_len) *sizeof(double));\n y1 = malloc((double)(resp->spec_len) *sizeof(double));\n x2 = malloc((double)(resp->spec_len) *sizeof(double));\n y2 = malloc((double)(resp->spec_len) *sizeof(double));\n\n min_l = 1e32;\n max_l = -1e32;\n\n for (i=0;ispec_len; i++) {\n if (resp->spec[i].lambda_mean > max_l) {\n max_l = resp->spec[i].lambda_mean;\n }\n if (resp->spec[i].lambda_mean < min_l) {\n min_l = resp->spec[i].lambda_mean;\n }\n \n x1[i] = resp->spec[i].lambda_mean;\n y1[i] = resp->spec[i].flux - resp->spec[i].ferror;\n x2[i] = resp->spec[i].lambda_mean;\n y2[i] = resp->spec[i].flux + resp->spec[i].ferror;\n }\n\n gsl_spline_init (spline1, x1, y1, resp->spec_len);\n gsl_spline_init (spline2, x2, y2, resp->spec_len);\n // test\n // nguess = 0;\n \n for (j=0; jspec_len; j++) {\n fprintf(stderr,\"%f %f %f\\n\",spec->spec[j].lambda_mean, min_l, max_l);\n if ((spec->spec[j].lambda_mean>=min_l) && (spec->spec[j].lambda_mean <= max_l)) {\n // fprintf(stderr,\"lambda mean between min and max\\n\\t%f : %f %f\\n\", spec->spec[j].lambda_mean, min_l, max_l);\n r1 = gsl_spline_eval(spline1, spec->spec[j].lambda_mean, acc1);\n r2 = gsl_spline_eval(spline2, spec->spec[j].lambda_mean, acc2);\n }\n else {\n r1 = 0;\n r2 = 0;\n }\n\n /* Need to divide by the pixel width of the\n wavelength calibration at the given lambda */\n\n if ((r2+r1)!=0) {\n\n // test\n // spec->spec[j].flux = spec->spec[j].count / tval;\n spec->spec[j].flux = spec->spec[j].count / ((r2+r1)/2.);\n spec->spec[j].flux = spec->spec[j].flux/spec->spec[j].dlambda;\n // fprintf(stdout, \"# %f %f %f\\n\", spec->spec[j].lambda_mean, spec->spec[j].dlambda, spec->spec[j].weight);\n\n\n if (quant_cont && (int)spec->spec[j].contam != -1)\n {\n // test\n // spec->spec[j].contam = spec->spec[j].contam / tval;\n spec->spec[j].contam = spec->spec[j].contam / ((r2+r1)/2.);\n spec->spec[j].contam = spec->spec[j].contam/spec->spec[j].dlambda;\n }\n } else {\n spec->spec[j].flux = GSL_NAN;\n }\n\n fr1 = spec->spec[j].error / spec->spec[j].count; /* frac. error */\n fr2 = fabs((r2-r1)/((r1+r2)/2.0)); /* frac. error in resp. */\n fr = sqrt(fr1*fr1+fr2*fr2);\n spec->spec[j].ferror = fabs(spec->spec[j].flux) * fr;\n }\n\n gsl_spline_free(spline1);\n gsl_interp_accel_free(acc1);\n gsl_spline_free(spline2);\n gsl_interp_accel_free(acc2);\n free(x1);\n free(x2);\n free(y1);\n free(y2);\n\n}\n\n/**\n * Function: apply_response_functionII\n * This function applies a thoughput curve to a given spectrum\n * by dividing the count attribute of the spectrum. The flux\n * and ferror attributes of the spectrum are populated.\n *\n * Parameters:\n * @param spec - a pointer to an existing spectrum array\n * @param resp_func - a pointer to a spectrum structure containing\n * a throughput curve previously loaded\n * @param quant_cont - the exposure time\n *\n * Returns\n * @return -\n */\nvoid\napply_response_functionII(spectrum *spec, response_function *resp_func, const int quant_cont)\n{\n long j;\n double fr, fr1, fr2;\n\n double *resp_vals = malloc( 2 * sizeof(double));\n\n // immediately return\n // an empty spectrum\n if ( spec==NULL)\n {\n aXe_message (aXe_M_WARN4, __FILE__, __LINE__,\n \"apply_response_function: spectra empty.\");\n return;\n }\n\n // go over all elements\n for (j=0;jspec_len;j++)\n {\n // get the sensitivity value plus error\n get_response_values(resp_func, spec->spec[j].lambda_mean, resp_vals);\n\n // make sure you can compute the flux value\n if (resp_vals[0] != 0.0)\n {\n // compute the flux value\n spec->spec[j].flux = spec->spec[j].count / resp_vals[0];\n spec->spec[j].flux = spec->spec[j].flux/spec->spec[j].dlambda;\n\n // compute the flux error\n fr1 = spec->spec[j].error / spec->spec[j].count; /* frac. error */\n fr2 = fabs(resp_vals[1] / resp_vals[0]); /* frac. error in resp. */\n fr = sqrt(fr1*fr1+fr2*fr2);\n spec->spec[j].ferror = fabs(spec->spec[j].flux) * fr;\n\n // check whether the contamination value is necessary\n if (quant_cont && (int)spec->spec[j].contam != -1)\n {\n // compute the contamination value\n spec->spec[j].contam = spec->spec[j].contam / resp_vals[0];\n spec->spec[j].contam = spec->spec[j].contam/spec->spec[j].dlambda;\n }\n }\n else\n {\n // set the flux and the error to NaN\n spec->spec[j].flux = GSL_NAN;\n spec->spec[j].ferror = GSL_NAN;\n }\n }\n\n // free the memory\n free(resp_vals);\n}\n\n/**\n * Function: get_smooth_pars_for_beam\n * The function determines the smoothing parameters for an object beam\n * and a given indicator. If smoothed calibration is requested, the source\n * size (in dispersion direction) is compared to the poin-like object size.\n * For non poin-like objects, the adjustment factor is extracted and\n * the smoothing size from the object is derived.\n *\n * Parameters:\n * @param conf - the configuarion file structure\n * @param smooth_conv - boolean for smooth conversion\n * @param actbeam - the beam to be calibrated\n *\n * Returns\n * @return smooth_pars - the paramters used in the smoothing\n */\nd_point\nget_smooth_pars_for_beam(const aperture_conf *conf, const int smooth_conv, beam actbeam)\n {\n d_point smooth_pars;\n\n // initialize the return\n smooth_pars.x = -1.0;\n smooth_pars.y = -1.0;\n\n // if there is nothing to\n // do, return the default\n if (!smooth_conv)\n return smooth_pars;\n\n // check whether the relevant information\n // does exist\n if (smooth_conv && actbeam.slitgeom[2] < 0.0)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"Smoothed flux conversion is impossible\"\n \" since the OAF\\ndoes not contain the slit width!\\n\");\n\n //fprintf(stdout, \"smoothing factor: %f, point-like size: %f\\n\", conf->smfactor, conf->pobjsize);\n // check whether the objects is smaller than a psf-object\n // in dispersion direction\n if (conf->pobjsize < actbeam.slitgeom[2])\n {\n // compute the smoothing size from the objects;\n // transfer the adjustment factor\n smooth_pars.x = pow((actbeam.slitgeom[2]* actbeam.slitgeom[2]) - (conf->pobjsize*conf->pobjsize), 0.5);\n smooth_pars.y = conf->smfactor;\n }\n\n // return the\n // smoothing parameters\n return smooth_pars;\n }\n\n/**\n * Function: check_conf_for_smoothing\n * The functions checks whether a smoothed flux conversion\n * is possible or not. In case that keywords in the configuration\n * files are missing, it is NOT possible, and 0 is returned.\n *\n * Parameters:\n * @param conf - the configuarion file structure\n * @param smooth_conv - boolean for smooth conversion\n *\n * Returns\n * @return is_possible - the paramters used in the smoothing\n */\nint\ncheck_conf_for_smoothing(const aperture_conf *conf, const int smooth_conv)\n {\n int is_possible=1;\n\n // make sure that, if smoothed covnersion is requested,\n // a point-like objects size and an adjustment factor is defined\n if (smooth_conv && (conf->pobjsize < 0.0 || conf->smfactor < 0.0))\n // change the switch\n is_possible = 0;\n\n // return the pointer\n return is_possible;\n }\n\n/**\n * Function: apply_smoothed_response\n * Convert a spectrum from e/s to flux units in f_lambda. The conversion is done\n * using smoothed sensitivity values that take the object width into account\n * by smoothing the sensitivity function. Gaussian smoothing is applied, taking\n * into account that the original calibration function was derived for a point\n * like object with a finite size.\n *\n * Parameters:\n * @param spec - a pointer to an existing spectrum array\n * @param resp_func - a pointer to a spectrum structure containing\n * a throughput curve\n * @param quant_cont - indicator for quantitative contamination\n * @param bwidth - the B_IMAGE value of the beam\n * @param psf_ext - the width of a point-like object\n * @param wl_calibration - the wavelength calibration structure\n *\n * Returns\n * @return -\n */\nvoid\napply_smoothed_response(const calib_function *wl_calibration, const int for_grism,\n const int quant_cont, response_function *resp_func,\n const d_point smooth_pars, spectrum *spec)\n{\n long j;\n double fr, fr1, fr2;\n //double sigma_wav=10.0;\n\n double *resp_vals = malloc( 2 * sizeof(double));\n //double *tmp_vals = malloc( 2 * sizeof(double));\n\n gsl_vector *weights;\n\n // allocate memory for the vectors\n weights = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);\n\n // immediately return\n // if an empty spectrum\n if ( (spec==NULL) || (spec->spec_len == 0))\n {\n aXe_message (aXe_M_WARN4, __FILE__, __LINE__,\n \"apply_response_function: spectra empty.\");\n return;\n }\n\n // fill the weight vector\n // for smoothing\n fill_weight(weights);\n\n // output to screen\n fprintf(stdout, \"aXe_PET2SPC: Gaussian smoothing in tracelength: %.2f * %.2f = %.2f pix\\n\", smooth_pars.x, smooth_pars.y, smooth_pars.x * smooth_pars.y);\n\n // go over all elements\n for (j=0;jspec_len;j++)\n {\n // get the smoothed sensitivity value plus error\n get_smoothed_response(spec->spec[j].lambda_mean, smooth_pars, wl_calibration,\n for_grism, weights, resp_func, resp_vals);\n // make sure you can compute the flux value\n if (resp_vals[0] != 0.0)\n {\n // compute the flux value\n spec->spec[j].flux = spec->spec[j].count / resp_vals[0];\n spec->spec[j].flux = spec->spec[j].flux/spec->spec[j].dlambda;\n\n // compute the flux error\n fr1 = spec->spec[j].error / spec->spec[j].count; /* frac. error */\n fr2 = fabs(resp_vals[1] / resp_vals[0]); /* frac. error in resp. */\n fr = sqrt(fr1*fr1+fr2*fr2);\n spec->spec[j].ferror = fabs(spec->spec[j].flux) * fr;\n\n // check whether the contamination value is necessary\n if (quant_cont && (int)spec->spec[j].contam != -1)\n {\n // compute the contamination value\n spec->spec[j].contam = spec->spec[j].contam / resp_vals[0];\n spec->spec[j].contam = spec->spec[j].contam/spec->spec[j].dlambda;\n }\n }\n else\n {\n // set the flux and the error to NaN\n spec->spec[j].flux = GSL_NAN;\n spec->spec[j].ferror = GSL_NAN;\n }\n }\n\n // free the memory\n free(resp_vals);\n gsl_vector_free(weights);\n}\n\n/**\n * Function: find_wavelength\n * For a given trace-length value, the function returns the difference\n * between the actual and the targeted wavelength.\n * The function is designed t be called by a gsl root-solving procedure.\n *\n * Parameters:\n * @param x - guess value for the tracelength\n * @param params - structure with input parameters\n *\n * Returns\n * @return wav_zero - difference between actual and targeted wavelength\n */\ndouble\nfind_wavelength(double x, void *params)\n {\n double wav_zero;\n\n // extract the components from the parameter-structure\n const calib_function *wl_calib = ((trlength_search *) params)->wl_calibration;\n double wavelength = ((trlength_search *) params)->wavelength;\n\n // compute the function value\n wav_zero = wl_calib->func (x, wl_calib->order, wl_calib->coeffs) - wavelength;\n\n // return the function value\n return wav_zero;\n }\n\n/**\n * Function: get_tlength_prismwav\n * The function determines the tracelength value for a given wavelength\n * value and dispersion function. Should be called only for a prism dispersion.\n * The gsl root solver is used.\n *\n * Parameters:\n * @param wavelength - the wavelength value\n * @param wl_calibration - the dispersion solution\n *\n * Returns\n * @return wav_zero - difference between actual and targeted wavelength\n */\ndouble\nget_tlength_prismwav(const double wavelength, const calib_function *wl_calibration)\n{\n int iter=0;\n int status;\n\n d_point x_interv;\n\n double tr_length=0.0;\n\n\n // define and initialize the solver\n const gsl_root_fsolver_type *T = gsl_root_fsolver_brent;\n gsl_root_fsolver *s = gsl_root_fsolver_alloc (T);\n\n gsl_function F;\n trlength_search *tr_pars;\n\n // allocate and fill the parameters\n tr_pars = (trlength_search *) malloc(sizeof(trlength_search));\n tr_pars->wl_calibration = wl_calibration;\n tr_pars->wavelength = wavelength;\n\n // fille the GSL-function\n F.function = &find_wavelength;\n F.params = tr_pars;\n\n // initialize the intervall variable\n x_interv.x = gsl_vector_get(wl_calibration->pr_range, 0) + wl_calibration->coeffs[0];\n x_interv.y = gsl_vector_get(wl_calibration->pr_range, 1) + wl_calibration->coeffs[0];\n\n // set the boundaries for the solver\n gsl_root_fsolver_set (s, &F, x_interv.x, x_interv.y);\n\n // iterate to find the zeropoint\n do\n {\n // increment the iteration counter\n iter++;\n\n // iterate on the solver\n status = gsl_root_fsolver_iterate (s);\n\n // get a new guess from the solver\n tr_length = gsl_root_fsolver_root (s);\n\n // derive and set new boundaries\n x_interv.x = gsl_root_fsolver_x_lower (s);\n x_interv.y = gsl_root_fsolver_x_upper (s);\n\n // check the accuracy\n status = gsl_root_test_interval (x_interv.x, x_interv.y,\n 0, 0.0001);\n }\n // check for the break condition\n while (status == GSL_CONTINUE && iter < MAX_ITER_TL);\n\n // free the memory\n free(tr_pars);\n\n // free the memory\n gsl_root_fsolver_free (s);\n\n // return the result\n return tr_length;\n}\n\n/**\n * Function: get_tlength_prismwav\n * The function determines the tracelength value for a given wavelength\n * value and dispersion function. Should be called only for a prism dispersion.\n * The gsl root solver is used.\n *\n * Parameters:\n * @param wavelength - the wavelength value\n * @param wl_calibration - the dispersion solution\n * @param for_grism - boolean to indicate grism/prism dispersion solution\n *\n * Returns\n * @return wav_zero - difference between actual and targeted wavelength\n */\ndouble\nget_central_tracelength(const double wavelength, const calib_function *wl_calibration,\n const int for_grism)\n {\n double tl_central=0.0;\n double a, b, c;\n\n // checc whether it's a grism\n if (for_grism)\n {\n // solve a linear dispersion\n if (wl_calibration->order == 1)\n {\n tl_central = (wavelength - wl_calibration->coeffs[0]) / wl_calibration->coeffs[1];\n }\n // solve a quadratic dispersion\n else if (wl_calibration->order == 2)\n {\n // make the quantities\n a = wl_calibration->coeffs[2];\n b = wl_calibration->coeffs[1];\n c = wl_calibration->coeffs[0] - wavelength;\n\n // compute the central tracelength\n //tl_central = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*c);\n tl_central = (-b + sqrt(b*b - 4.0*a*c)) / (2.0*a);\n //fprintf(stdout, \"I should be here... %g %g %g %g\\n\", tl_central, a, b, c);\n }\n else\n {\n // give error message\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"Smoothed flux conversion is impossible for grism \"\n \"data with dispersion solution of order: %i\", wl_calibration->order);\n }\n }\n else\n {\n // use the root finder to get the tace-length value\n // for the given wavelength\n if (isnan(wavelength))\n tl_central = GSL_NAN;\n else\n tl_central = get_tlength_prismwav(wavelength, wl_calibration);\n }\n\n // return the central\n // tracelength value\n return tl_central;\n }\n\n/**\n * Function: get_smoothed_response\n * The function determine a smoothe sensitivity value and its error.\n * Gaussian smoothing is applied, but the Gaussian weights are delivered\n * as a function parameter (for perfomrance reasons). The function detemines\n * the response values over the weight window and then combines these values\n * with the weights to get one weighted sensitivity value at the desired\n * wavelength.\n *\n * Parameters:\n * @param wavelength - the central wavelength\n * @param smooth_pars - the smoothing parameters\n * @param calib_function - the wavelength calibration function\n * @param for_grism - boolean to indicate grism/prism solution\n * @param weights - the weight vector\n * @param resp_func - the response function\n * @param resp_vals - vector for the response values\n *\n * Returns\n * @return -\n */\nvoid\nget_smoothed_response(const double wavelength, const d_point smooth_pars,\n const calib_function *wl_calibration, const int for_grism,\n const gsl_vector *weights, response_function *resp_func, double *resp_vals)\n{\n int j;\n\n double tl_incr;\n double tl_act;\n double tl_central;\n double lambda_act;\n\n gsl_vector *pixvalues;\n gsl_vector *errvalues;\n gsl_vector *pmask;\n\n double *tmp_vals = malloc( 2 * sizeof(double));\n\n // allocate memory for the vectors\n pixvalues = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);\n errvalues = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);\n pmask = gsl_vector_alloc(2 * RESP_SMOOTH_LENGTH + 1);\n\n // set all mask points to zero\n gsl_vector_set_all(pmask, 0.0);\n\n // determine the tracelength value\n tl_central = get_central_tracelength(wavelength, wl_calibration, for_grism);\n\n // determine the wavelength increments\n //wav_incr = (double)RESP_SMOOTH_NSIG * sigma_wav / (double)RESP_SMOOTH_LENGTH;\n tl_incr = smooth_pars.x * smooth_pars.y * (double)RESP_SMOOTH_NSIG / (double)RESP_SMOOTH_LENGTH;\n\n // set the initial wavelength value\n //value = wavelength - sigma_wav * (double)RESP_SMOOTH_NSIG;\n tl_act = tl_central - 1.0 * smooth_pars.x * smooth_pars.y * (double)RESP_SMOOTH_NSIG;\n\n // print the starting and central wavelength\n //fprintf(stdout, \" %.5g < %.5g\",\n // wl_calibration->func(tl_act, wl_calibration->order, wl_calibration->coeffs),\n // wl_calibration->func(tl_central, wl_calibration->order, wl_calibration->coeffs));\n\n // go over the array\n for (j=0; j < (int)pixvalues->size; j++)\n {\n // determine the wavelength value\n lambda_act = wl_calibration->func(tl_act, wl_calibration->order, wl_calibration->coeffs);\n\n // check whether the actual wavelength is inside\n // the defined sensitivity interval\n if (lambda_act < resp_func->xmin || lambda_act > resp_func->xmax)\n {\n // for outside values:\n // set everything to zero\n gsl_vector_set(pixvalues, j, 0.0);\n gsl_vector_set(errvalues, j, 0.0);\n gsl_vector_set(pmask, j, 0.0);\n }\n else\n {\n // for inside values:\n // compute and set the response\n get_response_values(resp_func, lambda_act, tmp_vals);\n gsl_vector_set(pixvalues, j, tmp_vals[0]);\n gsl_vector_set(errvalues, j, tmp_vals[1]);\n gsl_vector_set(pmask, j, 1.0);\n }\n\n // increment trace length\n tl_act += tl_incr;\n }\n // print the ending wavelength\n //fprintf(stdout, \" > %.5g;\", wl_calibration->func(tl_act, wl_calibration->order, wl_calibration->coeffs));\n\n // get the weighted response values\n get_weighted_sensitivity(pixvalues, errvalues, weights, pmask, resp_vals);\n\n // free the memory\n free(tmp_vals);\n gsl_vector_free(pixvalues);\n gsl_vector_free(errvalues);\n gsl_vector_free(pmask);\n}\n\n/**\n * Function: get_weighted_sensitivity\n * Combines the weigh values, the sensitivity and error at the weight point\n * to a single sensitivity value plus error. A mask array defines at which\n * points values do exist.\n *\n * Parameters:\n * @param pixvalues - the central wavelength\n * @param errvalues - the Gaussian sigma used in smoothing\n * @param weights - the weight vector\n * @param pmask - the response function\n * @param resp_vals - vector for the response values\n *\n * Returns\n * @return\n */\nvoid\nget_weighted_sensitivity(const gsl_vector *pixvalues, const gsl_vector *errvalues, const gsl_vector *weights,\n const gsl_vector *pmask, double *resp_vals)\n{\n int index;\n\n // initialize the total\n // sum and weight\n double val_sum = 0.0;\n double err_sum = 0.0;\n double www=0.0;\n\n // go over all indices of an array\n for (index=0; index < (int)pixvalues->size; index ++)\n {\n // check whether the index is masked\n if (gsl_vector_get(pmask, index) != 0.0)\n {\n // enhance the total sum\n val_sum += gsl_vector_get(pixvalues, index) * gsl_vector_get(weights, index);\n err_sum += gsl_vector_get(errvalues, index) * gsl_vector_get(errvalues, index)\n * gsl_vector_get(weights, index) * gsl_vector_get(weights, index);\n\n // enhance the total weight\n www += gsl_vector_get(weights, index);\n }\n }\n\n // check whether there\n // were weights at all\n if (www)\n {\n // return the total sum,\n // divided by the total weight\n resp_vals[0] = val_sum / www;\n resp_vals[1] = sqrt(err_sum) / www;\n }\n else\n {\n // set zero sensitivity\n resp_vals[0] = 0.0;\n resp_vals[1] = 0.0;\n }\n}\n\n/**\n * Function: fill_weight\n * The function fills an array with Gaussian values.\n * The number of points and the extend are all defined in\n * global variables in the h-file.\n *\n * Parameters:\n * @param weights - the weight vector\n *\n * Returns\n * @return -\n */\nvoid\nfill_weight(gsl_vector *weights)\n{\n int j;\n\n double d_incr;\n double value;\n\n // determine the increments\n d_incr = (double)RESP_SMOOTH_NSIG / (double)RESP_SMOOTH_LENGTH;\n\n // compute the initial exponent\n // go over the weights vector\n value = -(double)RESP_SMOOTH_NSIG;\n for (j=0; j < (int)weights->size; j++)\n {\n // compute and set the weight\n gsl_vector_set(weights, j, exp(-1.0*value * value));\n\n // increment the exponent\n value += d_incr;\n }\n}\n\n/**\n * Function: get_troughput_table_name\n * Parses a configuration file and get the name of the SENSITIVITY\n * curve defined for a wanted beamID\n *\n * Parameters:\n * @param filename - a pointer to a string containing the name of the\n * configuration file\n * @param beamID - the beam ID number (see BEAM())\n * @param table_name - a pointer pointing to a string to contain the name\n * of the file.\n *\n * Returns:\n * @return -\n */\nvoid\nget_troughput_table_name(char *filename, int beamID, char *table_name)\n{\n char beam[MAXCHAR];\n char name[MAXCHAR];\n int i=0;\n\n struct CfgStrings ThrConfig[] = {\n {NULL, NULL},\n {NULL,NULL}\n };\n ThrConfig[0].name = beam;\n sprintf (beam, \"SENSITIVITY_%c\", BEAM(beamID));\n\n CfgRead (filename, ThrConfig);\n if ((ThrConfig[0].name == beam) && (ThrConfig[0].data != NULL))\n {\n strcpy(name,ThrConfig[0].data);\n } else {\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"get_throughput_table_name: %s was not found in \"\n \"%s\",beam,filename);\n }\n\n // release memory\n i=0;\n while(ThrConfig[i].name!=NULL)\n free(ThrConfig[i++].data);\n\n strcpy(table_name,name);\n}\n\n/**\n * Function: get_response_value_plus\n * The function determines the sensitivity at a given wavelength\n * in a sensitivity curve. A guess value helps to start searching\n * around the estimated position of the wavelength in the vector\n * of the sensitifity curve. This should considerably speed up the\n * code. the guess value is updated in case that a sensitivity\n * value could be determined. The return value is interpolated\n * between the adjacent tabulated values.\n *\n * Parameters:\n * @param resp - the sensitivity spectrum\n * @param wavelength - the wavelength to determine the sensitivity for\n * @param nguess - the guess value for the array to start searching from\n *\n * Returns:\n * @return ret - the sensitivity value at the input wavelength\n */\ndouble\nget_response_value_plus(const spectrum *resp, const double wavelength,\n int *nguess)\n{\n double ret;\n double factor;\n\n int nact;\n\n // check whether the wavelength is within the range of\n //the sensitivity curve return GSL_NAN if not\n if (wavelength < resp->lambdamin || wavelength > resp->lambdamax)\n return GSL_NAN;\n\n // check whether you have to search upwards or downwards\n if (wavelength >= resp->spec[*nguess].lambda_mean)\n {\n\n // in case that you search upwards, go up\n // the spectrum until you find the right interval\n nact = *nguess + 1;\n while(wavelength > resp->spec[nact].lambda_mean)\n nact++;\n }\n else\n {\n\n // in case that you search upwards, go up\n // the spectrum until you find the right interval\n nact = *nguess;\n while(wavelength < resp->spec[nact-1].lambda_mean)\n nact--;\n }\n\n // interpolate within the interval to calculate the\n // sensitivity\n factor = (wavelength - resp->spec[nact-1].lambda_mean) /\n (resp->spec[nact].lambda_mean - resp->spec[nact-1].lambda_mean);\n ret = resp->spec[nact-1].flux + factor * (resp->spec[nact].flux - resp->spec[nact-1].flux);\n\n // update the guess value\n *nguess = nact;\n\n // return the sensitivity value\n return ret;\n}\n\n/**\n * Function: get_response_values\n * The function evaluates the response function at the desired\n * independent value. The sensitivity and it error are returned\n * in an array parameter.\n *\n * Parameters:\n * @param resp_func - the response function\n * @param wavelength - the independent value\n * @param resp_vals - the dependent value and its error\n *\n * Returns:\n * @return -\n */\nvoid\nget_response_values(response_function *resp_func, double wavelength, double* resp_vals)\n{\n // check whether the independent value is outside the deifned range\n if (wavelength < resp_func->xmin || wavelength > resp_func->xmax)\n {\n // give the default\n // outside values\n resp_vals[0] = 0.0;\n resp_vals[1] = 0.0;\n }\n else\n {\n // get the response value and its error\n resp_vals[0] = eval_interp(resp_func->resp_values, wavelength);\n resp_vals[1] = eval_interp(resp_func->resp_errors, wavelength);\n }\n}\n\n\n/**\n * Function: create_response_function\n * Load the sensitivity file and creates a new response\n * function. Relies heavily on other subroutines\n *\n * Parameters:\n * @param filename - sensitivity file name\n *\n * Returns:\n * @return resp_func - the response function created\n */\nresponse_function *\ncreate_response_function(char *filename)\n{\n response_function *resp_func;\n\n // allocate space for the return structure;\n // complain if this fails\n resp_func = (response_function *)malloc (sizeof (response_function));\n if (resp_func == NULL)\n aXe_message (aXe_M_FATAL, __FILE__, __LINE__,\n \"Could not allocate memory for response function\");\n\n // load the two intgerpolators\n resp_func->resp_values = create_interp_ftable(filename, 2, \"WAVELENGTH\", \"SENSITIVITY\", RESP_FUNC_INTERP_TYPE);\n resp_func->resp_errors = create_interp_ftable(filename, 2, \"WAVELENGTH\", \"ERROR\", RESP_FUNC_INTERP_TYPE);\n\n // transfer the min and max values from the interpolator\n resp_func->xmin = resp_func->resp_values->xmin;\n resp_func->xmax = resp_func->resp_values->xmax;\n\n // return the respons function\n return resp_func;\n}\n\n/**\n * Function: free_response_function\n * Releases the memory allocated in a response function\n *\n * Parameters:\n * @param resp_func - the response function\n *\n * Returns:\n * @return -\n */\nvoid\nfree_response_function(response_function *resp_func)\n{\n // free the two interpolators\n free_interp(resp_func->resp_values);\n free_interp(resp_func->resp_errors);\n\n // free the rest\n free(resp_func);\n\n // set it to NULL\n resp_func = NULL;\n\n}\n\n/**\n * Function: get_calfunc_for_beam\n * The subroutine determines and returns the calibration function\n * for a certain beam and configuration file. The coefficients of\n * the wavelength calibration are evaluated at the position of the\n * beam object.\n *\n * Parameters:\n * @param actbeam - the current beam\n * @param for_grism - indicator for grism or prism dispersion\n * @param CONF_file - full pathname to configuration file\n * @param conf - the configuration structure\n *\n * Returns:\n * @return wl_calibration - the calibration function\n */\ncalib_function *\nget_calfunc_for_beam(const beam actbeam, const int for_grism, char CONF_file[],\n const aperture_conf * conf)\n{\n calib_function *wl_calibration;\n dispstruct *disp;\n d_point pixel;\n\n // get the reference point right\n pixel.x = actbeam.refpoint.x - conf->refx;\n pixel.y = actbeam.refpoint.y - conf->refy;\n\n // get the dispersion structure\n disp = get_dispstruct_at_pos(CONF_file, for_grism, actbeam.ID, pixel);\n\n // transform the dispersion structure into the\n // wavelength calibration\n wl_calibration = create_calib_from_gsl_vector(for_grism, disp->pol);\n if (!for_grism)\n wl_calibration->pr_range = get_prange (CONF_file, actbeam.ID);\n\n // free the whole structure\n free_dispstruct(disp);\n\n // return the wavelength calibration\n return wl_calibration;\n}\n", "meta": {"hexsha": "3c0f327c6ebd65717fc064ee3bbaac5b32d44368", "size": 38060, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/spc_resp.c", "max_stars_repo_name": "sosey/pyaxe", "max_stars_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cextern/src/spc_resp.c", "max_issues_repo_name": "sosey/pyaxe", "max_issues_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cextern/src/spc_resp.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": 31.0693877551, "max_line_length": 155, "alphanum_fraction": 0.645585917, "num_tokens": 9889, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.554470450236115, "lm_q2_score": 0.42250463481418826, "lm_q1q2_score": 0.2342663350922683}} {"text": "/**\n *\n * @file core_dgbtype1cb.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 Azzam Haidar\n * @date 2012-12-15\n * @generated d Tue Jan 7 11:44:49 2014\n *\n **/\n#include \n#include \"common.h\"\n\n//#define AU(m,n) &(A[(m) + LDA*(n)])\n//#define AL(m,n) &(A[(m) + LDA*(n)])\n#define AL(m_, n_) (A + NB + LDA * (n_) + ((m_)-(n_)))\n#define AU(m_, n_) (A + NB + LDA * (n_) + ((m_)-(n_)+NB))\n#define VQ(m) (VQ + (m))\n#define VP(m) (VP + (m))\n#define TAUQ(m) (TAUQ + (m))\n#define TAUP(m) (TAUP + (m))\n\n/***************************************************************************//**\n *\n * @ingroup CORE_double\n *\n * CORE_dgbtype1cb is a kernel that will operate on a region (triangle) of data\n * bounded by st and ed. This kernel eliminate a column by an column-wise\n * annihiliation, then it apply a left+right update on the hermitian triangle.\n * Note that the column to be eliminated is located at st-1.\n *\n * All detail are available on technical report or SC11 paper.\n * Azzam Haidar, Hatem Ltaief, and Jack Dongarra. 2011.\n * Parallel reduction to condensed forms for symmetric eigenvalue problems\n * using aggregated fine-grained and memory-aware kernels. In Proceedings\n * of 2011 International Conference for High Performance Computing,\n * Networking, Storage and Analysis (SC '11). ACM, New York, NY, USA, ,\n * Article 8 , 11 pages.\n * http://doi.acm.org/10.1145/2063384.2063394\n *\n *******************************************************************************\n *\n * @param[in] N\n * The order of the matrix A.\n *\n * @param[in] NB\n * The size of the band.\n *\n * @param[in, out] A\n * A pointer to the matrix A of size (3*NB+1)-by-N.\n *\n * @param[in] LDA\n * The leading dimension of the matrix A. LDA >= max(1,3*NB+1)\n *\n * @param[out] V\n * double array, dimension N if eigenvalue only\n * requested or (LDV*blkcnt*Vblksiz) if Eigenvectors requested\n * The Householder reflectors are stored in this array.\n *\n * @param[out] TAU\n * double array, dimension (N).\n * The scalar factors of the Householder reflectors are stored\n * in this array.\n *\n * @param[in] st\n * A pointer to the start index where this kernel will operate.\n *\n * @param[in] ed\n * A pointer to the end index where this kernel will operate.\n *\n * @param[in] sweep\n * The sweep number that is eliminated. it serve to calculate the\n * pointer to the position where to store the Vs and Ts.\n *\n * @param[in] Vblksiz\n * constant which correspond to the blocking used when applying the Vs.\n * it serve to calculate the pointer to the position where to store the\n * Vs and Ts.\n *\n * @param[in] WANTZ\n * constant which indicate if Eigenvalue are requested or both\n * Eigenvalue/Eigenvectors.\n *\n * @param[in] WORK\n * Workspace of size nb.\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 * TYPE 1-BAND-bidiag Lower/Upper columnwise-Householder\n ***************************************************************************/\nvoid\nCORE_dgbtype1cb(PLASMA_enum uplo, int N, int NB,\n double *A, int LDA,\n double *VQ, double *TAUQ,\n double *VP, double *TAUP,\n int st, int ed, int sweep, int Vblksiz, int WANTZ,\n double *WORK)\n{\n double ctmp;\n int i, len, LDX, lenj;\n int blkid, vpos, taupos, tpos;\n /* find the pointer to the Vs and Ts as stored by the bulgechasing\n * note that in case no eigenvector required V and T are stored\n * on a vector of size N\n * */\n if( WANTZ == 0 ) {\n vpos = ((sweep+1)%2)*N + st;\n taupos = ((sweep+1)%2)*N + st;\n } else {\n findVTpos(N, NB, Vblksiz, sweep, st,\n &vpos, &taupos, &tpos, &blkid);\n }\n\n LDX = LDA-1;\n len = ed-st+1;\n\n if( uplo == PlasmaUpper ) {\n /* ========================\n * UPPER CASE\n * ========================*/\n /* Eliminate the row at st-1 */\n *VP(vpos) = 1.;\n for(i=1; i\n#include \n#include \n\nextern int LDA_INFERENCE_MAX_ITER;\n\nstatic double* scaled_influence = NULL;\n\n// const int TIME = 61;\nconst int TIME = -3;\nconst double PI = 3.141592654;\n\nDEFINE_int32(lda_sequence_max_iter,\n\t 20,\n\t \"The maximum number of iterations.\");\nDEFINE_int32(lda_sequence_min_iter,\n\t 1,\n\t \"The maximum number of iterations.\");\n\nDEFINE_int32(forward_window,\n\t 1,\n\t \"The forward window for deltas. \"\n\t \"If negative, we use a beta with mean \"\n\t \"5.\");\n\nDEFINE_string(normalize_docs,\n\t \"normalize\",\n\t \"Describes how documents's wordcounts \"\n\t \"are considered for finding influence. \"\n\t \"Options are \\\"normalize\\\", \\\"none\\\", \"\n\t \"\\\"occurrence\\\", \\\"log\\\", or \\\"log_norm\\\".\");\n\nDEFINE_int32(save_time,\n\t 1e20,\n\t \"Save a specific time. If -1, save all times.\");\n\nDEFINE_int32(fix_topics,\n\t 0,\n\t \"Fix a set of this many topics. This amounts \"\n\t \"to fixing these topics' variance at 1e-10.\");\n\n\nDECLARE_string(model);\nDECLARE_int32(max_number_time_points);\nDECLARE_double(sigma_d);\nDECLARE_double(sigma_l);\nDECLARE_double(sigma_c);\nDECLARE_double(sigma_cv);\n\n/*\n * populate an LDA model at a particular time point\n *\n */\n\ninf_var* inf_var_alloc(int number_topics,\n\t\t corpus_seq_t* corpus_seq) {\n // Hate to do this, but I had trouble using it before. This should\n // be the first place we use it; otherwise we'll get a sigsev nil.\n if (scaled_influence == NULL) {\n scaled_influence = NewScaledInfluence(FLAGS_max_number_time_points);\n }\n\n inf_var* inf_var_ptr = (inf_var*) malloc(sizeof(inf_var));\n inf_var_ptr->doc_weights = (gsl_matrix**) malloc(sizeof(gsl_matrix*)\n\t\t\t\t\t\t * corpus_seq->len);\n inf_var_ptr->renormalized_doc_weights = (gsl_matrix**) malloc(\n sizeof(gsl_matrix*)\n * corpus_seq->len);\n inf_var_ptr->ntime = corpus_seq->len;\n int i=0;\n for (i=0; i < corpus_seq->len; ++i) {\n corpus_t* corpus = corpus_seq->corpus[i];\n outlog(\"creating matrix. %d %d\", corpus->ndocs, number_topics);\n if (corpus->ndocs == 0) {\n inf_var_ptr->doc_weights[i] = (gsl_matrix*) malloc(sizeof(gsl_matrix));\n inf_var_ptr->doc_weights[i]->size1 = 0;\n inf_var_ptr->doc_weights[i]->size2 = number_topics;\n inf_var_ptr->renormalized_doc_weights[i] = (gsl_matrix*) malloc(sizeof(gsl_matrix));\n inf_var_ptr->renormalized_doc_weights[i]->size1 = 0;\n inf_var_ptr->renormalized_doc_weights[i]->size2 = number_topics;\n } else {\n inf_var_ptr->doc_weights[i] = gsl_matrix_calloc(corpus->ndocs,\n\t\t\t\t\t\t number_topics);\n inf_var_ptr->renormalized_doc_weights[i] = gsl_matrix_calloc(corpus->ndocs,\n\t\t\t\t\t\t\t\t number_topics);\n }\n }\n return inf_var_ptr;\n}\n\nvoid inf_var_free(inf_var* ptr) {\n // TODO.\n}\n\n// Solves the linear system Ax = b for x.\n// Assumes that x is already allocated.\nvoid Solve(gsl_matrix* A,\n\t const gsl_vector* b,\n\t gsl_vector* x) {\n int permutation_sign;\n gsl_permutation* permutation = gsl_permutation_alloc(b->size);\n gsl_linalg_LU_decomp(A, permutation, &permutation_sign);\n gsl_linalg_LU_solve(A, permutation, b, x);\n gsl_permutation_free(permutation);\n}\n\n\n// Find the sums of influence of all documents in advance.\n// g has scores for everything *up to but not including* g.\nvoid InfluenceTotalFixed(lda_seq* seq,\n\t\t const corpus_seq_t* data) {\n gsl_vector* exp_tmp = gsl_vector_alloc(seq->nterms);\n\n for (int k=0; k < seq->ntopics; ++k) {\n\n for (int s=0; s < seq->nseq; ++s) {\n // Pull out elements of g, and make sure to set them to 0!\n gsl_vector_view g = gsl_matrix_column(\n\t seq->influence_sum_lgl[k], s);\n gsl_vector_set_zero(&g.vector);\n\n for (int t=0; t <= s; ++t) {\n\tgsl_vector_view w_phi_l =\n\t gsl_matrix_column(seq->topic[k]->w_phi_l, t);\n\tgsl_vector_memcpy(exp_tmp, &w_phi_l.vector);\n\tgsl_vector_scale(exp_tmp, scaled_influence[s - t]);\n\tgsl_vector_add(&g.vector, exp_tmp);\n }\n }\n }\n gsl_vector_free(exp_tmp);\n}\n\n\nvoid DumpTimeDocTopicStats(const char* root,\n\t\t\t size_t t,\n\t\t\t corpus_t* corpus,\n\t\t\t gsl_matrix** phi) {\n // For all documents, dump the top topics.\n\n char name[400];\n // Dump the top topics for each word.\n sprintf(name, \"%s%ld_doc_term_topics.dat\", root, t);\n FILE* f = fopen(name, \"w\");\n for (unsigned int d=0; d < corpus->ndocs; ++d) {\n gsl_matrix* phi_d = phi[d];\n doc_t* doc = corpus->doc[d];\n for (unsigned int n=0; n < doc->nterms; ++n) {\n \n unsigned int w = doc->word[n];\n\n // First, find the max topic weight.\n unsigned int max_topic_index = 0;\n double max_topic_weight = gsl_matrix_get(phi_d, n, 0);\n for (unsigned int k=0; k < phi_d->size2; ++k) {\n\tdouble phi_d_n_k = gsl_matrix_get(phi_d, n, k);\n\tif (phi_d_n_k > max_topic_weight) {\n\t max_topic_weight = phi_d_n_k;\n\t max_topic_index = k;\n\t}\n }\n\n fprintf(f, \"%d:%d:%.3f\", w, max_topic_index, max_topic_weight);\n \n if (n < doc->nterms - 1) {\n\tfprintf(f, \" \");\n }\n }\n fprintf(f, \"\\n\");\n }\n fclose(f);\n}\n\nvoid PrepareRegressionComponents(\n corpus_t* corpus,\n lda_seq* seq,\n unsigned int k,\n gsl_matrix* W_phi,\n gsl_matrix* W_phi_var,\n gsl_vector* d_phi_var_tmp,\n gsl_vector* response,\n gsl_vector* d_tmp,\n gsl_matrix* dd_tmp,\n gsl_vector* document_weights,\n gsl_matrix* W_phi_tmp,\n gsl_vector* exp_h_tmp) {\n\n // Then left-multiply this by W_phi:\n gsl_blas_dgemv(CblasTrans,\n\t\t 1.0,\n\t\t W_phi,\n\t\t response,\n\t\t 0.0,\n\t\t d_tmp);\n\n // Set up the transformation matrix.\n // First, set up W_phi^T \\Lambda W_phi.\n gsl_matrix_memcpy(W_phi_tmp, W_phi);\n for (unsigned int d=0; d < corpus->ndocs; ++d) {\n gsl_vector_view col = gsl_matrix_column(W_phi_tmp, d);\n gsl_vector_mul(&col.vector, exp_h_tmp);\n }\n\n // Yuck. Maybe we should do this sparsely?\n // Probably won't be too bad, at least for now.\n gsl_blas_dgemm(CblasTrans,\n\t\t CblasNoTrans,\n\t\t 1.0,\n\t\t W_phi_tmp,\n\t\t W_phi,\n\t\t 0.0,\n\t\t dd_tmp);\n\n gsl_blas_dgemv(CblasTrans,\n\t\t 1.0,\n\t\t W_phi_var,\n\t\t exp_h_tmp,\n\t\t 0.0,\n\t\t d_phi_var_tmp);\n\n // Next, add elements to the diagonal of dd_tmp.\n for (unsigned int d=0; d < corpus->ndocs; ++d) {\n double value = gsl_matrix_get(dd_tmp, d, d);\n value += (seq->topic[k]->chain_variance\n\t / (FLAGS_sigma_d * FLAGS_sigma_d));\n // sgerrish: Is this supposed to be multiplied by anything?\n value += gsl_vector_get(d_phi_var_tmp, d);\n gsl_matrix_set(dd_tmp, d, d, value);\n } \n}\n\nvoid SetExpHTmp(lda_seq* seq,\n\t\tconst corpus_seq_t* data,\n\t\tunsigned int t,\n\t\tunsigned int k,\n\t\tunsigned int n,\n\t\tgsl_vector* exp_h_tmp,\n\t\tgsl_vector* zw_tmp,\n\t\tgsl_vector** exp_i_tmp) {\n gsl_vector_set_zero(exp_h_tmp);\n for (int i = t; i < seq->nseq; ++i) {\n gsl_vector_view mean_i_current =\n gsl_matrix_column(seq->topic[k]->e_log_prob, i);\n gsl_vector_view var_i_current =\n gsl_matrix_column(seq->topic[k]->variance, i + 1);\n\n // Set up exp_h_tmp.\n gsl_vector_memcpy(zw_tmp, &var_i_current.vector);\n gsl_vector_sub(zw_tmp, &mean_i_current.vector);\n gsl_vector_scale(zw_tmp, 2.0);\n for (n=0; n < data->nterms; ++n) {\n gsl_vector_set(zw_tmp, n,\n\t\t exp(gsl_vector_get(zw_tmp, n)));\n }\n gsl_vector_scale(zw_tmp,\n\t\t scaled_influence[i - t]\n\t\t * scaled_influence[i - t]);\n gsl_vector_add(exp_h_tmp, zw_tmp);\n \n // Set up exp_i_tmp.\n gsl_vector_memcpy(exp_i_tmp[i], &var_i_current.vector);\n gsl_vector_scale(exp_i_tmp[i], 0.5);\n gsl_vector_sub(exp_i_tmp[i], &mean_i_current.vector);\n for (n=0; n < data->nterms; ++n) {\n gsl_vector_set(exp_i_tmp[i], n,\n\t\t exp(gsl_vector_get(exp_i_tmp[i], n)));\n }\n }\n}\n\ndouble update_inf_var_fixed(lda_seq* seq,\n\t\t\t const corpus_seq_t* data,\n\t\t\t gsl_matrix** phi,\n\t\t\t size_t t,\n\t\t\t const char* root,\n\t\t\t int dump_doc_stats) {\n double lhood = 0.0;\n // Note that we're missing a suspicious factor of -2 on the document\n // weights currently. We won't worry about that for now (since\n // we're still experimenting), but it should soon be fixed.\n corpus_t* corpus = data->corpus[t];\n if (!corpus->ndocs) {\n return lhood;\n }\n inf_var* influence = seq->influence;\n if (t != TIME && 0) {\n return lhood;\n }\n\n // We need access to the following:\n gsl_matrix* documents_topics_t = influence->doc_weights[t];\n gsl_matrix* renormalized_documents_topics_t = influence->renormalized_doc_weights[t];\n\n size_t k;\n\n gsl_matrix* W_phi = gsl_matrix_calloc(\n seq->nterms, corpus->ndocs);\n gsl_matrix* W2_phi2 = gsl_matrix_calloc(\n seq->nterms, corpus->ndocs);\n gsl_matrix* W_phi_var =\n gsl_matrix_calloc(seq->nterms, corpus->ndocs);\n gsl_matrix* W_phi_tmp = gsl_matrix_alloc(\n seq->nterms, corpus->ndocs);\n gsl_matrix* dd_tmp = gsl_matrix_alloc(\n corpus->ndocs, corpus->ndocs);\n gsl_vector* xd_tmp = gsl_vector_calloc(\n corpus->ndocs);\n gsl_vector* yw_tmp = gsl_vector_calloc(\n seq->nterms);\n gsl_vector* zw_tmp = gsl_vector_calloc(\n seq->nterms);\n gsl_vector* terms_inc_tmp = gsl_vector_calloc(\n seq->nterms);\n gsl_vector** exp_i_tmp = new gsl_vector*[seq->nseq];\n for (int i=0; i < seq->nseq; ++i) {\n exp_i_tmp[i] = gsl_vector_calloc(seq->nterms);\n }\n\n int n;\n\n gsl_vector* response = gsl_vector_calloc(seq->nterms);\n gsl_vector* exp_h_tmp = gsl_vector_calloc(seq->nterms);\n gsl_vector* d_tmp = gsl_vector_calloc(corpus->ndocs);\n gsl_vector* d_phi_var_tmp = gsl_vector_calloc(corpus->ndocs);\n\n // assert(post->phi->size2 == documents_topics_t->size2);\n double* total_terms = (double*) malloc(sizeof(double) * corpus->ndocs);\n double* renormalization_totals = (double*) malloc(sizeof(double) * corpus->ndocs);\n for (k=0; k < documents_topics_t->size2; ++k) {\n // Set up W_phi and W_phi_var.\n for (int d=0; d < corpus->ndocs; ++d) {\n doc_t* doc = corpus->doc[d];\n total_terms[d] = 0.0;\n renormalization_totals[d] = 0.0;\n double log_norm_sum = 0.0;\n for (n=0; n < doc->nterms; ++n) {\n\ttotal_terms[d] += doc->count[n];\n\tif (FLAGS_normalize_docs == \"normalize\") {\n\t renormalization_totals[d] = 1.0;\n\t} else if (FLAGS_normalize_docs == \"log\") {\n\t renormalization_totals[d] += log(doc->count[n] + 1);\n\t} else if (FLAGS_normalize_docs == \"log_norm\") {\n\t double weight = log(doc->count[n] / doc->total);\n\t renormalization_totals[d] += weight;\n\t} else if (FLAGS_normalize_docs == \"identity\") {\n\t renormalization_totals[d] += doc->count[n];\n\t} else if (FLAGS_normalize_docs == \"occurrence\") {\n\t renormalization_totals[d] = 1.0;\n\t}\n }\n assert(doc->total == total_terms[d]);\n\n for (n=0; n < doc->nterms; ++n) {\n\t// Phi, for the doc's term n and topic k.\n\tdouble phi_d_n_k = gsl_matrix_get(phi[d], n, k);\n\n\t// This cast should happen automatically because total_terms is a double,\n\t// but we make the cast here to be explicit and to avoid bugs later.\n\tdouble number_terms;\n\tif (FLAGS_normalize_docs == \"normalize\") {\n\t number_terms = ((double) doc->count[n]\n\t\t\t / (double) total_terms[d]);\n\t} else if (FLAGS_normalize_docs == \"log\") {\n\t number_terms = log(doc->count[n] + 1.0);\n\t} else if (FLAGS_normalize_docs == \"log_norm\") {\n\t number_terms = log(doc->count[n] / total_terms[d]);\n\t renormalization_totals[d] += log(doc->count[n] / total_terms[d]);\n\t} else if (FLAGS_normalize_docs == \"identity\") {\n\t number_terms = doc->count[n];\n\t} else if (FLAGS_normalize_docs == \"occurrence\") {\n\t number_terms = ((double) doc->count[n] / (double) total_terms[d]);\n\t assert(doc->count[n] == 1);\n\t} else {\n\t assert(0);\n\t}\n\n\tgsl_matrix_set(W_phi, doc->word[n], d,\n\t\t number_terms * phi_d_n_k);\n\tgsl_matrix_set(W2_phi2, doc->word[n], d,\n\t\t number_terms * number_terms\n\t\t * phi_d_n_k * phi_d_n_k);\n\tgsl_matrix_set(W_phi_var, doc->word[n], d,\n\t\t number_terms * number_terms\n\t\t * (phi_d_n_k - phi_d_n_k * phi_d_n_k));\n }\n }\n\n gsl_vector_view document_weights = gsl_matrix_column(\n documents_topics_t,\n k);\n gsl_vector_view renormalized_document_weights = gsl_matrix_column(\n renormalized_documents_topics_t,\n k);\n assert(seq->topic[k]->e_log_prob->size2 == data->len);\n\n // Now, with w_phi_var, etc. set, determine\n // \\sum_{i=t}^{T-1} r(...) h(t, i)\n SetExpHTmp(seq,\n\t data,\n\t t,\n\t k,\n\t n,\n\t exp_h_tmp,\n\t zw_tmp,\n\t exp_i_tmp);\n\n // Next, set up the weighted response,\n // \\exp_{-m + v / 2) \\circ (m_{t+1} - m_t + v_t}).\n // Here we also subtract the current l's contribution to influence_sum_lgl.\n gsl_vector_view w_phi_l_t = gsl_matrix_column(seq->topic[k]->w_phi_l, t);\n gsl_vector_set_zero(response);\n for (int i = t; i < seq->nseq - 1; ++i) {\n gsl_vector_view total_influence_time_i =\n\tgsl_matrix_column(seq->influence_sum_lgl[k], i);\n gsl_vector_memcpy(zw_tmp, &w_phi_l_t.vector);\n gsl_vector_scale(zw_tmp, scaled_influence[i - t]);\n gsl_vector_sub(&total_influence_time_i.vector, zw_tmp);\n\n // Now, copy this total influence at time i back into zw_tmp.\n gsl_vector_memcpy(zw_tmp, &total_influence_time_i.vector);\n gsl_vector_mul(zw_tmp, exp_i_tmp[i]);\n\n gsl_vector_view mean_i_current =\n\tgsl_matrix_column(seq->topic[k]->e_log_prob, i);\n gsl_vector_view mean_i_next =\n\tgsl_matrix_column(seq->topic[k]->e_log_prob, i + 1);\n gsl_vector_view var_i_current =\n\tgsl_matrix_column(seq->topic[k]->variance, i + 1);\n gsl_vector_memcpy(terms_inc_tmp, &mean_i_next.vector);\n gsl_vector_sub(terms_inc_tmp, &mean_i_current.vector);\n gsl_vector_add(terms_inc_tmp, &var_i_current.vector);\n gsl_vector_sub(terms_inc_tmp, zw_tmp);\n assert(data->nterms == terms_inc_tmp->size);\n gsl_vector_mul(terms_inc_tmp, exp_i_tmp[i]);\n gsl_vector_scale(terms_inc_tmp, scaled_influence[i - t]);\n\n gsl_vector_add(response, terms_inc_tmp);\n }\n\n PrepareRegressionComponents(corpus,\n\t\t\t\tseq,\n\t\t\t\tk,\n\t\t\t\tW_phi,\n\t\t\t\tW_phi_var,\n\t\t\t\td_phi_var_tmp,\n\t\t\t\tresponse,\n\t\t\t\td_tmp,\n\t\t\t\tdd_tmp,\n\t\t\t\t&document_weights.vector,\n\t\t\t\tW_phi_tmp,\n\t\t\t\texp_h_tmp);\n // Finally, solve for the document weights d!\n Solve(dd_tmp,\n\t d_tmp,\n\t &document_weights.vector);\n \n // Keep track of the iteration so we can dump certain stats\n // occasionally (but not always).\n static int dump_count = 0;\n ++dump_count;\n\n if (FLAGS_save_time == t) {\n outlog(\"Updating topic %ld, time %ld.\", k, t);\n char name[400];\n sprintf(name, \"%s%ld_%ld_weighted_document_terms.dat\", root, k, t);\n FILE* f = fopen(name, \"w\");\n params_write_sparse_gsl_matrix(f, \"W_phi\", W_phi);\n fclose(f);\n \n sprintf(name, \"%s%ld_%ld_weighted_document_terms_var.dat\", root, k, t);\n f = fopen(name, \"w\");\n params_write_sparse_gsl_matrix(f, \"W_phi_var\", W_phi_var);\n fclose(f);\n\n sprintf(name, \"%s%ld_%ld_phi.dat\", root, k, t);\n f = fopen(name, \"w\");\n params_write_gsl_matrix(f, \"phi 0\", phi[0]);\n // params_write_gsl_matrix(f, \"phi 2\", phi[1]);\n // params_write_gsl_matrix(f, \"phi 2\", phi[7]);\n fclose(f);\n\n sprintf(name, \"%s%ld_%ld_weighted_document_terms_sq.dat\", root, k, t);\n f = fopen(name, \"w\");\n params_write_sparse_gsl_matrix(f, \"W2_phi2\", W2_phi2);\n fclose(f);\n\n sprintf(name, \"%s%ld_%ld_weighted_response.dat\", root, k, t);\n f = fopen(name, \"w\");\n params_write_gsl_vector_multiline(f, \"weighted_response\", d_tmp);\n fclose(f);\n\n sprintf(name, \"%s%ld_%ld_response.dat\", root, k, t);\n f = fopen(name, \"w\");\n params_write_gsl_vector_multiline(f, \"response\", response);\n fclose(f);\n\n sprintf(name, \"%s%ld_%ld_exp_h.dat\", root, k, t);\n f = fopen(name, \"w\");\n params_write_gsl_vector_multiline(f, \"exp_h\", exp_h_tmp);\n fclose(f);\n\n if (dump_doc_stats || dump_count % 4 == 0) {\n\tsprintf(name, \"%s%ld_%ld_document_document_matrix.dat\", root, k, t);\n\tf = fopen(name, \"w\");\n\tparams_write_gsl_matrix(f, \"document_document_matrix\", dd_tmp);\n\tfclose(f);\n\t\n\tsprintf(name, \"%s%ld_%ld_exp_h.dat\", root, k, t);\n\tf = fopen(name, \"w\");\n\tparams_write_gsl_vector_multiline(f, \"exp_h\", exp_h_tmp);\n\tfclose(f);\n }\n }\n\n if (FLAGS_save_time == -1) {\n // First, dump phi's for the top topics.\n DumpTimeDocTopicStats(root, t, corpus, phi);\n }\n outlog(\"Done updating topic %ld, time %ld.\", k, t);\n\n for (int d = 0; d < document_weights.vector.size; ++d) {\n gsl_vector_set(&renormalized_document_weights.vector, d,\n\t\t vget(&document_weights.vector, d)\n\t\t * renormalization_totals[d]);\n }\n\n // Now copy this and several products to \n // the sslm_var object.\n gsl_vector_view w_phi_l =\n gsl_matrix_column(seq->topic[k]->w_phi_l, t);\n gsl_blas_dgemv(CblasNoTrans,\n\t\t 1.0,\n\t\t W_phi,\n\t\t &document_weights.vector,\n\t\t 0.0,\n\t\t &w_phi_l.vector);\n\n // Copy this value back into lgl.\n for (int i=t; i < seq->nseq - 1; ++i) {\n gsl_vector_view total_influence_time_i = \n\tgsl_matrix_column(seq->influence_sum_lgl[k], i);\n gsl_vector_memcpy(zw_tmp, &w_phi_l.vector);\n gsl_vector_scale(zw_tmp, scaled_influence[i - t]);\n gsl_vector_add(&total_influence_time_i.vector, zw_tmp);\n }\n\n // Keep track of the term we need to add to m_update_coeff.\n gsl_vector_memcpy(terms_inc_tmp, &w_phi_l.vector);\n gsl_vector_mul(terms_inc_tmp, &w_phi_l.vector);\n\n // Copy and square the document weights vector.\n for (int i = 0; i < xd_tmp->size; ++i) {\n double value = gsl_vector_get(&document_weights.vector, i);\n value = value * value + FLAGS_sigma_l * FLAGS_sigma_l;\n gsl_vector_set(xd_tmp, i, value);\n }\n gsl_blas_dgemv(CblasNoTrans,\n\t\t 1.0,\n\t\t W_phi_var,\n\t\t xd_tmp,\n\t\t 0.0,\n\t\t yw_tmp);\n gsl_vector_add(terms_inc_tmp, yw_tmp);\n\n for (int i = 0; i < xd_tmp->size; ++i) {\n gsl_vector_set(xd_tmp, i, FLAGS_sigma_l * FLAGS_sigma_l);\n }\n gsl_blas_dgemv(CblasNoTrans,\n\t\t 1.0,\n\t\t W2_phi2,\n\t\t xd_tmp,\n\t\t 0.0,\n\t\t yw_tmp);\n gsl_vector_add(terms_inc_tmp, yw_tmp);\n \n // Store an update coefficient for the beta updates.\n for (int i = t; i < seq->nseq; ++i) {\n gsl_vector_view m_update_coeff_h =\n\t gsl_matrix_column(seq->topic[k]->m_update_coeff, i);\n if (t == 0) {\n\t gsl_vector_set_zero(&m_update_coeff_h.vector);\n }\n gsl_vector_memcpy(yw_tmp, terms_inc_tmp);\n gsl_vector_scale(yw_tmp, scaled_influence[i - t]);\n gsl_vector_add(&m_update_coeff_h.vector, yw_tmp);\n }\n\n for (int i = t; i < seq->nseq; ++i) {\n gsl_vector_view m_update_coeff_g = \n\t gsl_matrix_column(seq->topic[k]->m_update_coeff_g, i);\n if (t == 0) {\n\t gsl_vector_set_zero(&m_update_coeff_g.vector);\n }\n gsl_vector_memcpy(yw_tmp, &w_phi_l.vector);\n gsl_vector_scale(yw_tmp, scaled_influence[i - t]);\n gsl_vector_add(&m_update_coeff_g.vector, yw_tmp);\n }\n\n for (int i = 0; i < corpus->ndocs; ++i) {\n double value = gsl_vector_get(&document_weights.vector, i);\n\n // While we're here, increment the likelihood.\n lhood += (-(value * value + FLAGS_sigma_l * FLAGS_sigma_l)\n\t\t / (2.0 * FLAGS_sigma_d * FLAGS_sigma_d)\n\t\t - 0.5 * log(2 * PI)\n\t\t - log(FLAGS_sigma_d * FLAGS_sigma_d));\n }\n }\n free(total_terms);\n free(renormalization_totals);\n gsl_matrix_free(W_phi);\n gsl_matrix_free(W_phi_tmp);\n gsl_matrix_free(W2_phi2);\n gsl_matrix_free(W_phi_var);\n gsl_matrix_free(dd_tmp);\n gsl_vector_free(exp_h_tmp);\n gsl_vector_free(response);\n gsl_vector_free(terms_inc_tmp);\n for (int i=0; i < seq->nseq; ++i) {\n gsl_vector_free(exp_i_tmp[i]);\n }\n delete[] exp_i_tmp;\n gsl_vector_free(d_tmp);\n gsl_vector_free(d_phi_var_tmp);\n gsl_vector_free(xd_tmp);\n gsl_vector_free(yw_tmp);\n gsl_vector_free(zw_tmp);\n \n return lhood;\n}\n\n\nvoid make_lda_from_seq_slice(lda* lda_m,\n\t\t\t lda_seq* lda_seq_m,\n\t\t\t int time) {\n // set lda model topics\n // !!! note: we should be able to point to the view...\n\n int k;\n for (k = 0; k < lda_seq_m->ntopics; k++)\n {\n\t // get topic\n\t gsl_vector s =\n\t gsl_matrix_column(lda_seq_m->topic[k]->e_log_prob,\n\t\t\t time).vector;\n\t gsl_vector d =\n\t gsl_matrix_column(lda_m->topics, k).vector;\n\t gsl_blas_dcopy(&s, &d);\n }\n gsl_blas_dcopy(lda_seq_m->alpha, lda_m->alpha);\n }\n\nstatic gsl_matrix* g_alloc(lda_seq* model,\n\t\t\t const corpus_seq_t* data,\n\t\t\t int time) {\n gsl_matrix* g = gsl_matrix_calloc(model->nterms,\n\t\t\t\t model->ntopics);\n double exp_m, m, m_next;\n for (int k = 0; k < model->ntopics; ++k) {\n for (int w=0; w < model->nterms; ++w) {\n\t double variance_first = mget(model->topic[k]->variance, w, time);\n\t double m = mget(model->topic[k]->e_log_prob, w, time);\n\t double m_next;\n\t exp_m = exp(-m + variance_first / 2.0);\n\t gsl_matrix_set(g, w, k,\n\t\t\t(scaled_influence[0]\n\t\t\t * -variance_first\n\t\t\t * exp_m));\n\n\t for (int i=time; i < model->nseq - 1; ++i) {\n\t // This loop is kind of going overboard, but at least we\n\t // do this once per E-M iteration.\n\t double influence_other_times = 0.0;\n\t for (int j = 0; j < i; ++j) {\n\t exp_m = exp(-mget(model->topic[k]->e_log_prob, w, j)\n\t\t\t + mget(model->topic[k]->variance, w, j) / 2.0);\n\t // Note that we skip the other docs in this time period.\n\t // Those get special treatment below. \n\t if (j != time) {\n\t influence_other_times += (\n\t mget(model->topic[k]->w_phi_l, w, j)\n\t\t * scaled_influence[i - j]\n\t\t * exp_m);\n\t }\n\t }\n\n\t m = mget(model->topic[k]->e_log_prob, w, i);\n\t m_next = mget(model->topic[k]->e_log_prob, w, i + 1);\n\t // Increment the current count by this value.\n\t gsl_matrix_set(g, w, k,\n\t\t\t mget(g, w, k) +\n\t\t\t (scaled_influence[i - time]\n\t\t\t * (m_next - m - influence_other_times)));\n\t }\n\t exp_m = exp(-m\n\t\t + mget(model->topic[k]->variance, w, time) / 2.0);\n\t gsl_matrix_set(g, w, k, mget(g, w, k) * exp_m);\n }\n }\n return g;\n}\n\nstatic gsl_matrix* g3_alloc(lda_seq* model,\n\t\t\t const corpus_seq_t* data,\n\t\t\t int time) {\n gsl_matrix* g = gsl_matrix_calloc(model->nterms,\n\t\t\t\t model->ntopics);\n double exp_m, m, m_next, variance, total;\n for (int k = 0; k < model->ntopics; ++k) {\n for (int w=0; w < model->nterms; ++w) {\n\t total = 0.0;\n\t for (int i=time; i < model->nseq - 1; ++i) {\n\t // This loop is kind of going overboard, but at least we\n\t // do this once per E-M iteration.\n\t variance = mget(model->topic[k]->variance, w, i + 1);\n\t m = mget(model->topic[k]->e_log_prob, w, i);\n\t m_next = mget(model->topic[k]->e_log_prob, w, i + 1);\n\t exp_m = exp(-m + variance / 2.0);\n\t total += (scaled_influence[i - time]\n\t\t * exp_m\n\t\t * (m_next - m + variance));\n\t }\n\t gsl_matrix_set(g, w, k, total);\n }\n }\n return g;\n}\n\nstatic gsl_matrix* g4_alloc(lda_seq* model,\n\t\t const corpus_seq_t* data,\n\t\t int time) {\n gsl_matrix* g = gsl_matrix_calloc(model->nterms,\n\t\t\t\t model->ntopics);\n double exp_m, exp_m_scaled, m, total, variance, w_phi_l;\n for (int k = 0; k < model->ntopics; ++k) {\n for (int w=0; w < model->nterms; ++w) {\n\t total = 0.0;\n\t for (int i=time; i < model->nseq - 1; ++i) {\n\t // This loop is kind of going overboard, but at least we\n\t // do this once per E-M iteration.\n\t variance = mget(model->topic[k]->variance, w, i + 1);\n\t m = mget(model->topic[k]->e_log_prob, w, i);\n\t exp_m = exp(-2.0 * m + 2.0 * variance);\n\t exp_m_scaled = exp_m * scaled_influence[i - time];\n\t for (int j=0; j <= i; ++j) {\n\t w_phi_l = mget(model->topic[k]->w_phi_l, w, j);\n\t total += exp_m_scaled * w_phi_l * scaled_influence[i - j];\n\t }\n\t }\n\t gsl_matrix_set(g, w, k, total);\n }\n }\n return g;\n}\n\nstatic gsl_matrix* g5_alloc(lda_seq* model,\n\t\t\t const corpus_seq_t* data,\n\t\t\t int time) {\n gsl_matrix* g = gsl_matrix_calloc(model->nterms,\n\t\t\t\t model->ntopics);\n double exp_m, m, total, variance;\n for (int k = 0; k < model->ntopics; ++k) {\n for (int w=0; w < model->nterms; ++w) {\n\t total = 0.0;\n\t for (int i=time; i < model->nseq - 1; ++i) {\n\t // This loop is kind of going overboard, but at least we\n\t // do this once per E-M iteration.\n\t variance = mget(model->topic[k]->variance, w, i + 1);\n\t m = mget(model->topic[k]->e_log_prob, w, i);\n\t exp_m = exp(-2.0 * m + 2.0 * variance);\n\t total += exp_m * (scaled_influence[i - time]\n\t\t\t * scaled_influence[i - time]);\n\t }\n\t gsl_matrix_set(g, w, k, total);\n }\n }\n return g;\n}\n\n /*\n * compute the likelihood of a sequential corpus under an LDA seq\n * model. return the likelihood bound.\n *\n */\n\nstatic void InferDTMSeq(const int K,\n\t\t\tunsigned int iter,\n\t\t\tunsigned int last_iter,\n\t\t\tconst corpus_seq_t* data,\n\t\t\tgsl_matrix* gammas,\n\t\t\tgsl_matrix* lhoods,\n\t\t\tlda* lda_model,\n\t\t\tlda_post* post,\n\t\t\tlda_seq* model,\n\t\t\tgsl_matrix** suffstats,\n\t\t\tdouble* bound) {\n int doc_index = 0;\n for (int t = 0; t < data->len; t++) {\n // Prepare coefficients for the phi updates. This change is\n // relatively painless.\n make_lda_from_seq_slice(lda_model, model, t);\n int ndocs = data->corpus[t]->ndocs;\n for (int d = 0; d < ndocs; d++) {\n gsl_vector gam = gsl_matrix_row(gammas, doc_index).vector;\n gsl_vector lhood = gsl_matrix_row(lhoods, doc_index).vector;\n post->gamma = &gam;\n post->doc = data->corpus[t]->doc[d];\n post->lhood = &lhood;\n double doc_lhood;\n // For now, only do the standard, phi-based update.\n if (iter == 0) {\n\tdoc_lhood = fit_lda_post(d, t,\n\t\t\t\t post, NULL,\n\t\t\t\t NULL,\n\t\t\t\t NULL,\n\t\t\t\t NULL,\n\t\t\t\t NULL);\n } else {\n\tdoc_lhood = fit_lda_post(d, t, post, model, NULL,\n\t\t\t\t NULL, NULL, NULL);\n }\n if (suffstats != NULL) {\n\tupdate_lda_seq_ss(t,\n\t\t\t data->corpus[t]->doc[d],\n\t\t\t post,\n\t\t\t suffstats);\n }\n *bound += doc_lhood;\n doc_index++;\n }\n }\n}\n\nstatic void InferDIMSeq(const int K,\n\t\t\tunsigned int iter,\n\t\t\tunsigned int last_iter,\n\t\t\tconst char* file_root,\n\t\t\tconst corpus_seq_t* data,\n\t\t\tgsl_matrix* gammas,\n\t\t\tgsl_matrix* lhoods,\n\t\t\tlda* lda_model,\n\t\t\tlda_post* post,\n\t\t\tlda_seq* model,\n\t\t\tgsl_matrix** suffstats,\n\t\t\tdouble* bound) {\n int doc_index = 0;\n for (int t = 0; t < data->len; t++) {\n // Prepare coefficients for the phi updates. This change is\n // relatively painless.\n gsl_matrix* g = g_alloc(model, data, t);\n\n gsl_matrix* g3_matrix = g3_alloc(model, data, t);\n gsl_matrix* g4_matrix = g4_alloc(model, data, t);\n gsl_matrix* g5_matrix = g5_alloc(model, data, t);\n \n make_lda_from_seq_slice(lda_model, model, t);\n int ndocs = data->corpus[t]->ndocs;\n gsl_matrix** phi_t = (gsl_matrix**) malloc(ndocs\n\t\t\t\t\t * sizeof(gsl_matrix*));\n for (int d = 0; d < ndocs; d++) {\n gsl_vector gam = gsl_matrix_row(gammas, doc_index).vector;\n gsl_vector lhood = gsl_matrix_row(lhoods, doc_index).vector;\n post->gamma = &gam;\n post->doc = data->corpus[t]->doc[d];\n post->lhood = &lhood;\n double doc_lhood;\n // For now, only do the standard, phi-based update.\n if (iter == 0) {\n\tdoc_lhood = fit_lda_post(d, t,\n\t\t\t\t post, NULL,\n\t\t\t\t NULL,\n\t\t\t\t NULL,\n\t\t\t\t NULL,\n\t\t\t\t NULL);\n } else {\n\tdoc_lhood = fit_lda_post(d, t, post, model, g,\n\t\t\t\t g3_matrix, g4_matrix, g5_matrix);\n }\n if (suffstats != NULL) {\n\tupdate_lda_seq_ss(t,\n\t\t\t data->corpus[t]->doc[d],\n\t\t\t post,\n\t\t\t suffstats);\n }\n phi_t[d] = gsl_matrix_alloc(post->doc->nterms, K);\n gsl_matrix_view phi_view = gsl_matrix_submatrix(\n post->phi,\n\t0, 0, post->doc->nterms, K);\n gsl_matrix_memcpy(phi_t[d], &phi_view.matrix);\n *bound += doc_lhood;\n doc_index++;\n }\n\n if (t < data->len - 1) {\n if (FLAGS_model == \"fixed\") {\n\tdouble l_bound = update_inf_var_fixed(\n model,\n\t data,\n\t // Also want a copy of phi for each doc.\n\t // Can keep this as a vector for now.\n\t phi_t,\n\t t,\n\t file_root,\n\t last_iter || iter >= FLAGS_lda_sequence_min_iter);\n\t*bound += l_bound;\n }\n }\n\n for (int d=0; d < ndocs; ++d) {\n gsl_matrix_free(phi_t[d]);\n }\n free(phi_t);\n gsl_matrix_free(g);\n gsl_matrix_free(g3_matrix);\n gsl_matrix_free(g4_matrix);\n gsl_matrix_free(g5_matrix);\n }\n}\n\ndouble lda_seq_infer(lda_seq* model,\n\t\t const corpus_seq_t* data,\n\t\t gsl_matrix** suffstats,\n\t\t gsl_matrix* gammas,\n\t\t gsl_matrix* lhoods,\n\t\t unsigned int iter,\n\t\t unsigned int last_iter,\n\t\t const char* file_root) {\n int K = model->ntopics; int W = model->nterms;\n double bound = 0.0;\n lda* lda_model = new_lda_model(K, W);\n lda_post post;\n post.phi = gsl_matrix_calloc(data->max_nterms, K);\n post.log_phi = gsl_matrix_calloc(data->max_nterms, K);\n post.model = lda_model;\n \n if (FLAGS_model == \"fixed\") {\n // First, pre-compute the functions f and g.\n InfluenceTotalFixed(model, data);\n InferDIMSeq(K,\n\t\titer,\n\t\tlast_iter,\n\t\tfile_root,\n\t\tdata,\n\t\tgammas,\n\t\tlhoods,\n\t\tlda_model,\n\t\t&post,\n\t\tmodel,\n\t\tsuffstats,\n\t\t&bound);\n } else if (FLAGS_model == \"dtm\") {\n InferDTMSeq(K,\n\t\titer,\n\t\tlast_iter,\n\t\tdata,\n\t\tgammas,\n\t\tlhoods,\n\t\tlda_model,\n\t\t&post,\n\t\tmodel,\n\t\tsuffstats,\n\t\t&bound);\n } else {\n printf(\"Error. Unknown model.\\n\");\n exit(1);\n }\n\n gsl_matrix_free(post.phi);\n gsl_matrix_free(post.log_phi);\n free_lda_model(lda_model);\n return(bound);\n}\n\n\n /*\n * fit an lda sequence model:\n *\n * . for each time period\n * . set up lda model with E[log p(w|z)] and \\alpha\n * . for each document\n * . perform posterior inference\n * . update sufficient statistics/likelihood\n * .\n * . maximize topics\n *\n */\n\ndouble fit_lda_seq(lda_seq* m, const corpus_seq_t* data,\n\t\t const corpus_seq_t* heldout, const char* file_root) {\n int K = m->ntopics, W = m->nterms;\n int k;\n\n // initialize sufficient statistics\n\n gsl_matrix* topic_suffstats[K];\n for (k = 0; k < K; k++) {\n\t topic_suffstats[k] = gsl_matrix_calloc(W, data->len);\n }\n\n // set up variables\n\n char name[400];\n gsl_matrix* gammas = gsl_matrix_calloc(data->ndocs, K);\n gsl_matrix* lhoods = gsl_matrix_calloc(data->ndocs, K+1);\n gsl_matrix* heldout_gammas = NULL;\n gsl_matrix* heldout_lhoods = NULL;\n if (heldout != NULL)\n {\n\t heldout_gammas = gsl_matrix_calloc(heldout->ndocs, K);\n\t heldout_lhoods = gsl_matrix_calloc(heldout->ndocs, K+1);\n }\n\n double bound = 0, heldout_bound = 0, old_bound;\n double convergence = LDA_SEQ_EM_THRESH + 1;\n\n char root[400];\n sprintf(root, \"%s/lda-seq/\", file_root);\n make_directory(root);\n\n char em_log_filename[400];\n sprintf(em_log_filename, \"%s/em_log.dat\", file_root);\n FILE* em_log = fopen(em_log_filename, \"w\");\n\n // run EM\n\n int iter = 0;\n // LDA_INFERENCE_MAX_ITER = 1;\n short final_iters_flag = 0;\n unsigned int last_iter = 0;\n while (iter < FLAGS_lda_sequence_min_iter ||\n\t ((final_iters_flag == 0 || convergence > LDA_SEQ_EM_THRESH)\n\t && iter <= FLAGS_lda_sequence_max_iter)\n\t && !last_iter) {\n\n\t if (!(iter < FLAGS_lda_sequence_min_iter ||\n\t ((final_iters_flag == 0 || convergence > LDA_SEQ_EM_THRESH)\n\t\t&& iter <= FLAGS_lda_sequence_max_iter))) {\n\t last_iter = 1;\n\t }\n\t outlog(\"\\nEM iter %3d\\n\", iter);\n\t outlog(\"%s\", \"E step\\n\");\n\t fprintf(em_log, \"%17.14e %5.3e\\n\", bound, convergence);\n\n\t old_bound = bound;\n\t gsl_matrix_set_zero(gammas);\n\t gsl_matrix_set_zero(lhoods);\n\t if (heldout != NULL) {\n\t gsl_matrix_set_zero(heldout_gammas);\n\t gsl_matrix_set_zero(heldout_lhoods);\n\t }\n\n\t for (k = 0; k < K; k++) {\n\t gsl_matrix_set_zero(topic_suffstats[k]);\n\t }\n\n\t // compute the likelihood of a sequential corpus under an LDA\n\t // seq model and find the evidence lower bound.\n\t bound = lda_seq_infer(m,\n\t\t\t data,\n\t\t\t topic_suffstats,\n\t\t\t gammas,\n\t\t\t lhoods,\n\t\t\t iter,\n\t\t\t last_iter,\n\t\t\t file_root);\n\t if (heldout != NULL) {\n\t heldout_bound = lda_seq_infer(m,\n\t\t\t\t\t heldout,\n\t\t\t\t\t NULL,\n\t\t\t\t\t heldout_gammas,\n\t\t\t\t\t heldout_lhoods,\n\t\t\t\t\t iter,\n\t\t\t\t\t last_iter,\n\t\t\t\t\t file_root);\n\t }\n\n\t// print out the gammas and likelihoods.\n sprintf(name, \"%s/gam.dat\", root);\n mtx_fprintf(name, gammas);\n sprintf(name, \"%s/lhoods.dat\", root);\n mtx_fprintf(name, lhoods);\n if (heldout != NULL)\n {\n sprintf(name, \"%s/heldout_lhoods.dat\", root);\n mtx_fprintf(name, heldout_lhoods);\n sprintf(name, \"%s/heldout_gam.dat\", root);\n mtx_fprintf(name, heldout_gammas);\n }\n outlog(\"%s\", \"\\nM step\");\n\n\t// fit the variational distribution\n double topic_bnd = fit_lda_seq_topics(m, topic_suffstats);\n bound += topic_bnd;\n\n write_lda_seq(m, root);\n if ((bound - old_bound) < 0)\n {\n if (LDA_INFERENCE_MAX_ITER == 1)\n LDA_INFERENCE_MAX_ITER = 2;\n if (LDA_INFERENCE_MAX_ITER == 2)\n LDA_INFERENCE_MAX_ITER = 5;\n if (LDA_INFERENCE_MAX_ITER == 5)\n LDA_INFERENCE_MAX_ITER = 10;\n if (LDA_INFERENCE_MAX_ITER == 10)\n LDA_INFERENCE_MAX_ITER = 20;\n\n outlog( \"\\nWARNING: bound went down %18.14f; \"\n\t\t \"increasing var iter to %d\\n\",\n bound-old_bound, LDA_INFERENCE_MAX_ITER);\n }\n\n\t// check for convergence\n convergence = fabs((bound - old_bound) / old_bound);\n if (convergence < LDA_SEQ_EM_THRESH) {\n final_iters_flag = 1;\n LDA_INFERENCE_MAX_ITER = 500;\n outlog(\"starting final iterations : max iter = %d\\n\",\n LDA_INFERENCE_MAX_ITER);\n convergence = 1.0;\n }\n outlog(\"\\n(%02d) lda seq bound=% 15.7f; \"\n\t \"heldout bound=% 15.7f, conv=% 15.7e\\n\",\n iter, bound, heldout_bound, convergence);\n iter++;\n }\n return(bound);\n}\n\n\n/*\n * read and write lda sequence variational distribution\n *\n */\n\nvoid write_lda_seq(const lda_seq* model, const char* root) {\n char name[400];\n sprintf(name, \"%sinfo.dat\", root);\n FILE* f = fopen(name, \"w\");\n\n params_write_int(f, \"NUM_TOPICS\", model->ntopics);\n params_write_int(f, \"NUM_TERMS\", model->nterms);\n params_write_int(f, \"SEQ_LENGTH\", model->nseq);\n params_write_gsl_vector(f, \"ALPHA\", model->alpha);\n\n fclose(f);\n\n int k;\n for (k = 0; k < model->ntopics; k++) {\n const int tmp = k;\n outlog(\"\\nwriting topic %03d\", tmp);\n sprintf(name, \"%stopic-%03d\", root, tmp);\n write_sslm_var(model->topic[tmp], name);\n }\n \n if (FLAGS_model == \"fixed\") {\n for (int t=0; t < model->influence->ntime; ++t) {\n sprintf(name, \"%sinfluence_time-%03d\", root, t);\n outlog(\"\\nwriting influence weights for time %d to %s\", t, name);\n gsl_matrix* influence_t = model->influence->doc_weights[t];\n assert(model->ntopics == influence_t->size2);\n mtx_fprintf(name, influence_t);\n\n sprintf(name, \"%srenormalized_influence_time-%03d\", root, t);\n outlog(\"\\nwriting influence weights for time %d to %s\", t, name);\n influence_t = model->influence->renormalized_doc_weights[t];\n assert(model->ntopics == influence_t->size2);\n mtx_fprintf(name, influence_t);\n }\n }\n}\n\n// Read information about a particular model.\n// This model should be named \"{root}info.dat\"\n// and should contain the following rows:\n// number_topics\n// number_times\n// alpha, as a gsl vector\nlda_seq* read_lda_seq(const char* root, corpus_seq_t* data) {\n char name[400];\n lda_seq* model = (lda_seq*) malloc(sizeof(lda_seq));\n\n sprintf(name, \"%sinfo.dat\", root);\n FILE* f = fopen(name, \"r\");\n if (f == NULL) {\n outlog(\"Unable to open file %s. Failing.\", name);\n exit(1);\n }\n params_read_int(f, \"NUM_TOPICS\", &(model->ntopics));\n params_read_int(f, \"NUM_TERMS\", &(model->nterms));\n params_read_int(f, \"SEQ_LENGTH\", &(model->nseq));\n params_read_gsl_vector(f, \"ALPHA\", &(model->alpha));\n fclose(f);\n\n model->topic = (sslm_var**) malloc(sizeof(sslm_var*) * model->ntopics);\n\n for (int k = 0; k < model->ntopics; k++) {\n outlog( \"reading topic %d\", k);\n sprintf(name, \"%stopic-%03d\", root, k);\n model->topic[k] = read_sslm_var(name);\n \n model->topic[k]->w_phi_l =\n gsl_matrix_alloc(model->nterms, model->nseq);\n model->topic[k]->w_phi_sum =\n gsl_matrix_alloc(model->nterms, model->nseq);\n model->topic[k]->w_phi_l_sq =\n gsl_matrix_alloc(model->nterms, model->nseq);\n \n if (FLAGS_model == \"dim\"\n\t|| FLAGS_model == \"regression\") {\n sprintf(name, \"%sw_phi_l-%d\", root, k);\n mtx_fscanf(name, model->topic[k]->w_phi_l);\n \n sprintf(name, \"%sw_phi_sum-%d\", root, k);\n mtx_fscanf(name, model->topic[k]->w_phi_sum);\n \n sprintf(name, \"%sw_phi_l_sq-%d\", root, k);\n mtx_fscanf(name, model->topic[k]->w_phi_l_sq);\n }\n }\n \n if (FLAGS_model == \"dim\"\n || FLAGS_model == \"regression\"\n && data != NULL) {\n model->influence = (inf_var*) malloc(sizeof(inf_var));\n model->influence->doc_weights =\n (gsl_matrix**) malloc(sizeof(gsl_matrix*)); \n int t;\n model->influence->ntime = model->nseq;\n for (t=0; t < model->nseq; ++t) {\n //\toutlog(\"%d %d\", t, model->influence->ntime);\n sprintf(name, \"%sinfluence_time-%03d\", root, t);\n outlog(\"\\n reading influence weights for time %d from %s\", t, name);\n model->influence->doc_weights[t] =\n\tgsl_matrix_alloc(data->corpus[t]->ndocs,\n\t\t\t model->ntopics);\n mtx_fscanf(name, model->influence->doc_weights[t]);\n }\n } else {\n model->influence = NULL;\n }\n \n return(model);\n}\n\n/*\n * update lda sequence sufficient statistics from an lda posterior\n *\n */\n\nvoid update_lda_seq_ss(int time,\n const doc_t* doc,\n const lda_post* post,\n gsl_matrix** ss) {\n int K = post->phi->size2, N = doc->nterms;\n int k, n;\n\n for (k = 0; k < K; k++)\n {\n gsl_matrix* topic_ss = ss[k];\n for (n = 0; n < N; n++)\n {\n int w = doc->word[n];\n int c = doc->count[n];\n minc(topic_ss, w, time, c * mget(post->phi, n, k));\n }\n }\n}\n\n\n/*\n * fit lda sequence\n *\n */\n\ndouble fit_lda_seq_topics(lda_seq* model,\n gsl_matrix** ss) {\n double lhood = 0, lhood_term = 0;\n int k;\n\n for (k = 0; k < model->ntopics; k++)\n {\n outlog( \"\\nfitting topic %02d\", k);\n lhood_term = fit_sslm(model->topic[k], ss[k]);\n lhood += lhood_term;\n }\n return(lhood);\n}\n\n\n/*\n * allocate lda seq\n *\n */\n\nlda_seq* new_lda_seq(corpus_seq_t* data,\n\t\t int W, int T, int K) {\n lda_seq* model = (lda_seq*) malloc(sizeof(lda_seq));\n\n model->ntopics = K;\n model->nterms = W;\n model->nseq = T;\n\n model->alpha = gsl_vector_alloc(K);\n model->topic = (sslm_var**) malloc(sizeof(sslm_var*) * K);\n\n // Create the vectors of total counts for each time.\n model->influence_sum_lgl = (gsl_matrix**) malloc(sizeof(gsl_matrix*) * K);\n\n for (int k = 0; k < K; k++) {\n // model->w_phi_l = (gsl_matrix*) malloc(sizeof(gsl_matrix));\n // model->w_phi_l_sq = (gsl_matrix*) malloc(sizeof(gsl_matrix*));\n model->influence_sum_lgl[k] = gsl_matrix_calloc(W, T);\n\n model->topic[k] = sslm_var_alloc(W, T);\n if (k < FLAGS_fix_topics) {\n\tmodel->topic[k]->chain_variance = 1e-10;\n }\n model->topic[k]->w_phi_l = gsl_matrix_calloc(W, T);\n model->topic[k]->w_phi_sum = gsl_matrix_calloc(W, T);\n model->topic[k]->w_phi_l_sq = gsl_matrix_calloc(W, T);\n }\n model->influence = inf_var_alloc(K, data);\n\n return(model);\n}\n\n\n/*\n * initialize from sufficient statistics (expected counts).\n *\n */\n\nvoid init_lda_seq_from_ss(lda_seq* model,\n double topic_chain_variance,\n double topic_obs_variance,\n double alpha,\n gsl_matrix* init_suffstats) {\n gsl_vector_set_all(model->alpha, alpha);\n\n for (int k = 0; k < model->ntopics; k++)\n {\n gsl_vector slice = gsl_matrix_column(init_suffstats, k).vector;\n sslm_counts_init(model->topic[k],\n topic_obs_variance,\n topic_chain_variance,\n &slice);\n\tif (k < FLAGS_fix_topics) {\n\t model->topic[k]->chain_variance = 1e-10;\n\t}\n\tmodel->topic[k]->w_phi_l = gsl_matrix_calloc(model->nterms,\n\t\t\t\t\t\t model->nseq);\n\tmodel->topic[k]->w_phi_sum = gsl_matrix_calloc(model->nterms,\n\t\t\t\t\t\t model->nseq);\n\tmodel->topic[k]->w_phi_l_sq = gsl_matrix_calloc(model->nterms,\n\t\t\t\t\t\t\tmodel->nseq);\n }\n\n}\n", "meta": {"hexsha": "256d320a4727041030c9af457f58117b4f84ca46", "size": 40938, "ext": "c", "lang": "C", "max_stars_repo_path": "scripts/lib/DTM/dtm/lda-seq.c", "max_stars_repo_name": "iwangjian/dtm-lab", "max_stars_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-07-12T11:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-22T08:34:34.000Z", "max_issues_repo_path": "scripts/lib/DTM/dtm/lda-seq.c", "max_issues_repo_name": "iwangjian/topic-extractor", "max_issues_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lib/DTM/dtm/lda-seq.c", "max_forks_repo_name": "iwangjian/topic-extractor", "max_forks_repo_head_hexsha": "07c936c07d268208dcc2f19e07fb8d2a18e39ba8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-03-15T04:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-10T09:29:17.000Z", "avg_line_length": 29.8599562363, "max_line_length": 90, "alphanum_fraction": 0.6232351361, "num_tokens": 12058, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.39233683016710835, "lm_q1q2_score": 0.23252493517189743}} {"text": "/*\n * Copyright 2008-2014 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#include \n#include \n\n#define CUSP_CBLAS_COMPLEX_DEFS_1(FUNC_MACRO) \\\n FUNC_MACRO(cusp::complex , float , c) \\\n FUNC_MACRO(cusp::complex, double, z)\n\n#define CUSP_CBLAS_COMPLEX_DEFS_2(FUNC_MACRO) \\\n FUNC_MACRO(cusp::complex , float , sc) \\\n FUNC_MACRO(cusp::complex, double, dz)\n\n#define CUSP_CBLAS_COMPLEX_DEFS_3(FUNC_MACRO) \\\n FUNC_MACRO(cusp::complex , float , cs) \\\n FUNC_MACRO(cusp::complex, double, zd)\n\n#define CUSP_CBLAS_COMPLEX_AMAX(T,V,name) \\\n template \\\n int amax( const int n, const T* X, const int incX ) \\\n { \\\n return cblas_i##name##amax(n, (const V*) X, incX); \\\n }\n\n#define CUSP_CBLAS_COMPLEX_ASUM(T,V,name) \\\n template \\\n V asum( const int n, const T* X, const int incX ) \\\n { \\\n return cblas_##name##asum(n, (const V*) X, incX); \\\n }\n\n#define CUSP_CBLAS_COMPLEX_AXPY(T,V,name) \\\n template \\\n void axpy( const int n, const T alpha, const T* X, const int incX, T* Y, const int incY ) \\\n { \\\n cblas_##name##axpy(n, (const V*) &alpha, (const V*) X, incX, (V*) Y, incY); \\\n }\n\n#define CUSP_CBLAS_COMPLEX_COPY(T,V,name) \\\n template \\\n void copy( const int n, const T* X, const int incX, T* Y, const int incY ) \\\n { \\\n cblas_##name##copy(n, (const V*) X, incX, (V*) Y, incY); \\\n }\n\n// #define CUSP_CBLAS_COMPLEX_DOTC(T,V,name)\n// T dotc( const int n, const T* X, const int incX, const T* Y, const int incY )\n// {\n// typedef typename thrust::detail::eval_if<\n// thrust::detail::is_same::value,\n// thrust::detail::identity_,\n// thrust::detail::identity_\n// >::type Cmplx;\n// Cmplx z;\n// cblas_##name##dotc_sub(n, (const V*) X, incX, (const V*) Y, incY, &z);\n// return T(z.real, z.imag);\n// }\n//\n// #define CUSP_CBLAS_COMPLEX_DOTU(T,V,name)\n// T dotu( const int n, const T* X, const int incX, const T* Y, const int incY )\n// {\n// typedef typename thrust::detail::eval_if<\n// thrust::detail::is_same::value,\n// thrust::detail::identity_,\n// thrust::detail::identity_\n// >::type Cmplx;\n// Cmplx z;\n// cblas_##name##dotu_sub(n, (const V*) X, incX, (const V*) Y, incY, &z);\n// return T(z.real, z.imag);\n// }\n\n#define CUSP_CBLAS_COMPLEX_NRM2(T,V,name) \\\n template \\\n V nrm2( const int n, const T* X, const int incX ) \\\n { \\\n return cblas_##name##nrm2(n, (const V*) X, incX); \\\n }\n\n#define CUSP_CBLAS_COMPLEX_SCAL(T,V,name) \\\n template \\\n void scal( const int n, const V alpha, T* X, const int incX ) \\\n { \\\n cblas_##name##scal(n, alpha, (V*) X, incX); \\\n }\n\n#define CUSP_CBLAS_COMPLEX_SWAP(T,V,name) \\\n template \\\n void swap( const int n, T* X, const int incX, T* Y, const int incY ) \\\n { \\\n cblas_##name##swap(n, (V*) X, incX, (V*) Y, incY); \\\n }\n\n#define CUSP_CBLAS_COMPLEX_GEMV(T,V,name) \\\n template \\\n void gemv( CBLAS_ORDER order, CBLAS_TRANSPOSE trans, \\\n int m, int n, T alpha, const T* A, int lda, \\\n const T* x, int incx, T beta, T* y, int incy) \\\n{ \\\n cblas_##name##gemv(order, trans, m, n, (const V*) &alpha, (const V*) A, lda, \\\n (const V*) x, incx, (const V*) &beta, (V*) y, incy); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_GERC(T,V,name) \\\n template \\\n void ger( CBLAS_ORDER order, int m, int n, T alpha, const T* x, int incx, \\\n const T* y, int incy, T* A, int lda) \\\n{ \\\n cblas_##name##gerc(order, m, n, (const V*) &alpha, \\\n (const V*) x, incx, (const V*) y, incy, \\\n (V*) A, lda); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_HEMV(T,V,name) \\\n template \\\n void hemv( CBLAS_ORDER order, CBLAS_UPLO uplo, \\\n int n, T alpha, const T* A, int lda, \\\n const T* x, int incx, T beta, T* y, int incy) \\\n{ \\\n cblas_##name##hemv(order, uplo, n, (const V*) &alpha, (const V*) A, lda, \\\n (const V*) x, incx, (const V*) &beta, (V*) y, incy); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_HER(T,V,name) \\\n template \\\n void her( CBLAS_ORDER order, CBLAS_UPLO uplo, \\\n int n, const V alpha, const T* x, int incx, T* A, int lda) \\\n{ \\\n cblas_##name##her(order, uplo, n, alpha, \\\n (const V*) x, incx, (V*) A, lda); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_TRMV(T,V,name) \\\n template \\\n void trmv( CBLAS_ORDER order, CBLAS_UPLO uplo, \\\n CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \\\n int n, const T* A, int lda, T* x, int incx) \\\n{ \\\n cblas_##name##trmv(order, uplo, trans, diag, n, \\\n (const V*) A, lda, (V*) x, incx); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_TRSV(T,V,name) \\\n template \\\n void trsv( CBLAS_ORDER order, CBLAS_UPLO uplo, \\\n CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \\\n int n, const T* A, int lda, T* x, int incx) \\\n{ \\\n cblas_##name##trsv(order, uplo, trans, diag, n, \\\n (const V*) A, lda, (V*) x, incx); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_GEMM(T,V,name) \\\n template \\\nvoid gemm( CBLAS_ORDER order, \\\n CBLAS_TRANSPOSE transa, CBLAS_TRANSPOSE transb, \\\n int m, int n, int k, T alpha, const T* A, int lda, \\\n const T* B, int ldb, T beta, T* C, int ldc) \\\n{ \\\n cblas_##name##gemm(order, transa, transb, \\\n m, n, k, (const V*) &alpha, (const V*) A, lda, \\\n (const V*) B, ldb, (const V*) &beta, (V*) C, ldc); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_SYMM(T,V,name) \\\n template \\\n void symm( CBLAS_ORDER order, \\\n CBLAS_SIDE side, CBLAS_UPLO uplo, \\\n int m, int n, T alpha, const T* A, int lda, \\\n const T* B, int ldb, T beta, T* C, int ldc) \\\n{ \\\n cblas_##name##symm(order, side, uplo, m, n, \\\n (const V*) &alpha, (const V*) A, lda, \\\n (const V*) B, ldb, (const V*) &beta, (V*) C, ldc); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_SYRK(T,V,name) \\\n template \\\n void syrk( CBLAS_ORDER order, \\\n CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, \\\n int n, int k, T alpha, const T* A, int lda, \\\n T beta, T* C, int ldc) \\\n{ \\\n cblas_##name##syrk(order, uplo, trans, n, k, \\\n (const V*) &alpha, (const V*) A, lda, \\\n (const V*) &beta, (V*) C, ldc); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_SYR2K(T,V,name) \\\n template \\\n void syr2k( CBLAS_ORDER order, \\\n CBLAS_UPLO uplo, CBLAS_TRANSPOSE trans, \\\n int n, int k, T& alpha, const T* A, int lda, \\\n const T* B, int ldb, T& beta, T* C, int ldc) \\\n{ \\\n cblas_##name##syr2k(order, uplo, trans, n, k, \\\n (const V*) &alpha, (const V*) A, lda, \\\n (const V*) B, ldb, (const V*) &beta, (V*) C, ldc); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_TRMM(T,V,name) \\\n template \\\n void trmm( CBLAS_ORDER order, \\\n CBLAS_SIDE side, CBLAS_UPLO uplo, \\\n CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \\\n int m, int n, T alpha, const T* A, int lda, \\\n T* B, int ldb) \\\n{ \\\n cblas_##name##trmm(order, side, uplo, trans, diag, m, n, \\\n (const V*) &alpha, (const V*) A, lda, (V*) B, ldb); \\\n}\n\n#define CUSP_CBLAS_COMPLEX_TRSM(T,V,name) \\\n template \\\n void trsm( CBLAS_ORDER order, \\\n CBLAS_SIDE side, CBLAS_UPLO uplo, \\\n CBLAS_TRANSPOSE trans, CBLAS_DIAG diag, \\\n int m, int n, T alpha, const T* A, int lda, \\\n T* B, int ldb) \\\n{ \\\n cblas_##name##trsm(order, side, uplo, trans, diag, m, n, \\\n (const V*) &alpha, (const V*) A, lda, (V*) B, ldb); \\\n}\n\nnamespace cusp\n{\nnamespace system\n{\nnamespace cpp\n{\nnamespace detail\n{\nnamespace cblas\n{\n\n// LEVEL 1\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_AMAX);\nCUSP_CBLAS_COMPLEX_DEFS_2(CUSP_CBLAS_COMPLEX_ASUM);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_AXPY);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_COPY);\n// CUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_DOTC);\nCUSP_CBLAS_COMPLEX_DEFS_2(CUSP_CBLAS_COMPLEX_NRM2);\nCUSP_CBLAS_COMPLEX_DEFS_3(CUSP_CBLAS_COMPLEX_SCAL);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SWAP);\n\n// LEVEL 2\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_GEMV);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_GERC);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_HEMV);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_HER);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRMV);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRSV);\n\n// LEVEL 3\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_GEMM);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SYMM);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SYRK);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_SYR2K);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRMM);\nCUSP_CBLAS_COMPLEX_DEFS_1(CUSP_CBLAS_COMPLEX_TRSM);\n\n} // end namespace cblas\n} // end namespace detail\n} // end namespace cpp\n} // end namespace system\n} // end namespace cusp\n\n", "meta": {"hexsha": "47f25bc0cd22c897f9ab62469681440c3d5e8d1a", "size": 17127, "ext": "h", "lang": "C", "max_stars_repo_path": "cusp/system/cpp/detail/cblas/complex_stubs.h", "max_stars_repo_name": "Raman-sh/cusplibrary", "max_stars_repo_head_hexsha": "99dcde05991ef59cbc4546aeced6eb3bd49c90c9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 270.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:40:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T00:58:21.000Z", "max_issues_repo_path": "cusp/system/cpp/detail/cblas/complex_stubs.h", "max_issues_repo_name": "njh19/cusplibrary", "max_issues_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-08T18:07:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T02:37:38.000Z", "max_forks_repo_path": "cusp/system/cpp/detail/cblas/complex_stubs.h", "max_forks_repo_name": "njh19/cusplibrary", "max_forks_repo_head_hexsha": "4f72f152804dee592fec86719049af2b5469295a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2015-02-27T19:30:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T13:55:53.000Z", "avg_line_length": 60.9501779359, "max_line_length": 93, "alphanum_fraction": 0.3526011561, "num_tokens": 3445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266116, "lm_q2_score": 0.43398146480389854, "lm_q1q2_score": 0.23222279986964126}} {"text": "/****************************************************************************\n * Moreno2011Cell.h - defines cell_param struct - i.e. Cell\n *\n * Based on code from Moreno et al. 2011\n *\n * Created on: Sep 30, 2014\n * Author: Anthony Varghese\n ***************************************************************************/\n\n#ifndef CELL_H_\n#define CELL_H_\n\n\n#define M_PI 3.14159265358979323846 /* pi - needed if using -std=c++11 */\n#include \n#include \n\nnamespace cellmodel{\n\tclass Cells;\n}\n\nenum NaChannelMMSolver{\n\tNotUsed,\n\tIterative,\n\tLUDecomp\n};\n\nclass Moreno2011Cell {\npublic:\n\tMoreno2011Cell();\n\tvirtual ~Moreno2011Cell();\n\tMoreno2011Cell(const Moreno2011Cell& source);\n\tMoreno2011Cell& operator=(const Moreno2011Cell& rhs);\n\n\tvoid setParams(const double* par);\n\tvoid setXpos(unsigned int p){ pos_x = p; }\n\tvoid Copy(const Moreno2011Cell& in);\n\tvoid setEnvironment( cellmodel::Cells* env );\n\tvoid setState(double* newstate) {\n\t\tfor (unsigned int i = 0; i < nstates; i++)\n\t\t\tstate[i] = newstate[i];\n\t}\n\t/*\n\t * Calling method is responsible for allocating Y array\n\t */\n\tvoid getState(double* Y) {\n\t\tfor (unsigned int i = 0; i < nstates; i++)\n\t\t\tY[i] = state[i];\n\t}\n\t/*\n\t * Calling method is responsible for allocating dYdt array\n\t */\n\tvoid getRates(double* dYdt) {\n\t\tfor (unsigned int i = 0; i < nstates; i++)\n\t\t\tdYdt[i] = rates[i];\n\t}\n\tvoid Calculate_Points(double t);\n\tdouble CalculateCurrents(double t);\n\tdouble CalculateCurrents(double t, const double Vx);\n\tvoid Calculate_All(const double t);\n\tvoid SetInitialConditions();\n\tvoid Calculate_Reset(double t);\n\tvoid setI_stimulus(double t);\n\tvoid updatedVdt(const double Iaxnm1, const double Iaxnp1){\n\t\tdV_old = dVdt;\n\t\tI_axnm1 = Iaxnm1;\n\t\tI_axnp1 = Iaxnp1;\n\t\tI_axial = Iaxnp1 + Iaxnm1;\n\t\tdVdt = -I_axial - I_total; // Rate of change of Vm\n\t}\n\tdouble getV()\tconst {\treturn V;\t}\n\tdouble getdVdt()const {\treturn dVdt;\t}\n\tdouble getI_total()const {\treturn I_total;\t}\n\tvoid setV\t (const double Vnew)\t{ V = Vnew; }\n\tvoid setdVdt(const double dVdtnew){ dVdt = dVdtnew; }\n\t/*\n\t * Forward Euler update of V\n\t */\n\tvoid fe_updateV(const double dt)\t{ V = V + dVdt * dt; }\n\tdouble getI_K1()\tconst {\treturn I_K1; }\n\tdouble getI_Na()\tconst {\treturn I_Na; }\n\tdouble getI_axnm1() const {\treturn I_axnm1; }\n\tdouble getI_axnp1() const {\treturn I_axnp1; }\n\tdouble getI_axial() const {\treturn I_axial; }\n\t// Na Channel States\n\tdouble getNaClosed()const { return C1 + C2 + C3; }\n\tdouble getNaIC23()\tconst { return IC2 + IC3; }\n\tdouble getNaIF()\tconst { return IF; }\n\tdouble getNaOS()\tconst { return OS; }\n\tdouble getNaO()\t\tconst { return O; }\n\tdouble getNaDClosed() const { return DC1 + DC2 + DC3; }\n\tdouble getNaDIC23()\tconst { return DIC2 + DIC3; }\n\tdouble getNaDIF()\tconst { return DIF; }\n\tdouble getNaDOS()\tconst { return DOS; }\n\tdouble getNaDO()\tconst { return DO; }\n\tdouble getNaDIM1()\tconst { return DIM1; }\n\tdouble getNaD_Closed() const { return D_C1 + D_C2 + D_C3; }\n\tdouble getNaD_IC23()const { return D_IC2 + D_IC3; }\n\tdouble getNaD_IF()\tconst { return D_IF; }\n\tdouble getNaD_OS()\tconst { return D_OS; }\n\tdouble getNaD_O()\tconst { return D_O; }\n\tdouble getNaD_IM1()\tconst { return D_IM1; }\n\n\t/*\n\t * computeRushLarsenStepState\n\t * - take a time step using Rush Larsen for gating variables\n\t * and semi-implicit for Markov State models\n\t * Calling method is responsible for allocating Y array\n\t */\n\tvoid computeRushLarsenStepState( const double t, const double dt );\n\t/*\n\t * computeRushLarsen2StepState\n\t * - take a time step using Second-order Rush Larsen for all states\n\t * and semi-implicit for Markov State models\n\t * Calling method is responsible for allocating Y array\n\t */\n\tvoid computeRushLarsen2StepState( const double t, const double dt, const int step, const double Vhalf );\n\n\t// Indices into the state array\n\tstatic const unsigned int nNaChFirstState = 0;\n\t// Number of states for Na Channel Markov state model:\n\tstatic const unsigned int nNaChLastState = 29;\n\tstatic const unsigned int nNaChStates = nNaChLastState + 1;\n\t// start of gating variables:\n\tstatic const unsigned int ngatem = nNaChStates;\n\tstatic const unsigned int nLastState = ngatem + 20;\t\t// last state\n\t// Currently, the cell transmembrane potential is the last state\n\tstatic const unsigned int nV = nLastState;\n\tstatic const unsigned int nstates = nV + 1;\t// Total number of states\n\n\t// Cell States\n\tdouble state[nstates]; // state variables for integration\n\n\tdouble peak_slope, t_min, V_min, t_thr, V_thr, t_max, V_max, t_EAD, V_EAD;\n\tdouble t_EAD2, V_EAD2, t_90, V_90, dV_old;\n\tbool flag2;\n\tdouble APD_90, DI, L_EAD;\n\n\t// To measure the work involved in the iterations:\n\tint \tMarkovIterations;\n\tdouble\tMarkovIterationError;\n\nprivate:\n\t// Need a pointer back to the container class to\n\t// find out conditions like waitTime, drug conc, etc.\n\tcellmodel::Cells* cellenv = nullptr;\n\n\t/****************************************************************************\n\t Universal Constants\n\t *****************************************************************************/\n\tstatic constexpr double R = 8314.472;\t\t// J/mol*K\n\tstatic constexpr double T = 310;\t\t\t// K\n\tstatic constexpr double F = 96485.3415;\n\tstatic constexpr double RTF = R*T/F;\n\n\t// const double Cm = 2.0;\t\t\t\t\t// uF/ cm^2 -- not used anywhere\n\tstatic constexpr double CAP = 0.185;\t\t// Cellular capacitance\n\tstatic constexpr double rho = 162;\t\t\t// ohm*cm\n\n\t// Channel conductances - these can be set externally\n\t// used to be:\n\t// static constexpr double G_Na = 15.0;\t//27.5 //18.5\n\tdouble G_Na = 15.0;\t\t// 15.0 in Moreno et al 2011\n\tdouble GK1\t= 5.405;\t// 5.405 in Moreno et al 2011\n\n\t// Ion Valences\n\tstatic constexpr double z_Na = 1;\t\t\t// Valence of Na\n\tstatic constexpr double z_Ca = 2;\t\t\t// Valence of Ca\n\tstatic constexpr double z_K = 1;\t\t\t// Valence of K\n\n\t//Cell Geometry\n\tstatic constexpr double pi = M_PI;\t\t\t// Should be 3.141592\n\tstatic constexpr double S_cg = 0.2;\t\t\t// Surface to volume ratio (um^-1)\n\n\n\t//Intracellular volumes\n\tstatic constexpr double V_cyto=0.016404;\t//16404 uL\n\tstatic constexpr double V_sr=0.001094;\n\tstatic constexpr double V_ss=0.00005468;\n\n\t// initial conditions of ion concentrations\n\tstatic constexpr double Na_out = 140;\n\tstatic constexpr double Ca_out = 2.0;\n\tstatic constexpr double K_out = 5.4;\n\n\tstatic constexpr double Vmin_default =\t 0.0;\t// mV - a \"large\" value so that minimums (expected to be < 0) can be detected\n\tstatic constexpr double Vthr_default = -90.0;\t// mV - a \"low\" value so that the threshold can be detected\n\n\tbool initializedExternally = false;\n\tstatic const NaChannelMMSolver NaChanSolver = Iterative; // LUDecomp; // Iterative;\n\n\t// Arrays for each cell:\n\tdouble rates[nstates]; // rates of change of state - derivative\n\t// Total number of currents and auxilliary values:\n\tstatic const unsigned int naux = 26;\n\tdouble currents[naux];\n\n\tint Cell_type;\n\tunsigned int pos_x=0;\n//\tunsigned int pos_y=0, pos_z=0; // Position of cell in 3-d\n\n\t// Na Channel constants\n\tstatic constexpr double Q10 = 3;\n\t// This does not work in clang, ok in gcc\n\t//static constexpr double Tfactor = 1.0/(pow(Q10, (37.0-(T-273))/10.0));\n\tstatic constexpr double pH = 7.4;\n\n\n\t// Na channel markov state model - the individual states are only needed for outputs\n\tdouble &IC3\t\t= state[ 0], &IC2\t= state[1];\n\tdouble &IF\t\t= state[ 2], &IM1\t= state[3];\n\tdouble &IM2\t\t= state[ 4], &C3\t= state[5];\n\tdouble &C2\t\t= state[ 6], &O\t\t= state[7];\n\tdouble &OS\t\t= state[ 8], &C1\t= state[9];\n\n\tdouble &DIC3\t= state[10], &DIC2\t= state[11];\n\tdouble &DIF \t= state[12], &DIM1\t= state[13];\n\tdouble &DIM2\t= state[14], &DC3 \t= state[15];\n\tdouble &DC2\t\t= state[16], &DO\t= state[17];\n\tdouble &DOS\t\t= state[18], &DC1\t= state[19];\n\n\tdouble &D_IC3\t= state[20], &D_IC2 = state[21];\n\tdouble &D_IF\t= state[22], &D_IM1 = state[23];\n\tdouble &D_IM2\t= state[24], &D_C3 = state[25];\n\tdouble &D_C2\t= state[26], &D_O = state[27];\n\tdouble &D_OS\t= state[28], &D_C1 = state[29];\n\tdouble &V = state[ngatem + 20];\n\n\t// Gating variables\n\tdouble &m\t= state[ngatem],\t\t&h\t = state[ngatem + 1];\n\tdouble &j = state[ngatem + 2];\n\tdouble &d = state[ngatem + 3],\t&f\t = state[ngatem + 4];\n\tdouble &f2 = state[ngatem + 5],\t&f_Ca = state[ngatem + 6];\n\tdouble &r = state[ngatem + 7],\t&s\t = state[ngatem + 8];\n\tdouble &xr1 = state[ngatem + 9],\t&xr2 = state[ngatem + 10];\n\tdouble &xs = state[ngatem + 11];\n\tdouble &R_bar = state[ngatem + 12];\n\tdouble &mL = state[ngatem + 13], &hL\t = state[ngatem + 14];\n\tdouble &Ca_in = state[ngatem + 15], &Ca_sr = state[ngatem + 16];\n\tdouble &Ca_ss = state[ngatem + 17];\n\tdouble &Na_in = state[ngatem + 18], &K_in = state[ngatem + 19];\n\tdouble &dVdt = rates[ngatem + 20];\n\n\t// old gating variable values before half-step in 2nd order Rush Larsen\n\tdouble oldgates[20];\n\tdouble &oldm\t= oldgates[0],\t&oldh\t\t= oldgates[1];\n\tdouble &oldj\t= oldgates[2];\n\tdouble &oldd\t= oldgates[3],\t&oldf\t\t= oldgates[4];\n\tdouble &oldf2\t= oldgates[5],\t&oldf_Ca\t= oldgates[6];\n\tdouble &oldr\t= oldgates[7],\t&olds\t\t= oldgates[8];\n\tdouble &oldxr1\t= oldgates[9],\t&oldxr2 \t= oldgates[10];\n\tdouble &oldxs\t= oldgates[11];\n\tdouble &oldR_bar = oldgates[12];\n\tdouble &oldmL = oldgates[13], &oldhL\t\t= oldgates[14];\n\tdouble &oldCa_in = oldgates[15], &oldCa_sr\t= oldgates[16];\n\tdouble &oldCa_ss = oldgates[17];\n\tdouble &oldNa_in = oldgates[18], &oldK_in\t= oldgates[19];\n\n\t// Currents and auxilliary values - anything that may be useful to print out for plotting\n\tdouble &I_total = currents[0];\n\tdouble &I_axial = currents[1];\n\tdouble &I_axnm1 = currents[2], &I_axnp1 = currents[3];\n\tdouble &I_stim\t= currents[4];\n\tdouble &I_Na\t= currents[5], &I_Na_L = currents[6];\n\tdouble &mI_Na\t= currents[7], &I_Na_b = currents[8];\n\tdouble &I_Ca_L\t= currents[9], &I_Ca_b = currents[10];\n\tdouble &I_Kr\t= currents[11], &I_Ks = currents[12];\n\tdouble &I_K1\t= currents[13], &I_Kp = currents[14];\n\tdouble &I_to\t= currents[15];\n\tdouble &I_Na_Ca = currents[16], &I_Na_K = currents[17];\n\tdouble &I_p_Ca\t= currents[18];\n\tdouble &I_Na_ion_total\t= currents[19];\n\tdouble &I_Ca_ion_total\t= currents[20];\n\tdouble &I_K_ion_total\t= currents[21];\n\tdouble &I_tr\t= currents[22], &I_leak = currents[23];\n\tdouble &I_up\t= currents[24], &I_rel = currents[25];\n\n\t// RATES\n\t// Na channel markov state model\n\tdouble &dIC3\t= rates[ 0], &dIC2\t= rates[1];\n\tdouble &dIF\t\t= rates[ 2], &dIM1\t= rates[3];\n\tdouble &dIM2\t= rates[ 4], &dC3\t= rates[5];\n\tdouble &dC2\t\t= rates[ 6], &dO\t= rates[7];\n\tdouble &dOS\t\t= rates[ 8], &dC1\t= rates[9];\n\tdouble &dDIC3\t= rates[10], &dDIC2 = rates[11];\n\tdouble &dDIF\t= rates[12], &dDIM1 = rates[13];\n\tdouble &dDIM2\t= rates[14], &dDC3\t= rates[15];\n\tdouble &dDC2\t= rates[16], &dDO\t= rates[17];\n\tdouble &dDOS\t= rates[18], &dDC1\t= rates[19];\n\tdouble &dD_IC3\t= rates[20], &dD_IC2 = rates[21];\n\tdouble &dD_IF\t= rates[22], &dD_IM1 = rates[23];\n\tdouble &dD_IM2\t= rates[24], &dD_C3\t= rates[25];\n\tdouble &dD_C2\t= rates[26], &dD_O\t= rates[27];\n\tdouble &dD_OS\t= rates[28], &dD_C1\t= rates[29];\n\n\t// Gating variable rates\n\tdouble &dm\t\t= rates[ngatem ],\t&dh\t\t= rates[ngatem + 1];\n\tdouble &dj\t\t= rates[ngatem + 2];\n\tdouble &dd\t\t= rates[ngatem + 3],\t&df\t\t= rates[ngatem + 4];\n\tdouble &df2\t\t= rates[ngatem + 5],\t&df_Ca\t= rates[ngatem + 6];\n\tdouble &dr\t\t= rates[ngatem + 7],\t&ds\t\t= rates[ngatem + 8];\n\tdouble &dxr1\t= rates[ngatem + 9],\t&dxr2\t= rates[ngatem + 10];\n\tdouble &dxs\t\t= rates[ngatem + 11];\n\tdouble &dR_bar\t= rates[ngatem + 12];\n\tdouble &dmL\t\t= rates[ngatem + 13],\t&dhL\t= rates[ngatem + 14];\n\tdouble &dCa_in\t= rates[ngatem + 15],\t&dCa_sr\t= rates[ngatem + 16];\n\tdouble &dCa_ss\t= rates[ngatem + 17];\n\tdouble &dNa_in\t= rates[ngatem + 18],\t&dK_in\t= rates[ngatem + 19];\n\n\n\t// Cell data points - markers of cell function\n\tdouble I_total_old, dI_total, dI_total_old, t_I_total, I_total_pt;\n\tdouble V_I_total;\n\tbool flagI_total, flag_EAD, flag_EAD2;\n\tdouble t_90_old;\n\tdouble CV, CV_EAD;\n\n\t// The temporary array is used for a modified-Newton iteration to solve\n\t// for the markov channel state variables.\n\tstatic const unsigned int\ti3 = 0, i2 = 1,\tiF = 2, im = 3,\n\t\t\t\t\t\t\t\tiM = 4, c3 = 5,\tc2 = 6, op = 7,\n\t\t\t\t\t\t\t\toS = 8, c1 = 9;\n\tstatic const unsigned int\tdi3 = 10, di2 = 11,\tdiF = 12, dim = 13,\n\t\t\t\t\t\t\t\tdiM\t= 14, dc3 = 15,\tdc2\t= 16, dop = 17,\n\t\t\t\t\t\t\t\tdoS\t= 18, dc1 = 19;\n\tstatic const unsigned int\tDi3\t= 20, Di2 = 21,\tDiF\t= 22, Dim = 23,\n\t\t\t\t\t\t\t\tDiM\t= 24, Dc3 = 25,\tDc2\t= 26, Dop = 27,\n\t\t\t\t\t\t\t\tDoS\t= 28, Dc1 = 29;\n\n\t// BLAS vectors and methods to allocate, free and copy them\n\tgsl_vector* Yn = nullptr;\n\tgsl_vector* Ynph = nullptr;\n\tgsl_vector* Ynp1 = nullptr;\n\tgsl_vector* Ynp1i= nullptr;\n\tgsl_vector* DiagonalAn = nullptr;\n\tgsl_vector* DiagonalAnInv = nullptr;\n\tgsl_matrix* OffDiagonalAn = nullptr;\n\tvoid allocTemps();\n\tvoid freeTemps();\n\tvoid copyTemps(const Moreno2011Cell& source);\n\n\n\n\t/*********************************************************************************************************\n\t Current Function Prototypes\n\t *********************************************************************************************************/\n\tvoid WT_SCN5A_Initial_Conditions();\n\tvoid WT_SCN5A_Lidocaine();\n\tvoid WT_SCN5A_Flecainide();\n\tvoid checkNaChannelStates();\n\tvoid calcI_total(double t);\n\tvoid calcI_Na(double t);\t//Fast sodium current\n\tvoid calcI_Na_L();\n\tvoid calcI_K1();\t\t\t//Time independent potassium current\n\tvoid calcI_Kp();\t\t\t//Plateau K current, time independent, K_out insensitive\n\tvoid calcI_Na_Ca();\t\t\t//Sodium calcium exchanger\n\tvoid calcI_Na_K();\t\t\t//Sodium potassium pump\n\tvoid calcI_Ca_L();\t\t\t//L type calcium channel Ca contribution\n\tvoid calcI_Kr();\t\t\t//Rapid rectifier\n\tvoid calcI_Ks();\t\t\t//Slow rectifier\n\tvoid calcI_to();\t\t\t//Transient outward current\n\tvoid calcI_p_Ca();\t\t\t//Sarcolemmal calcium pump\n\tvoid calcI_Ca_b();\t\t\t//Calcium background current\n\tvoid calcI_Na_b();\t\t\t//Sodium background current\n\n\tvoid calcI_tr();\n\tvoid calcI_leak();\t\t\t//Leak from SR\n\tvoid calcI_up();\t\t\t//Uptake to SR\n\tvoid calcI_rel();\t\t\t//Release from SR\n\n\t//Dynamic Concentrations\n\tvoid Calculate_Na_in();\t\t\t//Dynamic [Na] in Myoplasm\n\tvoid Calculate_K_in();\t\t\t//Dynamic [K] in Myoplasm\n\tvoid Calculate_Ca_in();\t\t\t//Dynamic [Ca] in Myoplasm\n\tvoid Calculate_Ca_sr();\t\t\t//Dynamic [Ca] in JSR\n\tvoid Calculate_Ca_ss();\t\t\t//Dynamic [Ca] in NSR\n\n\t// Semi-implicit and Rush-Larsen\n\tstruct NaChannelParameters{\n\t\tdouble pKa, portion, diffusion,\n\t\t\t\tdrug_charged, drug_neutral,\n\t\t\t\tdrug_distance, kd0, kd_open;\n\t\tdouble\ta11, a12, a13, b11, b12, b13,\n\t\t\t\ta3,\t b3, a2, b2, a4, b4, a5, b5,\n\t\t\t\tax,\t bx, ax1, bx1,\n\t\t\t\ta13c,a22, b33, a33,\n\t\t\t\ta44, b44, a55, b55,\n\t\t\t\tax2, a13n, a_22, b_33,\n\t\t\t\ta_44,b_44, a_55, b_55,\n\t\t\t\tkon, koff, kcoff, kcon,\n\t\t\t\tb13c,b22, k_on, k_off,\n\t\t\t\tki_on, ki_off, kc_on, kc_off,\n\t\t\t\ta_33, b13n,\tb_22, bx2;\n\t\tvoid Initialize( cellmodel::Cells* cellenv );\n\t\tvoid ComputeVDepTerms(const double V, cellmodel::Cells* env );\n\t\tvoid set_NaCh_Matrices( gsl_matrix* M, gsl_vector* D);\n\t};\n\tNaChannelParameters NaChParams;\n\tstatic constexpr double tolerance = 1e-7;\n\tvoid semi_impl_I_Na(double t, const double dt);\t//Fast sodium current\n\tvoid semi_impl_WT_SCN5A(const double dt);\n\tvoid semi_impl_WT_SCN5A_LU(const double dt);\n\tvoid exponential_I_Na1(double t, const double dt);\n\tvoid exponential_I_Na2(double t, const double dt, const double Vhalf);\n\n\tvoid rush_I_Na_L(const double dt);\n\tvoid rush_I_Ca_L(const double dt);\t\t\t//L type calcium channel Ca contribution\n\tvoid rush_I_Kr(const double dt);\t\t\t//Rapid rectifier\n\tvoid rush_I_Ks(const double dt);\t\t\t//Slow rectifier\n\tvoid rush_I_to(const double dt);\t\t\t//Transient outward current\n\n\tvoid rush_I_rel(const double dt);\t\t\t//Release from SR\n\tvoid rush_Na_in(const double dt);\t\t\t//Dynamic [Na] in Myoplasm\n\tvoid rush_K_in(const double dt);\t\t\t//Dynamic [K] in Myoplasm\n\tvoid rush_Ca_in(const double dt);\t\t\t//Dynamic [Ca] in Myoplasm\n\tvoid rush_Ca_sr(const double dt);\t\t\t//Dynamic [Ca] in JSR\n\tvoid rush_Ca_ss(const double dt);\t\t\t//Dynamic [Ca] in NSR\n\n\n\t// Old code - not used and not needed - new code is working\n\tvoid semi_impl_WT_SCN5A_Lidocaine(const double dt);\n\tvoid semi_impl_WT_SCN5A_Flecainide(const double dt);\n\tvoid set_NaCh_Matrices( gsl_matrix* M, gsl_vector* D,\n\t\t\tconst double a11,\tconst double a12,\tconst double a13,\n\t\t\tconst double b11,\tconst double b12,\tconst double b13,\n\t\t\tconst double a3,\tconst double b3,\tconst double a2, const double b2,\n\t\t\tconst double a4,\tconst double b4,\tconst double a5, const double b5,\n\t\t\tconst double ax,\tconst double bx,\tconst double ax1,const double bx1,\n\t\t\tconst double a13c, const double a22,\tconst double b33,const double a33,\n\t\t\tconst double a44, const double b44,\tconst double a55,const double b55,\n\t\t\tconst double ax2, const double a13n, const double a_22, const double b_33,\n\t\t\tconst double a_44,\tconst double b_44, const double a_55, const double b_55,\n\t\t\tconst double kon, const double koff, const double kcoff, const double kcon,\n\t\t\tconst double b13c,\tconst double b22,\tconst double k_on,\tconst double k_off,\n\t\t\tconst double ki_on,\tconst double ki_off,const double kc_on, const double kc_off,\n\t\t\tconst double a_33,\tconst double b13n,\tconst double b_22,\tconst double bx2 );\n\tdouble MCtemp[nNaChStates];\n\tdouble &mIC3\t= MCtemp[ 0], &mIC2 \t= MCtemp[1];\n\tdouble &mIF\t\t= MCtemp[ 2], &mIM1\t\t= MCtemp[3];\n\tdouble &mIM2\t= MCtemp[ 4], &mC3\t\t= MCtemp[5];\n\tdouble &mC2\t\t= MCtemp[ 6], &mO\t\t= MCtemp[7];\n\tdouble &mOS\t\t= MCtemp[ 8], &mC1\t\t= MCtemp[9];\n\tdouble &mDIC3\t= MCtemp[10], &mDIC2\t= MCtemp[11];\n\tdouble &mDIF\t= MCtemp[12], &mDIM1\t= MCtemp[13];\n\tdouble &mDIM2\t= MCtemp[14], &mDC3\t\t= MCtemp[15];\n\tdouble &mDC2\t= MCtemp[16], &mDO\t\t= MCtemp[17];\n\tdouble &mDOS\t= MCtemp[18], &mDC1\t\t= MCtemp[19];\n\tdouble &mD_IC3\t= MCtemp[20], &mD_IC2\t= MCtemp[21];\n\tdouble &mD_IF\t= MCtemp[22], &mD_IM1\t= MCtemp[23];\n\tdouble &mD_IM2\t= MCtemp[24], &mD_C3\t= MCtemp[25];\n\tdouble &mD_C2\t= MCtemp[26], &mD_O\t\t= MCtemp[27];\n\tdouble &mD_OS\t= MCtemp[28], &mD_C1\t= MCtemp[29];\n\tvoid semi_impl_WT_SCN5A_Lidocaine_compare_BLAS_old(const double dt);\n\tvoid semi_impl_WT_SCN5A_Flecainide_old (const double dt);\n};\n\n#endif /* CELL_H_ */\n", "meta": {"hexsha": "59e2418bb5a78a5babd572394538604ee8a4f1d3", "size": 17940, "ext": "h", "lang": "C", "max_stars_repo_path": "src/cell/Moreno2011Cell.h", "max_stars_repo_name": "AnthonyVa/Cardcell", "max_stars_repo_head_hexsha": "ac1360d03d2ae9bf8d03a45c7e1823999f82addc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cell/Moreno2011Cell.h", "max_issues_repo_name": "AnthonyVa/Cardcell", "max_issues_repo_head_hexsha": "ac1360d03d2ae9bf8d03a45c7e1823999f82addc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cell/Moreno2011Cell.h", "max_forks_repo_name": "AnthonyVa/Cardcell", "max_forks_repo_head_hexsha": "ac1360d03d2ae9bf8d03a45c7e1823999f82addc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.1703056769, "max_line_length": 123, "alphanum_fraction": 0.6646042363, "num_tokens": 6052, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.2322206803411528}} {"text": "/*\nSimulation of a network of Izhikevich neurons, coupled by chemical synapses,\nreceiving uncorrelated, random input spiketrains.\n\nThe simulation was written by Ekkehard Ullner in 2013.\n\nThis is a modified version of E.U.'s original, stand-alone program,\nfor use e.g. via the ctypes ffi in Python.\n\nChangelog:\n- suport for networks with inhibitory synapses\n- Neuron type switched from FitzHugh-Nagumo to Izhikevich\n- Various simulation parameters exposed to allow arbitrary network topologies,\ninput patterns, neuron parameters etc.\n- results are written to a provided buffer instead of text files\n- the non-free, problematic[0] \"Numerical Recipes\" RAN1 random number generator\nwas replaced with a Mersenne Twister rng from the GNU scientific library.\n [0 \"Random Numbers in Scientific Computing: An Introduction\", Katzgraber, 2010\n http://arxiv.org/pdf/1005.4117.pdf]\n- cosmetics and a minimum of documentation (i.e. the comments)\n\nCK 2014-2016\n\nThe MIT License (MIT)\n\nCopyright (c) 2013,2014 Ekkehard Ullner, Clemens Korndörfer\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICU\nLAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nvoid sagwas(){\n puts(\"simulation version Oct 12 2016\");\n}\n\n\n/* function simulate\n * ------------------\n * Runs a single network simulation with the given parameters and writes the resulting\n * voltage traces into a given buffer.\n *\n * Parameters:\n *\n * N: Number of rows i in the simulated grid of neurons. (regardless of network topology,\n * the network is a 'grid' where each node is adressed by an (i,j) coordinate.)\n * M: number of columns j in the grid\n *\n * limit: number of simulation steps to run\n *\n * KT: maximum number of coupled neighbors of any node (degree of the network)\n * connection: function pointer, where\n * connection(i,j,l, '0' | '1') must return the first (second) coordinate of the l'th afferent to cell ij\n * connection(i,j,l, 's') must return the strength of that connection\n *\n * recording_voltage: array of shape (M,N,limit) in which simulation results will be written in row first order\n * recording_recov: same as recording_voltage, for the neuron's recovery variable\n * recording_spikes: same as recording_voltage, for binary log of spike events\n *\n * inputc_exc: array of shape (M,N) in row-first order. modulates the rate of input pulses fed into\n * each cell, values within [0,1]. aka \"the stimulus\".\n * inputc_inh: same for inhibitory input pulses\n * laminex: lambda_in_ex, the rate of excitatory input spikes to input-receiving nodes\n * lamini: lambda_in_in, the rate of inhibitory input spikes to input-receiving nodes\n * izhi_a: parameter a of the izhikevich neuron\n * izhi_b: parameter b of the izhikevich neuron\n * izhi_reset_c: reset constant of the neuron\n * izhi_recovery_d: recovery reset constant\n * con_upstr_exc: synapse conductivity of the excitatory random inputs\n * con_upstr_inh: synapse conductivity of the inhibitory random inputs\n * # lateral synapses:\n * taus: duration of transmitter presence after spike\n * alp: rising time constant of fraction of open receptors\n * bet: decay time constant of fraction of open receptors\n * # inhibitory synapses:\n * tauni: duration of transmitter presence after spike\n * ani: rising time constant of fraction of open receptors\n * bni: decay time constant of fraction of open receptors\n * # external excitatory synapses:\n * tauna: duration of transmitter presence after spike\n * ana: rising time constant of fraction of open receptors\n * bna: decay time constant of fraction of open receptors\n * activation_noise: scale of white noise added to each neuron's activation variable\n * seed: random seed > 0\n * verbose: print a lot or not\n * delta_t: integration step width\n*/\n\nvoid simulate(int M,\n int N,\n int limit,\n int KT,\n double (*connection)(int,int,int,char),\n double* recording_voltage,\n double* recording_recov,\n double* recording_spikes,\n double* inputc_exc,\n double* inputc_inh,\n double laminex,\n double lamini,\n double izhi_a,\n double izhi_b,\n double izhi_reset_c,\n double izhi_recovery_d,\n double con_upstr_exc,\n double con_upstr_inh,\n double taus,\n double alp,\n double bet,\n double tauni,\n double ani,\n double bni,\n double tauna,\n double ana,\n double bna,\n double activation_noise,\n int seed,\n int verbose,\n double delta_t){\n\n\n\n // say hello & show the current parametrisation & input pattern.\n if (verbose){\n printf(\"starting simulation (Izhikevich neuron)\\n\");\n printf(\"seed: %d\\nM: %d\\nN: %d\\nlimit: %d\\nKT: %d\\nlaminex: %f\\nlamini: %f\\nizhi_a: %f\\nizhi_b: %f\\nizhi_reset_c: %f\\nizhi_recovery_d: %f\\ncon_upstr_exc: %f\\ncon_upstr_inh: %f\\ntaus: %f\\nalp: %f\\nbet: %f\\ntauni: %f\\nani: %f\\nbni: %f\\ntauna: %f\\nana: %f\\nbna: %f\\nactivation_noise: %f\\ndelta_t: %f\\n\",\n seed, M, N, limit, KT, laminex, lamini, izhi_a, izhi_b, izhi_reset_c, izhi_recovery_d, con_upstr_exc, con_upstr_inh, taus, alp, bet, tauni, ani, bni, tauna, ana, bna, activation_noise, delta_t);\n\n int i1,j1;\n int print_exc, print_inh;\n for (j1 = 0; j1 0;\n print_inh = inputc_inh[i1 + N*j1] > 0;\n if (print_exc && print_inh) printf(\" ±\");\n else if (print_exc) printf(\" +\");\n else if (print_inh) printf(\" -\");\n else printf(\" .\");\n }\n printf(\"\\n\");\n }\n }\n\n assert(seed>0);\n gsl_rng* rng = gsl_rng_alloc(gsl_rng_mt19937);\n gsl_rng_set(rng, seed);\n\n // Initialisations & constant parameters:\n // neuron model:\n double xold[N][M],dx_h[N][M],xh[N][M],xnew[N][M]; // activation variable (previous value, first step, intermediate value, new value)\n double yold[N][M],dy_h[N][M],yh[N][M],ynew[N][M]; // recovery variable (previous value, first step, intermediate value, new value)\n double Isyn[N][M]; // collection of lateral input currents at each neuron in the current time step\n\n double spikes[N][M]; // recording of spike events in the current time step\n\n // lateral synapses:\n double rold[N][M],rh[N][M],rnew[N][M]; // fraction of open receptors (previous value, intermediate value, new value).\n\n // more precisely: r[i][j] is the fraction of open receptors at synapses anywhere in the network\n // that are the target of neuron (i,j). Since all synapses have the same rise and decay constants\n // alpha and beta, the effect of a spike at neuron i,j is the same at all of its target synapses.\n // We can therefore write the fractions of open receptors of all these target synapses as a\n // single variable r[i][j], associated with the source neuron i,j.\n\n double Tl[N][M]; // spike arrival times \"T_j\" (indexing follows the same logic as r[][])\n double Hs[N][M]; // transmitter concentrations \"[T]_j\" (...here, too)\n double Vna = 0.0; // synaptic reversal potential (excitatory)\n double Vni = -80; // synaptic reversal potential (inhibitory)\n\n // double taus = 0.01; // duration of transmitter presence after spike\n double Tm = 1.0; // maximum transmitter concentration\n\n // double alp = 8.0; // rising time constant of fraction of open receptors\n // double bet = 8.0; // decay time constant of fraction of open receptors\n\n\n // activatory external input synapses:\n double rnoa[N][M],rnha[N][M],rnna[N][M]; // fraction of open receptors\n double Tnla[N][M],Hna[N][M]; // spike arrival times and transmitter concentrations\n\n // double tauna = 0.01; // duration of transmitter presence after spike\n double Tna = 1.0; // maximum transmitter concentration\n\n // double ana = 8.0; // rising time constant of fraction of open receptors\n // double bna = 8.0; // decay time constant of fraction of open receptors\n\n\n // inhibitory external input synapses:\n double rnoi[N][M],rnhi[N][M],rnni[N][M]; // fraction of open receptors (previous value, intermediate value, new value)\n double Tnli[N][M],Hni[N][M]; // spike arrival times and transmitter concentrations\n\n // double tauni = 0.01; // duration of transmitter presence after spike\n double Tni = 1.0; // maximum transmitter concentration\n\n // double ani = 8.0; // rising time constant of fraction of open receptors\n // double bni = 8.0; // decay time constant of fraction of open receptors\n\n\n // misc:\n double izhi_reset_threshold = 30; // spike detection threshold\n long step; // simulation step count\n // double delta_t = 0.001; // integration step width\n // double delta_t = 0.01; // integration step width\n double current_time = 0.0; // simulation time\n\n int i,j,l; // various loop variables over network nodes.\n\n int p1[N][M][KT],p2[N][M][KT]; // lookup tables holding the first (p1) and second (p2) coordinate of the KT'th afferent to neuron N,M\n float conductance_net[N][M][KT]; // lookup table: synapse conductance of the KT'th afferent to neuron N,M\n\n double in_exc[N][M]; // excitatory stimulus strength (input noise rate modulation) for neuron N,M\n double in_inh[N][M]; // inhibitory ...\n\n\n // remaining initialisations:\n for (j = 0;jcurrent_time) Hs[i][j] = 1.0 * Tm;\n else Hs[i][j] = 0.0;\n\n // ..for activatory external input synapses..\n if (Tnla[i][j] + tauna>current_time) Hna[i][j] = 1.0 * Tna;\n else Hna[i][j] = 0.0;\n\n // ..and for inhibitory external input synapses.\n if (Tnli[i][j] + tauni>current_time) Hni[i][j] = 1.0 * Tni;\n else Hni[i][j] = 0.0;\n\n }}\n\n\n // first integration step\n double x;\n double y;\n double I;\n double g;\n for (j = 0;j=0 && p2[i][j][l]>=0){\n // input currents to neuron (i,j) depend proportionally on\n // r[ p1[i][j][l] ][ p2[i][j][l] ], that is, on the fraction of open\n // receptors of all the synapses targeted by neighbour l projecting\n // to neuron i,j. These synapses have a high fraction of open receptors\n // if their source neuron recently fired a spike. Thus, input currents\n // flow to neuron (i,j) if its neighbours have recently fired a spike.\n\n // we use signed conductance values to encode excitatory vs inhibitory synapses.\n // of course, conductance is in fact positive in both these synapses; what differs\n // is the reversal potential.\n g = conductance_net[i][j][l];\n if (g > 0.0)\n Isyn[i][j] -= g * rold[p1[i][j][l]][p2[i][j][l]] * (xold[i][j] - Vna);\n else if (g < 0.0)\n Isyn[i][j] -= -g * rold[p1[i][j][l]][p2[i][j][l]] * (xold[i][j] - Vni);\n\n }\n }\n\n I = Isyn[i][j];\n\n // collect external synaptic currents\n I -= con_upstr_exc * rnoa[i][j] * (xold[i][j] - Vna);\n I -= con_upstr_inh * rnoi[i][j] * (xold[i][j] - Vni);\n\n // Izhikevich neuron:\n // dv/dt = 0.04v^2 + 5v + 140 - u + I\n // du/dt = a(bv - u)\n dx_h[i][j] = 0.04*x*x + 5*x + 140 - y + I;\n dy_h[i][j] = izhi_a * (izhi_b*x - y);\n\n // step:\n xh[i][j] = xold[i][j] + (dx_h[i][j])*delta_t;\n yh[i][j] = yold[i][j] + (dy_h[i][j])*delta_t;\n\n\n // fraction of open receptors.. dr/dt = alpha [T] (1 - r) - beta r\n // ..of synapses within the network:\n rh[i][j] = rold[i][j] + (alp * Hs[i][j] * (1 - rold[i][j]) - bet * rold[i][j]) * delta_t;\n\n // ..of synapses receiving external noise, activatory:\n rnha[i][j] = rnoa[i][j] + (ana * Hna[i][j] * (1 - rnoa[i][j]) - bna * rnoa[i][j]) * delta_t;\n // ..of synapses receiving external noise, inhibitory:\n rnhi[i][j] = rnoi[i][j] + (ani * Hni[i][j] * (1 - rnoi[i][j]) - bni * rnoi[i][j]) * delta_t;\n\n\n }}\n\n\n // second integration step\n double dx;\n double dy;\n double Ihsyn;\n for (j = 0;j=0 && p2[i][j][l]>=0){\n g = conductance_net[i][j][l];\n if (g > 0)\n Ihsyn -= g * rh[p1[i][j][l]][p2[i][j][l]] * (xh[i][j] - Vna);\n else if (g < 0)\n Ihsyn -= -g * rh[p1[i][j][l]][p2[i][j][l]] * (xh[i][j] - Vni);\n }\n }\n\n I = 0.5 * (Isyn[i][j] + Ihsyn);\n\n // input currents from external synapses\n I -= 0.5 * con_upstr_exc * (rnoa[i][j] * (xold[i][j] - Vna) + rnha[i][j] * (xh[i][j] - Vna));\n I -= 0.5 * con_upstr_inh * (rnoi[i][j] * (xold[i][j] - Vni) + rnhi[i][j] * (xh[i][j] - Vni));\n\n // Izhikevich neuron:\n // dv/dt = 0.04v^2 + 5v + 140 - u + I\n // du/dt = a(bv -u)\n dx = 0.04*x*x + 5*x + 140 - y + I;\n dy = izhi_a * (izhi_b*x - y);\n\n xnew[i][j] = xold[i][j] + 0.5*(dx_h[i][j] + dx)*delta_t;\n ynew[i][j] = yold[i][j] + 0.5*(dy_h[i][j] + dy)*delta_t;\n\n // fraction of open receptors.. dr/dt = alpha [T] (1 - r) - beta r\n // ..of synapses within the network:\n rnew[i][j] = rold[i][j] + 0.5 * (alp * Hs[i][j] * (1 - rold[i][j]) - bet * rold[i][j] + alp * Hs[i][j] * (1 - rh[i][j]) - bet * rh[i][j]) * delta_t;\n // ..of synapses receiving external noise, activatory:\n rnna[i][j] = rnoa[i][j] + 0.5 * (ana * Hna[i][j] * (1 - rnoa[i][j]) - bna * rnoa[i][j] + ana * Hna[i][j] * (1 - rnha[i][j]) - bna * rnha[i][j]) * delta_t;\n // ..of synapses receiving external noise, inhibitory:\n rnni[i][j] = rnoi[i][j] + 0.5 * (ani * Hni[i][j] * (1 - rnoi[i][j]) - bni * rnoi[i][j] + ani * Hni[i][j] * (1 - rnhi[i][j]) - bni * rnhi[i][j]) * delta_t;\n\n }}\n\n // identify spike times & prepare next step\n current_time = delta_t * step;\n for (j = 0;j= izhi_reset_threshold){\n xnew[i][j] = izhi_reset_c;\n ynew[i][j] += izhi_recovery_d;\n spikes[i][j] = 1;\n Tl[i][j] = current_time;\n }\n else spikes[i][j] = 0;\n\n // sample random spike times for activatory external input\n if(gsl_rng_uniform(rng) <= (laminex * (double)in_exc[i][j]) * delta_t){\n Tnla[i][j] = current_time;\n }\n // sample random spike times for inhibitory external input\n if(gsl_rng_uniform(rng)<= (lamini * (double)in_inh[i][j]) * delta_t){\n Tnli[i][j] = current_time;\n }\n\n // swap\n xold[i][j] = xnew[i][j];\n yold[i][j] = ynew[i][j];\n rold[i][j] = rnew[i][j];\n rnoa[i][j] = rnna[i][j];\n rnoi[i][j] = rnni[i][j];\n\n if (activation_noise > 0)\n xold[i][j] += (gsl_rng_uniform(rng)-0.5)*activation_noise;\n }}\n\n\n // write the current network state into the provided output buffers.\n // each is a 3D array of shape (M,N,limit) in row first order,\n // so it has strides proportional to (N * limit, limit, 1).\n int linearind = 0;\n for(int oi = 0; oi < M; oi++ ) {\n for(int oj = 0; oj < N; oj++ ) {\n linearind = oi * limit * N + oj * limit + step - 1;\n recording_voltage[linearind] = xnew[oj][oi];\n recording_recov[linearind] = ynew[oj][oi];\n //recording_recov[linearind] = (double) Tnla[oj][oi] == current_time; // <-uncomment to show input spikes instead\n recording_spikes[linearind] = spikes[oj][oi];\n }\n\n }\n } // end of integration loop\n if (verbose){\n printf(\"\\033[2K\");\n fflush(stdout);\n }\n\n gsl_rng_free(rng);\n}\n\n\n\n// helper function to play with the random number generator.\nvoid rantest(long seed,int N,double * out){\n gsl_rng * rng = gsl_rng_alloc(gsl_rng_mt19937); // initialize a mersenne twister rng\n gsl_rng_set(rng, seed); // seed it\n double number = - 1;\n\n for(int i = 0; i\n#include \n#include \n#include \n#include \n#include \n\n#include \"allvars.h\"\n#include \"proto.h\"\n\n/*! \\file b_from_rot_a.c \n * \\brief calculates ror(b) to aloow an initial vector potential\n *\n * This file is only called once after reading the initial condition.\n * It is used to calculate b_ini from a initial vector potential, if needed.\n */\n\n#ifdef BFROMROTA\n\nvoid rot_a(void)\n{\n long long ntot, ntotleft;\n int ndone;\n int *noffset, *nbuffer, *nsend, *nsend_local, *numlist, *ndonelist;\n int i, j, n;\n int npleft;\n int maxfill, source;\n int level, ngrp, sendTask, recvTask;\n int place, nexport;\n double dmax1, dmax2, fac;\n double sumt, sumcomm;\n\n MPI_Status status;\n\n noffset = (int *) mymalloc(sizeof(int) * NTask);\t/* offsets of bunches in common list */\n nbuffer = (int *) mymalloc(sizeof(int) * NTask);\n nsend_local = (int *) mymalloc(sizeof(int) * NTask);\n nsend = (int *) mymalloc(sizeof(int) * NTask * NTask);\n ndonelist = (int *) mymalloc(sizeof(int) * NTask);\n\n NumSphUpdate = N_gas;\n\n numlist = (int *) mymalloc(NTask * sizeof(int) * NTask);\n MPI_Allgather(&NumSphUpdate, 1, MPI_INT, numlist, 1, MPI_INT, MPI_COMM_WORLD);\n for(i = 0, ntot = 0; i < NTask; i++)\n ntot += numlist[i];\n myfree(numlist);\n\n\n i = 0;\t\t\t/* beginn with this index */\n ntotleft = ntot;\t\t/* particles left for all tasks together */\n\n while(ntotleft > 0)\n {\n for(j = 0; j < NTask; j++)\n\tnsend_local[j] = 0;\n\n /* do local particles and prepare export list */\n for(nexport = 0, ndone = 0; i < N_gas && nexport < All.BunchSizeDensity - NTask; i++)\n\t{\n\t ndone++;\n\n\t for(j = 0; j < NTask; j++)\n\t Exportflag[j] = 0;\n\n\t rot_a_evaluate(i, 0);\n\n\t for(j = 0; j < NTask; j++)\n\t {\n\t if(Exportflag[j])\n\t\t{\n\t\t DensDataIn[nexport].Pos[0] = P[i].Pos[0];\n\t\t DensDataIn[nexport].Pos[1] = P[i].Pos[1];\n\t\t DensDataIn[nexport].Pos[2] = P[i].Pos[2];\n\t\t /* using velocity structure for BPred ... */\n\t\t DensDataIn[nexport].Vel[0] = SphP[i].BPred[0];\n\t\t DensDataIn[nexport].Vel[1] = SphP[i].BPred[1];\n\t\t DensDataIn[nexport].Vel[2] = SphP[i].BPred[2];\n\n\t\t DensDataIn[nexport].Hsml = PPP[i].Hsml;\n\t\t DensDataIn[nexport].Index = i;\n\t\t DensDataIn[nexport].Task = j;\n\t\t nexport++;\n\t\t nsend_local[j]++;\n\t\t}\n\t }\n\t}\n\n qsort(DensDataIn, nexport, sizeof(struct densdata_in), dens_compare_key);\n\n for(j = 1, noffset[0] = 0; j < NTask; j++)\n\tnoffset[j] = noffset[j - 1] + nsend_local[j - 1];\n\n MPI_Allgather(nsend_local, NTask, MPI_INT, nsend, NTask, MPI_INT, MPI_COMM_WORLD);\n\n /* now do the particles that need to be exported */\n\n for(level = 1; level < (1 << PTask); level++)\n\t{\n\t for(j = 0; j < NTask; j++)\n\t nbuffer[j] = 0;\n\t for(ngrp = level; ngrp < (1 << PTask); ngrp++)\n\t {\n\t maxfill = 0;\n\t for(j = 0; j < NTask; j++)\n\t\t{\n\t\t if((j ^ ngrp) < NTask)\n\t\t if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])\n\t\t maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];\n\t\t}\n\t if(maxfill >= All.BunchSizeDensity)\n\t\tbreak;\n\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)\n\t\t {\n\t\t /* get the particles */\n\t\t MPI_Sendrecv(&DensDataIn[noffset[recvTask]],\n\t\t\t\t nsend_local[recvTask] * sizeof(struct densdata_in), MPI_BYTE,\n\t\t\t\t recvTask, TAG_DENS_A,\n\t\t\t\t &DensDataGet[nbuffer[ThisTask]],\n\t\t\t\t nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_in),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_A, MPI_COMM_WORLD, &status);\n\t\t }\n\t\t}\n\n\t for(j = 0; j < NTask; j++)\n\t\tif((j ^ ngrp) < NTask)\n\t\t nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];\n\t }\n\n\t for(j = 0; j < nbuffer[ThisTask]; j++)\n\t {\n\t rot_a_evaluate(j, 1);\n\t }\n\n\t MPI_Barrier(MPI_COMM_WORLD);\n\n\t for(j = 0; j < NTask; j++)\n\t nbuffer[j] = 0;\n\t for(ngrp = level; ngrp < (1 << PTask); ngrp++)\n\t {\n\t maxfill = 0;\n\t for(j = 0; j < NTask; j++)\n\t\t{\n\t\t if((j ^ ngrp) < NTask)\n\t\t if(maxfill < nbuffer[j] + nsend[(j ^ ngrp) * NTask + j])\n\t\t maxfill = nbuffer[j] + nsend[(j ^ ngrp) * NTask + j];\n\t\t}\n\t if(maxfill >= All.BunchSizeDensity)\n\t\tbreak;\n\n\t sendTask = ThisTask;\n\t recvTask = ThisTask ^ ngrp;\n\n\t if(recvTask < NTask)\n\t\t{\n\t\t if(nsend[ThisTask * NTask + recvTask] > 0 || nsend[recvTask * NTask + ThisTask] > 0)\n\t\t {\n\t\t /* send the results */\n\t\t MPI_Sendrecv(&DensDataResult[nbuffer[ThisTask]],\n\t\t\t\t nsend[recvTask * NTask + ThisTask] * sizeof(struct densdata_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B,\n\t\t\t\t &DensDataPartialResult[noffset[recvTask]],\n\t\t\t\t nsend_local[recvTask] * sizeof(struct densdata_out),\n\t\t\t\t MPI_BYTE, recvTask, TAG_DENS_B, MPI_COMM_WORLD, &status);\n\n\t\t /* add the result to the particles */\n\t\t for(j = 0; j < nsend_local[recvTask]; j++)\n\t\t\t{\n\t\t\t source = j + noffset[recvTask];\n\t\t\t place = DensDataIn[source].Index;\n\n\t\t\t SphP[place].BSmooth[0] += DensDataPartialResult[source].BSmooth[0];\n\t\t\t SphP[place].BSmooth[1] += DensDataPartialResult[source].BSmooth[1];\n\t\t\t SphP[place].BSmooth[2] += DensDataPartialResult[source].BSmooth[2];\n\t\t\t SphP[place].DensityNorm += DensDataPartialResult[source].DensityNorm;\n\t\t\t}\n\t\t }\n\t\t}\n\n\t for(j = 0; j < NTask; j++)\n\t\tif((j ^ ngrp) < NTask)\n\t\t nbuffer[j] += nsend[(j ^ ngrp) * NTask + j];\n\t }\n\n\t level = ngrp - 1;\n\t}\n\n MPI_Allgather(&ndone, 1, MPI_INT, ndonelist, 1, MPI_INT, MPI_COMM_WORLD);\n for(j = 0; j < NTask; j++)\n\tntotleft -= ndonelist[j];\n }\n\n for(i = 0; i < N_gas; i++)\n for(j = 0; j < 3; j++)\n#ifndef IGNORE_PERIODIC_IN_ROTA\n SphP[i].B[j] = SphP[i].BPred[j] = SphP[i].BSmooth[j] / SphP[i].d.Density;\n#else\n SphP[i].B[j] = SphP[i].BPred[j] = SphP[i].BSmooth[j] / SphP[i].DensityNorm;\n#endif\n myfree(ndonelist);\n myfree(nsend);\n myfree(nsend_local);\n myfree(nbuffer);\n myfree(noffset);\n\n}\n\n\n\n/*! This function represents the core of the calculus of rot of vector potential\n * target particle may either be local, or reside in the communication\n * buffer.\n */\nvoid rot_a_evaluate(int target, int mode)\n{\n int j, n;\n int startnode, numngb, numngb_inbox;\n double h, h2, fac, hinv, hinv3, hinv4;\n\n double wk, dwk;\n double dx, dy, dz, r, r2, u, mass_j, rho;\n double dbx, dby, dbz;\n\n double rotb[3];\n\n MyFloat *pos, *b;\n\n rho = rotb[0] = rotb[1] = rotb[2] = 0;\n\n\n if(mode == 0)\n {\n pos = P[target].Pos;\n b = SphP[target].BPred;\n h = PPP[target].Hsml;\n }\n else\n {\n pos = DensDataGet[target].Pos;\n b = DensDataGet[target].Vel;\t/* Using Vel structure for BPred !!!! */\n h = DensDataGet[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 startnode = All.MaxPart;\n do\n {\n numngb_inbox = ngb_treefind_variable(&pos[0], 2 * h, &startnode);\n\n 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\t dbx = b[0] - SphP[j].BPred[0];\n\t dby = b[1] - SphP[j].BPred[1];\n\t dbz = b[2] - SphP[j].BPred[2];\n\n#ifndef IGNORE_PERIODIC_IN_ROTA\n#ifdef PERIODIC\t\t\t/* now find the closest image in the given box size */\n\t if(dx > boxHalf_X)\n\t dx -= boxSize_X;\n\t if(dx < -boxHalf_X)\n\t dx += boxSize_X;\n\t if(dy > boxHalf_Y)\n\t {\n#ifdef BRIOWU\n\t dbz /= dy;\n#endif\n\t dy -= boxSize_Y;\n#ifdef BRIOWU\n\t dbz *= dy;\n#endif\n\t }\n\t if(dy < -boxHalf_Y)\n\t {\n#ifdef BRIOWU\n\t dbz /= dy;\n#endif\n\t dy += boxSize_Y;\n#ifdef BRIOWU\n\t dbz *= dy;\n#endif\n\t }\n\t if(dz > boxHalf_Z)\n\t {\n#ifdef BRIOWU\n\t dbx /= dz;\n#endif\n\t dz -= boxSize_Z;\n#ifdef BRIOWU\n\t dbx *= dz;\n#endif\n\t }\n\t if(dz < -boxHalf_Z)\n\t {\n#ifdef BRIOWU\n\t dbx /= dz;\n#endif\n\t dz += boxSize_Z;\n#ifdef BRIOWU\n\t dbx *= dz;\n#endif\n\t }\n#endif\n#endif\n\t r2 = dx * dx + dy * dy + dz * dz;\n\n\t if(r2 < h2)\n\t {\n\t r = sqrt(r2);\n\t u = r * hinv;\n\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 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 mass_j = P[j].Mass;\n\n\t rho += mass_j * wk;\n\n\t if(r > 0)\n\t\t{\n\t\t fac = mass_j * dwk / r;\n#ifndef BRIOWU\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#else\n\t\t rotb[0] += FLT(fac * (-dy * dbz));\n\t\t rotb[1] += FLT(fac * (-dz * dbx));\n\t\t rotb[2] += FLT(fac * (0.0));\n#endif\n\t\t}\n\t }\n\t}\n\n }\n while(startnode >= 0);\n\n if(mode == 0)\n {\n SphP[target].BSmooth[0] = rotb[0];\t/* giving back rot(B) in the Smooth */\n SphP[target].BSmooth[1] = rotb[1];\t/* Data structure !!! */\n SphP[target].BSmooth[2] = rotb[2];\n SphP[target].DensityNorm = rho;\n }\n else\n {\n DensDataResult[target].BSmooth[0] = rotb[0];\n DensDataResult[target].BSmooth[1] = rotb[1];\n DensDataResult[target].BSmooth[2] = rotb[2];\n DensDataResult[target].DensityNorm = rho;\n }\n}\n\n#endif\n", "meta": {"hexsha": "cca8a0fe8155fc3da45ae100cdb68837260cc218", "size": 9333, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/b_from_rot_a.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/b_from_rot_a.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/b_from_rot_a.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": 24.4319371728, "max_line_length": 91, "alphanum_fraction": 0.5681988642, "num_tokens": 3331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.4301473485858429, "lm_q1q2_score": 0.23017117030618783}} {"text": "#pragma once\n#include \"Type/peColor.h\"\n#include \"Type\\peBitmask.h\"\n#include \"peCoreDefs.h\"\n\n#include \n#undef max\n#include \n#include \n\n#pragma warning(push)\n#pragma warning(disable : 4251)\n\n/*\n * Everything in here is taking more or less one-to-one from 'Physically based\n * rendering' (Pharr, Humphreys, 2010)\n */\n\nnamespace pe {\nstruct Sample;\nclass peCoordSys;\n\n//! \\brief Represents a color spectrum. We will use RGB with floating-point\n//! precision here\nusing Spectrum_t = RGB_32BitFloat;\n\n//! \\brief Types of BRDFs and BTDFs\nenum class BxDFType {\n Reflection = 1 << 0,\n Transmission = 1 << 1,\n Diffuse = 1 << 2,\n Glossy = 1 << 3,\n Specular = 1 << 4,\n AllTypes = Diffuse | Glossy | Specular,\n AllReflection = Reflection | AllTypes,\n AllTransmission = Transmission | AllTypes,\n All = AllReflection | AllTransmission\n};\n\ntemplate <> struct EnableEnumBitmask : std::true_type {};\n\n//! \\brief BRDF or BTDF base class\nclass PE_CORE_API peBxDF {\npublic:\n virtual ~peBxDF() = default;\n explicit peBxDF(BxDFType type);\n\n bool HasFlags(BxDFType flags) const;\n\n auto Type() const { return _type; }\n\n //! \\brief Evaluate this BxDF for the given outgoing and incoming vectors\n //! \\param wo Outgoing vector\n //! \\param wi Incoming vector\n //! \\returns Value of the distribution function for the two vectors\n virtual Spectrum_t Eval(const glm::vec3 &wo, const glm::vec3 &wi) const = 0;\n\n //! \\brief Sampling function for BxDF distributions that utilize delta\n //! distributions. Here, the incident direction wi cannot\n //! be known to the user, hence the BxDF computes it\n //! \\param wo Outgoing vector\n //! \\param wi Incoming vector, will be computed by the BxDF\n //! \\param rnd1 First uniform random variable\n //! \\param rnd2 Second uniform random variable\n //! \\param pdf Probability density function for this BxDF and the given pair\n //! of vectors \\returns Value of the distribution function for the two vectors\n virtual Spectrum_t Sample_f(const glm::vec3 &wo, glm::vec3 &wi,\n const float rnd1, const float rnd2,\n float &pdf) const;\n\n //! \\brief Computes the hemishperical-directional reflectance, which is the\n //! total reflection in the given direction due to constant illumination over\n //! the hemisphere. Not every BxDF will be able to compute this in closed\n //! form, so they will use something like a monte carlo algorithm to compute\n //! it, hence the member\n //! \\param wo Outgoing vector\n //! \\param samples Samples\n //! \\returns Hemispherical reflection around \n virtual Spectrum_t rho(const glm::vec3 &wo,\n const gsl::span &samples) const;\n\n //! \\brief Computes the hemispherical-hemispherical reflectance, which is the\n //! fraction of incident light reflected by the surface when the incident\n //! light is the same from all directions. Not every BxDF will be able to\n //! compute this in closed form, so they will use something like a monte carlo\n //! algorithm to compute it\n //! \\param samples1 First set of samples for monte carlo method\n //! \\param samples2 Second set of samples for monte carlo method\n //! \\returns Direction-independent reflectance\n virtual Spectrum_t rho(const gsl::span &samples1,\n const gsl::span &samples2) const;\n\n //! \\brief Returns the probability density function for the given pairs of\n //! vectors \\param wo Outgoing vector in shading space \\param wi Incoming\n //! vector in shading space \\returns PDF\n virtual float Pdf(const glm::vec3 &wo, const glm::vec3 &wi) const;\n\nprivate:\n const BxDFType _type;\n};\n\n#pragma region Fresnel\n\n//! \\brief Helper class to encapsulate fresnel reflectance\nstruct PE_CORE_API peFresnel {\n virtual ~peFresnel() {}\n virtual Spectrum_t Eval(float cosi) const = 0;\n};\n\n//! \\brief Fresnel reflectance for a conductor\nclass PE_CORE_API peFresnelConductor : public peFresnel {\npublic:\n //! \\brief Initializes this FresnelConductor structure with the given index of\n //! refraction and absorption\n //! \\param eta Index of refraction of conductor\n //! \\param k Absorption index of conductor\n peFresnelConductor(const Spectrum_t &eta, const Spectrum_t &k);\n Spectrum_t Eval(float cosi) const override;\n\nprivate:\n const Spectrum_t _eta;\n const Spectrum_t _k;\n};\n\n//! \\brief Fresnel reflectance for dielectric material\nclass PE_CORE_API peFresnelDielectric : public peFresnel {\npublic:\n //! \\brief Initializes this FresnelDielectric structure with the given\n //! incident and transmitted medium indices of refraction\n //! \\param etaIncident Index of refraction for incident material\n //! \\param etaTransmitted Index of refraction for transmitted material\n peFresnelDielectric(float etaIncident, float etaTransmitted);\n Spectrum_t Eval(float cosi) const override;\n\nprivate:\n const float _etaIndicent, _etaTransmitted;\n};\n\n#pragma endregion\n\n//! \\brief BRDF for specular reflection\nclass PE_CORE_API peSpecularReflection : public peBxDF {\npublic:\n peSpecularReflection(const Spectrum_t &spectrum, const peFresnel &fresnel);\n\n Spectrum_t Eval(const glm::vec3 &wo, const glm::vec3 &wi) const override;\n Spectrum_t Sample_f(const glm::vec3 &wo, glm::vec3 &wi, const float rnd1,\n const float rnd2, float &pdf) const override;\n\nprivate:\n const Spectrum_t _color;\n const peFresnel &_fresnel;\n};\n\n//! \\brief Lambertian diffuse reflection\nclass PE_CORE_API peLambert : public peBxDF {\npublic:\n explicit peLambert(const Spectrum_t &color);\n Spectrum_t Eval(const glm::vec3 &wo, const glm::vec3 &wi) const override;\n\n Spectrum_t rho(const glm::vec3 &wo,\n const gsl::span &samples) const override;\n Spectrum_t rho(const gsl::span &samples1,\n const gsl::span &samples2) const override;\n\nprivate:\n const Spectrum_t _color;\n};\n\n//! \\brief Random values for BSDF sampling\nstruct PE_CORE_API BSDFSample {\n BSDFSample() = default;\n BSDFSample(const glm::vec2 &dir, float component);\n template explicit BSDFSample(Rnd &rng) {\n std::uniform_real_distribution dist{0.f, 1.f};\n dir = {dist(rng), dist(rng)};\n component = dist(rng);\n }\n\n glm::vec2 dir;\n float component;\n};\n\n//! \\brief Bidirectional scattering distribution function. Determines surface\n//! properties of an object\nclass PE_CORE_API BSDF {\npublic:\n BSDF();\n\n BSDF(const BSDF &other);\n BSDF(BSDF &&other) noexcept;\n\n BSDF &operator=(const BSDF &);\n BSDF &operator=(BSDF &&) noexcept;\n\n void Add(peBxDF const *bxdf);\n\n uint32_t NumBxDFs() const;\n uint32_t NumBxDFsWithFlags(BxDFType flags) const;\n\n //! \\brief Evaluate the BSDF for the given set of incoming and outgoing\n //! vectors \\param outgoingWorld Outgoing vector in world space \\param\n //! incomingWorld Incoming vector in world space \\param shadingCoordSys\n //! Shading coordinate system \\param flags Types of BxDFs to sample \\param\n //! geometricNormal The normal of the actual geometry for the evaluated point\n //! \\returns Evaluated spectrum\n Spectrum_t Eval(const glm::vec3 &outgoingWorld,\n const glm::vec3 &incomingWorld,\n const peCoordSys &shadingCoordSys,\n const glm::vec3 &geometricNormal, BxDFType flags) const;\n\n //! \\brief Sample this BSDF by evaluating a random BxDF\n Spectrum_t Sample_f(const glm::vec3 &wo, glm::vec3 &wi,\n const peCoordSys &shadingCoordSys,\n const glm::vec3 &geometryNormal, const BSDFSample &sample,\n float &pdf, BxDFType flags, BxDFType &sampledType) const;\n\n //! \\brief Sums up the hemispherical-hemispherical reflectance values of\n //! all assigned BxDFs \\param rnd Random number generator for monte carlo\n //! method \\param flags Types of BxDFs to sample \\param sqrtSamples\n //! Sampling parameter for monte carlo \\returns Summed reflectance\n Spectrum_t rho(std::default_random_engine &rnd,\n BxDFType flags = BxDFType::All,\n uint32_t sqrtSamples = 6) const;\n\n //! \\brief Sums up the hemispherical-directional reflectance values of all\n //! assigned BxDFs \\param wo Outgoing direction \\param rnd Random number\n //! generator for monte carlo method \\param flags Types of BxDFs to sample\n //! \\param sqrtSamples Sampling parameter for monte carlo\n //! \\returns Summed reflectance\n Spectrum_t rho(const glm::vec3 &wo, std::default_random_engine &rnd,\n BxDFType flags = BxDFType::All,\n uint32_t sqrtSamples = 6) const;\n\n //! \\brief Probability density function of this BSDF for the given pair of\n //! vectors \\param wo Outgoing vector in world space \\param wi Incoming vector\n //! in world space\n float Pdf(const glm::vec3 &wo, const glm::vec3 &wi,\n const peCoordSys &shadingCoordSys,\n BxDFType flags = BxDFType::All) const;\n\nprivate:\n constexpr static size_t MaxBxDF = 8;\n uint32_t _numBxdfs;\n std::array _bxdfs;\n};\n\n#pragma region HelperFunctions\n\n//! \\brief Computes fresnel reflectance for dielectric materials\n//! \\param cosIncident Cosine of angle of incident direction\n//! \\param cosTransmitted Cosine of angle of transmitted direction\n//! \\param etaIncident Index of refraction for incident medium\n//! \\param etaTransmitted Index of refraction for transmitted medium\n//! \\returns Fresnel reflectance\nSpectrum_t PE_CORE_API FresnelDielectric(float cosIncident,\n float cosTransmitted,\n const Spectrum_t &etaIncident,\n const Spectrum_t &etaTransmitted);\n\n//! \\brief Computes the fresnel reflectance for a conducting material\n//! \\param cosIndicent Cosine of the angle of incident direction\n//! \\param eta Index of refraction of the conductor\n//! \\param k Absorption coefficient\n//! \\returns Fresnel reflectance\nSpectrum_t PE_CORE_API FresnelConductor(float cosIndicent,\n const Spectrum_t &eta,\n const Spectrum_t &k);\n\n//! \\brief Helper to evaluate fresnel shading for dieletric materials\n//! \\param cosIncident Cosine of angle of incident direction\n//! \\param etaIncident Index of refraction of incident medium\n//! \\param etaTransmitted Index of refraction of transmitted medium\n//! \\returns Fresnel reflectance\nSpectrum_t PE_CORE_API EvalFresnelDielectric(float cosIncident,\n float etaIncident,\n float etaTransmitted);\n\n#pragma endregion\n\n} // namespace pe\n\n#pragma warning(pop)\n", "meta": {"hexsha": "5e4e74eda0aa09dfa14ff56d1d40873ba17030a5", "size": 10776, "ext": "h", "lang": "C", "max_stars_repo_path": "PrismaticCore/Headers/Rendering/Utility/peBxDF.h", "max_stars_repo_name": "Mortano/Prismatic", "max_stars_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PrismaticCore/Headers/Rendering/Utility/peBxDF.h", "max_issues_repo_name": "Mortano/Prismatic", "max_issues_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PrismaticCore/Headers/Rendering/Utility/peBxDF.h", "max_forks_repo_name": "Mortano/Prismatic", "max_forks_repo_head_hexsha": "e2e931e1ee8bfd3899b26f8c91e593f0d7213d64", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.9436619718, "max_line_length": 80, "alphanum_fraction": 0.7023942094, "num_tokens": 2630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.4455295350395727, "lm_q1q2_score": 0.2297239013092188}} {"text": "/**\n *\n * @file sgecon.c\n *\n * PLASMA computational routines\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Jakub Kurzak\n * @author Ichitaro Yamazaki\n * @author Mathieu Faverge\n * @date 2012-10-04\n * @generated s Tue Jan 7 11:45:10 2014\n *\n **/\n#include \n#include \"common.h\"\n#include \n#undef COMPLEX\n#define REAL\n\n/***************************************************************************//**\n *\n * @ingroup float\n *\n * PLASMA_sgecon - estimates the reciprocal of the condition number\n * of a general complex matrix A, in either the 1-norm or the infinity-norm,\n * using the LU factorization computed by PLASMA_sgetrf().\n *\n * An estimate is obtained for norm(inv(A)), and the reciprocal of the condition\n * number is computed as\n *\n * \\f[ rcond = \\frac{1}{\\|\\|A\\-\\| \\times \\-\\|A^{-1}\\|\\|} \\f]\n *\n *******************************************************************************\n *\n * @param[in] norm\n * Specifies whether the 1-norm condition number\n * or the infinity-norm condition number is required:\n * = PlasmaOneNorm: One norm\n * = PlasmaInfNorm: Infinity norm\n *\n * @param[in] N\n * The order of the matrix A. N >= 0.\n *\n * @param[in] A\n * The N-by-N matrix A.\n *\n * @param[in] LDA\n * The leading dimension of the array A. LDA >= max(1,N).\n *\n * @param[in] Anorm\n * If norm = PlasmaOneNorm, the 1-norm of the original matrix A.\n * If norm = PlasmaInfNorm, the infinity-norm of the original matrix A.\n *\n * \\param[out] rcond\n * The reciprocal of the condition number of the matrix A,\n * computed as stated above.\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if -i, the i-th argument had an illegal value\n *\n *******************************************************************************\n *\n * @sa PLASMA_sgecon_Tile\n * @sa PLASMA_sgecon_Tile_Async\n * @sa PLASMA_cgecon\n * @sa PLASMA_dgecon\n * @sa PLASMA_sgecon\n *\n ******************************************************************************/\nint PLASMA_sgecon(PLASMA_enum norm, int N,\n float *A, int LDA, float Anorm, float *rcond)\n{\n int NB;\n int status;\n plasma_context_t *plasma;\n PLASMA_sequence *sequence = NULL;\n PLASMA_request request = PLASMA_REQUEST_INITIALIZER;\n PLASMA_desc descA;\n\n plasma = plasma_context_self();\n if (plasma == NULL) {\n plasma_fatal_error(\"PLASMA_sgecon\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n /* Check input arguments */\n if (norm != PlasmaOneNorm && norm != PlasmaInfNorm) {\n plasma_error(\"PLASMA_sgecon\", \"illegal value of norm\");\n return -1;\n }\n if (N < 0) {\n plasma_error(\"PLASMA_sgecon\", \"illegal value of N\");\n return -2;\n }\n if (LDA < max(1,N)) {\n plasma_error(\"PLASMA_sgecon\", \"illegal value of LDA\");\n return -4;\n }\n if (Anorm < 0.) {\n plasma_error(\"PLASMA_sgecon\", \"illegal value of Anorm\");\n return -5;\n }\n\n /* Quick return */\n *rcond = (float)0.;\n if (N == 0) {\n *rcond = (float)1.;\n return PLASMA_SUCCESS;\n }\n else if (Anorm == 0.) {\n return PLASMA_SUCCESS;\n }\n\n /* Tune NB depending on M, N & NRHS; Set NBNB */\n status = plasma_tune(PLASMA_FUNC_SGESV, N, N, 0);\n if (status != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_sgecon\", \"plasma_tune() failed\");\n return status;\n }\n /* Set NT */\n NB = PLASMA_NB;\n plasma_sequence_create(plasma, &sequence);\n\n if (PLASMA_TRANSLATION == PLASMA_OUTOFPLACE) {\n plasma_sooplap2tile(\n descA, A, NB, NB, LDA, N, 0, 0, N, N,\n sequence, &request, plasma_desc_mat_free(&(descA)));\n } else {\n plasma_siplap2tile(\n descA, A, NB, NB, LDA, N, 0, 0, N, N, sequence, &request);\n }\n\n /* Call the tile interface */\n PLASMA_sgecon_Tile_Async(norm, &descA, Anorm, rcond, sequence, &request);\n\n if (PLASMA_TRANSLATION == PLASMA_OUTOFPLACE) {\n plasma_dynamic_sync();\n plasma_desc_mat_free(&descA);\n } else {\n plasma_siptile2lap(descA, A, NB, NB, LDA, N, sequence, &request);\n plasma_dynamic_sync();\n }\n\n status = sequence->status;\n plasma_sequence_destroy(plasma, sequence);\n return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup float_Tile\n *\n * PLASMA_sgecon_Tile - estimates the reciprocal of the condition number\n * of a general complex matrix A, in either the 1-norm or the infinity-norm.\n * Tile equivalent of PLASMA_sgecon().\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] norm\n * Specifies whether the 1-norm condition number\n * or the infinity-norm condition number is required:\n * = PlasmaOneNorm: One norm\n * = PlasmaInfNorm: Infinity norm\n *\n * @param[in] A\n * The N-by-N matrix A.\n *\n * @param[in] Anorm\n * If norm = PlasmaOneNorm, the 1-norm of the original matrix A.\n * If norm = PlasmaInfNorm, the infinity-norm of the original matrix A.\n *\n * \\param[out] rcond\n * The reciprocal of the condition number of the matrix A,\n * computed as stated above.\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if -i, the i-th argument had an illegal value\n *\n *******************************************************************************\n *\n * @sa PLASMA_sgecon\n * @sa PLASMA_sgecon_Tile_Async\n * @sa PLASMA_cgecon_Tile\n * @sa PLASMA_dgecon_Tile\n * @sa PLASMA_sgecon_Tile\n *\n ******************************************************************************/\nint PLASMA_sgecon_Tile(PLASMA_enum norm, PLASMA_desc *A, float Anorm, float *rcond)\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_sgecon_Tile\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n plasma_sequence_create(plasma, &sequence);\n PLASMA_sgecon_Tile_Async(norm, A, Anorm, rcond, sequence, &request);\n plasma_dynamic_sync();\n status = sequence->status;\n plasma_sequence_destroy(plasma, sequence);\n return status;\n}\n\n/***************************************************************************//**\n *\n * @ingroup float_Tile_Async\n *\n * PLASMA_sgecon_Tile_Async - estimates the reciprocal of the condition number\n * of a general complex matrix A, in either the 1-norm or the infinity-norm.\n * Non-blocking equivalent of PLASMA_sgecon_Tile().\n * May return before the computation is finished.\n * Allows for pipelining of operations at runtime.\n *\n *******************************************************************************\n *\n * @param[in] sequence\n * Identifies the sequence of function calls that this call belongs to\n * (for completion checks and exception handling purposes).\n *\n * @param[out] request\n * Identifies this function call (for exception handling purposes).\n *\n *******************************************************************************\n *\n * @sa PLASMA_sgecon\n * @sa PLASMA_sgecon_Tile\n * @sa PLASMA_cgecon_Tile_Async\n * @sa PLASMA_dgecon_Tile_Async\n * @sa PLASMA_sgecon_Tile_Async\n *\n ******************************************************************************/\nint PLASMA_sgecon_Tile_Async(PLASMA_enum norm, PLASMA_desc *A, float Anorm, float *rcond,\n PLASMA_sequence *sequence, PLASMA_request *request)\n{\n plasma_context_t *plasma;\n PLASMA_desc descA;\n PLASMA_desc descW;\n float *workN;\n float Ainvnorm;\n int kase, kase1;\n int isave[3], itrs = 0;\n int fallback = PLASMA_FALSE;\n\n plasma = plasma_context_self();\n if (plasma == NULL) {\n plasma_fatal_error(\"PLASMA_sgecon_Tile_Async\", \"PLASMA not initialized\");\n return PLASMA_ERR_NOT_INITIALIZED;\n }\n if (sequence == NULL) {\n plasma_fatal_error(\"PLASMA_sgecon_Tile_Async\", \"NULL sequence\");\n return PLASMA_ERR_UNALLOCATED;\n }\n if (request == NULL) {\n plasma_fatal_error(\"PLASMA_sgecon_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 ( A->m != A->n ) {\n plasma_error(\"PLASMA_sgecon_Tile_Async\", \"invalid A descriptor (not square)\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n if (plasma_desc_check(A) != PLASMA_SUCCESS) {\n plasma_error(\"PLASMA_sgecon_Tile_Async\", \"invalid first descriptor\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n } else {\n descA = *A;\n }\n /* Check input arguments */\n if (descA.nb != descA.mb) {\n plasma_error(\"PLASMA_sgecon_Tile_Async\", \"only square tiles supported\");\n return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE);\n }\n\n /* Quick return */\n *rcond = (float)0.;\n if (descA.m == 0) {\n *rcond = (float)1.;\n return PLASMA_SUCCESS;\n }\n else if (Anorm == 0.) {\n return PLASMA_SUCCESS;\n }\n\n /* Estimate the norm of inv(A). */\n Ainvnorm = (float)0.;\n if (norm == PlasmaOneNorm)\n kase1 = 1;\n else\n kase1 = 2;\n kase = 0;\n\n#if defined(REAL)\n int *isgn = (int*)plasma_shared_alloc(plasma, descA.m, PlasmaInteger);\n#endif\n\n workN = (float*)plasma_shared_alloc(plasma, descA.m, PlasmaRealFloat);\n plasma_sdesc_alloc( descW, descA.mb, descA.nb,\n descA.m, 1, 0, 0, descA.m, 1, plasma_desc_mat_free(&(descW)));\n\n do {\n itrs ++;\n#if defined(REAL)\n LAPACKE_slacn2_work( descA.m, workN, descW.mat, isgn, &Ainvnorm, &kase, isave);\n#else\n LAPACKE_slacn2_work( descA.m, workN, descW.mat, &Ainvnorm, &kase, isave);\n#endif\n\n#define FALLBACK\n#ifdef FALLBACK\n /*\n * Fall back to LAPACK\n */\n if( isnan(Ainvnorm) || isinf(Ainvnorm) || Ainvnorm > LAPACKE_slamch('O') ) {\n int info;\n float *Atmp = (float*)malloc(descA.m * descA.n * sizeof(float));\n\n plasma_sooptile2lap( descA, Atmp, descA.mb, descA.nb, descA.m, descA.n, sequence, request);\n plasma_dynamic_sync();\n info = LAPACKE_sgecon(LAPACK_COL_MAJOR, lapack_const(norm), descA.n, Atmp, descA.m, Anorm, rcond);\n free(Atmp);\n fallback = PLASMA_TRUE;\n sequence->status = info;\n kase = 0;\n }\n#endif\n\n if (kase != 0) {\n if (kase == kase1) {\n /* Multiply by inv(L). */\n plasma_parallel_call_9(plasma_pstrsm,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaLower,\n PLASMA_enum, PlasmaNoTrans,\n PLASMA_enum, PlasmaUnit,\n float, 1.0,\n PLASMA_desc, descA,\n PLASMA_desc, descW,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n\n /* Multiply by inv(U). */\n plasma_parallel_call_9(plasma_pstrsm,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaUpper,\n PLASMA_enum, PlasmaNoTrans,\n PLASMA_enum, PlasmaNonUnit,\n float, 1.0,\n PLASMA_desc, descA,\n PLASMA_desc, descW,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n }\n else {\n /* Multiply by inv(U**T). */\n plasma_parallel_call_9(plasma_pstrsm,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaUpper,\n PLASMA_enum, PlasmaTrans,\n PLASMA_enum, PlasmaNonUnit,\n float, 1.0,\n PLASMA_desc, descA,\n PLASMA_desc, descW,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n\n /* Multiply by inv(L**T). */\n plasma_parallel_call_9(plasma_pstrsm,\n PLASMA_enum, PlasmaLeft,\n PLASMA_enum, PlasmaLower,\n PLASMA_enum, PlasmaTrans,\n PLASMA_enum, PlasmaUnit,\n float, 1.0,\n PLASMA_desc, descA,\n PLASMA_desc, descW,\n PLASMA_sequence*, sequence,\n PLASMA_request*, request);\n }\n }\n plasma_dynamic_sync();\n }\n while (kase != 0);\n\n /* Compute the estimate of the reciprocal condition number. */\n if ((Ainvnorm != 0.0) && (fallback == PLASMA_FALSE)) {\n *rcond = ((float)1.0 / Ainvnorm) / Anorm;\n }\n\n#if defined(REAL)\n plasma_shared_free(plasma, isgn);\n#endif\n plasma_shared_free(plasma, workN);\n plasma_desc_mat_free(&descW);\n\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "049e448ce307a41b20f16d5f90a14adae1930fb0", "size": 13776, "ext": "c", "lang": "C", "max_stars_repo_path": "compute/sgecon.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/sgecon.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/sgecon.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.035971223, "max_line_length": 110, "alphanum_fraction": 0.5516840883, "num_tokens": 3510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6261241632752915, "lm_q2_score": 0.36658973632215985, "lm_q1q2_score": 0.2295306919200221}} {"text": "#ifndef NonLinearLSQ_h\n#define NonLinearLSQ_h\n/** \n * @file \n * $Revision: 4928 $\n * $Date: 2012-12-21 10:44:12 -0700 (Fri, 21 Dec 2012) $\n * $Id: NonLinearLSQ.h 4928 2012-12-21 17:44:12Z slambright@GS.DOI.NET $\n * \n * Unless noted otherwise, the portions of Isis written by the USGS are \n * public domain. See individual third-party library and package descriptions \n * for intellectual property information, user agreements, and related \n * information. \n * \n * Although Isis has been used by the USGS, no warranty, expressed or \n * implied, is made by the USGS as to the accuracy and functioning of such \n * software and related material nor shall the fact of distribution \n * constitute any such warranty, and no responsibility is assumed by the\n * USGS in connection therewith. \n * \n * For additional information, launch \n * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html \n * in a browser or see the Privacy & Disclaimers page on the Isis website,\n * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on\n * http://www.usgs.gov/privacy.html. \n */ \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"IException.h\"\n\nnamespace Isis {\n\n /**\n * @brief NonLinearLSQ Computes a fit using a Levenberg-Marquardt algorithm\n * \n * This virtual base class uses the GSL toolkit to apply the \n * Levenberg-Marquardt algorithm to fit data to a non-linear equation using \n * least squares. \n * \n * @ingroup Utility\n * @author 2007-11-15 Kris Becker\n *\n * @internal\n */\n class NonLinearLSQ {\n public:\n typedef TNT::Array1D NLVector;\n typedef TNT::Array2D NLMatrix;\n\n // Constructors and Destructor\n NonLinearLSQ() : _fitParms(), _uncert(), _nIters(0), _maxIters(50),\n _status(0), _userTerminated(false), _userMessage() {}\n\n /** Destructor */\n virtual ~NonLinearLSQ() { }\n\n virtual int nSize() const = 0;\n virtual int nParms() const = 0;\n\n /** \n * @brief Sets the maximum number of iterations\n * \n * @param m User provides the maximum number iterations\n */\n void setMaxIters(int m) { _maxIters = m; }\n\n /** \n * @brief Maximum number iterations for valid solution\n * \n * \n * @return int Maximum resolutions\n */\n int maxIters() const { return (_maxIters); }\n\n virtual NLVector guess() = 0;\n virtual NLVector f_x(const NLVector &x) = 0;\n virtual NLMatrix df_x(const NLVector &x) = 0;\n\n virtual double absErr() const { return (1.0E-4); }\n virtual double relErr() const { return (1.0E-4); }\n\n int curvefit();\n /** Return status of last fit processing */\n inline int status() const { return (_status); }\n /** Determine success from last fit processing */\n inline bool success() const { return (_status == GSL_SUCCESS); }\n /** Check status for success of the given condition */\n inline bool success(int status) const { return (status == GSL_SUCCESS); }\n /** Return error message pertaining to last fit procesing */\n inline QString statusstr() const { \n return (QString(gsl_strerror(_status)));\n }\n /** Return error message given status condition */\n inline QString statusstr(int status) const { \n return (QString(gsl_strerror(status)));\n }\n\n /** Default interation test simply returns input status */\n virtual int checkIteration(const int Iter, const NLVector &fitcoefs, \n const NLVector &uncerts, double cplxconj,\n int Istatus) { \n return (Istatus);\n }\n\n /** Return coefficients from last fit processing */\n inline NLVector coefs() const { return (_fitParms); }\n /** Return uncertainties from last fit processing */\n inline NLVector uncert() const { return (_uncert); }\n /** Return number of iterations from last fit processing */\n inline int nIterations() const { return (_nIters); }\n\n protected:\n void Terminate(const QString &message = \"\");\n void Abort(const QString &reason = \"\");\n\n bool doContinue() const { return (!_userTerminated); }\n\n\n private:\n NLVector _fitParms;\n NLVector _uncert;\n int _nIters;\n int _maxIters;\n int _status;\n bool _userTerminated;\n QString _userMessage;\n\n struct _nlsqPointer {\n NonLinearLSQ *nlsq;\n };\n static int f(const gsl_vector *x, void *params, gsl_vector *fx);\n static int df(const gsl_vector *x, void *params, gsl_matrix *J);\n static int fdf(const gsl_vector *x, void *params, gsl_vector *fx, \n gsl_matrix *J);\n\n NLVector gslToNlsq(const gsl_vector *v) const;\n NLMatrix gslToNlsq(const gsl_matrix *m) const;\n gsl_vector *NlsqTogsl(const NLVector &v, gsl_vector *gv = 0) const;\n gsl_matrix *NlsqTogsl(const NLMatrix &m, gsl_matrix *gm = 0) const;\n NLVector getUncertainty(const gsl_matrix *m) const;\n };\n\n} // namespace Isis\n#endif\n\n", "meta": {"hexsha": "35356bd2560a0fab1a1647c2f8bb4e8f494ebb22", "size": 5934, "ext": "h", "lang": "C", "max_stars_repo_path": "isis/src/mro/apps/hical/NonLinearLSQ.h", "max_stars_repo_name": "ihumphrey-usgs/ISIS3_old", "max_stars_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "isis/src/mro/apps/hical/NonLinearLSQ.h", "max_issues_repo_name": "ihumphrey-usgs/ISIS3_old", "max_issues_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "isis/src/mro/apps/hical/NonLinearLSQ.h", "max_forks_repo_name": "ihumphrey-usgs/ISIS3_old", "max_forks_repo_head_hexsha": "284cc442b773f8369d44379ee29a9b46961d8108", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T06:05:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-12T06:05:03.000Z", "avg_line_length": 36.6296296296, "max_line_length": 80, "alphanum_fraction": 0.5837546343, "num_tokens": 1381, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980404, "lm_q2_score": 0.38861802670584894, "lm_q1q2_score": 0.2288529375553566}} {"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#include \n#include \n#include \n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n #if (PETSC_VERSION_MINOR >=6)\n #include \n #else\n #include \n #endif\n#else\n #include \n#endif\n#include \n#include \n#include \n#include \n#include \n#include \"Solvers/SLE/SLE.h\" /* to give the AugLagStokes_SLE type */\n#include \"Solvers/KSPSolvers/KSPSolvers.h\"\n#include \"BSSCR.h\"\n#include \"stokes_block_scaling.h\"\n#include \"stokes_mvblock_scaling.h\"\n#include \"writeMatVec.h\"\n#include \"createK2.h\"\n#include \"mg.h\"\n#include \"summary.h\"\n#include \"ksp_pressure_nullspace.h\"\n\n#define BSSCR_GetPetscMatrix( matrix ) ( (Mat)(matrix) )\n#define BSSCR_GetPetscVector( vector ) ( (Vec)(vector) )\n\ntypedef struct {\n PetscTruth initialrtol; /* default relative residual decrease is computing from initial residual, not rhs */\n PetscTruth mininitialrtol; /* default relative residual decrease is computing from min of initial residual and rhs */\n Vec work;\n PetscReal pointwise_max;\n} KSPPWConvergedCtx;\n\nPetscErrorCode BSSCR_KSPNormInfMonitor( KSP ksp, PetscInt iteration, PetscReal residualNorm, void *dummy);\nPetscErrorCode BSSCR_KSPNormInfToNorm2Monitor( KSP ksp, PetscInt iteration, PetscReal residualNorm, void *dummy);\n\nPetscErrorCode BSSCR_KSPPWConvergedCreate(void **ctx);\nPetscErrorCode BSSCR_KSPPWConvergedDestroy(void *ctx);\nPetscErrorCode BSSCR_KSPNormInfConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *ctx);\nPetscErrorCode BSSCR_KSPNormInfToNorm2Monitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy);\nPetscErrorCode BSSCR_KSPNormInfMonitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy);\nPetscErrorCode BSSCR_KSPNorm2RawMonitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy);\nPetscErrorCode BSSCR_KSPSetNormInfConvergenceTest(KSP ksp);\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_DRIVER_auglag\"\nPetscErrorCode BSSCR_DRIVER_auglag( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS,\n MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self )\n{\n PetscTruth uzawastyle, KisJustK=PETSC_TRUE, restorek, change_A11rhspresolve;\n PetscTruth usePreviousGuess, useNormInfStoppingConditions, useNormInfMonitor, found, forcecorrection;\n PetscTruth change_backsolve, mg_active, get_flops;\n PetscErrorCode ierr;\n KSPConvergedReason reason;\n\n PetscInt max_it,min_it;\n KSP ksp_inner, ksp_S, ksp_new_inner;\n PC pc_S, pcInner;\n Mat K,G,D,C, S, K2;\n Vec u,p,f,f2=0,f3=0,h, h_hat,t;\n Vec f_tmp;\n\n MGContext mgCtx;\n double mgSetupTime, problemBuildTime, scrSolveTime, RHSSolveTime, a11SingleSolveTime, penaltyNumber;// hFactor;\n double backsolveSetupTime, scrSetupTime, RHSSetupTime;\n int been_here = bsscrp_self->been_here;\n\n char name[PETSC_MAX_PATH_LEN];\n char suffix[PETSC_MAX_PATH_LEN];\n char str[PETSC_MAX_PATH_LEN];\n PetscTruth flg, extractMats;\n PetscLogDouble flopsA,flopsB;\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n //if( bsscrp_self->solver->st_sle->context->loadFromCheckPoint ){\n // been_here=1;\n //}\n /* get sub matrix / vector objects */\n /* note that here, the matrix D should always exist. It is set up in _StokesBlockKSPInterface_Solve in StokesBlockKSPInterface.c */\n /* now extract K,G etc from a MatNest object */\n MatNestGetSubMat( stokes_A, 0,0, &K );\n MatNestGetSubMat( stokes_A, 0,1, &G );\n MatNestGetSubMat( stokes_A, 1,0, &D );if(!D){ PetscPrintf( PETSC_COMM_WORLD, \"D does not exist but should!!\\n\"); exit(1); }\n MatNestGetSubMat( stokes_A, 1,1, &C );\n VecNestGetSubVec( stokes_x, 0, &u );\n VecNestGetSubVec( stokes_x, 1, &p );\n VecNestGetSubVec( stokes_b, 0, &f );\n VecNestGetSubVec( stokes_b, 1, &h );\n\n // Try this ...\n // MatMPIAIJSetPreallocation(K, 375 ,PETSC_NULL, 375, PETSC_NULL);\n\n PetscPrintf( PETSC_COMM_WORLD, \"AUGMENTED LAGRANGIAN K2 METHOD \" );\n PetscPrintf( PETSC_COMM_WORLD, \"- Penalty = %f\\n\\n\", bsscrp_self->solver->penaltyNumber );\n sprintf(suffix,\"%s\",\"x\");\n\n found = PETSC_FALSE;\n get_flops = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-get_flops\", &get_flops, &found);\n\n PetscOptionsGetString( PETSC_NULL, \"-matsuffix\", suffix, PETSC_MAX_PATH_LEN-1, &extractMats );\n\n flg=0;\n PetscOptionsGetString( PETSC_NULL, \"-matdumpdir\", name, PETSC_MAX_PATH_LEN-1, &flg );\n if(flg){\n sprintf(str,\"%s/K%s\",name, suffix);\n bsscr_writeMat( K, str, \"Writing K matrix in al Solver\");\n sprintf(str,\"%s/G%s\",name, suffix);\n bsscr_writeMat( G, str, \"Writing G matrix in al Solver\");\n sprintf(str,\"%s/D%s\",name, suffix);\n bsscr_writeMat( D, str, \"Writing D matrix in al Solver\");\n sprintf(str,\"%s/f%s\",name, suffix);\n bsscr_writeVec( f, str, \"Writing f vector in al Solver\");\n sprintf(str,\"%s/h%s\",name, suffix);\n bsscr_writeVec( h, str, \"Writing h vector in al Solver\");\n sprintf(str,\"%s/Shat%s\",name,suffix);\n bsscr_writeMat( approxS, str, \"Writing Shat matrix in al Solver\");\n if(C){\n sprintf(str,\"%s/C%s\",name,suffix);\n bsscr_writeMat( C, str, \"Writing C matrix in al Solver\");\n }\n }\n\n mg_active=PETSC_TRUE;\n PetscOptionsGetTruth( PETSC_NULL ,\"-A11_mg_active\", &mg_active, &found );\n bsscrp_self->solver->mg_active=mg_active;\n\n penaltyNumber = bsscrp_self->solver->penaltyNumber;\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /****** GET K2 ****************************************************************************************/\n\n if(penaltyNumber > 1e-10 && bsscrp_self->k2type){\n flg=0;\n PetscOptionsGetString( PETSC_NULL, \"-matdumpdir\", name, PETSC_MAX_PATH_LEN-1, &flg );\n if(flg){\n sprintf(str,\"%s/K2%s\",name, suffix);\n bsscr_writeMat( bsscrp_self->K2, str, \"Writing K2 matrix in al Solver\");\n }\n\n K2=bsscrp_self->K2;\n\n scrSolveTime = MPI_Wtime();\n ierr=MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr);/* Computes K = penaltyNumber*K2 + K */\n scrSolveTime = MPI_Wtime() - scrSolveTime;\n\n PetscPrintf( PETSC_COMM_WORLD, \"\\n\\t* K+p*K2 in time: %lf seconds\\n\\n\", scrSolveTime);\n KisJustK=PETSC_FALSE;\n forcecorrection=PETSC_TRUE;\n PetscOptionsGetTruth( PETSC_NULL ,\"-force_correction\", &forcecorrection, &found );\n if(forcecorrection){\n if(bsscrp_self->f2 && forcecorrection){\n f2=bsscrp_self->f2;\n ierr=VecAXPY(f,penaltyNumber,f2);/* f <- f +a*f2 */\n }\n else {\n switch (bsscrp_self->k2type) {\n case (K2_GG):\n {\n VecDuplicate( u, &f3 );\n MatMult( G, h, f3); ierr=VecAXPY(f,penaltyNumber,f3);/* f <- f +a*f2 */\n }\n break;\n case (K2_GMG):\n case (K2_DGMGD):\n { /* THIS IS THE ONE THAT WE KNOW WORKS PROPERLY */\n Mat M;\n Vec Mdiag;\n VecDuplicate( u, &f3 );\n M = bsscrp_self->solver->mStiffMat->matrix;\n MatGetVecs( M, &Mdiag, PETSC_NULL );\n MatGetDiagonal( M, Mdiag );\n VecReciprocal(Mdiag);\n VecPointwiseMult(Mdiag,Mdiag,h);\n MatMult( G, Mdiag, f3); ierr=VecAXPY(f,penaltyNumber,f3);/* f <- f +a*f2 */\n Stg_VecDestroy(&Mdiag);\n }\n break;\n case (K2_NULL):\n case (K2_SLE):\n {\n ;\n }\n break;\n }\n }\n }\n }\n\n /* Create Schur complement matrix */\n MatCreateSchurComplement(K,K,G,D,C, &S);\n MatSchurComplementGetKSP( S, &ksp_inner);\n KSPGetPC( ksp_inner, &pcInner );\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /********* SET PREFIX FOR INNER/VELOCITY KSP *************************************************************/\n\n KSPSetOptionsPrefix( ksp_inner, \"A11_\" );\n KSPSetFromOptions( ksp_inner );\n Stg_KSPSetOperators(ksp_inner, K, K, DIFFERENT_NONZERO_PATTERN);\n\n useNormInfStoppingConditions = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL ,\"-A11_use_norm_inf_stopping_condition\", &useNormInfStoppingConditions, &found );\n if(useNormInfStoppingConditions)\n BSSCR_KSPSetNormInfConvergenceTest( ksp_inner );\n\n useNormInfMonitor = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-A11_ksp_norm_inf_monitor\", &useNormInfMonitor, &found );\n if(useNormInfMonitor) KSPMonitorSet( ksp_inner, BSSCR_KSPNormInfMonitor, PETSC_NULL, PETSC_NULL );\n\n useNormInfMonitor = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-A11_ksp_norm_inf_to_norm_2_monitor\", &useNormInfMonitor, &found );\n if(useNormInfMonitor) KSPMonitorSet( ksp_inner, BSSCR_KSPNormInfToNorm2Monitor, PETSC_NULL, PETSC_NULL );\n\n usePreviousGuess = PETSC_FALSE;\n// if(been_here)\n// PetscOptionsGetTruth( PETSC_NULL, \"-scr_use_previous_guess\", &usePreviousGuess, &found );\n /***************************************************************************************************************/\n\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /* If multigrid is enabled, set it now. */\n change_A11rhspresolve = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-change_A11rhspresolve\", &change_A11rhspresolve, &found );\n\n if(bsscrp_self->solver->mg_active && !change_A11rhspresolve) { mgSetupTime=setupMG( bsscrp_self, ksp_inner, pcInner, K, &mgCtx ); }\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /* create right hand side */\n\n if(change_A11rhspresolve){\n KSPCreate(PETSC_COMM_WORLD, &ksp_new_inner);\n Stg_KSPSetOperators(ksp_new_inner, K, K, DIFFERENT_NONZERO_PATTERN);\n KSPSetOptionsPrefix(ksp_new_inner, \"rhsA11_\");\n MatSchurComplementSetKSP( S, ksp_new_inner );/* this call destroys the ksp_inner that is already set on S */\n ksp_inner=ksp_new_inner;\n KSPGetPC( ksp_inner, &pcInner );\n KSPSetFromOptions(ksp_inner); /* make sure we are setting up our solver how we want it */\n }\n\n MatGetVecs( S, PETSC_NULL, &h_hat );\n /* It may be the case that the current velocity solution might not be bad guess for f_tmp? <-- maybe not */\n MatGetVecs( K, PETSC_NULL, &f_tmp );\n\n\n /*************************************/\n /*************************************/\n\n// if (!been_here) {\n// VecDuplicate( u, &uStar );\n// VecSet(uStar,0.0);\n// }\n//\n// if(usePreviousGuess) {\n// VecCopy( uStar, f_tmp);\n// KSPSetInitialGuessNonzero( ksp_inner, PETSC_TRUE );\n// }\n// else {\n KSPSetInitialGuessNonzero( ksp_inner, PETSC_FALSE );\n// }\n\n\n RHSSetupTime = MPI_Wtime();\n KSPSetUp(ksp_inner);\n RHSSetupTime = MPI_Wtime() - RHSSetupTime;\n bsscrp_self->solver->stats.velocity_presolve_setup_time = RHSSetupTime;\n\n RHSSolveTime = MPI_Wtime();\n KSPSolve(ksp_inner, f, f_tmp);\n KSPGetConvergedReason( ksp_inner, &reason ); {if (reason < 0) bsscrp_self->solver->fhat_reason=(int)reason; }\n KSPGetIterationNumber( ksp_inner, &bsscrp_self->solver->stats.velocity_presolve_its );\n RHSSolveTime = MPI_Wtime() - RHSSolveTime;\n bsscrp_self->solver->stats.velocity_presolve_time = RHSSolveTime;\n\n // VecCopy( f_tmp, uStar);\n // scrSolveTime = RHSsolveTime;\n\n MatMult(D, f_tmp, h_hat);\n VecAYPX(h_hat, -1.0, h); /* Computes y = x + alpha y. h_hat -> h - Gt*K^(-1)*f*/\n Stg_VecDestroy(&f_tmp);\n\n /*************************************/\n /*************************************/\n\n\n\n if(bsscrp_self->solver->mg_active && change_A11rhspresolve) {\n //Stg_KSPDestroy(&ksp_inner );\n KSPCreate(PETSC_COMM_WORLD, &ksp_new_inner);\n Stg_KSPSetOperators(ksp_new_inner, K, K, DIFFERENT_NONZERO_PATTERN);\n KSPSetOptionsPrefix( ksp_new_inner, \"A11_\" );\n MatSchurComplementSetKSP( S, ksp_new_inner );\n ksp_inner=ksp_new_inner;\n //MatSchurSetKSP( S, ksp_inner );\n KSPGetPC( ksp_inner, &pcInner );\n KSPSetFromOptions( ksp_inner );\n mgSetupTime=setupMG( bsscrp_self, ksp_inner, pcInner, K, &mgCtx );\n }\n\n /* create solver for S p = h_hat */\n KSPCreate( PETSC_COMM_WORLD, &ksp_S );\n KSPSetOptionsPrefix( ksp_S, \"scr_\");\n\n /* By default use the UW approxS Schur preconditioner -- same as the one used by the Uzawa solver */\n /* Note that if scaling is activated then the approxS matrix has been scaled already */\n /* so no need to rebuild in the case of scaling as we have been doing */\n if(!approxS){\n PetscPrintf( PETSC_COMM_WORLD, \"WARNING approxS is NULL\\n\");\n }\n\n Stg_KSPSetOperators( ksp_S, S, S, SAME_NONZERO_PATTERN );\n KSPSetType( ksp_S, \"cg\" );\n KSPGetPC( ksp_S, &pc_S );\n BSSCR_BSSCR_StokesCreatePCSchur2( K,G,D,C,approxS, pc_S, sym, bsscrp_self );\n\n flg=0;\n PetscOptionsGetString( PETSC_NULL, \"-NN\", name, PETSC_MAX_PATH_LEN-1, &flg );\n if(flg){\n Mat Smat, Pmat;\n //MatStructure mstruct;\n Stg_PCGetOperators( pc_S, &Smat, &Pmat, NULL );\n sprintf(str,\"%s/Pmat%s\",name, suffix);\n bsscr_writeMat( Pmat, str, \"Writing Pmat matrix in al Solver\");\n }\n\n uzawastyle=PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-uzawa_style\", &uzawastyle, &found );\n if(uzawastyle){\n /* now want to set up the ksp_S->pc to be of type ksp (gmres) by default to match Uzawa */\n KSP pc_ksp;\n KSPGetPC( ksp_S, &pc_S );\n PCSetType(pc_S,PCKSP);\n PCKSPGetKSP( pc_S, &pc_ksp);\n KSPSetType(pc_ksp, \"gmres\" );\n KSPSetOptionsPrefix( pc_ksp, \"scrPCKSP_\");\n KSPSetFromOptions( pc_ksp );\n }\n\n KSPSetFromOptions( ksp_S );\n /* Set specific monitor test */\n KSPGetTolerances( ksp_S, PETSC_NULL, PETSC_NULL, PETSC_NULL, &max_it );\n\n if(usePreviousGuess) { /* Note this should actually look at checkpoint information */\n KSPSetInitialGuessNonzero( ksp_S, PETSC_TRUE ); }\n else {\n KSPSetInitialGuessNonzero( ksp_S, PETSC_FALSE ); }\n\n\n /***************************************************************************************************************/\n /* Pressure / Velocity Solve */\n /***************************************************************************************************************/\n\n /***************************************************************************************************************/\n /******* SET CONVERGENCE TESTS *************************************************************************/\n\n useNormInfStoppingConditions = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL ,\"-scr_use_norm_inf_stopping_condition\", &useNormInfStoppingConditions, &found );\n if(useNormInfStoppingConditions)\n BSSCR_KSPSetNormInfConvergenceTest(ksp_S);\n\n useNormInfMonitor = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-scr_ksp_norm_inf_monitor\", &useNormInfMonitor, &found );\n if(useNormInfMonitor)\n KSPMonitorSet( ksp_S, BSSCR_KSPNormInfToNorm2Monitor, PETSC_NULL, PETSC_NULL );\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /******* PRESSURE SOLVE ************************************************************************************/\n\n //PetscPrintf( PETSC_COMM_WORLD, \"\\t* KSPSolve( ksp_S, h_hat, p )\\n\");\n /* if h_hat needs to be fixed up ..take out any nullspace vectors here */\n /* we want to check that there is no \"noise\" in the null-space in the h vector */\n /* this causes problems when we are trying to solve a Jacobian system when the Residual is almost converged */\n\n if(bsscrp_self->check_pressureNS){\n bsscrp_self->buildPNS(ksp);/* build and set nullspace vectors on bsscr - which is on ksp (function pointer is set in KSPSetUp_BSSCR) */\n }\n\n PetscScalar hnorm, gnorm;\n MatNorm(G,NORM_INFINITY,&gnorm);\n VecNorm(h_hat, NORM_2, &hnorm);\n hnorm=hnorm/gnorm;\n\n if((hnorm < 1e-6) && (hnorm > 1e-20)){\n VecScale(h_hat,1.0/hnorm);\n }\n /* test to see if v or t are in nullspace of G and orthogonalize wrt h_hat if needed */\n KSPRemovePressureNullspace_BSSCR(ksp, h_hat);\n /* set convergence test to use min_it */\n found = PETSC_FALSE;\n min_it = 0;\n PetscOptionsGetInt( PETSC_NULL,\"-scr_ksp_set_min_it_converge\", &min_it, &found);\n if(found && min_it > 0){\n BSSCR_KSPSetConvergenceMinIts(ksp_S, min_it, bsscrp_self);\n }\n\n /** Pressure Setup **/\n scrSetupTime = MPI_Wtime();\n KSPSetUp(ksp_S);\n scrSetupTime = MPI_Wtime() - scrSetupTime;\n bsscrp_self->solver->stats.velocity_pressuresolve_setup_time = scrSetupTime;\n\n /** Pressure Solve **/\n if(get_flops) PetscGetFlops(&flopsA);\n scrSolveTime = MPI_Wtime();\n KSPSolve( ksp_S, h_hat, p );\n scrSolveTime = MPI_Wtime() - scrSolveTime;\n\n\n KSPGetConvergedReason( ksp_S, &reason ); {if (reason < 0) bsscrp_self->solver->outer_reason=(int)reason; }\n /*************************************/\n /*************************************/\n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >= 6 ) && (PETSC_VERSION_SUBMINOR >= 1 ))\n KSPGetTotalIterations(ksp_inner, &bsscrp_self->solver->stats.velocity_pressuresolve_its);\n if(!change_A11rhspresolve){\n bsscrp_self->solver->stats.velocity_pressuresolve_its -= bsscrp_self->solver->stats.velocity_presolve_its;\n }\n#else\n bsscrp_self->solver->stats.velocity_pressuresolve_its=-1;\n#endif\n\n\n if(get_flops) {\n PetscGetFlops(&flopsB);\n bsscrp_self->solver->stats.pressure_flops=(double)(flopsB-flopsA); }\n //PetscPrintf( PETSC_COMM_WORLD, \"\\n\\t* KSPSolve( ksp_S, h_hat, p ) Solve Finished in time: %lf seconds\\n\\n\", scrSolveTime);\n bsscrp_self->solver->stats.pressure_time=scrSolveTime;\n\n /***************************************/\n if((hnorm < 1e-6) && (hnorm > 1e-20)){\n VecScale(h_hat,hnorm);\n VecScale(p,hnorm);\n }\n KSPRemovePressureNullspace_BSSCR(ksp, p);\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /* restore K and f for the Velocity back solve */\n\n found = PETSC_FALSE;\n restorek = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-restore_K\", &restorek, &found);\n //PetscOptionsGetString( PETSC_NULL, \"-restore_K\", name, PETSC_MAX_PATH_LEN-1, &flg );\n if(penaltyNumber > 1e-10 && bsscrp_self->k2type){\n if(restorek){\n penaltyNumber = -penaltyNumber;\n if(f2) {\n ierr=VecAXPY(f,penaltyNumber,f2);\n }/* f <- f +a*f2 */\n if(f3) {\n ierr=VecAXPY(f,penaltyNumber,f3);\n }/* f <- f +a*f3 */\n ierr=MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);\n CHKERRQ(ierr);/* Computes K = penaltyNumber*K2 + K */\n Stg_KSPSetOperators(ksp_inner, K, K, DIFFERENT_NONZERO_PATTERN);\n KisJustK=PETSC_TRUE;\n }\n }\n if(f3){ Stg_VecDestroy(&f3 ); } /* always destroy this local vector if was created */\n\n /* obtain solution for u */\n\n VecDuplicate( u, &t );\n MatMult( G, p, t);\n VecAYPX( t, -1.0, f ); /*** t <- -t + f = f - G*p ***/\n\n MatSchurComplementGetKSP( S, &ksp_inner );\n a11SingleSolveTime = MPI_Wtime(); /* ---------------------------------- Final V Solve */\n if(usePreviousGuess)\n KSPSetInitialGuessNonzero( ksp_inner, PETSC_TRUE );\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /******* VELOCITY SOLVE ************************************************************************************/\n\n /** Easier to just create a new KSP here if we want to do backsolve diffferently. (getting petsc errors now when switching from fgmres) */\n\n change_backsolve=PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-change_backsolve\", &change_backsolve, &found );\n if(change_backsolve){\n //Stg_KSPDestroy(&ksp_inner );\n KSPCreate(PETSC_COMM_WORLD, &ksp_new_inner);\n Stg_KSPSetOperators(ksp_new_inner, K, K, DIFFERENT_NONZERO_PATTERN);\n KSPSetOptionsPrefix(ksp_new_inner, \"backsolveA11_\");\n KSPSetFromOptions(ksp_new_inner); /* make sure we are setting up our solver how we want it */\n MatSchurComplementSetKSP( S, ksp_new_inner );/* need to give the Schur it's inner ksp back for when we destroy it at end */\n ksp_inner=ksp_new_inner;\n }\n\n\n if(get_flops) PetscGetFlops(&flopsA);\n /*************************************/\n /*************************************/\n\n backsolveSetupTime = MPI_Wtime();\n KSPSetUp(ksp_inner);\n backsolveSetupTime = MPI_Wtime() - backsolveSetupTime;\n bsscrp_self->solver->stats.velocity_backsolve_setup_time = backsolveSetupTime;\n\n KSPSolve(ksp_inner, t, u);\n KSPGetConvergedReason(ksp_inner, &reason ); {if (reason < 0) bsscrp_self->solver->backsolve_reason=(int)reason; }\n /*************************************/\n /*************************************/\n KSPGetIterationNumber( ksp_inner, &bsscrp_self->solver->stats.velocity_backsolve_its );\n if(get_flops) {\n PetscGetFlops(&flopsB);\n bsscrp_self->solver->stats.velocity_backsolve_flops=(double)(flopsB-flopsA); }\n a11SingleSolveTime = MPI_Wtime() - a11SingleSolveTime; /* ------------------ Final V Solve */\n\n bsscrp_self->solver->stats.velocity_presolve_time=RHSSolveTime;\n bsscrp_self->solver->stats.velocity_backsolve_time=a11SingleSolveTime;\n bsscrp_self->solver->stats.velocity_total_its = bsscrp_self->solver->stats.velocity_backsolve_its +\n bsscrp_self->solver->stats.velocity_presolve_its +\n bsscrp_self->solver->stats.velocity_pressuresolve_its;\n\n flg=0;\n\n PetscOptionsGetString( PETSC_NULL, \"-solutiondumpdir\", name, PETSC_MAX_PATH_LEN-1, &flg );\n if(flg){\n sprintf(str,\"%s/p%s\",name,suffix);\n bsscr_writeVec( p, str, \"Writing p vector in al Solver\");\n sprintf(str,\"%s/u%s\",name, suffix);\n bsscr_writeVec( u, str, \"Writing u vector in al Solver\");\n sprintf(str,\"%s/h_hat%s\",name,suffix);\n bsscr_writeVec( h_hat, str, \"Writing h_hat vector in al Solver\");\n\n }\n\n found = PETSC_FALSE;\n restorek = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-restore_K_after_solve\", &restorek, &found);\n if(penaltyNumber > 1e-10 && bsscrp_self->k2type){\n if(restorek){\n penaltyNumber = -penaltyNumber;\n ierr=MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);CHKERRQ(ierr);/* Computes K = penaltyNumber*K2 + K */\n KisJustK=PETSC_TRUE;\n }\n }\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n /****** SOLUTION SUMMARY ******************************************************************************/\n bsscr_summary(bsscrp_self,ksp_S,ksp_inner,K,K2,D,G,C,u,p,f,h,t,penaltyNumber,KisJustK,\n mgSetupTime, RHSSolveTime, scrSolveTime, a11SingleSolveTime);\n\n /***************************************************************************************************************/\n /***************************************************************************************************************/\n Stg_VecDestroy(&t );\n Stg_KSPDestroy(&ksp_S );\n Stg_VecDestroy(&h_hat );\n Stg_MatDestroy(&S );//This will destroy ksp_inner: also.. pcInner == pc_MG and is destroyed when ksp_inner is\n been_here = 1;\n PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "3468585cb6912d021479d26b65d91f89e5c41442", "size": 26130, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/auglag-driver-DGTGD.c", "max_stars_repo_name": "StuartRClark/mantle", "max_stars_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T20:00:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T20:00:12.000Z", "max_issues_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/auglag-driver-DGTGD.c", "max_issues_repo_name": "StuartRClark/mantle", "max_issues_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "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/auglag-driver-DGTGD.c", "max_forks_repo_name": "StuartRClark/mantle", "max_forks_repo_head_hexsha": "27acbbbb70b00870bebc4f98c69af8edaa4f8bc4", "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": 45.4434782609, "max_line_length": 143, "alphanum_fraction": 0.554075775, "num_tokens": 6867, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5544704649604273, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.2279488348134456}} {"text": "/*\n# Program to run a Monte Carlo radiation transfer through the 2D\n# simulations of GRB jets.\n#\n# Python code written by D. Lazzati at Oregonstate, C code written by Tyler Parsotan @ Oregon State \n# ver 0.1 July 8, 2015\n# ver 1.1 July 20, 2015: added record of number of scatterings, included\n# \tall terms in weight. Should now give correct light curves.\n# ver 1.2 July 21, 2015: added parameter file to keep track of input\n# \tparams of each simulation\n\n# ver 2.0 July 22, 2015: corrected the problem that arises when there is\n# \tno scattering in the time span of one frame. Fixed output arrays dimension.\n\n# ver 2.1 July 25, 2015: fixed bug that did not make the number of\n# \tscattering grow with the number of photons.\n\n# ver 3.0 July 28, 2015: using scipy nearest neighbor interpolation to\n# \tspeed things up. Gained about factor 2\n\n# ver 3.1 July 29, 2015: added radial spread of photon injection points\n# ver 3.2 July 31, 2015: added Gamma to the weight of photons!!!\n\n# ver 4.0 Aug 5, 2015: try to speed up by inverting cycle\n# ver 4.1 Aug 8, 2015: add spherical test as an option\n# ver 4.2 Aug 9, 2015: saving files appending rather than re-writing\n# ver 4.3 Aug 11, 2015: corrected error in the calculation of the local temperature\n# ver 4.4 Aug 13, 2015: added cylindrical test\n# ver 4.5 Aug 18, 2015: fixd various problems pointed by the cylindrical test\n# ver 4.6 Aug 21, 2015: corrected mean free path for large radii\n\n# ver 5.0 Aug 25, 2015: corrected problem with high-T electrons and excess scatterings\n# ver 5.1 Aug 25, 2015: cleaned-up coding\n# ver 5.2 Sept 3, 2015: fixed problem with number of scatterings for multiple injections\n * \n * ver 6.0 Dec 28, 2016: rewrote the code in C, added checkpoint file so if the code is interrupted all the progress wont be lost, made the code only need to be compiled once for a given MC_XXX directory path\n so you just need to supply the sub directory of MC_XXX as a command line argument\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mclib.h\"\n\n#define THISRUN \"Spherical\"\n#define FILEPATH \"/Volumes/parsotat/Documents/16TI/\"\n#define FILEROOT \"rhd_jet_big_13_hdf5_plt_cnt_\"\n#define MC_PATH \"CMC_16TI_SPHERICAL/\"\n#define MCPAR \"mc.par\"\n\nint main(int argc, char **argv)\n{\n //compile each time a macro is changed, have to supply the subfolder within the MC_PATH directory as a command line argument to the C program eg. MCRAT 1/\n \n\t// Define variables\n\tchar flash_prefix[200]=\"\";\n\tchar flash_file[200]=\"\";\n\tchar mc_dir[200]=\"\" ;\n\tchar mc_file[200]=\"\" ;\n char mc_filename[200]=\"\";\n char mc_operation[200]=\"\";\n char this_run[200]=THISRUN;\n char *cyl=\"Cylindrical\";\n char *sph=\"Spherical\";\n int file_count = 0;\n DIR * dirp;\n struct dirent * entry;\n\tchar spect;//type of spectrum\n char restrt;//restart or not\n\tdouble fps, theta_jmin, theta_jmax ;//frames per second of sim, min opening angle of jet, max opening angle of jet in radians\n\tdouble inj_radius, ph_weight ;//radius at chich photons are injected into sim\n\tint frm0,last_frm, frm2, photon_num ;//frame starting from, last frame of sim, frame of last injection, number of photons (not necessary any more)\n\tdouble *xPtr=NULL, *yPtr=NULL, *rPtr=NULL, *thetaPtr=NULL, *velxPtr=NULL, *velyPtr=NULL, *densPtr=NULL, *presPtr=NULL, *gammaPtr=NULL, *dens_labPtr=NULL;\n double *szxPtr=NULL,*szyPtr=NULL, *tempPtr=NULL; //pointers to hold data from FLASH files\n int num_ph=0, array_num=0, ph_scatt_index=0, max_scatt=0, min_scatt=0,i=0; //number of photons produced in injection algorithm, number of array elleemnts from reading FLASH file, index of photon whch does scattering, generic counter\n double dt_max=0, thescatt=0, accum_time=0; \n double gamma_infinity=0;\n double time_now=0, time_step=0, avg_scatt=0;\n double ph_dens_labPtr=0, ph_vxPtr=0, ph_vyPtr=0, ph_tempPtr=0;// *ph_cosanglePtr=NULL ;\n int frame=0, scatt_frame=0, frame_scatt_cnt=0, scatt_framestart=0, framestart=0;\n struct photon *phPtr=NULL; //pointer to array of photons \n \n long seed;\n const gsl_rng_type * T;\n gsl_rng * rand;\n \n gsl_rng_env_setup();\n T = gsl_rng_ranlxs0;\n rand = gsl_rng_alloc (T);\n \n //make strings of proper directories etc.\n\tsnprintf(flash_prefix,sizeof(flash_prefix),\"%s%s\",FILEPATH,FILEROOT );\n\tsnprintf(mc_dir,sizeof(flash_prefix),\"%s%s%s\",FILEPATH,MC_PATH, argv[1]);\n\tsnprintf(mc_file,sizeof(flash_prefix),\"%s%s\",mc_dir,MCPAR);\n \n printf(\">> mc.py: I am working on path: %s \\n\",mc_dir);\n \n printf(\">> mc.py: Reading mc.par\\n\");\n \n readMcPar(mc_file, &fps, &theta_jmin, &theta_jmax,&inj_radius,&frm0,&last_frm,&frm2,&photon_num, &ph_weight, &spect, &restrt);\n \n if (restrt=='c')\n {\n printf(\">> mc.py: Reading checkpoint\\n\");\n readCheckpoint(mc_dir, &phPtr, &framestart, &scatt_framestart, &num_ph, &restrt, &time_now);\n for (i=0;ip0, (phPtr+i)->p1, (phPtr+i)->p2, (phPtr+i)->p3, (phPtr+i)->r0, (phPtr+i)->r1, (phPtr+i)->r2, (phPtr+i)->num_scatt );\n }\n \n if (restrt=='c')\n {\n printf(\"Starting from photons injected at frame: %d out of %d\\n\", framestart, frm2);\n printf(\"Continuing scattering %d photons from frame: %d\\n\", num_ph, scatt_framestart);\n printf(\"The time now is: %e\\n\", time_now);\n }\n else\n {\n printf(\"Continuing simulation by injecting photons at frame: %d out of %d\\n\", framestart, frm2); //starting with new photon injection is same as restarting sim\n }\n }\n else\n {\n //remove everything from MC directory to ensure no corruption of data if theres other files there besides the mc.par file\n //for a checkpoint implementation, need to find the latest checkpoint file and read it and not delete the files\n printf(\">> mc.py: Cleaning directory\\n\");\n dirp = opendir(mc_dir);\n while ((entry = readdir(dirp)) != NULL) \n {\n if (entry->d_type == DT_REG) { /* If the entry is a regular file */\n file_count++; //count how many files are in dorectory\n }\n }\n //printf(\"File count %d\\n\", file_count);\n \n if (file_count>2)\n {\n for (i=0;i<=last_frm;i++)\n {\n snprintf(mc_filename,sizeof(flash_prefix),\"%s%s%d%s\", mc_dir,\"mcdata_\",i,\"_P0.dat\");\n if( access( mc_filename, F_OK ) != -1 )\n {\n snprintf(mc_operation,sizeof(flash_prefix),\"%s%s%s%d%s\",\"exec rm \", mc_dir,\"mcdata_\",i,\"_*.dat\"); //prepares string to remove *.dat in mc_dir\n //printf(\"%s\",mc_operation);\n system(mc_operation);\n }\n }\n }\n framestart=frm0; //if restarting then start from parameters given in mc.par file\n scatt_framestart=framestart;\n }\n \n dt_max=1.0/fps;\n \n //loop over frames \n //for a checkpoint implementation, start from the last saved \"frame\" value and go to the saved \"frm2\" value\n for (frame=framestart;frame<=frm2;frame++)\n {\n if (restrt=='r')\n {\n time_now=frame/fps; //for a checkpoint implmentation, load the saved \"time_now\" value when reading the ckeckpoint file otherwise calculate it normally\n }\n \n printf(\">> mc.py: Working on Frame %d\\n\", frame);\n \n \n \n if (restrt=='r')\n {\n //put proper number at the end of the flash file\n if (frame<10)\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%.3d%d\",flash_prefix,000,frame);\n }\n else if (frame<100)\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%.2d%d\",flash_prefix,00,frame);\n }\n else if (frame<1000)\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%d%d\",flash_prefix,0,frame);\n }\n else\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%d\",flash_prefix,frame);\n }\n \n printf(\">> mc.py: Opening FLASH file %s\\n\",flash_file);\n //read in FLASH file\n //for a checkpoint implmentation, dont need to read the file yet\n readAndDecimate(flash_file, inj_radius, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num);\n \n //check for run type\n if(strcmp(cyl, this_run)==0)\n {\n //printf(\"In cylindrical prep\\n\");\n cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num);\n }\n else if (strcmp(sph, this_run)==0)\n {\n sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num );\n }\n \n //determine where to place photons and how many should go in a given place\n //for a checkpoint implmentation, dont need to inject photons, need to load photons' last saved data \n printf(\">> mc.py: Injecting photons\\n\");\n photonInjection(&phPtr, &num_ph, inj_radius, ph_weight, spect, array_num, fps, theta_jmin, theta_jmax, xPtr, yPtr, szxPtr, szyPtr,rPtr,thetaPtr, tempPtr, velxPtr, velyPtr,rand ); \n printf(\"%d\\n\",num_ph); //num_ph is one more photon than i actually have\n /*\n for (i=0;ir0, (phPtr+i)->r1, (phPtr+i)->r2 );\n */\n }\n \n //scatter photons all the way thoughout the jet\n //for a checkpoint implmentation, start from the last saved \"scatt_frame\" value eh start_frame=frame or start_frame=cont_frame\n if (restrt=='r')\n {\n scatt_framestart=frame; //have to make sure that once the inner loop is done and the outer loop is incrememnted by one the inner loop starts at that new value and not the one read by readCheckpoint()\n }\n \n for (scatt_frame=scatt_framestart;scatt_frame<=last_frm;scatt_frame++)\n {\n printf(\">>\\n\");\n printf(\">> mc.py: Working on photons injected at frame: %d out of %d\\n\", frame, frm2);\n printf(\">> mc.py: %s: Working on frame %d\\n\", THISRUN, scatt_frame);\n printf(\">> mc.py: Opening file...\\n\");\n \n \n //put proper number at the end of the flash file\n if (scatt_frame<10)\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%.3d%d\",flash_prefix,000,scatt_frame);\n }\n else if (scatt_frame<100)\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%.2d%d\",flash_prefix,00,scatt_frame);\n }\n else if (scatt_frame<1000)\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%d%d\",flash_prefix,0,scatt_frame);\n }\n else\n {\n snprintf(flash_file,sizeof(flash_prefix), \"%s%d\",flash_prefix,scatt_frame);\n }\n \n \n readAndDecimate(flash_file, inj_radius, &xPtr, &yPtr, &szxPtr, &szyPtr, &rPtr,\\\n &thetaPtr, &velxPtr, &velyPtr, &densPtr, &presPtr, &gammaPtr, &dens_labPtr, &tempPtr, &array_num);\n //printf(\"The result of read and decimate are arrays with %d elements\\n\", array_num);\n \n //check for run type\n if(strcmp(cyl, this_run)==0)\n {\n printf(\"In cylindrical prep\\n\");\n cylindricalPrep(gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num);\n }\n else if (strcmp(sph, this_run)==0)\n {\n sphericalPrep(rPtr, xPtr, yPtr,gammaPtr, velxPtr, velyPtr, densPtr, dens_labPtr, presPtr, tempPtr, array_num );\n }\n \n printf(\">> mc.py: propagating and scattering %d photons\\n\", num_ph);\n \n frame_scatt_cnt=0;\n while (time_now<((scatt_frame+1)/fps))\n {\n //if simulation time is less than the simulation time of the next frame, keep scattering in this frame\n //go through each photon and find blocks closest to each photon and properties of those blocks to calulate mean free path\n //and choose the photon with the smallest mfp and calculate the timestep\n \n ph_scatt_index=findNearestPropertiesAndMinMFP(phPtr, num_ph, array_num, &time_step, xPtr, yPtr, velxPtr, velyPtr, dens_labPtr, tempPtr,\\\n &ph_dens_labPtr, &ph_vxPtr, &ph_vyPtr, &ph_tempPtr, rand);\n \n //printf(\"In main: %e, %d, %e, %e\\n\", *(ph_num_scatt+ph_scatt_index), ph_scatt_index, time_step, time_now);\n //printf(\"In main: %e, %d, %e, %e\\n\",((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now);\n \n if (time_stepnum_scatt)+=1;\n frame_scatt_cnt+=1;\n time_now+=time_step;\n \n updatePhotonPosition(phPtr, num_ph, time_step);\n \n //scatter the photon\n //printf(\"Passed Parameters: %e, %e, %e\\n\", (ph_vxPtr), (ph_vyPtr), (ph_tempPtr));\n\n photonScatter( (phPtr+ph_scatt_index), (ph_vxPtr), (ph_vyPtr), (ph_tempPtr), rand );\n \n \n if (frame_scatt_cnt%1000 == 0)\n {\n printf(\"Scattering Number: %d\\n\", frame_scatt_cnt);\n printf(\"The local temp is: %e, Local energy: %e\\n\", (ph_tempPtr), (ph_tempPtr)*(1.380658e-16/1.6e-9));\n printf(\"Average photon energy is: %e keV\\n\", averagePhotonEnergy(phPtr, num_ph)/1.6e-9); //write function to average over the photons p0*c and then do (/1.6e-9)\n }\n \n }\n else\n {\n time_now+=dt_max;\n \n //for each photon update its position based on its momentum\n \n updatePhotonPosition(phPtr, num_ph, dt_max);\n }\n \n //printf(\"In main 2: %e, %d, %e, %e\\n\", ((phPtr+ph_scatt_index)->num_scatt), ph_scatt_index, time_step, time_now);\n\n }\n \n //get scattering statistics\n phScattStats(phPtr, num_ph, &max_scatt, &min_scatt, &avg_scatt);\n \n printf(\"The number of scatterings in this frame is: %d\\n\", frame_scatt_cnt);\n printf(\"The last time step was: %lf.\\nThe time now is: %lf\\n\", time_step,time_now);\n printf(\"The maximum number of scatterings for a photon is: %d\\nThe minimum number of scattering for a photon is: %d\\n\", max_scatt, min_scatt);\n printf(\"The average number of scatterings thus far is: %lf\\n\", avg_scatt);\n \n printPhotons(phPtr, num_ph, scatt_frame , mc_dir);\n \n //for a checkpoint implmentation,save the checkpoint file here after every 5 frames or something\n //save the photons data, the scattering number data, the scatt_frame value, and the frame value\n //WHAT IF THE PROGRAM STOPS AFTER THE LAST SCATT_FRAME, DURING THE FIRST SCATT_FRAME OF NEW FRAME VARIABLE - save restrt variable as 'r'\n printf(\">> mc.py: Making checkpoint file\\n\");\n saveCheckpoint(mc_dir, frame, scatt_frame, num_ph, time_now, phPtr, last_frm);\n \n free(xPtr);free(yPtr);free(szxPtr);free(szyPtr);free(rPtr);free(thetaPtr);free(velxPtr);free(velyPtr);free(densPtr);free(presPtr);\n free(gammaPtr);free(dens_labPtr);free(tempPtr);\n xPtr=NULL; yPtr=NULL; rPtr=NULL;thetaPtr=NULL;velxPtr=NULL;velyPtr=NULL;densPtr=NULL;presPtr=NULL;gammaPtr=NULL;dens_labPtr=NULL;\n szxPtr=NULL; szyPtr=NULL; tempPtr=NULL;\n }\n restrt='r';//set this to make sure that the next iteration of propogating photons doesnt use the values from the last reading of the checkpoint file\n free(phPtr); \n phPtr=NULL;\n \n }\n \n gsl_rng_free (rand);\n\treturn 0;\n \n}\n", "meta": {"hexsha": "690c22241cbe497c38271f6237aebd93e4434ca2", "size": 16821, "ext": "c", "lang": "C", "max_stars_repo_path": "OLDER_MCRaT_VERSIONS/SERIAL/TESTCASES/mcrat.c", "max_stars_repo_name": "outflows/MCRaT", "max_stars_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-10-20T08:37:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-05T14:51:37.000Z", "max_issues_repo_path": "OLDER_MCRaT_VERSIONS/SERIAL/TESTCASES/mcrat.c", "max_issues_repo_name": "outflows/MCRaT", "max_issues_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "OLDER_MCRaT_VERSIONS/SERIAL/TESTCASES/mcrat.c", "max_forks_repo_name": "outflows/MCRaT", "max_forks_repo_head_hexsha": "ad7e6a32b1a3136479f546adb2b50cdb1d2edb14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-09T16:11:50.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-20T09:12:08.000Z", "avg_line_length": 47.6515580737, "max_line_length": 236, "alphanum_fraction": 0.5974080019, "num_tokens": 4431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.3557748935136303, "lm_q1q2_score": 0.22792215303667823}} {"text": "/**\n */\n#include \n#include \n#include \"aXe_grism.h\"\n#include \n#include \n#include \n#include \"drz2pet_utils.h\"\n\n\n/**\n * Function: make_spc_drztable\n * The function generates and fills an ap_pixel vector for one\n * drizzled 2D grism image.\n *\n * Parameters:\n * @param obs - pointer to observation structure with image values\n * @param obs - pointer to observation structure with image values\n * @param ob - pointer to the description of the current beam\n * @param lambda0 - the starting wavelength in this drizzled image\n * @param dlambda - the dispersion in this drizzled image\n *\n * Returns:\n * @return table - pointer to an ap_pixel vector\n */\nap_pixel *\nmake_spc_drztable(observation * const obs, observation * const wobs,\n const object *ob, const double lambda0,\n const double dlambda){\n\n ap_pixel *table, *cur_ap;\n\n int npix1, npix2;\n int nsub1=1, nsub2=1;\n int i, j;\n int beamInt = 0;\n\n npix1 = obs->grism->size1;\n npix2 = obs->grism->size2;\n\n\n if (!(table = malloc ((npix1 * npix2 + 1) * sizeof (ap_pixel) * nsub1 * nsub2)))\n return NULL;\n\n cur_ap = table;\n\n for (i = 0; i < npix1; i++){\n for (j = 0; j < npix2; j++){\n\n //* check whether the pixel is within the extraction box\n if (fabs((double)j - ob->beams[beamInt].refpoint.y) > ob->beams[beamInt].width + .5)\n continue;\n\n //* fill the ap_pixel\n cur_ap->p_x = i;\n cur_ap->p_y = j;\n\n cur_ap->x = (double)i - ob->beams[beamInt].refpoint.x;\n cur_ap->y = (double)j - ob->beams[beamInt].refpoint.y;\n cur_ap->dist = (double)j - ob->beams[beamInt].refpoint.y;\n cur_ap->xs = (double)i - ob->beams[beamInt].refpoint.x;\n cur_ap->ys = 0.0;\n cur_ap->dxs = 0.0; // be reminded: dxs is the LOCAL TRACEANGLE, not the pixels size..\n cur_ap->xi = (double)i - ob->beams[beamInt].refpoint.x;\n cur_ap->lambda = lambda0 + dlambda * ((double)i - ob->beams[beamInt].refpoint.x);\n cur_ap->dlambda = dlambda;\n\n // transfer the cps values and the weight values\n cur_ap->count = gsl_matrix_get(obs->grism, i, j);\n cur_ap->weight = gsl_matrix_get(wobs->grism, i, j);\n\n cur_ap->error = gsl_matrix_get(obs->pixerrs, i, j);\n cur_ap->contam = gsl_matrix_get(obs->dq, i, j);\n\n // dq is always set to zero, bad (=unexposed) pixels\n // have exptime=weight=0.0\n cur_ap->dq = 0;\n\n // go to the next\n // PET pixel\n cur_ap++;\n }\n }\n\n cur_ap->p_x = -1;\n cur_ap->p_y = -1;\n cur_ap->count = -1;\n\n return table;\n}\n\n/**\n * Function: get_ID_num\n * The function generates the extension name used in the PET\n * for a 2D drizzled grism image\n *\n * Parameters:\n * @param grism_image - the name of the 2D drizzled grism image\n * @param extname - The ID number of the image\n *\n * Returns:\n * @return WorkPtr - Pointer to the ID-string\n */\nchar\n*get_ID_num (char *grism_image, char *extname){\n\n char *WorkPtr;\n char *WorkPtr2;\n char **t_err=NULL;\n char tmp[MAXCHAR];\n char ID[4];\n\n int len;\n int i=0;\n\n strcpy(ID,\"_ID\");\n strcpy(tmp, grism_image);\n\n t_err = (char **) malloc(sizeof(char *)*1);\n\n WorkPtr = strstr(tmp, ID)+3;\n WorkPtr2 = WorkPtr + strlen (WorkPtr);\n while (isspace ((int) *WorkPtr2))\n *WorkPtr2-- = '\\0';\n WorkPtr2 = WorkPtr2 - 1;\n len = strlen(WorkPtr);\n while (i++ < len){\n strtol(WorkPtr,t_err,10);\n if (strlen(t_err[0])==0)\n break;\n *WorkPtr2-- = '\\0';\n }\n strcpy(extname,WorkPtr);\n free(t_err);\n return WorkPtr;\n}\n\n/**\n * Function: normalize_weight\n * The function computes the weights used in the extraction\n * from the exposure times given for each pixel in a column.\n *\n * Parameters:\n * @param wobs - pointer to the structure which carries the pixel data\n * @param ob - pointer to the beam description\n */\nvoid\nnormalize_weight(observation *wobs, object *ob,\n const int opt_extr)\n{\n gsl_matrix *weight;\n //int i, j;\n // // check for optimal extraction\n if (opt_extr)\n {\n // let the optimal weights compute\n fprintf(stdout, \"aXe_DRZ2PET: Use otpimal weighting.\\n\");\n weight = comp_opt_weight(wobs->pixerrs, wobs->dq, ob);\n }\n else\n {\n // let the exposure time weights compute\n fprintf(stdout, \"aXe_DRZ2PET: Use normal, flat weighting.\\n\");\n weight = comp_equ_weight(wobs->grism, ob);\n\n // code lines for exposure time weighting\n //fprintf(stdout, \"use exposure time weighting\\n\");\n //weight = comp_exp_weight(wobs->grism, ob);\n }\n\n // replace the weight extension with the new weights\n gsl_matrix_free(wobs->grism);\n wobs->grism = weight;\n}\n\n/*\n * Function: comp_equ_weight\n * The function creates and fills a weight map with flat entries.\n * Pixels with non-zero exposure time which which contribute to the\n * extracted spectrum all receive the weight 1.0, all other\n * get the weight 0.0.\n *\n * Parameters:\n * @param exp_map - the matrix with the exposure times\n * @param ob - the object structure\n *\n * Returns:\n * @return weight - the matrix with the exposure time weights\n */\ngsl_matrix *\ncomp_equ_weight(gsl_matrix *exp_map, const object *ob)\n{\n gsl_matrix *weight;\n int i, j;\n int beamInt = 0;\n\n // allocate the matrix and set it to the default\n weight = gsl_matrix_alloc(exp_map->size1, exp_map->size2);\n gsl_matrix_set_all(weight, 0.0);\n\n // go over all columns\n for (i=0; i < (int)exp_map->size1; i++)\n // go over all rows\n for (j=0; j < (int)exp_map->size2; j++)\n // check whether the pixel is inside the extraction\n // area and has a positive exposure time\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 &&\n gsl_matrix_get(exp_map, i, j) > 0.0 )\n // set the weight to one\n gsl_matrix_set(weight, i,j,1.0);\n\n // return the resulting weight map\n return weight;\n}\n\n\n/*\n * Function: comp_exp_weight\n * The function uses the exposure time map and computes\n * the weights which are proportional to the relative\n * exposure time of the pixel. Pixels outside of the extraction\n * area are set to 1000.0 Inside the default is 1.0 in unexposed\n * columns and 0.0 within exposed columns.\n *\n * Parameters:\n * @param exp_map - the matrix with the exposure times\n * @param ob - the object structure\n *\n * Returns:\n * @return weight - the matrix with the exposure time weights\n */\ngsl_matrix *\ncomp_exp_weight(gsl_matrix *exp_map, const object *ob)\n{\n gsl_matrix *weight;\n int i, j;\n double sum, contr, norm, allweight;\n int beamInt = 0;\n\n // allocate the matrix and set it to the default\n weight = gsl_matrix_alloc(exp_map->size1, exp_map->size2);\n gsl_matrix_set_all(weight, 1000.0);\n\n //* go over all columns\n for (i=0; i < (int)exp_map->size1; i++)\n {\n sum = 0.0;\n contr = 0.0;\n allweight = 0.0;\n\n // determine for each column the total exposure time\n // and the number of pixels with non-zero exposure time\n for (j=0; j < (int)exp_map->size2; j++)\n {\n // check whether the pixel is inside the extraction\n // area and has a positive weight\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 &&\n gsl_matrix_get(exp_map, i, j) > 0.0 )\n {\n // sum up the weigth and the number of pixels\n sum = sum + gsl_matrix_get(exp_map, i, j);\n contr = contr + 1.0;\n }\n }\n\n // check whether the row has exposure time at all\n if (sum > 0.0)\n {\n // if the row is exposed:\n // determine the mean exposure time\n norm = sum / contr;\n\n // go over each pixel\n for (j=0; j < (int)exp_map->size2; j++)\n {\n // check whether the pixel is inside the extraction are\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5)\n {\n // compute and store the relative exposure time (==weight)\n // for positive exposure time\n if (gsl_matrix_get(exp_map, i, j) > 0.0)\n {\n gsl_matrix_set(weight, i,j,gsl_matrix_get(exp_map, i, j)/norm);\n allweight = allweight + gsl_matrix_get(weight, i, j);\n }\n // make a default to avoid values <0.0\n else\n {\n gsl_matrix_set(weight, i,j,0.0);\n }\n }\n }\n }\n // treat unexposed columns differently:\n else\n {\n\n // go over each row\n for (j=0; j < (int)exp_map->size2; j++)\n {\n // check whether the pixel is inside the extraction are\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5)\n {\n // set inside pixels to the defaulkt 1.0\n gsl_matrix_set(weight, i,j,1.0);\n allweight = allweight + gsl_matrix_get(weight, i, j);\n }\n }\n }\n }\n\n // return the resulting weight map\n return weight;\n}\n\n/*\n * Function: comp_opt_weight\n * The function uses the model map and and the variance\n * map and computes optimale weigths according to the\n * Hoorne method.\n * Pixels outside of the extraction\n * area are set to 1000.0\n *\n * Parameters:\n * @param mod_map - the matrix with the model values\n * @param var_map - the matrix with the variance values\n * @param ob - the object structure\n *\n * Returns:\n * @return weight - the matrix with the exposure time weights\n */\ngsl_matrix *\ncomp_opt_weight(gsl_matrix *mod_map,\n gsl_matrix *var_map, const object *ob)\n{\n gsl_matrix *weight;\n int i, j;\n double mod_sum, weight_sum, contr, norm, allweight;\n int beamInt = 0;\n double mod_val;\n //double var_val;\n\n // allocate the weight matrix and set the default\n weight = gsl_matrix_alloc(mod_map->size1, mod_map->size2);\n gsl_matrix_set_all(weight, 0.0);\n\n //* go over all columns\n for (i=0; i < (int)mod_map->size1; i++)\n {\n mod_sum = 0.0;\n contr = 0.0;\n allweight = 0.0;\n weight_sum=0.0;\n\n // determine for each column the total model counts\n // and the number of pixels with non-zero model_counts\n for (j=0; j < (int)mod_map->size2; j++)\n {\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 &&\n gsl_matrix_get(mod_map, i, j) > 0.0 )\n {\n mod_sum = mod_sum + gsl_matrix_get(mod_map, i, j);\n contr = contr + 1.0;\n }\n }\n\n // check whether the column has model values.\n // normalize the model values and compute\n // optimal weights if yes.\n if (mod_sum > 0.0)\n {\n //* determine the mean model value\n // norm = mod_sum / contr;\n norm = mod_sum;\n\n // go over each row\n for (j=0; j < (int)mod_map->size2; j++)\n {\n // check whether the pixel is inside the extraction area\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5 &&\n gsl_matrix_get(mod_map, i, j) > 0.0 )\n {\n // normalize the model counts\n mod_val = gsl_matrix_get(mod_map, i, j)/norm;\n\n // store the normalized model counts\n gsl_matrix_set(mod_map, i, j, mod_val);\n\n // add up the normalization value for the optimal weights\n weight_sum = weight_sum + mod_val*mod_val/gsl_matrix_get(var_map, i, j);\n }\n }\n\n // finally compute and write the weights:\n // go over each pixel\n for (j=0; j < (int)mod_map->size2; j++)\n {\n // check whether the pixel is inside the extraction area\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5)\n {\n if (gsl_matrix_get(mod_map, i, j) > 0.0 )\n {\n // compute and set the individual pixel weight\n gsl_matrix_set(weight, i, j, gsl_matrix_get(mod_map, i, j)/gsl_matrix_get(var_map, i, j)/weight_sum);\n allweight = allweight + gsl_matrix_get(weight, i, j);\n }\n else\n {\n // set the default value if no model value is zero\n gsl_matrix_set(weight, i, j,0.0);\n }\n }\n }\n }\n // if the column does not have model values at all:\n else\n {\n // go over each row\n for (j=0; j < (int)mod_map->size2; j++)\n {\n // check whether the pixel is within the extraction area\n if (fabs(ob->beams[beamInt].refpoint.y-(double)j) <= ob->beams[beamInt].width+0.5)\n {\n // set the inside default value\n gsl_matrix_set(weight, i,j,1.0);\n allweight = allweight + gsl_matrix_get(mod_map, i, j);\n }\n }\n }\n }\n\n // return the weight matrix\n return weight;\n}\n", "meta": {"hexsha": "63ee97c3d846a2ade893e749c03b008950b32e35", "size": 13374, "ext": "c", "lang": "C", "max_stars_repo_path": "cextern/src/drz2pet_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/drz2pet_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/drz2pet_utils.c", "max_forks_repo_name": "sosey/pyaxe", "max_forks_repo_head_hexsha": "f57de55daf77de21d5868ace08b69090778d5975", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6743119266, "max_line_length": 123, "alphanum_fraction": 0.5775385076, "num_tokens": 3637, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6334102498375401, "lm_q2_score": 0.35936415888237616, "lm_q1q2_score": 0.22762494166034336}} {"text": "#ifndef NOVUGNO_IMI_INCLUDE_GNOIMI_H_\n#define NOVUGNO_IMI_INCLUDE_GNOIMI_H_\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\n#include \n#include \n\nstruct threadInfo;\n\nclass GNOIMI {\n public:\n private:\n\tint D;\n\tint K;\n\tint totalLearnCount;\n\tint learnIterationsCount;\n\tint L;\n\n\tint threadsCount;\n\tint totalPoints_perThread;\n\tint Init_chunkSize;\n\n\tint* coarseAssigns;\n\tint* fineAssigns;\n\tfloat* alphaNum;\n\tfloat* alphaDen;\n\tfloat* alpha;\n\n\tvector alphaNumerators;\n\tvector alphaDenominators;\n\n\tfloat* coarseVocab;\n\tfloat* fineVocab;\n\tfloat* fineVocabNum;\n\tfloat* fineVocabDen;\n\tfloat* coarseVocabNum;\n\tfloat* coarseVocabDen;\n\n\tvector fineVocabNumerators;\n\tvector fineVocabDenominators;\n\tvector coarseVocabNumerators;\n\tvector coarseVocabDenominators;\n\n\tfloat* coarseNorms;\n\tfloat* fineNorms;\n\tfloat* coarseFineProducts;\n\n\tfloat* errors;\n\n\tstring output_prefix;\n};\n\nusing namespace std;\n\nint D = 512;\nint K = 657;\nint totalLearnCount = 260000;\nint learnIterationsCount = 20;\nint L = 6;\n\nstring learnFilename = \"./normalized_features_260k.fvecs\";\nstring initCoarseFilename = \"./coarse_260k.fvecs\";\nstring initFineFilename = \"./fine_260k.fvecs\";\nstring outputFilesPrefix = \"./260K_new_\";\n\nint threadsCount = 3;\nint totalPoints_perThread = 0;\nconst int Init_chunkSize = 3000; \n\nint* coarseAssigns = (int*)malloc(totalLearnCount * sizeof(int));\nint* fineAssigns = (int*)malloc(totalLearnCount * sizeof(int));\nfloat* alphaNum = (float*)malloc(K * K * sizeof(float));\nfloat* alphaDen = (float*)malloc(K * K * sizeof(float));\nfloat* alpha = (float*)malloc(K * K * sizeof(float));\n\nvector alphaNumerators(threadsCount);\nvector alphaDenominators(threadsCount);\n\nfloat* coarseVocab = (float*)malloc(D * K * sizeof(float));\nfloat* fineVocab = (float*)malloc(D * K * sizeof(float));\nfloat* fineVocabNum = (float*)malloc(D * K * sizeof(float));\nfloat* fineVocabDen = (float*)malloc(K * sizeof(float));\nfloat* coarseVocabNum = (float*)malloc(D * K * sizeof(float));\nfloat* coarseVocabDen = (float*)malloc(K * sizeof(float));\n\nvector fineVocabNumerators(threadsCount);\nvector fineVocabDenominators(threadsCount);\nvector coarseVocabNumerators(threadsCount);\nvector coarseVocabDenominators(threadsCount);\n\nfloat* coarseNorms = (float*)malloc(K * sizeof(float));\nfloat* fineNorms = (float*)malloc(K * sizeof(float));\nfloat* coarseFineProducts = (float*)malloc(K * K * sizeof(float));\n\nfloat* errors = (float*)malloc(threadsCount * sizeof(float));\nmutex mtx;\n\nstruct threadInfo {\n long long startId;\n int pointsCount;\n int chunksCount;\n int trainThreadChunkSize;\n int extra_ChunkSize;\n};\n\nthreadInfo get_threadInfo(const int& threadId) {\n threadInfo t_info;\n t_info.startId = totalPoints_perThread * threadId; \n t_info.trainThreadChunkSize = Init_chunkSize; \n\n if (totalPoints_perThread * (threadId + 1) <= totalLearnCount) {\n\tt_info.pointsCount = totalPoints_perThread;\t\n } else {\n\tt_info.pointsCount = totalLearnCount - totalPoints_perThread * threadId;\n }\n\n t_info.extra_ChunkSize = 0;\n if (t_info.pointsCount % t_info.trainThreadChunkSize == 0) {\n\tt_info.chunksCount = t_info.pointsCount / t_info.trainThreadChunkSize;\n } else {\n\tt_info.extra_ChunkSize = t_info.pointsCount % t_info.trainThreadChunkSize;\n\tt_info.chunksCount = (t_info.pointsCount - t_info.extra_ChunkSize) / t_info.trainThreadChunkSize + 1;\n }\t\n\n return t_info;\n}\n\nvoid computeOptimalAssignsSubset(int threadId) {\n\n threadInfo cur_t_info = get_threadInfo(threadId);\n int trainThreadChunkSize = cur_t_info.trainThreadChunkSize;\n\n errors[threadId] = 0.0;\n\n FILE* learnStream = fopen(learnFilename.c_str(), \"r\");\n fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET);\n\n float* pointsCoarseTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float));\n float* pointsFineTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float));\n float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\n std::vector > coarseScores(K);\n\n for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) {\n\tstd::cout << \"[Assigns][Thread \" << threadId << \"] \" << \"processing chunk \" << chunkId << \" of \" << cur_t_info.chunksCount << \"\\n\";\n\n\tif (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) {\n\t free(pointsCoarseTerms);\n\t free(pointsFineTerms);\n\t free(chunkPoints); \n\n\t trainThreadChunkSize = cur_t_info.extra_ChunkSize;\n\t pointsCoarseTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float));\n\t pointsFineTerms = (float*)malloc(trainThreadChunkSize * K * sizeof(float));\n\t chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\t}\n\n\tfvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D);\n\tfmat_mul_full(coarseVocab, chunkPoints, K, trainThreadChunkSize, D, \"TN\", pointsCoarseTerms);\n\tfmat_mul_full(fineVocab, chunkPoints, K, trainThreadChunkSize, D, \"TN\", pointsFineTerms);\n\n\tfor(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) {\n\t cblas_saxpy(K, -1.0, coarseNorms, 1, pointsCoarseTerms + pointId * K, 1);\n\n\t for(int k = 0; k < K; ++k) {\n\t\tcoarseScores[k].first = (-1.0) * pointsCoarseTerms[pointId * K + k];\n\t\tcoarseScores[k].second = k;\n\t }\n\n\t std::sort(coarseScores.begin(), coarseScores.end());\n\t float currentMinScore = 999999999.0;\n\t int currentMinCoarseId = -1;\n\t int currentMinFineId = -1;\n\n\t for(int l = 0; l < L; ++l) {\n\t\t//examine cluster l\n\t\tint currentCoarseId = coarseScores[l].second;\n\t\tfloat currentCoarseTerm = coarseScores[l].first;\n\t\tfor(int currentFineId = 0; currentFineId < K; ++currentFineId) {\n\t\t float alphaFactor = alpha[currentCoarseId * K + currentFineId];\n\t\t float score = currentCoarseTerm + alphaFactor * coarseFineProducts[currentCoarseId * K + currentFineId] + \n\t\t\t(-1.0) * alphaFactor * pointsFineTerms[pointId * K + currentFineId] + \n\t\t\talphaFactor * alphaFactor * fineNorms[currentFineId];\n\n\t\t if(score < currentMinScore) {\n\t\t\tcurrentMinScore = score;\n\t\t\tcurrentMinCoarseId = currentCoarseId;\n\t\t\tcurrentMinFineId = currentFineId;\n\t\t }\n\t\t}\n\t }\n\n\t coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId] = currentMinCoarseId;\n\t fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId] = currentMinFineId;\n\n\t errors[threadId] += currentMinScore * 2 + 1.0; // point has a norm equals 1.0\n\t}\n }\n\n fclose(learnStream);\n free(chunkPoints);\n free(pointsCoarseTerms);\n free(pointsFineTerms);\n}\n\nvoid computeOptimalAlphaSubset(int threadId) {\n memset(alphaNumerators[threadId], 0, K * K * sizeof(float));\n memset(alphaDenominators[threadId], 0, K * K * sizeof(float));\n\n threadInfo cur_t_info = get_threadInfo(threadId);\n int trainThreadChunkSize = cur_t_info.trainThreadChunkSize;\n\n FILE* learnStream = fopen(learnFilename.c_str(), \"r\");\n fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET);\n\n float* residual = (float*)malloc(D * sizeof(float));\n float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\n for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) {\n\tstd::cout << \"[Alpha][Thread \" << threadId << \"] \" << \"processing chunk \" << chunkId << \" of \" << cur_t_info.chunksCount << \"\\n\";\n\n\tif (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) {\n\t free(chunkPoints); \n\n\t trainThreadChunkSize = cur_t_info.extra_ChunkSize;\n\t chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\t}\n\n\tfvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D);\n\tfor(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) {\n\t //S_k\n\t int coarseAssign = coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId];\n\t //T_l\n\t int fineAssign = fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId];\n\n\t memcpy(residual, chunkPoints + pointId * D, D * sizeof(float));\n\t //P_i - S_k\n\t cblas_saxpy(D, -1.0, coarseVocab + coarseAssign * D, 1, residual, 1);\n\n\t //\n\t alphaNumerators[threadId][coarseAssign * K + fineAssign] += \n\t\tcblas_sdot(D, residual, 1, fineVocab + fineAssign * D, 1);\n\n\t //||T||^2\n\t alphaDenominators[threadId][coarseAssign * K + fineAssign] += fineNorms[fineAssign] * 2; // we keep halves of norms \n\t}\n }\n fclose(learnStream);\n free(chunkPoints);\n free(residual);\n}\n\nvoid computeOptimalFineVocabSubset(int threadId) {\n memset(fineVocabNumerators[threadId], 0, K * D * sizeof(float));\n memset(fineVocabDenominators[threadId], 0, K * sizeof(float));\n\n threadInfo cur_t_info = get_threadInfo(threadId);\n int trainThreadChunkSize = cur_t_info.trainThreadChunkSize;\n\n FILE* learnStream = fopen(learnFilename.c_str(), \"r\");\n fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET);\n\n float* residual = (float*)malloc(D * sizeof(float));\n float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\n for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) {\n\t//std::cout << \"[Fine vocabs][Thread \" << threadId << \"] \" << \"processing chunk \" << chunkId << \" of \" << chunksCount << \"\\n\";\n\t\n\tif (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) {\n\t free(chunkPoints); \n\n\t trainThreadChunkSize = cur_t_info.extra_ChunkSize;\n\t chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\t}\n\n\tfvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D);\n\tfor(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) {\n\n\t int coarseAssign = coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId];\n\t int fineAssign = fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId];\n\n\t float alphaFactor = alpha[coarseAssign * K + fineAssign];\n\t memcpy(residual, chunkPoints + pointId * D, D * sizeof(float));\n\n\t cblas_saxpy(D, -1.0, coarseVocab + coarseAssign * D, 1, residual, 1);\n\t cblas_saxpy(D, alphaFactor, residual, 1, fineVocabNumerators[threadId] + fineAssign * D, 1);\n\t fineVocabDenominators[threadId][fineAssign] += alphaFactor * alphaFactor;\n\t}\n }\n\n fclose(learnStream);\n free(chunkPoints);\n free(residual);\n}\n\nvoid computeOptimalCoarseVocabSubset(int threadId) {\n memset(coarseVocabNumerators[threadId], 0, K * D * sizeof(float));\n memset(coarseVocabDenominators[threadId], 0, K * sizeof(float));\n\n threadInfo cur_t_info = get_threadInfo(threadId);\n int trainThreadChunkSize = cur_t_info.trainThreadChunkSize;\n\n FILE* learnStream = fopen(learnFilename.c_str(), \"r\");\n fseek(learnStream, cur_t_info.startId * (D + 1) * sizeof(float), SEEK_SET);\n \n float* residual = (float*)malloc(D * sizeof(float));\n float* chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\n for(int chunkId = 0; chunkId < cur_t_info.chunksCount; ++chunkId) {\n\t//std::cout << \"[Coarse vocabs][Thread \" << threadId << \"] \" << \"processing chunk \" << chunkId << \" of \" << chunksCount << \"\\n\";\n\t\n\tif (chunkId == cur_t_info.chunksCount - 1 && cur_t_info.extra_ChunkSize != 0) {\n\t free(chunkPoints); \n\n\t trainThreadChunkSize = cur_t_info.extra_ChunkSize;\n\t chunkPoints = (float*)malloc(trainThreadChunkSize * D * sizeof(float));\n\t}\n\n\tfvecs_fread(learnStream, chunkPoints, trainThreadChunkSize, D);\n\tfor(int pointId = 0; pointId < trainThreadChunkSize; ++pointId) {\n\t int coarseAssign = coarseAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId];\n\t int fineAssign = fineAssigns[cur_t_info.startId + chunkId * cur_t_info.trainThreadChunkSize + pointId];\n\t float alphaFactor = alpha[coarseAssign * K + fineAssign];\n\t memcpy(residual, chunkPoints + pointId * D, D * sizeof(float));\n\t cblas_saxpy(D, -1.0 * alphaFactor, fineVocab + fineAssign * D, 1, residual, 1);\n\t cblas_saxpy(D, 1, residual, 1, coarseVocabNumerators[threadId] + coarseAssign * D, 1);\n\t coarseVocabDenominators[threadId][coarseAssign] += 1.0;\n\t}\n }\n\n fclose(learnStream);\n free(chunkPoints);\n free(residual);\n}\n\nint main() {\n totalPoints_perThread = totalLearnCount / threadsCount; \n\n //increase the threadCount\n if (totalLearnCount % threadsCount != 0) {\n \tthreadsCount += 1;\n\talphaNumerators.resize(threadsCount);\n\talphaDenominators.resize(threadsCount);\n\tfineVocabNumerators.resize(threadsCount);\n\tfineVocabDenominators.resize(threadsCount);\n\tcoarseVocabNumerators.resize(threadsCount);\n\tcoarseVocabDenominators.resize(threadsCount);\n\tfree(errors);\n\terrors = (float*)malloc(threadsCount * sizeof(float));\n }\n\n for(int threadId = 0; threadId < threadsCount; ++threadId) {\n\talphaNumerators[threadId] = (float*)malloc(K * K * sizeof(float*));\n\talphaDenominators[threadId] = (float*)malloc(K * K * sizeof(float*));\n }\n\n for(int threadId = 0; threadId < threadsCount; ++threadId) {\n\tfineVocabNumerators[threadId] = (float*)malloc(K * D * sizeof(float*));\n\tfineVocabDenominators[threadId] = (float*)malloc(K * sizeof(float*));\n } \n\n for(int threadId = 0; threadId < threadsCount; ++threadId) {\n\tcoarseVocabNumerators[threadId] = (float*)malloc(K * D * sizeof(float));\n\tcoarseVocabDenominators[threadId] = (float*)malloc(K * sizeof(float));\n }\n\n // init vocabs\n fvecs_read(initCoarseFilename.c_str(), D, K, coarseVocab);\n fvecs_read(initFineFilename.c_str(), D, K, fineVocab);\n\n // init alpha\n for(int i = 0; i < K * K; ++i) {\n\talpha[i] = 1.0f;\n }\n\n // learn iterations\n std::cout << \"Start learning iterations...\\n\";\n for(int it = 0; it < learnIterationsCount; ++it) {\n\tcout << \"learning iteration \" << it << endl;\n\tfor(int k = 0; k < K; ++k) {\n\t coarseNorms[k] = cblas_sdot(D, coarseVocab + k * D, 1, coarseVocab + k * D, 1) / 2;\n\t fineNorms[k] = cblas_sdot(D, fineVocab + k * D, 1, fineVocab + k * D, 1) / 2;\n\t}\n\n\tfmat_mul_full(fineVocab, coarseVocab, K, K, D, \"TN\", coarseFineProducts);\n\n\t// update Assigns\n\tvector workers;\n\tmemset(errors, 0, threadsCount * sizeof(float));\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers.push_back(std::thread(computeOptimalAssignsSubset, threadId));\n\t}\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers[threadId].join();\n\t}\n\n\tfloat totalError = 0.0;\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t cout << \"threadId \" << threadId << \": err \" << errors[threadId] << endl;\n\t totalError += errors[threadId];\n\t}\n\tstd::cout << \"Current reconstruction error... \" << totalError / totalLearnCount << \"\\n\";\n\n\t// update alpha\n\tworkers.clear();\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers.push_back(std::thread(computeOptimalAlphaSubset, threadId));\n\t}\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers[threadId].join();\n\t}\n\n\t// update fine Vocabs\n\tworkers.clear();\n\tmemset(alphaNum, 0, K * K * sizeof(float));\n\tmemset(alphaDen, 0, K * K * sizeof(float));\n\t\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t cblas_saxpy(K * K, 1, alphaNumerators[threadId], 1, alphaNum, 1);\n\t cblas_saxpy(K * K, 1, alphaDenominators[threadId], 1, alphaDen, 1);\n\t}\n\n\tfor(int i = 0; i < K * K; ++i) {\n\t alpha[i] = (alphaDen[i] == 0) ? 1.0 : alphaNum[i] / alphaDen[i];\n\t}\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers.push_back(std::thread(computeOptimalFineVocabSubset, threadId));\n\t}\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers[threadId].join();\n\t}\n\n\t// update coarse Vocabs\n\tworkers.clear();\n\tmemset(fineVocabNum, 0, K * D * sizeof(float));\n\tmemset(fineVocabDen, 0, K * sizeof(float));\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t cblas_saxpy(K * D, 1, fineVocabNumerators[threadId], 1, fineVocabNum, 1);\n\t cblas_saxpy(K, 1, fineVocabDenominators[threadId], 1, fineVocabDen, 1);\n\t}\n\n\tfor(int i = 0; i < K * D; ++i) {\n\t fineVocab[i] = (fineVocabDen[i / D] == 0) ? 0 : fineVocabNum[i] / fineVocabDen[i / D];\n\t}\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers.push_back(std::thread(computeOptimalCoarseVocabSubset, threadId));\n\t}\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t workers[threadId].join();\n\t}\n\n\tworkers.clear();\n\tmemset(coarseVocabNum, 0, K * D * sizeof(float));\n\tmemset(coarseVocabDen, 0, K * sizeof(float));\n\n\tfor(int threadId = 0; threadId < threadsCount; ++threadId) {\n\t cblas_saxpy(K * D, 1, coarseVocabNumerators[threadId], 1, coarseVocabNum, 1);\n\t cblas_saxpy(K, 1, coarseVocabDenominators[threadId], 1, coarseVocabDen, 1);\n\t}\n\n\tfor(int i = 0; i < K * D; ++i) {\n\t coarseVocab[i] = (coarseVocabDen[i / D] == 0) ? 0 : coarseVocabNum[i] / coarseVocabDen[i / D];\n\t}\n\n\t// save current alpha and vocabs\n\tstd::stringstream alphaFilename;\n\talphaFilename << outputFilesPrefix << \"alpha_\" << it << \".fvecs\";\n\tfvecs_write(alphaFilename.str().c_str(), K, K, alpha);\n\t\n\tstd::stringstream fineVocabFilename;\n\tfineVocabFilename << outputFilesPrefix << \"fine_\" << it << \".fvecs\";\n\tfvecs_write(fineVocabFilename.str().c_str(), D, K, fineVocab);\n\t\n\tstd::stringstream coarseVocabFilename;\n\tcoarseVocabFilename << outputFilesPrefix << \"coarse_\" << it << \".fvecs\";\n\tfvecs_write(coarseVocabFilename.str().c_str(), D, K, coarseVocab);\n\n\tcout << \"iteration \" << it << \" finished!\" << endl;\n }\n\n free(coarseAssigns);\n free(fineAssigns);\n free(alphaNum);\n free(alphaDen);\n free(alpha);\n free(coarseVocab);\n free(coarseVocabNum);\n free(coarseVocabDen);\n free(fineVocab);\n free(fineVocabNum);\n free(fineVocabDen);\n free(coarseNorms);\n free(fineNorms);\n free(coarseFineProducts);\n free(errors);\n return 0;\n}\n#endif //NOVUGNO_IMI_INCLUDE_GNOIMI_H_\n", "meta": {"hexsha": "b1abdac519ddb0b771bbbd7dbd101e5ccd8abbb1", "size": 18152, "ext": "h", "lang": "C", "max_stars_repo_path": "include/GNOIMI.h", "max_stars_repo_name": "5ace/GNOIMI-1", "max_stars_repo_head_hexsha": "befa71ab0c774a6c878c8a45ab77248cdc2be089", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-26T07:54:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-26T07:54:33.000Z", "max_issues_repo_path": "include/GNOIMI.h", "max_issues_repo_name": "5ace/GNOIMI-1", "max_issues_repo_head_hexsha": "befa71ab0c774a6c878c8a45ab77248cdc2be089", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/GNOIMI.h", "max_forks_repo_name": "5ace/GNOIMI-1", "max_forks_repo_head_hexsha": "befa71ab0c774a6c878c8a45ab77248cdc2be089", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T08:18:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-02T06:49:54.000Z", "avg_line_length": 35.0424710425, "max_line_length": 133, "alphanum_fraction": 0.6926509476, "num_tokens": 5253, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.38121956625614994, "lm_q1q2_score": 0.22737198531979133}} {"text": "/* multifit_nlinear/trust.c\n * \n * Copyright (C) 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common.c\"\n#include \"nielsen.c\"\n\n/*\n * This module contains a high level driver for a general trust\n * region nonlinear least squares solver. This container handles\n * the computation of all of the quantities relevant to all trust\n * region methods, including:\n *\n * residual vector: f_k = f(x_k)\n * Jacobian matrix: J_k = J(x_k)\n * gradient vector: g_k = J_k^T f_k\n * scaling matrix: D_k\n */\n\ntypedef struct\n{\n size_t n; /* number of observations */\n size_t p; /* number of parameters */\n double delta; /* trust region radius */\n double mu; /* LM parameter */\n long nu; /* for updating LM parameter */\n gsl_vector *diag; /* D = diag(J^T J) */\n gsl_vector *x_trial; /* trial parameter vector */\n gsl_vector *f_trial; /* trial function vector */\n gsl_vector *workp; /* workspace, length p */\n gsl_vector *workn; /* workspace, length n */\n\n void *trs_state; /* workspace for trust region subproblem */\n void *solver_state; /* workspace for linear least squares solver */\n\n double avratio; /* current |a| / |v| */\n\n /* tunable parameters */\n gsl_multifit_nlinear_parameters params;\n} trust_state_t;\n\nstatic void * trust_alloc (const gsl_multifit_nlinear_parameters * params,\n const size_t n, const size_t p);\nstatic void trust_free(void *vstate);\nstatic int trust_init(void *vstate, const gsl_vector * swts,\n gsl_multifit_nlinear_fdf *fdf, const gsl_vector *x,\n gsl_vector *f, gsl_matrix *J, gsl_vector *g);\nstatic int trust_iterate(void *vstate, const gsl_vector *swts,\n gsl_multifit_nlinear_fdf *fdf,\n gsl_vector *x, gsl_vector *f, gsl_matrix *J,\n gsl_vector *g, gsl_vector *dx);\nstatic int trust_rcond(double *rcond, void *vstate);\nstatic double trust_avratio(void *vstate);\nstatic void trust_trial_step(const gsl_vector * x, const gsl_vector * dx,\n gsl_vector * x_trial);\nstatic double trust_calc_rho(const gsl_vector * f, const gsl_vector * f_trial,\n const gsl_vector * g, const gsl_matrix * J,\n const gsl_vector * dx, trust_state_t * state);\nstatic int trust_eval_step(const gsl_vector * f, const gsl_vector * f_trial,\n const gsl_vector * g, const gsl_matrix * J,\n const gsl_vector * dx, double * rho, trust_state_t * state);\nstatic double trust_scaled_norm(const gsl_vector *D, const gsl_vector *a);\n\nstatic void *\ntrust_alloc (const gsl_multifit_nlinear_parameters * params,\n const size_t n, const size_t p)\n{\n trust_state_t *state;\n \n state = calloc(1, sizeof(trust_state_t));\n if (state == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate lm state\", GSL_ENOMEM);\n }\n\n state->diag = gsl_vector_alloc(p);\n if (state->diag == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for diag\", 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->x_trial = gsl_vector_alloc(p);\n if (state->x_trial == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for x_trial\", GSL_ENOMEM);\n }\n\n state->f_trial = gsl_vector_alloc(n);\n if (state->f_trial == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for f_trial\", GSL_ENOMEM);\n }\n\n state->trs_state = (params->trs->alloc)(params, n, p);\n if (state->trs_state == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for trs state\", GSL_ENOMEM);\n }\n\n state->solver_state = (params->solver->alloc)(n, p);\n if (state->solver_state == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for solver state\", GSL_ENOMEM);\n }\n\n state->n = n;\n state->p = p;\n state->delta = 0.0;\n state->params = *params;\n\n return state;\n}\n\nstatic void\ntrust_free(void *vstate)\n{\n trust_state_t *state = (trust_state_t *) vstate;\n const gsl_multifit_nlinear_parameters *params = &(state->params);\n\n if (state->diag)\n gsl_vector_free(state->diag);\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->x_trial)\n gsl_vector_free(state->x_trial);\n\n if (state->f_trial)\n gsl_vector_free(state->f_trial);\n\n if (state->trs_state)\n (params->trs->free)(state->trs_state);\n\n if (state->solver_state)\n (params->solver->free)(state->solver_state);\n\n free(state);\n}\n\n/*\ntrust_init()\n Initialize trust region solver\n\nInputs: vstate - workspace\n swts - sqrt(W) vector\n fdf - user callback functions\n x - initial parameter values\n f - (output) f(x) vector\n J - (output) J(x) matrix\n g - (output) J(x)' f(x) vector\n\nReturn: success/error\n*/\n\nstatic int\ntrust_init(void *vstate, const gsl_vector *swts,\n gsl_multifit_nlinear_fdf *fdf, const gsl_vector *x,\n gsl_vector *f, gsl_matrix *J, gsl_vector *g)\n{\n int status;\n trust_state_t *state = (trust_state_t *) vstate;\n const gsl_multifit_nlinear_parameters *params = &(state->params);\n double Dx;\n\n /* evaluate function and Jacobian at x and apply weight transform */\n status = gsl_multifit_nlinear_eval_f(fdf, x, swts, f);\n if (status)\n return status;\n\n status = gsl_multifit_nlinear_eval_df(x, f, swts, params->h_df,\n params->fdtype, fdf, J, state->workn);\n if (status)\n return status;\n\n /* compute g = J^T f */\n gsl_blas_dgemv(CblasTrans, 1.0, J, f, 0.0, g);\n\n /* initialize diagonal scaling matrix D */\n (params->scale->init)(J, state->diag);\n\n /* compute initial trust region radius */\n Dx = trust_scaled_norm(state->diag, x);\n state->delta = 0.3 * GSL_MAX(1.0, Dx);\n\n /* initialize LM parameter */\n status = nielsen_init(J, state->diag, &(state->mu), &(state->nu));\n if (status)\n return status;\n\n /* initialize trust region method solver */\n {\n gsl_multifit_nlinear_trust_state trust_state;\n \n trust_state.x = x;\n trust_state.f = f;\n trust_state.g = g;\n trust_state.J = J;\n trust_state.diag = state->diag;\n trust_state.sqrt_wts = swts;\n trust_state.mu = &(state->mu);\n trust_state.params = params;\n trust_state.solver_state = state->solver_state;\n trust_state.fdf = fdf;\n trust_state.avratio = &(state->avratio);\n\n status = (params->trs->init)(&trust_state, state->trs_state);\n\n if (status)\n return status;\n }\n\n /* set default parameters */\n\n state->avratio = 0.0;\n\n return GSL_SUCCESS;\n}\n\n/*\ntrust_iterate()\n This function performs 1 iteration of the trust region algorithm.\nIt calls a user-specified method for computing the next step\n(LM or dogleg), then tests if the computed step is acceptable.\n\nArgs: vstate - trust workspace\n swts - data weights (NULL if unweighted)\n fdf - function and Jacobian pointers\n x - on input, current parameter vector\n on output, new parameter vector x + dx\n f - on input, f(x)\n on output, f(x + dx)\n J - on input, J(x)\n on output, J(x + dx)\n g - on input, g(x) = J(x)' f(x)\n on output, g(x + dx) = J(x + dx)' f(x + dx)\n dx - (output only) parameter step vector\n\nReturn:\n1) GSL_SUCCESS if we found a step which reduces the cost\nfunction\n\n2) GSL_ENOPROG if 15 successive attempts were to made to\nfind a good step without success\n\n3) If a scaling matrix D is used, inputs and outputs are\nset to the unscaled quantities (ie: J and g)\n*/\n\nstatic int\ntrust_iterate(void *vstate, const gsl_vector *swts,\n gsl_multifit_nlinear_fdf *fdf, gsl_vector *x,\n gsl_vector *f, gsl_matrix *J, gsl_vector *g,\n gsl_vector *dx)\n{\n int status;\n trust_state_t *state = (trust_state_t *) vstate;\n const gsl_multifit_nlinear_parameters *params = &(state->params);\n const gsl_multifit_nlinear_trs *trs = params->trs;\n gsl_multifit_nlinear_trust_state trust_state;\n gsl_vector *x_trial = state->x_trial; /* trial x + dx */\n gsl_vector *f_trial = state->f_trial; /* trial f(x + dx) */\n gsl_vector *diag = state->diag; /* diag(D) */\n double rho; /* ratio actual_reduction/predicted_reduction */\n int foundstep = 0; /* found step dx */\n int bad_steps = 0; /* consecutive rejected steps */\n\n /* store all state parameters needed by low level methods */\n trust_state.x = x;\n trust_state.f = f;\n trust_state.g = g;\n trust_state.J = J;\n trust_state.diag = state->diag;\n trust_state.sqrt_wts = swts;\n trust_state.mu = &(state->mu);\n trust_state.params = params;\n trust_state.solver_state = state->solver_state;\n trust_state.fdf = fdf;\n trust_state.avratio = &(state->avratio);\n\n /* initialize trust region subproblem with this Jacobian */\n status = (trs->preloop)(&trust_state, state->trs_state);\n if (status)\n return status;\n\n /* loop until we find an acceptable step dx */\n while (!foundstep)\n {\n /* calculate new step */\n status = (trs->step)(&trust_state, state->delta, dx, state->trs_state);\n\n /* occasionally the iterative methods (ie: CG Steihaug) can fail to find a step,\n * so in this case skip rho calculation and count it as a rejected step */\n\n if (status == GSL_SUCCESS)\n {\n /* compute x_trial = x + dx */\n trust_trial_step(x, dx, x_trial);\n\n /* compute f_trial = f(x + dx) */\n status = gsl_multifit_nlinear_eval_f(fdf, x_trial, swts, f_trial);\n if (status)\n return status;\n\n /* check if step should be accepted or rejected */\n status = trust_eval_step(f, f_trial, g, J, dx, &rho, state);\n if (status == GSL_SUCCESS)\n foundstep = 1;\n }\n else\n {\n /* an iterative TRS method failed to find a step vector */\n rho = -1.0;\n }\n\n /*\n * update trust region radius: if rho is large,\n * then the quadratic model is a good approximation\n * to the objective function, enlarge trust region.\n * If rho is small (or negative), the model function\n * is a poor approximation so decrease trust region. This\n * can happen even if the step is accepted.\n */\n if (rho > 0.75)\n state->delta *= params->factor_up;\n else if (rho < 0.25)\n state->delta /= params->factor_down;\n\n if (foundstep)\n {\n /* step was accepted */\n\n /* compute J <- J(x + dx) */\n status = gsl_multifit_nlinear_eval_df(x_trial, f_trial, swts,\n params->h_df, params->fdtype,\n fdf, J, state->workn);\n if (status)\n return status;\n\n /* update x <- x + dx */\n gsl_vector_memcpy(x, x_trial);\n\n /* update f <- f(x + dx) */\n gsl_vector_memcpy(f, f_trial);\n\n /* compute new g = J^T f */\n gsl_blas_dgemv(CblasTrans, 1.0, J, f, 0.0, g);\n\n /* update scaling matrix D */\n (params->scale->update)(J, diag);\n\n /* step accepted, decrease LM parameter */\n status = nielsen_accept(rho, &(state->mu), &(state->nu));\n if (status)\n return status;\n\n bad_steps = 0;\n }\n else\n {\n /* step rejected, increase LM parameter */\n status = nielsen_reject(&(state->mu), &(state->nu));\n if (status)\n return status;\n\n if (++bad_steps > 15)\n {\n /* if more than 15 consecutive rejected steps, report no progress */\n return GSL_ENOPROG;\n }\n }\n }\n\n return GSL_SUCCESS;\n} /* trust_iterate() */\n\nstatic int\ntrust_rcond(double *rcond, void *vstate)\n{\n int status;\n trust_state_t *state = (trust_state_t *) vstate;\n const gsl_multifit_nlinear_parameters *params = &(state->params);\n \n status = (params->solver->rcond)(rcond, state->solver_state);\n\n return status;\n}\n\nstatic double\ntrust_avratio(void *vstate)\n{\n trust_state_t *state = (trust_state_t *) vstate;\n return state->avratio;\n}\n\n/* compute x_trial = x + dx */\nstatic void\ntrust_trial_step(const gsl_vector * x, const gsl_vector * dx,\n gsl_vector * x_trial)\n{\n size_t i, N = x->size;\n\n for (i = 0; i < N; i++)\n {\n double dxi = gsl_vector_get (dx, i);\n double xi = gsl_vector_get (x, i);\n gsl_vector_set (x_trial, i, xi + dxi);\n }\n}\n\n/*\ntrust_calc_rho()\n Calculate ratio of actual reduction to predicted\nreduction.\n\nrho = actual_reduction / predicted_reduction\n\nactual_reduction = 1 - ( ||f+|| / ||f|| )^2\npredicted_reduction = -2 g^T dx / ||f||^2 - ( ||J*dx|| / ||f|| )^2\n = -2 fhat . beta - ||beta||^2\n\nwhere: beta = J*dx / ||f||\n\nInputs: f - f(x)\n f_trial - f(x + dx)\n g - gradient J^T f\n J - Jacobian\n dx - proposed step, size p\n state - workspace\n\nReturn: rho = actual_reduction / predicted_reduction\nIf actual_reduction is < 0, return rho = -1\n*/\n\nstatic double\ntrust_calc_rho(const gsl_vector * f, const gsl_vector * f_trial,\n const gsl_vector * g, const gsl_matrix * J,\n const gsl_vector * dx, trust_state_t * state)\n{\n int status;\n const gsl_multifit_nlinear_parameters *params = &(state->params);\n const gsl_multifit_nlinear_trs *trs = params->trs;\n const double normf = gsl_blas_dnrm2(f);\n const double normf_trial = gsl_blas_dnrm2(f_trial);\n gsl_multifit_nlinear_trust_state trust_state;\n double rho;\n double actual_reduction;\n double pred_reduction;\n double u;\n\n /* if ||f(x+dx)|| > ||f(x)|| reject step immediately */\n if (normf_trial >= normf)\n return -1.0;\n\n trust_state.x = NULL;\n trust_state.f = f;\n trust_state.g = g;\n trust_state.J = J;\n trust_state.diag = state->diag;\n trust_state.sqrt_wts = NULL;\n trust_state.mu = &(state->mu);\n trust_state.params = params;\n trust_state.solver_state = state->solver_state;\n trust_state.fdf = NULL;\n trust_state.avratio = &(state->avratio);\n\n /* compute numerator of rho (actual reduction) */\n u = normf_trial / normf;\n actual_reduction = 1.0 - u*u;\n\n /*\n * compute denominator of rho (predicted reduction); this is calculated\n * inside each trust region subproblem, since it depends on the local\n * model used, which can vary according to each TRS\n */\n status = (trs->preduction)(&trust_state, dx, &pred_reduction, state->trs_state);\n if (status)\n return -1.0;\n\n if (pred_reduction > 0.0)\n rho = actual_reduction / pred_reduction;\n else\n rho = -1.0;\n\n return rho;\n}\n\n/*\ntrust_eval_step()\n Evaluate proposed step to determine if it should be\naccepted or rejected\n*/\n\nstatic int\ntrust_eval_step(const gsl_vector * f, const gsl_vector * f_trial,\n const gsl_vector * g, const gsl_matrix * J,\n const gsl_vector * dx, double * rho, trust_state_t * state)\n{\n int status = GSL_SUCCESS;\n const gsl_multifit_nlinear_parameters *params = &(state->params);\n\n if (params->trs == gsl_multifit_nlinear_trs_lmaccel)\n {\n /* reject step if acceleration is too large compared to velocity */\n if (state->avratio > params->avmax)\n status = GSL_FAILURE;\n }\n\n /* compute rho */\n *rho = trust_calc_rho(f, f_trial, g, J, dx, state);\n if (*rho <= 0.0)\n status = GSL_FAILURE;\n\n return status;\n}\n\n/* compute || diag(D) a || */\nstatic double\ntrust_scaled_norm(const gsl_vector *D, const gsl_vector *a)\n{\n const size_t n = a->size;\n double e2 = 0.0;\n size_t i;\n\n for (i = 0; i < n; ++i)\n {\n double Di = gsl_vector_get(D, i);\n double ai = gsl_vector_get(a, i);\n double u = Di * ai;\n\n e2 += u * u;\n }\n\n return sqrt (e2);\n}\n\nstatic const gsl_multifit_nlinear_type trust_type =\n{\n \"trust-region\",\n trust_alloc,\n trust_init,\n trust_iterate,\n trust_rcond,\n trust_avratio,\n trust_free\n};\n\nconst gsl_multifit_nlinear_type *gsl_multifit_nlinear_trust = &trust_type;\n", "meta": {"hexsha": "2d42ff70121bd02192fcfb6cf44d2c2ac74132bf", "size": 17443, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multifit_nlinear/trust.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/trust.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/trust.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": 29.6146010187, "max_line_length": 94, "alphanum_fraction": 0.622255346, "num_tokens": 4544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6370307944803832, "lm_q2_score": 0.35577489351363034, "lm_q1q2_score": 0.22663956307116168}} {"text": "/*\n * vbHmmPc.c\n * Model-specific core functions for VB-HMM-PC.\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 \n#include \n#include \n#include \n#include \n#include \n#include \"vbHmmPc.h\"\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//static int isGlobalAnalysis = 0;\n\nvoid setFunctions_pc(){\n commonFunctions funcs;\n funcs.newModelParameters = newModelParameters_pc;\n funcs.freeModelParameters = freeModelParameters_pc;\n funcs.newModelStats = newModelStats_pc;\n funcs.freeModelStats = freeModelStats_pc;\n funcs.initializeVbHmm = initializeVbHmm_pc;\n funcs.pTilde_z1 = pTilde_z1_pc;\n funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pc;\n funcs.pTilde_xn_zn = pTilde_xn_zn_pc;\n funcs.calcStatsVars = calcStatsVars_pc;\n funcs.maximization = maximization_pc;\n funcs.varLowerBound = varLowerBound_pc;\n funcs.reorderParameters = reorderParameters_pc;\n funcs.outputResults = outputResults_pc;\n setFunctions( funcs );\n}\n\n//void setGFunctions_pc(){\n// gCommonFunctions funcs;\n// funcs.newModelParameters = newModelParameters_pc;\n// funcs.freeModelParameters = freeModelParameters_pc;\n// funcs.newModelStats = newModelStats_pc;\n// funcs.freeModelStats = freeModelStats_pc;\n// funcs.newModelStatsG = newModelStatsG_pc;\n// funcs.freeModelStatsG = freeModelStatsG_pc;\n// funcs.initializeVbHmmG = initializeVbHmmG_pc;\n// funcs.pTilde_z1 = pTilde_z1_pc;\n// funcs.pTilde_zn_zn1 = pTilde_zn_zn1_pc;\n// funcs.pTilde_xn_zn = pTilde_xn_zn_pc;\n// funcs.calcStatsVarsG = calcStatsVarsG_pc;\n// funcs.maximizationG = maximizationG_pc;\n// funcs.varLowerBoundG = varLowerBoundG_pc;\n// funcs.reorderParametersG = reorderParametersG_pc;\n// funcs.outputResultsG = outputResultsG_pc;\n// setGFunctions( funcs );\n// isGlobalAnalysis = 1;\n//}\n\n\nvoid outputResults_pc( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n outputPcResults( xn, gv, iv, logFP );\n}\n\n//void outputResultsG_pc( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n// outputPcResultsG( xns, gv, ivs, logFP );\n//}\n\n\nvoid *newModelParameters_pc( xn, sNo )\nxnDataSet *xn;\nint sNo;\n{\n int i;\n pcParameters *p = (void*)malloc( sizeof(pcParameters) );\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 p->avgI = (double *)malloc( sNo * sizeof(double) );\n p->avgLnI = (double *)malloc( sNo * sizeof(double) );\n\n p->aIArr = (double*)malloc( sNo * sizeof(double) );\n p->bIArr = (double*)malloc( sNo * sizeof(double) );\n\n return p;\n}\n\nvoid freeModelParameters_pc( p, xn, sNo )\nvoid **p;\nxnDataSet *xn;\nint sNo;\n{\n pcParameters *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->avgI );\n free( gp->avgLnI );\n \n free( gp->aIArr );\n free( gp->bIArr );\n \n free( *p );\n *p = NULL;\n}\n\n\nvoid *newModelStats_pc( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n pcStats *s = (pcStats*)malloc( sizeof(pcStats) );\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->Ci = (double *)malloc( sNo * sizeof(double) );\n s->Mi = (double *)malloc( sNo * sizeof(double) );\n \n return s;\n \n// } else {\n// \n// return NULL;\n// \n// }\n}\n\nvoid freeModelStats_pc( s, xn, gv, iv )\nvoid **s;\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n// if( isGlobalAnalysis == 0 ){\n int sNo = gv->sNo;\n pcStats *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->Ci );\n free( gs->Mi );\n \n free( gs );\n *s = NULL;\n// }\n}\n\n//void *newModelStatsG_pc( xns, gv, ivs)\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// int sNo = gv->sNo;\n// pcGlobalStats *gs = (pcGlobalStats*)malloc( sizeof(pcGlobalStats) );\n// \n// return gs;\n//}\n\n//void freeModelStatsG_pc( gs, xns, gv, ivs )\n//void **gs;\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n// int sNo = gv->sNo;\n// pcGlobalStats *ggs = *gs;\n// \n// free( *gs );\n// *gs = NULL;\n//}\n\n\nvoid initializeVbHmm_pc( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcData *d = xn->data;\n size_t dLen = xn->N;\n int sNo = gv->sNo;\n pcParameters *p = gv->params;\n\n int i, j;\n size_t totalC = 0;\n for( i = 0 ; i < dLen ; i++ ){\n totalC += d->counts[i];\n }\n double meanI = (double)totalC / (double)dLen;\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( 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] = 100.0;\n } else {\n p->uAMat[i][j] = 1.0;\n }\n p->sumUAArr[i] += p->uAMat[i][j];\n }\n }\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_pc( xn, gv, iv );\n \n calcStatsVars_pc( xn, gv, iv );\n maximization_pc( xn, gv, iv );\n}\n\n//void initializeVbHmmG_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid initialize_indVars_pc( 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_pc( 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 = (pcData*)malloc( sizeof(pcData) );\n pcData *d = (pcData*)xn->data;\n d->binSize = 0.0;\n d->counts = NULL;\n return xn;\n}\n\nvoid freeXnDataSet_pc( xn )\nxnDataSet **xn;\n{\n pcData *d = (pcData*)(*xn)->data;\n free( d->counts );\n free( (*xn)->data );\n free( (*xn)->name );\n free( *xn );\n *xn = NULL;\n}\n\n\ndouble pTilde_z1_pc( i, params )\nint i;\nvoid *params;\n{\n pcParameters *p = (pcParameters*)params;\n return exp( p->avgLnPi[i] );\n}\n\ndouble pTilde_zn_zn1_pc( i, j, params )\nint i, j;\nvoid *params;\n{\n pcParameters *p = (pcParameters*)params;\n return exp( p->avgLnA[i][j] );\n}\n\ndouble pTilde_xn_zn_pc( xnWv, n, i, params )\nxnDataSet *xnWv;\nsize_t n;\nint i;\nvoid *params;\n{\n pcParameters *p = (pcParameters*)params;\n pcData *xn = (pcData*)xnWv->data;\n return exp( p->avgLnI[i] * (double)xn->counts[n] - p->avgI[i] ) / gsl_sf_fact( xn->counts[n] );\n}\n\n\nvoid calcStatsVars_pc( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcData *d = (pcData*)xn->data;\n pcStats *s = (pcStats*)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, **Nij = s->Nij;\n double *Mi = s->Mi, *Ci = s->Ci;\n size_t n;\n int i, j;\n\n for( i = 0 ; i < sNo ; i++ ){\n Ni[i] = 1e-10;\n Ci[i] = 1e-10;\n Mi[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 for( i = 0 ; i < sNo ; i++ ){\n Ni[i] += gmMat[n][i];\n Ci[i] += gmMat[n][i] * (double)d->counts[n];\n for( j = 0 ; j < sNo ; j++ ){\n Mi[i] += xiMat[n][i][j];\n Nij[i][j] += xiMat[n][i][j];\n }\n }\n }\n}\n\n//void calcStatsVarsG_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid maximization_pc( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcParameters *p = (pcParameters*)gv->params;\n pcStats *s = (pcStats*)iv->stats;\n int sNo = gv->sNo;\n double **gmMat = iv->gmMat;\n double *avgPi = p->avgPi, *avgLnPi = p->avgLnPi, **avgA = p->avgA, **avgLnA = p->avgLnA;\n double *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *Ni = s->Ni, **Nij = s->Nij;\n double *Mi = s->Mi, *Ci = s->Ci;\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] + Mi[i] );\n avgLnA[i][j] = gsl_sf_psi( uAMat[i][j] + Nij[i][j] ) - gsl_sf_psi( sumUAArr[i] + Mi[i] );\n }\n \n avgI[i] = (Ci[i] + aIArr[i]) / (Ni[i] + bIArr[i]);\n avgLnI[i] = gsl_sf_psi( Ci[i] + aIArr[i] ) - log( Ni[i] + bIArr[i] );\n#ifdef INTENSITY_CAP\n size_t n, totalC = 0;\n pcData *pc = xnWv->data;\n for( n = 0 ; n < xnWv->N ; n++ ){\n totalC += pc->counts[n];\n }\n double meanI = (double)totalC / (double)xnWv->N;\n avgI[i] = MIN( avgI[i], maxIntensityRatio * meanI );\n avgLnI[i] = MIN( avgLnI[i], log(maxIntensityRatio * meanI) );\n#endif\n }\n}\n\n//void maximizationG_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\ndouble varLowerBound_pc( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcParameters *p = (pcParameters*)gv->params;\n pcStats *s = (pcStats*)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, **avgLnA = p->avgLnA;\n double *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *uPiArr = p->uPiArr, sumUPi = p->sumUPi, *aIArr = p->aIArr, *bIArr = p->bIArr;\n double **uAMat = p->uAMat, *sumUAArr = p->sumUAArr;\n double *Ni = s->Ni, **Nij = s->Nij;\n double *Mi = s->Mi, *Ci = s->Ci;\n size_t n;\n int i, j;\n \n double lnpPi = gsl_sf_lngamma(sumUPi);\n double lnpA = 0.0;\n double lnpI = 0.0;\n double lnqPi = gsl_sf_lngamma(sumUPi + 1.0);\n double lnqA = 0.0;\n double lnqI = 0.0;\n for( i = 0 ; i < sNo ; i++ ){\n lnpPi += (uPiArr[i]-1.0) * avgLnPi[i] - gsl_sf_lngamma(uPiArr[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.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 lnqI += (Ci[i] + aIArr[i]) * log(Ni[i] + bIArr[i]) - gsl_sf_lngamma(Ci[i] + aIArr[i]);\n lnqI += (Ci[i] + aIArr[i] - 1.0) * avgLnI[i] - (Ni[i] + bIArr[i]) * avgI[i];\n\n lnpA += gsl_sf_lngamma(sumUAArr[i]);\n lnqA += gsl_sf_lngamma(sumUAArr[i] + Mi[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]+Mi[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 + lnpI;\n val -= lnqPi + lnqA + lnqI;\n val += lnpX;\n val += log(gsl_sf_fact(sNo));\n\n return val;\n} \n\n//double varLowerBoundG_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid reorderParameters_pc( xn, gv, iv )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\n{\n pcParameters *p = (pcParameters*)gv->params;\n pcStats *s = (pcStats*)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 *avgI = p->avgI, *avgLnI = p->avgLnI;\n double *Ni = s->Ni, *Ci = s->Ci;\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]] = 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( i = 0 ; i < sNo ; i++ ){ store[index[i]] = Ci[i]; }\n for( i = 0 ; i < sNo ; i++ ){ Ci[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_pc( xns, gv, ivs )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//{\n//}\n\n\nvoid outputPcResults( xn, gv, iv, logFP )\nxnDataSet *xn;\nglobalVars *gv;\nindVars *iv;\nFILE *logFP;\n{\n pcParameters *p = (pcParameters*)gv->params;\n int sNo = gv->sNo;\n\n int i, j;\n fprintf(logFP, \" results: K = %d \\n\", sNo);\n \n fprintf(logFP, \" intensity: ( %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, \" 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, \"I, 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\", p->avgI[i], 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\n//void outputPcResultsG( xns, gv, ivs, logFP )\n//xnDataBundle *xns;\n//globalVars *gv;\n//indVarBundle *ivs;\n//FILE *logFP;\n//{\n//}\n\n//\n", "meta": {"hexsha": "579c1e03b3fc9e8ab5a708a67ad2e5aa866680d1", "size": 18837, "ext": "c", "lang": "C", "max_stars_repo_path": "C/vbHmmPc.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/vbHmmPc.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/vbHmmPc.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": 26.7571022727, "max_line_length": 124, "alphanum_fraction": 0.497372193, "num_tokens": 6860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5660185351961015, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22630079924588875}} {"text": "#ifndef _MASSINTEGRAND__H\n#define _MASSINTEGRAND__H\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAS_MKL\n#include \n#else\n#include \n#endif\n\n#ifdef __SSE4_2__\n#include \n#include \n#endif\n\n#include \"SparseAssemblyNative.h\"\n#include \"_det_inv_.h\"\n#include \"_matmul_.h\"\n\n#ifndef LL_TYPES\n#define LL_TYPES\nusing Real = double;\nusing Integer = std::int64_t;\nusing UInteger = std::uint64_t;\n#endif\n\n\n\n\n/*---------------------------------------------------------------------------------------------*/\n#ifndef CUSTOM_ALLOCATION_\n#define CUSTOM_ALLOCATION_\ntemplate\nFASTOR_INLINE T *allocate(Integer size) {\n#if defined(__AVX__)\n T *out = (T*)_mm_malloc(sizeof(T)*size,32);\n#elif defined(__SSE__)\n T *out = (T*)_mm_malloc(sizeof(T)*size,16);\n#else\n T *out = (T*)malloc(sizeof(T)*size);\n#endif\n return out;\n}\n\ntemplate\nFASTOR_INLINE void deallocate(T *a) {\n#if defined(__SSE__)\n _mm_free(a);\n#else\n free(a);\n#endif\n}\n#endif\n/*---------------------------------------------------------------------------------------------*/\n\n\n\n\n/*---------------------------------------------------------------------------------------------*/\n#ifndef SPARSE_TRIPLET_FILLER\n#define SPARSE_TRIPLET_FILLER\n// IJV Filler\nFASTOR_INLINE\nvoid fill_triplet( const Integer *i,\n const Integer *j,\n const Real *coeff,\n int *I,\n int *J,\n Real *V,\n Integer elem,\n Integer nvar,\n Integer nodeperelem,\n const UInteger *elements,\n Integer i_shape,\n Integer j_shape\n ) {\n\n Integer ndof = nvar*nodeperelem;\n Integer *current_row_column = allocate(nvar*nodeperelem);\n\n Integer const_elem_retriever;\n for (Integer counter=0; counter(nvar*local_size);\n Real *rhoNN = allocate(local_size*local_size);\n\n std::fill(N,N+nvar*local_size,0.);\n\n for (int igauss = 0; igauss < ngauss; ++igauss) {\n\n // Fill mass integrand\n for (int j=0; j(nodeperelem*ndim);\n Real *MaterialGradient = allocate(ndim*nodeperelem);\n // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG\n int plus1 = ndim == 2 ? 0 : 1;\n Real *ParentGradientX = allocate(ndim*ndim+plus1);\n Real detJ = 0.;\n Real *massel = allocate(local_capacity);\n Real *massel_lumped = allocate(ndof);\n\n\n // PRE-COMPUTE ISOPARAMETRIC GRADIENTS\n std::vector> current_Jms(ngauss);\n for (int g=0; g current_Jm(ndim*nodeperelem);\n for (int j=0; j;\n V2 _va, _vb, _vout;\n _vb.set(detJ);\n int Vsize = V2::Size;\n int ROUND_ = ROUND_DOWN(local_capacity,Vsize);\n int i=0;\n for (; i(nodeperelem*ndim);\n Real *MaterialGradient = allocate(ndim*nodeperelem);\n // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG\n int plus1 = ndim == 2 ? 0 : 1;\n Real *ParentGradientX = allocate(ndim*ndim+plus1);\n Real detJ = 0.;\n Real *massel = allocate(local_capacity);\n Real *symmetric_massel = allocate(symmetric_local_capacity);\n Real *massel_lumped = allocate(ndof);\n\n // PRE-COMPUTE SYMMETRIC PART OF CONSTANT MASS WITHOUT ZEROS\n Real *symmetric_constant_mass_integrand = allocate(ngauss*symmetric_local_capacity);\n Integer counter = 0;\n for (Integer igauss = 0; igauss < ngauss; ++igauss) {\n for (Integer i=0; i> current_Jms(ngauss);\n for (int g=0; g current_Jm(ndim*nodeperelem);\n for (int j=0; j;\n V2 _va, _vb, _vout;\n _vb.set(detJ);\n int Vsize = V2::Size;\n int ROUND_ = ROUND_DOWN(symmetric_local_capacity,Vsize);\n int i=0;\n for (; i(nodeperelem*ndim);\n Real *MaterialGradient = allocate(ndim*nodeperelem);\n // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG\n int plus1 = ndim == 2 ? 0 : 1;\n Real *ParentGradientX = allocate(ndim*ndim+plus1);\n Real detJ = 0.;\n Real *massel = allocate(local_capacity);\n Real *massel_lumped = allocate(ndof);\n\n // PRE-COMPUTE SPARSITY PATTERN OF THE LOCAL MATRIX -\n // LOCAL MASS MATRICES TYPICALLY HAVE LOTS OF NONZEROS\n constexpr Real tolerance = 1e-12;\n std::vector nonzero_i_indices, nonzero_j_indices;\n Integer counter = 0;\n for (Integer i=0; i tolerance) {\n nonzero_i_indices.push_back(i);\n nonzero_j_indices.push_back(j);\n }\n }\n }\n // PRE-COMPUTE SYMMETRIC PART OF CONSTANT MASS WITHOUT ZEROS\n const Integer symmetric_local_capacity = nonzero_i_indices.size();\n Real *symmetric_massel = allocate(symmetric_local_capacity);\n Real *symmetric_constant_mass_integrand = allocate(ngauss*symmetric_local_capacity);\n counter = 0;\n for (Integer igauss = 0; igauss < ngauss; ++igauss) {\n for (Integer i=0; i> current_Jms(ngauss);\n for (int g=0; g current_Jm(ndim*nodeperelem);\n for (int j=0; j;\n V2 _va, _vb, _vout;\n _vb.set(detJ);\n int Vsize = V2::Size;\n int ROUND_ = ROUND_DOWN(symmetric_local_capacity,Vsize);\n int i=0;\n for (; i(nodeperelem*ndim);\n Real *MaterialGradient = allocate(ndim*nodeperelem);\n // +1 TO AVOID OVERSTEPPONG IN MATMUL UNALIGNED STORE - EXTREMELY DANGEROUSE BUG\n int plus1 = ndim == 2 ? 0 : 1;\n Real *ParentGradientX = allocate(ndim*ndim+plus1);\n Real detJ = 0.;\n Real *massel = allocate(local_capacity);\n Real *massel_lumped = allocate(ndof);\n\n // PRE-COMPUTE SPARSITY PATTERN OF THE LOCAL MATRIX -\n // LOCAL MASS MATRICES TYPICALLY HAVE LOTS OF NONZEROS\n constexpr Real tolerance = 1e-12;\n std::vector nonzero_i_indices, nonzero_j_indices;\n Integer counter = 0;\n for (Integer i=0; i tolerance) {\n nonzero_i_indices.push_back(i);\n nonzero_j_indices.push_back(j);\n }\n }\n }\n // PRE-COMPUTE SYMMETRIC PART OF CONSTANT MASS WITHOUT ZEROS\n const Integer symmetric_local_capacity = nonzero_i_indices.size();\n Real *symmetric_massel = allocate(symmetric_local_capacity);\n Real *symmetric_constant_mass_integrand = allocate(ngauss*symmetric_local_capacity);\n counter = 0;\n for (Integer igauss = 0; igauss < ngauss; ++igauss) {\n for (Integer i=0; i> current_Jms(ngauss);\n for (int g=0; g current_Jm(ndim*nodeperelem);\n for (int j=0; j;\n V2 _va, _vb, _vout;\n _vb.set(detJ);\n int Vsize = V2::Size;\n int ROUND_ = ROUND_DOWN(symmetric_local_capacity,Vsize);\n int i=0;\n for (; i\n#include \n#include \n#include \n#include \n\n#include \n#if ( (PETSC_VERSION_MAJOR >= 3) && (PETSC_VERSION_MINOR >=3) )\n #if (PETSC_VERSION_MINOR >=6)\n #include \n #else\n #include \n #endif\n#else\n #include \n#endif\n\n\n#include \"common-driver-utils.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"Solvers/KSPSolvers/KSPSolvers.h\"\n#include \"petsccompat.h\"\n#include \"BSSCR.h\"\n#include \"stokes_block_scaling.h\"\n#include \"stokes_mvblock_scaling.h\"\n#include \"mg.h\"\n#include \"ksp_pressure_nullspace.h\"\n\ntypedef struct {\n int num_nsp_vecs;\n Vec *nsp_vecs;\n} nsp_data_t;\n\n\ntypedef struct {\n KSP kspA11;\n SLE_Solver *sleSolver;\n} WendyContext;\n\n\n//PetscErrorCode BSSCR_NSPRemoveAll(Vec v, void *_data);\n\nPetscErrorCode BSSCR_KSPNormInfMonitor( KSP ksp, PetscInt iteration, PetscReal residualNorm, void *dummy);\nPetscErrorCode BSSCR_KSPNormInfToNorm2Monitor( KSP ksp, PetscInt iteration, PetscReal residualNorm, void *dummy);\n\n\n\nPetscErrorCode BSSCR_DRIVER_flex( KSP ksp, Mat stokes_A, Vec stokes_x, Vec stokes_b, Mat approxS, KSP ksp_K,\n MatStokesBlockScaling BA, PetscTruth sym, KSP_BSSCR * bsscrp_self )\n{\n char name[PETSC_MAX_PATH_LEN];\n char ubefore[100];\n char uafter[100];\n char pbefore[100];\n char pafter[100];\n PetscTruth flg, flg2, truth, useAcceleratingSmoothingMG, useFancySmoothingMG;\n PetscTruth usePreviousGuess, useNormInfStoppingConditions, useNormInfMonitor, found, extractMats;\n Mat K,G,D,C;\n Vec u,p,f,h;\n Mat S;\n Vec h_hat,t,t2,q,v;\n\n KSP ksp_inner;\n KSP ksp_S;\n KSP ksp_cleaner;\n KSPType ksp_inner_type;\n\n PetscTruth has_cnst_nullspace;\n PC pc_S, pc_MG, pcInner;\n PetscInt monitor_index,max_it,min_it;\n Vec nsp_vec = PETSC_NULL;\n\n PetscReal scr_rtol;\n PetscReal inner_rtol;\n PetscReal vSolver_rtol;\n\n PetscScalar uNormInf, pNormInf;\n PetscScalar uNorm, pNorm, rNorm, fNorm;\n PetscInt uSize, pSize;\n PetscInt lmin,lmax;\n PetscInt iterations, rhs_iterations;\n PetscReal min,max;\n PetscReal p_sum;\n\n MGContext mgCtx;\n PC shellPC;\n\n double t0, t1;\n double mgSetupTime, rhsSolveTime, problemBuildTime, scrSolveTime, a11SingleSolveTime, solutionAnalysisTime;\n Index nx,ny,nz;\n PetscInt j,start,end;\n\n static int been_here = 0; /* Ha Ha Ha !! */\n\n /* get sub matrix / vector objects */\n MatNestGetSubMat( stokes_A, 0,0, &K );\n MatNestGetSubMat( stokes_A, 0,1, &G );\n MatNestGetSubMat( stokes_A, 1,0, &D );\n MatNestGetSubMat( stokes_A, 1,1, &C );\n\n VecNestGetSubVec( stokes_x, 0, &u );\n VecNestGetSubVec( stokes_x, 1, &p );\n\n VecNestGetSubVec( stokes_b, 0, &f );\n VecNestGetSubVec( stokes_b, 1, &h );\n\n /* PetscPrintf( PETSC_COMM_WORLD, \"\\t Adress of stokes_x is %p\\n\", stokes_x); */\n /* VecNorm( u, NORM_2, &uNorm ); */\n /* PetscPrintf( PETSC_COMM_WORLD, \"\\t u Norm is %.6e in %s: address is %p\\n\",uNorm,__func__,u); */\n /* VecNorm( p, NORM_2, &pNorm ); */\n /* PetscPrintf( PETSC_COMM_WORLD, \"\\t p Norm is %.6e in %s: addres is %p\\n\",pNorm,__func__,p); */\n /* Create Schur complement matrix */\n\n\n problemBuildTime = MPI_Wtime();\n\n\n //MatCreateSchurFromBlock( stokes_A, 0.0, \"MatSchur_A11\", &S );\n MatCreateSchurComplement(K,K,G,D,C, &S);\n /* configure inner solver */\n if (ksp_K!=PETSC_NULL) {\n MatSchurComplementSetKSP( S, ksp_K );\n MatSchurComplementGetKSP( S, &ksp_inner );\n }\n else {\n abort();\n MatSchurComplementGetKSP( S, &ksp_inner );\n KSPSetType( ksp_inner, \"cg\" );\n }\n KSPGetPC( ksp_inner, &pcInner );\n\n /* If we're using multigrid, replace the preconditioner here\n so we get the same options prefix. */\n\n if(bsscrp_self->mg) {\n mgSetupTime=setupMG( bsscrp_self, ksp_inner, pcInner, K, &mgCtx );\n }\n\n /* SETFROMOPTIONS MIGHT FUCK MG UP */\n KSPSetOptionsPrefix( ksp_inner, \"A11_\" );\n KSPSetFromOptions( ksp_inner );\n\n useNormInfStoppingConditions = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL ,\"-A11_use_norm_inf_stopping_condition\", &useNormInfStoppingConditions, &found );\n if(useNormInfStoppingConditions)\n BSSCR_KSPSetNormInfConvergenceTest( ksp_inner );\n\n useNormInfMonitor = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-A11_ksp_norm_inf_monitor\", &useNormInfMonitor, &found );\n if(useNormInfMonitor)\n KSPMonitorSet( ksp_inner, BSSCR_KSPNormInfMonitor, PETSC_NULL, PETSC_NULL );\n\n useNormInfMonitor = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-A11_ksp_norm_inf_to_norm_2_monitor\", &useNormInfMonitor, &found );\n if(useNormInfMonitor)\n KSPMonitorSet( ksp_inner, BSSCR_KSPNormInfToNorm2Monitor, PETSC_NULL, PETSC_NULL );\n\n /* create right hand side */\n /* h_hat = G'*inv(K)*f - h */\n\n MatGetVecs(K,PETSC_NULL,&t);\n MatGetVecs( S, PETSC_NULL, &h_hat );\n\n KSPSetOptionsPrefix( ksp_inner, \"A11_\" );\n KSPSetFromOptions( ksp_inner );\n\n problemBuildTime = MPI_Wtime() - problemBuildTime;\n\n rhsSolveTime = MPI_Wtime();\n KSPSolve(ksp_inner,f,t);/* t=f/K */\n rhsSolveTime = MPI_Wtime() - rhsSolveTime;\n KSPGetIterationNumber( ksp_inner, &rhs_iterations);\n\n //bsscr_writeVec( t, \"ts\", \"Writing t vector\");\n MatMult(D,t,h_hat);/* G'*t */\n VecAXPY(h_hat, -1.0, h);/* h_hat = h_hat - h */\n Stg_VecDestroy(&t);\n //bsscr_writeVec( h_hat, \"h_hat\", \"Writing h_hat Vector in Solver\");\n //MatSchurApplyReductionToVecFromBlock( S, stokes_b, h_hat );\n\n /* create solver for S p = h_hat */\n\n KSPCreate( PETSC_COMM_WORLD, &ksp_S );\n KSPSetOptionsPrefix( ksp_S, \"scr_\");\n Stg_KSPSetOperators( ksp_S, S,S, SAME_NONZERO_PATTERN );\n KSPSetType( ksp_S, \"cg\" );\n\n /* Build preconditioner for S */\n KSPGetPC( ksp_S, &pc_S );\n BSSCR_BSSCR_StokesCreatePCSchur2( K,G,D,C,approxS,pc_S,sym, bsscrp_self );\n\n KSPSetFromOptions(ksp_S);\n\n /* Set specific monitor test */\n KSPGetTolerances( ksp_S, PETSC_NULL, PETSC_NULL, PETSC_NULL, &max_it );\n //BSSCR_KSPLogSetMonitor( ksp_S, max_it, &monitor_index );\n\n /* Pressure / Velocity Solve */\n scrSolveTime = MPI_Wtime();\n // PetscPrintf( PETSC_COMM_WORLD, \"\\t* Pressure / Velocity Solve \\n\");\n\n usePreviousGuess = PETSC_FALSE;\n if(been_here)\n PetscOptionsGetTruth( PETSC_NULL, \"-scr_use_previous_guess\", &usePreviousGuess, &found );\n\n if(usePreviousGuess) { /* Note this should actually look at checkpoint information */\n KSPSetInitialGuessNonzero( ksp_S, PETSC_TRUE );\n }\n else {\n KSPSetInitialGuessNonzero( ksp_S, PETSC_FALSE );\n }\n\n //KSPSetRelativeRhsConvergenceTest( ksp_S );\n\n useNormInfStoppingConditions = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL ,\"-scr_use_norm_inf_stopping_condition\", &useNormInfStoppingConditions, &found );\n if(useNormInfStoppingConditions)\n BSSCR_KSPSetNormInfConvergenceTest(ksp_S);\n\n useNormInfMonitor = PETSC_FALSE;\n PetscOptionsGetTruth( PETSC_NULL, \"-scr_ksp_norm_inf_monitor\", &useNormInfMonitor, &found );\n if(useNormInfMonitor)\n KSPMonitorSet( ksp_S, BSSCR_KSPNormInfToNorm2Monitor, PETSC_NULL, PETSC_NULL );\n\n\n // PetscPrintf( PETSC_COMM_WORLD, \"\\t* KSPSolve( ksp_S, h_hat, p )\\n\");\n /* if h_hat needs to be fixed up ..take out any nullspace vectors here */\n /* we want to check that there is no \"noise\" in the null-space in the h vector */\n /* this causes problems when we are trying to solve a Jacobian system when the Residual is almost converged */\n\n if(bsscrp_self->check_pressureNS){\n bsscrp_self->buildPNS(ksp);/* build and set nullspace vectors on bsscr - which is on ksp (function pointer is set in KSPSetUp_BSSCR */\n }\n\n PetscScalar norm, a, a1, a2, hnorm, pnorm, gnorm;\n MatNorm(G,NORM_INFINITY,&gnorm);\n VecNorm(h_hat, NORM_2, &hnorm);\n hnorm=hnorm/gnorm;\n\n if((hnorm < 1e-6) && (hnorm > 1e-20)){\n VecScale(h_hat,1.0/hnorm);\n }\n /* test to see if v or t are in nullspace of G and orthogonalize wrt h_hat if needed */\n KSPRemovePressureNullspace_BSSCR(ksp, h_hat);\n /***************************************/\n /* set convergence test to use min_it */\n found = PETSC_FALSE;\n min_it = 0;\n PetscOptionsGetInt( PETSC_NULL,\"-scr_ksp_set_min_it_converge\", &min_it, &found);\n if(found && min_it > 0){\n BSSCR_KSPSetConvergenceMinIts(ksp_S, min_it, bsscrp_self);\n }\n KSPSolve( ksp_S, h_hat, p );\n sprintf(pafter,\"psafter_%d\",been_here);\n // bsscr_writeVec( p, pafter, \"Writing p Vector in Solver\");\n /***************************************/\n if((hnorm < 1e-6) && (hnorm > 1e-20)){\n VecScale(h_hat,hnorm);\n VecScale(p,hnorm);\n }\n KSPRemovePressureNullspace_BSSCR(ksp, p);\n\n\n scrSolveTime = MPI_Wtime() - scrSolveTime;\n // PetscPrintf( PETSC_COMM_WORLD, \" SCR Solve Finished in time: %lf seconds\\n\\n\", scrSolveTime);\n /* Resolve with this pressure to obtain solution for u */\n\n /* obtain solution for u */\n VecDuplicate( u, &t );\n MatMult( G, p, t);\n VecAYPX( t, -1.0, f ); /* t <- -t + f */\n MatSchurComplementGetKSP( S, &ksp_inner );\n\n\n a11SingleSolveTime = MPI_Wtime(); /* ---------------------------------- Final V Solve */\n\n if(usePreviousGuess)\n KSPSetInitialGuessNonzero( ksp_inner, PETSC_TRUE );\n\n KSPSetOptionsPrefix( ksp_inner, \"backsolveA11_\" );\n KSPSetFromOptions( ksp_inner );\n KSPSolve( ksp_inner, t, u ); /* Solve, then restore default tolerance and initial guess */\n\n\n a11SingleSolveTime = MPI_Wtime() - a11SingleSolveTime; /* ------------------ Final V Solve */\n\n\n PetscPrintf( PETSC_COMM_WORLD, \"SCR Solver Summary:\\n\\n\");\n\n if(bsscrp_self->mg)\n PetscPrintf( PETSC_COMM_WORLD, \" Multigrid setup: = %.4g secs \\n\", mgSetupTime);\n\n\n PetscPrintf( PETSC_COMM_WORLD, \" RHS / Pre Solve: = %.4g secs / %d its\\n\", rhsSolveTime, rhs_iterations);\n KSPGetIterationNumber( ksp_S, &iterations);\n PetscPrintf( PETSC_COMM_WORLD, \" Pressure Solve: = %.4g secs / %d its\\n\", scrSolveTime, iterations);\n KSPGetIterationNumber( ksp_inner, &iterations);\n PetscPrintf( PETSC_COMM_WORLD, \" Final V Solve: = %.4g secs / %d its\\n\\n\", a11SingleSolveTime, iterations);\n\n /* Analysis of solution:\n This can be somewhat time consuming as it requires allocation / de-allocation,\n computing vector norms etc. So we make it optional..\n This should be put into a proper KSP monitor now?\n */\n flg = PETSC_TRUE;\n PetscOptionsGetTruth( PETSC_NULL, \"-scr_ksp_solution_summary\", &flg, &found );\n\n if(flg) {\n\n solutionAnalysisTime = MPI_Wtime();\n\n VecGetSize( u, &uSize );\n VecGetSize( p, &pSize );\n\n VecDuplicate( u, &t2 );\n MatMult( K, u, t2);\n VecAYPX( t2, -1.0, t ); /* t2 <- -t2 + t ... should be the formal residual vector */\n\n VecNorm( t2, NORM_2, &rNorm );\n VecNorm( f, NORM_2, &fNorm );\n\n PetscPrintf( PETSC_COMM_WORLD, \" |f - K u - G p|/|f| = %.6e\\n\", rNorm/fNorm );\n\n VecDuplicate( p, &q );\n MatMult( D, u, q );\n VecNorm( u, NORM_2, &uNorm );\n VecNorm( q, NORM_2, &rNorm );\n\n PetscPrintf( PETSC_COMM_WORLD, \" |G^T u|_2/|u|_2 = %.6e\\n\", sqrt( (double) uSize / (double) pSize ) * rNorm / uNorm);\n\n VecNorm( q, NORM_INFINITY, &rNorm );\n\n PetscPrintf( PETSC_COMM_WORLD, \" |G^T u|_infty/|u|_2 = %.6e\\n\", sqrt( (double) uSize ) * rNorm / uNorm);\n\n VecNorm( u, NORM_INFINITY, &uNormInf );\n VecNorm( u, NORM_2, &uNorm );\n VecGetSize( u, &uSize );\n\n VecNorm( p, NORM_INFINITY, &pNormInf );\n VecNorm( p, NORM_2, &pNorm );\n\n PetscPrintf( PETSC_COMM_WORLD, \" |u|_{\\\\infty} = %.6e , u_rms = %.6e\\n\",\n uNormInf, uNorm / sqrt( (double) uSize ) );\n\n PetscPrintf( PETSC_COMM_WORLD, \" |p|_{\\\\infty} = %.6e , p_rms = %.6e\\n\",\n pNormInf, pNorm / sqrt( (double) pSize ) );\n\n VecMax( u, &lmax, &max );\n VecMin( u, &lmin, &min );\n PetscPrintf( PETSC_COMM_WORLD, \" min/max(u) = %.6e [%d] / %.6e [%d]\\n\",min,lmin,max,lmax);\n\n VecMax( p, &lmax, &max );\n VecMin( p, &lmin, &min );\n PetscPrintf( PETSC_COMM_WORLD, \" min/max(p) = %.6e [%d] / %.6e [%d]\\n\",min,lmin,max,lmax);\n\n VecSum( p, &p_sum );\n PetscPrintf( PETSC_COMM_WORLD, \" \\\\sum_i p_i = %.6e \\n\", p_sum );\n\n solutionAnalysisTime = MPI_Wtime() - solutionAnalysisTime;\n\n PetscPrintf( PETSC_COMM_WORLD, \"\\n Time for this analysis = %.4g secs\\n\\n\",solutionAnalysisTime);\n\n Stg_VecDestroy(&t2 );\n Stg_VecDestroy(&q );\n\n }\n\n if(bsscrp_self->mg) {\n //MG_inner_solver_pcmg_shutdown( pcInner );\n }\n\n Stg_VecDestroy(&t );\n\n\n// KSPLogDestroyMonitor( ksp_S );\n\n Stg_KSPDestroy(&ksp_S );\n //Stg_KSPDestroy(&ksp_inner );\n Stg_VecDestroy(&h_hat );\n Stg_MatDestroy(&S );\n\n /* Destroy nullspace vector if it exists. */\n if(nsp_vec)\n Stg_VecDestroy(&nsp_vec);\n\n //been_here = 1;\n been_here++;\n PetscFunctionReturn(0);\n}\n\n\n\n/*\n A pointwise stopping condition (infinity norm)\n\n To activate this stopping condition, I add this piece of code somewhere before the call to KSPSolve().\n\n {\n PetscTruth pw,flg;\n pw = PETSC_FALSE;\n PetscOptionsGetTruth(0,\"-pointwise_stopping_condition\", &pw,&flg);\n if(pw==PETSC_TRUE) { KSPSetPointwiseConvergenceTest(ksp_T); }\n }\n\n You can activate a monitor for the max pointwise residual by using the cmd line option\n -XXX_ksp_pointwise_monitor\n where XXX is the solver prefix specified by the call KSPSetOptionsPrefix().\n\n DAM\n*/\n\n\n\ntypedef struct {\n PetscTruth initialrtol; /* default relative residual decrease is computing from initial residual, not rhs */\n PetscTruth mininitialrtol; /* default relative residual decrease is computing from min of initial residual and rhs */\n Vec work;\n PetscReal pointwise_max;\n} KSPPWConvergedCtx;\n\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPPWConvergedCreate\"\nPetscErrorCode BSSCR_KSPPWConvergedCreate(void **ctx)\n{\n PetscErrorCode ierr;\n KSPPWConvergedCtx *cctx;\n\n PetscFunctionBegin;\n ierr = Stg_PetscNew(KSPPWConvergedCtx,&cctx);CHKERRQ(ierr);\n *ctx = cctx;\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPPWConvergedDestroy\"\nPetscErrorCode BSSCR_KSPPWConvergedDestroy(void *ctx)\n{\n PetscErrorCode ierr;\n KSPPWConvergedCtx *cctx = (KSPPWConvergedCtx*) ctx;\n\n PetscFunctionBegin;\n if (cctx->work) {ierr = Stg_VecDestroy(&cctx->work);CHKERRQ(ierr);}\n ierr = PetscFree(cctx);CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPNormInfConverged\"\nPetscErrorCode BSSCR_KSPNormInfConverged(KSP ksp,PetscInt n,PetscReal rnorm,KSPConvergedReason *reason,void *ctx)\n{\n PetscErrorCode ierr;\n KSPPWConvergedCtx *cctx = (KSPPWConvergedCtx*)ctx;\n KSPNormType normtype;\n PetscReal min, max, R_max, R_min, R_Ninf;\n Vec R, work, w1,w2;\n\n PetscFunctionBegin;\n PetscValidHeaderSpecific(ksp,KSP_COOKIE,1);\n PetscValidPointer(reason,4);\n *reason = KSP_CONVERGED_ITERATING;\n\n ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);\n\n KSPBuildResidual( ksp, w1,w2, &R );\n VecNorm( R, NORM_INFINITY, &R_Ninf );\n\n //PetscPrintf( PETSC_COMM_WORLD, \"Norm inf convergence %s\\n \", ksp->prefix);\n\n cctx->pointwise_max = R_Ninf;\n\n ierr = KSPGetNormType(ksp,&normtype);\n\n CHKERRQ(ierr);\n if (normtype == KSP_NORM_NO)\n Stg_SETERRQ(PETSC_ERR_ARG_WRONGSTATE,\"Use BSSCR_KSPSkipConverged() with KSPNormType of KSP_NORM_NO\");\n\n if (!cctx)\n Stg_SETERRQ(PETSC_ERR_ARG_NULL,\"Convergence context must have been created with BSSCR_KSPDefaultConvergedCreate()\");\n\n if (!n) {\n /* if user gives initial guess need to compute norm of b */\n if (!ksp->guess_zero && !cctx->initialrtol) {\n PetscReal snorm;\n if (ksp->normtype == KSP_NORM_UNPRECONDITIONED || ksp->pc_side == PC_RIGHT) {\n ierr = PetscInfo(ksp,\"user has provided nonzero initial guess, computing 2-norm of RHS\\n\");\n CHKERRQ(ierr);\n ierr = VecNorm(ksp->vec_rhs,NORM_INFINITY,&snorm);CHKERRQ(ierr); /* <- b'*b */\n\n PetscPrintf( PETSC_COMM_WORLD, \"Non Zero Guess; RHS - %g\\n\", snorm);\n\n }\n else {\n Vec z;\n if (!cctx->work) {\n ierr = VecDuplicate(ksp->vec_rhs,&cctx->work);CHKERRQ(ierr);\n }\n z = cctx->work;\n ierr = KSP_PCApply(ksp,ksp->vec_rhs,z);CHKERRQ(ierr);\n if (ksp->normtype == KSP_NORM_PRECONDITIONED) {\n ierr = PetscInfo(ksp,\"user has provided nonzero initial guess, computing 2-norm of preconditioned RHS\\n\");CHKERRQ(ierr);\n ierr = VecNorm(z,NORM_INFINITY,&snorm);CHKERRQ(ierr); /* dp <- b'*B'*B*b */\n\n }\n else if (ksp->normtype == KSP_NORM_NATURAL) {\n PetscScalar norm;\n Vec bz;\n ierr = PetscInfo(ksp,\"user has provided nonzero initial guess, computing natural norm of RHS\\n\");CHKERRQ(ierr);\n // ierr = VecDot(ksp->vec_rhs,z,&norm);\n // snorm = sqrt(PetscAbsScalar(norm)); /* dp <- b'*B*b */\n VecDuplicate( z, &bz );\n VecPointwiseMult( bz, ksp->vec_rhs, z );\n ierr = VecNorm(bz,NORM_INFINITY,&snorm);CHKERRQ(ierr);\n Stg_VecDestroy(&bz);\n }\n }\n /* handle special case of zero RHS and nonzero guess */\n if (!snorm) {\n ierr = PetscInfo(ksp,\"Special case, user has provided nonzero initial guess and zero RHS\\n\");CHKERRQ(ierr);\n snorm = rnorm;\n }\n if (cctx->mininitialrtol) {\n ksp->rnorm0 = PetscMin(snorm,rnorm);\n } else {\n ksp->rnorm0 = snorm;\n }\n } else {\n ksp->rnorm0 = rnorm;\n }\n ksp->ttol = PetscMax(ksp->rtol*ksp->rnorm0,ksp->abstol);\n }\n\n // if (n <= ksp->chknorm) PetscFunctionReturn(0);\n\n if ( R_Ninf != R_Ninf ) {\n ierr = PetscInfo(ksp,\"Linear solver has created a not a number (NaN) as the pointwise residual norm, declaring divergence \\n\");CHKERRQ(ierr);\n *reason = KSP_DIVERGED_NAN;\n }\n else\n if (R_Ninf <= ksp->ttol) {\n if (R_Ninf < ksp->abstol) {\n ierr = PetscInfo3(ksp,\"Linear solver has converged. Pointwise residual %G is less than absolute tolerance %G at iteration %D\\n\",R_Ninf,ksp->abstol,n);\n CHKERRQ(ierr);\n *reason = KSP_CONVERGED_ATOL;\n }\n else {\n if (cctx->initialrtol) {\n ierr = PetscInfo4(ksp,\"Linear solver has converged. Norm_infinity %G is less than relative tolerance %G times initial Norm_infinity %G at iteration %D\\n\",R_Ninf,ksp->rtol,ksp->rnorm0,n);\n CHKERRQ(ierr);\n }\n else {\n ierr = PetscInfo4(ksp,\"Linear solver has converged. Norm_infinity %G is less than relative tolerance %G times initial norm_infinity right hand side %G at iteration %D\\n\",R_Ninf,ksp->rtol,ksp->rnorm0,n);CHKERRQ(ierr);\n }\n *reason = KSP_CONVERGED_RTOL;\n }\n }\n else\n if (R_Ninf >= ksp->divtol*ksp->rnorm0) {\n ierr = PetscInfo3(ksp,\"Linear solver is diverging. Initial right hand size Norm_infinity value %G, current residual norm %G at iteration %D\\n\",ksp->rnorm0,R_Ninf,n);CHKERRQ(ierr);\n *reason = KSP_DIVERGED_DTOL;\n }\n\n /* trash all work vectors here */\n\n Stg_VecDestroy(&work);\n Stg_VecDestroy(&w1);\n Stg_VecDestroy(&w2);\n\n PetscFunctionReturn(0);\n}\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPNormInfToNorm2Monitor\"\nPetscErrorCode BSSCR_KSPNormInfToNorm2Monitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy)\n{\n PetscErrorCode ierr;\n PetscViewerASCIIMonitor viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(((PetscObject)ksp)->comm);\n PetscReal R_normInf, R_norm2;\n PetscInt R_size;\n Vec R, work, w1, w2;\n\n PetscFunctionBegin;\n\n ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);\n\n KSPBuildResidual( ksp, w1,w2, &R );\n\n VecNorm( R, NORM_INFINITY, &R_normInf );\n VecNorm( R, NORM_2, &R_norm2 );\n VecGetSize( R, &R_size );\n\n ierr = PetscViewerASCIIMonitorCreate(((PetscObject)ksp)->comm,\"stdout\",0,&viewer); CHKERRQ(ierr);\n\n if(R_norm2 == 0.0) {\n ierr = PetscViewerASCIIMonitorPrintf(viewer,\"%3D KSP Residual Spikiness - INFINITY (%s) \\n\",\n n, ((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: \"\" );\n CHKERRQ(ierr);\n }\n else{\n ierr = PetscViewerASCIIMonitorPrintf(viewer,\"%3D KSP Residual Spikiness %14.12e (%s) Max / Rms \\n\",\n n, sqrt((double) R_size) * R_normInf / R_norm2,\n ((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: \"\");\n CHKERRQ(ierr);\n }\n\n ierr = PetscViewerASCIIMonitorDestroy(viewer);\n CHKERRQ(ierr);\n\n Stg_VecDestroy(&work);\n Stg_VecDestroy(&w1);\n Stg_VecDestroy(&w2);\n\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPNormInfMonitor\"\nPetscErrorCode BSSCR_KSPNormInfMonitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy)\n{\n PetscErrorCode ierr;\n PetscViewerASCIIMonitor viewer;\n PetscReal R_normInf;\n Vec R, work, w1,w2;\n\n PetscFunctionBegin;\n\n ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);\n\n\n KSPBuildResidual( ksp, w1,w2, &R );\n VecNorm( R, NORM_INFINITY, &R_normInf );\n\n ierr = PetscViewerASCIIMonitorCreate(((PetscObject)ksp)->comm,\"stdout\",0,&viewer);\n CHKERRQ(ierr);\n\n ierr = PetscViewerASCIIMonitorPrintf(viewer,\"%3D KSP Residual Ninf %14.12e (%s) \\n\",\n n, R_normInf,\n ((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: \"\");\n CHKERRQ(ierr);\n\n ierr = PetscViewerASCIIMonitorDestroy(viewer);\n CHKERRQ(ierr);\n\n Stg_VecDestroy(&work);\n Stg_VecDestroy(&w1);\n Stg_VecDestroy(&w2);\n\n PetscFunctionReturn(0);\n}\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPNorm2RawMonitor\"\nPetscErrorCode BSSCR_KSPNorm2RawMonitor(KSP ksp,PetscInt n,PetscReal rnorm, void *dummy)\n{\n PetscErrorCode ierr;\n PetscViewerASCIIMonitor viewer;\n PetscReal R_norm2;\n Vec R, work, w1,w2;\n\n PetscFunctionBegin;\n\n ierr = VecDuplicate(ksp->vec_rhs,&work);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w1);CHKERRQ(ierr);\n ierr = VecDuplicate(ksp->vec_rhs,&w2);CHKERRQ(ierr);\n\n\n KSPBuildResidual( ksp, w1,w2, &R );\n VecNorm( R, NORM_2, &R_norm2 );\n\n ierr = PetscViewerASCIIMonitorCreate(((PetscObject)ksp)->comm,\"stdout\",0,&viewer);\n CHKERRQ(ierr);\n\n ierr = PetscViewerASCIIMonitorPrintf(viewer,\"%3D KSP Residual Norm2raw %14.12e (%s) \\n\",\n n, R_norm2,\n ((PetscObject)ksp)->prefix ? ((PetscObject)ksp)->prefix: \"\");\n CHKERRQ(ierr);\n\n ierr = PetscViewerASCIIMonitorDestroy(viewer);\n CHKERRQ(ierr);\n\n Stg_VecDestroy(&work);\n Stg_VecDestroy(&w1);\n Stg_VecDestroy(&w2);\n\n PetscFunctionReturn(0);\n}\n\n\n\n\n#undef __FUNCT__\n#define __FUNCT__ \"BSSCR_KSPSetNormInfConvergenceTest\"\nPetscErrorCode BSSCR_KSPSetNormInfConvergenceTest(KSP ksp)\n{\n KSPPWConvergedCtx *ctx;\n PetscTruth monitor, flg;\n char *opt;\n const char *prefix;\n\n BSSCR_KSPPWConvergedCreate( (void**)&ctx );\n KSPGetOptionsPrefix( ksp, &prefix );\n\n#if(PETSC_VERSION_MAJOR == 3)\n KSPSetConvergenceTest( ksp, BSSCR_KSPNormInfConverged, ctx, BSSCR_KSPPWConvergedDestroy ); // 3.0.0 only\n#else\n KSPSetConvergenceTest( ksp, BSSCR_KSPNormInfConverged, ctx ); // 2.3.3\n#endif\n\n PetscFunctionReturn(0);\n}\n", "meta": {"hexsha": "56d1e4784399dfc4b5544d0677d08e90abd9e2f8", "size": 25836, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/bsscr-driver.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/bsscr-driver.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/bsscr-driver.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": 35.1989100817, "max_line_length": 236, "alphanum_fraction": 0.6177813903, "num_tokens": 7682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.399811640739795, "lm_q1q2_score": 0.22476470920450775}} {"text": "/*\nBallistic: a software to benchmam 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 runge-kutta.c\n * \\brief Source file to define the numerical method data and functions.\n * \\author Javier Burguete Tolosa.\n * \\copyright Copyright 2018.\n */\n#define _GNU_SOURCE\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"config.h\"\n#include \"utils.h\"\n#include \"equation.h\"\n#include \"method.h\"\n\n#define DEBUG_METHOD 0\n///< macro to debug the numerical method functions.\n\n/**\n * Function to init the numerical method.\n */\nvoid\nmethod_init (Method * m, ///< Method struct.\n unsigned int nsteps, ///< number of steps.\n unsigned int order) ///< order of accuracy.\n{\n#if DEBUG_METHOD\n fprintf (stderr, \"method_init: start\\n\");\n#endif\n m->nsteps = nsteps;\n m->order = order;\n#if DEBUG_METHOD\n fprintf (stderr, \"method_init: end\\n\");\n#endif\n}\n\n/**\n * Function to init the variables of the numerical method.\n */\nvoid\nmethod_init_variables (Method * m) ///< Method struct.\n{\n unsigned int i, n;\n#if DEBUG_METHOD\n fprintf (stderr, \"method_init_variables: start\\n\");\n fprintf (stderr, \"method_init_variables: nsteps=%u\\n\", m->nsteps);\n#endif\n n = m->nsteps + 1;\n m->r0 = (long double **) g_slice_alloc (n * sizeof (long double *));\n m->r1 = (long double **) g_slice_alloc (n * sizeof (long double *));\n m->r2 = (long double **) g_slice_alloc (n * sizeof (long double *));\n for (i = 0; i < n; ++i)\n {\n m->r0[i] = (long double *) g_slice_alloc (3 * sizeof (long double));\n m->r1[i] = (long double *) g_slice_alloc (3 * sizeof (long double));\n m->r2[i] = (long double *) g_slice_alloc (3 * sizeof (long double));\n }\n m->et0 = m->et1 = 0.L;\n#if DEBUG_METHOD\n fprintf (stderr, \"method_init_variables: end\\n\");\n#endif\n}\n\n/**\n * Function to calculate the following numerical step size based on error\n * control.\n *\n * \\return next time step size.\n */\nlong double\nmethod_dt (Method * m, ///< Method struct.\n long double dt) ///< actual time step size.\n{\n long double dt2;\n#if DEBUG_METHOD\n fprintf (stderr, \"method_dt: start\\n\");\n#endif\n dt2 = dt * fminl (m->alpha,\n powl (m->emt * dt / m->e0, 1.L / (m->order - 1.L)));\n#if DEBUG_METHOD\n fprintf (stderr, \"method_dt: dt=%Lg\\n\", dt2);\n fprintf (stderr, \"method_dt: end\\n\");\n#endif\n return dt2;\n}\n\n/**\n * Function to free the memory used by the Method struct.\n */\nvoid\nmethod_delete (Method * m) ///< Method struct.\n{\n unsigned int i, n;\n#if DEBUG_METHOD\n fprintf (stderr, \"method_delete: start\\n\");\n fprintf (stderr, \"method_delete: nsteps=%u\\n\", m->nsteps);\n#endif\n n = i = m->nsteps + 1;\n do\n {\n --i;\n g_slice_free1 (3 * sizeof (long double), m->r2[i]);\n g_slice_free1 (3 * sizeof (long double), m->r1[i]);\n g_slice_free1 (3 * sizeof (long double), m->r0[i]);\n }\n while (i);\n g_slice_free1 (n * sizeof (long double *), m->r2);\n g_slice_free1 (n * sizeof (long double *), m->r1);\n g_slice_free1 (n * sizeof (long double *), m->r0);\n#if DEBUG_METHOD\n fprintf (stderr, \"method_delete: end\\n\");\n#endif\n}\n\n/**\n * Function to read the numerical method data on a XML node.\n *\n * \\return 1 on success, 0 on error.\n */\nint\nmethod_read_xml (Method * m, ///< Method struct.\n xmlNode * node) ///< XML node.\n{\n const char *message[] = {\n \"Bad dt\",\n \"Bad alpha\",\n \"Bad beta\",\n \"Bad error per time\",\n \"Unknown error control type\"\n };\n int e, error_code;\n#if DEBUG_METHOD\n fprintf (stderr, \"method_read_xml: start\\n\");\n#endif\n m->error_dt = xml_node_get_uint (node, XML_TIME_STEP, &error_code);\n if (error_code)\n {\n e = 0;\n goto fail;\n }\n switch (m->error_dt)\n {\n case 0:\n m->emt = 0.L;\n break;\n case 1:\n m->alpha = xml_node_get_float (node, XML_ALPHA, &error_code);\n if (error_code)\n {\n e = 1;\n goto fail;\n }\n m->beta = xml_node_get_float (node, XML_BETA, &error_code);\n if (error_code)\n {\n e = 2;\n goto fail;\n }\n m->emt = xml_node_get_float (node, XML_ERROR_TIME, &error_code);\n if (error_code)\n {\n e = 3;\n goto fail;\n }\n break;\n default:\n e = 4;\n goto fail;\n }\n#if DEBUG_METHOD\n fprintf (stderr, \"method_read_xml: success\\n\");\n fprintf (stderr, \"method_read_xml: end\\n\");\n#endif\n return 1;\n\nfail:\n error_add (message[e]);\n#if DEBUG_METHOD\n fprintf (stderr, \"method_read_xml: error\\n\");\n fprintf (stderr, \"method_read_xml: end\\n\");\n#endif\n return 0;\n}\n", "meta": {"hexsha": "816e5e026cab0d5cc6bad18e759d4a895aa24494", "size": 5934, "ext": "c", "lang": "C", "max_stars_repo_path": "1.1.0/method.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/method.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/method.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": 27.3456221198, "max_line_length": 80, "alphanum_fraction": 0.6454330974, "num_tokens": 1586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5312093733737563, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.22241572285236275}} {"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\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 Hsml;\n int NodeList[NODELISTLENGTH];\n}\n *DensDataIn, *DensDataGet;\n\n\nstatic struct densdata_out\n{\n MyFloat Rho;\n MyFloat VelDisp, Vx, Vy, Vz;\n int Ngb;\n}\n *DensDataResult, *DensDataOut;\n\n\nstatic MyFloat *DM_Vx, *DM_Vy, *DM_Vz;\nstatic long long Ntotal;\n\n#ifdef DENSITY_SPLIT_BY_TYPE\nvoid subfind_density(int j_in)\n#else\nvoid subfind_density(void)\n#endif\n{\n long long ntot;\n int i, j, ndone, ndone_flag, npleft, dummy, iter = 0;\n MyFloat *Left, *Right;\n char *Todo;\n int ngrp, sendTask, recvTask, place, nexport, nimport;\n double vel_to_phys, dmax1, dmax2, t0, t1;\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n int j_target;\n\n if(j_in < 0)\n j_target = -j_in - 1;\n else\n j_target = j_in;\n#endif\n\n if(ThisTask == 0)\n {\n#ifdef DENSITY_SPLIT_BY_TYPE\n printf(\"finding densities, mode %d \\n\", j_in);\n#else\n printf(\"finding densities for all particles\\n\");\n#endif\n fflush(stdout);\n }\n\n /* allocate buffers to arrange communication */\n\n Ngblist = (int *) mymalloc(NumPart * sizeof(int));\n Dist2list = (double *) mymalloc(NumPart * sizeof(double));\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 Left = mymalloc(sizeof(MyFloat) * NumPart);\n Right = mymalloc(sizeof(MyFloat) * NumPart);\n Todo = mymalloc(sizeof(char) * NumPart);\n\n DM_Vx = mymalloc(sizeof(MyFloat) * NumPart);\n DM_Vy = mymalloc(sizeof(MyFloat) * NumPart);\n DM_Vz = mymalloc(sizeof(MyFloat) * NumPart);\n\n for(i = 0; i < NumPart; i++)\n {\n Left[i] = Right[i] = 0;\n P[i].DM_NumNgb = 0;\n Todo[i] = 1;\n }\n\n /* we will repeat the whole thing for those particles where we didn't find enough neighbours */\n do\n {\n t0 = second();\n\n i = 0;\t\t\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\n\t for(nexport = 0; i < NumPart; i++)\n\t {\n\t if(Todo[i])\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t\tif(P[i].Type == j_target)\n\t\t {\n\t\t if(subfind_density_evaluate(i, 0, &nexport, Send_count, j_in) < 0)\n\t\t break;\n\t\t }\n#else\n\t\tif(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))\n\t\t {\n\t\t if(subfind_density_evaluate(i, 0, &nexport, Send_count) < 0)\n\t\t break;\n\t\t }\n#endif\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 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 = P[place].DM_Hsml;\n\n\t memcpy(DensDataIn[j].NodeList,\n\t\t DataNodeList[DataIndexTable[j].IndexGet].NodeList, NODELISTLENGTH * sizeof(int));\n\t }\n\n\t /* exchange particle 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 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\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\t for(j = 0; j < nimport; j++)\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t subfind_density_evaluate(j, 1, &dummy, &dummy, j_in);\n#else\n\t subfind_density_evaluate(j, 1, &dummy, &dummy);\n#endif\n\t if(i >= NumPart)\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(&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\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 P[place].DM_NumNgb += DensDataOut[j].Ngb;\n\t P[place].u.DM_Density += DensDataOut[j].Rho;\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(j_in >= 0)\t/* sum up VelDisp only for own species */\n#endif\n\t\tP[place].v.DM_VelDisp += DensDataOut[j].VelDisp;\n\t DM_Vx[place] += DensDataOut[j].Vx;\n\t DM_Vy[place] += DensDataOut[j].Vy;\n\t DM_Vz[place] += DensDataOut[j].Vz;\n\t }\n\n\t myfree(DensDataOut);\n\t myfree(DensDataResult);\n\t myfree(DensDataGet);\n\t}\n while(ndone < NTask);\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(ThisTask == 0)\n\tprintf(\"checking smoothing lenghs ... \\n\");\n#endif\n\n /* do final operations on results */\n for(i = 0, npleft = 0; i < NumPart; i++)\n\t{\n\t /* now check whether we had enough neighbours */\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(j_in < 0)\n\t Todo[i] = 0;\n\t if((P[i].Type != j_target) || (j_in < 0))\n\t continue;\n#else\n\t if(!((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))\n\t continue;\n#endif\n\n\t if(Todo[i])\n\t {\n\t if(P[i].DM_NumNgb != All.DesNumNgb &&\n\t\t ((Right[i] - Left[i]) > 1.0e-4 * Left[i] || Left[i] == 0 || Right[i] == 0))\n\t\t{\n\t\t /* need to redo this particle */\n\t\t npleft++;\n\n\t\t if(P[i].DM_NumNgb < All.DesNumNgb)\n\t\t Left[i] = DMAX(P[i].DM_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(P[i].DM_Hsml < Right[i])\n\t\t\t Right[i] = P[i].DM_Hsml;\n\t\t\t}\n\t\t else\n\t\t\tRight[i] = P[i].DM_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, P[i].DM_Hsml, Left[i], Right[i],\n\t\t\t (double) P[i].DM_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 P[i].DM_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(8187);\t/* can't occur */\n\n\t\t if(Right[i] == 0 && Left[i] > 0)\n\t\t\tP[i].DM_Hsml *= 1.26;\n\n\t\t if(Right[i] > 0 && Left[i] == 0)\n\t\t\tP[i].DM_Hsml /= 1.26;\n\t\t }\n\t\t}\n\t else\n\t\tTodo[i] = 0;\n\t }\n\t}\n\n sumup_large_ints(1, &npleft, &ntot);\n\n t1 = second();\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. (took %g sec)\\n\", iter,\n\t\t (int) (ntot / 1000000000), (int) (ntot % 1000000000), timediff(t0, t1));\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 vel_to_phys = 1.0 / All.Time;\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(ThisTask == 0)\n printf(\"final operations ... \\n\");\n#endif\n\n for(i = 0; i < NumPart; i++)\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(P[i].Type == j_target && j_in >= 0)\n#else\n if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))\n#endif\n {\n#ifdef DENSITY_SPLIT_BY_TYPE\n\tif(P[i].DM_NumNgb == 0)\n\t endrun(5621);\n#endif\n\tDM_Vx[i] /= P[i].DM_NumNgb;\n\tDM_Vy[i] /= P[i].DM_NumNgb;\n\tDM_Vz[i] /= P[i].DM_NumNgb;\n\tP[i].v.DM_VelDisp /= P[i].DM_NumNgb;\n\n\tP[i].v.DM_VelDisp = vel_to_phys * sqrt(P[i].v.DM_VelDisp -\n\t\t\t\t\t DM_Vx[i] * DM_Vx[i] -\n\t\t\t\t\t DM_Vy[i] * DM_Vy[i] - DM_Vz[i] * DM_Vz[i]);\n }\n\n myfree(DM_Vz);\n myfree(DM_Vy);\n myfree(DM_Vx);\n\n myfree(Todo);\n myfree(Right);\n myfree(Left);\n\n myfree(DataNodeList);\n myfree(DataIndexTable);\n\n myfree(Dist2list);\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 */\n#ifdef DENSITY_SPLIT_BY_TYPE\nint subfind_density_evaluate(int target, int mode, int *nexport, int *nsend_local, int tp)\n#else\nint subfind_density_evaluate(int target, int mode, int *nexport, int *nsend_local)\n#endif\n{\n int j, n;\n int startnode, numngb, ngb, listindex = 0;\n double hmax;\n double h, h2, hinv, hinv3;\n double rho, wk;\n double r, r2, u, mass_j, v2, vx, vy, vz;\n MyDouble *pos;\n\n rho = 0;\n numngb = 0;\n v2 = vx = vy = vz = 0;\n\n if(mode == 0)\n {\n pos = P[target].Pos;\n h = P[target].DM_Hsml;\n }\n else\n {\n pos = DensDataGet[target].Pos;\n h = DensDataGet[target].Hsml;\n }\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(h == 0)\n endrun(5622);\n#endif\n\n h2 = h * h;\n hinv = 1.0 / h;\n hinv3 = hinv * hinv * 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 DENSITY_SPLIT_BY_TYPE\n\t if(tp < 0)\n\t ngb =\n\t subfind_ngb_treefind_linkpairs(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local);\n\t else\n\t ngb = subfind_ngb_treefind_linkngb(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local);\n#else\n\t ngb = subfind_ngb_treefind_linkngb(pos, h, target, &startnode, mode, &hmax, nexport, nsend_local);\n#endif\n\t if(ngb < 0)\n\t return -1;\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(tp >= 0)\n#endif\n\t if(mode == 0 && hmax > 0)\n\t {\n\t\tP[target].DM_Hsml = hmax;\n\t\th = hmax;\n\t\th2 = h * h;\n\t\thinv = 1.0 / h;\n\t\thinv3 = hinv * hinv * hinv;\n\n\t\tif(ngb != All.DesNumNgb)\n\t\t endrun(121);\n\t }\n\n\t numngb += ngb;\n\n\t for(n = 0; n < ngb; n++)\n\t {\n\t j = Ngblist[n];\n\n\t r2 = Dist2list[n];\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(tp < 0)\n\t\t{\n\t\t h = P[j].DM_Hsml;\n\t\t if(h == 0)\n\t\t endrun(5622);\n\t\t h2 = h * h;\n\t\t hinv = 1.0 / h;\n\t\t hinv3 = hinv * hinv * hinv;\n\t\t}\n#endif\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 wk = hinv3 * (KERNEL_COEFF_1 + KERNEL_COEFF_2 * (u - 1) * u * u);\n\t\t else\n\t\t wk = hinv3 * KERNEL_COEFF_5 * (1.0 - u) * (1.0 - u) * (1.0 - u);\n\n\t\t mass_j = P[j].Mass;\n\n\t\t rho += (mass_j * wk);\n\t\t}\n\n\t vx += P[j].Vel[0];\n\t vy += P[j].Vel[1];\n\t vz += P[j].Vel[2];\n\n\t v2 += P[j].Vel[0] * P[j].Vel[0] + P[j].Vel[1] * P[j].Vel[1] + P[j].Vel[2] * P[j].Vel[2];\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 P[target].DM_NumNgb = numngb;\n P[target].u.DM_Density = rho;\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(tp >= 0)\t\t/* sum up VelDisp only for own species */\n#endif\n\tP[target].v.DM_VelDisp = v2;\n DM_Vx[target] = vx;\n DM_Vy[target] = vy;\n DM_Vz[target] = vz;\n }\n else\n {\n DensDataResult[target].Ngb = numngb;\n DensDataResult[target].Rho = rho;\n DensDataResult[target].VelDisp = v2;\n DensDataResult[target].Vx = vx;\n DensDataResult[target].Vy = vy;\n DensDataResult[target].Vz = vz;\n }\n\n return 0;\n}\n\n\n#ifdef DENSITY_SPLIT_BY_TYPE\nvoid subfind_setup_smoothinglengths(int j)\n#else\nvoid subfind_setup_smoothinglengths(void)\n#endif\n{\n int i, no, p;\n\n for(i = 0; i < NumPart; i++)\n {\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(P[i].Type == j)\n#else\n if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))\n#endif\n\t{\n\t no = Father[i];\n\n\t /* Not a good guess for gas/stars component, need more thought ! */\n\t while(10 * All.DesNumNgb * P[i].Mass > Nodes[no].u.d.mass)\n\t {\n\t p = Nodes[no].u.d.father;\n\n\t if(p < 0)\n\t\tbreak;\n\n\t no = p;\n\t }\n\n#ifdef DENSITY_SPLIT_BY_TYPE\n\t if(P[i].Type == 0)\n\t P[i].DM_Hsml = PPP[i].Hsml;\n\t else\n#ifdef KEEP_DM_HSML_AS_GUESS\n\t if(P[i].DM_Hsml < 0)\n#endif\n\t P[i].DM_Hsml =\n\t pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;\n#else\n\t P[i].DM_Hsml =\n\t pow(3.0 / (4 * M_PI) * All.DesNumNgb * P[i].Mass / Nodes[no].u.d.mass, 1.0 / 3) * Nodes[no].len;\n#endif\n\t}\n }\n}\n\n\nstatic int Nhsml;\n\nstatic struct hsml_data\n{\n float Hsml;\n float Density;\n float VelDisp;\n MyIDType ID;\n}\n *Hsml_list;\n\nint subfind_compare_hsml_data(const void *a, const void *b)\n{\n if(((struct hsml_data *) a)->ID < ((struct hsml_data *) b)->ID)\n return -1;\n\n if(((struct hsml_data *) a)->ID > ((struct hsml_data *) b)->ID)\n return +1;\n\n return 0;\n}\n\n\nvoid subfind_save_densities(int num)\n{\n int i, nprocgroup, masterTask, groupTask;\n char buf[1000];\n double t0, t1;\n\n if(ThisTask == 0)\n {\n printf(\"start saving smoothing lengths and densities\\n\");\n fflush(stdout);\n }\n\n for(i = 0, Nhsml = 0; i < NumPart; i++)\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE)))\n#else\n if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))\n#endif\n Nhsml++;\n\n MPI_Allgather(&Nhsml, 1, MPI_INT, Send_count, 1, MPI_INT, MPI_COMM_WORLD);\n for(i = 1, Send_offset[0] = 0; i < NTask; i++)\n Send_offset[i] = Send_offset[i - 1] + Send_count[i - 1];\n\n sumup_large_ints(1, &Nhsml, &Ntotal);\n\n Hsml_list = mymalloc(Nhsml * sizeof(struct hsml_data));\n\n for(i = 0, Nhsml = 0; i < NumPart; i++)\n#ifdef DENSITY_SPLIT_BY_TYPE\n if(((1 << P[i].Type) & (DENSITY_SPLIT_BY_TYPE)))\n#else\n if(((1 << P[i].Type) & (FOF_PRIMARY_LINK_TYPES)))\n#endif\n {\n\tHsml_list[Nhsml].Hsml = P[i].DM_Hsml;\n\tHsml_list[Nhsml].Density = P[i].u.DM_Density;\n\tHsml_list[Nhsml].VelDisp = P[i].v.DM_VelDisp;\n#ifdef SAVE_HSML_IN_IC_ORDER\n\tHsml_list[Nhsml].ID = P[i].ID_ic_order;\n#else\n\tHsml_list[Nhsml].ID = P[i].ID;\n#endif\n\tNhsml++;\n }\n\n t0 = second();\n parallel_sort(Hsml_list, Nhsml, sizeof(struct hsml_data), subfind_compare_hsml_data);\n t1 = second();\n\n if(ThisTask == 0)\n {\n printf(\"Sorting of densities in ID sequence took = %g sec\\n\", timediff(t0, t1));\n fflush(stdout);\n }\n\n if(ThisTask == 0)\n {\n sprintf(buf, \"%s/hsmldir_%03d\", All.OutputDir, num);\n mkdir(buf, 02755);\n }\n MPI_Barrier(MPI_COMM_WORLD);\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 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_densities(num);\n MPI_Barrier(MPI_COMM_WORLD);\t/* wait inside the group */\n }\n\n myfree(Hsml_list);\n\n}\n\nvoid subfind_save_local_densities(int num)\n{\n char fname[1000];\n int i;\n float *tmp;\n FILE *fd;\n\n\n sprintf(fname, \"%s/hsmldir_%03d/%s_%03d.%d\", All.OutputDir, num, \"hsml\", num, ThisTask);\n if(!(fd = fopen(fname, \"w\")))\n {\n printf(\"can't open file `%s`\\n\", fname);\n endrun(1183);\n }\n\n my_fwrite(&Nhsml, sizeof(int), 1, fd);\n my_fwrite(&Send_offset[ThisTask], sizeof(int), 1, fd);\t/* this is the number of IDs in previous files */\n my_fwrite(&Ntotal, sizeof(long long), 1, fd);\n my_fwrite(&NTask, sizeof(int), 1, fd);\n\n tmp = mymalloc(Nhsml * sizeof(float));\n\n for(i = 0; i < Nhsml; i++)\n tmp[i] = Hsml_list[i].Hsml;\n my_fwrite(tmp, sizeof(float), Nhsml, fd);\n\n for(i = 0; i < Nhsml; i++)\n tmp[i] = Hsml_list[i].Density;\n my_fwrite(tmp, sizeof(float), Nhsml, fd);\n\n for(i = 0; i < Nhsml; i++)\n tmp[i] = Hsml_list[i].VelDisp;\n my_fwrite(tmp, sizeof(float), Nhsml, fd);\n\n myfree(tmp);\n\n fclose(fd);\n}\n\n\n#endif\n", "meta": {"hexsha": "c7767a644ee5b758fdd9650833a15453c638c21a", "size": 17755, "ext": "c", "lang": "C", "max_stars_repo_path": "testing/icgen/random_verschillende_resoluties_N-GenIC/gadget3_64/subfind_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/subfind_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/subfind_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": 23.5165562914, "max_line_length": 108, "alphanum_fraction": 0.5981413686, "num_tokens": 5973, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.3522017956470284, "lm_q1q2_score": 0.22180774758073674}} {"text": "// many-small-dgemms.c:\n// Mini-app which investigates different ways to perform many small dgemm operations.\n// Looping over thousands of rocblas calls is slow, so looking into other solutions.\n// This functionality is very interesting to several applications, including nuccor.\n// Date: Oct 15th, 2019\n// Author: Justin Gage Lietz\n// Contact: lietzjg@ornl.gov\n\n#include \n#include \n#include \n#include \n/* #include */\n#include \n#include \n#include \n#include //for memcpy\n\n#include \n\n// tolerance as 1.e-15 fails\n#define TOL 1.e-14\n\n// Pulled from magma test code\n#define TESTING_CHECK( err ) \\\n do { \\\n magma_int_t err_ = (err); \\\n if ( err_ != 0 ) { \\\n fprintf( stderr, \"Error: %s\\nfailed at %s:%d: error %lld: %s\\n\", \\\n #err, __FILE__, __LINE__, \\\n (long long) err_, magma_strerror(err_) ); \\\n exit(1); \\\n } \\\n } while( 0 )\n\n\nsize_t idx(size_t i, size_t j, size_t nrows, size_t ncols){\n return j*nrows + i;\n}\n\n\nsize_t cidx(size_t i, size_t j, size_t nrows, size_t ncols){\n return i*ncols + j;\n}\n\n\nvoid print_c_matrix(double *mat, size_t nrows, size_t ncols){\n for(int i = 0; i < nrows; i++){\n for(int j = 0; j < ncols; j++){\n printf(\"%f \", mat[ cidx(i,j,nrows,ncols) ]);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\n\nvoid print_matrix(double *mat, size_t nrows, size_t ncols){\n for(int i = 0; i < nrows; i++){\n for(int j = 0; j < ncols; j++){\n printf(\"%f \", mat[ idx(i,j,nrows,ncols) ]);\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\n\nvoid print_matrix_array(double *mat_A, size_t *Aoffsets, size_t *nrows, size_t *ncols, size_t nBlocks){\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n size_t Aoffset = Aoffsets[iBlock];\n printf(\"iBlock: %zu\\n\",iBlock);\n print_matrix( &mat_A[Aoffset], nrows[iBlock], ncols[iBlock] );\n }\n}\n\n\nvoid cblas_wrapper(double *A, double* B, double* C, size_t M_in, size_t N_in, size_t K_in){\n int M = M_in;\n int K = K_in;\n int N = N_in;\n int LDA = M;\n int LDB = K;\n int LDC = M;\n double alpha = 1.0;\n double beta = 0.0;\n\n cblas_dgemm(/*CBLAS*/ CblasColMajor,\n /* TRANS A */ CblasNoTrans,\n /* TRANS B */ CblasNoTrans,\n /* M */M,\n /* N */N,\n /* K */K,\n /* alpha */alpha,\n /* A */A,\n /* LDA */LDA,\n /* B */B,\n /* LDB */LDB,\n /* BETA */beta,\n /* C */C,\n /* LDC */LDC);\n}\n\n\nvoid device_dgemm(rocblas_handle handle, double *A, double* B, double* C, size_t M_in, size_t N_in, size_t K_in){\n int M = M_in;\n int K = K_in;\n int N = N_in;\n int LDA = M;\n int LDB = K;\n int LDC = M;\n double alpha = 1.0;\n double beta = 0.0;\n\n size_t ABytes = sizeof(double)*M*K;\n size_t BBytes = sizeof(double)*K*N;\n size_t CBytes = sizeof(double)*M*N;\n\n double *d_A;\n double *d_B;\n double *d_C;\n const rocblas_operation transA = rocblas_operation_none;\n const rocblas_operation transB = rocblas_operation_none;\n\n hipMalloc(&d_A, ABytes);\n hipMalloc(&d_B, BBytes);\n hipMalloc(&d_C, CBytes);\n\n hipMemcpy(d_A, A, ABytes, hipMemcpyHostToDevice);\n hipMemcpy(d_B, B, BBytes, hipMemcpyHostToDevice);\n\n rocblas_dgemm(/*rocblas handle*/ handle,\n /* TRANS A */ transA,\n /* TRANS B */ transB,\n /* M */M,\n /* N */N,\n /* K */K,\n /* alpha */&alpha,\n /* A */d_A,\n /* LDA */LDA,\n /* B */d_B,\n /* LDB */LDB,\n /* BETA */&beta,\n /* C */d_C,\n /* LDC */LDC);\n\n hipMemcpy(C, d_C, CBytes, hipMemcpyDeviceToHost);\n\n hipFree(d_A);\n hipFree(d_B);\n hipFree(d_C);\n}\n\n\nvoid rocblas_array_dgemm(\n rocblas_handle handle,\n const double *A, const double* B, double* C,\n const size_t *Ms, const size_t *Ns, const size_t *Ks,\n const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){\n\n const rocblas_operation transA = rocblas_operation_none;\n const rocblas_operation transB = rocblas_operation_none;\n\n double *d_A, *d_B, *d_C;\n size_t ABytes = Aoffsets[nBlocks]*sizeof(double);\n size_t BBytes = Boffsets[nBlocks]*sizeof(double);\n size_t CBytes = Coffsets[nBlocks]*sizeof(double);\n\n hipMalloc(&d_A, ABytes);\n hipMalloc(&d_B, BBytes);\n hipMalloc(&d_C, CBytes);\n\n hipMemcpy(d_A, A, ABytes, hipMemcpyHostToDevice);\n hipMemcpy(d_B, B, BBytes, hipMemcpyHostToDevice);\n\n double start = omp_get_wtime();\n\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n size_t Aoffset = Aoffsets[iBlock];\n size_t Boffset = Boffsets[iBlock];\n size_t Coffset = Coffsets[iBlock];\n\n int M = Ms[iBlock];\n int N = Ns[iBlock];\n int K = Ks[iBlock];\n int LDA = M;\n int LDB = K;\n int LDC = M;\n double alpha = 1.0;\n double beta = 0.0;\n /* char transa = 'N'; */\n /* char transb = 'N'; */\n\n rocblas_dgemm(/*rocblas handle*/ handle,\n /* TRANS A */ transA,\n /* TRANS B */ transB,\n /* M */ M,\n /* N */ N,\n /* K */ K,\n /* alpha */ &alpha,\n /* A */ &d_A[Aoffset],\n /* LDA */ LDA,\n /* B */ &d_B[Boffset],\n /* LDB */ LDB,\n /* BETA */ &beta,\n /* C */ &d_C[Coffset],\n /* LDC */ LDC);\n }\n double stop = omp_get_wtime();\n printf(\"time of rocblas_dgemm loop: %f\\n\", stop - start);\n hipMemcpy(C, d_C, CBytes, hipMemcpyDeviceToHost);\n\n hipFree(d_A);\n hipFree(d_B);\n hipFree(d_C);\n}\n\n\nvoid magma_array_dgemm(\n const double *A, const double* B, double* C,\n const size_t *Ms, const size_t *Ns, const size_t *Ks,\n const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){\n magma_trans_t transA = MagmaNoTrans;\n magma_trans_t transB = MagmaNoTrans;\n double const* * dA_array;\n double const* * dB_array;\n double **dC_array;\n double \talpha;\n double \tbeta;\n magma_int_t* d_lddb;\n magma_int_t* d_ldda;\n magma_int_t* d_lddc;\n magma_int_t* d_m;\n magma_int_t* d_n;\n magma_int_t* d_k;\n int* h_m;\n int* h_n;\n int* h_k;\n\n double **hA_array;\n double **hB_array;\n double **hC_array;\n double *d_A_elems;\n double *d_B_elems;\n double *d_C_elems;\n\n magma_int_t batchCount;\n magma_queue_t queue;\n magma_device_t device;\n\n magma_getdevice( &device );\n magma_queue_create( device, &queue );\n\n batchCount = nBlocks;\n // Magma needs larger arrays\n TESTING_CHECK( magma_malloc((void**)&d_m, (batchCount+1)*sizeof(magma_int_t)) );\n TESTING_CHECK( magma_malloc((void**)&d_n, (batchCount+1)*sizeof(magma_int_t)) );\n TESTING_CHECK( magma_malloc((void**)&d_k, (batchCount+1)*sizeof(magma_int_t)) );\n\n TESTING_CHECK( magma_malloc((void**)&d_ldda, (batchCount+1)*sizeof(magma_int_t) ) );\n TESTING_CHECK( magma_malloc((void**)&d_lddb, (batchCount+1)*sizeof(magma_int_t) ) );\n TESTING_CHECK( magma_malloc((void**)&d_lddc, (batchCount+1)*sizeof(magma_int_t) ) );\n\n // Looks like magma_malloc works with regular c int as well.\n TESTING_CHECK( magma_malloc_cpu((void**)&h_m, (batchCount+1)*sizeof(int) ) );\n TESTING_CHECK( magma_malloc_cpu((void**)&h_n, (batchCount+1)*sizeof(int) ) );\n TESTING_CHECK( magma_malloc_cpu((void**)&h_k, (batchCount+1)*sizeof(int) ) );\n\n // dA_array is the array of pointers need by dgemm\n // d_A_elems are the actual mtx elements being pointed to\n // hA_array is the host side pointers that will get passed to dA_array\n TESTING_CHECK( magma_malloc( (void**)&dA_array, sizeof(double*)*batchCount ) );\n TESTING_CHECK( magma_malloc( (void**)&dB_array, sizeof(double*)*batchCount ) );\n TESTING_CHECK( magma_malloc( (void**)&dC_array, sizeof(double*)*batchCount ) );\n\n TESTING_CHECK( magma_malloc( (void**)&d_A_elems, sizeof(double)*Aoffsets[nBlocks] ) );\n TESTING_CHECK( magma_malloc( (void**)&d_B_elems, sizeof(double)*Boffsets[nBlocks] ) );\n TESTING_CHECK( magma_malloc( (void**)&d_C_elems, sizeof(double)*Coffsets[nBlocks] ) );\n\n TESTING_CHECK( magma_malloc_cpu( (void**)&hA_array, sizeof(double*)*batchCount ) );\n TESTING_CHECK( magma_malloc_cpu( (void**)&hB_array, sizeof(double*)*batchCount ) );\n TESTING_CHECK( magma_malloc_cpu( (void**)&hC_array, sizeof(double*)*batchCount ) );\n\n // magma needs 32-bit int, while main was using 64\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n h_m[iBlock] = Ms[iBlock];\n h_n[iBlock] = Ns[iBlock];\n h_k[iBlock] = Ks[iBlock];\n }\n\n magma_setvector(batchCount, sizeof(magma_int_t), h_m, 1, d_m, 1, queue);\n magma_setvector(batchCount, sizeof(magma_int_t), h_n, 1, d_n, 1, queue);\n magma_setvector(batchCount, sizeof(magma_int_t), h_k, 1, d_k, 1, queue);\n magma_setvector(batchCount, sizeof(magma_int_t), h_m, 1, d_ldda, 1, queue);\n magma_setvector(batchCount, sizeof(magma_int_t), h_k, 1, d_lddb, 1, queue);\n magma_setvector(batchCount, sizeof(magma_int_t), h_m, 1, d_lddc, 1, queue);\n\n magma_setvector(Aoffsets[nBlocks], sizeof(double), A, 1, d_A_elems, 1, queue);\n magma_setvector(Boffsets[nBlocks], sizeof(double), B, 1, d_B_elems, 1, queue);\n\n size_t Aoffset;\n size_t Boffset;\n size_t Coffset;\n\n for(int iBlock = 0; iBlock < nBlocks; iBlock++){\n Aoffset = Aoffsets[iBlock];\n Boffset = Boffsets[iBlock];\n Coffset = Coffsets[iBlock];\n\n hA_array[iBlock] = d_A_elems + Aoffset;\n hB_array[iBlock] = d_B_elems + Boffset;\n hC_array[iBlock] = d_C_elems + Coffset;\n }\n\n magma_setvector(batchCount, sizeof(double*), hA_array, 1, dA_array, 1, queue);\n magma_setvector(batchCount, sizeof(double*), hB_array, 1, dB_array, 1, queue);\n magma_setvector(batchCount, sizeof(double*), hC_array, 1, dC_array, 1, queue);\n\n alpha = 1.0;\n beta = 0.0;\n batchCount = nBlocks;\n\n double start,stop;\n\n start = omp_get_wtime();\n\n magmablas_dgemm_vbatched(\t transA,\n /* magma_trans_t */ \t transB,\n /* magma_int_t * */ d_m,\n /* magma_int_t * */\t d_n,\n /* magma_int_t * */\t d_k,\n /* double */\t alpha,\n /* double const *const * */\tdA_array,\n /* magma_int_t * */\t d_ldda,\n /* double const *const * */\tdB_array,\n /* magma_int_t * */\t d_lddb,\n /* double */\t beta,\n /* double ** */\t dC_array,\n /* magma_int_t * */\t d_lddc,\n /* magma_int_t */\t batchCount,\n /* magma_queue_t */\t queue);\n stop = omp_get_wtime();\n\n printf(\"time of magmablas_dgemm_vbatched: %f\\n\", stop - start);\n\n magma_getvector(Coffsets[nBlocks], sizeof(double), d_C_elems, 1, C, 1, queue);\n\n // Clean up\n magma_queue_destroy( queue );\n\n TESTING_CHECK( magma_free(d_m) );\n TESTING_CHECK( magma_free(d_n) );\n TESTING_CHECK( magma_free(d_k) );\n\n TESTING_CHECK( magma_free(d_ldda) );\n TESTING_CHECK( magma_free(d_lddb) );\n TESTING_CHECK( magma_free(d_lddc) );\n\n TESTING_CHECK( magma_free_cpu(h_m) );\n TESTING_CHECK( magma_free_cpu(h_n) );\n TESTING_CHECK( magma_free_cpu(h_k) );\n\n TESTING_CHECK( magma_free(dA_array) );\n TESTING_CHECK( magma_free(dB_array) );\n TESTING_CHECK( magma_free(dC_array) );\n\n TESTING_CHECK( magma_free(d_A_elems) );\n TESTING_CHECK( magma_free(d_B_elems) );\n TESTING_CHECK( magma_free(d_C_elems) );\n\n TESTING_CHECK( magma_free_cpu(hA_array) );\n TESTING_CHECK( magma_free_cpu(hB_array) );\n TESTING_CHECK( magma_free_cpu(hC_array) );\n}\n\n\nvoid host_matmul(const double *A, const double* B, double* C, const size_t M, const size_t N, const size_t K){\n for(size_t i = 0; i < M; i++){\n for(size_t j = 0; j < N; j++){\n C[ idx(i,j,M,N) ] = 0.0;\n for(size_t k = 0; k < K; k++){\n C[ idx(i,j,M,N) ] += A[ idx(i,k,M,K) ] * B[ idx(k,j,K,N) ];\n }\n }\n }\n}\n\n\nvoid host_array_matmul(const double *A, const double* B, double* C,\n const size_t *Ms, const size_t *Ns, const size_t *Ks,\n const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){\n\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n size_t Aoffset = Aoffsets[iBlock];\n size_t Boffset = Boffsets[iBlock];\n size_t Coffset = Coffsets[iBlock];\n\n host_matmul(&A[Aoffset], &B[Boffset], &C[Coffset], Ms[iBlock], Ns[iBlock], Ks[iBlock]);\n }\n}\n\n\nvoid host_array_dgemm(const double *A, const double* B, double* C,\n const size_t *Ms, const size_t *Ns, const size_t *Ks,\n const size_t *Aoffsets, const size_t *Boffsets, const size_t *Coffsets, const size_t nBlocks){\n\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n size_t Aoffset = Aoffsets[iBlock];\n size_t Boffset = Boffsets[iBlock];\n size_t Coffset = Coffsets[iBlock];\n\n int M = Ms[iBlock];\n int N = Ns[iBlock];\n int K = Ks[iBlock];\n int LDA = M;\n int LDB = K;\n int LDC = M;\n double alpha = 1.0;\n double beta = 0.0;\n /* char transa = 'N'; */\n /* char transb = 'N'; */\n\n cblas_dgemm(/*CBLAS*/ CblasColMajor,\n /* TRANS A */ CblasNoTrans,\n /* TRANS B */ CblasNoTrans,\n /* M */ M,\n /* N */ N,\n /* K */ K,\n /* alpha */ alpha,\n /* A */ &A[Aoffset],\n /* LDA */ LDA,\n /* B */ &B[Boffset],\n /* LDB */ LDB,\n /* BETA */ beta,\n /* C */ &C[Coffset],\n /* LDC */ LDC);\n }\n}\n\n\nvoid host_transpose(double *mat_in, double *mat_out, size_t nrows_in, size_t ncols_in){\n for(size_t i = 0; i < nrows_in; i++){\n for(size_t j = 0; j < ncols_in; j++){\n mat_out[ idx(j,i,ncols_in,nrows_in) ] = mat_in[ idx(i,j,nrows_in, ncols_in) ];\n }\n }\n}\n\n\nint check_equal(double *mat_A, double *mat_B, size_t nrows, size_t ncols){\n int flag = 1;\n for(size_t i = 0; i < nrows; i++){\n for(size_t j = 0; j < ncols; j++){\n if( fabs( mat_A[ idx(i,j,nrows,ncols) ] - mat_B[ idx(i,j,nrows,ncols) ]) > TOL ){\n flag = 0;\n return flag;\n }\n }\n }\n return flag;\n}\n\n\nint check_matrix_array_equal(double *mat_A, double *mat_B, size_t *Aoffsets, size_t *Boffsets, size_t *nrows, size_t *ncols, size_t nBlocks){\n int flag = 1;\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n size_t Aoffset = Aoffsets[iBlock];\n size_t Boffset = Boffsets[iBlock];\n\n flag *= check_equal( &mat_A[Aoffset], &mat_B[Boffset], nrows[iBlock], ncols[iBlock] );\n if( !check_equal(&mat_A[Aoffset], &mat_B[Boffset], nrows[iBlock], ncols[iBlock]) ){\n printf(\"error in block: %zu\\n\");\n printf(\"A\\n\");\n print_matrix( &mat_A[Aoffset], nrows[iBlock], ncols[iBlock] );\n printf(\"B\\n\");\n print_matrix( &mat_B[Aoffset], nrows[iBlock], ncols[iBlock] );\n return flag;\n }\n }\n return flag;\n}\n\n\nvoid generate_random_array(size_t* array, size_t nBlocks, size_t max_size){\n size_t rando;\n\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n rando = rand()%max_size + 1;\n array[iBlock] = rando;\n }\n}\n\n\nvoid load_random_matrix(double* mat_in, size_t nrows, size_t ncols){\n double rando;\n\n for(size_t i = 0; i < nrows; i++){\n for(size_t j = 0; j < ncols; j++){\n rando= (double) rand()/RAND_MAX*2.0 - 1.0;\n mat_in[ idx(i,j,nrows,ncols) ] = rando;\n }\n }\n}\n\n\nint main(){\n // Start magma\n TESTING_CHECK( magma_init() );\n magma_print_environment();\n\n // magma seems to break at 2^16, but 2^15 blocks is fine\n size_t nBlocks = 1<<15;\n size_t max_block_size = 10;\n // Small test for debugging\n // size_t nBlocks = 3;\n // size_t max_block_size = 4;\n\n size_t *Ms_array;\n size_t *Ns_array;\n size_t *Ks_array;\n size_t *Aoffsets;\n size_t *Boffsets;\n size_t *Coffsets;\n\n Ms_array = (size_t*)malloc(sizeof(size_t)*nBlocks);\n Ns_array = (size_t*)malloc(sizeof(size_t)*nBlocks);\n Ks_array = (size_t*)malloc(sizeof(size_t)*nBlocks);\n\n Aoffsets = (size_t*)malloc(sizeof(size_t)*(nBlocks+1));\n Boffsets = (size_t*)malloc(sizeof(size_t)*(nBlocks+1));\n Coffsets = (size_t*)malloc(sizeof(size_t)*(nBlocks+1));\n\n /* srand( time(NULL) ); */\n // Reproducible seed\n srand( 100 );\n\n generate_random_array(Ms_array,nBlocks,max_block_size);\n generate_random_array(Ns_array,nBlocks,max_block_size);\n generate_random_array(Ks_array,nBlocks,max_block_size);\n\n Aoffsets[0] = 0;\n Boffsets[0] = 0;\n Coffsets[0] = 0;\n\n // Offset array elements indicate starting location of each block\n // Final array element indicates where the next block WOULD start\n // This is needed to count the total number of elements\n for(size_t iBlock = 1; iBlock < nBlocks + 1; iBlock++){\n Aoffsets[iBlock] = Aoffsets[iBlock-1] + Ms_array[iBlock-1] * Ks_array[iBlock-1];\n Boffsets[iBlock] = Boffsets[iBlock-1] + Ks_array[iBlock-1] * Ns_array[iBlock-1];\n Coffsets[iBlock] = Coffsets[iBlock-1] + Ms_array[iBlock-1] * Ns_array[iBlock-1];\n }\n\n size_t ABytes = Aoffsets[nBlocks]*sizeof(double);\n size_t BBytes = Boffsets[nBlocks]*sizeof(double);\n size_t CBytes = Coffsets[nBlocks]*sizeof(double);\n\n double *h_A;\n double *h_B;\n double *h_C;\n double *h_C_host;\n double *h_C_device;\n double *h_C_magma;\n\n h_A = (double*)malloc(ABytes);\n h_B = (double*)malloc(BBytes);\n h_C = (double*)malloc(CBytes);\n h_C_host = (double*)malloc(CBytes);\n h_C_device = (double*)malloc(CBytes);\n h_C_magma = (double*)malloc(CBytes);\n\n for(size_t iBlock = 0; iBlock < nBlocks; iBlock++){\n size_t Aoffset = Aoffsets[iBlock];\n size_t Boffset = Boffsets[iBlock];\n\n load_random_matrix(&h_A[Aoffset], Ms_array[iBlock], Ks_array[iBlock]);\n load_random_matrix(&h_B[Boffset], Ks_array[iBlock], Ns_array[iBlock]);\n }\n\n double start,stop;\n int check;\n //////////////////////////////////////////////////////////////////////\n // Tests on host\n //////////////////////////////////////////////////////////////////////\n\n start = omp_get_wtime();\n host_array_matmul(h_A, h_B, h_C, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks);\n stop = omp_get_wtime();\n printf(\"naive loop time: %f\\n\", stop - start);\n\n start = omp_get_wtime();\n host_array_dgemm(h_A, h_B, h_C_host, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks);\n stop = omp_get_wtime();\n printf(\"host blas time: %f\\n\", stop - start);\n\n check = check_matrix_array_equal(h_C_host, h_C, Coffsets, Coffsets, Ms_array, Ns_array, nBlocks);\n if( check == 0 ){\n printf(\"check host dgemm failed: %d\\n\",check);\n }\n\n //////////////////////////////////////////////////////////////////////\n // Run tests on device\n //////////////////////////////////////////////////////////////////////\n\n rocblas_handle handle;\n rocblas_create_handle(&handle);\n\n start = omp_get_wtime();\n rocblas_array_dgemm(handle, h_A, h_B, h_C_device, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks);\n stop = omp_get_wtime();\n printf(\"rocblas wrapper time: %f\\n\", stop - start);\n\n check = check_matrix_array_equal(h_C_device, h_C, Coffsets, Coffsets, Ms_array, Ns_array, nBlocks);\n if( check == 0 ){\n printf(\"check device dgemm failed: %d\\n\",check);\n }\n\n start = omp_get_wtime();\n magma_array_dgemm(h_A, h_B, h_C_magma, Ms_array, Ns_array, Ks_array, Aoffsets, Boffsets, Coffsets, nBlocks);\n stop = omp_get_wtime();\n printf(\"magma blas wrapper time: %f\\n\", stop - start);\n\n check = check_matrix_array_equal(h_C_magma, h_C, Coffsets, Coffsets, Ms_array, Ns_array, nBlocks);\n if( check == 0 ){\n printf(\"magma dgemm failed: %d\\n\",check);\n }\n\n // Clean up\n rocblas_destroy_handle(handle);\n free(h_A);\n free(h_B);\n free(h_C);\n free(h_C_host);\n free(h_C_device);\n free(h_C_magma);\n magma_finalize();\n\n return 0;\n}\n", "meta": {"hexsha": "2c227ba2eee44a06b39fd004b08b2d6b3d99ac06", "size": 19700, "ext": "c", "lang": "C", "max_stars_repo_path": "amd/many-small-dgemms-amd.c", "max_stars_repo_name": "justinlietz/small_dgemms", "max_stars_repo_head_hexsha": "e794ed4120a2f28f8d9650f8501397a451eb88c3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "amd/many-small-dgemms-amd.c", "max_issues_repo_name": "justinlietz/small_dgemms", "max_issues_repo_head_hexsha": "e794ed4120a2f28f8d9650f8501397a451eb88c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "amd/many-small-dgemms-amd.c", "max_forks_repo_name": "justinlietz/small_dgemms", "max_forks_repo_head_hexsha": "e794ed4120a2f28f8d9650f8501397a451eb88c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-11-01T23:33:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T01:26:09.000Z", "avg_line_length": 30.78125, "max_line_length": 141, "alphanum_fraction": 0.6144670051, "num_tokens": 6071, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665999540697, "lm_q2_score": 0.373875808818685, "lm_q1q2_score": 0.2215837044176478}} {"text": "// The MIT License (MIT)\n// \n// Copyright (c) 2008 - 2015 Stefan Faußer\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n// \n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n// \n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * \\file mlpLib.c\n * \\brief Multi-layer perceptron (MLP) libary\n *\n * This MLP library supports Online, Batch, Batch with Momentumterm, RPROP-, RPROP+ and Quickprop learning.\n * Further, it can be used for learning state-action value functions (reinforcement learning)\n * when used in combination with the tdlLib.\n * \n * \\author Stefan Fausser\n * \n * Modification history:\n * \n * 2008-04-01, S. Fausser - written\n */\n\n#include \n#include \n#include \n#include \n#include \n#include /*memset */\n#include \"mlpLib.h\"\n#include \"matrixLib.h\"\n#include \n#include \n#include \n\n#define MAX_WEIGHT_ONLINE_MODE 99999999\n#define ZERO_PRECISION 0.001 \n\n/**\n * structure including all mlp parameters for one mlp network\n */\nstruct mlp_vars\n{\n /**\n * weights for neurons in hidden layer\n */\n double ***w;\n double ***w_prime;\n \n /**\n * bias for neurons in hidden layer\n */\n double **theta;\n double **theta_prime;\n \n /**\n * modifyable eta values for supersab / resilient weight udpate mode in hidden layer\n */\n double ***eta_w;\n\n /**\n * last gradient (t-1) in hidden layer\n */\n double ***desc_w;\n\n /**\n * last weight-delta in hidden layer\n */\n double ***delta_w1;\n\n /**\n * dendrit potential in hidden layer\n */\n double ***u;\n\n /**\n * axon potential in hidden layer\n */\n double ***y;\n double ***y_tsignal;\n\n /**\n * delta values in hidden layer\n */\n double ***delta;\n double ****gradvec;\n double ****gradvec_tsignal;\n double ****grad2vec;\n double ****gradientTrace;\n /**\n * weights for neurons in output layer\n */\n double **w2;\n double **w2_prime;\n \n /**\n * bias for neurons in output layer\n */\n double *theta2;\n double *theta2_prime;\n \n /**\n * modifyable eta values for supersab / resilient weight udpate mode in output layer\n */\n double **eta_w2;\n\n /**\n * last gradient in output layer\n */\n double **desc_w2;\n\n /**\n * last weight-delta in output layer\n */\n double **delta_w2;\n\n /**\n * dendrit potential in output layer\n */\n double *u2;\n\n /**\n * axon potential in output layer\n */\n double **y2;\n double **y2_prime;\n\n /**\n * delta values in output layer\n */\n double **delta2;\n double **gradvec2;\n double **gradvec2_tsignal;\n double **grad2vec2;\n double **gradientTrace2;\n \n /**\n * mlp_param structure\n */\n struct mlp_param mlpP;\n\n /**\n * mlp_init_values structure\n */\n struct mlp_init_values mlpIv;\n\n /**\n * maximum number of training samples in one epoche\n */\n uint32_t micro_max;\n\n /**\n * floating point value that will be used to random initialize the weights\n */\n double a;\n\n double aOut;\n \n int weightNormalizedInitialization;\n \n int thresholdZeroInitialization;\n};\n\n/**\n * Gradient factor\n */\n#define GRADIENT_FACTOR (-1.0)\n\n/*Calculate S = summed gradient information (weight specific) over all patterns of the pattern set*/\n#define CALC_GRADIENT_WEIGHTS_OUTPUT(_S) \\\n _S = 0; \\\n for (muster=0;mustery[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers-1][muster][i] * pMlpVA[mlpfd]->delta2[muster][j]; \\\n } \\\n _S *= GRADIENT_FACTOR;\n\n#define CALC_GRADIENT_BIAS_OUTPUT(_S) \\\n _S = 0; \\\n for (muster=0;musterdelta2[muster][j]; \\\n }\n\n#define CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER(_S) \\\n _S = 0; \\\n for (muster=0;musterx[muster][k] * pMlpVA[mlpfd]->delta[l][muster][i]; \\\n } \\\n _S *= GRADIENT_FACTOR;\n\n#define CALC_GRADIENT_WEIGHTS_HIDDEN(_S) \\\n _S = 0; \\\n for (muster=0;mustery[l-1][muster][i2] * pMlpVA[mlpfd]->delta[l][muster][i]; \\\n } \\\n _S *= GRADIENT_FACTOR;\n\n#define CALC_GRADIENT_BIAS_HIDDEN(_S) \\\n _S = 0; \\\n for (muster=0;musterdelta[l][muster][i]; \\\n }\n\n#define CALC_RESILIENT_UPDATE_WEIGHT(_S,_weight,_delta) \\\n /*Berechnung der aktuellen Gewichtsaenderung*/ \\\n if ( _S > 0 ) { \\\n /*S(t)>0*/ \\\n _weight = _weight - _delta; \\\n } \\\n else if ( _S < 0 ) { \\\n /*S(t-1)<0*/ \\\n _weight = _weight + _delta; \\\n } \\\n else { \\\n /*S(t-1)*S(t)=0*/ \\\n }\n\n#define CALC_RESILIENT_DELTA_WEIGHT(_S,_delta_weight,_delta) \\\n /*Berechnung der aktuellen Gewichtsaenderung*/ \\\n if ( _S > 0 ) { \\\n /*S(t)>0*/ \\\n _delta_weight = - _delta; \\\n } \\\n else if ( _S < 0 ) { \\\n /*S(t-1)<0*/ \\\n _delta_weight = + _delta; \\\n } \\\n else { \\\n _delta_weight = 0; \\\n }\n\n#define CALC_RESILIENT_DELTA_INCREASE(_delta,_eta_pos,_max_delta) \\\n _delta = _eta_pos * _delta; \\\n if ( _delta > _max_delta ) \\\n _delta = _max_delta;\n\n#define CALC_RESILIENT_DELTA_DECREASE(_delta,_eta_neg,_min_delta) \\\n _delta = _eta_neg * _delta; \\\n if ( _delta < _min_delta ) \\\n _delta = _min_delta;\n\n#define CALC_RESILIENT_DS(_dS,_S,_desc_w) \\\n _dS = sign(_S) * sign(_desc_w);\n\n/* locals */\nstatic int maxMlps = -1;\nstatic struct mlp_vars **pMlpVA = NULL;\nstatic int nRegisteredMlps = -1;\nstatic int *mlpRegistered = NULL;\n\n\nint mlpLibInit (\n uint16_t nrMlps)\n{\n int i;\n\n maxMlps = nrMlps;\n\n mlpRegistered = malloc (sizeof (*mlpRegistered) * maxMlps);\n pMlpVA = malloc (sizeof (**pMlpVA) * maxMlps);\n\n nRegisteredMlps = 0;\n for (i = 0; i < maxMlps; i++)\n {\n mlpRegistered[i] = 0;\n }\n\n return 0;\n}\n\n\nint mlpLibDeinit (\n )\n{\n free (mlpRegistered);\n free (pMlpVA);\n\n return 0;\n}\n\n/*local function prototypes*/\nstatic int allocateWeights (\n struct mlp_vars *pMlpV);\nstatic int initializeWeights (\n struct mlp_vars *pMlpV,\n int verbose,\n unsigned int seed);\nstatic double randomVal (\n double min,\n double max);\n\n/*implementation*/\n\n#define TRANSFKT(Y,X,TYPE,BETA) \\\n /*Transferfunktion*/ \\\n if (TYPE==0) { \\\n /*Logistische Funktion*/ \\\n Y = 1.0 / (1.0 + exp(-X)); \\\n } \\\n else if (TYPE==1) { \\\n /*Fermi Funktion*/ \\\n Y = 1.0 / (1.0 + exp(-BETA*X)); \\\n } \\\n else if (TYPE==2) { \\\n /*Tangens hyperbolicus*/ \\\n Y = tanh(X); \\\n } \\\n else { \\\n Y = X; \\\n }\n\n#define TRANSFKT_DERIVATIVE(Y,FX,TYPE,BETA) \\\n /*1. Ableitung der Transferfunktion*/ \\\n if (TYPE==0) { \\\n /*1. Ableitung Logistische Funktion*/ \\\n Y = FX * (1.0 - FX); \\\n } \\\n else if (TYPE==1) { \\\n /*1. Ableitung Fermi Funktion*/ \\\n Y = BETA * FX * (1.0 - FX); \\\n } \\\n else if (TYPE==2) { \\\n /*1. Ableitung Tangens hyperbolicus*/ \\\n Y = 1.0 - (FX * FX); \\\n } \\\n else { \\\n Y = 1; \\\n }\n\n#define TRANSFKT_DERIVATIVE_2(Y,FX,TYPE,BETA) \\\n /*2. Ableitung der Transferfunktion*/ \\\n if (TYPE==0) { \\\n /*2. Ableitung Logistische Funktion*/ \\\n Y = FX * ((1.0 - FX) * ((1.0 - FX) - FX)); \\\n } \\\n else if (TYPE==1) { \\\n /*2. Ableitung Fermi Funktion*/ \\\n Y = BETA * FX * ((1.0 - FX) * ((1.0 - FX) - FX)); \\\n } \\\n else if (TYPE==2) { \\\n /*2. Ableitung Tangens hyperbolicus*/ \\\n Y = -2.0 * (FX - pow(FX, 3.0)); \\\n } \\\n else { \\\n Y = 0; \\\n }\n\nstatic int allocateWeights (\n struct mlp_vars *pMlpV)\n{\n uint16_t l;\n int ret;\n\n if (pMlpV == NULL)\n return -1;\n\n /*Speicher allozieren fuer w[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m][pMlpV->mlpIv.h] */\n pMlpV->w = (double ***) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double **));\n if (pMlpV->w == NULL)\n {\n printf (\"### not enough memory to allocate w.\\n\");\n return -2;\n }\n\n pMlpV->w_prime = (double ***) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double **));\n if (pMlpV->w_prime == NULL)\n {\n printf (\"### not enough memory to allocate w_prime.\\n\");\n return -2;\n }\n\n /*Speicher allozieren fuer theta[pMlpV->mlpIv.nrHiddenLayers][zeile] */\n pMlpV->theta = (double **) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double *));\n if (pMlpV->theta == NULL)\n {\n printf (\"### not enough memory to allocate theta1.\\n\");\n return -3;\n }\n\n pMlpV->theta_prime = (double **) malloc (pMlpV->mlpIv.nrHiddenLayers * sizeof (double *));\n if (pMlpV->theta_prime == NULL)\n {\n printf (\"### not enough memory to allocate theta1_prime.\\n\");\n return -3;\n }\n\n for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n ret = allocateMatrix2 (&pMlpV->w[l], pMlpV->mlpIv.m, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->w_prime[l], pMlpV->mlpIv.m, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n }\n else\n {\n ret = allocateMatrix2 (&pMlpV->w[l], pMlpV->mlpIv.h[l - 1], pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->w_prime[l], pMlpV->mlpIv.h[l - 1], pMlpV->mlpIv.h[l]);\n if (ret)\n return -2; \n }\n ret = allocateVector (&pMlpV->theta[l], pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateVector (&pMlpV->theta_prime[l], pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n }\n\n /*Speicher allozieren fuer w2[zeile][spalte] */\n ret = allocateMatrix2 (&pMlpV->w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1], pMlpV->mlpIv.n);\n if (ret)\n return -2;\n\n ret = allocateMatrix2 (&pMlpV->w2_prime, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1], pMlpV->mlpIv.n);\n if (ret)\n return -2;\n\n /*Speicher allozieren fuer theta2[zeile] */\n ret = allocateVector (&pMlpV->theta2, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n\n ret = allocateVector (&pMlpV->theta2_prime, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n\n return 0;\n}\n\n\nstatic int initializeWeights (\n struct mlp_vars *pMlpV,\n int verbose,\n unsigned int seed)\n{\n uint16_t k, i, i2, j, l;\n int ret;\n \n if (pMlpV == NULL)\n return -1;\n\n /*Allocate weights first */\n ret = allocateWeights (pMlpV);\n if (ret)\n return -2;\n\n /*Schritt 1: Initialisierung */\n srandom (seed);\n\n // Attention: The _prime weights are only used for TDC_MODE and they are just set to zero\n \n /* Hidden Layer */\n\n for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k < pMlpV->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpV->mlpIv.h[l]; i++)\n {\n double val = pMlpV->a;\n if(pMlpV->weightNormalizedInitialization == 1)\n val *= 1.0 / sqrt(pMlpV->mlpIv.m);\n else if(pMlpV->weightNormalizedInitialization == 2)\n val *= sqrt(6.0 / (pMlpV->mlpIv.m + pMlpV->mlpIv.h[l]));\n \n pMlpV->w[l][k][i] = randomVal (-val, val); \n pMlpV->w_prime[l][k][i] = 0;\n }\n }\n }\n else\n {\n for (i = 0; i < pMlpV->mlpIv.h[l - 1]; i++)\n {\n for (i2 = 0; i2 < pMlpV->mlpIv.h[l]; i2++)\n {\n double val = pMlpV->a;\n if(pMlpV->weightNormalizedInitialization == 1)\n val *= 1.0 / sqrt(pMlpV->mlpIv.h[l - 1]);\n else if(pMlpV->weightNormalizedInitialization == 2)\n val *= sqrt(6.0 / (pMlpV->mlpIv.h[l - 1] + pMlpV->mlpIv.h[l]));\n\n pMlpV->w[l][i][i2] = randomVal (-val, val); \n pMlpV->w_prime[l][i][i2] = 0; \n }\n }\n }\n \n for (i = 0; i < pMlpV->mlpIv.h[l]; i++)\n {\n if(pMlpV->thresholdZeroInitialization)\n pMlpV->theta[l][i] = 0;\n else\n {\n double val = pMlpV->a;\n if(pMlpV->weightNormalizedInitialization == 1)\n {\n if(l == 0)\n val *= 1.0 / sqrt(pMlpV->mlpIv.m);\n else\n val *= 1.0 / sqrt(pMlpV->mlpIv.h[l - 1]);\n }\n else if(pMlpV->weightNormalizedInitialization == 2)\n {\n if(l == 0)\n val *= sqrt(6.0 / (pMlpV->mlpIv.m + pMlpV->mlpIv.h[l]));\n else\n val *= sqrt(6.0 / (pMlpV->mlpIv.h[l - 1] + pMlpV->mlpIv.h[l]));\n }\n \n pMlpV->theta[l][i] = randomVal (-val, val);\n }\n \n pMlpV->theta_prime[l][i] = 0;\n }\n }\n\n /* output layer */\n for (i = 0; i < pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1]; i++)\n {\n for (j = 0; j < pMlpV->mlpIv.n; j++)\n {\n double val = pMlpV->a;\n if(pMlpV->aOut > 0)\n val = pMlpV->aOut; \n \n if(pMlpV->weightNormalizedInitialization == 1)\n val *= 1.0 / sqrt(pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1]);\n else if(pMlpV->weightNormalizedInitialization == 2)\n val *= sqrt(6.0 / (pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + pMlpV->mlpIv.n));\n\n pMlpV->w2[i][j] = randomVal (-val, val);\n pMlpV->w2_prime[i][j] = 0; \n }\n }\n for (j = 0; j < pMlpV->mlpIv.n; j++)\n {\n if(pMlpV->thresholdZeroInitialization)\n pMlpV->theta2[j] = 0;\n else\n {\n double val = pMlpV->a;\n if(pMlpV->aOut > 0)\n val = pMlpV->aOut;\n \n if(pMlpV->weightNormalizedInitialization == 1)\n val *= 1.0 / sqrt(pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1]);\n else if(pMlpV->weightNormalizedInitialization == 2)\n val *= sqrt(6.0 / (pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + pMlpV->mlpIv.n));\n\n pMlpV->theta2[j] = randomVal (-val, val); \n }\n \n pMlpV->theta2_prime[j] = 0;\n }\n\n return 0;\n}\n\nstatic int mlp_reset_specialvars (\n int mlpfd)\n{\n uint16_t k, i, i2, j;\n int32_t l; /*wegen for Schleife => Fehlerrückvermittlung... */\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n double eta = pMlpVA[mlpfd]->mlpP.eta_start;\n if(pMlpVA[mlpfd]->mlpP.etaNormalize)\n eta /= (double) pMlpVA[mlpfd]->micro_max;\n \n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n pMlpVA[mlpfd]->delta_w1[l][k][i] = 0;\n pMlpVA[mlpfd]->eta_w[l][k][i] = eta;\n pMlpVA[mlpfd]->desc_w[l][k][i] = 0;\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n pMlpVA[mlpfd]->delta_w1[l][i2][i] = 0;\n pMlpVA[mlpfd]->eta_w[l][i2][i] = eta;\n pMlpVA[mlpfd]->desc_w[l][i2][i] = 0;\n }\n }\n }\n }\n\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n { /*h+1 */\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n pMlpVA[mlpfd]->delta_w2[i][j] = 0;\n pMlpVA[mlpfd]->eta_w2[i][j] = eta;\n pMlpVA[mlpfd]->desc_w2[i][j] = 0;\n }\n }\n return 0;\n}\n\nstatic double randomVal (\n double min,\n double max)\n{\n if(min == 0 && max == 0)\n return 0;\n\n double val = min + ((max - min) * random () / (RAND_MAX + 1.0));\n \n return val;\n}\n\nint openMlpParameterFile (\n const char *filename,\n struct mlp_init_values *pMlpInitVals,\n struct mlp_param *pMlpP,\n uint32_t *seed,\n double *a,\n double *aOut,\n int *weightNormalizedInitialization,\n int *thresholdZeroInitialization)\n{\n FILE *fp;\n char var[512], value[512], line[512];\n int i = 0;\n char str[1000];\n\n if (pMlpP == NULL)\n return -1;\n\n if (pMlpInitVals == NULL)\n return -2;\n\n /* Set defaults (all zero) */\n memset(pMlpP, 0, sizeof(struct mlp_param));\n \n fp = fopen (filename, \"r\");\n if (fp)\n {\n while (fgets (line, sizeof (line), fp))\n {\n memset (var, 0, sizeof (var));\n memset (value, 0, sizeof (value));\n if (sscanf (line, \"%[^ \\t=]%*[\\t ]=%*[\\t ]%[^\\n]\", var, value) == 2)\n {\n if (strcmp (var, \"seed\") == 0)\n *seed = atoi (value);\n if (strcmp (var, \"a\") == 0)\n *a = atof (value);\n if (strcmp (var, \"aOut\") == 0)\n *aOut = atof (value);\n if (strcmp (var, \"weightNormalizedInitialization\") == 0)\n *weightNormalizedInitialization = atoi (value);\n if (strcmp (var, \"thresholdZeroInitialization\") == 0)\n *thresholdZeroInitialization = atoi (value);\n if (strcmp (var, \"nrHiddenLayers\") == 0)\n pMlpInitVals->nrHiddenLayers = atoi (value);\n for (i = 0; i < pMlpInitVals->nrHiddenLayers; i++)\n {\n sprintf (str, \"h%i\", i);\n if (strcmp (var, str) == 0)\n pMlpInitVals->h[i] = atoi (value);\n }\n if (strcmp (var, \"m\") == 0)\n pMlpInitVals->m = atoi (value);\n if (strcmp (var, \"n\") == 0)\n pMlpInitVals->n = atoi (value);\n if (strcmp (var, \"maxIterations\") == 0)\n pMlpP->maxIterations = atoi (value);\n if (strcmp (var, \"eta1\") == 0)\n pMlpP->eta1 = atof (value);\n if (strcmp (var, \"eta2\") == 0)\n pMlpP->eta2 = atof (value);\n if (strcmp (var, \"etaNormalize\") == 0)\n pMlpP->etaNormalize = atoi (value);\n if (strcmp (var, \"epsilon\") == 0)\n pMlpP->epsilon = atof (value);\n if (strcmp (var, \"transFktTypeHidden\") == 0)\n pMlpInitVals->transFktTypeHidden = atoi (value);\n if (strcmp (var, \"transFktTypeOutput\") == 0)\n pMlpInitVals->transFktTypeOutput = atoi (value);\n if (strcmp (var, \"hasThresholdOutput\") == 0)\n pMlpInitVals->hasThresholdOutput = atoi (value);\n if (strcmp (var, \"beta\") == 0)\n pMlpP->beta = atof (value);\n if (strcmp (var, \"eta_pos\") == 0)\n pMlpP->eta_pos = atof (value);\n if (strcmp (var, \"eta_neg\") == 0)\n pMlpP->eta_neg = atof (value);\n if (strcmp (var, \"eta_start\") == 0)\n pMlpP->eta_start = atof (value);\n if (strcmp (var, \"eta_max\") == 0)\n pMlpP->eta_max = atof (value);\n if (strcmp (var, \"eta_min\") == 0)\n pMlpP->eta_min = atof (value);\n if (strcmp (var, \"beta_max\") == 0)\n pMlpP->beta_max = atof (value);\n if (strcmp (var, \"alpha\") == 0)\n pMlpP->alpha = atof (value);\n if (strcmp (var, \"trainingMode\") == 0)\n pMlpP->trainingMode = atoi (value);\n if (strcmp (var, \"verboseOutput\") == 0)\n pMlpP->verboseOutput = atoi (value);\n }\n } /*while */\n fclose (fp);\n } /*if */\n else\n {\n return -2;\n }\n return 0;\n}\n\nint initializeMlpNet (\n struct mlp_init_values *pMlpInitVals,\n struct mlp_param *pMlpParam, \n double a,\n double aOut,\n int weightNormalizedInitialization,\n int thresholdZeroInitialization,\n uint32_t micro_max,\n unsigned int seed)\n{\n int ret;\n uint16_t i, l;\n struct mlp_vars *pMlpV = NULL;\n\n if ((!pMlpInitVals->m) || (!pMlpInitVals->h) || (!pMlpInitVals->n) || (!pMlpInitVals->nrHiddenLayers))\n return -2;\n\n pMlpV = malloc (sizeof (*pMlpV));\n if (pMlpV == NULL)\n {\n printf (\"### not enough memory to allocate pMlpV.\\n\");\n return -3;\n }\n\n pMlpV->mlpIv.m = pMlpInitVals->m;\n pMlpV->mlpIv.nrHiddenLayers = pMlpInitVals->nrHiddenLayers;\n \n for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)\n pMlpV->mlpIv.h[l] = pMlpInitVals->h[l];\n\n pMlpV->mlpIv.n = pMlpInitVals->n;\n\n pMlpV->mlpIv.transFktTypeHidden = pMlpInitVals->transFktTypeHidden;\n pMlpV->mlpIv.transFktTypeOutput = pMlpInitVals->transFktTypeOutput;\n pMlpV->mlpIv.hasThresholdOutput = pMlpInitVals->hasThresholdOutput;\n pMlpV->a = a;\n pMlpV->aOut = aOut;\n pMlpV->weightNormalizedInitialization = weightNormalizedInitialization;\n pMlpV->thresholdZeroInitialization = thresholdZeroInitialization;\n pMlpV->micro_max = micro_max;\n\n ret = initializeWeights (pMlpV, 0, seed);\n if (ret)\n {\n free (pMlpV);\n return -4;\n }\n\n /*Speicher allozieren fuer eta[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m+1][pMlpV->mlpIv.h[l]] */\n pMlpV->eta_w = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->eta_w == NULL)\n {\n printf (\"### not enough memory to allocate eta_w.\\n\");\n return -5;\n }\n /*Speicher allozieren fuer desc_w[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m+1][pMlpV->mlpIv.h[l]] */\n pMlpV->desc_w = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->desc_w == NULL)\n {\n printf (\"### not enough memory to allocate desc_w.\\n\");\n return -6;\n }\n /*Speicher allozieren fuer delta_w1[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.m+1][pMlpV->mlpIv.h[l]] */\n pMlpV->delta_w1 = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->delta_w1 == NULL)\n {\n printf (\"### not enough memory to allocate delta_w1.\\n\");\n return -7;\n }\n /*Speicher allozieeren fuer u[pMlpV->mlpIv.nrHiddenLayers][pMlpV->mlpIv.h[l]] */\n pMlpV->u = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->u == NULL)\n {\n printf (\"### not enough memory to allocate u.\\n\");\n return -8;\n }\n /*Speicher allozieren fuer pData->y[pMlpV->mlpIv.nrHiddenLayers][micro_max][pMlpV->mlpIv.h[l]] */\n pMlpV->y = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->y == NULL)\n {\n printf (\"### not enough memory to allocate y.\\n\");\n return -9;\n }\n pMlpV->y_tsignal = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->y_tsignal == NULL)\n {\n printf (\"### not enough memory to allocate y_tsignal.\\n\");\n return -9;\n }\n /*Speicher allozieeren fuer delta[pMlpV->mlpIv.nrHiddenLayers][micro_max][pMlpV->mlpIv.h[l]] */\n pMlpV->delta = (double ***) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double **));\n if (pMlpV->delta == NULL)\n {\n printf (\"### not enough memory to allocate delta.\\n\");\n return -10;\n }\n /*Speicher allozieeren fuer delta[pMlpV->mlpIv.nrHiddenLayers][micro_max][pMlpV->mlpIv.h[l]] */\n pMlpV->gradvec = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));\n if (pMlpV->gradvec == NULL)\n {\n printf (\"### not enough memory to allocate gradvec.\\n\");\n return -10;\n }\n pMlpV->gradvec_tsignal = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));\n if (pMlpV->gradvec_tsignal == NULL)\n {\n printf (\"### not enough memory to allocate gradvec_tsignal.\\n\");\n return -10;\n }\n pMlpV->grad2vec = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));\n if (pMlpV->grad2vec == NULL)\n {\n printf (\"### not enough memory to allocate grad2vec.\\n\");\n return -10;\n }\n \n pMlpV->gradientTrace = (double ****) malloc ((pMlpV->mlpIv.nrHiddenLayers) * sizeof (double ***));\n if (pMlpV->gradientTrace == NULL)\n {\n printf (\"### not enough memory to allocate gradientTrace.\\n\");\n return -10;\n } \n\n for (l = 0; l < pMlpV->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n ret = allocateMatrix2 (&pMlpV->eta_w[l], pMlpV->mlpIv.m + 1, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->desc_w[l], pMlpV->mlpIv.m + 1, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->delta_w1[l], pMlpV->mlpIv.m + 1, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n }\n else\n {\n ret = allocateMatrix2 (&pMlpV->eta_w[l], pMlpV->mlpIv.h[l - 1] + 1, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->desc_w[l], pMlpV->mlpIv.h[l - 1] + 1, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->delta_w1[l], pMlpV->mlpIv.h[l - 1] + 1, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n }\n\n if(l == 0)\n {\n if(l == pMlpV->mlpIv.nrHiddenLayers - 1)\n {\n // Naechste Schicht ist die Ausgabeschicht\n \n ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.n, pMlpV->mlpIv.m + 1);\n if (ret)\n return -2;\n }\n else\n {\n // Naechste Schicht ist die naechste Zwischenschicht\n\n ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1], pMlpV->mlpIv.m + 1);\n if (ret)\n return -2; \n }\n }\n else\n {\n if(l == pMlpV->mlpIv.nrHiddenLayers - 1)\n {\n // Naechste Schicht ist die Ausgabeschicht\n \n ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.n, pMlpV->mlpIv.h[l - 1] + 1);\n if (ret)\n return -2; \n }\n else\n {\n // Naechste Schicht ist die naechste Zwischenschicht\n\n ret = allocateArray3 (&pMlpV->gradvec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradvec_tsignal[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1]);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->gradientTrace[l], pMlpV->mlpIv.h[l], pMlpV->mlpIv.h[l + 1], pMlpV->mlpIv.h[l - 1] + 1);\n if (ret)\n return -2; \n }\n }\n\n ret = allocateMatrix2 (&pMlpV->u[l], micro_max, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->y[l], micro_max, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->y_tsignal[l], micro_max, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->delta[l], micro_max, pMlpV->mlpIv.h[l]);\n if (ret)\n return -2;\n ret = allocateArray3 (&pMlpV->grad2vec[l], micro_max, pMlpV->mlpIv.h[l], pMlpV->mlpIv.n);\n if (ret)\n return -2; \n } /* for l */\n\n ret = allocateMatrix2 (&pMlpV->gradientTrace2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);\n if (ret)\n return -2; \n ret = allocateMatrix2 (&pMlpV->eta_w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->desc_w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->delta_w2, pMlpV->mlpIv.h[pMlpV->mlpIv.nrHiddenLayers - 1] + 1, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateVector (&pMlpV->u2, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->y2, micro_max, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->y2_prime, micro_max, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->delta2, micro_max, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->gradvec2, micro_max, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->gradvec2_tsignal, micro_max, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n ret = allocateMatrix2 (&pMlpV->grad2vec2, micro_max, pMlpV->mlpIv.n);\n if (ret)\n return -2;\n\n if (nRegisteredMlps < maxMlps)\n {\n nRegisteredMlps++;\n for (i = 0; i < maxMlps; i++)\n {\n if (mlpRegistered[i] == 0)\n {\n pMlpVA[i] = pMlpV;\n mlpRegistered[i] = 1;\n break;\n }\n }\n }\n else\n {\n printf (\"### maximum number of mlps exceeded.\\n\");\n return -33;\n }\n\n setMlpParam(i, pMlpParam);\n mlp_reset_specialvars (i);\n clearGradientTrace(i);\n \n return i;\n}\n\n\nint cleanupMlpNet (\n int mlpfd)\n{\n uint16_t l;\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n /*Free everything for the hidden layer... */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n freeMatrix2 (pMlpVA[mlpfd]->w[l], pMlpVA[mlpfd]->mlpIv.m);\n freeMatrix2 (pMlpVA[mlpfd]->w_prime[l], pMlpVA[mlpfd]->mlpIv.m);\n }\n else\n {\n freeMatrix2 (pMlpVA[mlpfd]->w[l], pMlpVA[mlpfd]->mlpIv.h[l - 1]);\n freeMatrix2 (pMlpVA[mlpfd]->w_prime[l], pMlpVA[mlpfd]->mlpIv.h[l - 1]);\n }\n freeVector (pMlpVA[mlpfd]->theta[l]);\n freeVector (pMlpVA[mlpfd]->theta_prime[l]);\n }\n\n freeMatrix2 (pMlpVA[mlpfd]->w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]);\n freeMatrix2 (pMlpVA[mlpfd]->w2_prime, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]);\n \n freeVector (pMlpVA[mlpfd]->theta2);\n freeVector (pMlpVA[mlpfd]->theta2_prime);\n\n free (pMlpVA[mlpfd]->w);\n free (pMlpVA[mlpfd]->w_prime);\n\n free (pMlpVA[mlpfd]->theta);\n free (pMlpVA[mlpfd]->theta_prime);\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n freeMatrix2 (pMlpVA[mlpfd]->eta_w[l], pMlpVA[mlpfd]->mlpIv.m + 1);\n freeMatrix2 (pMlpVA[mlpfd]->desc_w[l], pMlpVA[mlpfd]->mlpIv.m + 1);\n freeMatrix2 (pMlpVA[mlpfd]->delta_w1[l], pMlpVA[mlpfd]->mlpIv.m + 1);\n }\n else\n {\n freeMatrix2 (pMlpVA[mlpfd]->eta_w[l], pMlpVA[mlpfd]->mlpIv.h[l - 1] + 1);\n freeMatrix2 (pMlpVA[mlpfd]->desc_w[l], pMlpVA[mlpfd]->mlpIv.h[l - 1] + 1);\n freeMatrix2 (pMlpVA[mlpfd]->delta_w1[l], pMlpVA[mlpfd]->mlpIv.h[l - 1] + 1);\n }\n\n if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)\n {\n freeArray3 (pMlpVA[mlpfd]->gradientTrace[l], pMlpVA[mlpfd]->mlpIv.h[l], pMlpVA[mlpfd]->mlpIv.n);\n }\n else\n {\n freeArray3 (pMlpVA[mlpfd]->gradientTrace[l], pMlpVA[mlpfd]->mlpIv.h[l], pMlpVA[mlpfd]->mlpIv.h[l + 1]); \n }\n\n freeMatrix2 (pMlpVA[mlpfd]->u[l], pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->y[l], pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->y_tsignal[l], pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->delta[l], pMlpVA[mlpfd]->micro_max);\n freeArray3 (pMlpVA[mlpfd]->gradvec[l], pMlpVA[mlpfd]->micro_max, pMlpVA[mlpfd]->mlpIv.h[l]);\n freeArray3 (pMlpVA[mlpfd]->gradvec_tsignal[l], pMlpVA[mlpfd]->micro_max, pMlpVA[mlpfd]->mlpIv.h[l]);\n freeArray3 (pMlpVA[mlpfd]->grad2vec[l], pMlpVA[mlpfd]->micro_max, pMlpVA[mlpfd]->mlpIv.h[l]); \n }\n\n freeMatrix2 (pMlpVA[mlpfd]->gradientTrace2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);\n freeMatrix2 (pMlpVA[mlpfd]->eta_w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);\n freeMatrix2 (pMlpVA[mlpfd]->desc_w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);\n freeMatrix2 (pMlpVA[mlpfd]->delta_w2, pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1] + 1);\n freeVector (pMlpVA[mlpfd]->u2);\n freeMatrix2 (pMlpVA[mlpfd]->y2, pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->y2_prime, pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->delta2, pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->gradvec2, pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->gradvec2_tsignal, pMlpVA[mlpfd]->micro_max);\n freeMatrix2 (pMlpVA[mlpfd]->grad2vec2, pMlpVA[mlpfd]->micro_max);\n\n free (pMlpVA[mlpfd]->eta_w);\n free (pMlpVA[mlpfd]->desc_w);\n free (pMlpVA[mlpfd]->delta_w1);\n free (pMlpVA[mlpfd]->u);\n free (pMlpVA[mlpfd]->y);\n free (pMlpVA[mlpfd]->y_tsignal);\n free (pMlpVA[mlpfd]->delta);\n free (pMlpVA[mlpfd]->gradvec);\n free (pMlpVA[mlpfd]->gradvec_tsignal);\n free (pMlpVA[mlpfd]->grad2vec);\n free (pMlpVA[mlpfd]->gradientTrace);\n \n mlpRegistered[mlpfd] = 0;\n nRegisteredMlps--;\n\n free (pMlpVA[mlpfd]);\n\n return 0;\n}\n\nint outputWeightsStatistics (\n int mlpfd)\n{\n uint16_t k, i, i2, j, l;\n uint32_t index;\n double *vals;\n double mean, variance;\n \n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n printf(\"'Zero' weights are in interval [-%lf,%lf]\\n\", ZERO_PRECISION, ZERO_PRECISION);\n \n unsigned long nZeroWeights;\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n printf (\"weights hidden layer (%i):\\n\", l);\n if (l == 0)\n {\n index = 0;\n vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.m * pMlpVA[mlpfd]->mlpIv.h[l]);\n nZeroWeights = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n vals[index] = pMlpVA[mlpfd]->w[l][k][i];\n index++;\n if(pMlpVA[mlpfd]->w[l][k][i] >= - ZERO_PRECISION && pMlpVA[mlpfd]->w[l][k][i] <= ZERO_PRECISION)\n nZeroWeights++;\n }\n }\n mean = gsl_stats_mean (vals, 1, index);\n variance = gsl_stats_variance (vals, 1, index);\n\n printf (\"The sample mean is %g\\n\", mean);\n printf (\"The estimated variance is %g\\n\", variance);\n\n free (vals);\n index = 0;\n }\n else\n {\n vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.h[l - 1] * pMlpVA[mlpfd]->mlpIv.h[l]);\n nZeroWeights = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n vals[index] = pMlpVA[mlpfd]->w[l][i2][i];\n index++;\n if(pMlpVA[mlpfd]->w[l][i2][i] >= - ZERO_PRECISION && pMlpVA[mlpfd]->w[l][i2][i] <= ZERO_PRECISION)\n nZeroWeights++; \n }\n }\n mean = gsl_stats_mean (vals, 1, index);\n variance = gsl_stats_variance (vals, 1, index);\n\n printf (\"The sample mean is %g\\n\", mean);\n printf (\"The estimated variance is %g\\n\", variance);\n\n free (vals);\n index = 0;\n }\n printf (\"bias hidden layer (%i):\\n\", l);\n vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.h[l]);\n nZeroWeights = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n vals[index] = pMlpVA[mlpfd]->theta[l][i];\n index++;\n if(pMlpVA[mlpfd]->theta[l][i] >= - ZERO_PRECISION && pMlpVA[mlpfd]->theta[l][i] <= ZERO_PRECISION)\n nZeroWeights++; \n }\n mean = gsl_stats_mean (vals, 1, index);\n variance = gsl_stats_variance (vals, 1, index);\n\n printf (\"The sample mean is %g\\n\", mean);\n printf (\"The estimated variance is %g\\n\", variance);\n\n free (vals);\n index = 0;\n }\n\n printf (\"weights output layer:\\n\");\n vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.n * pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]);\n nZeroWeights = 0;\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n {\n vals[index] = pMlpVA[mlpfd]->w2[i][j];\n index++;\n if(pMlpVA[mlpfd]->w2[i][j] >= - ZERO_PRECISION && pMlpVA[mlpfd]->w2[i][j] <= ZERO_PRECISION)\n nZeroWeights++; \n }\n }\n mean = gsl_stats_mean (vals, 1, index);\n variance = gsl_stats_variance (vals, 1, index);\n\n printf (\"The sample mean is %g\\n\", mean);\n printf (\"The estimated variance is %g\\n\", variance);\n\n free (vals);\n index = 0;\n\n printf (\"bias output layer:\\n\");\n vals = malloc (sizeof (double) * pMlpVA[mlpfd]->mlpIv.n);\n nZeroWeights = 0;\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n vals[index] = pMlpVA[mlpfd]->theta2[j];\n index++;\n if(pMlpVA[mlpfd]->theta2[j] >= - ZERO_PRECISION && pMlpVA[mlpfd]->theta2[j] <= ZERO_PRECISION)\n nZeroWeights++;\n }\n mean = gsl_stats_mean (vals, 1, index);\n variance = gsl_stats_variance (vals, 1, index);\n\n printf (\"The sample mean is %g\\n\", mean);\n printf (\"The estimated variance is %g\\n\", variance);\n\n free (vals);\n index = 0;\n\n return 0;\n}\n\n\nint outputWeights (\n int mlpfd)\n{\n uint16_t k, i, i2, j, l;\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n printf (\"weights hidden layer (%i)\\n\", l);\n if (l == 0)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n printf (\"%lf \", pMlpVA[mlpfd]->w[l][k][i]);\n }\n printf (\"\\n\");\n }\n }\n else\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n printf (\"%lf \", pMlpVA[mlpfd]->w[l][i2][i]);\n }\n printf (\"\\n\");\n }\n }\n printf (\"bias hidden layer\\n\");\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n printf (\"%lf \", pMlpVA[mlpfd]->theta[l][i]);\n }\n printf (\"\\n\");\n }\n\n printf (\"weights output layer\\n\");\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n {\n printf (\"%lf \", pMlpVA[mlpfd]->w2[i][j]);\n }\n printf (\"\\n\");\n }\n\n printf (\"bias output layer\\n\");\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n printf (\"%lf \", pMlpVA[mlpfd]->theta2[j]);\n }\n printf (\"\\n\");\n\n return 0;\n}\n\n\nint setMlpParam (\n int mlpfd,\n struct mlp_param *pMlpP)\n{\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n if (pMlpP == NULL)\n return -2;\n\n pMlpVA[mlpfd]->mlpP.maxIterations = pMlpP->maxIterations;\n pMlpVA[mlpfd]->mlpP.eta1 = pMlpP->eta1;\n pMlpVA[mlpfd]->mlpP.eta2 = pMlpP->eta2;\n pMlpVA[mlpfd]->mlpP.etaNormalize = pMlpP->etaNormalize;\n pMlpVA[mlpfd]->mlpP.epsilon = pMlpP->epsilon;\n pMlpVA[mlpfd]->mlpP.beta = pMlpP->beta;\n pMlpVA[mlpfd]->mlpP.eta_pos = pMlpP->eta_pos;\n pMlpVA[mlpfd]->mlpP.eta_neg = pMlpP->eta_neg;\n pMlpVA[mlpfd]->mlpP.eta_start = pMlpP->eta_start;\n pMlpVA[mlpfd]->mlpP.eta_max = pMlpP->eta_max;\n pMlpVA[mlpfd]->mlpP.eta_min = pMlpP->eta_min;\n pMlpVA[mlpfd]->mlpP.alpha = pMlpP->alpha;\n pMlpVA[mlpfd]->mlpP.beta_max = pMlpP->beta_max;\n pMlpVA[mlpfd]->mlpP.trainingMode = pMlpP->trainingMode;\n pMlpVA[mlpfd]->mlpP.verboseOutput = pMlpP->verboseOutput;\n\n return 0;\n}\n\n\nint getMlpParam (\n int mlpfd,\n struct mlp_param *pMlpP)\n{\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n if (pMlpP == NULL)\n return -2;\n\n pMlpP->maxIterations = pMlpVA[mlpfd]->mlpP.maxIterations;\n pMlpP->eta1 = pMlpVA[mlpfd]->mlpP.eta1;\n pMlpP->eta2 = pMlpVA[mlpfd]->mlpP.eta2;\n pMlpP->etaNormalize = pMlpVA[mlpfd]->mlpP.etaNormalize;\n pMlpP->epsilon = pMlpVA[mlpfd]->mlpP.epsilon;\n pMlpP->beta = pMlpVA[mlpfd]->mlpP.beta;\n pMlpP->eta_pos = pMlpVA[mlpfd]->mlpP.eta_pos;\n pMlpP->eta_neg = pMlpVA[mlpfd]->mlpP.eta_neg;\n pMlpP->eta_start = pMlpVA[mlpfd]->mlpP.eta_start;\n pMlpP->eta_max = pMlpVA[mlpfd]->mlpP.eta_max;\n pMlpP->eta_min = pMlpVA[mlpfd]->mlpP.eta_min;\n pMlpP->alpha = pMlpVA[mlpfd]->mlpP.alpha;\n pMlpP->beta_max = pMlpVA[mlpfd]->mlpP.beta_max;\n pMlpP->trainingMode = pMlpVA[mlpfd]->mlpP.trainingMode;\n pMlpP->verboseOutput = pMlpVA[mlpfd]->mlpP.verboseOutput;\n\n return 0;\n}\n\n\nint getMlpInitValues (\n int mlpfd,\n struct mlp_init_values *pMlpInitVals)\n{\n uint16_t l;\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n if (pMlpInitVals == NULL)\n return -2;\n\n pMlpInitVals->m = pMlpVA[mlpfd]->mlpIv.m;\n pMlpInitVals->nrHiddenLayers = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers;\n for (l = 0; l < pMlpInitVals->nrHiddenLayers; l++)\n pMlpInitVals->h[l] = pMlpVA[mlpfd]->mlpIv.h[l];\n pMlpInitVals->n = pMlpVA[mlpfd]->mlpIv.n;\n pMlpInitVals->transFktTypeHidden = pMlpVA[mlpfd]->mlpIv.transFktTypeHidden;\n pMlpInitVals->transFktTypeOutput = pMlpVA[mlpfd]->mlpIv.transFktTypeOutput;\n pMlpInitVals->hasThresholdOutput = pMlpVA[mlpfd]->mlpIv.hasThresholdOutput;\n\n return 0;\n}\n\n\nint clearGradientTrace (\n int mlpfd)\n{\n uint16_t k, i, i2, j;\n int32_t l; /*wegen for Schleife => Fehlerrückvermittlung... */\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n { /*m+1 */\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n int maxJ;\n if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)\n maxJ = pMlpVA[mlpfd]->mlpIv.n;\n else\n maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 1];\n \n for (j = 0; j < maxJ; j++)\n pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = 0;\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n { /*h+1 */\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n int maxJ;\n if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)\n maxJ = pMlpVA[mlpfd]->mlpIv.n;\n else\n maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 1];\n \n for (j = 0; j < maxJ; j++) \n pMlpVA[mlpfd]->gradientTrace[l][i][j][i2] = 0;\n }\n }\n }\n }\n\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n { /*h+1 */\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n pMlpVA[mlpfd]->gradientTrace2[i][j] = 0;\n }\n \n return 0; \n}\n\nint mlpSave (\n int mlpfd,\n const char *filename)\n{\n FILE *fp;\n uint16_t i, i2, j, k, l;\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n fp = fopen (filename, \"w\");\n if (fp == NULL)\n return -2;\n\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.m, sizeof (pMlpVA[mlpfd]->mlpIv.m), 1, fp) != 1)\n {\n fclose (fp);\n return -15;\n }\n\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.n, sizeof (pMlpVA[mlpfd]->mlpIv.n), 1, fp) != 1)\n {\n fclose (fp);\n return -17;\n }\n\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.nrHiddenLayers, sizeof (pMlpVA[mlpfd]->mlpIv.nrHiddenLayers), 1, fp) != 1)\n {\n fclose (fp);\n return -17;\n }\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.h[l], sizeof (pMlpVA[mlpfd]->mlpIv.h[l]), 1, fp) != 1)\n {\n fclose (fp);\n return -16;\n }\n }\n\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, sizeof (pMlpVA[mlpfd]->mlpIv.transFktTypeHidden), 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, sizeof (pMlpVA[mlpfd]->mlpIv.transFktTypeOutput), 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n if (fwrite (&pMlpVA[mlpfd]->a, sizeof (pMlpVA[mlpfd]->a), 1, fp) != 1)\n {\n fclose (fp);\n return -6;\n }\n\n if (fwrite (&pMlpVA[mlpfd]->mlpIv.hasThresholdOutput, sizeof (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput), 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n /* TODO: Remove me (kept for compatibility reasons) */\n\n int junksize = sizeof (pMlpVA[mlpfd]->mlpP.maxIterations) + \n sizeof (pMlpVA[mlpfd]->mlpP.eta1) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta2) +\n sizeof (pMlpVA[mlpfd]->mlpP.epsilon) + \n sizeof (pMlpVA[mlpfd]->mlpP.beta) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_pos) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_neg) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_start) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_max) +\n sizeof (pMlpVA[mlpfd]->mlpP.alpha) +\n sizeof (pMlpVA[mlpfd]->mlpP.trainingMode);\n \n uint8_t junk[junksize];\n \n memset(junk, 0, sizeof(uint8_t) * junksize);\n \n if (fwrite (&junk, junksize, 1, fp) != 1)\n {\n fclose (fp);\n return -18;\n }\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (fwrite (&pMlpVA[mlpfd]->w[l][k][i], sizeof (pMlpVA[mlpfd]->w[l][k][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -19;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fwrite (&pMlpVA[mlpfd]->w_prime[l][k][i], sizeof (pMlpVA[mlpfd]->w_prime[l][k][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -19;\n } \n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (fwrite (&pMlpVA[mlpfd]->w[l][i2][i], sizeof (pMlpVA[mlpfd]->w[l][i2][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -19;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fwrite (&pMlpVA[mlpfd]->w_prime[l][i2][i], sizeof (pMlpVA[mlpfd]->w_prime[l][i2][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -19;\n } \n } \n }\n }\n }\n\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (fwrite (&pMlpVA[mlpfd]->theta[l][i], sizeof (pMlpVA[mlpfd]->theta[l][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -20;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fwrite (&pMlpVA[mlpfd]->theta_prime[l][i], sizeof (pMlpVA[mlpfd]->theta_prime[l][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -20;\n } \n } \n }\n }\n\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (fwrite (&pMlpVA[mlpfd]->w2[i][j], sizeof (pMlpVA[mlpfd]->w2[i][j]), 1, fp) != 1)\n {\n fclose (fp);\n return -21;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fwrite (&pMlpVA[mlpfd]->w2_prime[i][j], sizeof (pMlpVA[mlpfd]->w2_prime[i][j]), 1, fp) != 1)\n {\n fclose (fp);\n return -21;\n }\n }\n }\n }\n\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (fwrite (&pMlpVA[mlpfd]->theta2[j], sizeof (pMlpVA[mlpfd]->theta2[j]), 1, fp) != 1)\n {\n fclose (fp);\n return -22;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fwrite (&pMlpVA[mlpfd]->theta2_prime[j], sizeof (pMlpVA[mlpfd]->theta2_prime[j]), 1, fp) != 1)\n {\n fclose (fp);\n return -22;\n }\n }\n }\n \n fclose (fp);\n \n return 0;\n}\n\nint mlpRestore (\n struct mlp_param *pMlpParam,\n const char *filename,\n uint32_t micro_max,\n unsigned int seed)\n{\n FILE *fp;\n uint16_t i, i2, j, k, l;\n struct mlp_init_values mlpInitVals;\n double a;\n int mlpfd;\n\n fp = fopen (filename, \"r\");\n if (fp == NULL)\n return -2;\n\n if (fread (&mlpInitVals.m, sizeof (mlpInitVals.m), 1, fp) != 1)\n {\n fclose (fp);\n return -15;\n }\n\n if (fread (&mlpInitVals.n, sizeof (mlpInitVals.n), 1, fp) != 1)\n {\n fclose (fp);\n return -17;\n }\n\n if (fread (&mlpInitVals.nrHiddenLayers, sizeof (mlpInitVals.nrHiddenLayers), 1, fp) != 1)\n {\n fclose (fp);\n return -18;\n }\n\n for (l = 0; l < mlpInitVals.nrHiddenLayers; l++)\n {\n if (fread (&mlpInitVals.h[l], sizeof (mlpInitVals.h[l]), 1, fp) != 1)\n {\n fclose (fp);\n return -16;\n }\n }\n\n if (fread (&mlpInitVals.transFktTypeHidden, sizeof (mlpInitVals.transFktTypeHidden), 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n if (fread (&mlpInitVals.transFktTypeOutput, sizeof (mlpInitVals.transFktTypeOutput), 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n if (fread (&a, sizeof (a), 1, fp) != 1)\n {\n fclose (fp);\n return -6;\n }\n\n if (fread (&mlpInitVals.hasThresholdOutput, sizeof (mlpInitVals.hasThresholdOutput), 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n /* TODO: Remove the following line in case the output layer should have a configurable\n * threshold. Currently this is done to be able to use the old mlp saves (compatibility reasons) */\n \n mlpInitVals.hasThresholdOutput = 0;\n \n /* TODO: Remove me (compatibility reasons) */\n\n int junksize = sizeof (pMlpVA[mlpfd]->mlpP.maxIterations) + \n sizeof (pMlpVA[mlpfd]->mlpP.eta1) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta2) +\n sizeof (pMlpVA[mlpfd]->mlpP.epsilon) + \n sizeof (pMlpVA[mlpfd]->mlpP.beta) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_pos) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_neg) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_start) +\n sizeof (pMlpVA[mlpfd]->mlpP.eta_max) +\n sizeof (pMlpVA[mlpfd]->mlpP.alpha) +\n sizeof (pMlpVA[mlpfd]->mlpP.trainingMode);\n \n uint8_t junk[junksize];\n \n if (fread (&junk, junksize, 1, fp) != 1)\n {\n fclose (fp);\n return -7;\n }\n\n mlpfd = initializeMlpNet (&mlpInitVals, pMlpParam, a, 0, 0, 0, micro_max, seed);\n if (mlpfd < 0)\n return -1;\n\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (fread (&pMlpVA[mlpfd]->w[l][k][i], sizeof (pMlpVA[mlpfd]->w[l][k][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -20;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fread (&pMlpVA[mlpfd]->w_prime[l][k][i], sizeof (pMlpVA[mlpfd]->w_prime[l][k][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -20;\n }\n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (fread (&pMlpVA[mlpfd]->w[l][i2][i], sizeof (pMlpVA[mlpfd]->w[l][i2][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -21;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fread (&pMlpVA[mlpfd]->w_prime[l][i2][i], sizeof (pMlpVA[mlpfd]->w_prime[l][i2][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -21;\n }\n }\n }\n }\n }\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (fread (&pMlpVA[mlpfd]->theta[l][i], sizeof (pMlpVA[mlpfd]->theta[l][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -22;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fread (&pMlpVA[mlpfd]->theta_prime[l][i], sizeof (pMlpVA[mlpfd]->theta_prime[l][i]), 1, fp) != 1)\n {\n fclose (fp);\n return -22;\n }\n }\n }\n }\n\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (fread (&pMlpVA[mlpfd]->w2[i][j], sizeof (pMlpVA[mlpfd]->w2[i][j]), 1, fp) != 1)\n {\n fclose (fp);\n return -23;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fread (&pMlpVA[mlpfd]->w2_prime[i][j], sizeof (pMlpVA[mlpfd]->w2_prime[i][j]), 1, fp) != 1)\n {\n fclose (fp);\n return -23;\n }\n }\n }\n }\n\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (fread (&pMlpVA[mlpfd]->theta2[j], sizeof (pMlpVA[mlpfd]->theta2[j]), 1, fp) != 1)\n {\n fclose (fp);\n return -24;\n }\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n if (fread (&pMlpVA[mlpfd]->theta2_prime[j], sizeof (pMlpVA[mlpfd]->theta2_prime[j]), 1, fp) != 1)\n {\n fclose (fp);\n return -24;\n }\n }\n }\n\n fclose (fp);\n\n return mlpfd;\n}\n\n\nint mlpOutput (\n int mlpfd,\n unsigned long micro_max,\n uint32_t offset,\n struct train_data *pData)\n{\n unsigned long micro;\n uint16_t k, i, i2, j, l;\n double fkt;\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n if ((pData->x == NULL) || (pData->y == NULL))\n return -2;\n \n for (micro = 0; micro < micro_max; micro++)\n {\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n pMlpVA[mlpfd]->u[l][0][i] = 0;\n \n if (l == 0)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n pMlpVA[mlpfd]->u[l][0][i] += pData->x[micro + offset][k] * pMlpVA[mlpfd]->w[l][k][i];\n }\n else\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n pMlpVA[mlpfd]->u[l][0][i] += pMlpVA[mlpfd]->y[l - 1][0][i2] * pMlpVA[mlpfd]->w[l][i2][i]; \n }\n \n pMlpVA[mlpfd]->u[l][0][i] -= pMlpVA[mlpfd]->theta[l][i];\n\n TRANSFKT (fkt, pMlpVA[mlpfd]->u[l][0][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);\n pMlpVA[mlpfd]->y[l][0][i] = fkt;\n }\n }\n\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n pMlpVA[mlpfd]->u2[j] = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n pMlpVA[mlpfd]->u2[j] += pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][0][i] * pMlpVA[mlpfd]->w2[i][j]; \n\n /* don't subtract the threshold of the neuron if the neuron has a linear transfer function */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n pMlpVA[mlpfd]->u2[j] -= pMlpVA[mlpfd]->theta2[j];\n\n TRANSFKT (fkt, pMlpVA[mlpfd]->u2[j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);\n pData->y[micro + offset][j] = fkt;\n }\n }\n \n return 0;\n}\n\n\ndouble mlp (\n int mlpfd,\n uint32_t micro_max,\n struct train_data *pData,\n // Attention: Following arguments are only used in combination with Reinforcement Learning.\n // Currently, this is for the learning modes: RG_MODE, TDC_MODE\n double alpha,\n double alpha2,\n double gamma,\n double lambda,\n bool updateFirstLayer,\n bool updateSecondLayer,\n double *sampleAlphaDiscount,\n double gradientPrimeFactor,\n double normFactor,\n bool checkGradients,\n bool tdcOwnSummedGradient,\n bool replacingTraces)\n{\n double E = 0, Emin = 999999999, Elast, Emax = 0;\n double fkt;\n uint32_t k, i, i2, j;\n int32_t l; /*wegen for Schleife => Fehlerrückvermittlung... */\n uint32_t micro;\n uint32_t muster;\n double S, deltaW, dS, beta;\n uint32_t numIterations = 0;\n int end = 0;\n int ouch = 0;\n double deltaWeight;\n\n if (pMlpVA[mlpfd] == NULL)\n return -1;\n\n if (micro_max > pMlpVA[mlpfd]->micro_max)\n return -2;\n\n if ((pData->x == NULL) || (pData->y == NULL))\n return -3;\n\n if (!pMlpVA[mlpfd]->mlpP.maxIterations)\n end = 1;\n \n if(pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE ||\n pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n // Must be a nonlinear transfer function in hidden layer\n if(pMlpVA[mlpfd]->mlpIv.transFktTypeHidden > 2)\n return -7;\n \n // Must be a single output neuron\n if(pMlpVA[mlpfd]->mlpIv.n != 1)\n return -8;\n }\n\n // Additional restrictions with TDC\n if(pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n // Must be one hidden layer\n if(pMlpVA[mlpfd]->mlpIv.nrHiddenLayers != 1)\n return -4;\n \n // Must be a single sample\n if(micro_max != 1)\n return -5; \n }\n \n while (!end)\n {\n Elast = E;\n E = 0;\n Emax = 0;\n double Evals[micro_max];\n long z, maxz;\n\n if((pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE) ||\n (pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE))\n maxz = 2;\n else\n maxz = 1;\n \n for(z = maxz - 1; z >=0; z--)\n {\n for (micro = 0; micro < micro_max; micro++)\n {\n if(z && (!pData->hasXPrime[micro]))\n continue;\n \n /*Schritt 2: Berechnung der Netzausgabe y2 (Vorwärtsphase) */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n pMlpVA[mlpfd]->u[l][micro][i] = 0;\n if(l == 0)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n if(!z)\n pMlpVA[mlpfd]->u[l][micro][i] += pData->x[micro][k] * pMlpVA[mlpfd]->w[l][k][i];\n else\n pMlpVA[mlpfd]->u[l][micro][i] += pData->x_prime[micro][k] * pMlpVA[mlpfd]->w[l][k][i];\n }\n }\n else\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n if(!z)\n pMlpVA[mlpfd]->u[l][micro][i] += pMlpVA[mlpfd]->y[l - 1][micro][i2] * pMlpVA[mlpfd]->w[l][i2][i];\n else\n pMlpVA[mlpfd]->u[l][micro][i] += pMlpVA[mlpfd]->y_tsignal[l - 1][micro][i2] * pMlpVA[mlpfd]->w[l][i2][i];\n } \n }\n \n pMlpVA[mlpfd]->u[l][micro][i] -= pMlpVA[mlpfd]->theta[l][i];\n \n TRANSFKT (fkt, pMlpVA[mlpfd]->u[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);\n if(!z)\n pMlpVA[mlpfd]->y[l][micro][i] = fkt;\n else\n pMlpVA[mlpfd]->y_tsignal[l][micro][i] = fkt; \n } /* for i */\n } /* for l */\n\n /* from output layer to last hidden layer */\n\n double E_single_sample = 0;\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n pMlpVA[mlpfd]->u2[j] = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1]; i++)\n {\n if(!z)\n pMlpVA[mlpfd]->u2[j] += pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] * pMlpVA[mlpfd]->w2[i][j];\n else\n pMlpVA[mlpfd]->u2[j] += pMlpVA[mlpfd]->y_tsignal[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] * pMlpVA[mlpfd]->w2[i][j];\n }\n\n /* don't subtract the threshold of the neuron if the neuron has a linear transfer function */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n pMlpVA[mlpfd]->u2[j] -= pMlpVA[mlpfd]->theta2[j];\n \n TRANSFKT (fkt, pMlpVA[mlpfd]->u2[j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);\n\n if ((pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE || pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE) && z)\n {\n pMlpVA[mlpfd]->y2_prime[micro][j] = fkt;\n\n /*Schritt 3: Bestimmung des Fehlers am Netzausgang */\n TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y2_prime[micro][j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);\n }\n else\n {\n pMlpVA[mlpfd]->y2[micro][j] = fkt;\n \n /*Schritt 3: Bestimmung des Fehlers am Netzausgang */\n TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y2[micro][j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);\n }\n \n /* gradient vector for bias output layer\n * iff multiplied by pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] then it is\n * the gradient vector for the weights output layer */\n if(!z)\n {\n double fkt2;\n TRANSFKT_DERIVATIVE_2 (fkt2, pMlpVA[mlpfd]->y2[micro][j], pMlpVA[mlpfd]->mlpIv.transFktTypeOutput, pMlpVA[mlpfd]->mlpP.beta);\n\n pMlpVA[mlpfd]->grad2vec2[micro][j] = fkt2;\n pMlpVA[mlpfd]->gradvec2[micro][j] = fkt;\n pMlpVA[mlpfd]->delta2[micro][j] = (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]) * fkt;\n\n double diff = 0;\n \n if((pMlpVA[mlpfd]->mlpP.trainingMode != RG_MODE && \n pMlpVA[mlpfd]->mlpP.trainingMode != TDC_MODE))\n diff = (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);\n else\n {\n if(!pData->hasXPrime[micro])\n diff = (pData->reward[micro] - pMlpVA[mlpfd]->y2[micro][j]);\n else\n diff = (pData->reward[micro] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[micro][j] + pData->y2[micro][j] - pMlpVA[mlpfd]->y2[micro][j]); \n }\n \n E_single_sample += pow (diff, 2.0);\n if(E_single_sample > Emax)\n Emax = E_single_sample;\n Evals[micro] = E_single_sample;\n }\n else\n pMlpVA[mlpfd]->gradvec2_tsignal[micro][j] = fkt;\n } /* for j */\n \n if(!z)\n E += E_single_sample;\n\n /*Schritt 4: Fehlerrückvermittlung (Rückwärtsphase) */\n\n /* from output layer to last hidden layer l */\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if(!z)\n {\n pMlpVA[mlpfd]->delta[l][micro][i] = 0;\n TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);\n }\n else\n {\n TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y_tsignal[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta); \n }\n \n double fkt2;\n TRANSFKT_DERIVATIVE_2 (fkt2, pMlpVA[mlpfd]->y[l][micro][i], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);\n \n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if(!z)\n {\n pMlpVA[mlpfd]->delta[l][micro][i] += fkt * pMlpVA[mlpfd]->w2[i][j] * pMlpVA[mlpfd]->delta2[micro][j];\n pMlpVA[mlpfd]->gradvec[l][micro][i][j] = fkt * pMlpVA[mlpfd]->w2[i][j] * pMlpVA[mlpfd]->gradvec2[micro][j];\n \n // TODO: Verify the following line\n pMlpVA[mlpfd]->grad2vec[l][micro][i][j] = pMlpVA[mlpfd]->w2[i][j] * (fkt2 * pMlpVA[mlpfd]->gradvec2[micro][j] + 2.0 * pMlpVA[mlpfd]->grad2vec2[micro][j] * pow(fkt, 2.0) * pMlpVA[mlpfd]->w2[i][j]);\n }\n else\n pMlpVA[mlpfd]->gradvec_tsignal[l][micro][i][j] = fkt * pMlpVA[mlpfd]->w2[i][j] * pMlpVA[mlpfd]->gradvec2_tsignal[micro][j];\n }\n } /* for i */\n\n /* from hidden layer l to hidden layer l-1 */\n for (l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 2; l >= 0; l--)\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l]; i2++)\n {\n if(!z)\n {\n pMlpVA[mlpfd]->delta[l][micro][i2] = 0;\n TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y[l][micro][i2], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta);\n }\n else\n {\n TRANSFKT_DERIVATIVE (fkt, pMlpVA[mlpfd]->y_tsignal[l][micro][i2], pMlpVA[mlpfd]->mlpIv.transFktTypeHidden, pMlpVA[mlpfd]->mlpP.beta); \n }\n\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l + 1]; i++)\n {\n int maxJ;\n if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 2)\n {\n // Naechste Schicht ist Ausgabeschicht\n maxJ = pMlpVA[mlpfd]->mlpIv.n;\n }\n else\n {\n // Naechste Schicht ist naechste Zwischenschicht\n maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 2];\n }\n \n if(!z)\n {\n pMlpVA[mlpfd]->delta[l][micro][i2] += fkt * pMlpVA[mlpfd]->w[l + 1][i2][i] * pMlpVA[mlpfd]->delta[l + 1][micro][i];\n \n pMlpVA[mlpfd]->gradvec[l][micro][i2][i] = 0; \n for (j = 0; j < maxJ; j++)\n pMlpVA[mlpfd]->gradvec[l][micro][i2][i] += fkt * pMlpVA[mlpfd]->w[l + 1][i2][i] * pMlpVA[mlpfd]->gradvec[l + 1][micro][i][j];\n }\n else\n {\n pMlpVA[mlpfd]->gradvec_tsignal[l][micro][i2][i] = 0; \n for (j = 0; j < maxJ; j++)\n pMlpVA[mlpfd]->gradvec_tsignal[l][micro][i2][i] += fkt * pMlpVA[mlpfd]->w[l + 1][i2][i] * pMlpVA[mlpfd]->gradvec_tsignal[l + 1][micro][i][j];\n }\n }\n }\n } /* for l */\n \n if(checkGradients)\n {\n if(pMlpVA[mlpfd]->mlpP.trainingMode != ONLINE_MODE)\n {\n printf(\"### checkGradients: Must be run in online mode, check trainingMode in configuration file\\n\");\n return -4;\n }\n \n /* Compares the gradients (gradvec and gradvec2) with the delta values (delta and delta2)\n * This is only for debugging / verifying the internal works of this function.\n * Normally checkGradients shall be false */\n \n for (l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l >= 0; l--)\n {\n if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)\n {\n // Output layer\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n double val = pMlpVA[mlpfd]->gradvec2[micro][j] * (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);\n \n if((float) val != (float) pMlpVA[mlpfd]->delta2[micro][j])\n {\n printf(\"### checkGradients: output layer, (%lf) != (%lf)\\n\", val, pMlpVA[mlpfd]->delta2[micro][j]);\n return -4;\n }\n }\n }\n \n // Last hidden layer\n \n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n double sum = 0;\n \n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n sum += pMlpVA[mlpfd]->gradvec[l][micro][i][j] * (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);\n \n if((float) sum != (float)pMlpVA[mlpfd]->delta[l][micro][i])\n {\n printf(\"### checkGradients: hidden layer (%i), i (%i), (%lf) != (%lf)\\n\", l, i, sum, pMlpVA[mlpfd]->delta[l][micro][i]);\n return -4;\n }\n }\n }\n else\n {\n // Hidden layer before last hidden layer\n\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n double sum = 0;\n \n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l + 1]; i2++)\n {\n for(j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n sum += pMlpVA[mlpfd]->gradvec[l][micro][i][i2] * (pData->y[micro][j] - pMlpVA[mlpfd]->y2[micro][j]);\n }\n \n if((float) sum != (float)pMlpVA[mlpfd]->delta[l][micro][i])\n {\n printf(\"### checkGradients: hidden layer (%i), i (%i), (%lf) != (%lf)\\n\", l, i, sum, pMlpVA[mlpfd]->delta[l][micro][i]);\n return -4;\n }\n }\n }\n }\n }\n \n /*Schritt 5: Lernen */\n if (pMlpVA[mlpfd]->mlpP.trainingMode == ONLINE_MODE)\n {\n /*Error Backpropagation: Online Mode */\n\n /*Adaptiere Gewichte nach Praesentation eines einzelnen Musters micro */\n /*Adaptiere Schwellwerte nach Praesentation eines einzelnen Musters micro */\n\n /*Adaptiere Gewichte der Ausgangsschicht */\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n deltaWeight = pMlpVA[mlpfd]->w2[i][j] + pMlpVA[mlpfd]->mlpP.eta2 * pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][micro][i] * pMlpVA[mlpfd]->delta2[micro][j];\n if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))\n deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);\n pMlpVA[mlpfd]->w2[i][j] = deltaWeight;\n }\n else\n {\n\n /* neurons with linear activation function don't have a threshold */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n deltaWeight = pMlpVA[mlpfd]->theta2[j] - (pMlpVA[mlpfd]->mlpP.eta2 * pMlpVA[mlpfd]->delta2[micro][j]);\n if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))\n deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);\n pMlpVA[mlpfd]->theta2[j] = deltaWeight;\n }\n }\n }\n }\n\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n deltaWeight = pMlpVA[mlpfd]->w[l][k][i] + pMlpVA[mlpfd]->mlpP.eta1 * pData->x[micro][k] * pMlpVA[mlpfd]->delta[l][micro][i];\n if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m))\n deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m) * sign (deltaWeight);\n pMlpVA[mlpfd]->w[l][k][i] = deltaWeight;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n deltaWeight = pMlpVA[mlpfd]->theta[l][i] - (pMlpVA[mlpfd]->mlpP.eta1 * pMlpVA[mlpfd]->delta[l][micro][i]);\n if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m))\n deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.m) * sign (deltaWeight);\n pMlpVA[mlpfd]->theta[l][i] = deltaWeight;\n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n {\n deltaWeight = pMlpVA[mlpfd]->w[l][i2][i] + pMlpVA[mlpfd]->mlpP.eta1 * pMlpVA[mlpfd]->y[l - 1][micro][i2] * pMlpVA[mlpfd]->delta[l][micro][i];\n if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))\n deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);\n pMlpVA[mlpfd]->w[l][i2][i] = deltaWeight;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n deltaWeight = pMlpVA[mlpfd]->theta[l][i] - (pMlpVA[mlpfd]->mlpP.eta1 * pMlpVA[mlpfd]->delta[l][micro][i]);\n if (fabs (deltaWeight) > (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]))\n deltaWeight = (MAX_WEIGHT_ONLINE_MODE / pMlpVA[mlpfd]->mlpIv.h[l]) * sign (deltaWeight);\n pMlpVA[mlpfd]->theta[l][i] = deltaWeight;\n }\n }\n }\n }\n }\n } /* ONLINE_MODE */\n } /* for micro */ /*Schritt 6: Ende Epoche, naechstes Muster, falls noch weitere vorhanden */\n } /* for z */ \n\n if (pMlpVA[mlpfd]->mlpP.trainingMode == BATCH_MODE)\n {\n /*Error Backpropagation: Batch Mode */\n\n /*Adaptiere Gewichte nach Praesentation aller Muster micro */\n\n /*Adaptiere Gewichte der Ausgangsschicht */\n /*Adaptiere Schwellwerte nach Praesentation aller Muster micro */\n\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n \n double eta = pMlpVA[mlpfd]->mlpP.eta2;\n if(pMlpVA[mlpfd]->mlpP.etaNormalize)\n eta /= (double) micro_max;\n \n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n CALC_GRADIENT_WEIGHTS_OUTPUT (S);\n deltaW = -eta * S; \n pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + deltaW;\n }\n else\n {\n /* neurons with linear activation function don't have a threshold */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n CALC_GRADIENT_BIAS_OUTPUT (S);\n deltaW = -eta * S; \n pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + deltaW;\n }\n }\n }\n }\n\n eta = pMlpVA[mlpfd]->mlpP.eta1;\n if(pMlpVA[mlpfd]->mlpP.etaNormalize)\n eta /= (double) micro_max;\n\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);\n deltaW = -eta * S;\n pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + deltaW;\n }\n else\n {\n CALC_GRADIENT_BIAS_HIDDEN (S);\n deltaW = -eta * S;\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;\n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN (S);\n deltaW = -eta * S; \n pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + deltaW;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n deltaW = -eta * S; \n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;\n }\n }\n }\n }\n }\n } /* BATCH_MODE */ \n else if (pMlpVA[mlpfd]->mlpP.trainingMode == RG_MODE)\n {\n double gradient_prime, gradient;\n\n if(updateSecondLayer)\n {\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n /* output neurons with linear activation function don't have a threshold */\n if (i < pMlpVA[mlpfd]->mlpIv.h[l] || pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n S = 0; \n for (muster = 0; muster < micro_max; muster++)\n {\n double diff;\n if(!pData->hasXPrime[muster])\n {\n diff = (pData->reward[muster] - pMlpVA[mlpfd]->y2[muster][j]);\n gradient_prime = 0;\n }\n else\n {\n diff = (pData->reward[muster] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[muster][j] + pData->y2[muster][j] - pMlpVA[mlpfd]->y2[muster][j]);\n\n double tmp = -1.0;\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n tmp = pMlpVA[mlpfd]->y_tsignal[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][muster][i];\n \n gradient_prime = pMlpVA[mlpfd]->gradvec2_tsignal[muster][j] * tmp;\n }\n \n if(sampleAlphaDiscount != NULL)\n diff *= sampleAlphaDiscount[muster];\n \n double tmp = -1.0;\n if(i < pMlpVA[mlpfd]->mlpIv.h[l])\n tmp = pMlpVA[mlpfd]->y[pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1][muster][i];\n\n gradient = pMlpVA[mlpfd]->gradvec2[muster][j] * tmp;\n\n if(replacingTraces)\n {\n // Replacing traces\n if(gradient == 0)\n pMlpVA[mlpfd]->gradientTrace2[i][j] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace2[i][j];\n else\n pMlpVA[mlpfd]->gradientTrace2[i][j] = gradient; \n }\n else\n {\n // Accumulating traces\n pMlpVA[mlpfd]->gradientTrace2[i][j] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace2[i][j] + gradient;\n }\n\n S += (pMlpVA[mlpfd]->gradientTrace2[i][j] - gradientPrimeFactor * gamma * gradient_prime) * diff;\n\n /* Clear gradient traces upon observing a terminal state */\n if(!pData->hasXPrime[muster])\n pMlpVA[mlpfd]->gradientTrace2[i][j] = 0;\n } /* for muster */\n \n deltaW = alpha * S;\n \n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n pMlpVA[mlpfd]->w2[i][j] += deltaW;\n else\n pMlpVA[mlpfd]->theta2[j] += deltaW;\n }\n }\n }\n }\n\n if(updateFirstLayer)\n {\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1; l >= 0; l--)\n {\n int maxK;\n if(l == 0)\n maxK = pMlpVA[mlpfd]->mlpIv.m;\n else\n maxK = pMlpVA[mlpfd]->mlpIv.h[l - 1];\n \n for (k = 0; k <= maxK; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n S = 0;\n for (muster = 0; muster < micro_max; muster++)\n {\n int maxJ;\n if(l == pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1)\n maxJ = pMlpVA[mlpfd]->mlpIv.n;\n else\n maxJ = pMlpVA[mlpfd]->mlpIv.h[l + 1];\n \n for (j = 0; j < maxJ; j++)\n {\n double diff;\n if(!pData->hasXPrime[muster])\n {\n diff = (pData->reward[muster] - pMlpVA[mlpfd]->y2[muster][0]);\n gradient_prime = 0;\n }\n else\n {\n diff = (pData->reward[muster] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[muster][0] + pData->y2[muster][0] - pMlpVA[mlpfd]->y2[muster][0]);\n\n double tmp = -1.0;\n if(l == 0)\n {\n if(k < pMlpVA[mlpfd]->mlpIv.m)\n tmp = pData->x_prime[muster][k];\n }\n else\n {\n if (k < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n tmp = pMlpVA[mlpfd]->y_tsignal[l - 1][muster][k]; \n }\n \n gradient_prime = pMlpVA[mlpfd]->gradvec_tsignal[l][muster][i][j] * tmp;\n }\n\n if(sampleAlphaDiscount != NULL)\n diff *= sampleAlphaDiscount[muster];\n\n double tmp = -1.0;\n if(l == 0)\n {\n if(k < pMlpVA[mlpfd]->mlpIv.m)\n tmp = pData->x[muster][k];\n }\n else\n {\n if (k < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n tmp = pMlpVA[mlpfd]->y[l - 1][muster][k];\n }\n \n gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][j] * tmp;\n \n if(replacingTraces)\n {\n // Replacing traces\n if(gradient == 0)\n pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace[l][i][j][k];\n else\n pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = gradient; \n }\n else\n {\n // Accumulating traces\n pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = gamma * lambda * pMlpVA[mlpfd]->gradientTrace[l][i][j][k] + gradient;\n }\n \n S += (pMlpVA[mlpfd]->gradientTrace[l][i][j][k] - gradientPrimeFactor * gamma * gradient_prime) * diff;\n \n /* Clear gradient traces upon observing a terminal state */\n if(!pData->hasXPrime[muster])\n pMlpVA[mlpfd]->gradientTrace[l][i][j][k] = 0;\n } /* for j */\n } /* for muster */\n \n deltaW = alpha2 * S;\n \n if((l == 0 && k < pMlpVA[mlpfd]->mlpIv.m) || (l > 0 && k < pMlpVA[mlpfd]->mlpIv.h[l - 1]))\n pMlpVA[mlpfd]->w[l][k][i] += deltaW;\n else\n pMlpVA[mlpfd]->theta[l][i] += deltaW;\n } /* for i */\n } /* for k */\n } /* for l */\n } /* updateFirstLayer */\n } /* RG_MODE */\n else if (pMlpVA[mlpfd]->mlpP.trainingMode == TDC_MODE)\n {\n muster = 0; /* We assume that there is only one state transition (sample) */\n \n // Calculate \\theta^T w\n\n double summed_W_Gradient_outputLayer = 0;\n double summed_W_Gradient_outputLayerBias = 0;\n double summed_W_Gradient_hiddenLayer = 0;\n double summed_W_Gradient_hiddenLayerBias = 0;\n if(tdcOwnSummedGradient)\n {\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n summed_W_Gradient_outputLayer += pMlpVA[mlpfd]->gradvec2[muster][0] * pMlpVA[mlpfd]->y[l][muster][i] * pMlpVA[mlpfd]->w2_prime[i][0];\n\n \n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n summed_W_Gradient_outputLayerBias += pMlpVA[mlpfd]->gradvec2[muster][0] * -1.0 * pMlpVA[mlpfd]->theta2_prime[0];\n\n \n l = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n summed_W_Gradient_hiddenLayer += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * pData->x[muster][k] * pMlpVA[mlpfd]->w_prime[l][k][i];\n \n summed_W_Gradient_hiddenLayerBias += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * -1.0 * pMlpVA[mlpfd]->theta_prime[l][i];\n } \n }\n else\n {\n double summed_W_Gradient = 0;\n \n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n summed_W_Gradient += pMlpVA[mlpfd]->gradvec2[muster][0] * pMlpVA[mlpfd]->y[l][muster][i] * pMlpVA[mlpfd]->w2_prime[i][0];\n \n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n summed_W_Gradient += pMlpVA[mlpfd]->gradvec2[muster][0] * -1.0 * pMlpVA[mlpfd]->theta2_prime[0];\n\n l = 0;\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n summed_W_Gradient += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * pData->x[muster][k] * pMlpVA[mlpfd]->w_prime[l][k][i];\n \n summed_W_Gradient += pMlpVA[mlpfd]->gradvec[l][muster][i][0] * -1.0 * pMlpVA[mlpfd]->theta_prime[l][i];\n }\n \n summed_W_Gradient_outputLayer = summed_W_Gradient_outputLayerBias = summed_W_Gradient_hiddenLayer = summed_W_Gradient_hiddenLayerBias = summed_W_Gradient;\n }\n\n double diff;\n if(!pData->hasXPrime[muster])\n diff = (pData->reward[muster] - pMlpVA[mlpfd]->y2[muster][0]);\n else\n diff = (pData->reward[muster] + gamma * normFactor * pMlpVA[mlpfd]->y2_prime[muster][0] + pData->y2[muster][0] - pMlpVA[mlpfd]->y2[muster][0]);\n \n // Adapt the first weights theta\n\n // Output layer\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1; \n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n double gradient = pMlpVA[mlpfd]->gradvec2[muster][0] * pMlpVA[mlpfd]->y[l][muster][i]; \n double gradient2 = pMlpVA[mlpfd]->grad2vec2[muster][0] * pow(pMlpVA[mlpfd]->y[l][muster][i], 2.0);\n double h = (diff - summed_W_Gradient_outputLayer) * gradient2 * pMlpVA[mlpfd]->w2_prime[i][0];\n\n double gradient_prime = 0;\n if(pData->hasXPrime[muster])\n gradient_prime = pMlpVA[mlpfd]->gradvec2_tsignal[muster][0] * pMlpVA[mlpfd]->y_tsignal[l][muster][i]; \n \n S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_outputLayer - h;\n\n deltaW = alpha * S;\n pMlpVA[mlpfd]->w2[i][0] += deltaW;\n }\n else if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n double gradient = pMlpVA[mlpfd]->gradvec2[muster][0] * -1.0;\n double gradient2 = pMlpVA[mlpfd]->grad2vec2[muster][0];\n double h = (diff - summed_W_Gradient_outputLayerBias) * gradient2 * pMlpVA[mlpfd]->theta2_prime[0];\n \n double gradient_prime = 0;\n if(pData->hasXPrime[muster])\n gradient_prime = pMlpVA[mlpfd]->gradvec2_tsignal[muster][0] * -1.0;\n \n S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_outputLayerBias - h;\n\n deltaW = alpha * S;\n pMlpVA[mlpfd]->theta2[0] += deltaW;\n }\n }\n\n // Hidden layer\n l = 0;\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n double gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][0] * pData->x[muster][k]; \n double gradient2 = pMlpVA[mlpfd]->grad2vec[l][muster][i][0] * pow(pData->x[muster][k], 2.0);\n double h = (diff - summed_W_Gradient_hiddenLayer) * gradient2 * pMlpVA[mlpfd]->w_prime[l][k][i];\n \n double gradient_prime = 0;\n if(pData->hasXPrime[muster])\n gradient_prime = pMlpVA[mlpfd]->gradvec_tsignal[l][muster][i][0] * pData->x_prime[muster][k];\n \n S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_hiddenLayer - h;\n\n deltaW = alpha * S;\n pMlpVA[mlpfd]->w[l][k][i] += deltaW;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n double gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][0] * -1.0; \n double gradient2 = pMlpVA[mlpfd]->grad2vec[l][muster][i][0];\n double h = (diff - summed_W_Gradient_hiddenLayerBias) * gradient2 * pMlpVA[mlpfd]->theta_prime[l][i];\n\n double gradient_prime = 0;\n if(pData->hasXPrime[muster])\n gradient_prime = pMlpVA[mlpfd]->gradvec_tsignal[l][muster][i][0] * -1.0;\n\n S = diff * gradient - gamma * gradient_prime * summed_W_Gradient_hiddenLayerBias - h;\n\n deltaW = alpha * S;\n pMlpVA[mlpfd]->theta[l][i] += deltaW;\n }\n } /* for i */\n } /* for k */\n\n // Update the second weights\n\n // Output layer\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1; \n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n double gradient = pMlpVA[mlpfd]->gradvec2[muster][0];\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n gradient *= pMlpVA[mlpfd]->y[l][muster][i];\n pMlpVA[mlpfd]->w2_prime[i][0] += alpha2 * (diff - summed_W_Gradient_outputLayer) * gradient; \n }\n else if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n gradient *= -1.0; \n pMlpVA[mlpfd]->theta2_prime[0] += alpha2 * (diff - summed_W_Gradient_outputLayerBias) * gradient;\n }\n }\n \n // Hidden layer\n l = 0;\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n double gradient = pMlpVA[mlpfd]->gradvec[l][muster][i][0];\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n gradient *= pData->x[muster][k]; \n pMlpVA[mlpfd]->w_prime[l][k][i] += alpha2 * (diff - summed_W_Gradient_hiddenLayer) * gradient;\n }\n else\n {\n gradient *= -1.0; \n pMlpVA[mlpfd]->theta_prime[l][i] += alpha2 * (diff - summed_W_Gradient_hiddenLayerBias) * gradient;\n }\n }\n }\n } /* TDC_MODE */\n else if (pMlpVA[mlpfd]->mlpP.trainingMode == MOMENTUMTERM_MODE)\n {\n /*Error Backpropagation mit Momentumterm: Batch Mode */\n\n /*Adaptiere Gewichte nach Praesentation aller Muster micro */\n /*Adaptiere Schwellwerte nach Praesentation aller Muster micro */\n\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n CALC_GRADIENT_WEIGHTS_OUTPUT (S);\n deltaW = -pMlpVA[mlpfd]->mlpP.eta2 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->w2[i][j] += deltaW;\n pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;\n }\n else\n {\n /* neurons with linear activation function don't have a threshold */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n CALC_GRADIENT_BIAS_OUTPUT (S);\n deltaW = -pMlpVA[mlpfd]->mlpP.eta2 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->theta2[j] += deltaW;\n pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;\n }\n }\n }\n }\n\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);\n deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->w[l][k][i] += deltaW;\n pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->theta[l][i] += deltaW;\n pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;\n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN (S);\n deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->w[l][i2][i] += deltaW;\n pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n deltaW = -pMlpVA[mlpfd]->mlpP.eta1 * S + pMlpVA[mlpfd]->mlpP.alpha * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->theta[l][i] += deltaW;\n pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;\n }\n }\n }\n }\n }\n }\n else if (pMlpVA[mlpfd]->mlpP.trainingMode == QUICKPROP_MODE)\n {\n /*Quickpropagation Mode */\n\n /*Adaptiere Gewichte nach Praesentation aller Muster micro */\n /*Adaptiere Schwellwerte nach Praesentation aller Muster micro */\n\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n CALC_GRADIENT_WEIGHTS_OUTPUT (S);\n if ((pMlpVA[mlpfd]->delta_w2[i][j] == 0) || (S > pMlpVA[mlpfd]->desc_w2[i][j]))\n {\n /*Standard Error Backpropagation Lernregel */\n deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta2 * S;\n }\n else\n {\n /* printf(\"Yes, Quickprop like...\\n\"); */\n if (S > pMlpVA[mlpfd]->desc_w2[i][j])\n {\n printf (\"### Quickprop: S(t) = %f, S(t-1) = %f\\n\", S, pMlpVA[mlpfd]->desc_w2[i][j]);\n return -2;\n }\n beta = S / (pMlpVA[mlpfd]->desc_w2[i][j] - S);\n if (fabs (beta * pMlpVA[mlpfd]->delta_w2[i][j]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w2[i][j]))\n deltaW = beta * pMlpVA[mlpfd]->delta_w2[i][j];\n else\n {\n if (beta < 0)\n deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];\n else\n deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];\n }\n }\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;\n pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + deltaW;\n }\n else\n {\n /* neurons with linear activation function don't have a threshold */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n CALC_GRADIENT_BIAS_OUTPUT (S);\n if ((pMlpVA[mlpfd]->delta_w2[i][j] == 0) || (S > pMlpVA[mlpfd]->desc_w2[i][j]))\n {\n /*Standard Error Backpropagation Lernregel */\n deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta2 * S;\n }\n else\n {\n if (S > pMlpVA[mlpfd]->desc_w2[i][j])\n {\n printf (\"### Quickprop: S(t) = %f, S(t-1) = %f\\n\", S, pMlpVA[mlpfd]->desc_w2[i][j]);\n return -2;\n }\n beta = S / (pMlpVA[mlpfd]->desc_w2[i][j] - S);\n if (fabs (beta * pMlpVA[mlpfd]->delta_w2[i][j]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w2[i][j]))\n deltaW = beta * pMlpVA[mlpfd]->delta_w2[i][j];\n else\n {\n if (beta < 0)\n deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];\n else\n deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w2[i][j];\n }\n }\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n pMlpVA[mlpfd]->delta_w2[i][j] = deltaW;\n pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + deltaW;\n }\n }\n }\n }\n\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);\n if ((pMlpVA[mlpfd]->delta_w1[l][k][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][k][i]))\n {\n /*Standard Error Backpropagation Lernregel */\n deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;\n }\n else\n {\n if (S > pMlpVA[mlpfd]->desc_w[l][k][i])\n {\n printf (\"### Quickprop: S(t) = %f, S(t-1) = %f\\n\", S, pMlpVA[mlpfd]->desc_w[l][k][i]);\n return -2;\n }\n beta = S / (pMlpVA[mlpfd]->desc_w[l][k][i] - S);\n if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][k][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][k][i]))\n deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][k][i];\n else\n {\n if (beta < 0)\n deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];\n else\n deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];\n }\n }\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;\n pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + deltaW;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n if ((pMlpVA[mlpfd]->delta_w1[l][k][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][k][i]))\n {\n /*Standard Error Backpropagation Lernregel */\n deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;\n }\n else\n {\n if (S > pMlpVA[mlpfd]->desc_w[l][k][i])\n {\n printf (\"### Quickprop: S(t) = %f, S(t-1) = %f\\n\", S, pMlpVA[mlpfd]->desc_w[l][k][i]);\n return -2;\n }\n beta = S / (pMlpVA[mlpfd]->desc_w[l][k][i] - S);\n if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][k][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][k][i]))\n deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][k][i];\n else\n {\n if (beta < 0)\n deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];\n else\n deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][k][i];\n }\n }\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n pMlpVA[mlpfd]->delta_w1[l][k][i] = deltaW;\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;\n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN (S);\n if ((pMlpVA[mlpfd]->delta_w1[l][i2][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][i2][i]))\n {\n /*Standard Error Backpropagation Lernregel */\n deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;\n }\n else\n {\n if (S > pMlpVA[mlpfd]->desc_w[l][i2][i])\n {\n printf (\"### Quickprop: S(t) = %f, S(t-1) = %f\\n\", S, pMlpVA[mlpfd]->desc_w[l][i2][i]);\n return -2;\n }\n beta = S / (pMlpVA[mlpfd]->desc_w[l][i2][i] - S);\n if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][i2][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][i2][i]))\n deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n else\n {\n if (beta < 0)\n deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n else\n deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n }\n }\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;\n pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + deltaW;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n if ((pMlpVA[mlpfd]->delta_w1[l][i2][i] == 0) || (S > pMlpVA[mlpfd]->desc_w[l][i2][i]))\n {\n /*Standard Error Backpropagation Lernregel */\n deltaW = -1 * pMlpVA[mlpfd]->mlpP.eta1 * S;\n }\n else\n {\n if (S > pMlpVA[mlpfd]->desc_w[l][i2][i])\n {\n printf (\"### Quickprop: S(t) = %f, S(t-1) = %f\\n\", S, pMlpVA[mlpfd]->desc_w[l][i2][i]);\n return -2;\n }\n beta = S / (pMlpVA[mlpfd]->desc_w[l][i2][i] - S);\n if (fabs (beta * pMlpVA[mlpfd]->delta_w1[l][i2][i]) <= pMlpVA[mlpfd]->mlpP.beta_max * fabs (pMlpVA[mlpfd]->delta_w1[l][i2][i]))\n deltaW = beta * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n else\n {\n if (beta < 0)\n deltaW = -pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n else\n deltaW = pMlpVA[mlpfd]->mlpP.beta_max * pMlpVA[mlpfd]->delta_w1[l][i2][i];\n }\n }\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n pMlpVA[mlpfd]->delta_w1[l][i2][i] = deltaW;\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + deltaW;\n }\n }\n }\n }\n }\n } /* MOMENTUMTERM_MODE */\n else if (pMlpVA[mlpfd]->mlpP.trainingMode == RPROPM_MODE)\n {\n /*Resilient Propagation Minus (RPROP-) Mode */\n\n /*Adaptiere Gewichte nach Praesentation aller Muster micro */\n /*Adaptiere Schwellwerte nach Praesentation aller Muster micro */\n\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n for (i = 0; i <= pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n if (i < pMlpVA[mlpfd]->mlpIv.h[l])\n {\n CALC_GRADIENT_WEIGHTS_OUTPUT (S);\n \n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n }\n\n CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n }\n else\n {\n /* neurons with linear activation function don't have a threshold */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n CALC_GRADIENT_BIAS_OUTPUT (S)\n\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n /* S = 0; */\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n }\n CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->theta2[j], pMlpVA[mlpfd]->eta_w2[i][j]);\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n }\n }\n }\n }\n\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k <= pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (k < pMlpVA[mlpfd]->mlpIv.m)\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n /* S = 0; */\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n }\n CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->w[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n /* S = 0; */\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n }\n CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->theta[l][i], pMlpVA[mlpfd]->eta_w[l][k][i]);\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n }\n }\n }\n }\n else\n {\n for (i2 = 0; i2 <= pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n if (i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1])\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n /* S = 0; */\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n }\n CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->w[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n }\n else\n {\n /*Adaptiere Schwellwerte der Zwischenschichten */\n CALC_GRADIENT_BIAS_HIDDEN (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n /* S = 0; */\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n }\n CALC_RESILIENT_UPDATE_WEIGHT (S, pMlpVA[mlpfd]->theta[l][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n }\n }\n }\n }\n }\n } /* RPROPM_MODE */\n else if (pMlpVA[mlpfd]->mlpP.trainingMode == RPROPP_MODE)\n {\n /*Resilient Propagation Plus (RPROP+) Mode */\n\n /*Adaptiere Gewichte nach Praesentation aller Muster micro */\n\n l = pMlpVA[mlpfd]->mlpIv.nrHiddenLayers - 1;\n /*Adaptiere Gewichte der Ausgangsschicht */\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n CALC_GRADIENT_WEIGHTS_OUTPUT (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);\n pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n if (E > Elast)\n pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] - pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->desc_w2[i][j] = 0;\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);\n pMlpVA[mlpfd]->w2[i][j] = pMlpVA[mlpfd]->w2[i][j] + pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n }\n }\n }\n\n /*Adaptiere Schwellwerte nach Praesentation aller Muster micro */\n\n /* neurons with linear activation function don't have a threshold */\n if (pMlpVA[mlpfd]->mlpIv.hasThresholdOutput)\n {\n\n /*Adaptiere Schwellwerte der Ausgangsschicht */\n for (j = 0; j < pMlpVA[mlpfd]->mlpIv.n; j++)\n {\n CALC_GRADIENT_BIAS_OUTPUT (S);\n i = pMlpVA[mlpfd]->mlpIv.h[l];\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w2[i][j]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);\n pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w2[i][j], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n if (E > Elast)\n pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] - pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->desc_w2[i][j] = 0;\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w2[i][j], pMlpVA[mlpfd]->eta_w2[i][j]);\n pMlpVA[mlpfd]->theta2[j] = pMlpVA[mlpfd]->theta2[j] + pMlpVA[mlpfd]->delta_w2[i][j];\n pMlpVA[mlpfd]->desc_w2[i][j] = S;\n }\n }\n }\n\n /*Adaptiere Gewichte der Zwischenschichten */\n for (l = 0; l < pMlpVA[mlpfd]->mlpIv.nrHiddenLayers; l++)\n {\n if (l == 0)\n {\n for (k = 0; k < pMlpVA[mlpfd]->mlpIv.m; k++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN_FIRSTLAYER (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);\n pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n if (E > Elast)\n pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] - pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->desc_w[l][k][i] = 0;\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);\n pMlpVA[mlpfd]->w[l][k][i] = pMlpVA[mlpfd]->w[l][k][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n }\n }\n }\n /*Adaptiere Schwellwerte der Zwischenschichten */\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n CALC_GRADIENT_BIAS_HIDDEN (S);\n k = pMlpVA[mlpfd]->mlpIv.m;\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][k][i])\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][k][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n if (E > Elast)\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] - pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->desc_w[l][k][i] = 0;\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][k][i], pMlpVA[mlpfd]->eta_w[l][k][i]);\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][k][i];\n pMlpVA[mlpfd]->desc_w[l][k][i] = S;\n }\n }\n }\n else\n {\n for (i2 = 0; i2 < pMlpVA[mlpfd]->mlpIv.h[l - 1]; i2++)\n {\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n CALC_GRADIENT_WEIGHTS_HIDDEN (S);\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);\n pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n if (E > Elast)\n pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] - pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->desc_w[l][i2][i] = 0;\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);\n pMlpVA[mlpfd]->w[l][i2][i] = pMlpVA[mlpfd]->w[l][i2][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n }\n }\n }\n\n /*Adaptiere Schwellwerte der Zwischenschichten */\n for (i = 0; i < pMlpVA[mlpfd]->mlpIv.h[l]; i++)\n {\n CALC_GRADIENT_BIAS_HIDDEN (S);\n i2 = pMlpVA[mlpfd]->mlpIv.h[l - 1];\n /*Berechnung von delta ij */\n CALC_RESILIENT_DS (dS, S, pMlpVA[mlpfd]->desc_w[l][i2][i]);\n if (dS > 0)\n {\n /*S(t-1)*S(t)>0 */\n CALC_RESILIENT_DELTA_INCREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_pos, pMlpVA[mlpfd]->mlpP.eta_max);\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n }\n else if (dS < 0)\n {\n /*S(t-1)*S(t)<0 */\n CALC_RESILIENT_DELTA_DECREASE (pMlpVA[mlpfd]->eta_w[l][i2][i], pMlpVA[mlpfd]->mlpP.eta_neg, pMlpVA[mlpfd]->mlpP.eta_min);\n if (E > Elast)\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] - pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->desc_w[l][i2][i] = 0;\n }\n else\n {\n /*S(t-1)*S(t)=0 */\n CALC_RESILIENT_DELTA_WEIGHT (S, pMlpVA[mlpfd]->delta_w1[l][i2][i], pMlpVA[mlpfd]->eta_w[l][i2][i]);\n pMlpVA[mlpfd]->theta[l][i] = pMlpVA[mlpfd]->theta[l][i] + pMlpVA[mlpfd]->delta_w1[l][i2][i];\n pMlpVA[mlpfd]->desc_w[l][i2][i] = S;\n }\n }\n }\n }\n } /* RPROPP_MODE */\n\n /*Schritt 7: Ende Training */\n numIterations++;\n if (E < Emin)\n Emin = E;\n if ((E <= pMlpVA[mlpfd]->mlpP.epsilon) || (numIterations >= pMlpVA[mlpfd]->mlpP.maxIterations))\n end = 1;\n\n if(pMlpVA[mlpfd]->mlpP.trainingMode != RG_MODE && \n pMlpVA[mlpfd]->mlpP.trainingMode != TDC_MODE)\n {\n if(E <= Elast)\n ouch = 0;\n else if(E > Elast)\n {\n ouch++;\n \n if (ouch > 10)\n {\n ouch = 0;\n printf (\"### Algorithm does not converge (E > Elast), lower the learning rate or stop earlier\\n\");\n }\n }\n }\n \n if (pMlpVA[mlpfd]->mlpP.verboseOutput)\n {\n double mean = gsl_stats_mean (Evals, 1, micro_max);\n double largest = gsl_stats_max (Evals, 1, micro_max);\n gsl_sort (Evals, 1, micro_max);\n double median = gsl_stats_median_from_sorted_data (Evals, 1, micro_max);\n double upperq = gsl_stats_quantile_from_sorted_data (Evals, 1, micro_max, 0.75);\n\n printf (\"number of iterations: %i, E: %lf. Max: %lf, Mean: %lf, Median: %lf, uQuart: %lf\\n\", numIterations, E, largest, mean, median, upperq);\n }\n \n if (pMlpVA[mlpfd]->mlpP.verboseOutput >= 2)\n outputWeights (mlpfd);\n \n } /* while */\n \n if (pMlpVA[mlpfd]->mlpP.verboseOutput)\n outputWeights (mlpfd);\n\n return E;\n}\n", "meta": {"hexsha": "4c8f47f6232fae9d6b6dff658d2dfaabd4f486ac", "size": 149114, "ext": "c", "lang": "C", "max_stars_repo_path": "rlLib/mlpLib.c", "max_stars_repo_name": "stefanfausser/neural-network-ensembles-rl", "max_stars_repo_head_hexsha": "2f5bd9bf7a8fa0ff2b7458facd941dc9cb77b904", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rlLib/mlpLib.c", "max_issues_repo_name": "stefanfausser/neural-network-ensembles-rl", "max_issues_repo_head_hexsha": "2f5bd9bf7a8fa0ff2b7458facd941dc9cb77b904", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rlLib/mlpLib.c", "max_forks_repo_name": "stefanfausser/neural-network-ensembles-rl", "max_forks_repo_head_hexsha": "2f5bd9bf7a8fa0ff2b7458facd941dc9cb77b904", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.4781641168, "max_line_length": 224, "alphanum_fraction": 0.4158764435, "num_tokens": 43306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5888891451980403, "lm_q2_score": 0.3738758367247085, "lm_q1q2_score": 0.22017142189901565}} {"text": "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n/* */\n/* This file is part of the program */\n/* GCG --- Generic Column Generation */\n/* a Dantzig-Wolfe decomposition based extension */\n/* of the branch-cut-and-price framework */\n/* SCIP --- Solving Constraint Integer Programs */\n/* */\n/* Copyright (C) 2010-2019 Operations Research, RWTH Aachen University */\n/* Zuse Institute Berlin (ZIB) */\n/* */\n/* This program is free software; you can redistribute it and/or */\n/* modify it under the terms of the GNU Lesser General Public License */\n/* as published by the Free Software Foundation; either version 3 */\n/* of the License, or (at your option) any later version. */\n/* */\n/* This program is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* GNU 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.*/\n/* */\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/**@file graph_gcg.h\n * @brief Implementation of the graph which supports both node and edge weights.\n * @author Igor Pesic\n */\n\n/*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/\n\n#ifndef GCG_GRAPH_GCG_H_\n#define GCG_GRAPH_GCG_H_\n\n#include \n#include \"bridge.h\"\n\n#ifdef WITH_GSL\n #include \n #include \n#endif\n\nnamespace gcg {\n\nclass EdgeGCG\n{\npublic:\n int src, dest;\n double weight;\n EdgeGCG() {}\n EdgeGCG(int s, int d, double w): src(s), dest(d), weight(w) {}\n} ;\n\nclass GraphGCG: public gcg::Bridge\n{\nprivate:\n bool undirected;\n bool locked; // true if we are not allowed to change the graph anymore\n bool initialized; // true if at least 1 node\n std::vector nodes;\n#ifdef WITH_GSL\n gsl_spmatrix* adj_matrix_sparse;\n gsl_spmatrix* working_adj_matrix; // this one is used ONLY during MCL algorithm!\n#else\n std::vector> adj_matrix; /** For undirected graphs, this matrix is symmetrical */\n#endif\n std::vector edges;\n\npublic:\n\n GraphGCG();\n GraphGCG(int _n_nodes, bool _undirected);\n\n virtual ~GraphGCG();\n virtual SCIP_RETCODE addNNodes(int _n_nodes);\n virtual SCIP_RETCODE addNNodes(int _n_nodes, std::vector weights);\n virtual int getNNodes();\n virtual int getNEdges();\n\n#ifdef WITH_GSL\n virtual gsl_spmatrix* getAdjMatrix();\n virtual void expand(int factor);\n virtual void inflate(double factor);\n virtual void colL1Norm();\n virtual void prune();\n virtual bool stopMCL(int iter);\n virtual std::vector getClustersMCL();\n virtual void initMCL();\n virtual void clearMCL();\n#else\n virtual std::vector> getAdjMatrix();\n#endif\n virtual SCIP_RETCODE getEdges(std::vector& edges);\n virtual SCIP_Bool isEdge(int node_i, int node_j);\n virtual int getNNeighbors(int node);\n virtual std::vector getNeighbors(int node);\n virtual std::vector > getNeighborWeights(int node);\n virtual SCIP_RETCODE addNode(int node, int weight);\n virtual SCIP_RETCODE addNode(); /** Sets node weight to 0 and the ID to the next available. */\n virtual SCIP_RETCODE deleteNode(int node);\n virtual SCIP_RETCODE addEdge(int i, int j); /** Sets edge weight to 1. */\n virtual SCIP_RETCODE addEdge(int node_i, int node_j, double weight);\n virtual SCIP_RETCODE setEdge(int node_i, int node_j, double weight);\n virtual SCIP_RETCODE deleteEdge(int node_i, int node_j);\n virtual int graphGetWeights(int node);\n virtual double getEdgeWeight(int node_i, int node_j);\n\n virtual int edgeComp(const EdgeGCG* a, const EdgeGCG* b);\n\n virtual SCIP_RETCODE flush(); // lock the graph and compresses the adj matrix if we use GSL\n virtual SCIP_RETCODE normalize();\n virtual double getEdgeWeightPercentile(double q);\n};\n\n} /* namespace gcg */\n#endif /* GCG_GRAPH_GCG_H_ */\n", "meta": {"hexsha": "bb70a64eada23fb9a150ab3e3f3b6b2780f076c5", "size": 5078, "ext": "h", "lang": "C", "max_stars_repo_path": "gcg/src/graph/graph_gcg.h", "max_stars_repo_name": "avrech/scipoptsuite-6.0.2-avrech", "max_stars_repo_head_hexsha": "bb4ef31b6e84ff7e1e65cee982acf150739cda86", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gcg/src/graph/graph_gcg.h", "max_issues_repo_name": "avrech/scipoptsuite-6.0.2-avrech", "max_issues_repo_head_hexsha": "bb4ef31b6e84ff7e1e65cee982acf150739cda86", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcg/src/graph/graph_gcg.h", "max_forks_repo_name": "avrech/scipoptsuite-6.0.2-avrech", "max_forks_repo_head_hexsha": "bb4ef31b6e84ff7e1e65cee982acf150739cda86", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-19T01:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T01:15:11.000Z", "avg_line_length": 42.3166666667, "max_line_length": 123, "alphanum_fraction": 0.5582906656, "num_tokens": 1162, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21998478011745345}} {"text": "\n/*\n* -----------------------------------------------------------------\n* Thermochemistry Library --- thrm_lib.c\n* Version: 1.6180\n* Date: Mar 15, 2010\n* ----------------------------------------------------------------- \n* Programmer: Americo Barbosa da Cunha Junior\n* americo.cunhajr@gmail.com\n* -----------------------------------------------------------------\n* Copyright (c) 2010 by Americo Barbosa da Cunha Junior\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 as\n* published by the Free Software Foundation, either version 3 of\n* 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* A copy of the GNU General Public License is available in\n* LICENSE.txt or http://www.gnu.org/licenses/.\n* -----------------------------------------------------------------\n* This is the implementation file of a library\n* with thermochemistry routines.\n* -----------------------------------------------------------------\n*/\n\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../include/cklib.h\"\n#include \"../include/ckthrm.h\"\n#include \"../include/thrm_lib.h\"\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_title\n*\n* This function prints the program title on the screen\n*\n* last update: Oct 20, 2009\n* -----------------------------------------------------------------\n*/\n\nvoid thrm_title()\n{\n time_t curtime = time (NULL);\n struct tm *loctime = localtime (&curtime);\n \n printf(\"\\n\");\n printf(\"=============================================\");\n printf(\"\\n Themochemistry Direct Simulation\\n\");\n printf(\"\\n Author:\");\n printf(\"\\n Americo Barbosa da Cunha Junior --- PUC-Rio\");\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* thrm_mech\n*\n* This function prints on the screen informations about the\n* chemical kinetics mechanism\n*\n* Input:\n* n_e - # of elements\n* n_s - # of species\n* n_r - # of reactions\n* mech - mechanism name\n*\n* last update: Jul 22, 2009\n*------------------------------------------------------------\n*/\n\nvoid thrm_mech(int n_e,int n_s,int n_r,char *mech)\n{ \n printf(\"\\n\");\n printf(\"\\n Thermochemistry Mechanism: %s\", mech);\n printf(\"\\n # of elements = %d\", n_e);\n printf(\"\\n # of species = %d\", n_s);\n printf(\"\\n # of reactions = %d\", n_r);\n printf(\"\\n\");\n printf(\"\\n\");\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* thrm_input\n*\n* This function receives the pmsr parameters\n* and returns GSL_SUCCESS if there is no error.\n*\n* Input:\n* Np - # of particles\n* k - # of discrete time steps\n* delta_t - time step\n* tau_res - residence time\n* tau_mix - mixture time\n* tau_pair - pairwize time\n*\n* Output:\n* success or error\n*\n* last update: Feb 5, 2009\n* -----------------------------------------------------------------\n*/\n\nint thrm_input(int *steps,double *t0,double *delta_t,\n double *Tmax,double *Tmin,double *tol)\n{\n printf(\"\\n Input simulation parameters:\\n\");\n \n printf(\"\\n # of integration steps:\");\n scanf(\"%d\", steps);\n printf(\"\\n %d\\n\", *steps);\n if( *steps <= 0 )\n\treturn GSL_EINVAL;\n\n printf(\"\\n initial time:\");\n scanf(\"%lf\", t0);\n printf(\"\\n %+.1e\\n\", *t0);\n if( *t0 < 0.0 )\n\treturn 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\treturn 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\treturn 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\treturn GSL_EINVAL;\n \n printf(\"\\n tolerance:\");\n scanf(\"%lf\", tol);\n printf(\"\\n %+.1e\\n\", *tol);\n if( *tol <= 0.0 )\n\treturn GSL_EINVAL;\n \n return GSL_SUCCESS;\n}\n/*----------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_alloc\n*\n* This function allocates a struct thermochemistry.\n*\n* Output:\n* thrm - pointer to a struct thermochemistry\n*\n* last update: May 10, 2009\n*------------------------------------------------------------\n*/\n\nthrm_wrk* thrm_alloc()\n{\n thrm_wrk *thrm = NULL;\n \n /* memory allocation for ck_wrk struct */\n thrm = (thrm_wrk *) malloc(sizeof(thrm_wrk));\n if ( thrm == NULL )\n return NULL;\n \n /* setting ck_wrk elements equal NULL and 0.0 */\n thrm->iwk = NULL;\n thrm->rwk = NULL;\n thrm->cwk = NULL;\n thrm->leniwk = 0;\n thrm->lenrwk = 0;\n thrm->lencwk = 0;\n thrm->n_e = 0;\n thrm->n_s = 0;\n thrm->n_r = 0;\n \n return thrm;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_free\n*\n* This function frees the memory used by CK work vectors\n*\n* Input:\n* thrm - pointer to a struct chemkin\n*\n* Output:\n* void\n*\n* last update: Jul 21, 2009\n*------------------------------------------------------------\n*/\n\nvoid thrm_free(void **thrm_bl)\n{\n thrm_wrk* thrm = NULL;\n \n /* checking if thrm_bl is NULL */\n if ( *thrm_bl == NULL )\n return;\n \n thrm = (thrm_wrk *) (*thrm_bl);\n \n /* releasing ck work vectors */\n if( thrm->iwk != NULL )\n {\n free(thrm->iwk);\n thrm->iwk = NULL;\n }\n \n if( thrm->rwk != NULL )\n {\n free(thrm->rwk);\n thrm->rwk = NULL;\n }\n \n if( thrm->cwk != NULL )\n {\n free(thrm->cwk);\n thrm->cwk = NULL;\n }\n \n /* releasing thrm struct */\n free(*thrm_bl);\n *thrm_bl = NULL;\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_init\n*\n* This function initiates chemkin work vectors and the\n* mechanism parameters.\n*\n* Input:\n* thrm - pointer to a struct thermochemistry\n*\n* Output:\n* success or error\n*\n* last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\nint thrm_init(thrm_wrk *thrm)\n{\n if ( thrm == NULL )\n return GSL_EINVAL;\n \n /* calling ck_wrk_len subroutine */\n ck_wrk_len(&(thrm->leniwk),&(thrm->lenrwk),&(thrm->lencwk));\n \n /* memory allocation for ck work vectors */\n thrm->iwk = (int *) malloc( (thrm->leniwk)*sizeof(int));\n thrm->rwk = (double *) malloc( (thrm->lenrwk)*sizeof(double));\n thrm->cwk = (char *) malloc(16*(thrm->lencwk)*sizeof(char));\n if ( thrm->iwk == NULL || thrm->rwk == NULL || thrm->cwk == NULL )\n {\n thrm_free((void **)&thrm);\n return GSL_ENOMEM;\n }\n \n /* calling ck_wrk_init subroutine */\n ck_wrk_init(&(thrm->leniwk),&(thrm->lenrwk),&(thrm->lencwk),\n thrm->iwk,thrm->rwk,thrm->cwk);\n \n /* calling ck_wrk_indx subroutine */\n ck_wrk_indx(thrm->iwk,thrm->rwk,&(thrm->n_e),&(thrm->n_s),&(thrm->n_r));\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_composition\n*\n* This function sets composition vector with values.\n*\n* Input:\n* thrm - pointer to a struct thermochemistry\n*\n* Output:\n* phi - composition vector\n* success or error\n*\n* last update: Mar 2, 2010\n*------------------------------------------------------------\n*/\n\nvoid thrm_composition(thrm_wrk *thrm,gsl_vector *phi)\n{ \n /* calling ck_wrk_comp subroutine */\n ck_composition(&(thrm->n_s),thrm->iwk,thrm->rwk,thrm->cwk,phi->data);\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_page_heading0\n*\n* This function prints the properties names on the screen.\n*\n* Input:\n* thrm - pointer to a struct thermochemistry\n*\n* last update: Nov 6, 2009\n*------------------------------------------------------------\n*/\n\nvoid thrm_page_heading0(FILE *file)\n{ \n fprintf(file,\" t(s) \");\n fprintf(file,\" T(K) \");\n fprintf(file,\" h \");\n fprintf(file,\" p \");\n fprintf(file,\" CO2 \");\n fprintf(file,\" O2 \");\n fprintf(file,\" CO \");\n fprintf(file,\" O \");\n \n return;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_h2T\n*\n* This function computes the mixture temperature for a \n* given enthalpy, pressure and species mass fraction.\n*\n* Input:\n* ck - pointer to a struct chemkin\n* phi - composition vector\n*\n* Output:\n* T - mixture temperature\n*\n* last update: Mar 2, 2010\n*------------------------------------------------------------\n*/\n\ndouble thrm_h2T(thrm_wrk *thrm,double *phi,double Tmax,double Tmin,double tol)\n{\n double T = 0.0;\n \n ck_h2t_bisec(&(thrm->n_s),phi,&Tmax,&Tmin,&tol,thrm->iwk,thrm->rwk,&T);\n /*ck_h2t_newt(&(thrm->n_s),phi,&tol,thrm->iwk,thrm->rwk,&T,&T);*/\n \n return T;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n\n/*\n* -----------------------------------------------------------------\n* thrm_temp_meanvar\n*\n* This function computes the temperature mean and variance\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* ps - system of particle\n* thrm - pointer to a struct thermochemistry\n* Tmax - temperature upper bound\n* Tmin - temperature lower bound\n* tol - tolerance\n* mean - temperature mean\n* var - temperature variance\n*\n* Output:\n* success or error\n*\n* last update: Mar 4, 2010\n* -----------------------------------------------------------------\n*/\n\nvoid thrm_temp_meanvar(int Np,gsl_vector **ps,thrm_wrk *thrm,\n double Tmax,double Tmin,double tol,double *mean,double *var)\n{\n int i;\n double T = 0.0;\n double S = 0.0;\n double M = 0.0;\n double delta = 0.0;\n \n for ( i = 0; i < Np; i++ )\n {\n T = thrm_h2T(thrm,ps[i]->data,Tmax,Tmin,tol);\n\tdelta = T - M;\n\tM += delta/(double) (i+1);\n S += delta*(T - 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* thrm_rrsum\n*\n* This function computes the reaction rates sum given the\n* reaction rate vector.\n*\n* Input:\n* phi - composition vector\n*\n* Output:\n* sum - reaction rates sum\n*\n* last update: Sep 28, 2009\n*------------------------------------------------------------\n*/\n\ndouble thrm_rrsum(gsl_vector *phi)\n{\n unsigned int i;\n double sum = 0.0;\n \n for (i = 2; i < phi->size; i++)\n sum += phi->data[i];\n \n return sum;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_mfsum\n*\n* This function computes the mass fraction sum given a\n* composition vector.\n*\n* Input:\n* phi - composition vector\n*\n* Output:\n* sum - mass fraction sum\n*\n* last update: Sep 24, 2009\n*------------------------------------------------------------\n*/\n\ndouble thrm_mfsum(gsl_vector *phi)\n{\n unsigned int i;\n double sum = 0.0;\n \n for (i = 2; i < phi->size; i++)\n sum += phi->data[i];\n \n return sum;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_mfsign\n*\n* This function checks if the mass fraction\n* components are all positive in a composition vector.\n*\n* Input:\n* phi - composition vector\n*\n* Output:\n* flag - success or fail\n*\n* last update: Sep 28, 2009\n*------------------------------------------------------------\n*/\n\nint thrm_mfsign(gsl_vector *phi)\n{\n unsigned int i;\n int flag = GSL_SUCCESS;\n \n for (i = 2; i < phi->size; i++)\n if ( phi->data[i] < 0.0 )\n flag = GSL_EFAILED;\n \n return flag;\n}\n/*------------------------------------------------------------*/\n\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_eqs\n*\n* This function defines the set of governing diferential\n* equations, one for enthalpy, one for pressure and ns\n* for species mass fractions.\n*\n* Input:\n* t - instant time\n* phi - composition vector\n* Sphi - reaction rate vector\n* thrm_data - pointer to external data\n*\n* Output:\n* success or error\n*\n* last update: Feb 19, 2010\n*------------------------------------------------------------\n*/\n\nint thrm_eqs(double t,N_Vector phi,N_Vector Sphi,void *thrm_data)\n{\n int i, Neq;\n double tol = 1.0e-4;\n double Tmax = 5000.0, Tmin = 100.0;\n double p, T, rho;\n double *phi_data = NULL;\n double *Sphi_data = NULL;\n double *wdot = NULL;\n double *wt = NULL;\n thrm_wrk *thrm = NULL;\n \n /* initiating ck workspace */\n thrm = (thrm_wrk *)thrm_data;\n if ( thrm == NULL )\n return GSL_EINVAL;\n \n /* obtaining phi and Rphi length and components */\n Neq = NV_LENGTH_S(phi);\n phi_data = NV_DATA_S(phi);\n Sphi_data = NV_DATA_S(Sphi);\n \n /* memory allocation for species molar mass and reaction rate vectors */\n wt = (double *) malloc((Neq-2)*sizeof(double));\n wdot = (double *) malloc((Neq-2)*sizeof(double));\n if( wt == NULL || wdot == NULL )\n {\n free(wt);\n free(wdot);\n return GSL_ENOMEM;\n }\n \n /* pressure (dynes/cm^2) */\n p = phi_data[1];\n \n /* mixture temperature (K) */\n T = thrm_h2T(thrm,phi_data,Tmax,Tmin,tol);\n if( T < tol )\n return GSL_EFAILED;\n \n /* mixture density (g/cm^3)*/\n ckrhoy(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,&rho);\n \n /* species molar weight (g/mol) */\n ckwt(thrm->iwk,thrm->rwk,wt);\n \n /* species molar production rates (mol/(cm^3.s)) */\n ckwyp(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,wdot);\n \n /* dh/dt = 0 (isoenthalpic) */\n Sphi_data[0] = 0.0;\n \n /* dp/dt = 0 (isobaric) */\n Sphi_data[1] = 0.0;\n \n /* dY[i]/dt = wdot[i-2].wt[i-2]/rho */\n for ( i = 2; i < Neq; i++ )\n Sphi_data[i] = wdot[i-2]*wt[i-2]/rho;\n \n /* releasing allocated memory */\n free(wdot);\n free(wt);\n phi_data = NULL;\n Sphi_data = NULL;\n wdot = NULL;\n wt = NULL;\n thrm = NULL;\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n\n\n\n/*\n*------------------------------------------------------------\n* thrm_eqs2\n*\n* This function defines the set of governing diferential\n* equations, one for temperature and ns\n* for species mass fractions.\n*\n* Input:\n* t - instant time\n* phi - state vector\n* Sphi - reaction rate vector\n* thrm_data - pointer to external data\n*\n* Output:\n* success or error\n*\n* last update: Dec 28, 2010\n*------------------------------------------------------------\n*/\n\nint thrm_eqs2(double t,N_Vector phi,N_Vector Sphi,void *thrm_data)\n{\n int i, Neq;\n double T, p, rho, cpb, sum = 0.0;\n double *phi_data = NULL;\n double *Sphi_data = NULL;\n double *wdot = NULL;\n double *wt = NULL;\n double *h = NULL;\n thrm_wrk *thrm = NULL;\n \n /* initiating ck workspace */\n thrm = (thrm_wrk *)thrm_data;\n if ( thrm == NULL )\n return GSL_EINVAL;\n \n /* obtaining phi and Rphi length and components */\n Neq = NV_LENGTH_S(phi);\n phi_data = NV_DATA_S(phi);\n Sphi_data = NV_DATA_S(Sphi);\n \n /* memory allocation for species molar mass and reaction rate vectors */\n wt = (double *) malloc((Neq-2)*sizeof(double));\n wdot = (double *) malloc((Neq-2)*sizeof(double));\n h = (double *) malloc((Neq-2)*sizeof(double));\n if( wt == NULL || wdot == NULL || h == NULL)\n {\n free(wt);\n free(wdot);\n\tfree(h);\n return GSL_ENOMEM;\n }\n\n /* mixture temperature (K) */\n T = phi_data[0];\n \n /* pressure (dynes/cm^2) */\n p = phi_data[1];\n \n /* mixture density (g/cm^3)*/\n ckrhoy(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,&rho);\n\n /* mean specific heat at constant pressure (ergs/g.K) */\n ckcpbs(&T,&(phi_data[2]),thrm->iwk,thrm->rwk,&cpb);\n \n /* species molar weight (g/mol) */\n ckwt(thrm->iwk,thrm->rwk,wt);\n \n /* species molar production rates (mol/(cm^3.s)) */\n ckwyp(&p,&T,&(phi_data[2]),thrm->iwk,thrm->rwk,wdot);\n \n /* species specific enthalpy (ergs/g) */\n ckhms(&T,thrm->iwk,thrm->rwk,h);\n \n /* dY[i+2]/dt = wdot[i].wt[i]/rho */\n for ( i = 0; i < thrm->n_s; i++ )\n {\n Sphi_data[i+2] = wdot[i]*wt[i]/rho;\n\tsum += h[i]*wdot[i]*wt[i];\n }\n\n /* dT/dt = -1/(rho.cpb) . sum_i=1^ns h[i].wdot[i].wt[i] */\n Sphi_data[0] = -sum/(rho*cpb);\n \n /* dp/dt = 0 (isobaric) */\n Sphi_data[1] = 0.0;\n \n \n /* releasing allocated memory */\n free(wdot);\n free(wt);\n free(h);\n phi_data = NULL;\n Sphi_data = NULL;\n wdot = NULL;\n wt = NULL;\n h = NULL;\n thrm = NULL;\n \n return GSL_SUCCESS;\n}\n/*------------------------------------------------------------*/\n", "meta": {"hexsha": "44e73a1b02c37b40385c7dd06cef3919d7774346", "size": 18418, "ext": "c", "lang": "C", "max_stars_repo_path": "CRFlowLib-2.0/src/thrm_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-1.0/src/thrm_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-1.0/src/thrm_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": 23.6128205128, "max_line_length": 78, "alphanum_fraction": 0.469866435, "num_tokens": 4977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5698526514141572, "lm_q2_score": 0.38491214448393346, "lm_q1q2_score": 0.21934320609567864}} {"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_line2d.c\n * \\brief run dnest for 2d line analysis.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"brains.h\"\n\n\nDNestFptrSet *fptrset_line2d;\n\n/*!\n * this function does dnest sampling.\n */\nint dnest_line2d(int argc, char **argv)\n{\n int i;\n\n set_blr_model2d();\n \n num_params_blr = num_params_blr_model + num_params_nlr \n + num_params_res + num_params_linecenter + 1; /* include line sys err */\n num_params_blr_tot = num_params_blr;\n num_params = parset.n_con_recon + num_params_blr_tot + num_params_var;\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 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_line2d;\n fptrset_line2d->print_particle = print_particle_line2d;\n fptrset_line2d->restart_action = restart_action_2d;\n fptrset_line2d->accept_action = accept_action_2d;\n fptrset_line2d->kill_action = kill_action_2d;\n fptrset_line2d->perturb = perturb_line2d;\n fptrset_line2d->read_particle = read_particle_line2d;\n \n if(parset.flag_exam_prior != 1)\n {\n fptrset_line2d->log_likelihoods_cal_initial = log_likelihoods_cal_initial_line2d;\n fptrset_line2d->log_likelihoods_cal_restart = log_likelihoods_cal_restart_line2d;\n fptrset_line2d->log_likelihoods_cal = log_likelihoods_cal_line2d;\n }\n else\n {\n fptrset_line2d->log_likelihoods_cal_initial = log_likelihoods_cal_line2d_exam;\n fptrset_line2d->log_likelihoods_cal_restart = log_likelihoods_cal_line2d_exam;\n fptrset_line2d->log_likelihoods_cal = log_likelihoods_cal_line2d_exam;\n }\n \n set_par_range_model2d();\n /* setup the fixed parameters */\n set_par_fix_blrmodel();\n\n /* setup the remaining paramters */\n for(i=num_params_blr_model; i= 2)\n {\n /* width */\n if(parset.width_narrowline_err == 0.0)\n {\n par_fix[num_params_blr_model+1] = 1.0;\n par_fix_val[num_params_blr_model+1] = 0.0;\n } \n /* shift */\n if(parset.shift_narrowline_err == 0.0)\n {\n par_fix[num_params_blr_model+2] = 1.0;\n par_fix_val[num_params_blr_model+2] = 0.0;\n }\n }\n\n /* if flag_fixvar is true, fix continuum variation parameter sigma and tau */\n if(parset.flag_fixvar == 1)\n {\n par_fix[num_params_blr + 1] = 1;\n par_fix_val[num_params_blr + 1] = var_param[1];\n par_fix[num_params_blr + 2] = 1;\n par_fix_val[num_params_blr + 2] = var_param[2];\n }\n\n /* fix systematic error of line */\n if(parset.flag_line_sys_err != 1)\n {\n par_fix[num_params_blr-1] = 1;\n par_fix_val[num_params_blr-1] = log(1.0);\n }\n \n /* fix systematic error of continuum */\n if(parset.flag_con_sys_err != 1)\n {\n par_fix[num_params_blr] = 1;\n par_fix_val[num_params_blr] = log(1.0);\n }\n\n /* fix non-linear response */\n if(parset.flag_nonlinear !=1)\n {\n par_fix[idx_resp + 1] = 1;\n par_fix_val[idx_resp + 1] = 0.0;\n }\n \n print_par_names_model2d();\n\n force_update = parset.flag_force_update;\n if(parset.flag_para_name != 1)\n logz_line2d = dnest(argc, argv, fptrset_line2d, num_params, dnest_options_file);\n \n dnest_free_fptrset(fptrset_line2d);\n return 0;\n}\n\n/*!\n * this function setups parameter ranges.\n * \n * The order of parameters is: \\n\n * I. blr model.............() \\n\n * II. narrow line...........(if flag_narrowline is true)\\n\n * III. spectral broadening...() \\n\n * IV. line center...........(if flag_linecenter is true)\\n\n * V. systematic error......() \\n\n * VI. variability...........() \\n\n * VII. long-term trend.......() \\n\n * VIII.response A and Ag.....() \\n\n * IX. different trend.......(if flag_difftend is ture) \\n\n * X. continuum light curve.() \\n\n */\nvoid set_par_range_model2d()\n{\n int i, j, i1, i2;\n\n /* setup parameter range, BLR parameters first */\n for(i=0; i 0.0)\n {\n par_range_model[i][0] = var_param[i-num_params_blr] - 5.0 * var_param_std[i-num_params_blr];\n par_range_model[i][1] = var_param[i-num_params_blr] + 5.0 * var_param_std[i-num_params_blr];\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][0]);\n par_range_model[i][1] = fmin(par_range_model[i][1], var_range_model[i-num_params_blr][1]);\n\n par_prior_model[i] = GAUSSIAN;\n par_prior_gaussian[i][0] = var_param[i-num_params_blr];\n par_prior_gaussian[i][1] = var_param_std[i-num_params_blr];\n }\n else\n {\n par_range_model[i][0] = var_range_model[i-num_params_blr][0];\n par_range_model[i][1] = var_range_model[i-num_params_blr][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; i< num_params_drw + num_params_trend + num_params_blr; 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 width = ( par_range_model[which][1] - par_range_model[which][0] );\n }\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 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\n return logH;\n}\n\n\n/*!\n * this function calculates likelihood.\n */\ndouble log_likelihoods_cal_line2d_exam(const void *model)\n{\n return 0.0;\n}\n\nvoid accept_action_2d()\n{\n int param;\n double *ptemp;\n\n // the parameter previously updated\n param = which_parameter_update;\n // continuum parameter is updated\n if(param >= num_params_blr)\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 if(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 }\n else if( param < num_params_blr -1 && force_update != 1)\n {\n /* 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 and Fline are unchanged.\n * b) Fline is always changed, except for param = num_params_blr-1.\n */\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 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 }\n } \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_2d(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 return;\n}\n", "meta": {"hexsha": "46d544376614c095454fcc54a6756ce98b6f3897", "size": 19310, "ext": "c", "lang": "C", "max_stars_repo_path": "src/dnest_line2d.c", "max_stars_repo_name": "yzxamos/BRAINS", "max_stars_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/dnest_line2d.c", "max_issues_repo_name": "yzxamos/BRAINS", "max_issues_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/dnest_line2d.c", "max_forks_repo_name": "yzxamos/BRAINS", "max_forks_repo_head_hexsha": "b81cec02a1902df1e544542a970b66d9916a7496", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4809160305, "max_line_length": 128, "alphanum_fraction": 0.6485240808, "num_tokens": 5793, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.37022537869825406, "lm_q1q2_score": 0.21802170144980626}} {"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:52 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 32 */\n\n/*\n * This function contains 764 FP additions, 340 FP multiplications,\n * (or, 618 additions, 194 multiplications, 146 fused multiply/add),\n * 91 stack variables, and 256 memory accesses\n */\nstatic const fftw_real K145142338 = FFTW_KONST(+0.145142338627231183818096187908697637345738139);\nstatic const fftw_real K478470167 = FFTW_KONST(+0.478470167866104432467898943490134984741424603);\nstatic const fftw_real K235698368 = FFTW_KONST(+0.235698368412998824278193812952627188828730159);\nstatic const fftw_real K440960632 = FFTW_KONST(+0.440960632174177514856378431830194174754221310);\nstatic const fftw_real K317196642 = FFTW_KONST(+0.317196642081822749107585806612746685337843547);\nstatic const fftw_real K386505226 = FFTW_KONST(+0.386505226681368480405453304879234900485520646);\nstatic const fftw_real K497592363 = FFTW_KONST(+0.497592363336098443122418476554739960787737434);\nstatic const fftw_real K049008570 = FFTW_KONST(+0.049008570164780300997097781944320922930568337);\nstatic const fftw_real K277785116 = FFTW_KONST(+0.277785116509801112371415406974266437187468595);\nstatic const fftw_real K415734806 = FFTW_KONST(+0.415734806151272618539394188808952878369280406);\nstatic const fftw_real K097545161 = FFTW_KONST(+0.097545161008064133924142434238511120463845809);\nstatic const fftw_real K490392640 = FFTW_KONST(+0.490392640201615224563091118067119518486966865);\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);\nstatic const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618);\nstatic const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731);\nstatic const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191);\nstatic const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812);\nstatic const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);\nstatic const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);\nstatic const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);\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_32(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 + (32 * iostride);\n {\n\t fftw_real tmp685;\n\t fftw_real tmp813;\n\t fftw_real tmp709;\n\t fftw_real tmp761;\n\t fftw_real tmp692;\n\t fftw_real tmp826;\n\t fftw_real tmp712;\n\t fftw_real tmp760;\n\t fftw_real tmp801;\n\t fftw_real tmp821;\n\t fftw_real tmp749;\n\t fftw_real tmp777;\n\t fftw_real tmp804;\n\t fftw_real tmp822;\n\t fftw_real tmp754;\n\t fftw_real tmp778;\n\t fftw_real tmp700;\n\t fftw_real tmp814;\n\t fftw_real tmp716;\n\t fftw_real tmp758;\n\t fftw_real tmp707;\n\t fftw_real tmp815;\n\t fftw_real tmp719;\n\t fftw_real tmp757;\n\t fftw_real tmp794;\n\t fftw_real tmp818;\n\t fftw_real tmp732;\n\t fftw_real tmp774;\n\t fftw_real tmp797;\n\t fftw_real tmp819;\n\t fftw_real tmp737;\n\t fftw_real tmp775;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp679;\n\t fftw_real tmp680;\n\t fftw_real tmp681;\n\t fftw_real tmp682;\n\t fftw_real tmp683;\n\t fftw_real tmp684;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp679 = X[0];\n\t tmp680 = X[16 * iostride];\n\t tmp681 = tmp679 + tmp680;\n\t tmp682 = X[8 * iostride];\n\t tmp683 = X[24 * iostride];\n\t tmp684 = tmp682 + tmp683;\n\t tmp685 = tmp681 + tmp684;\n\t tmp813 = tmp681 - tmp684;\n\t tmp709 = tmp679 - tmp680;\n\t tmp761 = tmp682 - tmp683;\n\t }\n\t {\n\t fftw_real tmp688;\n\t fftw_real tmp710;\n\t fftw_real tmp691;\n\t fftw_real tmp711;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp686;\n\t\t fftw_real tmp687;\n\t\t fftw_real tmp689;\n\t\t fftw_real tmp690;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp686 = X[4 * iostride];\n\t\t tmp687 = X[20 * iostride];\n\t\t tmp688 = tmp686 + tmp687;\n\t\t tmp710 = tmp686 - tmp687;\n\t\t tmp689 = X[28 * iostride];\n\t\t tmp690 = X[12 * iostride];\n\t\t tmp691 = tmp689 + tmp690;\n\t\t tmp711 = tmp689 - tmp690;\n\t }\n\t tmp692 = tmp688 + tmp691;\n\t tmp826 = tmp691 - tmp688;\n\t tmp712 = K707106781 * (tmp710 + tmp711);\n\t tmp760 = K707106781 * (tmp711 - tmp710);\n\t }\n\t {\n\t fftw_real tmp741;\n\t fftw_real tmp799;\n\t fftw_real tmp753;\n\t fftw_real tmp800;\n\t fftw_real tmp744;\n\t fftw_real tmp802;\n\t fftw_real tmp747;\n\t fftw_real tmp803;\n\t fftw_real tmp748;\n\t fftw_real tmp750;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp739;\n\t\t fftw_real tmp740;\n\t\t fftw_real tmp751;\n\t\t fftw_real tmp752;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp739 = X[31 * iostride];\n\t\t tmp740 = X[15 * iostride];\n\t\t tmp741 = tmp739 - tmp740;\n\t\t tmp799 = tmp739 + tmp740;\n\t\t tmp751 = X[7 * iostride];\n\t\t tmp752 = X[23 * iostride];\n\t\t tmp753 = tmp751 - tmp752;\n\t\t tmp800 = tmp751 + tmp752;\n\t }\n\t {\n\t\t fftw_real tmp742;\n\t\t fftw_real tmp743;\n\t\t fftw_real tmp745;\n\t\t fftw_real tmp746;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp742 = X[3 * iostride];\n\t\t tmp743 = X[19 * iostride];\n\t\t tmp744 = tmp742 - tmp743;\n\t\t tmp802 = tmp742 + tmp743;\n\t\t tmp745 = X[27 * iostride];\n\t\t tmp746 = X[11 * iostride];\n\t\t tmp747 = tmp745 - tmp746;\n\t\t tmp803 = tmp745 + tmp746;\n\t }\n\t tmp801 = tmp799 + tmp800;\n\t tmp821 = tmp799 - tmp800;\n\t tmp748 = K707106781 * (tmp744 + tmp747);\n\t tmp749 = tmp741 + tmp748;\n\t tmp777 = tmp741 - tmp748;\n\t tmp804 = tmp802 + tmp803;\n\t tmp822 = tmp803 - tmp802;\n\t tmp750 = K707106781 * (tmp747 - tmp744);\n\t tmp754 = tmp750 - tmp753;\n\t tmp778 = tmp753 + tmp750;\n\t }\n\t {\n\t fftw_real tmp696;\n\t fftw_real tmp714;\n\t fftw_real tmp699;\n\t fftw_real tmp715;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp694;\n\t\t fftw_real tmp695;\n\t\t fftw_real tmp697;\n\t\t fftw_real tmp698;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp694 = X[2 * iostride];\n\t\t tmp695 = X[18 * iostride];\n\t\t tmp696 = tmp694 + tmp695;\n\t\t tmp714 = tmp694 - tmp695;\n\t\t tmp697 = X[10 * iostride];\n\t\t tmp698 = X[26 * iostride];\n\t\t tmp699 = tmp697 + tmp698;\n\t\t tmp715 = tmp697 - tmp698;\n\t }\n\t tmp700 = tmp696 + tmp699;\n\t tmp814 = tmp696 - tmp699;\n\t tmp716 = (K923879532 * tmp714) - (K382683432 * tmp715);\n\t tmp758 = (K382683432 * tmp714) + (K923879532 * tmp715);\n\t }\n\t {\n\t fftw_real tmp703;\n\t fftw_real tmp717;\n\t fftw_real tmp706;\n\t fftw_real tmp718;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp701;\n\t\t fftw_real tmp702;\n\t\t fftw_real tmp704;\n\t\t fftw_real tmp705;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp701 = X[30 * iostride];\n\t\t tmp702 = X[14 * iostride];\n\t\t tmp703 = tmp701 + tmp702;\n\t\t tmp717 = tmp701 - tmp702;\n\t\t tmp704 = X[6 * iostride];\n\t\t tmp705 = X[22 * iostride];\n\t\t tmp706 = tmp704 + tmp705;\n\t\t tmp718 = tmp704 - tmp705;\n\t }\n\t tmp707 = tmp703 + tmp706;\n\t tmp815 = tmp703 - tmp706;\n\t tmp719 = (K923879532 * tmp717) + (K382683432 * tmp718);\n\t tmp757 = (K382683432 * tmp717) - (K923879532 * tmp718);\n\t }\n\t {\n\t fftw_real tmp724;\n\t fftw_real tmp792;\n\t fftw_real tmp736;\n\t fftw_real tmp793;\n\t fftw_real tmp727;\n\t fftw_real tmp795;\n\t fftw_real tmp730;\n\t fftw_real tmp796;\n\t fftw_real tmp731;\n\t fftw_real tmp733;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp722;\n\t\t fftw_real tmp723;\n\t\t fftw_real tmp734;\n\t\t fftw_real tmp735;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp722 = X[iostride];\n\t\t tmp723 = X[17 * iostride];\n\t\t tmp724 = tmp722 - tmp723;\n\t\t tmp792 = tmp722 + tmp723;\n\t\t tmp734 = X[9 * iostride];\n\t\t tmp735 = X[25 * iostride];\n\t\t tmp736 = tmp734 - tmp735;\n\t\t tmp793 = tmp734 + tmp735;\n\t }\n\t {\n\t\t fftw_real tmp725;\n\t\t fftw_real tmp726;\n\t\t fftw_real tmp728;\n\t\t fftw_real tmp729;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp725 = X[5 * iostride];\n\t\t tmp726 = X[21 * iostride];\n\t\t tmp727 = tmp725 - tmp726;\n\t\t tmp795 = tmp725 + tmp726;\n\t\t tmp728 = X[29 * iostride];\n\t\t tmp729 = X[13 * iostride];\n\t\t tmp730 = tmp728 - tmp729;\n\t\t tmp796 = tmp728 + tmp729;\n\t }\n\t tmp794 = tmp792 + tmp793;\n\t tmp818 = tmp792 - tmp793;\n\t tmp731 = K707106781 * (tmp727 + tmp730);\n\t tmp732 = tmp724 + tmp731;\n\t tmp774 = tmp724 - tmp731;\n\t tmp797 = tmp795 + tmp796;\n\t tmp819 = tmp796 - tmp795;\n\t tmp733 = K707106781 * (tmp730 - tmp727);\n\t tmp737 = tmp733 - tmp736;\n\t tmp775 = tmp736 + tmp733;\n\t }\n\t {\n\t fftw_real tmp693;\n\t fftw_real tmp708;\n\t fftw_real tmp809;\n\t fftw_real tmp810;\n\t fftw_real tmp811;\n\t fftw_real tmp812;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp693 = tmp685 + tmp692;\n\t tmp708 = tmp700 + tmp707;\n\t tmp809 = tmp693 + tmp708;\n\t tmp810 = tmp794 + tmp797;\n\t tmp811 = tmp801 + tmp804;\n\t tmp812 = tmp810 + tmp811;\n\t X[8 * iostride] = tmp693 - tmp708;\n\t Y[-8 * iostride] = tmp811 - tmp810;\n\t X[16 * iostride] = tmp809 - tmp812;\n\t X[0] = tmp809 + tmp812;\n\t }\n\t {\n\t fftw_real tmp791;\n\t fftw_real tmp807;\n\t fftw_real tmp806;\n\t fftw_real tmp808;\n\t fftw_real tmp798;\n\t fftw_real tmp805;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp791 = tmp685 - tmp692;\n\t tmp807 = tmp707 - tmp700;\n\t tmp798 = tmp794 - tmp797;\n\t tmp805 = tmp801 - tmp804;\n\t tmp806 = K707106781 * (tmp798 + tmp805);\n\t tmp808 = K707106781 * (tmp805 - tmp798);\n\t X[12 * iostride] = tmp791 - tmp806;\n\t X[4 * iostride] = tmp791 + tmp806;\n\t Y[-4 * iostride] = tmp807 + tmp808;\n\t Y[-12 * iostride] = tmp808 - tmp807;\n\t }\n\t {\n\t fftw_real tmp817;\n\t fftw_real tmp833;\n\t fftw_real tmp827;\n\t fftw_real tmp829;\n\t fftw_real tmp824;\n\t fftw_real tmp828;\n\t fftw_real tmp832;\n\t fftw_real tmp834;\n\t fftw_real tmp816;\n\t fftw_real tmp825;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp816 = K707106781 * (tmp814 + tmp815);\n\t tmp817 = tmp813 + tmp816;\n\t tmp833 = tmp813 - tmp816;\n\t tmp825 = K707106781 * (tmp815 - tmp814);\n\t tmp827 = tmp825 - tmp826;\n\t tmp829 = tmp826 + tmp825;\n\t {\n\t\t fftw_real tmp820;\n\t\t fftw_real tmp823;\n\t\t fftw_real tmp830;\n\t\t fftw_real tmp831;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp820 = (K923879532 * tmp818) + (K382683432 * tmp819);\n\t\t tmp823 = (K923879532 * tmp821) - (K382683432 * tmp822);\n\t\t tmp824 = tmp820 + tmp823;\n\t\t tmp828 = tmp823 - tmp820;\n\t\t tmp830 = (K923879532 * tmp819) - (K382683432 * tmp818);\n\t\t tmp831 = (K382683432 * tmp821) + (K923879532 * tmp822);\n\t\t tmp832 = tmp830 + tmp831;\n\t\t tmp834 = tmp831 - tmp830;\n\t }\n\t X[14 * iostride] = tmp817 - tmp824;\n\t X[2 * iostride] = tmp817 + tmp824;\n\t Y[-6 * iostride] = tmp827 + tmp828;\n\t Y[-10 * iostride] = tmp828 - tmp827;\n\t Y[-2 * iostride] = tmp829 + tmp832;\n\t Y[-14 * iostride] = tmp832 - tmp829;\n\t X[10 * iostride] = tmp833 - tmp834;\n\t X[6 * iostride] = tmp833 + tmp834;\n\t }\n\t {\n\t fftw_real tmp773;\n\t fftw_real tmp789;\n\t fftw_real tmp788;\n\t fftw_real tmp790;\n\t fftw_real tmp780;\n\t fftw_real tmp784;\n\t fftw_real tmp783;\n\t fftw_real tmp785;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp771;\n\t\t fftw_real tmp772;\n\t\t fftw_real tmp786;\n\t\t fftw_real tmp787;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp771 = tmp709 - tmp712;\n\t\t tmp772 = tmp758 + tmp757;\n\t\t tmp773 = tmp771 + tmp772;\n\t\t tmp789 = tmp771 - tmp772;\n\t\t tmp786 = (K831469612 * tmp775) - (K555570233 * tmp774);\n\t\t tmp787 = (K555570233 * tmp777) + (K831469612 * tmp778);\n\t\t tmp788 = tmp786 + tmp787;\n\t\t tmp790 = tmp787 - tmp786;\n\t }\n\t {\n\t\t fftw_real tmp776;\n\t\t fftw_real tmp779;\n\t\t fftw_real tmp781;\n\t\t fftw_real tmp782;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp776 = (K831469612 * tmp774) + (K555570233 * tmp775);\n\t\t tmp779 = (K831469612 * tmp777) - (K555570233 * tmp778);\n\t\t tmp780 = tmp776 + tmp779;\n\t\t tmp784 = tmp779 - tmp776;\n\t\t tmp781 = tmp719 - tmp716;\n\t\t tmp782 = tmp761 + tmp760;\n\t\t tmp783 = tmp781 - tmp782;\n\t\t tmp785 = tmp782 + tmp781;\n\t }\n\t X[13 * iostride] = tmp773 - tmp780;\n\t X[3 * iostride] = tmp773 + tmp780;\n\t Y[-5 * iostride] = tmp783 + tmp784;\n\t Y[-11 * iostride] = tmp784 - tmp783;\n\t Y[-3 * iostride] = tmp785 + tmp788;\n\t Y[-13 * iostride] = tmp788 - tmp785;\n\t X[11 * iostride] = tmp789 - tmp790;\n\t X[5 * iostride] = tmp789 + tmp790;\n\t }\n\t {\n\t fftw_real tmp721;\n\t fftw_real tmp769;\n\t fftw_real tmp768;\n\t fftw_real tmp770;\n\t fftw_real tmp756;\n\t fftw_real tmp764;\n\t fftw_real tmp763;\n\t fftw_real tmp765;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp713;\n\t\t fftw_real tmp720;\n\t\t fftw_real tmp766;\n\t\t fftw_real tmp767;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp713 = tmp709 + tmp712;\n\t\t tmp720 = tmp716 + tmp719;\n\t\t tmp721 = tmp713 + tmp720;\n\t\t tmp769 = tmp713 - tmp720;\n\t\t tmp766 = (K980785280 * tmp737) - (K195090322 * tmp732);\n\t\t tmp767 = (K195090322 * tmp749) + (K980785280 * tmp754);\n\t\t tmp768 = tmp766 + tmp767;\n\t\t tmp770 = tmp767 - tmp766;\n\t }\n\t {\n\t\t fftw_real tmp738;\n\t\t fftw_real tmp755;\n\t\t fftw_real tmp759;\n\t\t fftw_real tmp762;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp738 = (K980785280 * tmp732) + (K195090322 * tmp737);\n\t\t tmp755 = (K980785280 * tmp749) - (K195090322 * tmp754);\n\t\t tmp756 = tmp738 + tmp755;\n\t\t tmp764 = tmp755 - tmp738;\n\t\t tmp759 = tmp757 - tmp758;\n\t\t tmp762 = tmp760 - tmp761;\n\t\t tmp763 = tmp759 - tmp762;\n\t\t tmp765 = tmp762 + tmp759;\n\t }\n\t X[15 * iostride] = tmp721 - tmp756;\n\t X[iostride] = tmp721 + tmp756;\n\t Y[-7 * iostride] = tmp763 + tmp764;\n\t Y[-9 * iostride] = tmp764 - tmp763;\n\t Y[-iostride] = tmp765 + tmp768;\n\t Y[-15 * iostride] = tmp768 - tmp765;\n\t X[9 * iostride] = tmp769 - tmp770;\n\t X[7 * iostride] = tmp769 + tmp770;\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 + 31) {\n\t fftw_real tmp201;\n\t fftw_real tmp533;\n\t fftw_real tmp653;\n\t fftw_real tmp667;\n\t fftw_real tmp623;\n\t fftw_real tmp637;\n\t fftw_real tmp373;\n\t fftw_real tmp485;\n\t fftw_real tmp343;\n\t fftw_real tmp561;\n\t fftw_real tmp458;\n\t fftw_real tmp508;\n\t fftw_real tmp568;\n\t fftw_real tmp604;\n\t fftw_real tmp441;\n\t fftw_real tmp505;\n\t fftw_real tmp224;\n\t fftw_real tmp636;\n\t fftw_real tmp383;\n\t fftw_real tmp487;\n\t fftw_real tmp536;\n\t fftw_real tmp618;\n\t fftw_real tmp378;\n\t fftw_real tmp486;\n\t fftw_real tmp366;\n\t fftw_real tmp569;\n\t fftw_real tmp564;\n\t fftw_real tmp605;\n\t fftw_real tmp452;\n\t fftw_real tmp509;\n\t fftw_real tmp461;\n\t fftw_real tmp506;\n\t fftw_real tmp248;\n\t fftw_real tmp541;\n\t fftw_real tmp395;\n\t fftw_real tmp491;\n\t fftw_real tmp540;\n\t fftw_real tmp594;\n\t fftw_real tmp390;\n\t fftw_real tmp490;\n\t fftw_real tmp296;\n\t fftw_real tmp555;\n\t fftw_real tmp431;\n\t fftw_real tmp498;\n\t fftw_real tmp552;\n\t fftw_real tmp599;\n\t fftw_real tmp414;\n\t fftw_real tmp501;\n\t fftw_real tmp271;\n\t fftw_real tmp543;\n\t fftw_real tmp406;\n\t fftw_real tmp494;\n\t fftw_real tmp546;\n\t fftw_real tmp595;\n\t fftw_real tmp401;\n\t fftw_real tmp493;\n\t fftw_real tmp319;\n\t fftw_real tmp553;\n\t fftw_real tmp558;\n\t fftw_real tmp600;\n\t fftw_real tmp425;\n\t fftw_real tmp499;\n\t fftw_real tmp434;\n\t fftw_real tmp502;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp183;\n\t fftw_real tmp621;\n\t fftw_real tmp188;\n\t fftw_real tmp620;\n\t fftw_real tmp194;\n\t fftw_real tmp370;\n\t fftw_real tmp199;\n\t fftw_real tmp371;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp183 = X[0];\n\t tmp621 = Y[-31 * iostride];\n\t {\n\t\t fftw_real tmp185;\n\t\t fftw_real tmp187;\n\t\t fftw_real tmp184;\n\t\t fftw_real tmp186;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp185 = X[16 * iostride];\n\t\t tmp187 = Y[-15 * iostride];\n\t\t tmp184 = c_re(W[15]);\n\t\t tmp186 = c_im(W[15]);\n\t\t tmp188 = (tmp184 * tmp185) - (tmp186 * tmp187);\n\t\t tmp620 = (tmp186 * tmp185) + (tmp184 * tmp187);\n\t }\n\t {\n\t\t fftw_real tmp191;\n\t\t fftw_real tmp193;\n\t\t fftw_real tmp190;\n\t\t fftw_real tmp192;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp191 = X[8 * iostride];\n\t\t tmp193 = Y[-23 * iostride];\n\t\t tmp190 = c_re(W[7]);\n\t\t tmp192 = c_im(W[7]);\n\t\t tmp194 = (tmp190 * tmp191) - (tmp192 * tmp193);\n\t\t tmp370 = (tmp192 * tmp191) + (tmp190 * tmp193);\n\t }\n\t {\n\t\t fftw_real tmp196;\n\t\t fftw_real tmp198;\n\t\t fftw_real tmp195;\n\t\t fftw_real tmp197;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp196 = X[24 * iostride];\n\t\t tmp198 = Y[-7 * iostride];\n\t\t tmp195 = c_re(W[23]);\n\t\t tmp197 = c_im(W[23]);\n\t\t tmp199 = (tmp195 * tmp196) - (tmp197 * tmp198);\n\t\t tmp371 = (tmp197 * tmp196) + (tmp195 * tmp198);\n\t }\n\t {\n\t\t fftw_real tmp189;\n\t\t fftw_real tmp200;\n\t\t fftw_real tmp651;\n\t\t fftw_real tmp652;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp189 = tmp183 + tmp188;\n\t\t tmp200 = tmp194 + tmp199;\n\t\t tmp201 = tmp189 + tmp200;\n\t\t tmp533 = tmp189 - tmp200;\n\t\t tmp651 = tmp621 - tmp620;\n\t\t tmp652 = tmp194 - tmp199;\n\t\t tmp653 = tmp651 - tmp652;\n\t\t tmp667 = tmp652 + tmp651;\n\t }\n\t {\n\t\t fftw_real tmp619;\n\t\t fftw_real tmp622;\n\t\t fftw_real tmp369;\n\t\t fftw_real tmp372;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp619 = tmp370 + tmp371;\n\t\t tmp622 = tmp620 + tmp621;\n\t\t tmp623 = tmp619 + tmp622;\n\t\t tmp637 = tmp622 - tmp619;\n\t\t tmp369 = tmp183 - tmp188;\n\t\t tmp372 = tmp370 - tmp371;\n\t\t tmp373 = tmp369 - tmp372;\n\t\t tmp485 = tmp369 + tmp372;\n\t }\n\t }\n\t {\n\t fftw_real tmp325;\n\t fftw_real tmp454;\n\t fftw_real tmp341;\n\t fftw_real tmp439;\n\t fftw_real tmp330;\n\t fftw_real tmp455;\n\t fftw_real tmp336;\n\t fftw_real tmp438;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp322;\n\t\t fftw_real tmp324;\n\t\t fftw_real tmp321;\n\t\t fftw_real tmp323;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp322 = X[31 * iostride];\n\t\t tmp324 = Y[0];\n\t\t tmp321 = c_re(W[30]);\n\t\t tmp323 = c_im(W[30]);\n\t\t tmp325 = (tmp321 * tmp322) - (tmp323 * tmp324);\n\t\t tmp454 = (tmp323 * tmp322) + (tmp321 * tmp324);\n\t }\n\t {\n\t\t fftw_real tmp338;\n\t\t fftw_real tmp340;\n\t\t fftw_real tmp337;\n\t\t fftw_real tmp339;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp338 = X[23 * iostride];\n\t\t tmp340 = Y[-8 * iostride];\n\t\t tmp337 = c_re(W[22]);\n\t\t tmp339 = c_im(W[22]);\n\t\t tmp341 = (tmp337 * tmp338) - (tmp339 * tmp340);\n\t\t tmp439 = (tmp339 * tmp338) + (tmp337 * tmp340);\n\t }\n\t {\n\t\t fftw_real tmp327;\n\t\t fftw_real tmp329;\n\t\t fftw_real tmp326;\n\t\t fftw_real tmp328;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp327 = X[15 * iostride];\n\t\t tmp329 = Y[-16 * iostride];\n\t\t tmp326 = c_re(W[14]);\n\t\t tmp328 = c_im(W[14]);\n\t\t tmp330 = (tmp326 * tmp327) - (tmp328 * tmp329);\n\t\t tmp455 = (tmp328 * tmp327) + (tmp326 * tmp329);\n\t }\n\t {\n\t\t fftw_real tmp333;\n\t\t fftw_real tmp335;\n\t\t fftw_real tmp332;\n\t\t fftw_real tmp334;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp333 = X[7 * iostride];\n\t\t tmp335 = Y[-24 * iostride];\n\t\t tmp332 = c_re(W[6]);\n\t\t tmp334 = c_im(W[6]);\n\t\t tmp336 = (tmp332 * tmp333) - (tmp334 * tmp335);\n\t\t tmp438 = (tmp334 * tmp333) + (tmp332 * tmp335);\n\t }\n\t {\n\t\t fftw_real tmp331;\n\t\t fftw_real tmp342;\n\t\t fftw_real tmp456;\n\t\t fftw_real tmp457;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp331 = tmp325 + tmp330;\n\t\t tmp342 = tmp336 + tmp341;\n\t\t tmp343 = tmp331 + tmp342;\n\t\t tmp561 = tmp331 - tmp342;\n\t\t tmp456 = tmp454 - tmp455;\n\t\t tmp457 = tmp336 - tmp341;\n\t\t tmp458 = tmp456 + tmp457;\n\t\t tmp508 = tmp456 - tmp457;\n\t }\n\t {\n\t\t fftw_real tmp566;\n\t\t fftw_real tmp567;\n\t\t fftw_real tmp437;\n\t\t fftw_real tmp440;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp566 = tmp454 + tmp455;\n\t\t tmp567 = tmp438 + tmp439;\n\t\t tmp568 = tmp566 - tmp567;\n\t\t tmp604 = tmp566 + tmp567;\n\t\t tmp437 = tmp325 - tmp330;\n\t\t tmp440 = tmp438 - tmp439;\n\t\t tmp441 = tmp437 - tmp440;\n\t\t tmp505 = tmp437 + tmp440;\n\t }\n\t }\n\t {\n\t fftw_real tmp206;\n\t fftw_real tmp374;\n\t fftw_real tmp222;\n\t fftw_real tmp381;\n\t fftw_real tmp211;\n\t fftw_real tmp375;\n\t fftw_real tmp217;\n\t fftw_real tmp380;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp203;\n\t\t fftw_real tmp205;\n\t\t fftw_real tmp202;\n\t\t fftw_real tmp204;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp203 = X[4 * iostride];\n\t\t tmp205 = Y[-27 * iostride];\n\t\t tmp202 = c_re(W[3]);\n\t\t tmp204 = c_im(W[3]);\n\t\t tmp206 = (tmp202 * tmp203) - (tmp204 * tmp205);\n\t\t tmp374 = (tmp204 * tmp203) + (tmp202 * tmp205);\n\t }\n\t {\n\t\t fftw_real tmp219;\n\t\t fftw_real tmp221;\n\t\t fftw_real tmp218;\n\t\t fftw_real tmp220;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp219 = X[12 * iostride];\n\t\t tmp221 = Y[-19 * iostride];\n\t\t tmp218 = c_re(W[11]);\n\t\t tmp220 = c_im(W[11]);\n\t\t tmp222 = (tmp218 * tmp219) - (tmp220 * tmp221);\n\t\t tmp381 = (tmp220 * tmp219) + (tmp218 * tmp221);\n\t }\n\t {\n\t\t fftw_real tmp208;\n\t\t fftw_real tmp210;\n\t\t fftw_real tmp207;\n\t\t fftw_real tmp209;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp208 = X[20 * iostride];\n\t\t tmp210 = Y[-11 * iostride];\n\t\t tmp207 = c_re(W[19]);\n\t\t tmp209 = c_im(W[19]);\n\t\t tmp211 = (tmp207 * tmp208) - (tmp209 * tmp210);\n\t\t tmp375 = (tmp209 * tmp208) + (tmp207 * tmp210);\n\t }\n\t {\n\t\t fftw_real tmp214;\n\t\t fftw_real tmp216;\n\t\t fftw_real tmp213;\n\t\t fftw_real tmp215;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp214 = X[28 * iostride];\n\t\t tmp216 = Y[-3 * iostride];\n\t\t tmp213 = c_re(W[27]);\n\t\t tmp215 = c_im(W[27]);\n\t\t tmp217 = (tmp213 * tmp214) - (tmp215 * tmp216);\n\t\t tmp380 = (tmp215 * tmp214) + (tmp213 * tmp216);\n\t }\n\t {\n\t\t fftw_real tmp212;\n\t\t fftw_real tmp223;\n\t\t fftw_real tmp379;\n\t\t fftw_real tmp382;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp212 = tmp206 + tmp211;\n\t\t tmp223 = tmp217 + tmp222;\n\t\t tmp224 = tmp212 + tmp223;\n\t\t tmp636 = tmp223 - tmp212;\n\t\t tmp379 = tmp217 - tmp222;\n\t\t tmp382 = tmp380 - tmp381;\n\t\t tmp383 = tmp379 + tmp382;\n\t\t tmp487 = tmp379 - tmp382;\n\t }\n\t {\n\t\t fftw_real tmp534;\n\t\t fftw_real tmp535;\n\t\t fftw_real tmp376;\n\t\t fftw_real tmp377;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp534 = tmp374 + tmp375;\n\t\t tmp535 = tmp380 + tmp381;\n\t\t tmp536 = tmp534 - tmp535;\n\t\t tmp618 = tmp534 + tmp535;\n\t\t tmp376 = tmp374 - tmp375;\n\t\t tmp377 = tmp206 - tmp211;\n\t\t tmp378 = tmp376 - tmp377;\n\t\t tmp486 = tmp377 + tmp376;\n\t }\n\t }\n\t {\n\t fftw_real tmp348;\n\t fftw_real tmp442;\n\t fftw_real tmp353;\n\t fftw_real tmp443;\n\t fftw_real tmp444;\n\t fftw_real tmp445;\n\t fftw_real tmp359;\n\t fftw_real tmp448;\n\t fftw_real tmp364;\n\t fftw_real tmp449;\n\t fftw_real tmp447;\n\t fftw_real tmp450;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp345;\n\t\t fftw_real tmp347;\n\t\t fftw_real tmp344;\n\t\t fftw_real tmp346;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp345 = X[3 * iostride];\n\t\t tmp347 = Y[-28 * iostride];\n\t\t tmp344 = c_re(W[2]);\n\t\t tmp346 = c_im(W[2]);\n\t\t tmp348 = (tmp344 * tmp345) - (tmp346 * tmp347);\n\t\t tmp442 = (tmp346 * tmp345) + (tmp344 * tmp347);\n\t }\n\t {\n\t\t fftw_real tmp350;\n\t\t fftw_real tmp352;\n\t\t fftw_real tmp349;\n\t\t fftw_real tmp351;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp350 = X[19 * iostride];\n\t\t tmp352 = Y[-12 * iostride];\n\t\t tmp349 = c_re(W[18]);\n\t\t tmp351 = c_im(W[18]);\n\t\t tmp353 = (tmp349 * tmp350) - (tmp351 * tmp352);\n\t\t tmp443 = (tmp351 * tmp350) + (tmp349 * tmp352);\n\t }\n\t tmp444 = tmp442 - tmp443;\n\t tmp445 = tmp348 - tmp353;\n\t {\n\t\t fftw_real tmp356;\n\t\t fftw_real tmp358;\n\t\t fftw_real tmp355;\n\t\t fftw_real tmp357;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp356 = X[27 * iostride];\n\t\t tmp358 = Y[-4 * iostride];\n\t\t tmp355 = c_re(W[26]);\n\t\t tmp357 = c_im(W[26]);\n\t\t tmp359 = (tmp355 * tmp356) - (tmp357 * tmp358);\n\t\t tmp448 = (tmp357 * tmp356) + (tmp355 * tmp358);\n\t }\n\t {\n\t\t fftw_real tmp361;\n\t\t fftw_real tmp363;\n\t\t fftw_real tmp360;\n\t\t fftw_real tmp362;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp361 = X[11 * iostride];\n\t\t tmp363 = Y[-20 * iostride];\n\t\t tmp360 = c_re(W[10]);\n\t\t tmp362 = c_im(W[10]);\n\t\t tmp364 = (tmp360 * tmp361) - (tmp362 * tmp363);\n\t\t tmp449 = (tmp362 * tmp361) + (tmp360 * tmp363);\n\t }\n\t tmp447 = tmp359 - tmp364;\n\t tmp450 = tmp448 - tmp449;\n\t {\n\t\t fftw_real tmp354;\n\t\t fftw_real tmp365;\n\t\t fftw_real tmp562;\n\t\t fftw_real tmp563;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp354 = tmp348 + tmp353;\n\t\t tmp365 = tmp359 + tmp364;\n\t\t tmp366 = tmp354 + tmp365;\n\t\t tmp569 = tmp365 - tmp354;\n\t\t tmp562 = tmp442 + tmp443;\n\t\t tmp563 = tmp448 + tmp449;\n\t\t tmp564 = tmp562 - tmp563;\n\t\t tmp605 = tmp562 + tmp563;\n\t }\n\t {\n\t\t fftw_real tmp446;\n\t\t fftw_real tmp451;\n\t\t fftw_real tmp459;\n\t\t fftw_real tmp460;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp446 = tmp444 - tmp445;\n\t\t tmp451 = tmp447 + tmp450;\n\t\t tmp452 = K707106781 * (tmp446 - tmp451);\n\t\t tmp509 = K707106781 * (tmp446 + tmp451);\n\t\t tmp459 = tmp447 - tmp450;\n\t\t tmp460 = tmp445 + tmp444;\n\t\t tmp461 = K707106781 * (tmp459 - tmp460);\n\t\t tmp506 = K707106781 * (tmp460 + tmp459);\n\t }\n\t }\n\t {\n\t fftw_real tmp230;\n\t fftw_real tmp386;\n\t fftw_real tmp246;\n\t fftw_real tmp393;\n\t fftw_real tmp235;\n\t fftw_real tmp387;\n\t fftw_real tmp241;\n\t fftw_real tmp392;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp227;\n\t\t fftw_real tmp229;\n\t\t fftw_real tmp226;\n\t\t fftw_real tmp228;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp227 = X[2 * iostride];\n\t\t tmp229 = Y[-29 * iostride];\n\t\t tmp226 = c_re(W[1]);\n\t\t tmp228 = c_im(W[1]);\n\t\t tmp230 = (tmp226 * tmp227) - (tmp228 * tmp229);\n\t\t tmp386 = (tmp228 * tmp227) + (tmp226 * tmp229);\n\t }\n\t {\n\t\t fftw_real tmp243;\n\t\t fftw_real tmp245;\n\t\t fftw_real tmp242;\n\t\t fftw_real tmp244;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp243 = X[26 * iostride];\n\t\t tmp245 = Y[-5 * iostride];\n\t\t tmp242 = c_re(W[25]);\n\t\t tmp244 = c_im(W[25]);\n\t\t tmp246 = (tmp242 * tmp243) - (tmp244 * tmp245);\n\t\t tmp393 = (tmp244 * tmp243) + (tmp242 * tmp245);\n\t }\n\t {\n\t\t fftw_real tmp232;\n\t\t fftw_real tmp234;\n\t\t fftw_real tmp231;\n\t\t fftw_real tmp233;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp232 = X[18 * iostride];\n\t\t tmp234 = Y[-13 * iostride];\n\t\t tmp231 = c_re(W[17]);\n\t\t tmp233 = c_im(W[17]);\n\t\t tmp235 = (tmp231 * tmp232) - (tmp233 * tmp234);\n\t\t tmp387 = (tmp233 * tmp232) + (tmp231 * tmp234);\n\t }\n\t {\n\t\t fftw_real tmp238;\n\t\t fftw_real tmp240;\n\t\t fftw_real tmp237;\n\t\t fftw_real tmp239;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp238 = X[10 * iostride];\n\t\t tmp240 = Y[-21 * iostride];\n\t\t tmp237 = c_re(W[9]);\n\t\t tmp239 = c_im(W[9]);\n\t\t tmp241 = (tmp237 * tmp238) - (tmp239 * tmp240);\n\t\t tmp392 = (tmp239 * tmp238) + (tmp237 * tmp240);\n\t }\n\t {\n\t\t fftw_real tmp236;\n\t\t fftw_real tmp247;\n\t\t fftw_real tmp391;\n\t\t fftw_real tmp394;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp236 = tmp230 + tmp235;\n\t\t tmp247 = tmp241 + tmp246;\n\t\t tmp248 = tmp236 + tmp247;\n\t\t tmp541 = tmp236 - tmp247;\n\t\t tmp391 = tmp230 - tmp235;\n\t\t tmp394 = tmp392 - tmp393;\n\t\t tmp395 = tmp391 - tmp394;\n\t\t tmp491 = tmp391 + tmp394;\n\t }\n\t {\n\t\t fftw_real tmp538;\n\t\t fftw_real tmp539;\n\t\t fftw_real tmp388;\n\t\t fftw_real tmp389;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp538 = tmp386 + tmp387;\n\t\t tmp539 = tmp392 + tmp393;\n\t\t tmp540 = tmp538 - tmp539;\n\t\t tmp594 = tmp538 + tmp539;\n\t\t tmp388 = tmp386 - tmp387;\n\t\t tmp389 = tmp241 - tmp246;\n\t\t tmp390 = tmp388 + tmp389;\n\t\t tmp490 = tmp388 - tmp389;\n\t }\n\t }\n\t {\n\t fftw_real tmp278;\n\t fftw_real tmp410;\n\t fftw_real tmp294;\n\t fftw_real tmp429;\n\t fftw_real tmp283;\n\t fftw_real tmp411;\n\t fftw_real tmp289;\n\t fftw_real tmp428;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp275;\n\t\t fftw_real tmp277;\n\t\t fftw_real tmp274;\n\t\t fftw_real tmp276;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp275 = X[iostride];\n\t\t tmp277 = Y[-30 * iostride];\n\t\t tmp274 = c_re(W[0]);\n\t\t tmp276 = c_im(W[0]);\n\t\t tmp278 = (tmp274 * tmp275) - (tmp276 * tmp277);\n\t\t tmp410 = (tmp276 * tmp275) + (tmp274 * tmp277);\n\t }\n\t {\n\t\t fftw_real tmp291;\n\t\t fftw_real tmp293;\n\t\t fftw_real tmp290;\n\t\t fftw_real tmp292;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp291 = X[25 * iostride];\n\t\t tmp293 = Y[-6 * iostride];\n\t\t tmp290 = c_re(W[24]);\n\t\t tmp292 = c_im(W[24]);\n\t\t tmp294 = (tmp290 * tmp291) - (tmp292 * tmp293);\n\t\t tmp429 = (tmp292 * tmp291) + (tmp290 * tmp293);\n\t }\n\t {\n\t\t fftw_real tmp280;\n\t\t fftw_real tmp282;\n\t\t fftw_real tmp279;\n\t\t fftw_real tmp281;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp280 = X[17 * iostride];\n\t\t tmp282 = Y[-14 * iostride];\n\t\t tmp279 = c_re(W[16]);\n\t\t tmp281 = c_im(W[16]);\n\t\t tmp283 = (tmp279 * tmp280) - (tmp281 * tmp282);\n\t\t tmp411 = (tmp281 * tmp280) + (tmp279 * tmp282);\n\t }\n\t {\n\t\t fftw_real tmp286;\n\t\t fftw_real tmp288;\n\t\t fftw_real tmp285;\n\t\t fftw_real tmp287;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp286 = X[9 * iostride];\n\t\t tmp288 = Y[-22 * iostride];\n\t\t tmp285 = c_re(W[8]);\n\t\t tmp287 = c_im(W[8]);\n\t\t tmp289 = (tmp285 * tmp286) - (tmp287 * tmp288);\n\t\t tmp428 = (tmp287 * tmp286) + (tmp285 * tmp288);\n\t }\n\t {\n\t\t fftw_real tmp284;\n\t\t fftw_real tmp295;\n\t\t fftw_real tmp427;\n\t\t fftw_real tmp430;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp284 = tmp278 + tmp283;\n\t\t tmp295 = tmp289 + tmp294;\n\t\t tmp296 = tmp284 + tmp295;\n\t\t tmp555 = tmp284 - tmp295;\n\t\t tmp427 = tmp278 - tmp283;\n\t\t tmp430 = tmp428 - tmp429;\n\t\t tmp431 = tmp427 - tmp430;\n\t\t tmp498 = tmp427 + tmp430;\n\t }\n\t {\n\t\t fftw_real tmp550;\n\t\t fftw_real tmp551;\n\t\t fftw_real tmp412;\n\t\t fftw_real tmp413;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp550 = tmp410 + tmp411;\n\t\t tmp551 = tmp428 + tmp429;\n\t\t tmp552 = tmp550 - tmp551;\n\t\t tmp599 = tmp550 + tmp551;\n\t\t tmp412 = tmp410 - tmp411;\n\t\t tmp413 = tmp289 - tmp294;\n\t\t tmp414 = tmp412 + tmp413;\n\t\t tmp501 = tmp412 - tmp413;\n\t }\n\t }\n\t {\n\t fftw_real tmp253;\n\t fftw_real tmp397;\n\t fftw_real tmp269;\n\t fftw_real tmp404;\n\t fftw_real tmp258;\n\t fftw_real tmp398;\n\t fftw_real tmp264;\n\t fftw_real tmp403;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp250;\n\t\t fftw_real tmp252;\n\t\t fftw_real tmp249;\n\t\t fftw_real tmp251;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp250 = X[30 * iostride];\n\t\t tmp252 = Y[-iostride];\n\t\t tmp249 = c_re(W[29]);\n\t\t tmp251 = c_im(W[29]);\n\t\t tmp253 = (tmp249 * tmp250) - (tmp251 * tmp252);\n\t\t tmp397 = (tmp251 * tmp250) + (tmp249 * tmp252);\n\t }\n\t {\n\t\t fftw_real tmp266;\n\t\t fftw_real tmp268;\n\t\t fftw_real tmp265;\n\t\t fftw_real tmp267;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp266 = X[22 * iostride];\n\t\t tmp268 = Y[-9 * iostride];\n\t\t tmp265 = c_re(W[21]);\n\t\t tmp267 = c_im(W[21]);\n\t\t tmp269 = (tmp265 * tmp266) - (tmp267 * tmp268);\n\t\t tmp404 = (tmp267 * tmp266) + (tmp265 * tmp268);\n\t }\n\t {\n\t\t fftw_real tmp255;\n\t\t fftw_real tmp257;\n\t\t fftw_real tmp254;\n\t\t fftw_real tmp256;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp255 = X[14 * iostride];\n\t\t tmp257 = Y[-17 * iostride];\n\t\t tmp254 = c_re(W[13]);\n\t\t tmp256 = c_im(W[13]);\n\t\t tmp258 = (tmp254 * tmp255) - (tmp256 * tmp257);\n\t\t tmp398 = (tmp256 * tmp255) + (tmp254 * tmp257);\n\t }\n\t {\n\t\t fftw_real tmp261;\n\t\t fftw_real tmp263;\n\t\t fftw_real tmp260;\n\t\t fftw_real tmp262;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp261 = X[6 * iostride];\n\t\t tmp263 = Y[-25 * iostride];\n\t\t tmp260 = c_re(W[5]);\n\t\t tmp262 = c_im(W[5]);\n\t\t tmp264 = (tmp260 * tmp261) - (tmp262 * tmp263);\n\t\t tmp403 = (tmp262 * tmp261) + (tmp260 * tmp263);\n\t }\n\t {\n\t\t fftw_real tmp259;\n\t\t fftw_real tmp270;\n\t\t fftw_real tmp402;\n\t\t fftw_real tmp405;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp259 = tmp253 + tmp258;\n\t\t tmp270 = tmp264 + tmp269;\n\t\t tmp271 = tmp259 + tmp270;\n\t\t tmp543 = tmp259 - tmp270;\n\t\t tmp402 = tmp253 - tmp258;\n\t\t tmp405 = tmp403 - tmp404;\n\t\t tmp406 = tmp402 - tmp405;\n\t\t tmp494 = tmp402 + tmp405;\n\t }\n\t {\n\t\t fftw_real tmp544;\n\t\t fftw_real tmp545;\n\t\t fftw_real tmp399;\n\t\t fftw_real tmp400;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp544 = tmp397 + tmp398;\n\t\t tmp545 = tmp403 + tmp404;\n\t\t tmp546 = tmp544 - tmp545;\n\t\t tmp595 = tmp544 + tmp545;\n\t\t tmp399 = tmp397 - tmp398;\n\t\t tmp400 = tmp264 - tmp269;\n\t\t tmp401 = tmp399 + tmp400;\n\t\t tmp493 = tmp399 - tmp400;\n\t }\n\t }\n\t {\n\t fftw_real tmp301;\n\t fftw_real tmp421;\n\t fftw_real tmp306;\n\t fftw_real tmp422;\n\t fftw_real tmp420;\n\t fftw_real tmp423;\n\t fftw_real tmp312;\n\t fftw_real tmp416;\n\t fftw_real tmp317;\n\t fftw_real tmp417;\n\t fftw_real tmp415;\n\t fftw_real tmp418;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp298;\n\t\t fftw_real tmp300;\n\t\t fftw_real tmp297;\n\t\t fftw_real tmp299;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp298 = X[5 * iostride];\n\t\t tmp300 = Y[-26 * iostride];\n\t\t tmp297 = c_re(W[4]);\n\t\t tmp299 = c_im(W[4]);\n\t\t tmp301 = (tmp297 * tmp298) - (tmp299 * tmp300);\n\t\t tmp421 = (tmp299 * tmp298) + (tmp297 * tmp300);\n\t }\n\t {\n\t\t fftw_real tmp303;\n\t\t fftw_real tmp305;\n\t\t fftw_real tmp302;\n\t\t fftw_real tmp304;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp303 = X[21 * iostride];\n\t\t tmp305 = Y[-10 * iostride];\n\t\t tmp302 = c_re(W[20]);\n\t\t tmp304 = c_im(W[20]);\n\t\t tmp306 = (tmp302 * tmp303) - (tmp304 * tmp305);\n\t\t tmp422 = (tmp304 * tmp303) + (tmp302 * tmp305);\n\t }\n\t tmp420 = tmp301 - tmp306;\n\t tmp423 = tmp421 - tmp422;\n\t {\n\t\t fftw_real tmp309;\n\t\t fftw_real tmp311;\n\t\t fftw_real tmp308;\n\t\t fftw_real tmp310;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp309 = X[29 * iostride];\n\t\t tmp311 = Y[-2 * iostride];\n\t\t tmp308 = c_re(W[28]);\n\t\t tmp310 = c_im(W[28]);\n\t\t tmp312 = (tmp308 * tmp309) - (tmp310 * tmp311);\n\t\t tmp416 = (tmp310 * tmp309) + (tmp308 * tmp311);\n\t }\n\t {\n\t\t fftw_real tmp314;\n\t\t fftw_real tmp316;\n\t\t fftw_real tmp313;\n\t\t fftw_real tmp315;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp314 = X[13 * iostride];\n\t\t tmp316 = Y[-18 * iostride];\n\t\t tmp313 = c_re(W[12]);\n\t\t tmp315 = c_im(W[12]);\n\t\t tmp317 = (tmp313 * tmp314) - (tmp315 * tmp316);\n\t\t tmp417 = (tmp315 * tmp314) + (tmp313 * tmp316);\n\t }\n\t tmp415 = tmp312 - tmp317;\n\t tmp418 = tmp416 - tmp417;\n\t {\n\t\t fftw_real tmp307;\n\t\t fftw_real tmp318;\n\t\t fftw_real tmp556;\n\t\t fftw_real tmp557;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp307 = tmp301 + tmp306;\n\t\t tmp318 = tmp312 + tmp317;\n\t\t tmp319 = tmp307 + tmp318;\n\t\t tmp553 = tmp318 - tmp307;\n\t\t tmp556 = tmp421 + tmp422;\n\t\t tmp557 = tmp416 + tmp417;\n\t\t tmp558 = tmp556 - tmp557;\n\t\t tmp600 = tmp556 + tmp557;\n\t }\n\t {\n\t\t fftw_real tmp419;\n\t\t fftw_real tmp424;\n\t\t fftw_real tmp432;\n\t\t fftw_real tmp433;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp419 = tmp415 - tmp418;\n\t\t tmp424 = tmp420 + tmp423;\n\t\t tmp425 = K707106781 * (tmp419 - tmp424);\n\t\t tmp499 = K707106781 * (tmp424 + tmp419);\n\t\t tmp432 = tmp423 - tmp420;\n\t\t tmp433 = tmp415 + tmp418;\n\t\t tmp434 = K707106781 * (tmp432 - tmp433);\n\t\t tmp502 = K707106781 * (tmp432 + tmp433);\n\t }\n\t }\n\t {\n\t fftw_real tmp273;\n\t fftw_real tmp613;\n\t fftw_real tmp625;\n\t fftw_real tmp627;\n\t fftw_real tmp368;\n\t fftw_real tmp628;\n\t fftw_real tmp616;\n\t fftw_real tmp626;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp225;\n\t\t fftw_real tmp272;\n\t\t fftw_real tmp617;\n\t\t fftw_real tmp624;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp225 = tmp201 + tmp224;\n\t\t tmp272 = tmp248 + tmp271;\n\t\t tmp273 = tmp225 + tmp272;\n\t\t tmp613 = tmp225 - tmp272;\n\t\t tmp617 = tmp594 + tmp595;\n\t\t tmp624 = tmp618 + tmp623;\n\t\t tmp625 = tmp617 + tmp624;\n\t\t tmp627 = tmp624 - tmp617;\n\t }\n\t {\n\t\t fftw_real tmp320;\n\t\t fftw_real tmp367;\n\t\t fftw_real tmp614;\n\t\t fftw_real tmp615;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp320 = tmp296 + tmp319;\n\t\t tmp367 = tmp343 + tmp366;\n\t\t tmp368 = tmp320 + tmp367;\n\t\t tmp628 = tmp367 - tmp320;\n\t\t tmp614 = tmp599 + tmp600;\n\t\t tmp615 = tmp604 + tmp605;\n\t\t tmp616 = tmp614 - tmp615;\n\t\t tmp626 = tmp614 + tmp615;\n\t }\n\t Y[-16 * iostride] = tmp273 - tmp368;\n\t X[0] = tmp273 + tmp368;\n\t Y[-24 * iostride] = tmp613 - tmp616;\n\t X[8 * iostride] = tmp613 + tmp616;\n\t X[16 * iostride] = -(tmp625 - tmp626);\n\t Y[0] = tmp626 + tmp625;\n\t X[24 * iostride] = -(tmp627 - tmp628);\n\t Y[-8 * iostride] = tmp628 + tmp627;\n\t }\n\t {\n\t fftw_real tmp597;\n\t fftw_real tmp609;\n\t fftw_real tmp631;\n\t fftw_real tmp633;\n\t fftw_real tmp602;\n\t fftw_real tmp610;\n\t fftw_real tmp607;\n\t fftw_real tmp611;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp593;\n\t\t fftw_real tmp596;\n\t\t fftw_real tmp629;\n\t\t fftw_real tmp630;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp593 = tmp201 - tmp224;\n\t\t tmp596 = tmp594 - tmp595;\n\t\t tmp597 = tmp593 + tmp596;\n\t\t tmp609 = tmp593 - tmp596;\n\t\t tmp629 = tmp271 - tmp248;\n\t\t tmp630 = tmp623 - tmp618;\n\t\t tmp631 = tmp629 + tmp630;\n\t\t tmp633 = tmp630 - tmp629;\n\t }\n\t {\n\t\t fftw_real tmp598;\n\t\t fftw_real tmp601;\n\t\t fftw_real tmp603;\n\t\t fftw_real tmp606;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp598 = tmp296 - tmp319;\n\t\t tmp601 = tmp599 - tmp600;\n\t\t tmp602 = tmp598 + tmp601;\n\t\t tmp610 = tmp601 - tmp598;\n\t\t tmp603 = tmp343 - tmp366;\n\t\t tmp606 = tmp604 - tmp605;\n\t\t tmp607 = tmp603 - tmp606;\n\t\t tmp611 = tmp603 + tmp606;\n\t }\n\t {\n\t\t fftw_real tmp608;\n\t\t fftw_real tmp634;\n\t\t fftw_real tmp612;\n\t\t fftw_real tmp632;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp608 = K707106781 * (tmp602 + tmp607);\n\t\t Y[-20 * iostride] = tmp597 - tmp608;\n\t\t X[4 * iostride] = tmp597 + tmp608;\n\t\t tmp634 = K707106781 * (tmp607 - tmp602);\n\t\t X[28 * iostride] = -(tmp633 - tmp634);\n\t\t Y[-12 * iostride] = tmp634 + tmp633;\n\t\t tmp612 = K707106781 * (tmp610 - tmp611);\n\t\t Y[-28 * iostride] = tmp609 - tmp612;\n\t\t X[12 * iostride] = tmp609 + tmp612;\n\t\t tmp632 = K707106781 * (tmp610 + tmp611);\n\t\t X[20 * iostride] = -(tmp631 - tmp632);\n\t\t Y[-4 * iostride] = tmp632 + tmp631;\n\t }\n\t }\n\t {\n\t fftw_real tmp537;\n\t fftw_real tmp577;\n\t fftw_real tmp548;\n\t fftw_real tmp635;\n\t fftw_real tmp580;\n\t fftw_real tmp643;\n\t fftw_real tmp560;\n\t fftw_real tmp574;\n\t fftw_real tmp638;\n\t fftw_real tmp644;\n\t fftw_real tmp584;\n\t fftw_real tmp590;\n\t fftw_real tmp571;\n\t fftw_real tmp575;\n\t fftw_real tmp587;\n\t fftw_real tmp591;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp542;\n\t\t fftw_real tmp547;\n\t\t fftw_real tmp582;\n\t\t fftw_real tmp583;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp537 = tmp533 - tmp536;\n\t\t tmp577 = tmp533 + tmp536;\n\t\t tmp542 = tmp540 - tmp541;\n\t\t tmp547 = tmp543 + tmp546;\n\t\t tmp548 = K707106781 * (tmp542 - tmp547);\n\t\t tmp635 = K707106781 * (tmp542 + tmp547);\n\t\t {\n\t\t\t fftw_real tmp578;\n\t\t\t fftw_real tmp579;\n\t\t\t fftw_real tmp554;\n\t\t\t fftw_real tmp559;\n\t\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t\t tmp578 = tmp541 + tmp540;\n\t\t\t tmp579 = tmp543 - tmp546;\n\t\t\t tmp580 = K707106781 * (tmp578 + tmp579);\n\t\t\t tmp643 = K707106781 * (tmp579 - tmp578);\n\t\t\t tmp554 = tmp552 - tmp553;\n\t\t\t tmp559 = tmp555 - tmp558;\n\t\t\t tmp560 = (K923879532 * tmp554) + (K382683432 * tmp559);\n\t\t\t tmp574 = (K382683432 * tmp554) - (K923879532 * tmp559);\n\t\t }\n\t\t tmp638 = tmp636 + tmp637;\n\t\t tmp644 = tmp637 - tmp636;\n\t\t tmp582 = tmp552 + tmp553;\n\t\t tmp583 = tmp555 + tmp558;\n\t\t tmp584 = (K382683432 * tmp582) + (K923879532 * tmp583);\n\t\t tmp590 = (K923879532 * tmp582) - (K382683432 * tmp583);\n\t\t {\n\t\t\t fftw_real tmp565;\n\t\t\t fftw_real tmp570;\n\t\t\t fftw_real tmp585;\n\t\t\t fftw_real tmp586;\n\t\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t\t tmp565 = tmp561 - tmp564;\n\t\t\t tmp570 = tmp568 - tmp569;\n\t\t\t tmp571 = (K382683432 * tmp565) - (K923879532 * tmp570);\n\t\t\t tmp575 = (K382683432 * tmp570) + (K923879532 * tmp565);\n\t\t\t tmp585 = tmp561 + tmp564;\n\t\t\t tmp586 = tmp568 + tmp569;\n\t\t\t tmp587 = (K923879532 * tmp585) - (K382683432 * tmp586);\n\t\t\t tmp591 = (K923879532 * tmp586) + (K382683432 * tmp585);\n\t\t }\n\t }\n\t {\n\t\t fftw_real tmp549;\n\t\t fftw_real tmp572;\n\t\t fftw_real tmp573;\n\t\t fftw_real tmp576;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp549 = tmp537 + tmp548;\n\t\t tmp572 = tmp560 + tmp571;\n\t\t Y[-22 * iostride] = tmp549 - tmp572;\n\t\t X[6 * iostride] = tmp549 + tmp572;\n\t\t tmp573 = tmp537 - tmp548;\n\t\t tmp576 = tmp574 - tmp575;\n\t\t Y[-30 * iostride] = tmp573 - tmp576;\n\t\t X[14 * iostride] = tmp573 + tmp576;\n\t }\n\t {\n\t\t fftw_real tmp645;\n\t\t fftw_real tmp646;\n\t\t fftw_real tmp647;\n\t\t fftw_real tmp648;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp645 = tmp643 + tmp644;\n\t\t tmp646 = tmp574 + tmp575;\n\t\t X[22 * iostride] = -(tmp645 - tmp646);\n\t\t Y[-6 * iostride] = tmp646 + tmp645;\n\t\t tmp647 = tmp644 - tmp643;\n\t\t tmp648 = tmp571 - tmp560;\n\t\t X[30 * iostride] = -(tmp647 - tmp648);\n\t\t Y[-14 * iostride] = tmp648 + tmp647;\n\t }\n\t {\n\t\t fftw_real tmp581;\n\t\t fftw_real tmp588;\n\t\t fftw_real tmp589;\n\t\t fftw_real tmp592;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp581 = tmp577 + tmp580;\n\t\t tmp588 = tmp584 + tmp587;\n\t\t Y[-18 * iostride] = tmp581 - tmp588;\n\t\t X[2 * iostride] = tmp581 + tmp588;\n\t\t tmp589 = tmp577 - tmp580;\n\t\t tmp592 = tmp590 - tmp591;\n\t\t Y[-26 * iostride] = tmp589 - tmp592;\n\t\t X[10 * iostride] = tmp589 + tmp592;\n\t }\n\t {\n\t\t fftw_real tmp639;\n\t\t fftw_real tmp640;\n\t\t fftw_real tmp641;\n\t\t fftw_real tmp642;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp639 = tmp635 + tmp638;\n\t\t tmp640 = tmp590 + tmp591;\n\t\t X[18 * iostride] = -(tmp639 - tmp640);\n\t\t Y[-2 * iostride] = tmp640 + tmp639;\n\t\t tmp641 = tmp638 - tmp635;\n\t\t tmp642 = tmp587 - tmp584;\n\t\t X[26 * iostride] = -(tmp641 - tmp642);\n\t\t Y[-10 * iostride] = tmp642 + tmp641;\n\t }\n\t }\n\t {\n\t fftw_real tmp489;\n\t fftw_real tmp517;\n\t fftw_real tmp520;\n\t fftw_real tmp659;\n\t fftw_real tmp654;\n\t fftw_real tmp660;\n\t fftw_real tmp496;\n\t fftw_real tmp649;\n\t fftw_real tmp504;\n\t fftw_real tmp514;\n\t fftw_real tmp524;\n\t fftw_real tmp530;\n\t fftw_real tmp511;\n\t fftw_real tmp515;\n\t fftw_real tmp527;\n\t fftw_real tmp531;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp488;\n\t\t fftw_real tmp518;\n\t\t fftw_real tmp519;\n\t\t fftw_real tmp650;\n\t\t fftw_real tmp492;\n\t\t fftw_real tmp495;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp488 = K707106781 * (tmp486 + tmp487);\n\t\t tmp489 = tmp485 - tmp488;\n\t\t tmp517 = tmp485 + tmp488;\n\t\t tmp518 = (K382683432 * tmp490) + (K923879532 * tmp491);\n\t\t tmp519 = (K923879532 * tmp494) - (K382683432 * tmp493);\n\t\t tmp520 = tmp518 + tmp519;\n\t\t tmp659 = tmp519 - tmp518;\n\t\t tmp650 = K707106781 * (tmp378 + tmp383);\n\t\t tmp654 = tmp650 + tmp653;\n\t\t tmp660 = tmp653 - tmp650;\n\t\t tmp492 = (K923879532 * tmp490) - (K382683432 * tmp491);\n\t\t tmp495 = (K923879532 * tmp493) + (K382683432 * tmp494);\n\t\t tmp496 = tmp492 - tmp495;\n\t\t tmp649 = tmp492 + tmp495;\n\t }\n\t {\n\t\t fftw_real tmp500;\n\t\t fftw_real tmp503;\n\t\t fftw_real tmp522;\n\t\t fftw_real tmp523;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp500 = tmp498 - tmp499;\n\t\t tmp503 = tmp501 - tmp502;\n\t\t tmp504 = (K555570233 * tmp500) + (K831469612 * tmp503);\n\t\t tmp514 = (K555570233 * tmp503) - (K831469612 * tmp500);\n\t\t tmp522 = tmp498 + tmp499;\n\t\t tmp523 = tmp501 + tmp502;\n\t\t tmp524 = (K980785280 * tmp522) + (K195090322 * tmp523);\n\t\t tmp530 = (K980785280 * tmp523) - (K195090322 * tmp522);\n\t }\n\t {\n\t\t fftw_real tmp507;\n\t\t fftw_real tmp510;\n\t\t fftw_real tmp525;\n\t\t fftw_real tmp526;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp507 = tmp505 - tmp506;\n\t\t tmp510 = tmp508 - tmp509;\n\t\t tmp511 = (K555570233 * tmp507) - (K831469612 * tmp510);\n\t\t tmp515 = (K831469612 * tmp507) + (K555570233 * tmp510);\n\t\t tmp525 = tmp505 + tmp506;\n\t\t tmp526 = tmp508 + tmp509;\n\t\t tmp527 = (K980785280 * tmp525) - (K195090322 * tmp526);\n\t\t tmp531 = (K195090322 * tmp525) + (K980785280 * tmp526);\n\t }\n\t {\n\t\t fftw_real tmp497;\n\t\t fftw_real tmp512;\n\t\t fftw_real tmp513;\n\t\t fftw_real tmp516;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp497 = tmp489 + tmp496;\n\t\t tmp512 = tmp504 + tmp511;\n\t\t Y[-21 * iostride] = tmp497 - tmp512;\n\t\t X[5 * iostride] = tmp497 + tmp512;\n\t\t tmp513 = tmp489 - tmp496;\n\t\t tmp516 = tmp514 - tmp515;\n\t\t Y[-29 * iostride] = tmp513 - tmp516;\n\t\t X[13 * iostride] = tmp513 + tmp516;\n\t }\n\t {\n\t\t fftw_real tmp661;\n\t\t fftw_real tmp662;\n\t\t fftw_real tmp663;\n\t\t fftw_real tmp664;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp661 = tmp659 + tmp660;\n\t\t tmp662 = tmp514 + tmp515;\n\t\t X[21 * iostride] = -(tmp661 - tmp662);\n\t\t Y[-5 * iostride] = tmp662 + tmp661;\n\t\t tmp663 = tmp660 - tmp659;\n\t\t tmp664 = tmp511 - tmp504;\n\t\t X[29 * iostride] = -(tmp663 - tmp664);\n\t\t Y[-13 * iostride] = tmp664 + tmp663;\n\t }\n\t {\n\t\t fftw_real tmp521;\n\t\t fftw_real tmp528;\n\t\t fftw_real tmp529;\n\t\t fftw_real tmp532;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp521 = tmp517 + tmp520;\n\t\t tmp528 = tmp524 + tmp527;\n\t\t Y[-17 * iostride] = tmp521 - tmp528;\n\t\t X[iostride] = tmp521 + tmp528;\n\t\t tmp529 = tmp517 - tmp520;\n\t\t tmp532 = tmp530 - tmp531;\n\t\t Y[-25 * iostride] = tmp529 - tmp532;\n\t\t X[9 * iostride] = tmp529 + tmp532;\n\t }\n\t {\n\t\t fftw_real tmp655;\n\t\t fftw_real tmp656;\n\t\t fftw_real tmp657;\n\t\t fftw_real tmp658;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp655 = tmp649 + tmp654;\n\t\t tmp656 = tmp530 + tmp531;\n\t\t X[17 * iostride] = -(tmp655 - tmp656);\n\t\t Y[-iostride] = tmp656 + tmp655;\n\t\t tmp657 = tmp654 - tmp649;\n\t\t tmp658 = tmp527 - tmp524;\n\t\t X[25 * iostride] = -(tmp657 - tmp658);\n\t\t Y[-9 * iostride] = tmp658 + tmp657;\n\t }\n\t }\n\t {\n\t fftw_real tmp385;\n\t fftw_real tmp469;\n\t fftw_real tmp472;\n\t fftw_real tmp673;\n\t fftw_real tmp668;\n\t fftw_real tmp674;\n\t fftw_real tmp408;\n\t fftw_real tmp665;\n\t fftw_real tmp436;\n\t fftw_real tmp466;\n\t fftw_real tmp476;\n\t fftw_real tmp482;\n\t fftw_real tmp463;\n\t fftw_real tmp467;\n\t fftw_real tmp479;\n\t fftw_real tmp483;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp384;\n\t\t fftw_real tmp470;\n\t\t fftw_real tmp471;\n\t\t fftw_real tmp666;\n\t\t fftw_real tmp396;\n\t\t fftw_real tmp407;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp384 = K707106781 * (tmp378 - tmp383);\n\t\t tmp385 = tmp373 - tmp384;\n\t\t tmp469 = tmp373 + tmp384;\n\t\t tmp470 = (K923879532 * tmp390) + (K382683432 * tmp395);\n\t\t tmp471 = (K382683432 * tmp406) - (K923879532 * tmp401);\n\t\t tmp472 = tmp470 + tmp471;\n\t\t tmp673 = tmp471 - tmp470;\n\t\t tmp666 = K707106781 * (tmp487 - tmp486);\n\t\t tmp668 = tmp666 + tmp667;\n\t\t tmp674 = tmp667 - tmp666;\n\t\t tmp396 = (K382683432 * tmp390) - (K923879532 * tmp395);\n\t\t tmp407 = (K382683432 * tmp401) + (K923879532 * tmp406);\n\t\t tmp408 = tmp396 - tmp407;\n\t\t tmp665 = tmp396 + tmp407;\n\t }\n\t {\n\t\t fftw_real tmp426;\n\t\t fftw_real tmp435;\n\t\t fftw_real tmp474;\n\t\t fftw_real tmp475;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp426 = tmp414 - tmp425;\n\t\t tmp435 = tmp431 - tmp434;\n\t\t tmp436 = (K980785280 * tmp426) + (K195090322 * tmp435);\n\t\t tmp466 = (K195090322 * tmp426) - (K980785280 * tmp435);\n\t\t tmp474 = tmp414 + tmp425;\n\t\t tmp475 = tmp431 + tmp434;\n\t\t tmp476 = (K555570233 * tmp474) + (K831469612 * tmp475);\n\t\t tmp482 = (K831469612 * tmp474) - (K555570233 * tmp475);\n\t }\n\t {\n\t\t fftw_real tmp453;\n\t\t fftw_real tmp462;\n\t\t fftw_real tmp477;\n\t\t fftw_real tmp478;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp453 = tmp441 - tmp452;\n\t\t tmp462 = tmp458 - tmp461;\n\t\t tmp463 = (K195090322 * tmp453) - (K980785280 * tmp462);\n\t\t tmp467 = (K195090322 * tmp462) + (K980785280 * tmp453);\n\t\t tmp477 = tmp441 + tmp452;\n\t\t tmp478 = tmp458 + tmp461;\n\t\t tmp479 = (K831469612 * tmp477) - (K555570233 * tmp478);\n\t\t tmp483 = (K831469612 * tmp478) + (K555570233 * tmp477);\n\t }\n\t {\n\t\t fftw_real tmp409;\n\t\t fftw_real tmp464;\n\t\t fftw_real tmp465;\n\t\t fftw_real tmp468;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp409 = tmp385 + tmp408;\n\t\t tmp464 = tmp436 + tmp463;\n\t\t Y[-23 * iostride] = tmp409 - tmp464;\n\t\t X[7 * iostride] = tmp409 + tmp464;\n\t\t tmp465 = tmp385 - tmp408;\n\t\t tmp468 = tmp466 - tmp467;\n\t\t Y[-31 * iostride] = tmp465 - tmp468;\n\t\t X[15 * iostride] = tmp465 + tmp468;\n\t }\n\t {\n\t\t fftw_real tmp675;\n\t\t fftw_real tmp676;\n\t\t fftw_real tmp677;\n\t\t fftw_real tmp678;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp675 = tmp673 + tmp674;\n\t\t tmp676 = tmp466 + tmp467;\n\t\t X[23 * iostride] = -(tmp675 - tmp676);\n\t\t Y[-7 * iostride] = tmp676 + tmp675;\n\t\t tmp677 = tmp674 - tmp673;\n\t\t tmp678 = tmp463 - tmp436;\n\t\t X[31 * iostride] = -(tmp677 - tmp678);\n\t\t Y[-15 * iostride] = tmp678 + tmp677;\n\t }\n\t {\n\t\t fftw_real tmp473;\n\t\t fftw_real tmp480;\n\t\t fftw_real tmp481;\n\t\t fftw_real tmp484;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp473 = tmp469 + tmp472;\n\t\t tmp480 = tmp476 + tmp479;\n\t\t Y[-19 * iostride] = tmp473 - tmp480;\n\t\t X[3 * iostride] = tmp473 + tmp480;\n\t\t tmp481 = tmp469 - tmp472;\n\t\t tmp484 = tmp482 - tmp483;\n\t\t Y[-27 * iostride] = tmp481 - tmp484;\n\t\t X[11 * iostride] = tmp481 + tmp484;\n\t }\n\t {\n\t\t fftw_real tmp669;\n\t\t fftw_real tmp670;\n\t\t fftw_real tmp671;\n\t\t fftw_real tmp672;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp669 = tmp665 + tmp668;\n\t\t tmp670 = tmp482 + tmp483;\n\t\t X[19 * iostride] = -(tmp669 - tmp670);\n\t\t Y[-3 * iostride] = tmp670 + tmp669;\n\t\t tmp671 = tmp668 - tmp665;\n\t\t tmp672 = tmp479 - tmp476;\n\t\t X[27 * iostride] = -(tmp671 - tmp672);\n\t\t Y[-11 * iostride] = tmp672 + tmp671;\n\t }\n\t }\n }\n if (i == m) {\n\t fftw_real tmp5;\n\t fftw_real tmp105;\n\t fftw_real tmp158;\n\t fftw_real tmp171;\n\t fftw_real tmp12;\n\t fftw_real tmp170;\n\t fftw_real tmp108;\n\t fftw_real tmp155;\n\t fftw_real tmp74;\n\t fftw_real tmp97;\n\t fftw_real tmp130;\n\t fftw_real tmp146;\n\t fftw_real tmp82;\n\t fftw_real tmp98;\n\t fftw_real tmp127;\n\t fftw_real tmp145;\n\t fftw_real tmp24;\n\t fftw_real tmp90;\n\t fftw_real tmp115;\n\t fftw_real tmp138;\n\t fftw_real tmp35;\n\t fftw_real tmp91;\n\t fftw_real tmp112;\n\t fftw_real tmp139;\n\t fftw_real tmp51;\n\t fftw_real tmp94;\n\t fftw_real tmp123;\n\t fftw_real tmp143;\n\t fftw_real tmp59;\n\t fftw_real tmp95;\n\t fftw_real tmp120;\n\t fftw_real tmp142;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp1;\n\t fftw_real tmp157;\n\t fftw_real tmp4;\n\t fftw_real tmp156;\n\t fftw_real tmp2;\n\t fftw_real tmp3;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp1 = X[0];\n\t tmp157 = X[16 * iostride];\n\t tmp2 = X[8 * iostride];\n\t tmp3 = X[24 * iostride];\n\t tmp4 = K707106781 * (tmp2 - tmp3);\n\t tmp156 = K707106781 * (tmp2 + tmp3);\n\t tmp5 = tmp1 + tmp4;\n\t tmp105 = tmp1 - tmp4;\n\t tmp158 = tmp156 + tmp157;\n\t tmp171 = tmp157 - tmp156;\n\t }\n\t {\n\t fftw_real tmp8;\n\t fftw_real tmp106;\n\t fftw_real tmp11;\n\t fftw_real tmp107;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp6;\n\t\t fftw_real tmp7;\n\t\t fftw_real tmp9;\n\t\t fftw_real tmp10;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp6 = X[4 * iostride];\n\t\t tmp7 = X[20 * iostride];\n\t\t tmp8 = (K923879532 * tmp6) - (K382683432 * tmp7);\n\t\t tmp106 = (K382683432 * tmp6) + (K923879532 * tmp7);\n\t\t tmp9 = X[12 * iostride];\n\t\t tmp10 = X[28 * iostride];\n\t\t tmp11 = (K382683432 * tmp9) - (K923879532 * tmp10);\n\t\t tmp107 = (K923879532 * tmp9) + (K382683432 * tmp10);\n\t }\n\t tmp12 = tmp8 + tmp11;\n\t tmp170 = tmp11 - tmp8;\n\t tmp108 = tmp106 - tmp107;\n\t tmp155 = tmp106 + tmp107;\n\t }\n\t {\n\t fftw_real tmp65;\n\t fftw_real tmp80;\n\t fftw_real tmp63;\n\t fftw_real tmp78;\n\t fftw_real tmp69;\n\t fftw_real tmp75;\n\t fftw_real tmp72;\n\t fftw_real tmp76;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp64;\n\t\t fftw_real tmp79;\n\t\t fftw_real tmp61;\n\t\t fftw_real tmp62;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp64 = X[31 * iostride];\n\t\t tmp65 = K2_000000000 * tmp64;\n\t\t tmp79 = X[15 * iostride];\n\t\t tmp80 = K2_000000000 * tmp79;\n\t\t tmp61 = X[7 * iostride];\n\t\t tmp62 = X[23 * iostride];\n\t\t tmp63 = K1_414213562 * (tmp61 - tmp62);\n\t\t tmp78 = K1_414213562 * (tmp61 + tmp62);\n\t\t {\n\t\t\t fftw_real tmp67;\n\t\t\t fftw_real tmp68;\n\t\t\t fftw_real tmp70;\n\t\t\t fftw_real tmp71;\n\t\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t\t tmp67 = X[3 * iostride];\n\t\t\t tmp68 = X[19 * iostride];\n\t\t\t tmp69 = (K1_847759065 * tmp67) - (K765366864 * tmp68);\n\t\t\t tmp75 = (K765366864 * tmp67) + (K1_847759065 * tmp68);\n\t\t\t tmp70 = X[11 * iostride];\n\t\t\t tmp71 = X[27 * iostride];\n\t\t\t tmp72 = (K765366864 * tmp70) - (K1_847759065 * tmp71);\n\t\t\t tmp76 = (K1_847759065 * tmp70) + (K765366864 * tmp71);\n\t\t }\n\t }\n\t {\n\t\t fftw_real tmp66;\n\t\t fftw_real tmp73;\n\t\t fftw_real tmp128;\n\t\t fftw_real tmp129;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp66 = tmp63 - tmp65;\n\t\t tmp73 = tmp69 + tmp72;\n\t\t tmp74 = tmp66 + tmp73;\n\t\t tmp97 = tmp66 - tmp73;\n\t\t tmp128 = tmp72 - tmp69;\n\t\t tmp129 = tmp80 - tmp78;\n\t\t tmp130 = tmp128 - tmp129;\n\t\t tmp146 = tmp128 + tmp129;\n\t }\n\t {\n\t\t fftw_real tmp77;\n\t\t fftw_real tmp81;\n\t\t fftw_real tmp125;\n\t\t fftw_real tmp126;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp77 = tmp75 + tmp76;\n\t\t tmp81 = tmp78 + tmp80;\n\t\t tmp82 = tmp77 + tmp81;\n\t\t tmp98 = tmp81 - tmp77;\n\t\t tmp125 = tmp63 + tmp65;\n\t\t tmp126 = tmp75 - tmp76;\n\t\t tmp127 = tmp125 + tmp126;\n\t\t tmp145 = tmp126 - tmp125;\n\t }\n\t }\n\t {\n\t fftw_real tmp15;\n\t fftw_real tmp22;\n\t fftw_real tmp18;\n\t fftw_real tmp20;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp14;\n\t\t fftw_real tmp21;\n\t\t fftw_real tmp16;\n\t\t fftw_real tmp17;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp14 = X[2 * iostride];\n\t\t tmp15 = K2_000000000 * tmp14;\n\t\t tmp21 = X[18 * iostride];\n\t\t tmp22 = K2_000000000 * tmp21;\n\t\t tmp16 = X[10 * iostride];\n\t\t tmp17 = X[26 * iostride];\n\t\t tmp18 = K1_414213562 * (tmp16 - tmp17);\n\t\t tmp20 = K1_414213562 * (tmp16 + tmp17);\n\t }\n\t {\n\t\t fftw_real tmp19;\n\t\t fftw_real tmp23;\n\t\t fftw_real tmp113;\n\t\t fftw_real tmp114;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp19 = tmp15 + tmp18;\n\t\t tmp23 = tmp20 + tmp22;\n\t\t tmp24 = (K490392640 * tmp19) - (K097545161 * tmp23);\n\t\t tmp90 = (K097545161 * tmp19) + (K490392640 * tmp23);\n\t\t tmp113 = tmp22 - tmp20;\n\t\t tmp114 = tmp15 - tmp18;\n\t\t tmp115 = (K415734806 * tmp113) - (K277785116 * tmp114);\n\t\t tmp138 = (K415734806 * tmp114) + (K277785116 * tmp113);\n\t }\n\t }\n\t {\n\t fftw_real tmp29;\n\t fftw_real tmp33;\n\t fftw_real tmp27;\n\t fftw_real tmp31;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp28;\n\t\t fftw_real tmp32;\n\t\t fftw_real tmp25;\n\t\t fftw_real tmp26;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp28 = X[30 * iostride];\n\t\t tmp29 = K2_000000000 * tmp28;\n\t\t tmp32 = X[14 * iostride];\n\t\t tmp33 = K2_000000000 * tmp32;\n\t\t tmp25 = X[6 * iostride];\n\t\t tmp26 = X[22 * iostride];\n\t\t tmp27 = K1_414213562 * (tmp25 - tmp26);\n\t\t tmp31 = K1_414213562 * (tmp25 + tmp26);\n\t }\n\t {\n\t\t fftw_real tmp30;\n\t\t fftw_real tmp34;\n\t\t fftw_real tmp110;\n\t\t fftw_real tmp111;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp30 = tmp27 - tmp29;\n\t\t tmp34 = tmp31 + tmp33;\n\t\t tmp35 = (K490392640 * tmp30) + (K097545161 * tmp34);\n\t\t tmp91 = (K097545161 * tmp30) - (K490392640 * tmp34);\n\t\t tmp110 = tmp33 - tmp31;\n\t\t tmp111 = tmp27 + tmp29;\n\t\t tmp112 = (K415734806 * tmp110) - (K277785116 * tmp111);\n\t\t tmp139 = (K415734806 * tmp111) + (K277785116 * tmp110);\n\t }\n\t }\n\t {\n\t fftw_real tmp39;\n\t fftw_real tmp57;\n\t fftw_real tmp42;\n\t fftw_real tmp55;\n\t fftw_real tmp46;\n\t fftw_real tmp52;\n\t fftw_real tmp49;\n\t fftw_real tmp53;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp38;\n\t\t fftw_real tmp56;\n\t\t fftw_real tmp40;\n\t\t fftw_real tmp41;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp38 = X[iostride];\n\t\t tmp39 = K2_000000000 * tmp38;\n\t\t tmp56 = X[17 * iostride];\n\t\t tmp57 = K2_000000000 * tmp56;\n\t\t tmp40 = X[9 * iostride];\n\t\t tmp41 = X[25 * iostride];\n\t\t tmp42 = K1_414213562 * (tmp40 - tmp41);\n\t\t tmp55 = K1_414213562 * (tmp40 + tmp41);\n\t\t {\n\t\t\t fftw_real tmp44;\n\t\t\t fftw_real tmp45;\n\t\t\t fftw_real tmp47;\n\t\t\t fftw_real tmp48;\n\t\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t\t tmp44 = X[5 * iostride];\n\t\t\t tmp45 = X[21 * iostride];\n\t\t\t tmp46 = (K1_847759065 * tmp44) - (K765366864 * tmp45);\n\t\t\t tmp52 = (K765366864 * tmp44) + (K1_847759065 * tmp45);\n\t\t\t tmp47 = X[13 * iostride];\n\t\t\t tmp48 = X[29 * iostride];\n\t\t\t tmp49 = (K765366864 * tmp47) - (K1_847759065 * tmp48);\n\t\t\t tmp53 = (K1_847759065 * tmp47) + (K765366864 * tmp48);\n\t\t }\n\t }\n\t {\n\t\t fftw_real tmp43;\n\t\t fftw_real tmp50;\n\t\t fftw_real tmp121;\n\t\t fftw_real tmp122;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp43 = tmp39 + tmp42;\n\t\t tmp50 = tmp46 + tmp49;\n\t\t tmp51 = tmp43 + tmp50;\n\t\t tmp94 = tmp43 - tmp50;\n\t\t tmp121 = tmp49 - tmp46;\n\t\t tmp122 = tmp57 - tmp55;\n\t\t tmp123 = tmp121 - tmp122;\n\t\t tmp143 = tmp121 + tmp122;\n\t }\n\t {\n\t\t fftw_real tmp54;\n\t\t fftw_real tmp58;\n\t\t fftw_real tmp118;\n\t\t fftw_real tmp119;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp54 = tmp52 + tmp53;\n\t\t tmp58 = tmp55 + tmp57;\n\t\t tmp59 = tmp54 + tmp58;\n\t\t tmp95 = tmp58 - tmp54;\n\t\t tmp118 = tmp39 - tmp42;\n\t\t tmp119 = tmp52 - tmp53;\n\t\t tmp120 = tmp118 - tmp119;\n\t\t tmp142 = tmp118 + tmp119;\n\t }\n\t }\n\t {\n\t fftw_real tmp37;\n\t fftw_real tmp85;\n\t fftw_real tmp160;\n\t fftw_real tmp162;\n\t fftw_real tmp84;\n\t fftw_real tmp153;\n\t fftw_real tmp88;\n\t fftw_real tmp161;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp13;\n\t\t fftw_real tmp36;\n\t\t fftw_real tmp154;\n\t\t fftw_real tmp159;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp13 = tmp5 + tmp12;\n\t\t tmp36 = tmp24 + tmp35;\n\t\t tmp37 = tmp13 - tmp36;\n\t\t tmp85 = tmp13 + tmp36;\n\t\t tmp154 = tmp91 - tmp90;\n\t\t tmp159 = tmp155 + tmp158;\n\t\t tmp160 = tmp154 - tmp159;\n\t\t tmp162 = tmp154 + tmp159;\n\t }\n\t {\n\t\t fftw_real tmp60;\n\t\t fftw_real tmp83;\n\t\t fftw_real tmp86;\n\t\t fftw_real tmp87;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp60 = (K049008570 * tmp51) + (K497592363 * tmp59);\n\t\t tmp83 = (K049008570 * tmp74) - (K497592363 * tmp82);\n\t\t tmp84 = tmp60 + tmp83;\n\t\t tmp153 = tmp83 - tmp60;\n\t\t tmp86 = (K497592363 * tmp51) - (K049008570 * tmp59);\n\t\t tmp87 = (K497592363 * tmp74) + (K049008570 * tmp82);\n\t\t tmp88 = tmp86 + tmp87;\n\t\t tmp161 = tmp87 - tmp86;\n\t }\n\t X[8 * iostride] = tmp37 - tmp84;\n\t X[7 * iostride] = tmp37 + tmp84;\n\t X[15 * iostride] = tmp85 - tmp88;\n\t X[0] = tmp85 + tmp88;\n\t Y[-15 * iostride] = tmp153 - tmp160;\n\t Y[0] = tmp153 + tmp160;\n\t Y[-8 * iostride] = tmp161 - tmp162;\n\t Y[-7 * iostride] = tmp161 + tmp162;\n\t }\n\t {\n\t fftw_real tmp93;\n\t fftw_real tmp101;\n\t fftw_real tmp166;\n\t fftw_real tmp168;\n\t fftw_real tmp100;\n\t fftw_real tmp163;\n\t fftw_real tmp104;\n\t fftw_real tmp167;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp89;\n\t\t fftw_real tmp92;\n\t\t fftw_real tmp164;\n\t\t fftw_real tmp165;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp89 = tmp5 - tmp12;\n\t\t tmp92 = tmp90 + tmp91;\n\t\t tmp93 = tmp89 + tmp92;\n\t\t tmp101 = tmp89 - tmp92;\n\t\t tmp164 = tmp35 - tmp24;\n\t\t tmp165 = tmp158 - tmp155;\n\t\t tmp166 = tmp164 - tmp165;\n\t\t tmp168 = tmp164 + tmp165;\n\t }\n\t {\n\t\t fftw_real tmp96;\n\t\t fftw_real tmp99;\n\t\t fftw_real tmp102;\n\t\t fftw_real tmp103;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp96 = (K386505226 * tmp94) + (K317196642 * tmp95);\n\t\t tmp99 = (K386505226 * tmp97) - (K317196642 * tmp98);\n\t\t tmp100 = tmp96 + tmp99;\n\t\t tmp163 = tmp99 - tmp96;\n\t\t tmp102 = (K317196642 * tmp97) + (K386505226 * tmp98);\n\t\t tmp103 = (K386505226 * tmp95) - (K317196642 * tmp94);\n\t\t tmp104 = tmp102 - tmp103;\n\t\t tmp167 = tmp103 + tmp102;\n\t }\n\t X[12 * iostride] = tmp93 - tmp100;\n\t X[3 * iostride] = tmp93 + tmp100;\n\t X[11 * iostride] = tmp101 - tmp104;\n\t X[4 * iostride] = tmp101 + tmp104;\n\t Y[-11 * iostride] = tmp163 - tmp166;\n\t Y[-4 * iostride] = tmp163 + tmp166;\n\t Y[-12 * iostride] = tmp167 - tmp168;\n\t Y[-3 * iostride] = tmp167 + tmp168;\n\t }\n\t {\n\t fftw_real tmp117;\n\t fftw_real tmp133;\n\t fftw_real tmp174;\n\t fftw_real tmp176;\n\t fftw_real tmp132;\n\t fftw_real tmp175;\n\t fftw_real tmp136;\n\t fftw_real tmp169;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp109;\n\t\t fftw_real tmp116;\n\t\t fftw_real tmp172;\n\t\t fftw_real tmp173;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp109 = tmp105 - tmp108;\n\t\t tmp116 = tmp112 - tmp115;\n\t\t tmp117 = tmp109 + tmp116;\n\t\t tmp133 = tmp109 - tmp116;\n\t\t tmp172 = tmp170 - tmp171;\n\t\t tmp173 = tmp138 + tmp139;\n\t\t tmp174 = tmp172 - tmp173;\n\t\t tmp176 = tmp173 + tmp172;\n\t }\n\t {\n\t\t fftw_real tmp124;\n\t\t fftw_real tmp131;\n\t\t fftw_real tmp134;\n\t\t fftw_real tmp135;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp124 = (K440960632 * tmp120) + (K235698368 * tmp123);\n\t\t tmp131 = (K440960632 * tmp127) + (K235698368 * tmp130);\n\t\t tmp132 = tmp124 - tmp131;\n\t\t tmp175 = tmp124 + tmp131;\n\t\t tmp134 = (K440960632 * tmp130) - (K235698368 * tmp127);\n\t\t tmp135 = (K440960632 * tmp123) - (K235698368 * tmp120);\n\t\t tmp136 = tmp134 - tmp135;\n\t\t tmp169 = tmp135 + tmp134;\n\t }\n\t X[13 * iostride] = tmp117 - tmp132;\n\t X[2 * iostride] = tmp117 + tmp132;\n\t X[10 * iostride] = tmp133 - tmp136;\n\t X[5 * iostride] = tmp133 + tmp136;\n\t Y[-13 * iostride] = tmp169 - tmp174;\n\t Y[-2 * iostride] = tmp169 + tmp174;\n\t Y[-5 * iostride] = -(tmp175 + tmp176);\n\t Y[-10 * iostride] = tmp176 - tmp175;\n\t }\n\t {\n\t fftw_real tmp141;\n\t fftw_real tmp149;\n\t fftw_real tmp180;\n\t fftw_real tmp182;\n\t fftw_real tmp148;\n\t fftw_real tmp177;\n\t fftw_real tmp152;\n\t fftw_real tmp181;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp137;\n\t\t fftw_real tmp140;\n\t\t fftw_real tmp178;\n\t\t fftw_real tmp179;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp137 = tmp105 + tmp108;\n\t\t tmp140 = tmp138 - tmp139;\n\t\t tmp141 = tmp137 + tmp140;\n\t\t tmp149 = tmp137 - tmp140;\n\t\t tmp178 = tmp115 + tmp112;\n\t\t tmp179 = tmp170 + tmp171;\n\t\t tmp180 = tmp178 - tmp179;\n\t\t tmp182 = tmp178 + tmp179;\n\t }\n\t {\n\t\t fftw_real tmp144;\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 tmp144 = (K478470167 * tmp142) + (K145142338 * tmp143);\n\t\t tmp147 = (K478470167 * tmp145) - (K145142338 * tmp146);\n\t\t tmp148 = tmp144 + tmp147;\n\t\t tmp177 = tmp147 - tmp144;\n\t\t tmp150 = (K145142338 * tmp145) + (K478470167 * tmp146);\n\t\t tmp151 = (K478470167 * tmp143) - (K145142338 * tmp142);\n\t\t tmp152 = tmp150 - tmp151;\n\t\t tmp181 = tmp151 + tmp150;\n\t }\n\t X[14 * iostride] = tmp141 - tmp148;\n\t X[iostride] = tmp141 + tmp148;\n\t X[9 * iostride] = tmp149 - tmp152;\n\t X[6 * iostride] = tmp149 + tmp152;\n\t Y[-9 * iostride] = tmp177 - tmp180;\n\t Y[-6 * iostride] = tmp177 + tmp180;\n\t Y[-14 * iostride] = tmp181 - tmp182;\n\t Y[-iostride] = tmp181 + tmp182;\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 fftw_hc2hc_forward_32_desc =\n{\n \"fftw_hc2hc_forward_32\",\n (void (*)()) fftw_hc2hc_forward_32,\n 32,\n FFTW_FORWARD,\n FFTW_HC2HC,\n 707,\n 31,\n twiddle_order,\n};\n", "meta": {"hexsha": "52404daff8ed8ebab80d51d71ffff70d4080df23", "size": 67445, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_32.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_32.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_32.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.159100735, "max_line_length": 125, "alphanum_fraction": 0.5738157017, "num_tokens": 21074, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.3380771374883919, "lm_q1q2_score": 0.2165843313375145}} {"text": "#include \"lib.h\"\n#include \"defines.h\"\n#include \"milosUtils.h\"\n#include \"time.h\"\n#include \n#include //siempre a continuacion de complex.h\n#include \n\n#include \n#include \n#include \n#include \n#include //siempre a continuacion de complex.h\n#include \"convolution.h\"\n#include \"svdcmp.h\"\n\n\nextern PRECISION **PUNTEROS_CALCULOS_COMPARTIDOS;\nextern int POSW_PUNTERO_CALCULOS_COMPARTIDOS;\nextern int POSR_PUNTERO_CALCULOS_COMPARTIDOS;\nextern REAL *gp4_gp2_rhoq, *gp5_gp2_rhou, *gp6_gp2_rhov;\nextern REAL *gp1, *gp2, *dt, *dti, *gp3, *gp4, *gp5, *gp6, *etai_2;\nextern REAL *dgp1, *dgp2, *dgp3, *dgp4, *dgp5, *dgp6, *d_dt;\nextern REAL *d_ei, *d_eq, *d_eu, *d_ev, *d_rq, *d_ru, *d_rv;\nextern REAL *dfi, *dshi;\nextern REAL *fi_p, *fi_b, *fi_r, *shi_p, *shi_b, *shi_r;\nextern REAL *spectra, *d_spectra, *spectra_mac, *spectra_slight;\nextern REAL *etain, *etaqn, *etaun, *etavn, *rhoqn, *rhoun, *rhovn;\nextern REAL *etai, *etaq, *etau, *etav, *rhoq, *rhou, *rhov;\nextern REAL *parcial1, *parcial2, *parcial3;\nextern REAL *nubB, *nupB, *nurB;\nextern PRECISION *G,*GMAC;\nextern fftw_complex * inSpectraFwPSF, *inSpectraBwPSF, *outSpectraFwPSF, *outSpectraBwPSF;\nextern fftw_plan planForwardPSF, planBackwardPSF;\nextern fftw_complex * fftw_G_PSF;\nextern Cuantic *cuantic; // Variable global, está hecho así, de momento,para parecerse al original\nextern gsl_vector *eval;\nextern gsl_matrix *evec;\nextern gsl_eigen_symmv_workspace * workspace;\nextern int NTERMS;\n\n\n\n\n\n\nvoid AplicaDelta(Init_Model *model, PRECISION *delta, int *fixed, Init_Model *modelout)\n{\n\n\t\n\tint index =0;\n\tif (fixed[0]) // ETHA 0 \n\t{\n\t\tmodelout->eta0 = model->eta0 - delta[0]; // 0\n\t}\n\tif (fixed[1]) // B\n\t{\n\t\tif (delta[1] < -300) //300\n\t\t\tdelta[1] = -300;\n\t\telse if (delta[1] > 300)\n\t\t\tdelta[1] = 300;\n\t\tmodelout->B = model->B - delta[1]; //magnetic field\n\t}\n\tif (fixed[2]) // VLOS\n\t{\n\t\tmodelout->vlos = model->vlos - delta[2];\n\t}\n\n\tif (fixed[3]) // DOPPLER WIDTH\n\t{\n\t\tmodelout->dopp = model->dopp - delta[3];\n\t}\n\n\tif (fixed[4]) // DAMPING \n\t\tmodelout->aa = model->aa - delta[4];\n\n\tif (fixed[5]) // GAMMA \n\t{\n\t\tif (delta[5] < -30) //15\n\t\t\tdelta[5] = -30;\n\t\telse if (delta[5] > 30)\n\t\t\tdelta[5] = 30;\n\n\t\tmodelout->gm = model->gm - delta[5]; //5\n\t}\n\tif (fixed[6]) // AZIMUTH\n\t{\n\n\n\t\tif (delta[6] < -30)\n\t\t\tdelta[6] = -30;\n\t\telse if (delta[6] > 30)\n\t\t\tdelta[6] = 30;\n\n\t\tmodelout->az = model->az - delta[6];\n\t}\n\tif (fixed[7])\n\t\tmodelout->S0 = model->S0 - delta[7];\n\n\tif (fixed[8])\n\t\tmodelout->S1 = model->S1 - delta[8];\n\n\tif (fixed[9]){\n\t\tmodelout->mac = model->mac - delta[9]; //9\n\n\t}\n\tif (fixed[10]){\n\t\tif(NTERMS==11)\n\t\t\tmodelout->alfa = model->alfa - delta[10];\n\t\telse\n\t\t{\n\t\t\tmodelout->alfa = model->alfa - delta[9];\n\t\t}\n\t}\n}\n\n\nint check(Init_Model *model)\n{\n\t//Magnetic field\n\tif (model->B < 0)\n\t{\n\t\tmodel->B = -(model->B);\n\t\tmodel->gm = 180.0 - (model->gm);\n\t}\n\tif (model->B > 5000)\n\t\tmodel->B = 5000;\n\n\t//Inclination\n\tif (model->gm < 0)\n\t\tmodel->gm = -(model->gm);\n\tif (model->gm > 180)\n\t{\n\t\tmodel->gm = 360.0 - model->gm;\n\t}\n\n\t//azimuth\n\tif (model->az < 0)\n\t\tmodel->az = 180 + (model->az); //model->az= 180 + (model->az);\n\tif (model->az > 180)\n\t{\n\t\tmodel->az = model->az - 180.0;\n\t}\n\n\t//Eta0\n\tif (model->eta0 < 1)\n\t\tmodel->eta0 = 1;\n\tif (model->eta0 > 2500) //idl 2500\n\t\tmodel->eta0 = 2500;\n\n\t//velocity\n\tif (model->vlos < (-20)) //20\n\t\tmodel->vlos = (-20);\n\tif (model->vlos > 20)\n\t\tmodel->vlos = 20;\n\n\t//doppler width ;Do NOT CHANGE THIS\n\tif (model->dopp < 0.0001)\n\t\tmodel->dopp = 0.0001;\n\tif (model->dopp > 0.6) // idl 0.6\n\t\tmodel->dopp = 0.6;\n\n\t// damping \n\tif (model->aa < 0.0001) // idl 1e-4\n\t\tmodel->aa = 0.0001;\n\tif (model->aa > 10.0) //10\n\t\tmodel->aa = 10.0;\n\n\t//S0\n\tif (model->S0 < 0.0001)\n\t\tmodel->S0 = 0.0001;\n\tif (model->S0 > 2.00)\n\t\tmodel->S0 = 2.00;\n\n\t//S1\n\tif (model->S1 < 0.0001)\n\t\tmodel->S1 = 0.0001;\n\tif (model->S1 > 2.00)\n\t\tmodel->S1 = 2.00;\n\n\t//macroturbulence\n\tif (model->mac < 0)\n\t\tmodel->mac = 0;\n\tif (model->mac > 4)\n\t\tmodel->mac = 4;\n\t\n\t// filling factor \n\tif(model->alfa<0)\n\t\tmodel->alfa = 0.0;\n\tif(model->alfa>1.0)\n\t\tmodel->alfa = 1.0;\n\t\n\t\n\n\treturn 1;\n}\n\n\nvoid FijaACeroDerivadasNoNecesarias(REAL *d_spectra, int *fixed, int nlambda)\n{\n\n\tint In, j, i;\n\n\tif(NTERMS==9 || NTERMS==11){\n\t\tfor (In = 0; In < NTERMS; In++)\n\t\t\tif (fixed[In] == 0)\n\t\t\t\tfor (j = 0; j < NPARMS; j++)\n\t\t\t\t\tfor (i = 0; i < nlambda; i++)\n\t\t\t\t\t\td_spectra[i + nlambda * In + j * nlambda * NTERMS] = 0;\n\t}\n\telse if (NTERMS==10){\n\t\tfor (In = 0; In < NTERMS; In++){\n\t\t\tif(In<9){\n\t\t\t\tif (fixed[In] == 0)\n\t\t\t\t\tfor (j = 0; j < NPARMS; j++)\n\t\t\t\t\t\tfor (i = 0; i < nlambda; i++)\n\t\t\t\t\t\t\td_spectra[i + nlambda * In + j * nlambda * NTERMS] = 0;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tif (fixed[9] == 0 && fixed[10] == 0)\n\t\t\t\t\tfor (j = 0; j < NPARMS; j++)\n\t\t\t\t\t\tfor (i = 0; i < nlambda; i++)\n\t\t\t\t\t\t\td_spectra[i + nlambda * In + j * nlambda * NTERMS] = 0;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n/*\n\tTamaño de H es \t NTERMS x NTERMS\n\tTamaño de beta es 1xNTERMS\n\n\treturn en delta tam 1xNTERMS\n*/\n\nint mil_svd(PRECISION *h, REAL *beta, PRECISION *delta)\n{\n\n\tconst PRECISION epsilon = 1e-12;\n\n\tPRECISION *v, *w;\n\tint i, j;\n\tPRECISION aux2[NTERMS];\n\n\n\tgsl_matrix_view gsl_h1 = gsl_matrix_view_array (h, NTERMS, NTERMS);\n\tgsl_eigen_symmv(&gsl_h1.matrix, eval, evec, workspace);\n\tw = gsl_vector_ptr(eval,0);\n\tv = gsl_matrix_ptr(evec,0,0);\n\n\tPRECISION sum;\n\t\t\n\tfor ( j = 0; j < NTERMS; j++){\n\t\tsum=0;\n\t\tfor ( i = 0; i < NTERMS; i++){\n\t\t\tsum += beta[i] * v[i*NTERMS+j];\n\t\t}\n\t\taux2[j] = sum * ((fabs(w[j]) > epsilon) ? (1/w[j]): 0.0);\n\t}\n\n\n\tfor ( i = 0; i < NTERMS; i++){\t\t\n\t\tsum=0;\n\t\tfor ( j = 0; j < NTERMS; j++){\n\t\t\tsum += v[i*NTERMS+j] * aux2[j];\n\t\t}\n\t\tdelta[i] = sum;\n\t}\n\treturn 1;\n}\n\n\n/*\n*\n*\n* Cálculo de las estimaciones clásicas.\n*\n*\n* lambda_0 : centro de la línea\n* lambda : vector de muestras\n* nlambda : numero de muesras\n* spectro : vector [I,Q,U,V]\n* initModel: Modelo de atmosfera a ser modificado\n*\n*/\nvoid estimacionesClasicas(PRECISION lambda_0, PRECISION *lambda, int nlambda, float *spectro, Init_Model *initModel, int forInitialUse)\n{\n\n\tdouble x, y, aux, LM_lambda_plus, LM_lambda_minus, Blos, Ic, Vlos;\n\tdouble aux_vlos,x_vlos,y_vlos;\n\tfloat *spectroI, *spectroQ, *spectroU, *spectroV;\n\tdouble L, m, gamma, gamma_rad, tan_gamma, C;\n\tint i;\n\n\tspectroI = spectro;\n\tspectroQ = spectro + nlambda;\n\tspectroU = spectro + nlambda * 2;\n\tspectroV = spectro + nlambda * 3;\n\n\t//check if there is ghost lambdas in the extrems\n\tint beginLambda = 0;\n\t\n\tint exit=0;\n\tfor(i=0;i=0 && !exit;i--){\n\t\tif(spectroI[i]<0){\n\t\t\tendLambda--;\n\t\t}\n\t\telse\n\t\t{\n\t\t\texit=1;\n\t\t}\t\n\t}\n\n\n\tIc = spectro[endLambda - 1]; // Continuo ultimo valor de I\n\n\tx = 0;\n\ty = 0;\n\tx_vlos = 0;\n\ty_vlos = 0;\n\tfor (i = beginLambda; i < endLambda-1 ; i++)\n\t{\n\t\tif(spectroI[i]>-1 && spectroV[i]>-1){\n\t\t\taux = (Ic - (spectroI[i] + spectroV[i]));\n\t\t\taux_vlos = (Ic - spectroI[i]);\n\t\t\tx += (aux * (lambda[i] - lambda_0));\n\t\t\tx_vlos += (aux_vlos * (lambda[i] - lambda_0));\n\t\t\ty += aux;\n\t\t\ty_vlos += aux_vlos;\n\t\t}\n\t}\n\n\t//Para evitar nan\n\tif (fabs(y) > 1e-15)\n\t\tLM_lambda_plus = x / y;\n\telse\n\t\tLM_lambda_plus = 0;\n\n\tx = 0;\n\ty = 0;\n\tfor (i = beginLambda; i < endLambda-1 ; i++)\n\t{\n\t\tif(spectroI[i]>-1 && spectroV[i]>-1){\n\t\t\taux = (Ic - (spectroI[i] - spectroV[i]));\n\t\t\tx += (aux * (lambda[i] - lambda_0));\n\t\t\ty += aux;\n\t\t}\n\t}\n\n\tif (fabs(y) > 1e-15)\n\t\tLM_lambda_minus = x / y;\n\telse\n\t\tLM_lambda_minus = 0;\n\n\tC = (CTE4_6_13 * (lambda_0*lambda_0) * cuantic->GEFF);\n\t\n\n\tBlos = (1 / C) * ((LM_lambda_plus - LM_lambda_minus) / 2);\n\tVlos = (VLIGHT / (lambda_0)) * ((x_vlos/y_vlos) / 2); // for now use the center without spectroV only spectroI \n\n\t//inclinacion\n\tx = 0;\n\ty = 0;\n\tfor (i = beginLambda; i < endLambda - 1; i++)\n\t{\n\t\tif(spectroQ[i]>-1 && spectroU[i]>-1 && spectroV[i]>-1){\n\t\t\tL = FABS(SQRT(spectroQ[i] * spectroQ[i] + spectroU[i] * spectroU[i]));\n\t\t\tm = fabs((4 * (lambda[i] - lambda_0) * L)); \n\n\t\t\tx = x + FABS(spectroV[i]) * m;\n\t\t\ty = y + FABS(spectroV[i]) * FABS(spectroV[i]);\n\t\t}\n\t}\n\n\ty = y * fabs((3 * C * Blos));\n\n\ttan_gamma = fabs(sqrt(x / y));\n\n\tgamma_rad = atan(tan_gamma); //gamma en radianes\n\tgamma = gamma_rad * (180 / PI); //gamma en grados\n\n\tif(forInitialUse){\n\t\tif(gamma>=85 && gamma <=90){ \n\t\t\tgamma_rad = 85 *(PI/180);\n\t\t}\n\t\tif(gamma>90 && gamma <=95){ \n\t\t\tgamma_rad = 95 *(PI/180);\n\t\t}\n\t}\n\t//correction \n\t//we use the sign of Blos to see to correct the quadrant\n\tif (Blos < 0)\n\t\tgamma = (180) - gamma;\n\n\n\t// CALCULATIONS FOR AZIMUTH \n\tPRECISION tan2phi, phi;\n\n\tdouble sum_u =0.0, sum_q = 0.0;\n\tfor(i=0;i-1 && spectroQ[i]>-1){\n\t\t\tif( fabs(spectroU[i])>0.0001 || fabs(spectroQ[i])>0.0001 ){\n\t\t\t\tsum_u += spectroU[i];\n\t\t\t\tsum_q += spectroQ[i];\n\t\t\t}\n\t\t}\n\t}\n\ttan2phi = sum_u/sum_q;\n\tphi = (atan(tan2phi) * 180 / PI) / 2;\n\tif ( sum_u > 0 && sum_q > 0 )\n\t\tphi = phi;\n\telse if ( sum_u < 0 && sum_q > 0 )\n\t\tphi = phi + 180;\n\telse if ( sum_u< 0 && sum_q < 0 )\n\t\tphi = phi + 90;\n\telse if ( sum_u > 0 && sum_q < 0 )\n\t\tphi = phi + 90;\n\t\n\t// END CALCULATIONS FOR AZIMUTH \n\t\n\tPRECISION B_aux;\n\tB_aux = fabs(Blos / cos(gamma_rad)); // \n\n\t\n\tif (Vlos < (-4))\n\t\tVlos = -4;\n\tif (Vlos > (4))\n\t\tVlos = 4;\n\n\n\tinitModel->B = (B_aux > 4000 ? 4000 : B_aux);\n\tinitModel->vlos = Vlos;\n\tinitModel->gm = gamma;\n\tinitModel->az = phi;\n\n\tif(!forInitialUse) // store Blos in SO if we are in non-initialization use\n\t\tinitModel->S0 = Blos;\n\t\n}\n\n\n\n\n/*\n *\n * nwlineas : numero de lineas espectrales\n * wlines :\t\tlineas spectrales\n * lambda :\t\twavelength axis in angstrom\n\t\t\tlongitud nlambda\n * spectra : IQUV por filas, longitud ny=nlambda\n */\n\nint lm_mils(Cuantic *cuantic, PRECISION *wlines, PRECISION *lambda, int nlambda, float *spectro, int nspectro,\n\t\t\t\tInit_Model *initModel, REAL *spectra, float *chisqrf,\n\t\t\t\tREAL * slight, PRECISION toplim, int miter, REAL *weight, int *fix,\n\t\t\t\tREAL *vSigma, REAL sigma, REAL ilambda, int * INSTRUMENTAL_CONVOLUTION, int * iter, REAL ah, int logclambda)\n{\n\n\t\n\t\n\n\tREAL PARBETA_better = 5.0;\n \tREAL PARBETA_worst = 10.0;\n \tREAL PARBETA_FACTOR = 1.0;\n\n\t//int iter;\n\tint i, *fixed, nfree, n_ghosts=0, log = 0;\n\t\n\tPRECISION delta[NTERMS];\n\t\n\tfor(i=0;imac,initModel->alfa);\n\t\t\t}\t\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (i = 0; i < NTERMS * NTERMS; i++)\n\t\t\t\tcovar[i] = alpha[i];\n\n\t\t\tflambda=flambda*PARBETA_worst*PARBETA_FACTOR;\n\t\t\tif(log)\n\t\t\t\tprintf(\"\\n%d\\t%f\\t increases\\t______________________________\",*iter,flambda);\n\t\t}\n\n\t\tif ((flambda > 1e+7) || (flambda < 1e-25)) \n\t\t\tclanda=1 ; // condition to exit of the loop \t\t\n\n\t\t(*iter)++;\n\t\tif(logclambda) PARBETA_FACTOR = log10f(chisqr)/log10f(chisqr0);\n\n\t} while (*iter < miter && !clanda);\n\n\t*chisqrf = ochisqr;\n\t\n\tif(log){\n\t\tprintf(\"\\n______________________________________________________________________\\n\");\n\t\n\t}\n\tif (fix == NULL)\n\t\tfree(fixed);\n\n\treturn 1;\n}\n\n\n\n/**\n * Make the interpolation between deltaLambda and PSF where deltaLambda es x and PSF f(x)\n * Return the array with the interpolation. \n * */\nint interpolationSplinePSF(PRECISION *deltaLambda, PRECISION * PSF, PRECISION * lambdasSamples, size_t N_PSF, PRECISION * fInterpolated, size_t NSamples){\n\n\tsize_t i;\n\tgsl_interp_accel *acc = gsl_interp_accel_alloc();\n \tgsl_spline *spline_cubic = gsl_spline_alloc(gsl_interp_cspline, N_PSF);\n\t//gsl_spline *spline_akima = gsl_spline_alloc(gsl_interp_akima, NSamples);\n\t//gsl_spline *spline_steffen = gsl_spline_alloc(gsl_interp_steffen, NSamples);\n\n\tgsl_spline_init(spline_cubic, deltaLambda, PSF, N_PSF);\n\t//gsl_spline_init(spline_akima, deltaLambda, PSF, N_PSF);\n\t//gsl_spline_init(spline_steffen, deltaLambda, PSF, N_PSF);\n\n\tfor (i = 0; i < NSamples; ++i){\n \t\n //fInterpolated[i] = gsl_spline_eval(spline_cubic, xi, acc);\n //PRECISION yi_akima = gsl_spline_eval(spline_akima, xi, acc);\n //PRECISION yi_steffen = gsl_spline_eval(spline_steffen, lambdasSamples[i], acc);\n\t\tPRECISION yi = gsl_spline_eval(spline_cubic, lambdasSamples[i], acc);\n\t\tif(!gsl_isnan(yi)){\n\t\t\tfInterpolated[i] = yi;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfInterpolated[i] = 0.0f;\n\t\t}\n\t\t\n }\n\n \tgsl_spline_free(spline_cubic);\n\t//gsl_spline_free(spline_akima);\n\t//gsl_spline_free(spline_steffen);\n\tgsl_interp_accel_free(acc);\n\n\treturn 1;\n}\n\n\n/**\n * Make the interpolation between deltaLambda and PSF where deltaLambda es x and PSF f(x)\n * Return the array with the interpolation. \n * */\nint interpolationLinearPSF(PRECISION *deltaLambda, PRECISION * PSF, PRECISION * lambdasSamples, size_t N_PSF, PRECISION * fInterpolated, size_t NSamples,double offset){\n\n\tsize_t i;\n\tgsl_interp *interpolation = gsl_interp_alloc (gsl_interp_linear,N_PSF);\n\tgsl_interp_init(interpolation, deltaLambda, PSF, N_PSF);\n\tgsl_interp_accel * accelerator = gsl_interp_accel_alloc();\n\n\tfor (i = 0; i < NSamples; ++i){\n\t\tdouble aux;\n\t\tif(offset>=0){\n\t\t\tif(lambdasSamples[i]-offset>= deltaLambda[0]){\n\t\t\t\taux = gsl_interp_eval(interpolation, deltaLambda, PSF, lambdasSamples[i]-offset, accelerator);\n\t\t\t\t\t\t// if lambdasSamples[i] is out of range from deltaLambda then aux is GSL_NAN, we put nan values to 0. \n\t\t\t\tif(!gsl_isnan(aux)) \n\t\t\t\t\tfInterpolated[i] = aux;\n\t\t\t\telse\n\t\t\t\t\tfInterpolated[i] = 0.0f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\taux = 0.0f;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(lambdasSamples[i]-offset>= deltaLambda[NSamples-1]){\n\t\t\t\taux = gsl_interp_eval(interpolation, deltaLambda, PSF, lambdasSamples[i]-offset, accelerator);\n\t\t\t\t\t\t// if lambdasSamples[i] is out of range from deltaLambda then aux is GSL_NAN, we put nan values to 0. \n\t\t\t\tif(!gsl_isnan(aux)) \n\t\t\t\t\tfInterpolated[i] = aux;\n\t\t\t\telse\n\t\t\t\t\tfInterpolated[i] = 0.0f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\taux = 0.0f;\n\t\t\t}\t\t\t\n\t\t}\n\t}\n\n \t// normalizations \n\tdouble cte = 0;\n\tfor(i=0; i< NSamples; i++){\n\t\tcte += fInterpolated[i];\n\t}\n\tfor(i=0; i< NSamples; i++){\n\t\tfInterpolated[i] /= cte;\n\t}\n \tgsl_interp_accel_free(accelerator);\n\tgsl_interp_free(interpolation);\n \t\n\n\n\n\treturn 1;\n}\n", "meta": {"hexsha": "95966861ef263bcfa94d5dd70fc366cf99f51554", "size": 17272, "ext": "c", "lang": "C", "max_stars_repo_path": "p-milos/src/milosUtils.c", "max_stars_repo_name": "dcalc/hrt_pipeline", "max_stars_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "p-milos/src/milosUtils.c", "max_issues_repo_name": "dcalc/hrt_pipeline", "max_issues_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2021-11-05T14:03:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T14:18:48.000Z", "max_forks_repo_path": "p-milos/src/milosUtils.c", "max_forks_repo_name": "dcalc/hrt_pipeline", "max_forks_repo_head_hexsha": "bee72e8baeb45bba42a5ccc4d7807df8f10aa178", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-06-14T12:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-09T19:10:00.000Z", "avg_line_length": 23.3721244926, "max_line_length": 168, "alphanum_fraction": 0.6168943956, "num_tokens": 6369, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.531209388216861, "lm_q2_score": 0.4073334000459302, "lm_q1q2_score": 0.2163793262386925}} {"text": "/* The MIT License\n\n Copyright (c) 2013-2015 Genome Research Ltd.\n\n Author: Petr Danecek \n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bcftools.h\"\n#include \"peakfit.h\"\n\ntypedef struct\n{\n int nvals; // all values, including RR,AA peaks\n double *xvals; // pointer to args_t.xvals\n double *yvals;\n int copy_number; // heuristics to skip futile CN1 fits when no het peak is detected\n int irr, ira, iaa; // chop off RR and AA peaks\n char *chr;\n}\ndist_t;\n\ntypedef struct\n{\n int ndist, nbins, ra_rr_scaling, smooth;\n double *xvals;\n dist_t *dist;\n char **argv, *output_dir;\n double fit_th, peak_symmetry, cn_penalty, min_peak_size, min_fraction;\n int argc, plot, verbose, regions_is_file, targets_is_file, include_aa, force_cn;\n char *dat_fname, *fname, *regions_list, *targets_list, *sample;\n FILE *dat_fp;\n}\nargs_t;\n\nFILE *open_file(char **fname, const char *mode, const char *fmt, ...);\n\nstatic void init_dist(args_t *args, dist_t *dist, int verbose)\n{\n // isolate RR and AA peaks and rescale so that they are comparable to hets\n int i, irr, iaa, n = dist->nvals;\n\n // smooth the distribution, this is just to find the peaks\n double *tmp = (double*) malloc(sizeof(double)*n);\n int win = args->smooth ? fabs(args->smooth)*2 + 1 : 7; // must be an odd number\n int hwin = win/2;\n double avg = tmp[0] = dist->yvals[0];\n for (i=1; iyvals[2*i-1]; \n tmp[i] = avg/(2*i+1);\n }\n avg = 0;\n for (i=0; iyvals[i];\n if ( i>=win-1 )\n {\n tmp[i-hwin] = avg/win;\n avg -= dist->yvals[i-win+1];\n }\n }\n for (i=n-hwin; iyvals[i-hwin];\n hwin--;\n tmp[i] = avg/(2*hwin+1);\n avg -= dist->yvals[i-hwin];\n }\n\n // find the extremes; first a simple approach: find a gap\n for (irr=0,i=0; i=n/2; i--) if ( tmp[i] < tmp[iaa] ) iaa = i;\n irr += win*0.5;\n iaa += win*0.5;\n if ( iaa>=n ) iaa = n-1;\n if ( irr>=iaa ) error(\"FIXME: oops, dist normalization failed for %s: %d vs %d\\n\", dist->chr,irr,iaa); // we may need to be smarter\n if ( args->smooth>0 ) for (i=0; iyvals[i] = tmp[i];\n free(tmp);\n\n // clean the data: the AA peak is occasionally not centered at 1.0 but is closer to the center, chop off\n int imax_aa = iaa;\n for (i=iaa; iyvals[imax_aa] < dist->yvals[i] ) imax_aa = i;\n dist->nvals = imax_aa+1;\n if ( iaa>=dist->nvals ) iaa = dist->nvals-1;\n\n // find the maximum and scale the peaks (first draft: no attempt to join the segments smootly)\n double max_rr = 0, max_aa = 0, max_ra = 0, srr = 0, saa = 0, sra = 0;\n for (i=0; iyvals[i];\n if ( max_rr < dist->yvals[i] ) max_rr = dist->yvals[i];\n }\n for (i=irr; i<=iaa; i++)\n {\n sra += dist->yvals[i];\n if ( max_ra < dist->yvals[i] ) max_ra = dist->yvals[i];\n }\n for (i=iaa+1; iyvals[i];\n if ( max_aa < dist->yvals[i] ) max_aa = dist->yvals[i];\n }\n\n\n // Does the het peak exist at all? Usually the numbers are as follows:\n // 1: cn=0 ra/rr=0.205730 aa/ra=0.674922 nra=7066\n // 20: cn=0 ra/rr=0.258019 aa/ra=0.548929 nra=2381\n // X: cn=0 ra/rr=0.005976 aa/ra=44.116667 nra=60\n // Y: cn=0 ra/rr=0.008316 aa/ra=7.250000 nra=12\n // MT: cn=0 ra/rr=0.013699 aa/ra=0.666667 nra=3\n\n if ( !args->ra_rr_scaling ) max_ra = max_aa = max_rr;\n if ( !sra || (sra/srr<0.1 && saa/sra>1.0) ) // too few hets, CN1\n {\n max_ra = max_aa;\n dist->copy_number = 1;\n }\n else if ( sra/srr<0.1 || saa/sra>1.0 )\n {\n max_ra = max_aa;\n dist->copy_number = -1; // unknown copy number\n }\n if ( max_rr ) for (i=0; iyvals[i] /= max_rr;\n if ( max_ra ) for (i=irr; i<=iaa; i++) dist->yvals[i] /= max_ra;\n if ( max_aa ) for (i=iaa+1; iyvals[i] /= max_aa;\n\n dist->irr = irr;\n dist->iaa = iaa;\n dist->ira = n*0.5;\n\n if ( verbose )\n fprintf(stderr,\"%s:\\t irr,ira,iaa=%.2f,%.2f,%.2f \\t cn=%2d \\t ra/rr=%f \\t aa/ra=%f \\t nra=%d\\n\", \n dist->chr, dist->xvals[irr],dist->xvals[dist->ira],dist->xvals[iaa],\n dist->copy_number,sra/srr,saa/sra, (int)sra);\n}\n\nstatic void init_data(args_t *args)\n{\n bcf_srs_t *files = bcf_sr_init();\n if ( args->regions_list )\n {\n if ( bcf_sr_set_regions(files, args->regions_list, args->regions_is_file)<0 )\n error(\"Failed to read the regions: %s\\n\", args->regions_list);\n }\n if ( args->targets_list )\n {\n if ( bcf_sr_set_targets(files, args->targets_list, args->targets_is_file, 0)<0 )\n error(\"Failed to read the targets: %s\\n\", args->targets_list);\n }\n if ( !bcf_sr_add_reader(files, args->fname) ) error(\"Failed to open %s: %s\\n\", args->fname,bcf_sr_strerror(files->errnum));\n bcf_hdr_t *hdr = files->readers[0].header;\n if ( !args->sample )\n {\n if ( bcf_hdr_nsamples(hdr)>1 ) error(\"Missing the option -s, --sample\\n\");\n args->sample = hdr->samples[0];\n }\n else if ( bcf_hdr_id2int(hdr,BCF_DT_SAMPLE,args->sample)<0 ) error(\"No such sample: %s\\n\", args->sample);\n int ret = bcf_hdr_set_samples(hdr, args->sample, 0);\n if ( ret<0 ) error(\"Error setting the sample: %s\\n\", args->sample);\n\n if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,bcf_hdr_id2int(hdr,BCF_DT_ID,\"BAF\")) )\n error(\"The tag FORMAT/BAF is not present in the VCF: %s\\n\", args->fname);\n\n int i;\n args->xvals = (double*) calloc(args->nbins,sizeof(double));\n for (i=0; inbins; i++) args->xvals[i] = 1.0*i/(args->nbins-1);\n\n // collect BAF distributions for all chromosomes\n int idist = -1, nbaf = 0, nprocessed = 0, ntotal = 0, prev_chr = -1;\n float *baf = NULL;\n while ( bcf_sr_next_line(files) )\n {\n ntotal++;\n\n bcf1_t *line = bcf_sr_get_line(files,0);\n if ( bcf_get_format_float(hdr,line,\"BAF\",&baf,&nbaf) != 1 ) continue;\n if ( bcf_float_is_missing(baf[0]) ) continue;\n\n nprocessed++;\n\n if ( prev_chr==-1 || prev_chr!=line->rid )\n {\n // new chromosome\n idist = args->ndist++;\n args->dist = (dist_t*) realloc(args->dist, sizeof(dist_t)*args->ndist);\n memset(&args->dist[idist],0,sizeof(dist_t));\n args->dist[idist].chr = strdup(bcf_seqname(hdr,line));\n args->dist[idist].yvals = (double*) calloc(args->nbins,sizeof(double));\n args->dist[idist].xvals = args->xvals;\n args->dist[idist].nvals = args->nbins;\n prev_chr = line->rid;\n }\n int bin = baf[0]*(args->nbins-1);\n args->dist[idist].yvals[bin]++; // the distribution\n }\n free(baf);\n bcf_sr_destroy(files);\n\n for (idist=0; idistndist; idist++)\n {\n #if 0\n int j;\n for (j=0; jnbins; j++)\n {\n double x = args->dist[idist].xvals[j];\n args->dist[idist].yvals[j] = exp(-(x-0.5)*(x-0.5)/1e-3);\n }\n #endif\n init_dist(args, &args->dist[idist],args->verbose);\n }\n\n args->dat_fp = open_file(&args->dat_fname,\"w\",\"%s/dist.dat\", args->output_dir);\n fprintf(args->dat_fp, \"# This file was produced by: bcftools polysomy(%s+htslib-%s), the command line was:\\n\", bcftools_version(),hts_version());\n fprintf(args->dat_fp, \"# \\t bcftools %s \", args->argv[0]);\n for (i=1; iargc; i++)\n fprintf(args->dat_fp, \" %s\",args->argv[i]);\n fprintf(args->dat_fp,\"\\n#\\n\");\n fprintf(args->dat_fp,\"# DIST\\t[2]Chrom\\t[3]BAF\\t[4]Normalized Count\\n\");\n fprintf(args->dat_fp,\"# FIT\\t[2]Goodness of Fit\\t[3]iFrom\\t[4]iTo\\t[5]The Fitted Function\\n\");\n fprintf(args->dat_fp,\"# CN\\t[2]Chrom\\t[3]Estimated Copy Number\\t[4]Absolute fit deviation\\n\");\n\n char *fname = NULL;\n FILE *fp = open_file(&fname,\"w\",\"%s/dist.py\", args->output_dir);\n//-------- matplotlib script --------------\n fprintf(fp,\n \"#!/usr/bin/env python\\n\"\n \"#\\n\"\n \"import matplotlib as mpl\\n\"\n \"mpl.use('Agg')\\n\"\n \"import matplotlib.pyplot as plt\\n\"\n \"import csv,sys,argparse\\n\"\n \"from math import exp\\n\"\n \"\\n\"\n \"outdir = '%s'\\n\"\n \"\\n\"\n \"def read_dat(dat,fit,cn):\\n\"\n \" csv.register_dialect('tab', delimiter='\\t', quoting=csv.QUOTE_NONE)\\n\"\n \" with open(outdir+'/dist.dat', 'rb') as f:\\n\"\n \" reader = csv.reader(f, 'tab')\\n\"\n \" for row in reader:\\n\"\n \" if row[0][0]=='#': continue\\n\"\n \" type = row[0]\\n\"\n \" chr = row[1]\\n\"\n \" if type=='DIST':\\n\"\n \" if chr not in dat: dat[chr] = []\\n\"\n \" dat[chr].append(row)\\n\"\n \" elif type=='FIT':\\n\"\n \" if chr not in fit: fit[chr] = []\\n\"\n \" fit[chr].append(row)\\n\"\n \" elif type=='CN':\\n\"\n \" cn[chr] = row[2]\\n\"\n \"\\n\"\n \"def plot_dist(dat,fit,chr):\\n\"\n \" fig, ax = plt.subplots(1, 1, figsize=(7,5))\\n\"\n \" ax.plot([x[2] for x in dat[chr]],[x[3] for x in dat[chr]],'k-',label='Distribution')\\n\"\n \" if chr in fit:\\n\"\n \" for i in range(len(fit[chr])):\\n\"\n \" pfit = fit[chr][i]\\n\"\n \" exec('def xfit(x): return '+pfit[5])\\n\"\n \" istart = int(pfit[3])\\n\"\n \" iend = int(pfit[4])+1\\n\"\n \" vals = dat[chr][istart:iend]\\n\"\n \" args = {}\\n\"\n \" if i==0: args = {'label':'Target to Fit'}\\n\"\n \" ax.plot([x[2] for x in vals],[x[3] for x in vals],'r-',**args)\\n\"\n \" if i==0: args = {'label':'Best Fit'}\\n\"\n \" ax.plot([x[2] for x in vals],[xfit(float(x[2])) for x in vals],'g-',**args)\\n\"\n \" ax.set_title('BAF distribution, chr'+chr)\\n\"\n \" ax.set_xlabel('BAF')\\n\"\n \" ax.set_ylabel('Frequency')\\n\"\n \" ax.legend(loc='best',prop={'size':7},frameon=False)\\n\"\n \" plt.savefig(outdir+'/dist.chr'+chr+'.png')\\n\"\n \" plt.close()\\n\"\n \"\\n\"\n \"def plot_copy_number(cn):\\n\"\n \" fig, ax = plt.subplots(1, 1, figsize=(7,5))\\n\"\n \" xlabels = sorted(cn.keys())\\n\"\n \" xvals = range(len(xlabels))\\n\"\n \" yvals = [float(cn[x]) for x in xlabels]\\n\"\n \" ax.plot(xvals,yvals,'o',color='red')\\n\"\n \" for i in range(len(xvals)):\\n\"\n \" if yvals[i]==-1: ax.annotate('?', xy=(xvals[i],0.5),va='center',ha='center',color='red',fontweight='bold')\\n\"\n \" ax.tick_params(axis='both', which='major', labelsize=9)\\n\"\n \" ax.set_xticks(xvals)\\n\"\n \" ax.set_xticklabels(xlabels,rotation=45)\\n\"\n \" ax.set_xlim(-1,len(xlabels))\\n\"\n \" ax.set_ylim(0,5.0)\\n\"\n \" ax.set_yticks([1.0,2.0,3.0,4.0])\\n\"\n \" ax.set_xlabel('Chromosome')\\n\"\n \" ax.set_ylabel('Copy Number')\\n\"\n \" plt.savefig(outdir+'/copy-number.png')\\n\"\n \" plt.close()\\n\"\n \"\\n\"\n \"class myParser(argparse.ArgumentParser):\\n\"\n \" def error(self, message):\\n\"\n \" self.print_help()\\n\"\n \" sys.stderr.write('error: %%s\\\\n' %% message)\\n\"\n \" sys.exit(2)\\n\"\n \"\\n\"\n \"def main():\\n\"\n \" parser = myParser()\\n\"\n \" parser.add_argument('-a', '--all', action='store_true', help='Create all plots')\\n\"\n \" parser.add_argument('-c', '--copy-number', action='store_true', help='Create copy-number plot')\\n\"\n \" parser.add_argument('-d', '--distrib', metavar='CHR', help='Plot BAF distribution of a single chromosome')\\n\"\n \" args = parser.parse_args()\\n\"\n \" dat = {}; fit = {}; cn = {}\\n\"\n \" read_dat(dat,fit,cn)\\n\"\n \" if args.distrib!=None:\\n\"\n \" plot_dist(dat,fit,args.distrib)\\n\"\n \" if args.all:\\n\"\n \" for chr in dat: plot_dist(dat,fit,chr)\\n\"\n \" plot_copy_number(cn)\\n\"\n \" elif args.copy_number:\\n\"\n \" plot_copy_number(cn)\\n\"\n \" else:\\n\"\n \" for chr in dat: plot_dist(dat,fit,chr)\\n\"\n \"\\n\"\n \"if __name__ == '__main__':\\n\"\n \" main()\\n\",\n args->output_dir);\n//---------------------------------------\n chmod(fname, S_IWUSR|S_IRUSR|S_IRGRP|S_IROTH|S_IXUSR|S_IXGRP|S_IXOTH);\n free(fname);\n fclose(fp);\n}\n\nstatic void destroy_data(args_t *args)\n{\n int i;\n for (i=0; indist; i++)\n {\n free(args->dist[i].chr);\n free(args->dist[i].yvals);\n }\n free(args->dist);\n free(args->xvals);\n free(args->dat_fname);\n fclose(args->dat_fp);\n}\n\nstatic void save_dist(args_t *args, dist_t *dist)\n{\n int i;\n for (i=0; inbins; i++)\n fprintf(args->dat_fp,\"DIST\\t%s\\t%f\\t%f\\n\",dist->chr,dist->xvals[i],dist->yvals[i]);\n}\nstatic void fit_curves(args_t *args)\n{\n peakfit_t *pkf = peakfit_init();\n peakfit_verbose(pkf,args->verbose);\n\n int i, nmc = 50;\n for (i=0; indist; i++)\n {\n dist_t *dist = &args->dist[i];\n save_dist(args, &args->dist[i]);\n\n if ( dist->copy_number!=0 )\n {\n fprintf(args->dat_fp,\"CN\\t%s\\t%.2f\\n\", dist->chr,(float)dist->copy_number);\n continue;\n }\n\n if ( args->verbose )\n fprintf(stderr,\"%s:\\n\", dist->chr);\n\n int nrr_aa = dist->iaa - dist->irr + 1;\n int nrr_ra = dist->ira - dist->irr + 1;\n int naa_max = dist->nvals - dist->iaa;\n double xrr = dist->xvals[dist->irr], *xrr_vals = &dist->xvals[dist->irr], *yrr_vals = &dist->yvals[dist->irr];\n double xaa = dist->xvals[dist->iaa], *xaa_vals = &dist->xvals[dist->iaa], *yaa_vals = &dist->yvals[dist->iaa];\n double xra = dist->xvals[dist->ira];\n double xmax = dist->xvals[dist->nvals-1];\n\n\n // CN2\n double cn2aa_fit = 0, cn2ra_fit, cn2_fit;\n char *cn2aa_func = 0, *cn2ra_func;\n double cn2aa_params[3] = {1,1,1} ,cn2ra_params[3];\n if ( args->include_aa )\n {\n peakfit_reset(pkf);\n peakfit_add_exp(pkf, 1.0,1.0,0.2, 5);\n peakfit_set_mc(pkf, 0.01,0.3,2,nmc);\n peakfit_set_mc(pkf, 0.05,1.0,0,nmc);\n cn2aa_fit = peakfit_run(pkf, naa_max, xaa_vals, yaa_vals);\n cn2aa_func = strdup(peakfit_sprint_func(pkf));\n peakfit_get_params(pkf,0,cn2aa_params,3);\n }\n peakfit_reset(pkf);\n peakfit_add_bounded_gaussian(pkf, 1.0,0.5,0.03, 0.45,0.55, 7);\n peakfit_set_mc(pkf, 0.01,0.3,2,nmc);\n peakfit_set_mc(pkf, 0.05,1.0,0,nmc);\n cn2ra_fit = peakfit_run(pkf, nrr_aa,xrr_vals,yrr_vals);\n cn2ra_func = strdup(peakfit_sprint_func(pkf));\n cn2_fit = cn2ra_fit + cn2aa_fit;\n peakfit_get_params(pkf,0,cn2ra_params,3);\n\n\n // CN3: fit two peaks, then enforce the symmetry and fit again\n double cn3rra_params[5], cn3raa_params[5], *cn3aa_params = cn2aa_params;\n double cn3aa_fit = cn2aa_fit, cn3ra_fit;\n char *cn3aa_func = cn2aa_func, *cn3ra_func;\n double min_dx3 = 0.5 - 1./(args->min_fraction+2);\n peakfit_reset(pkf);\n peakfit_add_bounded_gaussian(pkf, 1.0,1/3.,0.03, xrr,xra-min_dx3, 7);\n peakfit_set_mc(pkf, xrr,xra-min_dx3, 1,nmc);\n peakfit_add_bounded_gaussian(pkf, 1.0,2/3.,0.03, xra+min_dx3,xaa, 7);\n peakfit_set_mc(pkf, xra+min_dx3,xaa, 1,nmc);\n peakfit_run(pkf, nrr_aa, xrr_vals, yrr_vals);\n // force symmetry around x=0.5\n peakfit_get_params(pkf,0,cn3rra_params,5);\n peakfit_get_params(pkf,1,cn3raa_params,5);\n double cn3_dx = (0.5-cn3rra_params[1] + cn3raa_params[1]-0.5)*0.5;\n if ( cn3_dx > 0.5/3 ) cn3_dx = 0.5/3; // CN3 peaks should not be separated by more than 1/3\n peakfit_reset(pkf);\n peakfit_add_gaussian(pkf, cn3rra_params[0],0.5-cn3_dx,cn3rra_params[2], 5);\n peakfit_add_gaussian(pkf, cn3raa_params[0],0.5+cn3_dx,cn3raa_params[2], 5);\n cn3ra_fit = peakfit_run(pkf, nrr_aa, xrr_vals, yrr_vals);\n cn3ra_func = strdup(peakfit_sprint_func(pkf));\n // compare peak sizes\n peakfit_get_params(pkf,0,cn3rra_params,3);\n peakfit_get_params(pkf,1,cn3raa_params,3);\n double cn3rra_size = cn3rra_params[0]*cn3rra_params[0];\n double cn3raa_size = cn3raa_params[0]*cn3raa_params[0];\n double cn3_dy = cn3rra_size > cn3raa_size ? cn3raa_size/cn3rra_size : cn3rra_size/cn3raa_size;\n double cn3_frac = (1 - 2*cn3rra_params[1]) / cn3rra_params[1];\n double cn3_fit = cn3ra_fit + cn3aa_fit;\n // A very reasonable heuristics: check if the peak's width converged, exclude far too broad or far too narrow peaks\n if ( cn3rra_params[2]>0.3 || cn3raa_params[2]>0.3 ) cn3_fit = HUGE_VAL;\n if ( cn3rra_params[2]<1e-2 || cn3raa_params[2]<1e-2 ) cn3_fit = HUGE_VAL;\n\n\n // CN4 (contaminations)\n // - first fit only the [0,0.5] part of the data, then enforce the symmetry and fit again\n // - min_frac=1 (resp. 0.5) is interpreted as 50:50% (rep. 75:25%) contamination\n double cn4AAaa_params[3] = {1,1,1} ,cn4AAra_params[3] = {1,1,1}, cn4RAra_params[3], cn4RArr_params[5], cn4RAaa_params[5];\n double cn4aa_fit = 0, cn4ra_fit;\n char *cn4aa_func = 0, *cn4ra_func;\n double min_dx4 = 0.25*args->min_fraction;\n if ( args->include_aa )\n {\n peakfit_reset(pkf);\n peakfit_add_exp(pkf, 0.5,1.0,0.2, 5);\n peakfit_set_mc(pkf, 0.01,0.3,2,nmc);\n peakfit_add_bounded_gaussian(pkf, 0.4,(xaa+xmax)*0.5,2e-2, xaa,xmax, 7);\n peakfit_set_mc(pkf, xaa,xmax, 1,nmc);\n cn4aa_fit = peakfit_run(pkf, naa_max, xaa_vals,yaa_vals);\n cn4aa_func = strdup(peakfit_sprint_func(pkf));\n peakfit_get_params(pkf,0,cn4AAaa_params,3);\n peakfit_get_params(pkf,1,cn4AAra_params,5);\n }\n peakfit_reset(pkf);\n // first fit only the [0,0.5] part of the data\n peakfit_add_gaussian(pkf, 1.0,0.5,0.03, 5);\n peakfit_add_bounded_gaussian(pkf, 0.6,0.3,0.03, xrr,xra-min_dx4, 7);\n peakfit_set_mc(pkf, xrr,xra-min_dx4,2,nmc);\n peakfit_run(pkf, nrr_ra , xrr_vals, yrr_vals);\n // now forcet symmetry around x=0.5\n peakfit_get_params(pkf,0,cn4RAra_params,3);\n peakfit_get_params(pkf,1,cn4RArr_params,5);\n double cn4_dx = 0.5-cn4RArr_params[1];\n if ( cn4_dx > 0.25 ) cn4_dx = 0.25; // CN4 peaks should not be separated by more than 0.5\n peakfit_reset(pkf);\n peakfit_add_gaussian(pkf, cn4RAra_params[0],0.5,cn4RAra_params[2], 5);\n peakfit_add_gaussian(pkf, cn4RArr_params[0],0.5-cn4_dx,cn4RArr_params[2], 5);\n peakfit_add_gaussian(pkf, cn4RArr_params[0],0.5+cn4_dx,cn4RArr_params[2], 5);\n peakfit_set_mc(pkf, 0.1,cn4RAra_params[0],0,nmc);\n peakfit_set_mc(pkf, 0.01,0.1,2,nmc);\n cn4ra_fit = peakfit_run(pkf, nrr_aa , xrr_vals, yrr_vals);\n cn4ra_func = strdup(peakfit_sprint_func(pkf));\n peakfit_get_params(pkf,0,cn4RAra_params,3);\n peakfit_get_params(pkf,1,cn4RArr_params,3);\n peakfit_get_params(pkf,2,cn4RAaa_params,3);\n double cn4RAra_size = cn4RAra_params[0]==0 ? HUGE_VAL : cn4RAra_params[0]*cn4RAra_params[0];\n double cn4RArr_size = cn4RArr_params[0]*cn4RArr_params[0];\n double cn4RAaa_size = cn4RAaa_params[0]*cn4RAaa_params[0];\n double cn4RArr_dy = cn4RArr_size < cn4RAra_size ? cn4RArr_size/cn4RAra_size : cn4RAra_size/cn4RArr_size;\n double cn4RAaa_dy = cn4RAaa_size < cn4RAra_size ? cn4RAaa_size/cn4RAra_size : cn4RAra_size/cn4RAaa_size;\n double cn4_dy = cn4RArr_dy < cn4RAaa_dy ? cn4RArr_dy/cn4RAaa_dy : cn4RAaa_dy/cn4RArr_dy;\n double cn4_ymin = cn4RArr_size < cn4RAaa_size ? cn4RArr_size/cn4RAra_size : cn4RAaa_size/cn4RAra_size;\n cn4_dx = (cn4RAaa_params[1]-0.5) - (0.5-cn4RArr_params[1]);\n double cn4_frac = cn4RAaa_params[1] - cn4RArr_params[1];\n double cn4_fit = cn4ra_fit + cn4aa_fit;\n // A very reasonable heuristics: check if the peak's width converged, exclude far too broad or far too narrow peaks\n if ( cn4RAra_params[2]>0.3 || cn4RArr_params[2]>0.3 || cn4RAaa_params[2]>0.3 ) cn4_fit = HUGE_VAL;\n if ( cn4RAra_params[2]<1e-2 || cn4RArr_params[2]<1e-2 || cn4RAaa_params[2]<1e-2 ) cn4_fit = HUGE_VAL;\n\n\n // Choose the best match\n char cn2_fail = '*', cn3_fail = '*', cn4_fail = '*';\n if ( cn2_fit > args->fit_th ) cn2_fail = 'f';\n\n if ( cn3_fit > args->fit_th ) cn3_fail = 'f';\n else if ( cn3_dy < args->peak_symmetry ) cn3_fail = 'y'; // size difference is too big\n\n if ( cn4_fit > args->fit_th ) cn4_fail = 'f';\n else if ( cn4_ymin < args->min_peak_size ) cn4_fail = 'y'; // side peak is too small\n else if ( cn4_dy < args->peak_symmetry ) cn4_fail = 'Y'; // size difference is too big\n else if ( cn4_dx > 0.1 ) cn4_fail = 'x'; // side peaks placed assymetrically\n\n double cn = -1, fit = cn2_fit;\n if ( cn2_fail == '*' ) { cn = 2; fit = cn2_fit; }\n if ( cn3_fail == '*' )\n {\n // Use cn_penalty as a tiebreaker. If set to 0.3, cn3_fit must be 30% smaller than cn2_fit.\n if ( cn<0 || cn3_fit < (1-args->cn_penalty) * fit )\n {\n cn = 2 + cn3_frac; \n fit = cn3_fit; \n if ( cn2_fail=='*' ) cn2_fail = 'p';\n }\n else cn3_fail = 'p';\n }\n if ( cn4_fail == '*' )\n {\n if ( cn<0 || cn4_fit < (1-args->cn_penalty) * fit )\n {\n cn = 3 + cn4_frac;\n fit = cn4_fit;\n if ( cn2_fail=='*' ) cn2_fail = 'p';\n if ( cn3_fail=='*' ) cn3_fail = 'p';\n }\n else cn4_fail = 'p';\n }\n\n if ( args->verbose )\n {\n fprintf(stderr,\"\\tcn2 %c fit=%e\\n\", cn2_fail, cn2_fit);\n fprintf(stderr,\"\\t .. %e\\n\", cn2ra_fit);\n fprintf(stderr,\"\\t RA: %f %f %f\\n\", cn2ra_params[0],cn2ra_params[1],cn2ra_params[2]);\n fprintf(stderr,\"\\t .. %e\\n\", cn2aa_fit);\n fprintf(stderr,\"\\t AA: %f %f %f\\n\", cn2aa_params[0],cn2aa_params[1],cn2aa_params[2]);\n fprintf(stderr,\"\\t func:\\n\");\n fprintf(stderr,\"\\t %s\\n\", cn2ra_func);\n fprintf(stderr,\"\\t %s\\n\", cn2aa_func);\n fprintf(stderr,\"\\n\");\n fprintf(stderr,\"\\tcn3 %c fit=%e frac=%f symmetry=%f\\n\", cn3_fail, cn3_fit, cn3_frac, cn3_dy);\n fprintf(stderr,\"\\t .. %e\\n\", cn3ra_fit);\n fprintf(stderr,\"\\t RRA: %f %f %f\\n\", cn3rra_params[0],cn3rra_params[1],cn3rra_params[2]);\n fprintf(stderr,\"\\t RAA: %f %f %f\\n\", cn3raa_params[0],cn3raa_params[1],cn3raa_params[2]);\n fprintf(stderr,\"\\t .. %e\\n\", cn3aa_fit);\n fprintf(stderr,\"\\t AAA: %f %f %f\\n\", cn3aa_params[0],cn3aa_params[1],cn3aa_params[2]);\n fprintf(stderr,\"\\t func:\\n\");\n fprintf(stderr,\"\\t %s\\n\", cn3ra_func);\n fprintf(stderr,\"\\t %s\\n\", cn3aa_func);\n fprintf(stderr,\"\\n\");\n fprintf(stderr,\"\\tcn4 %c fit=%e frac=%f symmetry=%f ymin=%f\\n\", cn4_fail, cn4_fit, cn4_frac, cn4_dy, cn4_ymin);\n fprintf(stderr,\"\\t .. %e\\n\", cn4ra_fit);\n fprintf(stderr,\"\\t RArr: %f %f %f\\n\", cn4RArr_params[0],cn4RArr_params[1],cn4RArr_params[2]);\n fprintf(stderr,\"\\t RAra: %f %f %f\\n\", cn4RAra_params[0],cn4RAra_params[1],cn4RAra_params[2]);\n fprintf(stderr,\"\\t RAaa: %f %f %f\\n\", cn4RAaa_params[0],cn4RAaa_params[1],cn4RAaa_params[2]);\n fprintf(stderr,\"\\t .. %e\\n\", cn4aa_fit);\n fprintf(stderr,\"\\t AAaa: %f %f %f\\n\", cn4AAaa_params[0],cn4AAaa_params[1],cn4AAaa_params[2]);\n fprintf(stderr,\"\\t func:\\n\");\n fprintf(stderr,\"\\t %s\\n\", cn4ra_func);\n fprintf(stderr,\"\\t %s\\n\", cn4aa_func);\n fprintf(stderr,\"\\n\");\n }\n\n if ( args->force_cn==2 || cn2_fail == '*' )\n {\n fprintf(args->dat_fp,\"FIT\\t%s\\t%e\\t%d\\t%d\\t%s\\n\", dist->chr,cn2ra_fit,dist->irr,dist->iaa,cn2ra_func);\n if ( cn2aa_func ) fprintf(args->dat_fp,\"FIT\\t%s\\t%e\\t%d\\t%d\\t%s\\n\", dist->chr,cn2aa_fit,dist->iaa,dist->nvals-1,cn2aa_func);\n }\n if ( args->force_cn==3 || cn3_fail == '*' )\n {\n fprintf(args->dat_fp,\"FIT\\t%s\\t%e\\t%d\\t%d\\t%s\\n\", dist->chr,cn3ra_fit,dist->irr,dist->iaa,cn3ra_func);\n if ( cn3aa_func ) fprintf(args->dat_fp,\"FIT\\t%s\\t%e\\t%d\\t%d\\t%s\\n\", dist->chr,cn3aa_fit,dist->iaa,dist->nvals-1,cn3aa_func);\n }\n if ( args->force_cn==4 || cn4_fail == '*' )\n {\n fprintf(args->dat_fp,\"FIT\\t%s\\t%e\\t%d\\t%d\\t%s\\n\", dist->chr,cn4ra_fit,dist->irr,dist->iaa,cn4ra_func);\n if ( cn4aa_func ) fprintf(args->dat_fp,\"FIT\\t%s\\t%e\\t%d\\t%d\\t%s\\n\", dist->chr,cn4aa_fit,dist->iaa,dist->nvals-1,cn4aa_func);\n }\n fprintf(args->dat_fp,\"CN\\t%s\\t%.2f\\t%f\\n\", dist->chr, cn, fit);\n\n free(cn2aa_func);\n free(cn2ra_func);\n free(cn3ra_func);\n free(cn4ra_func);\n free(cn4aa_func);\n }\n\n peakfit_destroy(pkf);\n}\n\nstatic void usage(args_t *args)\n{\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"About: Detect number of chromosomal copies from Illumina's B-allele frequency (BAF)\\n\");\n fprintf(stderr, \"Usage: bcftools polysomy [OPTIONS] \\n\");\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"General options:\\n\");\n fprintf(stderr, \" -o, --output-dir \\n\");\n fprintf(stderr, \" -r, --regions restrict to comma-separated list of regions\\n\");\n fprintf(stderr, \" -R, --regions-file restrict to regions listed in a file\\n\");\n fprintf(stderr, \" -s, --sample sample to analyze\\n\");\n fprintf(stderr, \" -t, --targets similar to -r but streams rather than index-jumps\\n\");\n fprintf(stderr, \" -T, --targets-file similar to -R but streams rather than index-jumps\\n\");\n fprintf(stderr, \" -v, --verbose \\n\");\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"Algorithm options:\\n\");\n fprintf(stderr, \" -b, --peak-size minimum peak size (0-1, larger is stricter) [0.1]\\n\");\n fprintf(stderr, \" -c, --cn-penalty penalty for increasing CN (0-1, larger is stricter) [0.7]\\n\");\n fprintf(stderr, \" -f, --fit-th goodness of fit threshold (>0, smaller is stricter) [3.3]\\n\");\n fprintf(stderr, \" -i, --include-aa include the AA peak in CN2 and CN3 evaluation\\n\");\n fprintf(stderr, \" -m, --min-fraction minimum distinguishable fraction of aberrant cells [0.1]\\n\");\n fprintf(stderr, \" -p, --peak-symmetry peak symmetry threshold (0-1, larger is stricter) [0.5]\\n\");\n fprintf(stderr, \"\\n\");\n exit(1);\n}\n\nint main_polysomy(int argc, char *argv[])\n{\n args_t *args = (args_t*) calloc(1,sizeof(args_t));\n args->argc = argc; args->argv = argv;\n args->nbins = 150;\n args->fit_th = 3.3;\n args->cn_penalty = 0.7;\n args->peak_symmetry = 0.5;\n args->min_peak_size = 0.1;\n args->ra_rr_scaling = 1;\n args->min_fraction = 0.1;\n args->smooth = -3;\n\n static struct option loptions[] =\n {\n {\"ra-rr-scaling\",0,0,1}, // hidden option\n {\"force-cn\",1,0,2}, // hidden option\n {\"smooth\",1,0,'S'}, // hidden option\n {\"nbins\",1,0,'n'}, // hidden option\n {\"include-aa\",0,0,'i'},\n {\"peak-size\",1,0,'b'},\n {\"min-fraction\",1,0,'m'},\n {\"verbose\",0,0,'v'},\n {\"fit-th\",1,0,'f'},\n {\"cn-penalty\",1,0,'c'},\n {\"peak-symmetry\",1,0,'p'},\n {\"output-dir\",1,0,'o'},\n {\"sample\",1,0,'s'},\n {\"targets\",1,0,'t'},\n {\"targets-file\",1,0,'T'},\n {\"regions\",1,0,'r'},\n {\"regions-file\",1,0,'R'},\n {0,0,0,0}\n };\n char c, *tmp;\n while ((c = getopt_long(argc, argv, \"h?o:vt:T:r:R:s:f:p:c:im:b:n:S:\",loptions,NULL)) >= 0)\n {\n switch (c)\n {\n case 1 : args->ra_rr_scaling = 0; break;\n case 2 : args->force_cn = atoi(optarg); break;\n case 'n': args->nbins = atoi(optarg); break;\n case 'S': args->smooth = atoi(optarg); break;\n case 'i': args->include_aa = 1; break;\n case 'b':\n args->min_peak_size = strtod(optarg,&tmp);\n if ( *tmp ) error(\"Could not parse: -b %s\\n\", optarg);\n if ( args->min_peak_size<0 || args->min_peak_size>1 ) error(\"Range error: -b %s\\n\", optarg);\n break;\n case 'm':\n args->min_fraction = strtod(optarg,&tmp);\n if ( *tmp ) error(\"Could not parse: -n %s\\n\", optarg);\n if ( args->min_fraction<0 || args->min_fraction>1 ) error(\"Range error: -n %s\\n\", optarg);\n break;\n case 'f':\n args->fit_th = strtod(optarg,&tmp);\n if ( *tmp ) error(\"Could not parse: -f %s\\n\", optarg);\n break;\n case 'p':\n args->peak_symmetry = strtod(optarg,&tmp);\n if ( *tmp ) error(\"Could not parse: -p %s\\n\", optarg);\n break;\n case 'c':\n args->cn_penalty = strtod(optarg,&tmp);\n if ( *tmp ) error(\"Could not parse: -c %s\\n\", optarg);\n break;\n case 's': args->sample = optarg; break;\n case 't': args->targets_list = optarg; break;\n case 'T': args->targets_list = optarg; args->targets_is_file = 1; break;\n case 'r': args->regions_list = optarg; break;\n case 'R': args->regions_list = optarg; args->regions_is_file = 1; break;\n case 'o': args->output_dir = optarg; break;\n case 'v': args->verbose++; break;\n default: usage(args); break;\n }\n }\n if ( optind>=argc )\n {\n if ( !isatty(fileno((FILE *)stdin)) ) args->fname = \"-\";\n }\n else args->fname = argv[optind];\n if ( !args->fname ) usage(args);\n if ( !args->output_dir ) error(\"Missing the -o option\\n\");\n\n init_data(args);\n fit_curves(args);\n destroy_data(args);\n free(args);\n\n return 0;\n}\n\n\n", "meta": {"hexsha": "c5a5394e1119e3eff92972ca4353fd25b4f2808e", "size": 32362, "ext": "c", "lang": "C", "max_stars_repo_path": "USAP_H37Rv/Tools/bcftools-1.3/polysomy.c", "max_stars_repo_name": "SANBI-SA-archive/s_bvc_pipeline", "max_stars_repo_head_hexsha": "43948b4ea5db6333633361dd91f7e7b320392fb2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "USAP_H37Rv/Tools/bcftools-1.3/polysomy.c", "max_issues_repo_name": "SANBI-SA-archive/s_bvc_pipeline", "max_issues_repo_head_hexsha": "43948b4ea5db6333633361dd91f7e7b320392fb2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "USAP_H37Rv/Tools/bcftools-1.3/polysomy.c", "max_forks_repo_name": "SANBI-SA-archive/s_bvc_pipeline", "max_forks_repo_head_hexsha": "43948b4ea5db6333633361dd91f7e7b320392fb2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.9104477612, "max_line_length": 149, "alphanum_fraction": 0.5546010753, "num_tokens": 10434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5736783928749127, "lm_q2_score": 0.3738758227716966, "lm_q1q2_score": 0.2144844811424526}} {"text": "/* multilarge_nlinear/fdf.c\n * \n * Copyright (C) 2015, 2016 Patrick Alken\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ngsl_multilarge_nlinear_workspace *\ngsl_multilarge_nlinear_alloc (const gsl_multilarge_nlinear_type * T, \n const gsl_multilarge_nlinear_parameters * params,\n const size_t n, const size_t p)\n{\n gsl_multilarge_nlinear_workspace * w;\n\n if (n < p)\n {\n GSL_ERROR_VAL (\"insufficient data points, n < p\", GSL_EINVAL, 0);\n }\n\n w = calloc (1, sizeof (gsl_multilarge_nlinear_workspace));\n if (w == 0)\n {\n GSL_ERROR_VAL (\"failed to allocate space for workspace\",\n GSL_ENOMEM, 0);\n }\n\n w->n = n;\n w->p = p;\n w->type = T;\n w->fdf = NULL;\n w->niter = 0;\n w->params = *params;\n\n /* the cgst method uses its own built-in linear solver */\n if (w->params.trs == gsl_multilarge_nlinear_trs_cgst)\n {\n w->params.solver = gsl_multilarge_nlinear_solver_none;\n }\n\n w->x = gsl_vector_calloc (p);\n if (w->x == 0) \n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for x\", GSL_ENOMEM, 0);\n }\n\n w->f = gsl_vector_calloc (n);\n if (w->f == 0) \n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for f\", GSL_ENOMEM, 0);\n }\n\n w->dx = gsl_vector_calloc (p);\n if (w->dx == 0) \n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for dx\", GSL_ENOMEM, 0);\n }\n\n w->g = gsl_vector_alloc (p);\n if (w->g == 0) \n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for g\", GSL_ENOMEM, 0);\n }\n\n if (w->params.solver == gsl_multilarge_nlinear_solver_cholesky ||\n w->params.solver == gsl_multilarge_nlinear_solver_mcholesky)\n {\n w->JTJ = gsl_matrix_alloc (p, p);\n if (w->JTJ == 0) \n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for JTJ\", GSL_ENOMEM, 0);\n }\n }\n\n w->sqrt_wts_work = gsl_vector_calloc (n);\n if (w->sqrt_wts_work == 0)\n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for weights\", GSL_ENOMEM, 0);\n }\n\n w->state = (T->alloc)(&(w->params), n, p);\n if (w->state == 0)\n {\n gsl_multilarge_nlinear_free (w);\n GSL_ERROR_VAL (\"failed to allocate space for state\", GSL_ENOMEM, 0);\n }\n\n return w;\n}\n\nvoid\ngsl_multilarge_nlinear_free (gsl_multilarge_nlinear_workspace * w)\n{\n RETURN_IF_NULL (w);\n\n if (w->state)\n (w->type->free) (w->state);\n\n if (w->dx)\n gsl_vector_free (w->dx);\n\n if (w->x)\n gsl_vector_free (w->x);\n\n if (w->f)\n gsl_vector_free (w->f);\n\n if (w->sqrt_wts_work)\n gsl_vector_free (w->sqrt_wts_work);\n\n if (w->g)\n gsl_vector_free (w->g);\n\n if (w->JTJ)\n gsl_matrix_free (w->JTJ);\n\n free (w);\n}\n\ngsl_multilarge_nlinear_parameters\ngsl_multilarge_nlinear_default_parameters(void)\n{\n gsl_multilarge_nlinear_parameters params;\n\n params.trs = gsl_multilarge_nlinear_trs_lm;\n params.scale = gsl_multilarge_nlinear_scale_more;\n params.solver = gsl_multilarge_nlinear_solver_cholesky;\n params.fdtype = GSL_MULTILARGE_NLINEAR_FWDIFF;\n params.factor_up = 3.0;\n params.factor_down = 2.0;\n params.avmax = 0.75;\n params.h_df = GSL_SQRT_DBL_EPSILON;\n params.h_fvv = 0.01;\n params.max_iter = 0;\n params.tol = 1.0e-6;\n\n return params;\n}\n\nint\ngsl_multilarge_nlinear_init (const gsl_vector * x,\n gsl_multilarge_nlinear_fdf * fdf,\n gsl_multilarge_nlinear_workspace * w)\n{\n return gsl_multilarge_nlinear_winit(x, NULL, fdf, w);\n}\n\nint\ngsl_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{\n const size_t n = w->f->size;\n\n if (n != fdf->n)\n {\n GSL_ERROR (\"function size does not match workspace\", GSL_EBADLEN);\n }\n else if (w->x->size != x->size)\n {\n GSL_ERROR (\"vector length does not match workspace\", GSL_EBADLEN);\n }\n else if (wts != NULL && n != wts->size)\n {\n GSL_ERROR (\"weight vector length does not match workspace\", GSL_EBADLEN);\n }\n else\n {\n size_t i;\n\n /* initialize counters for function and Jacobian evaluations */\n fdf->nevalf = 0;\n fdf->nevaldfu = 0;\n fdf->nevaldf2 = 0;\n fdf->nevalfvv = 0;\n\n w->fdf = fdf;\n gsl_vector_memcpy(w->x, x);\n w->niter = 0;\n\n if (wts)\n {\n w->sqrt_wts = w->sqrt_wts_work;\n\n for (i = 0; i < n; ++i)\n {\n double wi = gsl_vector_get(wts, i);\n gsl_vector_set(w->sqrt_wts, i, sqrt(wi));\n }\n }\n else\n {\n w->sqrt_wts = NULL;\n }\n \n return (w->type->init) (w->state, w->sqrt_wts, w->fdf,\n w->x, w->f, w->g, w->JTJ);\n }\n}\n\nint\ngsl_multilarge_nlinear_iterate (gsl_multilarge_nlinear_workspace * w)\n{\n int status =\n (w->type->iterate) (w->state, w->sqrt_wts, w->fdf,\n w->x, w->f, w->g, w->JTJ, w->dx);\n\n w->niter++;\n\n return status;\n}\n\ndouble\ngsl_multilarge_nlinear_avratio (const gsl_multilarge_nlinear_workspace * w)\n{\n return (w->type->avratio) (w->state);\n}\n\nint\ngsl_multilarge_nlinear_rcond (double * rcond, const gsl_multilarge_nlinear_workspace * w)\n{\n int status = (w->type->rcond) (rcond, w->JTJ, w->state);\n return status;\n}\n\nint\ngsl_multilarge_nlinear_covar (gsl_matrix * covar, gsl_multilarge_nlinear_workspace * w)\n{\n if (covar->size1 != covar->size2)\n {\n GSL_ERROR (\"covariance matrix must be square\", GSL_ENOTSQR);\n }\n else if (covar->size1 != w->p)\n {\n GSL_ERROR (\"covariance matrix does not match workspace\", GSL_EBADLEN);\n }\n else\n {\n int status = (w->type->covar) (w->JTJ, covar, w->state);\n return status;\n }\n}\n\n/*\ngsl_multilarge_nlinear_driver()\n Iterate the nonlinear least squares solver until completion\n\nInputs: maxiter - maximum iterations to allow\n xtol - tolerance in step x\n gtol - tolerance in gradient\n ftol - tolerance in ||f||\n callback - callback function to call each iteration\n callback_params - parameters to pass to callback function\n info - (output) info flag on why iteration terminated\n 1 = stopped due to small step size ||dx|\n 2 = stopped due to small gradient\n 3 = stopped due to small change in f\n GSL_ETOLX = ||dx|| has converged to within machine\n precision (and xtol is too small)\n GSL_ETOLG = ||g||_inf is smaller than machine\n precision (gtol is too small)\n GSL_ETOLF = change in ||f|| is smaller than machine\n precision (ftol is too small)\n w - workspace\n\nReturn:\nGSL_SUCCESS if converged\nGSL_MAXITER if maxiter exceeded without converging\nGSL_ENOPROG if no accepted step found on first iteration\n*/\n\nint\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{\n int status;\n size_t iter = 0;\n\n /* call user callback function prior to any iterations\n * with initial system state */\n if (callback)\n callback(iter, callback_params, w);\n\n do\n {\n status = gsl_multilarge_nlinear_iterate (w);\n\n /*\n * If the solver reports no progress on the first iteration,\n * then it didn't find a single step to reduce the\n * cost function and more iterations won't help so return.\n *\n * If we get a no progress flag on subsequent iterations,\n * it means we did find a good step in a previous iteration,\n * so continue iterating since the solver has now reset\n * mu to its initial value.\n */\n if (status == GSL_ENOPROG && iter == 0)\n {\n *info = status;\n return GSL_EMAXITER;\n }\n\n ++iter;\n\n if (callback)\n callback(iter, callback_params, w);\n\n /* test for convergence */\n status = gsl_multilarge_nlinear_test(xtol, gtol, ftol, info, w);\n }\n while (status == GSL_CONTINUE && iter < maxiter);\n\n /*\n * the following error codes mean that the solution has converged\n * to within machine precision, so record the error code in info\n * and return success\n */\n if (status == GSL_ETOLF || status == GSL_ETOLX || status == GSL_ETOLG)\n {\n *info = status;\n status = GSL_SUCCESS;\n }\n\n /* check if max iterations reached */\n if (iter >= maxiter && status != GSL_SUCCESS)\n status = GSL_EMAXITER;\n\n return status;\n} /* gsl_multilarge_nlinear_driver() */\n\nconst char *\ngsl_multilarge_nlinear_name (const gsl_multilarge_nlinear_workspace * w)\n{\n return w->type->name;\n}\n\ngsl_vector *\ngsl_multilarge_nlinear_position (const gsl_multilarge_nlinear_workspace * w)\n{\n return w->x;\n}\n\ngsl_vector *\ngsl_multilarge_nlinear_residual (const gsl_multilarge_nlinear_workspace * w)\n{\n return w->f;\n}\n\ngsl_vector *\ngsl_multilarge_nlinear_step (const gsl_multilarge_nlinear_workspace * w)\n{\n return w->dx;\n}\n\nsize_t\ngsl_multilarge_nlinear_niter (const gsl_multilarge_nlinear_workspace * w)\n{\n return w->niter;\n}\n\nconst char *\ngsl_multilarge_nlinear_trs_name (const gsl_multilarge_nlinear_workspace * w)\n{\n return w->params.trs->name;\n}\n\n/*\ngsl_multilarge_nlinear_eval_f()\n Compute residual vector y with user callback function, and apply\nweighting transform if given:\n\ny~ = sqrt(W) y\n\nInputs: fdf - callback function\n x - model parameters\n swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn))\n set to NULL for unweighted fit\n y - (output) (weighted) residual vector\n y_i = sqrt(w_i) f_i where f_i is unweighted residual\n*/\n\nint\ngsl_multilarge_nlinear_eval_f(gsl_multilarge_nlinear_fdf *fdf,\n const gsl_vector *x,\n const gsl_vector *swts,\n gsl_vector *y)\n{\n int s = ((*((fdf)->f)) (x, fdf->params, y));\n\n ++(fdf->nevalf);\n\n /* y <- sqrt(W) y */\n if (swts)\n gsl_vector_mul(y, swts);\n\n return s;\n}\n\n/*\ngsl_multilarge_nlinear_eval_df()\n Compute Jacobian matrix-vector product:\n \nv = J * u\n\nor\n\nv = J^T u\n\nInputs: TransJ - use J or J^T\n x - model parameters\n f - residual vector f(x)\n u - input vector u\n swts - weight matrix W = diag(w1,w2,...,wn)\n set to NULL for unweighted fit\n h - finite difference step size\n fdtype - finite difference method\n fdf - callback function\n v - (output) vector v\n JTJ - (output) matrix J^T J\n work - workspace for finite difference, size n\n*/\n\nint\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{\n const size_t n = fdf->n;\n const size_t p = fdf->p;\n\n if (u != NULL && ((TransJ == CblasNoTrans && u->size != p) ||\n (TransJ == CblasTrans && u->size != n)))\n {\n GSL_ERROR(\"u vector has wrong size\", GSL_EBADLEN);\n }\n else if (v != NULL && ((TransJ == CblasNoTrans && v->size != n) ||\n (TransJ == CblasTrans && v->size != p)))\n {\n GSL_ERROR(\"v vector has wrong size\", GSL_EBADLEN);\n }\n else if (JTJ != NULL && ((JTJ->size1 != p) || (JTJ->size2 != p)))\n {\n GSL_ERROR(\"JTJ matrix has wrong size\", GSL_EBADLEN);\n }\n else\n {\n int status = GSL_SUCCESS;\n\n if (fdf->df)\n {\n /* call user-supplied function */\n status = ((*((fdf)->df)) (TransJ, x, u, fdf->params, v, JTJ));\n\n if (v)\n ++(fdf->nevaldfu);\n\n if (JTJ)\n ++(fdf->nevaldf2);\n }\n else\n {\n#if 0\n /* use finite difference Jacobian approximation */\n status = gsl_multilarge_nlinear_df(h, fdtype, x, swts, fdf, f, df, work);\n#endif\n }\n\n return status;\n }\n}\n\n/*\ngsl_multilarge_nlinear_eval_fvv()\n Compute second direction derivative vector yvv with user\ncallback function, and apply weighting transform if given:\n\nyvv~ = sqrt(W) yvv\n\nInputs: h - step size for finite difference, if needed\n x - model parameters, size p\n v - unscaled geodesic velocity vector, size p\n f - residual vector f(x), size n\n swts - weight matrix sqrt(W) = sqrt(diag(w1,w2,...,wn))\n set to NULL for unweighted fit\n fdf - callback function\n yvv - (output) (weighted) second directional derivative vector\n yvv_i = sqrt(w_i) fvv_i where f_i is unweighted\n work - workspace, size p\n*/\n\nint\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 int status = GSL_SUCCESS;\n \n if (fdf->fvv != NULL)\n {\n /* call user-supplied function */\n status = ((*((fdf)->fvv)) (x, v, fdf->params, yvv));\n ++(fdf->nevalfvv);\n }\n else\n {\n#if 0\n /* use finite difference approximation */\n status = gsl_multilarge_nlinear_fdfvv(h, x, v, f, J,\n swts, fdf, yvv, work);\n#endif\n }\n\n /* yvv <- sqrt(W) yvv */\n if (swts)\n gsl_vector_mul(yvv, swts);\n\n return status;\n}\n", "meta": {"hexsha": "bdea91c8c798b0d2e1fd0006ab9941f386442d71", "size": 15541, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/multilarge_nlinear/fdf.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/multilarge_nlinear/fdf.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/multilarge_nlinear/fdf.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": 27.4575971731, "max_line_length": 91, "alphanum_fraction": 0.5842609871, "num_tokens": 4175, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.411110869232168, "lm_q1q2_score": 0.21197695174630615}} {"text": "// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at\n// the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights\n// reserved. See files LICENSE and NOTICE for details.\n//\n// This file is part of CEED, a collection of benchmarks, miniapps, software\n// libraries and APIs for efficient high-order finite element and spectral\n// element discretizations for exascale applications. For more information and\n// source code availability see http://github.com/ceed.\n//\n// The CEED research is supported by the Exascale Computing Project 17-SC-20-SC,\n// a collaborative effort of two U.S. Department of Energy organizations (Office\n// of Science and the National Nuclear Security Administration) responsible for\n// the planning and preparation of a capable exascale ecosystem, including\n// software, applications, hardware, advanced system engineering and early\n// testbed platforms, in support of the nation's exascale computing imperative.\n\n#ifndef setupsphere_h\n#define setupsphere_h\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"qfunctions/bps/bp1sphere.h\"\n#include \"qfunctions/bps/bp2sphere.h\"\n#include \"qfunctions/bps/bp3sphere.h\"\n#include \"qfunctions/bps/bp4sphere.h\"\n#include \"qfunctions/bps/common.h\"\n\n#if PETSC_VERSION_LT(3,14,0)\n# define DMPlexGetClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexGetClosureIndices(a,b,c,d,f,g,i)\n# define DMPlexRestoreClosureIndices(a,b,c,d,e,f,g,h,i) DMPlexRestoreClosureIndices(a,b,c,d,f,g,i)\n#endif\n\n#if PETSC_VERSION_LT(3,14,0)\n# define DMPlexCreateSphereMesh(a,b,c,d,e) DMPlexCreateSphereMesh(a,b,c,e)\n#endif\n\n// -----------------------------------------------------------------------------\n// PETSc Operator Structs\n// -----------------------------------------------------------------------------\n\n// Data for PETSc\ntypedef struct UserO_ *UserO;\nstruct UserO_ {\n MPI_Comm comm;\n DM dm;\n Vec Xloc, Yloc, diag;\n CeedVector xceed, yceed;\n CeedOperator op;\n Ceed ceed;\n};\n\n// Data for PETSc Interp/Restrict operators\ntypedef struct UserIR_ *UserIR;\nstruct UserIR_ {\n MPI_Comm comm;\n DM dmc, dmf;\n Vec Xloc, Yloc, mult;\n CeedVector ceedvecc, ceedvecf;\n CeedOperator op;\n Ceed ceed;\n};\n\n// -----------------------------------------------------------------------------\n// libCEED Data Struct\n// -----------------------------------------------------------------------------\n\n// libCEED data struct for level\ntypedef struct CeedData_ *CeedData;\nstruct CeedData_ {\n Ceed ceed;\n CeedBasis basisx, basisu, basisctof;\n CeedElemRestriction Erestrictx, Erestrictu, Erestrictui, Erestrictqdi;\n CeedQFunction qf_apply;\n CeedOperator op_apply, op_restrict, op_interp;\n CeedVector qdata, xceed, yceed;\n};\n\n// -----------------------------------------------------------------------------\n// Command Line Options\n// -----------------------------------------------------------------------------\n\n// Coarsening options\ntypedef enum {\n COARSEN_UNIFORM = 0, COARSEN_LOGARITHMIC = 1\n} coarsenType;\nstatic const char *const coarsenTypes [] = {\"uniform\",\"logarithmic\",\n \"coarsenType\",\"COARSEN\",0\n };\n\n// -----------------------------------------------------------------------------\n// BP Option Data\n// -----------------------------------------------------------------------------\n\n// BP options\ntypedef enum {\n CEED_BP1 = 0, CEED_BP2 = 1, CEED_BP3 = 2,\n CEED_BP4 = 3, CEED_BP5 = 4, CEED_BP6 = 5\n} bpType;\nstatic const char *const bpTypes[] = {\"bp1\",\"bp2\",\"bp3\",\"bp4\",\"bp5\",\"bp6\",\n \"bpType\",\"CEED_BP\",0\n };\n\n// BP specific data\ntypedef struct {\n CeedInt ncompu, qdatasize, qextra;\n CeedQFunctionUser setupgeo, setuprhs, apply, error;\n const char *setupgeofname, *setuprhsfname, *applyfname, *errorfname;\n CeedEvalMode inmode, outmode;\n CeedQuadMode qmode;\n PetscBool enforce_bc;\n PetscErrorCode (*bcs_func)(PetscInt, PetscReal, const PetscReal *,\n PetscInt, PetscScalar *, void *);\n} bpData;\n\nstatic bpData bpOptions[6] = {\n [CEED_BP1] = {\n .ncompu = 1,\n .qdatasize = 1,\n .qextra = 1,\n .setupgeo = SetupMassGeo,\n .setuprhs = SetupMassRhs,\n .apply = Mass,\n .error = Error,\n .setupgeofname = SetupMassGeo_loc,\n .setuprhsfname = SetupMassRhs_loc,\n .applyfname = Mass_loc,\n .errorfname = Error_loc,\n .inmode = CEED_EVAL_INTERP,\n .outmode = CEED_EVAL_INTERP,\n .qmode = CEED_GAUSS\n },\n [CEED_BP2] = {\n .ncompu = 3,\n .qdatasize = 1,\n .qextra = 1,\n .setupgeo = SetupMassGeo,\n .setuprhs = SetupMassRhs3,\n .apply = Mass3,\n .error = Error3,\n .setupgeofname = SetupMassGeo_loc,\n .setuprhsfname = SetupMassRhs3_loc,\n .applyfname = Mass3_loc,\n .errorfname = Error3_loc,\n .inmode = CEED_EVAL_INTERP,\n .outmode = CEED_EVAL_INTERP,\n .qmode = CEED_GAUSS\n },\n [CEED_BP3] = {\n .ncompu = 1,\n .qdatasize = 4,\n .qextra = 1,\n .setupgeo = SetupDiffGeo,\n .setuprhs = SetupDiffRhs,\n .apply = Diff,\n .error = Error,\n .setupgeofname = SetupDiffGeo_loc,\n .setuprhsfname = SetupDiffRhs_loc,\n .applyfname = Diff_loc,\n .errorfname = Error_loc,\n .inmode = CEED_EVAL_GRAD,\n .outmode = CEED_EVAL_GRAD,\n .qmode = CEED_GAUSS\n },\n [CEED_BP4] = {\n .ncompu = 3,\n .qdatasize = 4,\n .qextra = 1,\n .setupgeo = SetupDiffGeo,\n .setuprhs = SetupDiffRhs3,\n .apply = Diff3,\n .error = Error3,\n .setupgeofname = SetupDiffGeo_loc,\n .setuprhsfname = SetupDiffRhs3_loc,\n .applyfname = Diff_loc,\n .errorfname = Error3_loc,\n .inmode = CEED_EVAL_GRAD,\n .outmode = CEED_EVAL_GRAD,\n .qmode = CEED_GAUSS\n },\n [CEED_BP5] = {\n .ncompu = 1,\n .qdatasize = 4,\n .qextra = 0,\n .setupgeo = SetupDiffGeo,\n .setuprhs = SetupDiffRhs,\n .apply = Diff,\n .error = Error,\n .setupgeofname = SetupDiffGeo_loc,\n .setuprhsfname = SetupDiffRhs_loc,\n .applyfname = Diff_loc,\n .errorfname = Error_loc,\n .inmode = CEED_EVAL_GRAD,\n .outmode = CEED_EVAL_GRAD,\n .qmode = CEED_GAUSS_LOBATTO\n },\n [CEED_BP6] = {\n .ncompu = 3,\n .qdatasize = 4,\n .qextra = 0,\n .setupgeo = SetupDiffGeo,\n .setuprhs = SetupDiffRhs3,\n .apply = Diff3,\n .error = Error3,\n .setupgeofname = SetupDiffGeo_loc,\n .setuprhsfname = SetupDiffRhs3_loc,\n .applyfname = Diff_loc,\n .errorfname = Error3_loc,\n .inmode = CEED_EVAL_GRAD,\n .outmode = CEED_EVAL_GRAD,\n .qmode = CEED_GAUSS_LOBATTO\n }\n};\n\n// -----------------------------------------------------------------------------\n// PETSc sphere auxiliary functions\n// -----------------------------------------------------------------------------\n\n// Utility function taken from petsc/src/dm/impls/plex/examples/tutorials/ex7.c\nstatic PetscErrorCode ProjectToUnitSphere(DM dm) {\n Vec coordinates;\n PetscScalar *coords;\n PetscInt Nv, v, dim, d;\n PetscErrorCode ierr;\n\n PetscFunctionBeginUser;\n ierr = DMGetCoordinatesLocal(dm, &coordinates); CHKERRQ(ierr);\n ierr = VecGetLocalSize(coordinates, &Nv); CHKERRQ(ierr);\n ierr = VecGetBlockSize(coordinates, &dim); CHKERRQ(ierr);\n Nv /= dim;\n ierr = VecGetArray(coordinates, &coords); CHKERRQ(ierr);\n for (v = 0; v < Nv; ++v) {\n PetscReal r = 0.0;\n\n for (d = 0; d < dim; ++d) r += PetscSqr(PetscRealPart(coords[v*dim+d]));\n r = PetscSqrtReal(r);\n for (d = 0; d < dim; ++d) coords[v*dim+d] /= r;\n }\n ierr = VecRestoreArray(coordinates, &coords); CHKERRQ(ierr);\n PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// PETSc FE Boilerplate\n// -----------------------------------------------------------------------------\n\n// Create FE by degree\nstatic int PetscFECreateByDegree(DM dm, PetscInt dim, PetscInt Nc,\n PetscBool isSimplex, const char prefix[],\n PetscInt order, PetscFE *fem) {\n PetscQuadrature q, fq;\n DM K;\n PetscSpace P;\n PetscDualSpace Q;\n PetscInt quadPointsPerEdge;\n PetscBool tensor = isSimplex ? PETSC_FALSE : PETSC_TRUE;\n PetscErrorCode ierr;\n\n PetscFunctionBeginUser;\n /* Create space */\n ierr = PetscSpaceCreate(PetscObjectComm((PetscObject) dm), &P); CHKERRQ(ierr);\n ierr = PetscObjectSetOptionsPrefix((PetscObject) P, prefix); CHKERRQ(ierr);\n ierr = PetscSpacePolynomialSetTensor(P, tensor); CHKERRQ(ierr);\n ierr = PetscSpaceSetFromOptions(P); CHKERRQ(ierr);\n ierr = PetscSpaceSetNumComponents(P, Nc); CHKERRQ(ierr);\n ierr = PetscSpaceSetNumVariables(P, dim); CHKERRQ(ierr);\n ierr = PetscSpaceSetDegree(P, order, order); CHKERRQ(ierr);\n ierr = PetscSpaceSetUp(P); CHKERRQ(ierr);\n ierr = PetscSpacePolynomialGetTensor(P, &tensor); CHKERRQ(ierr);\n /* Create dual space */\n ierr = PetscDualSpaceCreate(PetscObjectComm((PetscObject) dm), &Q);\n CHKERRQ(ierr);\n ierr = PetscDualSpaceSetType(Q,PETSCDUALSPACELAGRANGE); CHKERRQ(ierr);\n ierr = PetscObjectSetOptionsPrefix((PetscObject) Q, prefix); CHKERRQ(ierr);\n ierr = PetscDualSpaceCreateReferenceCell(Q, dim, isSimplex, &K); CHKERRQ(ierr);\n ierr = PetscDualSpaceSetDM(Q, K); CHKERRQ(ierr);\n ierr = DMDestroy(&K); CHKERRQ(ierr);\n ierr = PetscDualSpaceSetNumComponents(Q, Nc); CHKERRQ(ierr);\n ierr = PetscDualSpaceSetOrder(Q, order); CHKERRQ(ierr);\n ierr = PetscDualSpaceLagrangeSetTensor(Q, tensor); CHKERRQ(ierr);\n ierr = PetscDualSpaceSetFromOptions(Q); CHKERRQ(ierr);\n ierr = PetscDualSpaceSetUp(Q); CHKERRQ(ierr);\n /* Create element */\n ierr = PetscFECreate(PetscObjectComm((PetscObject) dm), fem); CHKERRQ(ierr);\n ierr = PetscObjectSetOptionsPrefix((PetscObject) *fem, prefix); CHKERRQ(ierr);\n ierr = PetscFESetFromOptions(*fem); CHKERRQ(ierr);\n ierr = PetscFESetBasisSpace(*fem, P); CHKERRQ(ierr);\n ierr = PetscFESetDualSpace(*fem, Q); CHKERRQ(ierr);\n ierr = PetscFESetNumComponents(*fem, Nc); CHKERRQ(ierr);\n ierr = PetscFESetUp(*fem); CHKERRQ(ierr);\n ierr = PetscSpaceDestroy(&P); CHKERRQ(ierr);\n ierr = PetscDualSpaceDestroy(&Q); CHKERRQ(ierr);\n /* Create quadrature */\n quadPointsPerEdge = PetscMax(order + 1,1);\n if (isSimplex) {\n ierr = PetscDTStroudConicalQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,\n &q); CHKERRQ(ierr);\n ierr = PetscDTStroudConicalQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,\n &fq); CHKERRQ(ierr);\n } else {\n ierr = PetscDTGaussTensorQuadrature(dim, 1, quadPointsPerEdge, -1.0, 1.0,\n &q); CHKERRQ(ierr);\n ierr = PetscDTGaussTensorQuadrature(dim-1, 1, quadPointsPerEdge, -1.0, 1.0,\n &fq); CHKERRQ(ierr);\n }\n ierr = PetscFESetQuadrature(*fem, q); CHKERRQ(ierr);\n ierr = PetscFESetFaceQuadrature(*fem, fq); CHKERRQ(ierr);\n ierr = PetscQuadratureDestroy(&q); CHKERRQ(ierr);\n ierr = PetscQuadratureDestroy(&fq); CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// PETSc Setup for Level\n// -----------------------------------------------------------------------------\n\n// This function sets up a DM for a given degree\nstatic int SetupDMByDegree(DM dm, PetscInt degree, PetscInt ncompu,\n PetscInt dim) {\n PetscInt ierr;\n PetscFE fe;\n\n PetscFunctionBeginUser;\n\n // Setup FE\n ierr = PetscFECreateByDegree(dm, dim, ncompu, PETSC_FALSE, NULL, degree, &fe);\n CHKERRQ(ierr);\n ierr = DMAddField(dm, NULL, (PetscObject)fe); CHKERRQ(ierr);\n\n // Setup DM\n ierr = DMCreateDS(dm); CHKERRQ(ierr);\n ierr = DMPlexSetClosurePermutationTensor(dm, PETSC_DETERMINE, NULL);\n CHKERRQ(ierr);\n ierr = PetscFEDestroy(&fe); CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n// -----------------------------------------------------------------------------\n// libCEED Setup for Level\n// -----------------------------------------------------------------------------\n\n// Destroy libCEED operator objects\nstatic PetscErrorCode CeedDataDestroy(CeedInt i, CeedData data) {\n PetscInt ierr;\n\n CeedVectorDestroy(&data->qdata);\n CeedVectorDestroy(&data->xceed);\n CeedVectorDestroy(&data->yceed);\n CeedBasisDestroy(&data->basisx);\n CeedBasisDestroy(&data->basisu);\n CeedElemRestrictionDestroy(&data->Erestrictu);\n CeedElemRestrictionDestroy(&data->Erestrictx);\n CeedElemRestrictionDestroy(&data->Erestrictui);\n CeedElemRestrictionDestroy(&data->Erestrictqdi);\n CeedQFunctionDestroy(&data->qf_apply);\n CeedOperatorDestroy(&data->op_apply);\n if (i > 0) {\n CeedOperatorDestroy(&data->op_interp);\n CeedBasisDestroy(&data->basisctof);\n CeedOperatorDestroy(&data->op_restrict);\n }\n ierr = PetscFree(data); CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n// Get CEED restriction data from DMPlex\nstatic int CreateRestrictionPlex(Ceed ceed, CeedInt P, CeedInt ncomp,\n CeedElemRestriction *Erestrict, DM dm) {\n PetscInt ierr;\n PetscInt c, cStart, cEnd, nelem, nnodes, *erestrict, eoffset;\n PetscSection section;\n Vec Uloc;\n\n PetscFunctionBegin;\n\n // Get Nelem\n ierr = DMGetSection(dm, §ion); CHKERRQ(ierr);\n ierr = DMPlexGetHeightStratum(dm, 0, &cStart,& cEnd); CHKERRQ(ierr);\n nelem = cEnd - cStart;\n\n // Get indices\n ierr = PetscMalloc1(nelem*P*P, &erestrict); CHKERRQ(ierr);\n for (c=cStart, eoffset = 0; cbasisx = basisx; data->basisu = basisu;\n data->Erestrictx = Erestrictx;\n data->Erestrictu = Erestrictu;\n data->Erestrictui = Erestrictui;\n data->Erestrictqdi = Erestrictqdi;\n data->qf_apply = qf_apply;\n data->op_apply = op_apply;\n data->qdata = qdata;\n data->xceed = xceed;\n data->yceed = yceed;\n\n PetscFunctionReturn(0);\n}\n\n#ifdef multigrid\n// Setup libCEED level transfer operator objects\nstatic PetscErrorCode CeedLevelTransferSetup(Ceed ceed, CeedInt numlevels,\n CeedInt ncompu, bpType bpChoice, CeedData *data, CeedInt *leveldegrees,\n CeedQFunction qf_restrict, CeedQFunction qf_prolong) {\n // Return early if numlevels=1\n if (numlevels==1)\n PetscFunctionReturn(0);\n\n // Set up each level\n for (CeedInt i=1; iErestrictu,\n CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n CeedOperatorSetField(op_restrict, \"output\", data[i-1]->Erestrictu,\n basisctof, CEED_VECTOR_ACTIVE);\n\n // Save libCEED data required for level\n data[i]->basisctof = basisctof;\n data[i]->op_restrict = op_restrict;\n\n // Interpolation - Corse to fine\n CeedOperator op_interp;\n\n // Create the prolongation operator\n CeedOperatorCreate(ceed, qf_prolong, NULL, NULL, &op_interp);\n CeedOperatorSetField(op_interp, \"uin\", data[i-1]->Erestrictu,\n basisctof, CEED_VECTOR_ACTIVE);\n CeedOperatorSetField(op_interp, \"uout\", data[i]->Erestrictu,\n CEED_BASIS_COLLOCATED, CEED_VECTOR_ACTIVE);\n\n // Save libCEED data required for level\n data[i]->op_interp = op_interp;\n }\n\n PetscFunctionReturn(0);\n}\n#endif\n\n// -----------------------------------------------------------------------------\n// Mat Shell Functions\n// -----------------------------------------------------------------------------\n\n#ifdef multigrid\n// This function returns the computed diagonal of the operator\nstatic PetscErrorCode MatGetDiag(Mat A, Vec D) {\n PetscErrorCode ierr;\n UserO user;\n\n PetscFunctionBeginUser;\n ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n ierr = VecCopy(user->diag, D); CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n#endif\n\n// This function uses libCEED to compute the action of the Laplacian with\n// Dirichlet boundary conditions\nstatic PetscErrorCode MatMult_Ceed(Mat A, Vec X, Vec Y) {\n PetscErrorCode ierr;\n UserO user;\n PetscScalar *x, *y;\n\n PetscFunctionBeginUser;\n ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n // Global-to-local\n ierr = DMGlobalToLocalBegin(user->dm, X, INSERT_VALUES, user->Xloc);\n CHKERRQ(ierr);\n ierr = DMGlobalToLocalEnd(user->dm, X, INSERT_VALUES, user->Xloc);\n CHKERRQ(ierr);\n ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);\n\n // Setup CEED vectors\n ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);\n CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);\n CeedVectorSetArray(user->yceed, CEED_MEM_HOST, CEED_USE_POINTER, y);\n\n // Apply CEED operator\n CeedOperatorApply(user->op, user->xceed, user->yceed, CEED_REQUEST_IMMEDIATE);\n\n // Restore PETSc vectors\n CeedVectorTakeArray(user->xceed, CEED_MEM_HOST, NULL);\n CeedVectorTakeArray(user->yceed, CEED_MEM_HOST, NULL);\n ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);\n CHKERRQ(ierr);\n ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);\n\n // Local-to-global\n ierr = VecZeroEntries(Y); CHKERRQ(ierr);\n ierr = DMLocalToGlobalBegin(user->dm, user->Yloc, ADD_VALUES, Y);\n CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(user->dm, user->Yloc, ADD_VALUES, Y);\n CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n#ifdef multigrid\n// This function uses libCEED to compute the action of the interp operator\nstatic PetscErrorCode MatMult_Interp(Mat A, Vec X, Vec Y) {\n PetscErrorCode ierr;\n UserIR user;\n PetscScalar *x, *y;\n\n PetscFunctionBeginUser;\n ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n // Global-to-local\n ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);\n ierr = DMGlobalToLocalBegin(user->dmc, X, INSERT_VALUES, user->Xloc);\n CHKERRQ(ierr);\n ierr = DMGlobalToLocalEnd(user->dmc, X, INSERT_VALUES, user->Xloc);\n CHKERRQ(ierr);\n ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);\n\n // Setup CEED vectors\n ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);\n CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, x);\n CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, y);\n\n // Apply CEED operator\n CeedOperatorApply(user->op, user->ceedvecc, user->ceedvecf,\n CEED_REQUEST_IMMEDIATE);\n\n // Restore PETSc vectors\n CeedVectorTakeArray(user->ceedvecc, CEED_MEM_HOST, NULL);\n CeedVectorTakeArray(user->ceedvecf, CEED_MEM_HOST, NULL);\n ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);\n CHKERRQ(ierr);\n ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);\n\n // Multiplicity\n ierr = VecPointwiseMult(user->Yloc, user->Yloc, user->mult);\n\n // Local-to-global\n ierr = VecZeroEntries(Y); CHKERRQ(ierr);\n ierr = DMLocalToGlobalBegin(user->dmf, user->Yloc, ADD_VALUES, Y);\n CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(user->dmf, user->Yloc, ADD_VALUES, Y);\n CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n\n// This function uses libCEED to compute the action of the restriction operator\nstatic PetscErrorCode MatMult_Restrict(Mat A, Vec X, Vec Y) {\n PetscErrorCode ierr;\n UserIR user;\n PetscScalar *x, *y;\n\n PetscFunctionBeginUser;\n ierr = MatShellGetContext(A, &user); CHKERRQ(ierr);\n\n // Global-to-local\n ierr = VecZeroEntries(user->Xloc); CHKERRQ(ierr);\n ierr = DMGlobalToLocalBegin(user->dmf, X, INSERT_VALUES, user->Xloc);\n CHKERRQ(ierr);\n ierr = DMGlobalToLocalEnd(user->dmf, X, INSERT_VALUES, user->Xloc);\n CHKERRQ(ierr);\n ierr = VecZeroEntries(user->Yloc); CHKERRQ(ierr);\n\n // Multiplicity\n ierr = VecPointwiseMult(user->Xloc, user->Xloc, user->mult); CHKERRQ(ierr);\n\n // Setup CEED vectors\n ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n ierr = VecGetArray(user->Yloc, &y); CHKERRQ(ierr);\n CeedVectorSetArray(user->ceedvecf, CEED_MEM_HOST, CEED_USE_POINTER, x);\n CeedVectorSetArray(user->ceedvecc, CEED_MEM_HOST, CEED_USE_POINTER, y);\n\n // Apply CEED operator\n CeedOperatorApply(user->op, user->ceedvecf, user->ceedvecc,\n CEED_REQUEST_IMMEDIATE);\n\n // Restore PETSc vectors\n CeedVectorTakeArray(user->ceedvecf, CEED_MEM_HOST, NULL);\n CeedVectorTakeArray(user->ceedvecc, CEED_MEM_HOST, NULL);\n ierr = VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x);\n CHKERRQ(ierr);\n ierr = VecRestoreArray(user->Yloc, &y); CHKERRQ(ierr);\n\n // Local-to-global\n ierr = VecZeroEntries(Y); CHKERRQ(ierr);\n ierr = DMLocalToGlobalBegin(user->dmc, user->Yloc, ADD_VALUES, Y);\n CHKERRQ(ierr);\n ierr = DMLocalToGlobalEnd(user->dmc, user->Yloc, ADD_VALUES, Y);\n CHKERRQ(ierr);\n\n PetscFunctionReturn(0);\n}\n#endif\n\n// This function calculates the error in the final solution\nstatic PetscErrorCode ComputeErrorMax(UserO user, CeedOperator op_error,\n Vec X, CeedVector target,\n PetscReal *maxerror) {\n PetscErrorCode ierr;\n PetscScalar *x;\n CeedVector collocated_error;\n CeedInt length;\n\n PetscFunctionBeginUser;\n CeedVectorGetLength(target, &length);\n CeedVectorCreate(user->ceed, length, &collocated_error);\n\n // Global-to-local\n ierr = DMGlobalToLocal(user->dm, X, INSERT_VALUES, user->Xloc); CHKERRQ(ierr);\n\n // Setup CEED vector\n ierr = VecGetArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n CeedVectorSetArray(user->xceed, CEED_MEM_HOST, CEED_USE_POINTER, x);\n\n // Apply CEED operator\n CeedOperatorApply(op_error, user->xceed, collocated_error,\n CEED_REQUEST_IMMEDIATE);\n\n // Restore PETSc vector\n VecRestoreArrayRead(user->Xloc, (const PetscScalar **)&x); CHKERRQ(ierr);\n\n // Reduce max error\n *maxerror = 0;\n const CeedScalar *e;\n CeedVectorGetArrayRead(collocated_error, CEED_MEM_HOST, &e);\n for (CeedInt i=0; icomm); CHKERRQ(ierr);\n\n // Cleanup\n CeedVectorDestroy(&collocated_error);\n\n PetscFunctionReturn(0);\n}\n\n#endif // setupsphere_h\n", "meta": {"hexsha": "6820308f54bfe2632f345b3bc7de48ad63fa19f7", "size": 30763, "ext": "h", "lang": "C", "max_stars_repo_path": "examples/petsc/setupsphere.h", "max_stars_repo_name": "barker29/libCEED", "max_stars_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/petsc/setupsphere.h", "max_issues_repo_name": "barker29/libCEED", "max_issues_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/petsc/setupsphere.h", "max_forks_repo_name": "barker29/libCEED", "max_forks_repo_head_hexsha": "3d576824e8d990e1f48c6609089904bee9170514", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-30T23:13:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-30T23:13:18.000Z", "avg_line_length": 36.4922894425, "max_line_length": 99, "alphanum_fraction": 0.6511718623, "num_tokens": 8646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5195213219520929, "lm_q2_score": 0.40356685373537454, "lm_q1q2_score": 0.2096615853486487}} {"text": "/*\n * This file is part of the GROMACS molecular simulation package.\n *\n * Copyright (c) 1991-2000, University of Groningen, The Netherlands.\n * Copyright (c) 2001-2004, The GROMACS development team,\n * check out http://www.gromacs.org for more information.\n * Copyright (c) 2012,2013, by the GROMACS development team, led by\n * David van der Spoel, Berk Hess, Erik Lindahl, and including many\n * others, as listed in the AUTHORS file in the top-level source\n * directory and at http://www.gromacs.org.\n *\n * GROMACS is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public License\n * as published by the Free Software Foundation; either version 2.1\n * of the License, or (at your option) any later version.\n *\n * GROMACS is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with GROMACS; if not, see\n * http://www.gnu.org/licenses, or write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * If you want to redistribute modifications to GROMACS, please\n * consider that scientific software is very special. Version\n * control is crucial - bugs must be traceable. We will be happy to\n * consider code for inclusion in the official distribution, but\n * derived work must not be called official GROMACS. Details are found\n * in the README & COPYING files - if they are missing, get the\n * official version at http://www.gromacs.org.\n *\n * To help us fund GROMACS development, we humbly ask that you cite\n * the research papers on the package. Check out http://www.gromacs.org.\n */\n#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#ifdef HAVE_LIBGSL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \n#include \"typedefs.h\"\n#include \"smalloc.h\"\n#include \"vec.h\"\n#include \"geminate.h\"\n#include \"gmx_omp.h\"\n\n\n/* The first few sections of this file contain functions that were adopted,\n * and to some extent modified, by Erik Marklund (erikm[aT]xray.bmc.uu.se,\n * http://folding.bmc.uu.se) from code written by Omer Markovitch (email, url).\n * This is also the case with the function eq10v2().\n *\n * The parts menetioned in the previous paragraph were contributed under the BSD license.\n */\n\n\n/* This first part is from complex.c which I recieved from Omer Markowitch.\n * - Erik Marklund\n *\n * ------------- from complex.c ------------- */\n\n/* Complexation of a paired number (r,i) */\nstatic gem_complex gem_cmplx(double r, double i)\n{\n gem_complex value;\n value.r = r;\n value.i = i;\n return value;\n}\n\n/* Complexation of a real number, x */\nstatic gem_complex gem_c(double x)\n{\n gem_complex value;\n value.r = x;\n value.i = 0;\n return value;\n}\n\n/* Magnitude of a complex number z */\nstatic double gem_cx_abs(gem_complex z)\n{\n return (sqrt(z.r*z.r+z.i*z.i));\n}\n\n/* Addition of two complex numbers z1 and z2 */\nstatic gem_complex gem_cxadd(gem_complex z1, gem_complex z2)\n{\n gem_complex value;\n value.r = z1.r+z2.r;\n value.i = z1.i+z2.i;\n return value;\n}\n\n/* Addition of a complex number z1 and a real number r */\nstatic gem_complex gem_cxradd(gem_complex z, double r)\n{\n gem_complex value;\n value.r = z.r + r;\n value.i = z.i;\n return value;\n}\n\n/* Subtraction of two complex numbers z1 and z2 */\nstatic gem_complex gem_cxsub(gem_complex z1, gem_complex z2)\n{\n gem_complex value;\n value.r = z1.r-z2.r;\n value.i = z1.i-z2.i;\n return value;\n}\n\n/* Multiplication of two complex numbers z1 and z2 */\nstatic gem_complex gem_cxmul(gem_complex z1, gem_complex z2)\n{\n gem_complex value;\n value.r = z1.r*z2.r-z1.i*z2.i;\n value.i = z1.r*z2.i+z1.i*z2.r;\n return value;\n}\n\n/* Square of a complex number z */\nstatic gem_complex gem_cxsq(gem_complex z)\n{\n gem_complex value;\n value.r = z.r*z.r-z.i*z.i;\n value.i = z.r*z.i*2.;\n return value;\n}\n\n/* multiplication of a complex number z and a real number r */\nstatic gem_complex gem_cxrmul(gem_complex z, double r)\n{\n gem_complex value;\n value.r = z.r*r;\n value.i = z.i*r;\n return value;\n}\n\n/* Division of two complex numbers z1 and z2 */\nstatic gem_complex gem_cxdiv(gem_complex z1, gem_complex z2)\n{\n gem_complex value;\n double num;\n num = z2.r*z2.r+z2.i*z2.i;\n if (num == 0.)\n {\n fprintf(stderr, \"ERROR in gem_cxdiv function\\n\");\n }\n value.r = (z1.r*z2.r+z1.i*z2.i)/num; value.i = (z1.i*z2.r-z1.r*z2.i)/num;\n return value;\n}\n\n/* division of a complex z number by a real number x */\nstatic gem_complex gem_cxrdiv(gem_complex z, double r)\n{\n gem_complex value;\n value.r = z.r/r;\n value.i = z.i/r;\n return value;\n}\n\n/* division of a real number r by a complex number x */\nstatic gem_complex gem_rxcdiv(double r, gem_complex z)\n{\n gem_complex value;\n double f;\n f = r/(z.r*z.r+z.i*z.i);\n value.r = f*z.r;\n value.i = -f*z.i;\n return value;\n}\n\n/* Exponential of a complex number-- exp (z)=|exp(z.r)|*{cos(z.i)+I*sin(z.i)}*/\nstatic gem_complex gem_cxdexp(gem_complex z)\n{\n gem_complex value;\n double exp_z_r;\n exp_z_r = exp(z.r);\n value.r = exp_z_r*cos(z.i);\n value.i = exp_z_r*sin(z.i);\n return value;\n}\n\n/* Logarithm of a complex number -- log(z)=log|z|+I*Arg(z), */\n/* where -PI < Arg(z) < PI */\nstatic gem_complex gem_cxlog(gem_complex z)\n{\n gem_complex value;\n double mag2;\n mag2 = z.r*z.r+z.i*z.i;\n if (mag2 < 0.)\n {\n fprintf(stderr, \"ERROR in gem_cxlog func\\n\");\n }\n value.r = log(sqrt(mag2));\n if (z.r == 0.)\n {\n value.i = PI/2.;\n if (z.i < 0.)\n {\n value.i = -value.i;\n }\n }\n else\n {\n value.i = atan2(z.i, z.r);\n }\n return value;\n}\n\n/* Square root of a complex number z = |z| exp(I*the) -- z^(1/2) */\n/* z^(1/2)=|z|^(1/2)*[cos(the/2)+I*sin(the/2)] */\n/* where 0 < the < 2*PI */\nstatic gem_complex gem_cxdsqrt(gem_complex z)\n{\n gem_complex value;\n double sq;\n sq = gem_cx_abs(z);\n value.r = sqrt(fabs((sq+z.r)*0.5)); /* z'.r={|z|*[1+cos(the)]/2}^(1/2) */\n value.i = sqrt(fabs((sq-z.r)*0.5)); /* z'.i={|z|*[1-cos(the)]/2}^(1/2) */\n if (z.i < 0.)\n {\n value.r = -value.r;\n }\n return value;\n}\n\n/* Complex power of a complex number z1^z2 */\nstatic gem_complex gem_cxdpow(gem_complex z1, gem_complex z2)\n{\n gem_complex value;\n value = gem_cxdexp(gem_cxmul(gem_cxlog(z1), z2));\n return value;\n}\n\n/* ------------ end of complex.c ------------ */\n\n/* This next part was derived from cubic.c, also received from Omer Markovitch.\n * ------------- from cubic.c ------------- */\n\n/* Solver for a cubic equation: x^3-a*x^2+b*x-c=0 */\nstatic void gem_solve(gem_complex *al, gem_complex *be, gem_complex *gam,\n double a, double b, double c)\n{\n double t1, t2, two_3, temp;\n gem_complex ctemp, ct3;\n\n two_3 = pow(2., 1./3.); t1 = -a*a+3.*b; t2 = 2.*a*a*a-9.*a*b+27.*c;\n temp = 4.*t1*t1*t1+t2*t2;\n\n ctemp = gem_cmplx(temp, 0.); ctemp = gem_cxadd(gem_cmplx(t2, 0.), gem_cxdsqrt(ctemp));\n ct3 = gem_cxdpow(ctemp, gem_cmplx(1./3., 0.));\n\n ctemp = gem_rxcdiv(-two_3*t1/3., ct3);\n ctemp = gem_cxadd(ctemp, gem_cxrdiv(ct3, 3.*two_3));\n\n *gam = gem_cxadd(gem_cmplx(a/3., 0.), ctemp);\n\n ctemp = gem_cxmul(gem_cxsq(*gam), gem_cxsq(gem_cxsub(*gam, gem_cmplx(a, 0.))));\n ctemp = gem_cxadd(ctemp, gem_cxmul(gem_cmplx(-4.*c, 0.), *gam));\n ctemp = gem_cxdiv(gem_cxdsqrt(ctemp), *gam);\n *al = gem_cxrmul(gem_cxsub(gem_cxsub(gem_cmplx(a, 0.), *gam), ctemp), 0.5);\n *be = gem_cxrmul(gem_cxadd(gem_cxsub(gem_cmplx(a, 0.), *gam), ctemp), 0.5);\n}\n\n/* ------------ end of cubic.c ------------ */\n\n/* This next part was derived from cerror.c and rerror.c, also received from Omer Markovitch.\n * ------------- from [cr]error.c ------------- */\n\n/************************************************************/\n/* Real valued error function and related functions */\n/* x, y : real variables */\n/* erf(x) : error function */\n/* erfc(x) : complementary error function */\n/* omega(x) : exp(x*x)*erfc(x) */\n/* W(x,y) : exp(-x*x)*omega(x+y)=exp(2*x*y+y^2)*erfc(x+y) */\n/************************************************************/\n\n/*---------------------------------------------------------------------------*/\n/* Utilzed the series approximation of erf(x) */\n/* Relative error=|err(x)|/erf(x)=6 series sum deteriorates -> Asymptotic series used instead */\n/*---------------------------------------------------------------------------*/\n/* This gives erfc(z) correctly only upto >10-15 */\n\nstatic double gem_erf(double x)\n{\n double n, sum, temp, exp2, xm, x2, x4, x6, x8, x10, x12;\n temp = x;\n sum = temp;\n xm = 26.;\n x2 = x*x;\n x4 = x2*x2;\n x6 = x4*x2;\n x8 = x6*x2;\n x10 = x8*x2;\n x12 = x10*x2;\n exp2 = exp(-x2);\n if (x <= xm)\n {\n for (n = 1.; n <= 2000.; n += 1.)\n {\n temp *= 2.*x2/(2.*n+1.);\n sum += temp;\n if (fabs(temp/sum) < 1.E-16)\n {\n break;\n }\n }\n\n if (n >= 2000.)\n {\n fprintf(stderr, \"In Erf calc - iteration exceeds %lg\\n\", n);\n }\n sum *= 2./sPI*exp2;\n }\n else\n {\n /* from the asymptotic expansion of experfc(x) */\n sum = (1. - 0.5/x2 + 0.75/x4\n - 1.875/x6 + 6.5625/x8\n - 29.53125/x10 + 162.421875/x12)\n / sPI/x;\n sum *= exp2; /* now sum is erfc(x) */\n sum = -sum+1.;\n }\n return x >= 0.0 ? sum : -sum;\n}\n\n/* Result --> Alex's code for erfc and experfc behaves better than this */\n/* complementray error function. Returns 1.-erf(x) */\nstatic double gem_erfc(double x)\n{\n double t, z, ans;\n z = fabs(x);\n t = 1.0/(1.0+0.5*z);\n\n ans = t * exp(-z*z - 1.26551223 +\n t*(1.00002368 +\n t*(0.37409196 +\n t*(0.09678418 +\n t*(-0.18628806 +\n t*(0.27886807 +\n t*(-1.13520398 +\n t*(1.48851587 +\n t*(-0.82215223 +\n t*0.17087277)))))))));\n\n return x >= 0.0 ? ans : 2.0-ans;\n}\n\n/* omega(x)=exp(x^2)erfc(x) */\nstatic double gem_omega(double x)\n{\n double xm, ans, xx, x4, x6, x8, x10, x12;\n xm = 26;\n xx = x*x;\n x4 = xx*xx;\n x6 = x4*xx;\n x8 = x6*xx;\n x10 = x8*xx;\n x12 = x10*xx;\n\n if (x <= xm)\n {\n ans = exp(xx)*gem_erfc(x);\n }\n else\n {\n /* Asymptotic expansion */\n ans = (1. - 0.5/xx + 0.75/x4 - 1.875/x6 + 6.5625/x8 - 29.53125/x10 + 162.421875/x12) / sPI/x;\n }\n return ans;\n}\n\n/*---------------------------------------------------------------------------*/\n/* Utilzed the series approximation of erf(z=x+iy) */\n/* Relative error=|err(z)|/|erf(z)|kD;\n D = params->D;\n r = params->sigma;\n a = (1.0 + ka/kD) * sqrt(D)/r;\n b = kd;\n c = kd * sqrt(D)/r;\n\n gem_solve(&alpha, &beta, &gamma, a, b, c);\n /* Finding the 3 roots */\n\n sumimaginary = 0;\n part1 = gem_cxmul(alpha, gem_cxmul(gem_cxadd(beta, gamma), gem_cxsub(beta, gamma))); /* 1(2+3)(2-3) */\n part2 = gem_cxmul(beta, gem_cxmul(gem_cxadd(gamma, alpha), gem_cxsub(gamma, alpha))); /* 2(3+1)(3-1) */\n part3 = gem_cxmul(gamma, gem_cxmul(gem_cxadd(alpha, beta), gem_cxsub(alpha, beta))); /* 3(1+2)(1-2) */\n part4 = gem_cxmul(gem_cxsub(gamma, alpha), gem_cxmul(gem_cxsub(alpha, beta), gem_cxsub(beta, gamma))); /* (3-1)(1-2)(2-3) */\n\n#pragma omp parallel for \\\n private(i, tsqrt, oma, omb, omc, c1, c2, c3, c4) \\\n reduction(+:sumimaginary) \\\n default(shared) \\\n schedule(guided)\n for (i = 0; i < manytimes; i++)\n {\n tsqrt = sqrt(time[i]);\n oma = gem_comega(gem_cxrmul(alpha, tsqrt));\n c1 = gem_cxmul(oma, gem_cxdiv(part1, part4));\n omb = gem_comega(gem_cxrmul(beta, tsqrt));\n c2 = gem_cxmul(omb, gem_cxdiv(part2, part4));\n omc = gem_comega(gem_cxrmul(gamma, tsqrt));\n c3 = gem_cxmul(omc, gem_cxdiv(part3, part4));\n c4.r = c1.r+c2.r+c3.r;\n c4.i = c1.i+c2.i+c3.i;\n theoryCt[i] = c4.r;\n sumimaginary += c4.i * c4.i;\n }\n\n return sumimaginary;\n\n} /* eq10v2 */\n\n/* This returns the real-valued index(!) to an ACF, equidistant on a log scale. */\nstatic double getLogIndex(const int i, const t_gemParams *params)\n{\n return (exp(((double)(i)) * params->logQuota) -1);\n}\n\nextern t_gemParams *init_gemParams(const double sigma, const double D,\n const real *t, const int len, const int nFitPoints,\n const real begFit, const real endFit,\n const real ballistic, const int nBalExp, const gmx_bool bDt)\n{\n double tDelta;\n t_gemParams *p;\n\n snew(p, 1);\n\n /* A few hardcoded things here. For now anyway. */\n/* p->ka_min = 0; */\n/* p->ka_max = 100; */\n/* p->dka = 10; */\n/* p->kd_min = 0; */\n/* p->kd_max = 2; */\n/* p->dkd = 0.2; */\n p->ka = 0;\n p->kd = 0;\n/* p->lsq = -1; */\n/* p->lifetime = 0; */\n p->sigma = sigma*10; /* Omer uses Ã…, not nm */\n/* p->lsq_old = 99999; */\n p->D = sqcm_per_s_to_sqA_per_ps(D);\n p->kD = 4*acos(-1.0)*sigma*p->D;\n\n\n /* Parameters used by calcsquare(). Better to calculate them\n * here than in calcsquare every time it's called. */\n p->len = len;\n/* p->logAfterTime = logAfterTime; */\n tDelta = (t[len-1]-t[0]) / len;\n if (tDelta <= 0)\n {\n gmx_fatal(FARGS, \"Time between frames is non-positive!\");\n }\n else\n {\n p->tDelta = tDelta;\n }\n\n p->nExpFit = nBalExp;\n/* p->nLin = logAfterTime / tDelta; */\n p->nFitPoints = nFitPoints;\n p->begFit = begFit;\n p->endFit = endFit;\n p->logQuota = (double)(log(p->len))/(p->nFitPoints-1);\n/* if (p->nLin <= 0) { */\n/* fprintf(stderr, \"Number of data points in the linear regime is non-positive!\\n\"); */\n/* sfree(p); */\n/* return NULL; */\n/* } */\n/* We want the same number of data points in the log regime. Not crucial, but seems like a good idea. */\n/* p->logDelta = log(((float)len)/p->nFitPoints) / p->nFitPoints;/\\* log(((float)len)/p->nLin) / p->nLin; *\\/ */\n/* p->logPF = p->nFitPoints*p->nFitPoints/(float)len; /\\* p->nLin*p->nLin/(float)len; *\\/ */\n/* logPF and logDelta are stitched together with the macro GETLOGINDEX defined in geminate.h */\n\n/* p->logMult = pow((float)len, 1.0/nLin);/\\* pow(t[len-1]-t[0], 1.0/p->nLin); *\\/ */\n p->ballistic = ballistic;\n return p;\n}\n\n/* There was a misunderstanding regarding the fitting. From our\n * recent correspondence it appears that Omer's code require\n * the ACF data on a log-scale and does not operate on the raw data.\n * This needs to be redone in gemFunc_residual() as well as in the\n * t_gemParams structure. */\n#ifdef HAVE_LIBGSL\nstatic double gemFunc_residual2(const gsl_vector *p, void *data)\n{\n gemFitData *GD;\n int i, iLog, nLin, nFitPoints, nData;\n double r, residual2, *ctTheory, *y;\n\n GD = (gemFitData *)data;\n nLin = GD->params->nLin;\n nFitPoints = GD->params->nFitPoints;\n nData = GD->nData;\n residual2 = 0;\n ctTheory = GD->ctTheory;\n y = GD->y;\n\n /* Now, we'd save a lot of time by not calculating eq10v2 for all\n * time points, but only those that we sample to calculate the mse.\n */\n\n eq10v2(GD->ctTheory, GD->doubleLogTime /* GD->time */, nFitPoints /* GD->nData */,\n gsl_vector_get(p, 0), gsl_vector_get(p, 1),\n GD->params);\n\n fixGemACF(GD->ctTheory, nFitPoints);\n\n /* Removing a bunch of points from the log-part. */\n#pragma omp parallel for schedule(dynamic) \\\n firstprivate(nData, ctTheory, y, nFitPoints) \\\n private (i, iLog, r) \\\n reduction(+:residual2) \\\n default(shared)\n for (i = 0; i < nFitPoints; i++)\n {\n iLog = GD->logtime[i];\n r = log(ctTheory[i /* iLog */]);\n residual2 += sqr(r-log(y[iLog]));\n }\n residual2 /= nFitPoints; /* Not really necessary for the fitting, but gives more meaning to the returned data. */\n /* printf(\"ka=%3.5f\\tkd=%3.5f\\trmse=%3.5f\\n\", gsl_vector_get(p,0), gsl_vector_get(p,1), residual2); */\n return residual2;\n\n/* for (i=0; iparams); */\n/* if (iLog >= nData) */\n/* gmx_fatal(FARGS, \"log index out of bounds: %i\", iLog); */\n/* r = ctTheory[iLog]; */\n/* residual2 += sqr(r-y[iLog]); */\n\n/* } */\n/* residual2 /= GD->n; */\n/* return residual2; */\n}\n#endif\n\nstatic real* d2r(const double *d, const int nn);\n\nextern real fitGemRecomb(double *ct, double *time, double **ctFit,\n const int nData, t_gemParams *params)\n{\n\n int nThreads, i, iter, status, maxiter;\n real size, d2, tol, *dumpdata;\n size_t p, n;\n gemFitData *GD;\n char *dumpstr, dumpname[128];\n\n /* nmsimplex2 had convergence problems prior to gsl v1.14,\n * but it's O(N) instead of O(N) operations, so let's use it if v >= 1.14 */\n#ifdef HAVE_LIBGSL\n gsl_multimin_fminimizer *s;\n gsl_vector *x, *dx; /* parameters and initial step size */\n gsl_multimin_function fitFunc;\n#ifdef GSL_MAJOR_VERSION\n#ifdef GSL_MINOR_VERSION\n#if ((GSL_MAJOR_VERSION == 1 && GSL_MINOR_VERSION >= 14) || \\\n (GSL_MAJOR_VERSION > 1))\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2;\n#else\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;\n#endif /* #if ... */\n#endif /* GSL_MINOR_VERSION */\n#else\n const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex;\n#endif /* GSL_MAJOR_VERSION */\n fprintf(stdout, \"Will fit ka and kd to the ACF according to the reversible geminate recombination model.\\n\");\n#else /* HAVE_LIBGSL */\n fprintf(stderr, \"Sorry, can't do reversible geminate recombination without gsl. \"\n \"Recompile using --with-gsl.\\n\");\n return -1;\n#endif /* HAVE_LIBGSL */\n\n#ifdef HAVE_LIBGSL\n#ifdef GMX_OPENMP\n nThreads = gmx_omp_get_max_threads();\n gmx_omp_set_num_threads(nThreads);\n fprintf(stdout, \"We will be using %i threads.\\n\", nThreads);\n#endif\n\n iter = 0;\n status = 0;\n maxiter = 100;\n tol = 1e-10;\n\n p = 2; /* Number of parameters to fit. ka and kd. */\n n = params->nFitPoints; /* params->nLin*2 */; /* Number of points in the reduced dataset */\n\n if (params->D <= 0)\n {\n fprintf(stderr, \"Fitting of D is not implemented yet. It must be provided on the command line.\\n\");\n return -1;\n }\n\n/* if (nDatan = n;\n GD->y = ct;\n GD->ctTheory = NULL;\n snew(GD->ctTheory, nData);\n GD->LinLog = NULL;\n snew(GD->LinLog, n);\n GD->time = time;\n GD->ka = 0;\n GD->kd = 0;\n GD->tDelta = time[1]-time[0];\n GD->nData = nData;\n GD->params = params;\n snew(GD->logtime, params->nFitPoints);\n snew(GD->doubleLogTime, params->nFitPoints);\n\n for (i = 0; i < params->nFitPoints; i++)\n {\n GD->doubleLogTime[i] = (double)(getLogIndex(i, params));\n GD->logtime[i] = (int)(GD->doubleLogTime[i]);\n GD->doubleLogTime[i] *= GD->tDelta;\n\n if (GD->logtime[i] >= nData)\n {\n fprintf(stderr, \"Ayay. It seems we're indexing out of bounds.\\n\");\n params->nFitPoints = i;\n }\n }\n\n fitFunc.f = &gemFunc_residual2;\n fitFunc.n = 2;\n fitFunc.params = (void*)GD;\n\n x = gsl_vector_alloc (fitFunc.n);\n dx = gsl_vector_alloc (fitFunc.n);\n gsl_vector_set (x, 0, 25);\n gsl_vector_set (x, 1, 0.5);\n gsl_vector_set (dx, 0, 0.1);\n gsl_vector_set (dx, 1, 0.01);\n\n\n s = gsl_multimin_fminimizer_alloc (T, fitFunc.n);\n gsl_multimin_fminimizer_set (s, &fitFunc, x, dx);\n gsl_vector_free (x);\n gsl_vector_free (dx);\n\n do\n {\n iter++;\n status = gsl_multimin_fminimizer_iterate (s);\n\n if (status != 0)\n {\n gmx_fatal(FARGS, \"Something went wrong in the iteration in minimizer %s:\\n \\\"%s\\\"\\n\",\n gsl_multimin_fminimizer_name(s), gsl_strerror(status));\n }\n\n d2 = gsl_multimin_fminimizer_minimum(s);\n size = gsl_multimin_fminimizer_size(s);\n params->ka = gsl_vector_get (s->x, 0);\n params->kd = gsl_vector_get (s->x, 1);\n\n if (status)\n {\n fprintf(stderr, \"%s\\n\", gsl_strerror(status));\n break;\n }\n\n status = gsl_multimin_test_size(size, tol);\n\n if (status == GSL_SUCCESS)\n {\n fprintf(stdout, \"Converged to minimum at\\n\");\n }\n\n printf (\"iter %5d: ka = %2.5f kd = %2.5f f() = %7.3f size = %.3f chi2 = %2.5f\\n\",\n iter,\n params->ka,\n params->kd,\n s->fval, size, d2);\n\n if (iter%1 == 0)\n {\n eq10v2(GD->ctTheory, time, nData, params->ka, params->kd, params);\n /* fixGemACF(GD->ctTheory, nFitPoints); */\n sprintf(dumpname, \"Iter_%i.xvg\", iter);\n for (i = 0; i < GD->nData; i++)\n {\n dumpdata[i] = (real)(GD->ctTheory[i]);\n if (!gmx_isfinite(dumpdata[i]))\n {\n gmx_fatal(FARGS, \"Non-finite value in acf.\");\n }\n }\n dumpN(dumpdata, GD->nData, dumpname);\n }\n }\n while ((status == GSL_CONTINUE) && (iter < maxiter));\n\n /* /\\* Calculate the theoretical ACF from the parameters one last time. *\\/ */\n eq10v2(GD->ctTheory, time, nData, params->ka, params->kd, params);\n *ctFit = GD->ctTheory;\n\n sfree(GD);\n gsl_multimin_fminimizer_free (s);\n\n\n return d2;\n\n#endif /* HAVE_LIBGSL */\n}\n\n#ifdef HAVE_LIBGSL\nstatic int balFunc_f(const gsl_vector *x, void *data, gsl_vector *f)\n{\n /* C + sum{ A_i * exp(-B_i * t) }*/\n\n balData *BD;\n int n, i, j, nexp;\n double *y, *A, *B, C, /* There are the parameters to be optimized. */\n t, ct;\n\n BD = (balData *)data;\n n = BD->n;\n nexp = BD->nexp;\n y = BD->y,\n snew(A, nexp);\n snew(B, nexp);\n\n for (i = 0; i < nexp; i++)\n {\n A[i] = gsl_vector_get(x, i*2);\n B[i] = gsl_vector_get(x, i*2+1);\n }\n C = gsl_vector_get(x, nexp*2);\n\n for (i = 0; i < n; i++)\n {\n t = i*BD->tDelta;\n ct = 0;\n for (j = 0; j < nexp; j++)\n {\n ct += A[j] * exp(B[j] * t);\n }\n ct += C;\n gsl_vector_set (f, i, ct - y[i]);\n }\n return GSL_SUCCESS;\n}\n\n/* The derivative stored in jacobian form (J)*/\nstatic int balFunc_df(const gsl_vector *params, void *data, gsl_matrix *J)\n{\n balData *BD;\n size_t n, i, j;\n double *y, *A, *B, C, /* There are the parameters. */\n t;\n int nexp;\n\n BD = (balData*)data;\n n = BD->n;\n y = BD->y;\n nexp = BD->nexp;\n\n snew(A, nexp);\n snew(B, nexp);\n\n for (i = 0; i < nexp; i++)\n {\n A[i] = gsl_vector_get(params, i*2);\n B[i] = gsl_vector_get(params, i*2+1);\n }\n C = gsl_vector_get(params, nexp*2);\n for (i = 0; i < n; i++)\n {\n t = i*BD->tDelta;\n for (j = 0; j < nexp; j++)\n {\n gsl_matrix_set (J, i, j*2, exp(B[j]*t)); /* df(t)/dA_j */\n gsl_matrix_set (J, i, j*2+1, A[j]*t*exp(B[j]*t)); /* df(t)/dB_j */\n }\n gsl_matrix_set (J, i, nexp*2, 1); /* df(t)/dC */\n }\n return GSL_SUCCESS;\n}\n\n/* Calculation of the function and its derivative */\nstatic int balFunc_fdf(const gsl_vector *params, void *data,\n gsl_vector *f, gsl_matrix *J)\n{\n balFunc_f(params, data, f);\n balFunc_df(params, data, J);\n return GSL_SUCCESS;\n}\n#endif /* HAVE_LIBGSL */\n\n/* Removes the ballistic term from the beginning of the ACF,\n * just like in Omer's paper.\n */\nextern void takeAwayBallistic(double *ct, double *t, int len, real tMax, int nexp, gmx_bool bDerivative)\n{\n\n /* Use nonlinear regression with GSL instead.\n * Fit with 4 exponentials and one constant term,\n * subtract the fatest exponential. */\n\n int nData, i, status, iter;\n balData *BD;\n double *guess, /* Initial guess. */\n *A, /* The fitted parameters. (A1, B1, A2, B2,... C) */\n a[2],\n ddt[2];\n gmx_bool sorted;\n size_t n;\n size_t p;\n\n nData = 0;\n do\n {\n nData++;\n }\n while (t[nData] < tMax+t[0] && nData < len);\n\n p = nexp*2+1; /* Number of parameters. */\n\n#ifdef HAVE_LIBGSL\n const gsl_multifit_fdfsolver_type *T\n = gsl_multifit_fdfsolver_lmsder;\n\n gsl_multifit_fdfsolver *s; /* The solver itself. */\n gsl_multifit_function_fdf fitFunction; /* The function to be fitted. */\n gsl_matrix *covar; /* Covariance matrix for the parameters.\n * We'll not use the result, though. */\n gsl_vector_view theParams;\n\n nData = 0;\n do\n {\n nData++;\n }\n while (t[nData] < tMax+t[0] && nData < len);\n\n guess = NULL;\n n = nData;\n\n snew(guess, p);\n snew(A, p);\n covar = gsl_matrix_alloc (p, p);\n\n /* Set up an initial gess for the parameters.\n * The solver is somewhat sensitive to the initial guess,\n * but this worked fine for a TIP3P box with -geminate dd\n * EDIT: In fact, this seems like a good starting pont for other watermodels too. */\n for (i = 0; i < nexp; i++)\n {\n guess[i*2] = 0.1;\n guess[i*2+1] = -0.5 + (((double)i)/nexp - 0.5)*0.3;\n }\n guess[nexp * 2] = 0.01;\n\n theParams = gsl_vector_view_array(guess, p);\n\n snew(BD, 1);\n BD->n = n;\n BD->y = ct;\n BD->tDelta = t[1]-t[0];\n BD->nexp = nexp;\n\n fitFunction.f = &balFunc_f;\n fitFunction.df = &balFunc_df;\n fitFunction.fdf = &balFunc_fdf;\n fitFunction.n = nData;\n fitFunction.p = p;\n fitFunction.params = BD;\n\n s = gsl_multifit_fdfsolver_alloc (T, nData, p);\n if (s == NULL)\n {\n gmx_fatal(FARGS, \"Could not set up the nonlinear solver.\");\n }\n\n gsl_multifit_fdfsolver_set(s, &fitFunction, &theParams.vector);\n\n /* \\=============================================/ */\n\n iter = 0;\n do\n {\n iter++;\n status = gsl_multifit_fdfsolver_iterate (s);\n\n if (status)\n {\n break;\n }\n status = gsl_multifit_test_delta (s->dx, s->x, 1e-4, 1e-4);\n }\n while (iter < 5000 && status == GSL_CONTINUE);\n\n if (iter == 5000)\n {\n fprintf(stderr, \"The non-linear fitting did not converge in 5000 steps.\\n\"\n \"Check the quality of the fit!\\n\");\n }\n else\n {\n fprintf(stderr, \"Non-linear fitting of ballistic term converged in %d steps.\\n\\n\", (int)iter);\n }\n for (i = 0; i < nexp; i++)\n {\n fprintf(stdout, \"%c * exp(%c * t) + \", 'A'+(char)i*2, 'B'+(char)i*2);\n }\n\n fprintf(stdout, \"%c\\n\", 'A'+(char)nexp*2);\n fprintf(stdout, \"Here are the actual numbers for A-%c:\\n\", 'A'+nexp*2);\n\n for (i = 0; i < nexp; i++)\n {\n A[i*2] = gsl_vector_get(s->x, i*2);\n A[i*2+1] = gsl_vector_get(s->x, i*2+1);\n fprintf(stdout, \" %g*exp(%g * x) +\", A[i*2], A[i*2+1]);\n }\n A[i*2] = gsl_vector_get(s->x, i*2); /* The last and constant term */\n fprintf(stdout, \" %g\\n\", A[i*2]);\n\n fflush(stdout);\n\n /* Implement some check for parameter quality */\n for (i = 0; i < nexp; i++)\n {\n if (A[i*2] < 0 || A[i*2] > 1)\n {\n fprintf(stderr, \"WARNING: ----------------------------------\\n\"\n \" | A coefficient does not lie within [0,1].\\n\"\n \" | This may or may not be a problem.\\n\"\n \" | Double check the quality of the fit!\\n\");\n }\n if (A[i*2+1] > 0)\n {\n fprintf(stderr, \"WARNING: ----------------------------------\\n\"\n \" | One factor in the exponent is positive.\\n\"\n \" | This could be a problem if the coefficient\\n\"\n \" | is large. Double check the quality of the fit!\\n\");\n }\n }\n if (A[i*2] < 0 || A[i*2] > 1)\n {\n fprintf(stderr, \"WARNING: ----------------------------------\\n\"\n \" | The constant term does not lie within [0,1].\\n\"\n \" | This may or may not be a problem.\\n\"\n \" | Double check the quality of the fit!\\n\");\n }\n\n /* Sort the terms */\n sorted = (nexp > 1) ? FALSE : TRUE;\n while (!sorted)\n {\n sorted = TRUE;\n for (i = 0; i < nexp-1; i++)\n {\n ddt[0] = A[i*2] * A[i*2+1];\n ddt[1] = A[i*2+2] * A[i*2+3];\n\n if ((bDerivative && (ddt[0] < 0 && ddt[1] < 0 && ddt[0] > ddt[1])) || /* Compare derivative at t=0... */\n (!bDerivative && (A[i*2+1] > A[i*2+3]))) /* Or just the coefficient in the exponent */\n {\n sorted = FALSE;\n a[0] = A[i*2]; /* coefficient */\n a[1] = A[i*2+1]; /* parameter in the exponent */\n\n A[i*2] = A[i*2+2];\n A[i*2+1] = A[i*2+3];\n\n A[i*2+2] = a[0];\n A[i*2+3] = a[1];\n }\n }\n }\n\n /* Subtract the fastest component */\n fprintf(stdout, \"Fastest component is %g * exp(%g * t)\\n\"\n \"Subtracting fastest component from ACF.\\n\", A[0], A[1]);\n\n for (i = 0; i < len; i++)\n {\n ct[i] = (ct[i] - A[0] * exp(A[1] * i*BD->tDelta)) / (1-A[0]);\n }\n\n sfree(guess);\n sfree(A);\n\n gsl_multifit_fdfsolver_free(s);\n gsl_matrix_free(covar);\n fflush(stdout);\n\n#else\n /* We have no gsl. */\n fprintf(stderr, \"Sorry, can't take away ballistic component without gsl. \"\n \"Recompile using --with-gsl.\\n\");\n return;\n#endif /* HAVE_LIBGSL */\n\n}\n\nextern void dumpN(const real *e, const int nn, char *fn)\n{\n /* For debugging only */\n int i;\n FILE *f;\n char standardName[] = \"Nt.xvg\";\n if (fn == NULL)\n {\n fn = standardName;\n }\n\n f = fopen(fn, \"w\");\n fprintf(f,\n \"@ type XY\\n\"\n \"@ xaxis label \\\"Frame\\\"\\n\"\n \"@ yaxis label \\\"N\\\"\\n\"\n \"@ s0 line type 3\\n\");\n\n for (i = 0; i < nn; i++)\n {\n fprintf(f, \"%-10i %-g\\n\", i, e[i]);\n }\n\n fclose(f);\n}\n\nstatic real* d2r(const double *d, const int nn)\n{\n real *r;\n int i;\n\n snew(r, nn);\n for (i = 0; i < nn; i++)\n {\n r[i] = (real)d[i];\n }\n\n return r;\n}\n\nstatic void _patchBad(double *ct, int n, double dy)\n{\n /* Just do lin. interpolation for now. */\n int i;\n\n for (i = 1; i < n; i++)\n {\n ct[i] = ct[0]+i*dy;\n }\n}\n\nstatic void patchBadPart(double *ct, int n)\n{\n _patchBad(ct, n, (ct[n] - ct[0])/n);\n}\n\nstatic void patchBadTail(double *ct, int n)\n{\n _patchBad(ct+1, n-1, ct[1]-ct[0]);\n\n}\n\nextern void fixGemACF(double *ct, int len)\n{\n int i, j, b, e;\n gmx_bool bBad;\n\n /* Let's separate two things:\n * - identification of bad parts\n * - patching of bad parts.\n */\n\n b = 0; /* Start of a bad stretch */\n e = 0; /* End of a bad stretch */\n bBad = FALSE;\n\n /* An acf of binary data must be one at t=0. */\n if (abs(ct[0]-1.0) > 1e-6)\n {\n ct[0] = 1.0;\n fprintf(stderr, \"|ct[0]-1.0| = %1.6d. Setting ct[0] to 1.0.\\n\", abs(ct[0]-1.0));\n }\n\n for (i = 0; i < len; i++)\n {\n\n#ifdef HAS_ISFINITE\n if (isfinite(ct[i]))\n#elif defined(HAS__ISFINITE)\n if (_isfinite(ct[i]))\n#else\n if (1)\n#endif\n {\n if (!bBad)\n {\n /* Still on a good stretch. Proceed.*/\n continue;\n }\n\n /* Patch up preceding bad stretch. */\n if (i == (len-1))\n {\n /* It's the tail */\n if (b <= 1)\n {\n gmx_fatal(FARGS, \"The ACF is mostly NaN or Inf. Aborting.\");\n }\n patchBadTail(&(ct[b-2]), (len-b)+1);\n }\n\n e = i;\n patchBadPart(&(ct[b-1]), (e-b)+1);\n bBad = FALSE;\n }\n else\n {\n if (!bBad)\n {\n b = i;\n\n bBad = TRUE;\n }\n }\n }\n}\n", "meta": {"hexsha": "d9e69984502dc1f6ad5855c63de2ac8aa62625fe", "size": 37092, "ext": "c", "lang": "C", "max_stars_repo_path": "gromacs-4.6.5/src/tools/geminate.c", "max_stars_repo_name": "farajilab/gifs_release", "max_stars_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-04T18:56:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T16:49:22.000Z", "max_issues_repo_path": "gromacs-4.6.5/src/tools/geminate.c", "max_issues_repo_name": "farajilab/gifs_release", "max_issues_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gromacs-4.6.5/src/tools/geminate.c", "max_forks_repo_name": "farajilab/gifs_release", "max_forks_repo_head_hexsha": "ffa674110bcd15de851a8b6a703b4f4bc96fcd2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-02-08T00:11:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T00:11:00.000Z", "avg_line_length": 29.7449879711, "max_line_length": 135, "alphanum_fraction": 0.515555915, "num_tokens": 11263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926665855647395, "lm_q2_score": 0.3522017820478896, "lm_q1q2_score": 0.2087382275961393}} {"text": "/* C functions for running SampleTau from Cython*/\n\n/*System includes*/\n#include \n#include \n#include \n#include \n#include \n\n/*GSL includes*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*User includes*/\n//#include \"c_sample_tau.h\"\n\nstatic gsl_rng *ptGSLRNG;\n\nvoid c_initRNG()\n{\n //const gsl_rng_type * T;\n \n gsl_rng_env_setup();\n\n //T = gsl_rng_default;\n ptGSLRNG = gsl_rng_alloc (gsl_rng_mt19937);\n}\n\nvoid c_setRNG(unsigned long int seed)\n{\n //printf(\"GSL RNG initialise %lu\\n\",seed);\n gsl_rng_set (ptGSLRNG, seed);\n}\n\nvoid c_freeRNG()\n{\n gsl_rng_free (ptGSLRNG);\n}\n\n\nvoid normaliseLog4(double *adLogProb)\n{\n double dMax = adLogProb[0], dSum = 0.0;\n int b = 0;\n \n for(b = 1; b < 4; b++){\n if(adLogProb[b] > dMax){\n dMax = adLogProb[b];\n }\n }\n \n for(b = 0; b < 4; b++){\n adLogProb[b] = adLogProb[b] - dMax;\n dSum += exp(adLogProb[b]);\n }\n \n for(b = 0; b < 4; b++){\n adLogProb[b] = exp(adLogProb[b])/dSum;\n //printf(\"b=%d,p=%f\\n\",b,adLogProb[b]);\n }\n \n return;\n}\n\nint sample4(double *adProb, double dU){\n double adCProb[4];\n \n adCProb[0] = adProb[0];\n adCProb[1] = adProb[1] + adCProb[0];\n adCProb[2] = adProb[2] + adCProb[1];\n adCProb[3] = 1.0;\n \n if(dU < adCProb[0]){\n return 0;\n }\n else if(dU < adCProb[1])\n return 1;\n else if(dU < adCProb[2]){\n return 2;\n }\n else{\n return 3;\n }\n}\n\n\n\nint c_sample_tau (long *anTau, double* adPi, double *adEta, long* anVariants, int nV, int nG, int nS)\n{\n int a = 0, b = 0;\n int g = 0, h = 0, v = 0, s = 0, t = 0;\n int nchange = 0;\n double adPSB[nS][4];\n double adPSBStore[nS][4];\n double dLogProb[4];\n int** anTauIndex = NULL;\n double u = 0.0;\n\n \n anTauIndex = (int **) malloc(nV*sizeof(int*));\n if(!anTauIndex)\n goto memoryError;\n \n for(v = 0; v < nV; v++){\n anTauIndex[v] = (int *) malloc(nG*sizeof(int));\n if(!anTauIndex[v])\n goto memoryError;\n for(g = 0; g < nG; g++){\n for(b = 0; b < 4; b++){\n int vIndex = v*4*nG + 4*g + b;\n \n if(anTau[vIndex] == 1){\n anTauIndex[v][g] = b;\n break;\n }\n }\n //printf(\"%d,%d,%d\\n\",v,g,anTauIndex[v][g]);\n }\n \n }\n \n //loop V positions\n for(v = 0; v < nV; v++){\n \n //loop G strains\n for(g = 0; g < nG; g++){\n \n //calc contribution from all other strains\n for(s = 0; s < nS; s++){\n for(b = 0; b < 4; b++){\n adPSBStore[s][b] = 0.0;\n\n for(h = 0; h < nG; h++){\n if(h != g){\n int pIndex = s*nG + h;\n int eIndex = anTauIndex[v][h]*4 + b;\n \n adPSBStore[s][b] += adEta[eIndex]*adPi[pIndex]; \n }\n } \n \n }\n }\n\n for(a = 0; a < 4; a++){\n for(s = 0; s < nS; s++){\n for(b = 0; b < 4; b++){ \n adPSB[s][b] = adPSBStore[s][b];\n \n adPSB[s][b] += adEta[a*4 + b]*adPi[s*nG + g];\n }\n }\n dLogProb[a] = 0.0;\n for(s = 0; s < nS; s++){\n for(b = 0; b < 4; b++){\n int vIndex = v*4*nS + 4*s + b;\n double temp = ((float) anVariants[vIndex])*log(adPSB[s][b]);\n //printf(\"s=%d,b=%d,cont=%f\\n\",s,b,temp);\n dLogProb[a] += temp;\n }\n }\n } \n // printf(\"u=%f,p1=%f,p2=%f,p3=%f,p4 =%f\\n\",u,dLogProb[0],dLogProb[1],dLogProb[2],dLogProb[3]);\n \n normaliseLog4(dLogProb);\n \n u = gsl_rng_uniform (ptGSLRNG);\n // printf(\"u=%f,p1=%f,p2=%f,p3=%f,p4 =%f\\n\",u,dLogProb[0],dLogProb[1],dLogProb[2],dLogProb[3]);\n t = sample4(dLogProb, u);\n // printf(\"v=%d,g=%d,tnew=%d,told=%d\\n\",v,g,t,anTauIndex[v][g]);\n if(t != anTauIndex[v][g]){\n int vIndex = v*4*nG + 4*g;\n anTau[vIndex + anTauIndex[v][g]] = 0; \n anTau[vIndex + t] = 1;\n \n nchange++;\n anTauIndex[v][g] = t;\n }\n } //finish sampling strain g\n \n }//finish sampling position v\n \n \n //Free up tau indices\n for(v = 0; v < nV; v++){\n free(anTauIndex[v]);\n }\n free(anTauIndex);\n \n\n return nchange;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in c_sample_tau\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\n", "meta": {"hexsha": "4676b84bf8b5628c9ddbc8378a395685f89532c6", "size": 5213, "ext": "c", "lang": "C", "max_stars_repo_path": "sampletau/c_sample_tau.c", "max_stars_repo_name": "MatthewWolff/DESMAN", "max_stars_repo_head_hexsha": "3f683e75830c4862b5f2c7577ef31b4cc86bdd61", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2016-09-08T10:43:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T08:56:51.000Z", "max_issues_repo_path": "sampletau/c_sample_tau.c", "max_issues_repo_name": "MatthewWolff/DESMAN", "max_issues_repo_head_hexsha": "3f683e75830c4862b5f2c7577ef31b4cc86bdd61", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 39.0, "max_issues_repo_issues_event_min_datetime": "2016-10-02T13:32:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T03:01:35.000Z", "max_forks_repo_path": "sampletau/c_sample_tau.c", "max_forks_repo_name": "MatthewWolff/DESMAN", "max_forks_repo_head_hexsha": "3f683e75830c4862b5f2c7577ef31b4cc86bdd61", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2016-10-17T20:45:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T12:22:54.000Z", "avg_line_length": 25.3058252427, "max_line_length": 106, "alphanum_fraction": 0.4329560714, "num_tokens": 1605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.35936414516010196, "lm_q1q2_score": 0.20753112824392017}} {"text": "#include \n#include \n#include \n#include \n#include \n\nstatic int compute_rank(gsl_vector *v);\n\n#define BASE_LONG_DOUBLE\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_LONG_DOUBLE\n\n#define BASE_DOUBLE\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_DOUBLE\n\n#define BASE_FLOAT\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_FLOAT\n\n#define BASE_ULONG\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_ULONG\n\n#define BASE_LONG\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_LONG\n\n#define BASE_UINT\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_UINT\n\n#define BASE_INT\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_INT\n\n#define BASE_USHORT\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_USHORT\n\n#define BASE_SHORT\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_SHORT\n\n#define BASE_UCHAR\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_UCHAR\n\n#define BASE_CHAR\n#include \"templates_on.h\"\n#include \"covariance_source.c\"\n#include \"templates_off.h\"\n#undef BASE_CHAR\n\n/*\ncompute_rank()\n Compute rank of a sorted vector\n\nInputs: v - sorted data vector on input; rank vector on output\n\nNotes: ranks are always computed in double precision\n*/\n\nstatic int\ncompute_rank(gsl_vector *v)\n{\n const size_t n = v->size;\n size_t i = 0;\n\n while (i < n - 1)\n {\n double vi = gsl_vector_get(v, i);\n\n if (vi == gsl_vector_get(v, i + 1))\n {\n size_t j = i + 2;\n size_t k;\n double rank = 0.0;\n\n /* we have detected a tie, find number of equal elements */\n while (j < n && vi == gsl_vector_get(v, j))\n ++j;\n\n /* compute rank */\n for (k = i; k < j; ++k)\n rank += k + 1.0;\n\n /* divide by number of ties */\n rank /= (double) (j - i);\n\n for (k = i; k < j; ++k)\n gsl_vector_set(v, k, rank);\n\n i = j;\n }\n else\n {\n /* no tie - set rank to natural ordered position */\n gsl_vector_set(v, i, i + 1.0);\n ++i;\n }\n }\n\n if (i == n - 1)\n gsl_vector_set(v, n - 1, (double) n);\n\n return GSL_SUCCESS;\n} /* compute_rank() */\n", "meta": {"hexsha": "78803c9eabf7ce3fe8937939648f78c5fe331023", "size": 2666, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/statistics/covariance.c", "max_stars_repo_name": "ielomariala/Hex-Game", "max_stars_repo_head_hexsha": "2c2e7c85f8414cb0e654cb82e9686cce5e75c63a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T18:09:25.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:31:28.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/statistics/covariance.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/statistics/covariance.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": 20.6666666667, "max_line_length": 69, "alphanum_fraction": 0.6549137284, "num_tokens": 686, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230157, "lm_q2_score": 0.3998116407397951, "lm_q1q2_score": 0.20615084450333376}} {"text": "/** \n * @file piecewise_regimes.c\n * @author Carl Boettiger \n * @date 17 May 2010\n *\n * @section LICENSE \n *\n * GPLv3\n *\n * @section DESCRIPTION\n *\n * Code for computing the likelihood of a multitype OU process on a phylogenetic tree\n *\n */\n\n#include \"likelihood.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"optimizers.h\"\n#include \"mvn.h\"\n\n/**\n* @brief Function which wraps general format used by siman and multimin \n* into the likelihood format of calc_lik\n*\n* @param v vector of values being optimized by the algorithm \n* @param params specifies the tree and observed data\n*\n* @return minus log likelihood\n*/\ndouble optim_func (const gsl_vector *v, void *params)\n{\n tree * mytree = (tree *) params;\n int i, n_regimes = mytree->n_regimes;\n// Force root to match Theta of regime assigned to it, should also reduce vector size!\n mytree->Xo[0] = mytree->theta[mytree->regimes[0]];\n // mytree->Xo[0] = gsl_vector_get(v, 0);\n for(i = 0; i < n_regimes; i++){\n mytree->alpha[i] = v->data[i];\n mytree->theta[i] = v->data[n_regimes+i];\n mytree->sigma[i] = v->data[2*n_regimes+i];\n\n if( (mytree->alpha[i] < 0) | (mytree->sigma[i] < 0) ){ return GSL_POSINF; }\n if( mytree->theta[i] < 0 ){ return GSL_POSINF; }\n }\n \n double llik = 0;\n calc_lik(mytree->Xo, mytree->alpha, mytree->theta, mytree->sigma,\n mytree->regimes, mytree->ancestor, mytree->branch_length,\n mytree->traits, &(mytree->n_nodes), mytree->lca_matrix, &llik);\n return -llik;\n}\n\n\n/** Fit the model by maximum likelihood, called by R */\nvoid fit_model(double * Xo, \n double * alpha, \n double * theta, \n double * sigma, \n int * regimes, \n int * ancestor, \n double * branch_length, \n double * traits, \n int * n_nodes, \n int * n_regimes,\n double * llik,\n int * use_siman)\n{\n\n// Perhaps don't want to see gsl_errors once we're handling in R?\n// Still want better/smarter behavior of the optimizer \n gsl_set_error_handler_off ();\n \n /** First, initialize the tree structure to facilitate passing all these elements */\n int i,j;\n tree * mytree = (tree *) malloc(sizeof(tree));\n mytree->Xo = Xo;\n mytree->alpha = alpha;\n mytree->theta = theta;\n mytree->sigma = sigma;\n mytree->regimes = regimes;\n mytree->ancestor = ancestor;\n mytree->branch_length = branch_length;\n mytree->traits = traits;\n mytree->n_nodes = *n_nodes;\n mytree->n_regimes = *n_regimes;\n\n /** Second, save time by storing the least common ancestor matrix */\n /* Save time by calculating least common ancestor ahead of time.\n * Though this does the calc for all nodes, only tip ones are used. \n * Current get_lca algorithm is only designed for tips anyway. */\n double sep; // separation time, not actually used\n mytree->lca_matrix = (int *) malloc(gsl_pow_2(*n_nodes) * sizeof(int) );\n for(i=0; i < *n_nodes; i++){\n for(j=0; j < *n_nodes; j++){\n mytree->lca_matrix[*n_nodes*i+j] = get_lca(i,j, *n_nodes, ancestor, branch_length, &sep);\n }\n }\n\n /** Then initialize the vector of parameters to be searched */\n gsl_vector *x = gsl_vector_alloc(3 * *n_regimes);\n// gsl_vector_set(x, 0, *Xo); /* Forces Xo to match theta (?) */\n for(i = 0; i < *n_regimes; i++){\n gsl_vector_set(x, i, alpha[i]);\n gsl_vector_set(x, *n_regimes+i, theta[i]);\n gsl_vector_set(x, 2 * *n_regimes+i, mytree->sigma[i]);\n }\n\n /** Select and call a likelihood optimization routine \n * given the tree (with data) and parameters */\n gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);\n if(*use_siman)\n *llik = siman(x, mytree, rng); \n else \n *llik = multimin(x, mytree);\n\n\n gsl_rng_free(rng);\n gsl_vector_free(x);\n free(mytree->lca_matrix);\n free(mytree);\n}\n\n\n\n\n/* Externally exported function to determine LCA matrix */\n/**\n* @brief Determine the last common ancestor matrix of the tips,\n* used in the likelihood calculation\n*\n* @param ancestor ancestor of the specified nide\n* @param branch_length double branch lengths below each of the nodes\n* @param n_nodes: integer number of nodes (including tips) in the tree \n* @param lca_matrix must be an integer array of size n_nodes^2\n*/\nvoid calc_lca(int * ancestor, double * branch_length, \n int * n_nodes, int * lca_matrix)\n{\n int i,j;\n /* Save time by calculating least common ancestor ahead of time.\n * Though this does the calc for all nodes, only tip ones are used. \n * Current get_lca algorithm is only designed for tips anyway. */\n double sep; // separation time, not actually used \n for(i=0; i < *n_nodes; i++){\n for(j=0; j < *n_nodes; j++){\n lca_matrix[*n_nodes*i+j] = get_lca(i,j, *n_nodes, ancestor,\n branch_length, &sep);\n }\n }\n\n}\n\n\n\n\n/** Simulate under the model. Called by R */\nvoid simulate_model (double * Xo, double * alpha, double * theta, \n double * sigma, int * regimes, int * ancestor, \n double * branch_length, double * traits, int * n_nodes,\n int * n_regimes, double * llik, double * seed)\n{\n\n /* Turn off likelihood calcuation on the simulated data for speed */\n int return_likelihood = 0; // consider making an option at the .C level \n\n int i,j;\n tree * mytree = (tree *) malloc(sizeof(tree));\n mytree->Xo = Xo;\n mytree->alpha = alpha;\n mytree->theta = theta;\n mytree->sigma = sigma;\n mytree->regimes = regimes;\n mytree->ancestor = ancestor;\n mytree->branch_length = branch_length;\n mytree->traits = traits;\n mytree->n_nodes = *n_nodes;\n mytree->n_regimes = *n_regimes;\n\n /* Save time by calculating least common ancestor ahead of time. */\n double sep; // separation time, not actually used\n mytree->lca_matrix = (int *) malloc(gsl_pow_2(*n_nodes) * sizeof(int) );\n for(i=0; i < *n_nodes; i++){\n for(j=0; j < *n_nodes; j++){\n mytree->lca_matrix[*n_nodes*i+j] = \n get_lca(i,j, *n_nodes, ancestor, branch_length, &sep);\n }\n }\n\n\n /* Allocate the parameter vector */\n gsl_vector *x = gsl_vector_alloc(1 + 3 * *n_regimes);\n gsl_vector_set(x, 0, *Xo);\n for(i = 0; i < *n_regimes; i++){\n gsl_vector_set(x, 1+i, alpha[i]);\n gsl_vector_set(x, 1+*n_regimes+i, theta[i]);\n gsl_vector_set(x, 1+2 * *n_regimes+i, mytree->sigma[i]);\n }\n \n gsl_rng * rng = gsl_rng_alloc(gsl_rng_default);\n gsl_rng_set(rng, *seed);\n\n /* These are the only lines that differ from the fit_models wrapper */ \n simulate (rng, mytree);\n \n if(return_likelihood){\n calc_lik(mytree->Xo, mytree->alpha, mytree->theta, mytree->sigma, \n mytree->regimes, mytree->ancestor, mytree->branch_length, \n mytree->traits, &(mytree->n_nodes), mytree->lca_matrix, llik);\n }\n\n// for(i=0; i< mytree->n_regimes; i++) printf(\"%g %g %g\\n\", mytree->alpha[i], mytree->theta[i], mytree->sigma[i] );\n// printf(\"sim llik: %g\\n\", *llik);\n\n\n gsl_rng_free(rng);\n gsl_vector_free(x);\n free(mytree->lca_matrix);\n free(mytree);\n}\n\n\n\n\n\n/** Test code by running in pure C */\nint main(void)\n{\n /** Define the tree and the trait data (Anoles tree from \"ouch\" R package) */\n int n_nodes = 45;\n\n double branch_length[] = { 0.0, 12./38, 20./38, 2./38, 2./38, 4./38, \n 8./38, 5./38, 5./38, 5./38, 5./38, 10./38, \n 9./38, 4./38, 8./38, 2./38, 20./38, 2./38, \n 4./38, 2./38, 1./38, 2./38, 26./38, 4./38, \n 2./38, 2./38, 2./38, 2./38, 15./38, 10./38, \n 10./38, 10./38, 10./38, 16./38, 12./38, 4./38, \n 2./38, 2./38, 10./38, 8./38, 2./38, 1./38, \n 1./38, 2./38, 2./38};\n\n\n/* Almost a star tree */\n/* double branch_length[] = { 0.000, .001, .001, .001, .001, \n\t\t\t 0.001, .001, .001, .001, .001,\n\t\t\t 0.001, .001, .001, .001, .001,\n\t\t\t 0.001, .001, .001, .001, .001,\n\t\t\t 0.001, .001, .999, .999, .999,\n\t\t\t 0.999, .999, .999, .999, .999,\n\t\t\t 0.999, .999, .999, .999, .999,\n\t\t\t 0.999, .999, .999, .999, .999,\n\t\t\t 0.999, .999, .999, .999, .999 };\n*/\n\n int ancestor[] = {-1, 0, 1, 2, 3, 2, 0, 6, 7, 8, 9,\n 8, 7, 12, 13,14, 6, 16, 17, 18, 19, 18, 1,\n 3, 4, 4, 5, 5, 9, 10, 10, 11, 11, 12, \n 13, 14, 15, 15, 16, 17, 19, 20, 20, 21, 21};\n\n double traits[] = {0.000000, 0.000000, 0.000000, 0.000000, 0.000000, \n 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,\n 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,\n 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, \n 0.000000, 0.000000, 2.602690, 2.660260, 2.660260, \n 2.653242, 2.674149, 2.701361, 7.161247, 13.299534, \n 3.328627, 3.353407, 3.360375, 3.049273, 2.906901, \n 2.980619, 2.933857, 3.975530, -3.104587, 3.346389,\n 12.928524, -12.939162, 7.990720, 8.058707, -5.068053};\n\n/*\n int regimes[] = {1, 1, 2, 2, 2, \n 2, 1, 1, 0, 0, \n 0, 0, 1, 1, 1, \n 1, 1, 1, 1, 1, \n 1, 1, 2, 2, 2, \n 2, 2, 2, 0, 0, \n 0, 0, 0, 1, 1, \n 1, 1, 0, 1, 1, \n 1, 1, 1, 1, 1}; \n*/\n\n int regimes[] = {0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0, \n 0, 0, 0, 0, 0}; \n\n\n double Xo = 3;\n\n double alpha[3] = {2.6, 2.6, 2.6};\n double theta[3] = {3., 3.,3};\n double sigma[3] = {0.2, 0.2, 0.2 };\n int n_regimes = 3;\n\n double llik = 0;\n\n /* Initialize the lca matrix */\n int * lca = (int *) calloc(n_nodes*n_nodes, sizeof(int));\n \n /* test the pure likelihood function first */\n calc_lca(ancestor, branch_length, &n_nodes, lca);\n\n calc_lik(&Xo, alpha, theta, sigma, regimes, ancestor, \n branch_length, traits, &n_nodes, lca, &llik);\n printf(\"log likelihood: %g\\n\", llik);\n\n /* We'll use the faster Nelder-Mead algorithm for the check */\n int use_siman = 0;\n /* Test the fitting routine */\n\n fit_model(&Xo, alpha, theta, sigma, regimes, ancestor, branch_length,\n traits, &n_nodes, &n_regimes, &llik, &use_siman);\n printf(\"Xo = %g\\n\", Xo);\n printf(\"alphas: %g %g %g\\n\", alpha[0], alpha[1], alpha[2]);\n printf(\"thetas: %g %g %g\\n\", theta[0], theta[1], theta[2]);\n printf(\"sigmas: %g %g %g\\n\", sigma[0], sigma[1], sigma[2]);\n printf(\"log likelihood: %g\\n\", llik);\n\n\n /* Test the simulation code */\n/*\n double seed = 1.0;\n printf(\"seed: %lo\\n\", (unsigned long int) seed);\n simulate_model(&Xo, alpha, theta, sigma, regimes, ancestor, branch_length,\n traits, &n_nodes, &n_regimes, &llik, &seed);\n int i;\n printf(\"simulated traits:\\n\");\n for(i=0; i < 45; i++) \n printf(\"%g \", traits[i]);\n printf(\"\\n\");\n*/\n\n free(lca); \n return 0;\n}\n", "meta": {"hexsha": "de2d614c2aeb11183ed0a4de643b59fd784b767d", "size": 11138, "ext": "c", "lang": "C", "max_stars_repo_path": "src/piecewise_regimes.c", "max_stars_repo_name": "cboettig/wrightscape", "max_stars_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/piecewise_regimes.c", "max_issues_repo_name": "cboettig/wrightscape", "max_issues_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/piecewise_regimes.c", "max_forks_repo_name": "cboettig/wrightscape", "max_forks_repo_head_hexsha": "93947673f4342266acf5af667141bd466de13b3a", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.284057971, "max_line_length": 116, "alphanum_fraction": 0.5735320524, "num_tokens": 3820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5428632831725052, "lm_q2_score": 0.37754066879814546, "lm_q1q2_score": 0.20495296699490465}} {"text": "/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. */\n\n#ifndef MATHFUNCTIONS_H_\n#define MATHFUNCTIONS_H_\n\n#ifdef PADDLE_USE_MKL\n#include \n#include \n#else\nextern \"C\" {\n#include \n}\n#ifdef PADDLE_USE_ATLAS\nextern \"C\" {\n#include \n}\n#else\n#include \n#endif\n#endif\n\n#include \n\nnamespace paddle {\n\ntemplate \nvoid gemm(const CBLAS_TRANSPOSE transA,\n const CBLAS_TRANSPOSE transB,\n const int M,\n const int N,\n const int K,\n const T alpha,\n const T* A,\n const int lda,\n const T* B,\n const int ldb,\n const T beta,\n T* C,\n const int ldc);\n\ntemplate \nint getrf(const CBLAS_ORDER Order,\n const int M,\n const int N,\n T* A,\n const int lda,\n int* ipiv);\n\ntemplate \nint getri(\n const CBLAS_ORDER Order, const int N, T* A, const int lda, const int* ipiv);\n\ntemplate \nvoid axpy(const int n, const T alpha, const T* x, T* y);\n\ntemplate \nT dotProduct(const int n, const T* x, const T* y);\n\ntemplate \nvoid vExp(const int n, const T* a, T* r);\n\ntemplate \nvoid vPow(const int n, const T* a, const T b, T* r);\n\ntemplate \nvoid vLog(const int n, const T* a, T* r);\n\ntemplate \nvoid vAdd(const int n, const T* a, const T* b, T* r);\n\ntemplate \nvoid vInvSqrt(const int n, const T* a, T* r);\n\ntemplate \nvoid vLog1p(const int n, const T* a, T* r);\n\ntemplate \nvoid vTanh(const int n, const T* a, T* r);\n\n} // namespace paddle\n\n#endif // MATHFUNCTIONS_H_\n", "meta": {"hexsha": "c8559eefd8378450fc18c2ba821c65b39c8cc046", "size": 2182, "ext": "h", "lang": "C", "max_stars_repo_path": "paddle/math/MathFunctions.h", "max_stars_repo_name": "emailweixu/Paddle", "max_stars_repo_head_hexsha": "7b67f9863e4af535835bf3012b3192db42362308", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T20:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2016-10-07T20:40:11.000Z", "max_issues_repo_path": "paddle/math/MathFunctions.h", "max_issues_repo_name": "anuranrc/Paddle", "max_issues_repo_head_hexsha": "21fa3eb0688459d3b71141d316e8358d31882b8d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-26T18:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-26T18:33:00.000Z", "max_forks_repo_path": "paddle/math/MathFunctions.h", "max_forks_repo_name": "anuranrc/Paddle", "max_forks_repo_head_hexsha": "21fa3eb0688459d3b71141d316e8358d31882b8d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-10-07T00:50:53.000Z", "max_forks_repo_forks_event_max_datetime": "2016-10-07T00:50:53.000Z", "avg_line_length": 22.9684210526, "max_line_length": 80, "alphanum_fraction": 0.6626947754, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5926666143433998, "lm_q2_score": 0.34510527095787247, "lm_q1q2_score": 0.20453237253066392}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Geometrics\n{\n\ttemplate \n\tstruct Triangle\n\t{\n\t\tstatic constexpr size_t VertexCount = 3;\n\t\ttypedef std::array container_type;\n\t\tcontainer_type v;\n\n\t\ttypedef IndexType value_type;\r\n\t\ttypedef size_t size_type;\r\n\t\ttypedef ptrdiff_t difference_type;\r\n\t\ttypedef IndexType *pointer;\r\n\t\ttypedef const IndexType *const_pointer;\r\n\t\ttypedef IndexType& reference;\r\n\t\ttypedef const IndexType& const_reference;\r\n\r\n\t\ttypedef typename container_type::iterator iterator;\r\n\t\ttypedef typename container_type::const_iterator const_iterator;\r\n\r\n\t\ttypedef typename container_type::reverse_iterator reverse_iterator;\r\n\t\ttypedef typename container_type::const_reverse_iterator const_reverse_iterator;\r\n\n\t\tTriangle() {}\n\t\tTriangle(const IndexType &v0, const IndexType &v1, const IndexType &v2)\n\t\t{\n\t\t\tv[0] = v0; v[1] = v1; v[2] = v2;\n\t\t}\n\t\tTriangle(const IndexType *v_)\n\t\t{\n\t\t\tv[0] = v_[0]; v[1] = v_[1]; v[2] = v_[2];\n\t\t}\n\t\ttemplate explicit Triangle(const S &x)\n\t\t{\n\t\t\tv[0] = x[0]; v[1] = x[1]; v[2] = x[2];\n\t\t}\n\t\tIndexType &operator[] (int i) { return v[i]; }\n\t\tconst IndexType &operator[] (int i) const { return v[i]; }\n\t\toperator const IndexType * () const { return &(v[0]); }\n\t\toperator IndexType * () { return &(v[0]); }\n\n\t\tvoid rewind() {\n\t\t\tstd::swap(v[0], v[2]);\n\t\t}\n\n\t\tint indexof(IndexType v_) const\n\t\t{\n\t\t\treturn (v[0] == v_) ? 0 :\n\t\t\t\t(v[1] == v_) ? 1 :\n\t\t\t\t(v[2] == v_) ? 2 : -1;\n\t\t}\n\n\t\t// contrainer access\n\t\tauto begin() { return v.begin(); }\n\t\tauto end() { return v.end(); }\n\t\tauto begin() const { return v.begin(); }\n\t\tauto end() const { return v.end(); }\n\n\t\tauto rbegin() { return v.rbegin(); }\n\t\tauto rend() { return v.rend(); }\n\t\tauto rbegin() const { return v.rbegin(); }\n\t\tauto rend() const { return v.rend(); }\n\n\t\tsize_t size() const { return VertexCount; }\n\t};\n\n\t// generate per vertex normal for given triangle mesh\n\ttemplate \n\tbool generate_normal(gsl::span vertices, gsl::span> facets)\n\t{\n\t\tusing namespace DirectX::VertexTraits;\n\t\tusing namespace DirectX;\n\n\t\tif (!has_normal::value)\n\t\t\treturn false;\n\n\t\t//static_assert(has_normal::value, \"The vertex type dose not contains normal field\");\n\n\t\tstd::vector normals(vertices.size());\n\n\t\t// set zero\n\t\tstd::memset(normals.data(), 0, normals.size() * sizeof(XMVECTOR));\n\n\t\tXMVECTOR v0, v1, v2, n;\n\t\tfor (const auto& face : facets)\n\t\t{\n\t\t\tv0 = get_position(vertices[face[0]]);\n\t\t\tv1 = get_position(vertices[face[1]]);\n\t\t\tv2 = get_position(vertices[face[2]]);\n\t\t\tv1 -= v0;\n\t\t\tv2 -= v0;\n\n\t\t\tv1 = XMVector3Normalize(v1);\n\t\t\tv2 = XMVector3Normalize(v2);\n\t\t\tn = XMVector3Cross(v1, v2); // weighted normal \n\n\t\t\tnormals[face[0]] += n;\n\t\t\tnormals[face[1]] += n;\n\t\t\tnormals[face[2]] += n;\n\t\t}\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\r\n\t\t{\r\n\t\t\tn = XMVector3Normalize(normals[i]);\r\n\t\t\tset_normal(vertices[i], n);\r\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t// generate per vertex tangent for given triangle mesh\n\ttemplate \n\tbool generate_tangent(gsl::span vertices, gsl::span> facets)\n\t{\n\t\tusing namespace DirectX::VertexTraits;\n\t\tusing namespace DirectX;\n\n\t\tif (!has_tangent::value)\n\t\t\treturn false;\n\t\t//static_assert(has_tangent::value, \"The vertex type dose not contains tangent field\");\n\n\t\tstd::vector tan1(vertices.size() * 2);\n\t\tXMVECTOR* tan2 = &tan1[vertices.size()];\n\t\tstd::memset(tan1.data(), 0, tan1.size() * sizeof(XMVECTOR));\n\n\t\tfor (const auto& face : facets)\n\t\t{\n\t\t\t{\n\t\t\t\tXMVECTOR v0, v1, v2, w0, w1, w2;\n\t\t\t\tv0 = get_position(vertices[face[0]]);\n\t\t\t\tw0 = get_uv(vertices[face[0]]);\n\n\t\t\t\tv1 = get_position(vertices[face[1]]);\n\t\t\t\tw1 = get_uv(vertices[face[1]]);\n\n\t\t\t\tv2 = get_position(vertices[face[2]]);\n\t\t\t\tw2 = get_uv(vertices[face[2]]);\n\t\t\t}\n\t\t\tXMFLOAT4A v_1, v_2, w_1, w_2;\n\n\t\t\tXMStoreA(v_1, v1 - v0);\n\t\t\tXMStoreA(v_2, v2 - v0);\n\t\t\tXMStoreA(w_1, w1 - w0);\n\t\t\tXMStoreA(w_2, w2 - w0);\n\n\t\t\tfloat x1 = v_1.x; float x2 = v_2.x;\r\n\t\t\tfloat y1 = v_1.y; float y2 = v_2.y;\r\n\t\t\tfloat z1 = v_1.z; float z2 = v_2.z;\r\n\r\n\t\t\tfloat s1 = w_1.x; float s2 = w_2.x;\r\n\t\t\tfloat t1 = w_1.y; float t2 = w_2.y;\r\n\r\n\t\t\tfloat r = 1.0F / (s1 * t2 - s2 * t1);\r\n\t\t\tXMVECTOR sdir = XMVectorSet(\r\n\t\t\t\t(t2 * x1 - t1 * x2) * r,\r\n\t\t\t\t(t2 * y1 - t1 * y2) * r,\r\n\t\t\t\t(t2 * z1 - t1 * z2) * r, .0f);\r\n\t\t\tXMVECTOR tdir = XMVectorSet(\r\n\t\t\t\t(s1 * x2 - s2 * x1) * r,\r\n\t\t\t\t(s1 * y2 - s2 * y1) * r,\r\n\t\t\t\t(s1 * z2 - s2 * z1) * r, .0f);\r\n\r\n\t\t\ttan1[face[0]] += sdir;\n\t\t\ttan1[face[1]] += sdir;\n\t\t\ttan1[face[2]] += sdir;\n\r\n\t\t\ttan2[face[0]] += tdir;\n\t\t\ttan2[face[1]] += tdir;\n\t\t\ttan2[face[2]] += tdir;\n\t\t}\n\n\t\tfor (size_t i = 0; i < vertices.size(); i++)\r\n\t\t{\r\n\t\t\tXMVECTOR n = get_normal(vertices[i], n);\r\n\t\t\tXMVECTOR t = tan1[i];\r\n\n\t\t\t// Gram-Schmidt orthogonalize\n\t\t\tXMVECTOR nt = XMVector3Normalize(t - n * XMVector3Dot(n, t));\r\n\n\t\t\tXMVECTOR w = XMVectorLess(XMVector3Dot(XMVector3Cross(n, t), tan2[i]), XMVectorZero());\n\t\t\tw = XMVectorSelect(g_XMNegativeOne.v, g_XMOne.v, w);\n\n\t\t\tnt = _DXMEXT XMVectorSelect<0, 0, 0, 1>(nt, w);\n\t\t\tset_tangent(vertices[i], nt);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\ttemplate >\n\tclass PolygonSoup\n\t{\n\tpublic:\n\t\ttypedef _VertexType VertexType;\n\t\ttypedef _IndexType\tIndexType;\n\t\ttypedef _FaceType\tFaceType;\n\n\t\tstatic constexpr size_t PolygonVertex = FaceType::VertexCount;\n\n\t\tPolygonSoup() {}\n\n\t\tbool empty() const {\n\t\t\treturn vertices.empty() || indices.empty();\n\t\t}\n\n\t\tvoid clear()\n\t\t{\n\t\t\tvertices.clear();\n\t\t\tindices.clear();\n\t\t}\n\n\t\tinline const FaceType& facet(int idx) const\n\t\t{\n\t\t\treturn reinterpret_cast(indices[idx * FaceType::VertexCount]);\n\t\t}\n\n\t\tinline FaceType& facet(int idx)\n\t\t{\n\t\t\treturn reinterpret_cast(indices[idx * FaceType::VertexCount]);\n\t\t}\n\n\t\tvoid add_facet(const FaceType& new_facet)\n\t\t{\n\t\t\tindices.insert(indices.end(), new_facet.begin(), new_facet.end());\n\t\t}\n\n\t\ttemplate \n\t\tstd::enable_if_t add_facet(_TIndecies... _indices)\n\t\t{\n\t\t\tindices.insert(indices.end(), { static_cast(_indices)... });\n\t\t}\n\n\n\t\tgsl::span facets() {\n\t\t\treturn gsl::span(\n\t\t\t\treinterpret_cast(indices.data()),\n\t\t\t\tindices.size() / FaceType::VertexCount);\n\t\t}\n\n\t\tgsl::span facets() const {\n\t\t\treturn gsl::span(\n\t\t\t\treinterpret_cast(indices.data()),\n\t\t\t\tindices.size() / FaceType::VertexCount);\n\t\t}\n\n\t\tconst VertexType& vertex(int facet, int vidx) const\n\t\t{\n\t\t\treturn this->vertices[facet * FaceType::VertexCount + vidx];\n\t\t}\n\n\t\tVertexType& vertex(int facet, int vidx)\n\t\t{\n\t\t\treturn this->vertices[facet * FaceType::VertexCount + vidx];\n\t\t}\n\n\t\t// flip all the polygons' winding and vertices' normal \n\t\tvoid flip()\n\t\t{\n\t\t\tusing namespace DirectX::VertexTraits;\n\n\t\t\tif (has_normal::value)\n\t\t\t{\n\t\t\t\tfor (auto& v : vertices)\r\n\t\t\t\t\tset_normal(v, -get_normal(v));\r\n\t\t\t}\r\n\r\n\t\t\tstatic constexpr int vc = FaceType::VertexCount;\r\n\t\t\tfor (int i = 0; i < indices.size() / vc; i++)\r\n\t\t\t\tstd::reverse(indices.begin() + i * vc, indices.begin() + (i + 1)* vc);\r\n\t\t}\n\n\t\tvoid generate_normal()\n\t\t{\n\t\t\tstatic_assert(PolygonVertex == 3, \"This mesh is not trigle mesh, please trianglize it first\");\n\t\t\tgenerate_normal(this->vertices, this->facets());\n\t\t}\n\n\t\tvoid generate_tangent()\n\t\t{\n\t\t\tstatic_assert(PolygonVertex == 3, \"This mesh is not trigle mesh, please trianglize it first\");\n\t\t\tgenerate_tangent(this->vertices, this->facets());\n\t\t}\n\n\t\t// applies an uniform transform to all vertices in the mesh \n\t\tvoid XM_CALLCONV transform(DirectX::FXMMATRIX M)\n\t\t{\n\t\t\tusing namespace DirectX::VertexTraits;\n\t\t\tfor (auto& v : vertices)\r\n\t\t\t{\r\n\t\t\t\tXMVECTOR p = get_position(v);\r\n\t\t\t\tp = _DXMEXT XMVector3TransformCoord(p, M);\r\n\t\t\t\tset_position(v, p);\r\n\r\n\t\t\t\tif (has_normal::value)\r\n\t\t\t\t{\r\n\t\t\t\t\tp = get_normal(v);\r\n\t\t\t\t\tp = _DXMEXT XMVector3TransformNormal(p, M);\r\n\t\t\t\t\tset_normal(v, p);\r\n\r\n\t\t\t\t\tif (has_tangent::value)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tp = get_tangent(v);\r\n\t\t\t\t\t\tp = _DXMEXT XMVector3TransformNormal(p, M);\r\n\t\t\t\t\t\tset_tangent(v, p);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\n\t\t}\n\n\t\tstd::vector vertices;\n\t\tstd::vector\tindices;\n\t};\n\n\ttemplate \n\tint XM_CALLCONV intersect(const PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>> &Mesh, DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, std::vector* distances = nullptr)\n\t{\n\t\tusing namespace DirectX;\n\t\tusing namespace DirectX::VertexTraits;\n\t\tint count = 0;\n\t\tXMVECTOR vDir = XMVector3Normalize(Direction);\n\t\tfor (const auto& tri : Mesh.facets())\n\t\t{\n\t\t\tfloat distance;\n\n\t\t\tXMVECTOR v0 = get_position(&Mesh.vertices[tri[0]]);\n\t\t\tXMVECTOR v1 = get_position(&Mesh.vertices[tri[1]]);\n\t\t\tXMVECTOR v2 = get_position(&Mesh.vertices[tri[2]]);\n\n\t\t\tbool hr = DirectX::TriangleTests::Intersects(Origin, vDir, v0, v1, v2, distance);\n\t\t\tif (hr) {\n\t\t\t\t++count;\n\t\t\t\tif (distances) {\n\t\t\t\t\tdistances->push_back(distances);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn count;\n\t}\n\n\n\tstruct MeshRayIntersectionInfo\n\t{\n\t\tusing Vector3 = DirectX::Vector3;\n\n\t\tVector3 position;\n\t\tfloat\tdistance;\n\t\tVector3 barycentric;\n\t\tint\t\tfacet; // facet id\n\n\t\tinline bool operator < (const MeshRayIntersectionInfo& rhs)\n\t\t{\n\t\t\treturn this->distance < rhs.distance;\n\t\t}\n\t};\n\n\t/// \n\t/// Basic triangle mesh, each index represent an edge, which is the edge oppsite to the vertex in it's owner triangle\n\t/// \n\ttemplate \n\tclass TriangleMesh : public PolygonSoup<_VertexType, _IndexType, Triangle<_IndexType>>\n\t{\n\tpublic:\n\t\tstatic const size_t VertexCount = FaceType::VertexCount;\n\n\tpublic:\n\t\t// edge's reverse edge\n\t\t// stores the adjacent edges of a edge in a triangle\n\t\tstd::vector revedges;\n\n\t\t// vertex's first adjacant edge\n\t\t// std::vector vedges;\n\n\t\tunion EdgeType\n\t\t{\n\t\t\t_IndexType v[2];\n\t\t\tstruct {\n\t\t\t\t_IndexType v0, v1;\n\t\t\t};\n\t\t};\n\n\t\tinline EdgeType edge(int facet, int edge) const\n\t\t{\n\t\t\tEdgeType e;\n\t\t\tauto& tri = this->facet(facet);\n\t\t\tswitch (edge)\n\t\t\t{\n\t\t\tcase 0:\n\t\t\t\te.v0 = tri[1];\n\t\t\t\te.v1 = tri[2];\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\te.v0 = tri[2];\n\t\t\t\te.v1 = tri[0];\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\te.v0 = tri[0];\n\t\t\t\te.v1 = tri[1];\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\te.v0 = -1;\n\t\t\t\te.v1 = -1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn e;\n\t\t}\n\n\t\tinline EdgeType edge(int eid) const\n\t\t{\n\t\t\treturn edge(eid / VertexCount, eid % VertexCount);\n\t\t}\n\n\t\tinline int adjacentFacet(int facet, int edge) const\n\t\t{\n\t\t\treturn revedges[facet * VertexCount + edge] / VertexCount;\n\t\t}\n\n\t\tinline int adjacentFacet(int eid) const\n\t\t{\n\t\t\treturn revedges[eid] / VertexCount;\n\t\t}\n\n\t\t// build the adjacent map so we can access all the 1 rings\n\t\tvoid build()\n\t\t{\n\t\t\t// intialize all adjacant edges to -1\n\t\t\trevedges.resize(this->indices.size(), -1);\n\t\t\t_IndexType vsize = this->vertices.size();\n\t\t\tint esize = this->indices.size();\n\n\t\t\tusing hash_type = uint64_t;\n\t\t\t// make sure int for hash is enough\n\t\t\tassert(vsize*vsize < std::numeric_limits::max());\n\t\t\tstd::unordered_map edges(esize * 2);\n\t\t\t// max items inside this table should be less than (esize / 2)\n\n\t\t\t_IndexType fid = 0;\n\t\t\tfor (const Triangle<_IndexType>& tri : this->facets())\n\t\t\t{\n\t\t\t\tfor (_IndexType i = 0; i < VertexCount; i++)\n\t\t\t\t{\n\t\t\t\t\t_IndexType eid = i + fid * 3;\n\t\t\t\t\tauto e = edge(fid, i);\n\n\t\t\t\t\thash_type ehash = e.v0 * vsize + e.v1;\n\t\t\t\t\thash_type revehash = e.v0 + e.v1 * vsize;\n\n\t\t\t\t\tauto revItr = edges.find(revehash);\n\t\t\t\t\tif (revItr == edges.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tedges[ehash] = fid + 0;\n\t\t\t\t\t}\n\t\t\t\t\telse // find reversed edge, remove from edges map\n\t\t\t\t\t{\n\t\t\t\t\t\tauto revEid = revItr->second;\n\t\t\t\t\t\trevedges[eid] = revEid;\n\t\t\t\t\t\trevedges[revEid] = eid;\n\t\t\t\t\t\tedges.erase(revItr);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t++fid;\n\t\t\t}\n\t\t}\n\n\t\tint XM_CALLCONV intersect(DirectX::FXMVECTOR Origin, DirectX::FXMVECTOR Direction, std::vector* output) const\n\t\t{\n\t\t\t//assert(revedges.size() == indices.size());\n\t\t\tusing namespace DirectX;\n\t\t\tusing namespace DirectX::VertexTraits;\n\t\t\tsize_t count = 0;\n\t\t\tXMVECTOR vDir = XMVector3Normalize(Direction);\n\t\t\tauto fid = 0;\n\t\t\tfor (const auto& tri : this->facets())\n\t\t\t{\n\t\t\t\tfloat distance;\n\n\t\t\t\tXMVECTOR v0 = get_position(&this->vertices[tri[0]]);\n\t\t\t\tXMVECTOR v1 = get_position(&this->vertices[tri[1]]);\n\t\t\t\tXMVECTOR v2 = get_position(&this->vertices[tri[2]]);\n\n\t\t\t\tbool hr = DirectX::TriangleTests::Intersects(Origin, vDir, v0, v1, v2, distance);\n\t\t\t\tif (hr) {\n\t\t\t\t\t++count;\n\t\t\t\t\tif (output) {\n\t\t\t\t\t\toutput->emplace_back();\n\t\t\t\t\t\tauto& info = output->back();\n\t\t\t\t\t\tXMVECTOR pos = distance * vDir + Origin;\n\t\t\t\t\t\tXMVECTOR bc = DirectX::TriangleTests::BarycentricCoordinate(pos, v0, v1, v2);\n\t\t\t\t\t\tinfo.facet = fid;\n\t\t\t\t\t\tinfo.position = pos;\n\t\t\t\t\t\tinfo.distance = distance;\n\t\t\t\t\t\tinfo.barycentric = bc;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t++fid;\n\t\t\t}\n\n\t\t\tif (output)\n\t\t\t\tstd::sort(output->begin(), output->end());\n\t\t\treturn count;\n\t\t}\n\t};\n\n\tnamespace Internal\n\t{\n#ifndef min\n\t\ttemplate \n\t\tinline T clamp(T value, T minV, T maxV)\n\t\t{\n\t\t\treturn std::max(std::min(value, maxV), minV);\n\t\t}\n#else\n\t\ttemplate \n\t\tinline T clamp(T value, T minV, T maxV)\n\t\t{\n\t\t\treturn max(min(value, maxV), minV);\n\t\t}\n#endif\n\t}\n\n\t/// \n\t/// Compute the closest projection point from P0 to triangle(V0,V1,V2).\n\t/// \n\t/// The p0.\n\t/// The v0.\n\t/// The v1.\n\t/// The v2.\n\t/// \n\tinline DirectX::XMVECTOR XM_CALLCONV Projection(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)\n\t{\n\t\tusing namespace DirectX;\n\t\tusing namespace Geometrics::Internal;\n\t\tXMVECTOR edge0 = V1 - V0;\n\t\tXMVECTOR edge1 = V2 - V0;\n\t\tXMVECTOR p0 = V0 - P0;\n\n\t\t//XMVectorBaryCentric();\n\n\t\tfloat a = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge0));\n\t\tfloat b = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, edge1));\n\t\tfloat c = XMVectorGetX(_DXMEXT XMVector3LengthSq(edge1));\n\t\tfloat d = XMVectorGetX(_DXMEXT XMVector3Dot(edge0, p0));\n\t\tfloat e = XMVectorGetX(_DXMEXT XMVector3Dot(edge1, p0));\n\n\t\tfloat det = a*c - b*b;\n\t\tfloat s = b*e - c*d;\n\t\tfloat t = b*d - a*e;\n\n\t\tif (s + t < det)\n\t\t{\n\t\t\tif (s < 0.f)\n\t\t\t{\n\t\t\t\tif (t < 0.f)\n\t\t\t\t{\n\t\t\t\t\tif (d < 0.f)\n\t\t\t\t\t{\n\t\t\t\t\t\ts = clamp(-d / a, 0.f, 1.f);\n\t\t\t\t\t\tt = 0.f;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\ts = 0.f;\n\t\t\t\t\t\tt = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts = 0.f;\n\t\t\t\t\tt = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (t < 0.f)\n\t\t\t{\n\t\t\t\ts = clamp(-d / a, 0.f, 1.f);\n\t\t\t\tt = 0.f;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat invDet = 1.f / det;\n\t\t\t\ts *= invDet;\n\t\t\t\tt *= invDet;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (s < 0.f)\n\t\t\t{\n\t\t\t\tfloat tmp0 = b + d;\n\t\t\t\tfloat tmp1 = c + e;\n\t\t\t\tif (tmp1 > tmp0)\n\t\t\t\t{\n\t\t\t\t\tfloat numer = tmp1 - tmp0;\n\t\t\t\t\tfloat denom = a - 2 * b + c;\n\t\t\t\t\ts = clamp(numer / denom, 0.f, 1.f);\n\t\t\t\t\tt = 1 - s;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tt = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t\ts = 0.f;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (t < 0.f)\n\t\t\t{\n\t\t\t\tif (a + d > b + e)\n\t\t\t\t{\n\t\t\t\t\tfloat numer = c + e - b - d;\n\t\t\t\t\tfloat denom = a - 2 * b + c;\n\t\t\t\t\ts = clamp(numer / denom, 0.f, 1.f);\n\t\t\t\t\tt = 1 - s;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ts = clamp(-e / c, 0.f, 1.f);\n\t\t\t\t\tt = 0.f;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfloat numer = c + e - b - d;\n\t\t\t\tfloat denom = a - 2 * b + c;\n\t\t\t\ts = clamp(numer / denom, 0.f, 1.f);\n\t\t\t\tt = 1.f - s;\n\t\t\t}\n\t\t}\n\n\t\treturn V0 + s * edge0 + t * edge1;\n\t}\n\n\tinline float XM_CALLCONV Distance(DirectX::FXMVECTOR P0, DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::GXMVECTOR V2)\n\t{\n\t\tusing namespace DirectX;\n\t\tXMVECTOR vProj = Projection(P0, V0, V1, V2);\n\t\tvProj -= P0;\n\t\treturn XMVectorGetX(_DXMEXT XMVector3Length(vProj));\n\t}\n\n\ttemplate \n\tinline float XM_CALLCONV Distance(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)\n\t{\n\t\tusing namespace DirectX;\n\t\tfloat minDis = numeric_limits::max();\n\t\tfor (const auto& tri : Mesh.facets())\n\t\t{\n\t\t\tfloat dis;\n\n\t\t\tXMVECTOR v0 = XMLoadFloat3(&Mesh.vertices[tri[0]].position);\n\t\t\tXMVECTOR v1 = XMLoadFloat3(&Mesh.vertices[tri[1]].position);\n\t\t\tXMVECTOR v2 = XMLoadFloat3(&Mesh.vertices[tri[2]].position);\n\n\t\t\tdis = Distance(Point, v0, v1, v2);\n\t\t\tif (dis < minDis) minDis = dis;\n\t\t\t//minDis = std::min(dis,minDis);\n\t\t}\n\n\t\t//XMVECTOR vDis = XMVectorReplicate(numeric_limits::max());\n\t\t//for (const auto& vertex : Mesh.vertices)\n\t\t//{\n\t\t//\tXMVECTOR vPos = XMLoadFloat3(&vertex.position);\n\t\t//\tvPos -= Point;\n\t\t//\tXMVECTOR dis = XMVector3Length(vPos);\n\t\t//\tvDis = XMVectorMin(vDis,dis);\n\t\t//}\n\n\t\t//float minDisV = XMVectorGetX(vDis);\n\t\t//assert(minDisV >= minDis);\n\t\treturn minDis;\n\t\t//return XMVectorGetX(minDis);\n\t}\n\n\n\ttemplate \n\tbool XM_CALLCONV Inside(const TriangleMesh<_VertexType, _IndexType> &Mesh, DirectX::FXMVECTOR Point)\n\t{\n\t\tXMFLOAT3A Direction;\n\t\tDirection.x = (float)std::rand() / (RAND_MAX + 1);\n\t\tDirection.y = (float)std::rand() / (RAND_MAX + 1);\n\t\tDirection.z = (float)std::rand() / (RAND_MAX + 1);\n\t\tXMVECTOR vDir = XMLoadFloat3A(&Direction);\n\t\tauto count = intersect(Mesh, Point, vDir, nullptr);\n\t\treturn count & 1; //count % 2\n\t}\n\n\n\n}", "meta": {"hexsha": "60333707730a3a4d8df108ff59ada3993253807b", "size": 17582, "ext": "h", "lang": "C", "max_stars_repo_path": "Geometrics/TriangleMesh.h", "max_stars_repo_name": "ArcEarth/PPARM", "max_stars_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-13T18:30:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-31T22:20:34.000Z", "max_issues_repo_path": "Geometrics/TriangleMesh.h", "max_issues_repo_name": "ArcEarth/PPARM", "max_issues_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Geometrics/TriangleMesh.h", "max_forks_repo_name": "ArcEarth/PPARM", "max_forks_repo_head_hexsha": "8e22e3f20a90a22940218c243b7fe5e24e754e5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2016-01-16T14:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2017-06-12T16:15:18.000Z", "avg_line_length": 25.1891117479, "max_line_length": 196, "alphanum_fraction": 0.6275736549, "num_tokens": 5700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5156199157230156, "lm_q2_score": 0.3923368301671084, "lm_q1q2_score": 0.2022966833057995}} {"text": "/* $Id$ */\n/*--------------------------------------------------------------------*/\n/*; Copyright (C) 2008-2020 */\n/*; Associated Universities, Inc. Washington DC, USA. */\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 as */\n/*; published by the Free Software Foundation; either version 2 of */\n/*; 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 */\n/*; License along with this program; if not, write to the Free */\n/*; Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, */\n/*; MA 02139, USA. */\n/*; */\n/*;Correspondence about this software should be addressed as follows: */\n/*; Internet email: bcotton@nrao.edu. */\n/*; Postal address: William Cotton */\n/*; National Radio Astronomy Observatory */\n/*; 520 Edgemont Road */\n/*; Charlottesville, VA 22903-2475 USA */\n/*--------------------------------------------------------------------*/\n\n#include \"ObitSpectrumFit.h\"\n#include \"ObitImageMF.h\"\n#include \"ObitThread.h\"\n#ifdef HAVE_GSL\n#include \n#endif /* HAVE_GSL */ \n/*----------------Obit: Merx mollis mortibus nuper ------------------*/\n/**\n * \\file ObitSpectrumFit.c\n * ObitSpectrumFit class function definitions.\n * This class is derived from the Obit base class.\n */\n\n/** name of the class defined in this file */\nstatic gchar *myClassName = \"ObitSpectrumFit\";\n\n/** Function to obtain parent ClassInfo */\nstatic ObitGetClassFP ObitParentGetClass = ObitGetClass;\n\n/**\n * ClassInfo structure ObitSpectrumFitClassInfo.\n * This structure is used by class objects to access class functions.\n */\nstatic ObitSpectrumFitClassInfo myClassInfo = {FALSE};\n\n/*--------------- File Global Variables ----------------*/\n\n\n/*---------------Private function prototypes----------------*/\n/** Private: Initialize newly instantiated object. */\nvoid ObitSpectrumFitInit (gpointer in);\n\n/** Private: Deallocate members. */\nvoid ObitSpectrumFitClear (gpointer in);\n\n/** Private: Set Class function pointers. */\nstatic void ObitSpectrumFitClassInfoDefFn (gpointer inClass);\n\n#ifdef HAVE_GSL\n/** Private: Solver function evaluation */\nstatic int SpecFitFunc (const gsl_vector *x, void *params, \n\t\t\tgsl_vector *f);\n\n/** Private: Solver Jacobian evaluation */\nstatic int SpecFitJac (const gsl_vector *x, void *params, \n\t\t\tgsl_matrix *J);\n\n/** Private: Solver function + Jacobian evaluation */\nstatic int SpecFitFuncJac (const gsl_vector *x, void *params, \n\t\t\tgsl_vector *f, gsl_matrix *J);\n\n/** Private: Solver function evaluation - broken power law */\nstatic int SpecFitFuncBP (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f);\n\n/** Private: Solver Jacobian evaluation - broken power law */\nstatic int SpecFitJacBP (const gsl_vector *x, void *params, \n\t\t\t gsl_matrix *J);\n\n/** Private: Solver function + Jacobian evaluation - broken power law */\nstatic int SpecFitFuncJacBP (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f, gsl_matrix *J);\n#endif /* HAVE_GSL */ \n\n/** Private: Threaded fitting */\nstatic gpointer ThreadNLFit (gpointer arg);\n\n/*---------------Private structures----------------*/\n/* FT threaded function argument */\ntypedef struct {\n /** ObitSpectrumFit object */\n ObitSpectrumFit *in;\n /* Obit error stack object */\n ObitErr *err;\n /** First (1-rel) value in y to process this thread */\n olong first;\n /** Highest (1-rel) value in y to process this thread */\n olong last;\n /** thread number, >0 -> no threading */\n olong ithread;\n /** max number of terms to fit */\n olong nterm;\n /** number of terms being fitted */\n olong fitTerm;\n /** number of frequencies */\n olong nfreq;\n /** Minimum fraction of weight */\n ofloat minWt;\n /** Array of Nu per frequency point - broken power law */\n ofloat *nu;\n /** Array of log (Nu/Nu_0) per frequency point */\n ofloat *logNuOnu0;\n /** Array of weights (1/RMS**2) per inFArrays (nfreq) */\n ofloat *weight;\n /** Array of 1/RMS per inFArrays (nfreq) */\n ofloat *isigma;\n /** Array of pixel values being fitted per frequency point */\n ofloat *obs;\n /** maximum iteration */\n olong maxIter;\n /** acceptable iteration delta, rel and abs. */\n odouble minDelta;\n /** max acceptable normalized chi squares */\n ofloat maxChiSq;\n /** Reference frequency */\n ofloat refFreq;\n /* Spectral index correction to be applied to data */\n ofloat corAlpha;\n /** Vector of guess/fitted coefficients, optional errors */\n ofloat *coef;\n /** Chi squared of fit */\n ofloat ChiSq;\n /** Do error analysis? */\n gboolean doError;\n /** Do broken power law ? */\n gboolean doBrokePow;\n /** Do Primary beam correction? */\n gboolean doPBCorr;\n#ifdef HAVE_GSL\n /** Fitting solver for two terms */\n gsl_multifit_fdfsolver *solver2;\n /** Fitting solver for three terms */\n gsl_multifit_fdfsolver *solver3;\n /** Fitting solver for four terms */\n gsl_multifit_fdfsolver *solver4;\n /** Fitting solver for five terms */\n gsl_multifit_fdfsolver *solver5;\n /** Fitting solver function structure */\n gsl_multifit_function_fdf *funcStruc;\n /** Fitting work vector of length 2 */\n gsl_vector *work2;\n /** Fitting work vector of length 3 */\n gsl_vector *work3;\n /** Fitting work vector of length 4 */\n gsl_vector *work4;\n /** Fitting work vector of length 5 */\n gsl_vector *work5;\n /** Covariance matrix for two terms */\n gsl_matrix *covar2;\n /** Covariance matrix for three terms */\n gsl_matrix *covar3;\n /** Covariance matrix for four terms */\n gsl_matrix *covar4;\n /** Covariance matrix for five terms */\n gsl_matrix *covar5;\n#endif /* HAVE_GSL */ \n} NLFitArg;\n\n/** Private: Actual fitting */\nstatic void NLFit (NLFitArg *arg);\n\n/** Private: Actual fitting broken power */\nstatic void NLFitBP (NLFitArg *arg);\n\n/*----------------------Public functions---------------------------*/\n/**\n * Constructor.\n * Initializes class if needed on first call.\n * \\param name An optional name for the object.\n * \\return the new object.\n */\nObitSpectrumFit* newObitSpectrumFit (gchar* name)\n{\n ObitSpectrumFit* out;\n\n /* Class initialization if needed */\n if (!myClassInfo.initialized) ObitSpectrumFitClassInit();\n\n /* allocate/init structure */\n out = g_malloc0(sizeof(ObitSpectrumFit));\n\n /* initialize values */\n if (name!=NULL) out->name = g_strdup(name);\n else out->name = g_strdup(\"Noname\");\n\n /* set ClassInfo */\n out->ClassInfo = (gpointer)&myClassInfo;\n\n /* initialize other stuff */\n ObitSpectrumFitInit((gpointer)out);\n\n return out;\n} /* end newObitSpectrumFit */\n\n/**\n * Returns ClassInfo pointer for the class.\n * \\return pointer to the class structure.\n */\ngconstpointer ObitSpectrumFitGetClass (void)\n{\n /* Class initialization if needed */\n if (!myClassInfo.initialized) ObitSpectrumFitClassInit();\n\n return (gconstpointer)&myClassInfo;\n} /* end ObitSpectrumFitGetClass */\n\n/**\n * Make a deep copy of an ObitSpectrumFit.\n * \\param in The object to copy\n * \\param out An existing object pointer for output or NULL if none exists.\n * \\param err Obit error stack object.\n * \\return pointer to the new object.\n */\nObitSpectrumFit* ObitSpectrumFitCopy (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err)\n{\n const ObitClassInfo *ParentClass;\n gboolean oldExist;\n gchar *outName;\n olong i, nOut;\n\n /* error checks */\n if (err->error) return out;\n g_assert (ObitIsA(in, &myClassInfo));\n if (out) g_assert (ObitIsA(out, &myClassInfo));\n\n /* Create if it doesn't exist */\n oldExist = out!=NULL;\n if (!oldExist) {\n /* derive object name */\n outName = g_strconcat (\"Copy: \",in->name,NULL);\n out = newObitSpectrumFit(outName);\n g_free(outName);\n }\n\n /* deep copy any base class members */\n ParentClass = myClassInfo.ParentClass;\n g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n ParentClass->ObitCopy (in, out, err);\n\n /* copy this class */\n out->nfreq = in->nfreq;\n out->nterm = in->nterm;\n\n /* Arrays */\n if (out->RMS) g_free(out->RMS);\n out->RMS = g_malloc0(out->nfreq*sizeof(ofloat));\n if (in->RMS)\n for (i=0; infreq; i++) out->RMS[i] = in->RMS[i];\n if (out->calFract) g_free(out->calFract);\n out->calFract = g_malloc0(out->nfreq*sizeof(ofloat));\n if (in->calFract)\n if (out->calFract) g_free(out->calFract);\n \n /* reference this class members */\n if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc);\n if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc);\n if (out->inFArrays) {\n for (i=0; infreq; i++) out->inFArrays[i] = ObitFArrayUnref(out->inFArrays[i]);\n }\n if (in->inFArrays) {\n for (i=0; infreq; i++) out->inFArrays[i] = ObitFArrayRef(in->inFArrays[i]);\n }\n\n if (out->BeamShapes) {\n for (i=0; infreq; i++) out->BeamShapes[i] = ObitBeamShapeUnref(out->BeamShapes[i]);\n }\n if (in->BeamShapes) {\n for (i=0; infreq; i++) out->BeamShapes[i] = ObitBeamShapeRef(in->BeamShapes[i]);\n }\n\n\n /* How many output planes */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n if (out->outFArrays) {\n for (i=0; ioutFArrays[i] = ObitFArrayUnref(out->outFArrays[i]);\n }\n if (in->outFArrays) {\n for (i=0; ioutFArrays[i] = ObitFArrayRef(in->outFArrays[i]);\n }\n\n return out;\n} /* end ObitSpectrumFitCopy */\n\n/**\n * Make a copy of a object but do not copy the actual data\n * This is useful to create an SpectrumFit similar to the input one.\n * \\param in The object to copy\n * \\param out An existing object pointer for output, must be defined.\n * \\param err Obit error stack object.\n */\nvoid ObitSpectrumFitClone (ObitSpectrumFit *in, ObitSpectrumFit *out, ObitErr *err)\n{\n const ObitClassInfo *ParentClass;\n olong i, nOut;\n\n /* error checks */\n g_assert (ObitErrIsA(err));\n if (err->error) return;\n g_assert (ObitIsA(in, &myClassInfo));\n g_assert (ObitIsA(out, &myClassInfo));\n\n /* deep copy any base class members */\n ParentClass = myClassInfo.ParentClass;\n g_assert ((ParentClass!=NULL) && (ParentClass->ObitCopy!=NULL));\n ParentClass->ObitCopy (in, out, err);\n\n /* copy this class */\n out->nfreq = in->nfreq;\n out->nterm = in->nterm;\n \n /* Arrays */\n if (out->RMS) g_free(out->RMS);\n out->RMS = g_malloc0(out->nfreq*sizeof(ofloat));\n if (in->RMS)\n for (i=0; infreq; i++) out->RMS[i] = in->RMS[i];\n if (out->calFract) g_free(out->calFract);\n out->calFract = g_malloc0(out->nfreq*sizeof(ofloat));\n if (in->calFract)\n if (out->calFract) g_free(out->calFract);\n \n\n /* reference this class members */\n if (out->outDesc) out->outDesc = ObitImageDescUnref(out->outDesc);\n if (in->outDesc) out->outDesc = ObitImageDescRef(in->outDesc);\n if (out->inFArrays) {\n for (i=0; infreq; i++) out->inFArrays[i] = ObitFArrayUnref(out->inFArrays[i]);\n }\n if (in->inFArrays) {\n for (i=0; infreq; i++) out->inFArrays[i] = ObitFArrayRef(in->inFArrays[i]);\n }\n\n if (out->BeamShapes) {\n for (i=0; infreq; i++) out->BeamShapes[i] = ObitBeamShapeUnref(out->BeamShapes[i]);\n }\n if (in->BeamShapes) {\n for (i=0; infreq; i++) out->BeamShapes[i] = ObitBeamShapeRef(in->BeamShapes[i]);\n }\n\n /* How many output planes */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n if (out->outFArrays) {\n for (i=0; ioutFArrays[i] = ObitFArrayUnref(out->outFArrays[i]);\n }\n if (in->outFArrays) {\n for (i=0; ioutFArrays[i] = ObitFArrayRef(in->outFArrays[i]);\n }\n\n} /* end ObitSpectrumFitClone */\n\n/**\n * Creates an ObitSpectrumFit \n * \\param name An optional name for the object.\n * \\param nterm Number of coefficients of powers of log(nu)\n * \\return the new object.\n */\nObitSpectrumFit* ObitSpectrumFitCreate (gchar* name, olong nterm)\n{\n ObitSpectrumFit* out;\n\n /* Create basic structure */\n out = newObitSpectrumFit (name);\n out->nterm = nterm;\n\n return out;\n} /* end ObitSpectrumFitCreate */\n\n/**\n * Fit spectra to an image cube pixels.\n * The third axis of the output image will be \"SPECLOGF\" to indicate that then\n * planes are spectral fit parameters. The \"CRVAL\" on this axis will be the reference \n * Frequency for the fitting.\n * Item \"NTERM\" is added to the output image descriptor to give the maximum number \n * Item \"\"BROKENPO\" is added to the output image descriptor if fit is a broken power law\n * of terms fitted\n * \\param in Spectral fitting object\n * Potential parameters on in->info:\n * \\li \"refFreq\" OBIT_double scalar Reference frequency for fit [def ref for inImage]\n * \\li \"maxChi2\" OBIT_float scalar Max. Chi Sq for accepting a partial spectrum [def 1.5]\n * \\li \"doError\" OBIT_boolean scalar If true do error analysis [def False]\n * \\li \"doPBCor\" OBIT_boolean scalar If true do primary beam correction. [def False]\n * \\li \"doBrokePow\" OBIT_boolean scalar If true do broken power law (3 terms). [def False]\n * \\li \"calFract\" OBIT_float (?,1,1) Calibration error as fraction of flux\n * One per frequency or one for all, def 1.0e-5\n * \\li \"PBmin\" OBIT_float (?,1,1) Minimum beam gain correction\n * One per frequency or one for all, def 0.05, 1.0 => no gain corrections\n * \\li \"antSize\" OBIT_float (?,1,1) Antenna diameter (m) for gain corr, \n * One per frequency or one for all, def 25.0\n * \\li corAlpha OBIT_float scalar, if non zero, spectral index \n * correction to apply, def = 0.0\n *\n * \\param inImage Image cube to be fitted\n * If an ObitImageMF the the fitter in that class is called\n * \\param outImage Image cube with fitted spectra.\n * Should be defined but not created.\n * Planes 1->nterm are coefficients per pixel\n * if doError:\n * Planes nterm+1->2*nterm are uncertainties in coefficients\n * Plane 2*nterm+1 = Chi squared of fit\n * \\param err Obit error stack object.\n */\nvoid ObitSpectrumFitCube (ObitSpectrumFit* in, ObitImage *inImage, \n\t\t\t ObitImage *outImage, ObitErr *err)\n{\n olong i, iplane, nOut;\n olong naxis[2];\n ObitIOSize IOBy;\n ObitInfoType type;\n ObitIOCode retCode;\n union ObitInfoListEquiv InfoReal; \n gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}, PBdim[MAXINFOELEMDIM], ASdim[MAXINFOELEMDIM];\n ofloat *calFract, *PBmin, *antSize, aSize, pbmin, antsize;\n gboolean doGain, isMF;\n gchar *today=NULL, *SPECLOGF = \"SPECLOGF\";\n gchar *routine = \"ObitSpectrumFitCube\";\n\n /* error checks */\n if (err->error) return;\n g_assert (ObitIsA(in, &myClassInfo));\n g_assert(ObitImageIsA(inImage));\n g_assert(ObitImageIsA(outImage));\n\n /* Control parameters */\n /* Min Chi^2 for fit */\n InfoReal.flt = 1.5; type = OBIT_float;\n in->maxChi2 = 1.5;\n ObitInfoListGetTest(in->info, \"maxChi2\", &type, dim, &InfoReal);\n if (type==OBIT_float) in->maxChi2 = InfoReal.flt;\n else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl;\n\n /* Want Error analysis? */\n InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n ObitInfoListGetTest(in->info, \"doError\", &type, dim, &InfoReal);\n in->doError = InfoReal.itg;\n\n /* Want primary beam correction? */\n InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n ObitInfoListGetTest(in->info, \"doPBCor\", &type, dim, &InfoReal);\n in->doPBCorr = InfoReal.itg;\n\n /* Want Broken power law ? */\n InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n ObitInfoListGetTest(in->info, \"doBrokePow\", &type, dim, &InfoReal);\n in->doBrokePow = InfoReal.itg;\n\n /* Spectral index correction */\n in->corAlpha = 0.0;\n ObitInfoListGetTest(in->info, \"corAlpha\", &type, dim, &in->corAlpha);\n /* Min PB gain */\n ObitInfoListGetP(in->info, \"PBmin\", &type, PBdim, (gpointer)&PBmin);\n /* Antenna diameter */\n ObitInfoListGetP(in->info, \"antSize\", &type, ASdim, (gpointer)&antSize);\n\n /* Check if an ObitImageMF input image */\n isMF = ObitImageMFIsA(inImage);\n /* Use ObitImageMF class for fitting */\n if (isMF) {\n /* Copy pixels first */\n outImage = (ObitImage*)ObitImageMFCopy ((ObitImageMF*)inImage, (ObitImageMF*)outImage, err);\n /* Then Fit */\n if (!in->doPBCorr) aSize = 0.0;\n else aSize = antSize[0];\n ObitImageMFFitSpec ((ObitImageMF*)outImage, aSize, err);\n if (err->error) Obit_traceback_msg (err, routine, inImage->name);\n return;\n }\n\n /* Open input image to get info */\n IOBy = OBIT_IO_byPlane;\n dim[0] = 1;\n ObitInfoListAlwaysPut (inImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n inImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */\n retCode = ObitImageOpen (inImage, OBIT_IO_ReadOnly, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, inImage->name);\n\n /* Get Reference frequency , default input ref. freq. */\n InfoReal.dbl = inImage->myDesc->crval[inImage->myDesc->jlocf]; \n type = OBIT_double;\n in->refFreq = InfoReal.dbl;\n ObitInfoListGetTest(in->info, \"refFreq\", &type, dim, &InfoReal);\n if (type==OBIT_float) in->refFreq = InfoReal.flt;\n else if (type==OBIT_double) in->refFreq = (ofloat)InfoReal.dbl;\n \n /* Determine number of frequency planes and initialize in */\n in->nfreq = inImage->myDesc->inaxes[inImage->myDesc->jlocf];\n in->BeamShapes = g_malloc0(in->nfreq*sizeof(ObitBeamShape*));\n for (i=0; infreq; i++) in->BeamShapes[i] = NULL;\n in->RMS = g_malloc0(in->nfreq*sizeof(ofloat));\n in->calFract = g_malloc0(in->nfreq*sizeof(ofloat));\n in->inFArrays = g_malloc0(in->nfreq*sizeof(ObitFArray*));\n in->freqs = g_malloc0(in->nfreq*sizeof(odouble));\n\n /* How many output planes? */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n\n /* Define term arrays */\n in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*));\n for (i=0; ioutFArrays[i] = NULL;\n\n /* Image size */\n in->nx = inImage->myDesc->inaxes[0];\n in->ny = inImage->myDesc->inaxes[1];\n naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny; \n for (i=0; infreq; i++) in->inFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n for (i=0; ioutFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n\n /* Calibration error */\n for (i=0; infreq; i++) in->calFract[i] = 1.0e-5; /* default */\n if (ObitInfoListGetP(in->info, \"calFract\", &type, dim, (gpointer)&calFract)) {\n if (dim[0]>=in->nfreq) for (i=0; infreq; i++) in->calFract[i] = calFract[i];\n else for (i=0; infreq; i++) in->calFract[i] = calFract[0];\n }\n\n /* Output Image descriptor */\n outImage->myDesc = ObitImageDescCopy (inImage->myDesc, in->outDesc, err);\n if (err->error) Obit_traceback_msg (err, routine, inImage->name);\n\n /* Change third axis to type \"SPECLOGF\" and leave the reference frequency\n as the \"CRVAL\" */\n outImage->myDesc->inaxes[outImage->myDesc->jlocf] = nOut;\n outImage->myDesc->crval[outImage->myDesc->jlocf] = in->refFreq;\n outImage->myDesc->crpix[outImage->myDesc->jlocf] = 1.0;\n outImage->myDesc->cdelt[outImage->myDesc->jlocf] = 1.0;\n strncpy (outImage->myDesc->ctype[outImage->myDesc->jlocf], SPECLOGF, IMLEN_KEYWORD);\n outImage->myDesc->bitpix = -32; /* Float it */\n\n /* Creation date today */\n today = ObitToday();\n strncpy (outImage->myDesc->date, today, IMLEN_VALUE);\n if (today) g_free(today);\n\n /* Copy of output descriptor to in */\n in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err);\n\n /* Loop reading planes */\n for (iplane=0; iplanenfreq; iplane++) {\n retCode = ObitImageRead (inImage, in->inFArrays[iplane]->array, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, inImage->name);\n\n /* Get BeamShape */\n antsize = 25.0;\n if (antSize) antsize = antSize[0];\n if (antSize && (ASdim[0]>=in->nfreq)) antsize = antSize[i];\n pbmin = 0.05;\n if (PBmin) pbmin = PBmin[0];\n if (PBmin && (PBdim[0]>=in->nfreq)) pbmin = PBmin[i];\n doGain = pbmin<0.999;\n in->BeamShapes[iplane] = ObitBeamShapeCreate (\"BS\", inImage, pbmin, antsize, doGain);\n\n /* Plane RMS */\n in->RMS[iplane] = ObitFArrayRMS(in->inFArrays[iplane]);\n /* Frequency */\n in->freqs[iplane] = inImage->myDesc->crval[inImage->myDesc->jlocf] + \n inImage->myDesc->cdelt[inImage->myDesc->jlocf] * \n (inImage->myDesc->plane - inImage->myDesc->crpix[inImage->myDesc->jlocf]);\n \n } /* end loop reading planes */\n\n /* Close input */\n retCode = ObitImageClose (inImage, err);\n inImage->extBuffer = FALSE; /* May need I/O buffer later */\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, inImage->name);\n\n /* Average Frequency - no\n in->refFreq = 0.0;\n for (i=0; infreq; i++) in->refFreq += in->freqs[i];\n in->refFreq /= in->nfreq;*/\n\n /* Do actual fitting */\n ObitSpectrumFitter (in, err);\n if (err->error) Obit_traceback_msg (err, routine, inImage->name);\n\n /* Update output header to reference Frequency */\n outImage->myDesc->crval[outImage->myDesc->jlocf] = in->refFreq;\n in->outDesc->crval[in->outDesc->jlocf] = in->refFreq;\n\n /* Write output */\n ObitSpectrumWriteOutput(in, outImage, err);\n if (err->error) Obit_traceback_msg (err, routine, inImage->name);\n\n} /* end ObitSpectrumFitCube */\n\n/**\n * Fit spectra to an array of images\n * The third axis of the output image will be \"SPECLOGF\" to indicate that then\n * planes are spectral fit parameters. The \"CRVAL\" on this axis will be the reference \n * Frequency for the fitting.\n * Item \"NTERM\" is added to the output image descriptor to give the maximum number \n * of terms fitted\n * Item \"\"BROKENPO\" is added to the output image descriptor if fit is a broken power law\n * \\param in Spectral fitting object\n * \\li \"refFreq\" OBIT_double scalar Reference frequency for fit [def average of inputs]\n * \\li \"maxChi2\" OBIT_float scalar Max. Chi Sq for accepting a partial spectrum [def 1.5]\n * \\li \"doError\" OBIT_boolean scalar If true do error analysis [def False]\n * \\li \"doPBCor\" OBIT_boolean scalar If true do primary beam correction.[def False]\n * \\li \"doBrokePow\" OBIT_boolean scalar If true do broken power law (3 terms). [def False]\n * \\li \"calFract\" OBIT_float (?,1,1) Calibration error as fraction of flux\n * One per frequency or one for all, def 0.05\n * \\li \"PBmin\" OBIT_float (?,1,1) Minimum beam gain correction\n * One per frequency or one for all, def 0.05, 1.0 => no gain corrections\n * \\li \"antSize\" OBIT_float (?,1,1) Antenna diameter (m) for gain corr, \n * One per frequency or one for all, def 25.0\n * \\li corAlpha OBIT_float scalar, if non zero, spectral index \n * correction to apply, def = 0.0\n * \\param nimage Number of entries in imArr\n * \\param imArr Array of images to be fitted\n * \\param outImage Image cube with fitted spectra.\n * Should be defined but not created.\n * Planes 1->nterm are coefficients per pixel\n * if doError:\n * Planes nterm+1->2*nterm are uncertainties in coefficients\n * Plane 2*nterm+1 = Chi squared of fit\n * \\param err Obit error stack object.\n */\nvoid ObitSpectrumFitImArr (ObitSpectrumFit* in, olong nimage, ObitImage **imArr, \n\t\t\t ObitImage *outImage, ObitErr *err)\n{\n olong i, jlocf, iplane, nOut;\n olong naxis[2];\n ObitIOSize IOBy;\n ObitInfoType type;\n ObitIOCode retCode;\n union ObitInfoListEquiv InfoReal; \n gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1}, PBdim[MAXINFOELEMDIM], ASdim[MAXINFOELEMDIM];\n ofloat *calFract=NULL, *PBmin=NULL, *antSize=NULL, pbmin, antsize, ipixel[2], opixel[2];\n gboolean doGain, bad;\n odouble avgFreq;\n gchar *today=NULL, *SPECLOGF = \"SPECLOGF\";\n gchar *routine = \"ObitSpectrumFitCube\";\n\n /* error checks */\n if (err->error) return;\n g_assert (ObitIsA(in, &myClassInfo));\n g_assert(ObitImageIsA(outImage));\n\n /* Control parameters */\n /* Max Chi^2 for fit */\n InfoReal.flt = 1.5; type = OBIT_float;\n in->maxChi2 = 1.5;\n ObitInfoListGetTest(in->info, \"maxChi2\", &type, dim, &InfoReal);\n if (type==OBIT_float) in->maxChi2 = InfoReal.flt;\n else if (type==OBIT_double) in->maxChi2 = (ofloat)InfoReal.dbl;\n\n /* Want Error analysis? */\n InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n ObitInfoListGetTest(in->info, \"doError\", &type, dim, &InfoReal);\n in->doError = InfoReal.itg;\n\n /* Want primary beam correction? */\n InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n ObitInfoListGetTest(in->info, \"doPBCor\", &type, dim, &InfoReal);\n in->doPBCorr = InfoReal.itg;\n\n /* Want Broken power law ? */\n InfoReal.itg = (olong)FALSE; type = OBIT_bool;\n ObitInfoListGetTest(in->info, \"doBrokePow\", &type, dim, &InfoReal);\n in->doBrokePow = InfoReal.itg;\n\n /* Spectral index correction */\n in->corAlpha = 0.0;\n ObitInfoListGetTest(in->info, \"corAlpha\", &type, dim, &in->corAlpha);\n /* Min PB gain */\n ObitInfoListGetP(in->info, \"PBmin\", &type, PBdim, (gpointer)&PBmin);\n /* Antenna diameter */\n ObitInfoListGetP(in->info, \"antSize\", &type, ASdim, (gpointer)&antSize);\n\n /* Determine number of frequency planes and initialize in */\n in->nfreq = nimage;\n in->BeamShapes = g_malloc0(in->nfreq*sizeof(ObitBeamShape*));\n for (i=0; infreq; i++) in->BeamShapes[i] = NULL;\n in->RMS = g_malloc0(in->nfreq*sizeof(ofloat));\n in->calFract = g_malloc0(in->nfreq*sizeof(ofloat));\n in->inFArrays = g_malloc0(in->nfreq*sizeof(ObitFArray*));\n in->freqs = g_malloc0(in->nfreq*sizeof(odouble));\n\n /* Calibration error */\n for (i=0; infreq; i++) in->calFract[i] = 0.05; /* default */\n if (ObitInfoListGetP(in->info, \"calFract\", &type, dim, (gpointer)&calFract)) {\n if (dim[0]>=in->nfreq) for (i=0; infreq; i++) in->calFract[i] = calFract[i];\n else for (i=0; infreq; i++) in->calFract[i] = calFract[0];\n }\n \n /* How many output planes? */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n \n /* Define term arrays */\n in->outFArrays = g_malloc0((nOut)*sizeof(ObitFArray*));\n for (i=0; ioutFArrays[i] = NULL;\n\n /* Loop over images */\n for (iplane = 0; iplaneinfo, \"IOBy\", OBIT_long, dim, &IOBy);\n imArr[iplane]->extBuffer = TRUE; /* Using inFArrays as I/O buffer */\n retCode = ObitImageOpen (imArr[iplane], OBIT_IO_ReadOnly, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, imArr[iplane]->name);\n \n /* On first image initialize */\n if (iplane==0) {\n /* Image size */\n in->nx = imArr[iplane]->myDesc->inaxes[0];\n in->ny = imArr[iplane]->myDesc->inaxes[1];\n naxis[0] = (olong)in->nx; naxis[1] = (olong)in->ny; \n for (i=0; infreq; i++) in->inFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n for (i=0; ioutFArrays[i] = ObitFArrayCreate (NULL, 2, naxis);\n \n /* Output Image descriptor */\n outImage->myDesc = ObitImageDescCopy (imArr[iplane]->myDesc, in->outDesc, err);\n if (err->error) Obit_traceback_msg (err, routine, imArr[iplane]->name);\n\n /* Change third axis to type \"SPECLOGF\" and leave the reference frequency\n\t as the \"CRVAL\" */\n if (outImage->myDesc->jlocf>0) jlocf = outImage->myDesc->jlocf;\n else jlocf = 2; /* Trap CASA problem */\n outImage->myDesc->inaxes[jlocf] = nOut;\n outImage->myDesc->crpix[jlocf] = 1.0;\n outImage->myDesc->cdelt[jlocf] = 1.0;\n strncpy (outImage->myDesc->ctype[jlocf], SPECLOGF, IMLEN_KEYWORD);\n outImage->myDesc->bitpix = -32; /* Float it */\n\n /* Creation date today */\n today = ObitToday();\n strncpy (outImage->myDesc->date, today, IMLEN_VALUE);\n if (today) g_free(today);\n\n /* Copy of output descriptor to in */\n in->outDesc = ObitImageDescCopy (outImage->myDesc, in->outDesc, err);\n\n } else { /* On subsequent images check for consistency */\n /* Check size of planes */\n Obit_return_if_fail(((imArr[iplane]->myDesc->inaxes[0]==in->outDesc->inaxes[0]) && \n\t\t\t (imArr[iplane]->myDesc->inaxes[1]==in->outDesc->inaxes[1])), err,\n\t\t\t \"%s: Image planes incompatible %d!= %d or %d!= %d\", \n\t\t\t routine, imArr[iplane]->myDesc->inaxes[0], in->outDesc->inaxes[0], \n\t\t\t imArr[iplane]->myDesc->inaxes[1], in->outDesc->inaxes[1]) ;\n\n /* Check alignment of pixels */\n ipixel[0] = 1.0; ipixel[1] = 1.0;\n bad = !ObitImageDescCvtPixel (imArr[iplane]->myDesc, in->outDesc, ipixel, opixel, err);\n if (err->error) Obit_traceback_msg (err, routine, imArr[iplane]->name);\n Obit_return_if_fail(!bad, err,\n\t\t\t \"%s: Image planes incompatible\", routine);\n Obit_return_if_fail(((fabs(ipixel[0]-opixel[0])<0.01) &&\n\t\t\t (fabs(ipixel[1]-opixel[1])<0.01)), err,\n\t\t\t \"%s: Image pixels not aligned %f!=%f or %f!=%f\", \n\t\t\t routine, ipixel[0], opixel[0], ipixel[1], opixel[1]) ;\n } /* end consistency check */\n \n /* Read plane */\n retCode = ObitImageRead (imArr[iplane], in->inFArrays[iplane]->array, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, imArr[iplane]->name);\n \n /* Get BeamShape */\n antsize = 25.0;\n if (antSize) antsize = antSize[0];\n if (antSize && (ASdim[0]>=in->nfreq)) antsize = antSize[iplane];\n pbmin = 0.05;\n if (PBmin) pbmin = PBmin[0];\n if (PBmin && (PBdim[0]>=in->nfreq)) pbmin = PBmin[iplane];\n doGain = pbmin<0.999;\n in->BeamShapes[iplane] = ObitBeamShapeCreate (\"BS\", imArr[iplane], pbmin, antsize, doGain);\n \n /* Plane RMS */\n in->RMS[iplane] = ObitFArrayRMS(in->inFArrays[iplane]);\n\n /* Frequency */\n in->freqs[iplane] = imArr[iplane]->myDesc->crval[imArr[iplane]->myDesc->jlocf] + \n imArr[iplane]->myDesc->cdelt[imArr[iplane]->myDesc->jlocf] * \n (imArr[iplane]->myDesc->plane - imArr[iplane]->myDesc->crpix[imArr[iplane]->myDesc->jlocf]);\n \n /* Close input */\n retCode = ObitImageClose (imArr[iplane], err);\n imArr[iplane]->extBuffer = FALSE; /* May need I/O buffer later */\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, imArr[iplane]->name);\n } /* end loop over input images */\n\n /* Average Frequency */\n avgFreq = 0.0;\n for (i=0; infreq; i++) avgFreq += in->freqs[i];\n avgFreq /= in->nfreq;\n\n /* Get Reference frequency , default avg. input ref. freq. */\n InfoReal.dbl = avgFreq; type = OBIT_double;\n in->refFreq = InfoReal.dbl;\n ObitInfoListGetTest(in->info, \"refFreq\", &type, dim, &InfoReal);\n if (type==OBIT_float) in->refFreq = InfoReal.flt;\n else if (type==OBIT_double) in->refFreq = (ofloat)InfoReal.dbl;\n \n /* Update output header to reference Frequency */\n outImage->myDesc->crval[outImage->myDesc->jlocf] = in->refFreq;\n in->outDesc->crval[in->outDesc->jlocf] = in->refFreq;\n\n /* Do actual fitting */\n ObitSpectrumFitter (in, err);\n if (err->error) Obit_traceback_msg (err, routine, imArr[0]->name);\n\n /* Write output */\n ObitSpectrumWriteOutput(in, outImage, err);\n if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n} /* end ObitSpectrumFitImArr */\n\n/**\n * Evaluate spectrum at a given frequency\n * \\param in Spectral fitting object\n * \\param inImage Spectral coefficient image\n * Planes 1->nterm are coefficients per pixel\n * Planes nterm+1->2*nterm are uncertainties in coefficients\n * Plane 2*nterm+1 = Chi squared of fit\n * \\param outFreq Output Frequency in Hz\n * \\param outImage Image to write, must be defined but not yet exist.\n * \\param err Obit error stack object.\n */\nvoid ObitSpectrumFitEval (ObitSpectrumFit* in, ObitImage *inImage, \n\t\t\t odouble outFreq, ObitImage *outImage, ObitErr *err)\n{\n olong ix, iy, i, indx, nx, ny, nterm, jlocspec;\n olong naxis[2];\n ObitIOSize IOBy;\n ObitIOCode retCode;\n ObitInfoType type;\n gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n ObitFArray **inArrays=NULL, *outArray=NULL;\n odouble refFreq, arg, aarg, sum;\n gchar *today=NULL, *SPECLOGF = \"SPECLOGF\";\n gchar *routine = \"ObitSpectrumFitEval\";\n\n /* error checks */\n if (err->error) return;\n g_assert (ObitIsA(in, &myClassInfo));\n g_assert(ObitImageIsA(inImage));\n g_assert(ObitImageIsA(outImage));\n\n /* Open input image to get info */\n IOBy = OBIT_IO_byPlane;\n dim[0] = 1;\n ObitInfoListAlwaysPut (inImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n inImage->extBuffer = TRUE; /* Using inFArrays as I/O buffer */\n retCode = ObitImageOpen (inImage, OBIT_IO_ReadOnly, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, inImage->name);\n\n /* Find \"SPECLOGF\" axis */\n jlocspec = -1;\n for (i=0; imyDesc->naxis; i++) {\n if (!strncmp (inImage->myDesc->ctype[i], SPECLOGF, 8)) jlocspec = i;\n }\n Obit_return_if_fail((jlocspec>=0), err, \n\t\t \"%s: No %s axis on %s\", routine, SPECLOGF, inImage->name);\n \n\n /* Reference frequency is on inImage */\n refFreq = inImage->myDesc->crval[jlocspec];\n\n /* Output Image descriptor */\n outImage->myDesc = ObitImageDescCopy (inImage->myDesc, outImage->myDesc, err);\n if (err->error) Obit_traceback_msg (err, routine, inImage->name);\n /* Frequency axis is actually fitted spectrum parameters and errors */\n outImage->myDesc->inaxes[outImage->myDesc->jlocf] = 1;\n outImage->myDesc->crval[outImage->myDesc->jlocf] = outFreq;\n\n /* Creation date today */\n today = ObitToday();\n strncpy (outImage->myDesc->date, today, IMLEN_VALUE);\n if (today) g_free(today);\n outImage->myDesc->bitpix = -32; /* Float it */\n\n /* Determine number of frequency terms and initialize storage arrays \n get nterm from input image descriptor with default number of pixels on\n SPECLOGF\" axis */\n nterm = inImage->myDesc->inaxes[jlocspec];\n ObitInfoListGetTest (outImage->myDesc->info, \"NTERM\", &type, dim, &nterm);\n\n /* Image size */\n nx = inImage->myDesc->inaxes[0];\n ny = inImage->myDesc->inaxes[1];\n naxis[0] = (olong)nx; naxis[1] = (olong)ny; \n for (i=0; iarray, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n } /* end loop over planes */\n\n /* Loop over pixels evaluating spectrum */\n arg = log(outFreq/refFreq);\n /* Loop over pixels in Y */\n indx = -1;\n for (iy=0; iyarray[indx]*aarg;\n\taarg *= arg;\n }\n /* Add value at reference frequency */\n sum = exp(sum) * inArrays[0]->array[indx];\n outArray->array[indx] = sum;\n } /* end loop in X */\n } /* end loop in y */\n\n /* Write output */\n IOBy = OBIT_IO_byPlane;\n dim[0] = 1;\n ObitInfoListAlwaysPut (outImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n inImage->extBuffer = TRUE; /* Using outFArrays as I/O buffer */\n retCode = ObitImageOpen (outImage, OBIT_IO_WriteOnly, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n \n /* Write */\n retCode = ObitImageWrite (outImage, outArray->array, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n /* Close output */\n retCode = ObitImageClose (outImage, err);\n outImage->extBuffer = FALSE; /* May need I/O buffer later */\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) goto cleanup;\n\n /* Cleanup */\n cleanup:\n if (inArrays) {\n for (i=0; ierror) Obit_traceback_msg (err, routine, outImage->name);\n} /* end ObitSpectrumFitEval */\n\n/**\n * Fit single spectrum to flux measurements\n * Without GSL, only the average intensity is determined (no spectrum)\n * \\param nfreq Number of entries in freq, flux, sigma\n * \\param nterm Number of coefficients of powers of log(nu) to fit\n * \\param refFreq Reference frequency (Hz)\n * \\param freq Array of Frequencies (Hz)\n * \\param flux Array of fluxes (Jy) same dim as freq\n * \\param sigma Array of errors (Jy) same dim as freq\n * \\param doBrokePow TRUE if a broken power law fit is desired (3 terms)\n * \\param err Obit error stack object.\n * \\return Array of fitter parameters, errors for each and Chi Squares of fit\n * Initial terms are in Jy, other in log.\n */\nofloat* ObitSpectrumFitSingle (olong nfreq, olong nterm, odouble refFreq, \n\t\t\t odouble *freq, ofloat *flux, ofloat *sigma, \n\t\t\t gboolean doBrokePow, ObitErr *err)\n{\n ofloat *out = NULL;\n olong i, j;\n NLFitArg *arg=NULL;\n gchar *routine = \"ObitSpectrumFitSingle\";\n /* GSL implementation */\n#ifdef HAVE_GSL\n const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n\n if (err->error) return out;\n\n /* Warn if too many terms asked for */\n if (nterm>5) {\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Asked for %d terms, will limit to 5\", routine, nterm);\n }\n\n /* Warn if incorrect number of terms */\n if (doBrokePow && (nterm!=3)) {\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Must have three terms for broken power law, not %d\", \n\t\t routine, nterm);\n }\n\n /* Warn if ref. freq <= 0, set to 1.0e9 */\n if (refFreq<=0.0) {\n refFreq = 1.0e9;\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Setting reference Frequency to 1 GHz\", routine);\n }\n\n /* Create function argument */\n arg = g_malloc(sizeof(NLFitArg));\n arg->in = NULL; /* Not needed here */\n arg->nfreq = nfreq;\n arg->nterm = nterm;\n arg->doError = TRUE;\n arg->doBrokePow = doBrokePow;\n arg->doPBCorr = FALSE;\n arg->corAlpha = 0.0;\n arg->maxIter = 100;\n arg->minDelta = 1.0e-5; /* Min step size */\n arg->maxChiSq = 1.5; /* max acceptable normalized chi squares */\n arg->refFreq = refFreq; /* Reference Frequency */\n arg->weight = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->isigma = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->obs = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->nu = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->logNuOnu0 = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat));\n for (i=0; i0.0) {\n arg->isigma[i] = 1.0 / sigma[i];\n arg->weight[i] = arg->isigma[i]*arg->isigma[i];\n } else {\n arg->isigma[i] = 0.0;\n arg->weight[i] = 0.0;\n }\n arg->obs[i] = flux[i];\n arg->nu[i] = freq[i];\n arg->logNuOnu0[i] = log(freq[i]/refFreq);\n }\n\n /* GSL implementation */\n#ifdef HAVE_GSL\n arg->solver2 = arg->solver3 = arg->solver4 = arg->solver5 = NULL;\n arg->covar2 = arg->covar3 = arg->covar4 = arg->covar5 = NULL;\n arg->work2 = arg->work3 = arg->work4 = arg->work5 = NULL;\n /* Setup solvers */\n T = gsl_multifit_fdfsolver_lmder;\n if (arg->nterm>=2)\n arg->solver2 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 2);\n if (arg->nterm>=3)\n arg->solver3 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 3);\n if (arg->nterm>=4)\n arg->solver4 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 4);\n if (arg->nterm>=5)\n arg->solver5 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 5);\n\n /* Fitting function info */\n arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n if (doBrokePow) {\n arg->funcStruc->f = &SpecFitFuncBP;\n arg->funcStruc->df = &SpecFitJacBP;\n arg->funcStruc->fdf = &SpecFitFuncJacBP;\n } else {\n arg->funcStruc->f = &SpecFitFunc;\n arg->funcStruc->df = &SpecFitJac;\n arg->funcStruc->fdf = &SpecFitFuncJac;\n }\n arg->funcStruc->n = arg->nfreq;\n arg->funcStruc->p = arg->nterm;\n arg->funcStruc->params = arg;\n\n /* Set up work arrays */\n if (arg->nterm>=2) {\n arg->covar2 = gsl_matrix_alloc(2, 2);\n arg->work2 = gsl_vector_alloc(2);\n }\n if (arg->nterm>=3) {\n arg->covar3 = gsl_matrix_alloc(3, 3);\n arg->work3 = gsl_vector_alloc(3);\n }\n if (arg->nterm>=4) {\n arg->covar4 = gsl_matrix_alloc(4, 4);\n arg->work4 = gsl_vector_alloc(4);\n }\n if (arg->nterm>=5) {\n arg->covar5 = gsl_matrix_alloc(5, 5);\n arg->work5 = gsl_vector_alloc(5);\n }\n#endif /* HAVE_GSL */ \n\n /* Fit - poly power or broken power */\n if (arg->doBrokePow) {\n /* Broken power law */\n arg->nterm = 2; /* simple power law */\n arg->funcStruc->f = &SpecFitFunc;\n arg->funcStruc->df = &SpecFitJac;\n arg->funcStruc->fdf = &SpecFitFuncJac;\n NLFit(arg);\n arg->nterm = 3; /* broken power law */\n arg->funcStruc->f = &SpecFitFuncBP;\n arg->funcStruc->df = &SpecFitJacBP;\n arg->funcStruc->fdf = &SpecFitFuncJacBP;\n NLFitBP(arg);\n } else {\n /* multi term power */\n NLFit(arg);\n }\n \n /* get results parameters + errors */\n out = g_malloc0((2*arg->nterm+1)*sizeof(ofloat));\n for (j=0; jcoef[j];\n /* Chi squared */\n out[nterm*2] = arg->ChiSq;\n \n /* Cleanup */\n if (arg->weight) g_free(arg->weight);\n if (arg->isigma) g_free(arg->isigma);\n if (arg->obs) g_free(arg->obs);\n if (arg->nu) g_free(arg->nu);\n if (arg->logNuOnu0) g_free(arg->logNuOnu0);\n if (arg->coef) g_free(arg->coef);\n#ifdef HAVE_GSL\n if (arg->solver2) gsl_multifit_fdfsolver_free (arg->solver2);\n if (arg->solver3) gsl_multifit_fdfsolver_free (arg->solver3);\n if (arg->solver4) gsl_multifit_fdfsolver_free (arg->solver4);\n if (arg->solver5) gsl_multifit_fdfsolver_free (arg->solver5);\n if (arg->work2) gsl_vector_free(arg->work2);\n if (arg->work3) gsl_vector_free(arg->work3);\n if (arg->work4) gsl_vector_free(arg->work4);\n if (arg->work5) gsl_vector_free(arg->work5);\n if (arg->covar2) gsl_matrix_free(arg->covar2);\n if (arg->covar3) gsl_matrix_free(arg->covar3);\n if (arg->covar4) gsl_matrix_free(arg->covar4);\n if (arg->covar5) gsl_matrix_free(arg->covar5);\n if (arg->funcStruc) g_free(arg->funcStruc);\n#endif /* HAVE_GSL */\n g_free(arg);\n\n return out;\n} /* end ObitSpectrumFitSingle */\n\n/**\n * Make single spectrum fitting argument array\n * Without GSL, only the average intensity is determined (no spectrum)\n * \\param nfreq Number of entries in freq, flux, sigma\n * \\param nterm Number of coefficients of powers of log(nu) to fit\n * \\param refFreq Reference frequency (Hz)\n * \\param freq Array of Frequencies (Hz)\n * \\param flux Array of fluxes (Jy) same dim as freq\n * \\param sigma Array of errors (Jy) same dim as freq\n * \\param doBrokePow TRUE if a broken power law fit is desired (3 terms)\n * \\param out Array for output results, should be g_freed when done\n * \\param err Obit error stack object.\n * \\return argument for single spectrum fitting, use ObitSpectrumFitKillArg to dispose.\n */\ngpointer ObitSpectrumFitMakeArg (olong nfreq, olong nterm, odouble refFreq, \n\t\t\t\t odouble *freq, gboolean doBrokePow, \n\t\t\t\t ofloat **out, ObitErr *err)\n{\n olong i;\n NLFitArg *arg=NULL;\n gchar *routine = \"ObitSpectrumFitMakeArg\";\n /* GSL implementation */\n#ifdef HAVE_GSL\n const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n\n if (err->error) return out;\n\n /* Warn if too many terms asked for */\n if (nterm>5) {\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Asked for %d terms, will limit to 5\", routine, nterm);\n }\n\n /* Warn if incorrect number of terms */\n if (doBrokePow && (nterm!=3)) {\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Must have three terms for broken power law, not %d\", \n\t\t routine, nterm);\n }\n\n /* Warn if ref. freq <= 0, set to 1.0e9 */\n if (refFreq<=0.0) {\n refFreq = 1.0e9;\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Setting reference Frequency to 1 GHz\", routine);\n }\n\n /* Create function argument */\n arg = g_malloc(sizeof(NLFitArg));\n arg->in = NULL; /* Not needed here */\n arg->nfreq = nfreq;\n arg->nterm = nterm;\n arg->doError = TRUE;\n arg->doBrokePow = doBrokePow;\n arg->doPBCorr = FALSE;\n arg->corAlpha = 0.0;\n arg->maxIter = 100;\n arg->minDelta = 1.0e-5; /* Min step size */\n arg->maxChiSq = 3.0; /* max acceptable normalized chi squares */\n arg->refFreq = refFreq; /* Reference Frequency */\n arg->weight = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->isigma = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->obs = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->nu = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->logNuOnu0 = g_malloc0(arg->nfreq*sizeof(ofloat));\n arg->coef = g_malloc0(3*arg->nterm*sizeof(ofloat));\n for (i=0; inu[i] = freq[i];\n arg->logNuOnu0[i] = log(freq[i]/refFreq);\n }\n\n /* GSL implementation */\n#ifdef HAVE_GSL\n arg->solver2 = arg->solver3 = arg->solver4 = arg->solver5 = NULL;\n arg->covar2 = arg->covar3 = arg->covar4 = arg->covar5 = NULL;\n arg->work2 = arg->work3 = arg->work4 = arg->work5 = NULL;\n /* Setup solvers */\n T = gsl_multifit_fdfsolver_lmder;\n if (arg->nterm>=2)\n arg->solver2 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 2);\n if (arg->nterm>=3)\n arg->solver3 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 3);\n if (arg->nterm>=4)\n arg->solver4 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 4);\n if (arg->nterm>=5)\n arg->solver5 = gsl_multifit_fdfsolver_alloc(T, arg->nfreq, 5);\n\n /* Fitting function info */\n arg->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n if (doBrokePow) {\n arg->funcStruc->f = &SpecFitFuncBP;\n arg->funcStruc->df = &SpecFitJacBP;\n arg->funcStruc->fdf = &SpecFitFuncJacBP;\n } else {\n arg->funcStruc->f = &SpecFitFunc;\n arg->funcStruc->df = &SpecFitJac;\n arg->funcStruc->fdf = &SpecFitFuncJac;\n }\n arg->funcStruc->n = arg->nfreq;\n arg->funcStruc->p = arg->nterm;\n arg->funcStruc->params = arg;\n\n /* Set up work arrays */\n if (arg->nterm>=2) {\n arg->covar2 = gsl_matrix_alloc(2, 2);\n arg->work2 = gsl_vector_alloc(2);\n }\n if (arg->nterm>=3) {\n arg->covar3 = gsl_matrix_alloc(3, 3);\n arg->work3 = gsl_vector_alloc(3);\n }\n if (arg->nterm>=4) {\n arg->covar4 = gsl_matrix_alloc(4, 4);\n arg->work4 = gsl_vector_alloc(4);\n }\n if (arg->nterm>=5) {\n arg->covar5 = gsl_matrix_alloc(5, 5);\n arg->work5 = gsl_vector_alloc(5);\n }\n#endif /* HAVE_GSL */ \n\n /* output array */\n *out = (ofloat*)g_malloc0((2*arg->nterm+1)*sizeof(ofloat));\n\n return (gpointer)arg;\n} /* end ObitSpectrumFitMakeArg */\n\n/**\n * Fit single spectrum to flux measurements using precomputed argument\n * \\param aarg pointer to argument for fitting\n * \\param flux Array of values to be fitted\n * \\param sigma Array of uncertainties of flux\n * \\param out Result array at least 2*nterms+1 in size.\n * in order, fitted parameters, error estimates, chi sq of fit.\n */\nvoid ObitSpectrumFitSingleArg (gpointer aarg, ofloat *flux, ofloat *sigma,\n\t\t\t ofloat *out)\n{\n olong i, j;\n NLFitArg *arg=(NLFitArg*)aarg;\n ofloat fblank = ObitMagicF();\n gboolean allBad;\n\n /* Save flux array, sigma, Check if all data blanked */\n allBad = TRUE;\n for (i=0; infreq; i++) arg->obs[i] = flux[i];\n for (i=0; infreq; i++) {\n arg->obs[i] = flux[i];\n if (arg->obs[i]!=fblank) allBad = FALSE;\n arg->isigma[i] = 1.0 / sigma[i];\n arg->weight[i] = arg->isigma[i]*arg->isigma[i];\n }\n\n /* Return fblanks/zeroes for no data */\n if (allBad) {\n out[0] = fblank;\n for (j=1; j<=arg->nterm*2; j++) out[j] = 0.0;\n return;\n }\n\n /* Fit - poly power or broken power */\n if (arg->doBrokePow) {\n /* Broken power law */\n arg->nterm = 2; /* simple power law */\n arg->funcStruc->f = &SpecFitFunc;\n arg->funcStruc->df = &SpecFitJac;\n arg->funcStruc->fdf = &SpecFitFuncJac;\n NLFit(arg);\n arg->nterm = 3; /* broken power law */\n arg->funcStruc->f = &SpecFitFuncBP;\n arg->funcStruc->df = &SpecFitJacBP;\n arg->funcStruc->fdf = &SpecFitFuncJacBP;\n NLFitBP(arg);\n } else {\n /* multi term power */\n NLFit(arg);\n }\n \n /* get results parameters + errors */\n for (j=0; jnterm*2; j++) out[j] = arg->coef[j];\n /* Chi squared */\n out[arg->nterm*2] = arg->ChiSq;\n \n return;\n} /* end ObitSpectrumFitSingleArg */\n\n/**\n * Delete single fitting argument\n * \\param aarg pointer to argument to kill\n */\nvoid ObitSpectrumFitKillArg (gpointer aarg)\n{\n NLFitArg *arg= (NLFitArg*)aarg;\n\n if (arg==NULL) return;\n if (arg->weight) g_free(arg->weight);\n if (arg->isigma) g_free(arg->isigma);\n if (arg->obs) g_free(arg->obs);\n if (arg->nu) g_free(arg->nu);\n if (arg->logNuOnu0) g_free(arg->logNuOnu0);\n if (arg->coef) g_free(arg->coef);\n#ifdef HAVE_GSL\n if (arg->solver2) gsl_multifit_fdfsolver_free (arg->solver2);\n if (arg->solver3) gsl_multifit_fdfsolver_free (arg->solver3);\n if (arg->solver4) gsl_multifit_fdfsolver_free (arg->solver4);\n if (arg->solver5) gsl_multifit_fdfsolver_free (arg->solver5);\n if (arg->work2) gsl_vector_free(arg->work2);\n if (arg->work3) gsl_vector_free(arg->work3);\n if (arg->work4) gsl_vector_free(arg->work4);\n if (arg->work5) gsl_vector_free(arg->work5);\n if (arg->covar2) gsl_matrix_free(arg->covar2);\n if (arg->covar3) gsl_matrix_free(arg->covar3);\n if (arg->covar4) gsl_matrix_free(arg->covar4);\n if (arg->covar5) gsl_matrix_free(arg->covar5);\n if (arg->funcStruc) g_free(arg->funcStruc);\n#endif /* HAVE_GSL */\n g_free(arg);\n\n} /* end ObitSpectrumFitKillArg */\n\n/**\n * Initialize global ClassInfo Structure.\n */\nvoid ObitSpectrumFitClassInit (void)\n{\n if (myClassInfo.initialized) return; /* only once */\n \n /* Set name and parent for this class */\n myClassInfo.ClassName = g_strdup(myClassName);\n myClassInfo.ParentClass = ObitParentGetClass();\n\n /* Set function pointers */\n ObitSpectrumFitClassInfoDefFn ((gpointer)&myClassInfo);\n \n myClassInfo.initialized = TRUE; /* Now initialized */\n \n} /* end ObitSpectrumFitClassInit */\n\n/**\n * Initialize global ClassInfo Function pointers.\n */\nstatic void ObitSpectrumFitClassInfoDefFn (gpointer inClass)\n{\n ObitSpectrumFitClassInfo *theClass = (ObitSpectrumFitClassInfo*)inClass;\n ObitClassInfo *ParentClass = (ObitClassInfo*)myClassInfo.ParentClass;\n\n if (theClass->initialized) return; /* only once */\n\n /* Check type of inClass */\n g_assert (ObitInfoIsA(inClass, (ObitClassInfo*)&myClassInfo));\n\n /* Initialize (recursively) parent class first */\n if ((ParentClass!=NULL) && \n (ParentClass->ObitClassInfoDefFn!=NULL))\n ParentClass->ObitClassInfoDefFn(theClass);\n\n /* function pointers defined or overloaded this class */\n theClass->ObitClassInit = (ObitClassInitFP)ObitSpectrumFitClassInit;\n theClass->newObit = (newObitFP)newObitSpectrumFit;\n theClass->ObitClassInfoDefFn = (ObitClassInfoDefFnFP)ObitSpectrumFitClassInfoDefFn;\n theClass->ObitGetClass = (ObitGetClassFP)ObitSpectrumFitGetClass;\n theClass->ObitCopy = (ObitCopyFP)ObitSpectrumFitCopy;\n theClass->ObitClone = NULL;\n theClass->ObitClear = (ObitClearFP)ObitSpectrumFitClear;\n theClass->ObitInit = (ObitInitFP)ObitSpectrumFitInit;\n theClass->ObitSpectrumFitCreate = (ObitSpectrumFitCreateFP)ObitSpectrumFitCreate;\n theClass->ObitSpectrumFitCube = (ObitSpectrumFitCubeFP)ObitSpectrumFitCube;\n theClass->ObitSpectrumFitImArr = (ObitSpectrumFitImArrFP)ObitSpectrumFitImArr;\n theClass->ObitSpectrumFitEval = (ObitSpectrumFitEvalFP)ObitSpectrumFitEval;\n theClass->ObitSpectrumFitSingle = (ObitSpectrumFitSingleFP)ObitSpectrumFitSingle;\n theClass->ObitSpectrumFitter = (ObitSpectrumFitterFP)ObitSpectrumFitter;\n theClass->ObitSpectrumWriteOutput = (ObitSpectrumWriteOutputFP)ObitSpectrumWriteOutput;\n} /* end ObitSpectrumFitClassDefFn */\n\n/*---------------Private functions--------------------------*/\n\n/**\n * Creates empty member objects, initialize reference count.\n * Parent classes portions are (recursively) initialized first\n * \\param inn Pointer to the object to initialize.\n */\nvoid ObitSpectrumFitInit (gpointer inn)\n{\n ObitClassInfo *ParentClass;\n ObitSpectrumFit *in = inn;\n\n /* error checks */\n g_assert (in != NULL);\n\n /* recursively initialize parent class members */\n ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n if ((ParentClass!=NULL) && ( ParentClass->ObitInit!=NULL)) \n ParentClass->ObitInit (inn);\n\n /* set members in this class */\n in->thread = newObitThread();\n in->info = newObitInfoList(); \n in->nterm = 0;\n in->nfreq = 0;\n in->doBrokePow = FALSE;\n in->maxChi2 = 1.5;\n in->minWt = 0.5;\n in->RMS = NULL;\n in->calFract = NULL;\n in->outDesc = NULL;\n in->inFArrays = NULL;\n in->BeamShapes = NULL;\n in->outFArrays = NULL;\n in->freqs = NULL;\n\n} /* end ObitSpectrumFitInit */\n\n/**\n * Deallocates member objects.\n * Does (recursive) deallocation of parent class members.\n * \\param inn Pointer to the object to deallocate.\n * Actually it should be an ObitSpectrumFit* cast to an Obit*.\n */\nvoid ObitSpectrumFitClear (gpointer inn)\n{\n ObitClassInfo *ParentClass;\n ObitSpectrumFit *in = inn;\n olong i, nOut;\n\n /* error checks */\n g_assert (ObitIsA(in, &myClassInfo));\n\n /* delete this class members */\n if (in->RMS) g_free(in->RMS);\n if (in->calFract) g_free(in->calFract);\n in->thread = ObitThreadUnref(in->thread);\n in->info = ObitInfoListUnref(in->info);\n if (in->outDesc) in->outDesc = ObitImageDescUnref(in->outDesc);\n if (in->inFArrays) {\n for (i=0; infreq; i++) in->inFArrays[i] = ObitFArrayUnref(in->inFArrays[i]);\n g_free(in->inFArrays);\n }\n\n if (in->BeamShapes) {\n for (i=0; infreq; i++) in->BeamShapes[i] = ObitBeamShapeUnref(in->BeamShapes[i]);\n g_free(in->BeamShapes);\n }\n\n /* How many output planes */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n\n if (in->outFArrays) {\n for (i=0; ioutFArrays[i] = ObitFArrayUnref(in->outFArrays[i]);\n g_free(in->outFArrays);\n }\n if (in->freqs) g_free(in->freqs);\n\n /* unlink parent class members */\n ParentClass = (ObitClassInfo*)(myClassInfo.ParentClass);\n /* delete parent class members */\n if ((ParentClass!=NULL) && ( ParentClass->ObitClear!=NULL)) \n ParentClass->ObitClear (inn);\n \n} /* end ObitSpectrumFitClear */\n\n/**\n * Does spectral fitting, input and output on input object\n * Work divided up amoung 1 or more threads\n * In each pixel determines weighted average and RMS and if the SNR\n * exceeds maxChi2 then the spectrum is fitted. \n * The pixel value at the reference frequency is either the average pixel \n * if the SNR is too low or 10^(first term) of fit.\n * The results are stored in outFArrays:\n * \\li first entry is the pixel value (Jy/bm) at the reference freq\n * \\li entries 1->nterm-1 are the coefficients of log(freq/refFreq)^n\n * possibly magic value blanked for pixels with no signal\n * \\li outFArrays[nterm] = RMS estimate for pixel values (Jy/bm) at refFreq\n * \\li entries nterm+1->nterm*2 RMS uncertainties on higher order coefficients\n * \\li entry 1+nterm*2 = the Chi squared of the fit\n *\n * \\param in SpectrumFit to fit\n * \\param err Obit error stack object.\n */\nvoid ObitSpectrumFitter (ObitSpectrumFit* in, ObitErr *err)\n{\n olong i, loy, hiy, nyPerThread, nThreads;\n gboolean OK;\n NLFitArg **threadArgs;\n NLFitArg *args=NULL;\n ObitThreadFunc func=(ObitThreadFunc)ThreadNLFit;\n gchar *routine = \"ObitSpectrumFitter\";\n /* GSL implementation */\n#ifdef HAVE_GSL\n const gsl_multifit_fdfsolver_type *T=NULL;\n#endif /* HAVE_GSL */ \n\n /* error checks */\n if (err->error) return;\n\n /* Warn if too many terms asked for */\n if (in->nterm>5) {\n Obit_log_error(err, OBIT_InfoWarn, \n\t\t \"%s: Asked for %d terms, will limit to 5\", routine, in->nterm);\n }\n\n /* How many threads to use? */\n nThreads = MAX (1, ObitThreadNumProc(in->thread));\n\n /* Initialize threadArg array */\n threadArgs = g_malloc0(nThreads*sizeof(NLFitArg*));\n for (i=0; iin = in;\n args->err = err;\n args->nfreq = in->nfreq;\n args->nterm = in->nterm;\n args->doError = in->doError;\n args->doBrokePow = in->doBrokePow;\n args->doPBCorr = in->doPBCorr;\n args->corAlpha = in->corAlpha;\n args->minWt = in->minWt;\n args->maxIter = 100;\n args->minDelta = 1.0e-2; /* Min step size */\n args->maxChiSq = in->maxChi2; /* max acceptable normalized chi squares */\n args->weight = g_malloc0(args->nfreq*sizeof(ofloat));\n args->isigma = g_malloc0(args->nfreq*sizeof(ofloat));\n args->obs = g_malloc0(args->nfreq*sizeof(ofloat));\n args->nu = g_malloc0(args->nfreq*sizeof(ofloat));\n args->logNuOnu0 = g_malloc0(args->nfreq*sizeof(ofloat));\n if (args->doError)\n args->coef = g_malloc0(2*args->nterm*sizeof(ofloat));\n else\n args->coef = g_malloc0(args->nterm*sizeof(ofloat));\n /* GSL implementation */\n#ifdef HAVE_GSL\n args->solver2 = args->solver3 = args->solver4 = args->solver5 = NULL;\n args->covar2 = args->covar3 = args->covar4 = args->covar5 = NULL;\n args->work2 = args->work3 = args->work4 = args->work5 = NULL;\n /* Setup solvers */\n T = gsl_multifit_fdfsolver_lmder;\n if (args->nterm>=2)\n args->solver2 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 2);\n if (args->nterm>=3)\n args->solver3 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 3);\n if (args->nterm>=4)\n args->solver4 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 4);\n if (args->nterm>=5)\n args->solver5 = gsl_multifit_fdfsolver_alloc(T, args->nfreq, 5);\n \n /* Fitting function info */\n args->funcStruc = g_malloc0(sizeof(gsl_multifit_function_fdf));\n if (in->doBrokePow) {\n args->funcStruc->f = &SpecFitFuncBP;\n args->funcStruc->df = &SpecFitJacBP;\n args->funcStruc->fdf = &SpecFitFuncJacBP;\n } else {\n args->funcStruc->f = &SpecFitFunc;\n args->funcStruc->df = &SpecFitJac;\n args->funcStruc->fdf = &SpecFitFuncJac;\n }\n args->funcStruc->n = args->nfreq;\n args->funcStruc->p = args->nterm;\n args->funcStruc->params = args;\n \n /* Set up work arrays */\n if (args->nterm>=2) {\n args->covar2 = gsl_matrix_alloc(2, 2);\n args->work2 = gsl_vector_alloc(2);\n }\n if (args->nterm>=3) {\n args->covar3 = gsl_matrix_alloc(3, 3);\n args->work3 = gsl_vector_alloc(3);\n }\n if (args->nterm>=4) {\n args->covar4 = gsl_matrix_alloc(4, 4);\n args->work4 = gsl_vector_alloc(4);\n }\n if (args->nterm>=5) {\n args->covar5 = gsl_matrix_alloc(5, 5);\n args->work5 = gsl_vector_alloc(5);\n }\n#endif /* HAVE_GSL */ \n }\n /* end initialize */\n \n /* Divide up work */\n nyPerThread = in->ny/nThreads;\n loy = 1;\n hiy = nyPerThread;\n hiy = MIN (hiy, in->ny);\n \n /* Set up thread arguments */\n for (i=0; iny; /* Make sure do all */\n args = (NLFitArg*)threadArgs[i];\n args->first = loy;\n args->last = hiy;\n if (nThreads>1) args->ithread = i;\n else args->ithread = -1;\n /* Update which y */\n loy += nyPerThread;\n hiy += nyPerThread;\n hiy = MIN (hiy, in->ny);\n }\n \n /* Do operation possibly with threads */\n OK = ObitThreadIterator (in->thread, nThreads, func, (gpointer)threadArgs);\n \n /* Check for problems */\n if (!OK) {\n Obit_log_error(err, OBIT_Error,\"%s: Problem in threading\", routine);\n }\n\n /* Shut down any threading */\n ObitThreadPoolFree (in->thread);\n if (threadArgs) {\n for (i=0; iweight) g_free(args->weight);\n if (args->isigma) g_free(args->isigma);\n if (args->obs) g_free(args->obs);\n if (args->nu) g_free(args->nu);\n if (args->logNuOnu0) g_free(args->logNuOnu0);\n if (args->coef) g_free(args->coef);\n#ifdef HAVE_GSL\n if (args->solver2) gsl_multifit_fdfsolver_free (args->solver2);\n if (args->solver3) gsl_multifit_fdfsolver_free (args->solver3);\n if (args->solver4) gsl_multifit_fdfsolver_free (args->solver3);\n if (args->solver4) gsl_multifit_fdfsolver_free (args->solver3);\n if (args->work2) gsl_vector_free(args->work2);\n if (args->work3) gsl_vector_free(args->work3);\n if (args->work4) gsl_vector_free(args->work4);\n if (args->work5) gsl_vector_free(args->work5);\n if (args->covar2) gsl_matrix_free(args->covar2);\n if (args->covar3) gsl_matrix_free(args->covar3);\n if (args->covar4) gsl_matrix_free(args->covar4);\n if (args->covar5) gsl_matrix_free(args->covar5);\n if (args->funcStruc) g_free(args->funcStruc);\n#endif /* HAVE_GSL */\n g_free(threadArgs[i]);\n }\n g_free(threadArgs);\n }\n\n} /* end ObitSpectrumFitter */\n\n/**\n * Write contents on in to outImage\n * \\param in Spectral fitting object\n * \\param outImage Image cube with fitted spectra.\n * Should be defined but not created.\n * Planes 1->nterm are coefficients per pixel\n * Planes nterm+1->2*nterm are uncertainties in coefficients\n * \\param err Obit error stack object.\n */\nvoid ObitSpectrumWriteOutput (ObitSpectrumFit* in, ObitImage *outImage, \n\t\t\t ObitErr *err)\n{\n olong iplane, nOut;\n ObitIOSize IOBy;\n olong i, blc[IM_MAXDIM], trc[IM_MAXDIM];\n ObitIOCode retCode;\n gint32 dim[MAXINFOELEMDIM] = {1,1,1,1,1};\n gchar *routine = \"ObitSpectrumWriteOutput\";\n\n /* error checks */\n if (err->error) return;\n g_assert (ObitIsA(in, &myClassInfo));\n g_assert(ObitImageIsA(outImage));\n\n /* Open output- all, by plane */\n dim[0] = IM_MAXDIM;\n for (i=0; iinfo, \"BLC\", OBIT_long, dim, blc, err); \n ObitInfoListPut (outImage->info, \"TRC\", OBIT_long, dim, trc, err); \n IOBy = OBIT_IO_byPlane;\n dim[0] = 1;\n ObitInfoListAlwaysPut (outImage->info, \"IOBy\", OBIT_long, dim, &IOBy);\n outImage->extBuffer = TRUE; /* Using outFArrays as I/O buffer */\n retCode = ObitImageOpen (outImage, OBIT_IO_ReadWrite, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, outImage->name);\n\n /* save descriptive material */\n ObitImageDescCopyDesc (in->outDesc, outImage->myDesc, err);\n if (err->error) Obit_traceback_msg (err, routine, outImage->name);\n\n /* How many output planes? */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n\n /* Loop writing planes */\n for (iplane=0; iplaneoutFArrays[iplane]->array, err);\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) Obit_traceback_msg (err, routine, outImage->name);\n\n } /* end loop writing planes */\n\n /* Save nterms on output descriptor */\n dim[0] = dim[1] = dim[2] = 1;\n ObitInfoListAlwaysPut (outImage->myDesc->info, \"NTERM\", OBIT_long, dim, &in->nterm);\n ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, \"NTERM\", \n OBIT_long, dim, &in->nterm);\n\n /* If doBrokePow set \"BROKENPO\" to TRUE on output descriptor */\n if (in->doBrokePow) {\n dim[0] = dim[1] = dim[2] = 1;\n ObitInfoListAlwaysPut (outImage->myDesc->info, \"BROKENPO\", OBIT_bool, dim, &in->doBrokePow);\n ObitInfoListAlwaysPut (((ObitImageDesc*)outImage->myIO->myDesc)->info, \"BROKENPO\", \n\t\t\t OBIT_bool, dim, &in->doBrokePow);\n }\n\n /* Close output */\n retCode = ObitImageClose (outImage, err);\n outImage->extBuffer = FALSE; /* May need I/O buffer later */\n /* if it didn't work bail out */\n if ((retCode!=OBIT_IO_OK) || (err->error)) \n Obit_traceback_msg (err, routine, outImage->name);\n\n} /* end ObitSpectrumWriteOutput */\n\n/**\n * Thread function to fit a portion of the image set\n * \\param arg NLFitArg structure\n */\nstatic gpointer ThreadNLFit (gpointer arg)\n{\n NLFitArg *larg = (NLFitArg*)arg;\n ObitSpectrumFit* in = (ObitSpectrumFit*)larg->in;\n olong lo = larg->first-1; /* First in y range */\n olong hi = larg->last; /* Highest in y range */\n gboolean doError = larg->doError; /* Error analysis? */\n gboolean doPBCorr = larg->doPBCorr; /* Primary beam correction? */\n ofloat corAlpha = larg->corAlpha;\n ofloat *Freq = larg->nu;\n ObitErr *err = larg->err;\n\n olong ix, iy, indx, i, nOut;\n odouble Angle=0.0, pos[2];\n ofloat pbfact, spFact, pixel[2];\n ofloat fblank = ObitMagicF();\n ObitBeamShapeClassInfo *BSClass;\n ofloat sumWt, allWt;\n gchar *routine = \"ThreadNLFit\";\n\n /* error checks */\n if (err->error) return NULL;\n g_assert (ObitIsA(in, &myClassInfo));\n\n /* Set up frequency info */\n larg->refFreq = in->refFreq;\n for (i=0; infreq; i++) {\n larg->logNuOnu0[i] = log(in->freqs[i]/in->refFreq);\n larg->nu[i] = in->freqs[i];\n }\n\n /* How many output planes */\n if (in->doError) nOut = 1+in->nterm*2;\n else nOut = in->nterm;\n\n /* Get maximum possible weight */\n allWt = 0.0;\n for (i=0; infreq; i++) {\n if (in->RMS[i]>0.0) {\n allWt += 1.0 / (in->RMS[i]*in->RMS[i]);\n }\n }\n\n /* Loop over pixels in Y */\n indx = lo*in->nx -1; /* Offset in pixel arrays */\n for (iy=lo; iynx; ix++) {\n indx ++;\n\n /* Primary beam correction? */\n if (doPBCorr) {\n\t/* Distance from Center */\n\tpixel[0] = (ofloat)(ix+1.0); pixel[1] = (ofloat)(iy+1.0);\n\tObitImageDescGetPos(in->outDesc, pixel, pos, err);\n\tif (err->error) {\n\t ObitThreadLock(in->thread); /* Lock against other threads */\n\t Obit_log_error(err, OBIT_Error,\"%s Error with position %s\",\n\t\t\t routine, in->name);\n\t ObitThreadUnlock(in->thread); \n\t return NULL;\n\t}\n\tBSClass = (ObitBeamShapeClassInfo*)(in->BeamShapes[0]->ClassInfo);\n\tAngle = BSClass->ObitBeamShapeAngle(in->BeamShapes[0], pos[0], pos[1], 0.0);\n }\n\n /* Collect values; */\n sumWt = 0.0;\n for (i=0; infreq; i++) {\n\tlarg->obs[i] = in->inFArrays[i]->array[indx];\n\t if (larg->obs[i]!=fblank) {\n\t /* Statistical weight */\n\t if (in->RMS[i]>0.0) {\n\t larg->isigma[i] = 1.0 / (in->RMS[i]*in->RMS[i] + \n\t\t\t\t in->calFract[i]*in->calFract[i]*\n\t\t\t\t larg->obs[i]*larg->obs[i]);\n\t larg->weight[i] = larg->isigma[i];\n\t larg->isigma[i] = sqrt(larg->isigma[i]);\n\t } else {\n\t larg->weight[i] = 0.0;\n\t larg->isigma[i] = 0.0;\n\t }\n\t /* Primary beam correction */\n\t if (doPBCorr) {\n\t BSClass = (ObitBeamShapeClassInfo*)(in->BeamShapes[i]->ClassInfo);\n\t pbfact = BSClass->ObitBeamShapeGainSym(in->BeamShapes[i], Angle);\n\t if ((pbfact==fblank) ||(pbfact<1.001*in->BeamShapes[i]->pbmin)) {\n\t\tlarg->obs[i] = fblank;\n\t\tlarg->weight[i] = 0.0;\n\t } else {\n\t\tlarg->obs[i] /= pbfact;\n\t\tlarg->weight[i] *= pbfact*pbfact;\n\t\tsumWt += 1.0 / (in->RMS[i]*in->RMS[i]);\n\t }\n\t }\n\t /* End if datum valid */\n\t } else { /* invalid pixel */\n\t larg->weight[i] = 0.0;\n\t larg->isigma[i] = 0.0;\n\t }\n } /* end loop over frequencies */\n\n /* Enough data to bother with? */\n if (sumWtminWt*allWt) {\n\t/* Save to output */\n\tif (doError) {\n\t for (i=0; ioutFArrays[i]->array[indx] = fblank;\n\t in->outFArrays[nOut-1]->array[indx] = 0.0;\n\t} else { /* only values */\n\t for (i=0; interm; i++) \n\t in->outFArrays[i]->array[indx] = fblank;\n\t}\n\tcontinue; /* Done with pixel */\n }\n\t \n \n /* Spectral index correction */\n if (corAlpha!=0.0) {\n\tfor (i=0; infreq; i++) {\n\t spFact = (ofloat)pow(Freq[i]/in->refFreq, -corAlpha);\n\t larg->obs[i] *= spFact;\n\t larg->weight[i] /= spFact*spFact;\n\t larg->isigma[i] /= spFact;\n\t}\n }\n\n /* initialize with values from last time */\n if (doError) {\n\tfor (i=0; icoef[i] = in->outFArrays[i]->array[indx];\n\tlarg->ChiSq = 0.0;\n } else { /* only values */\n \tfor (i=0; interm; i++) \n\t larg->coef[i] = in->outFArrays[i]->array[indx];\n }\n /* Fit - poly power or broken power */\n if (larg->doBrokePow) {\n\t/* Broken power law */\n\tin->nterm = 2; /* simple power law */\n\tlarg->funcStruc->f = &SpecFitFunc;\n\tlarg->funcStruc->df = &SpecFitJac;\n\tlarg->funcStruc->fdf = &SpecFitFuncJac;\n\tNLFit(larg);\n\tin->nterm = 3; /* broken power law */\n\tlarg->funcStruc->f = &SpecFitFuncBP;\n\tlarg->funcStruc->df = &SpecFitJacBP;\n\tlarg->funcStruc->fdf = &SpecFitFuncJacBP;\n\tNLFitBP(larg);\n } else {\n\t/* multi term power */\n \tNLFit(larg);\n }\n\n /* Spectral index correction */\n if (nOut>=1) larg->coef[1] += corAlpha;\n \n /* Save to output */\n if (doError) {\n\tfor (i=0; ioutFArrays[i]->array[indx] = larg->coef[i];\n\tin->outFArrays[nOut-1]->array[indx] = larg->ChiSq;\n } else { /* only values */\n \tfor (i=0; interm; i++) \n\t in->outFArrays[i]->array[indx] = larg->coef[i];\n }\n\n } /* end x loop */\n } /* end y loop */\n\n /* Indicate completion */\n if (larg->ithread>=0)\n ObitThreadPoolDone (in->thread, (gpointer)&larg->ithread);\n\n return NULL;\n} /* end ThreadNLFit */\n\n/**\n * Do non linear fit to a spectrum\n * Only fits for up to 5 terms\n * \\param arg NLFitArg structure\n * fitted parameters returned in arg->in->coef\n */\nstatic void NLFit (NLFitArg *arg)\n{\n olong iter=0, i, nterm=arg->nterm, nvalid, best;\n ofloat avg, delta, chi2Test, sigma, fblank = ObitMagicF();\n ofloat meanSNR, SNRperTerm=1.0;\n odouble sum, sumwt, sum2;\n gboolean isDone;\n int status;\n#ifdef HAVE_GSL\n gsl_multifit_fdfsolver *solver=NULL;\n gsl_matrix *covar=NULL;\n gsl_vector *work=NULL;\n gsl_matrix *J;\n#endif /* HAVE_GSL */ \n \n /* Initialize output */\n if (arg->doError) \n for (i=0; i<2*arg->nterm; i++) arg->coef[i] = 0.0;\n else\n for (i=0; interm; i++) arg->coef[i] = 0.0;\n \n /* determine weighted average, count valid data */\n sum = sumwt = 0.0;\n nvalid = 0;\n for (i=0; infreq; i++) {\n if ((arg->obs[i]!=fblank) && (arg->weight[i]>0.0)) {\n sum += arg->weight[i] * arg->obs[i];\n sumwt += arg->weight[i];\n nvalid++;\n }\n }\n if (nvalid<=0) return; /* any good data? */\n avg = sum/sumwt;\n\n /* Estimate of noise */\n sigma = 1.0 / sqrt(sumwt);\n\n /* Initial fit */\n arg->coef[0] = avg;\n best = 1; /* best fit number of terms */\n if (nvalid==1) return; /* Only one? */\n \n /* determine chi squared, mean SNR */\n sum = sum2 = sumwt = 0.0;\n for (i=0; infreq; i++) {\n if ((arg->obs[i]!=fblank) && (arg->weight[i]>0.0)) {\n delta = (arg->obs[i]-avg);\n sumwt += arg->weight[i] * delta*delta;\n sum += delta*delta;\n sum2 += fabs(arg->obs[i])*sqrt(arg->weight[i]);\n }\n }\n\n /* normalized Chi squares */\n if (nvalid>1) {\n arg->ChiSq = sumwt/(nvalid-1);\n meanSNR = sum2/nvalid; /* mean SNR */\n } else {\n arg->ChiSq = -1.0;\n meanSNR = 0.0; /* Only one value - don't need mean SNR */\n }\n\n /* Errors wanted? */\n if (arg->doError) {\n arg->coef[2] = sigma; /* Flux error */\n arg->coef[2*arg->nterm] = sum/nvalid;\n }\n\n /* Is this good enough? */\n isDone = (arg->ChiSq<0.0) || (arg->ChiSq<=arg->maxChiSq);\n //if (meanSNR>(SNRperTerm*3.0)) isDone = FALSE; /* Always try for high SNR */\n if (meanSNR>SNRperTerm) isDone = FALSE; /*Always try for high SNR */\n if (isDone) goto done;\n\n /* Higher order terms do nonlinear least-squares fit */\n nterm = 2;\n while ((nterm<=MIN(5,arg->nterm)) && (nterm<=nvalid)) {\n arg->fitTerm = nterm; /* How many actually being fitted */\n#ifdef HAVE_GSL\n\n /* Set solver and covar */\n if (nterm==2) {\n solver = arg->solver2;\n covar = arg->covar2;\n work = arg->work2;\n } else if (nterm==3) {\n solver = arg->solver3;\n covar = arg->covar3;\n work = arg->work3;\n } else if (nterm==4) {\n solver = arg->solver4;\n covar = arg->covar4;\n work = arg->work4;\n } else if (nterm==5) {\n solver = arg->solver5;\n covar = arg->covar5;\n work = arg->work5;\n } \n \n /* set initial guess - start with lower order fit */\n for (i=0; icoef[i]);\n arg->funcStruc->n = arg->nfreq;\n arg->funcStruc->p = nterm;\n arg->funcStruc->params = arg;\n gsl_multifit_fdfsolver_set (solver, arg->funcStruc, work);\n iter = 0;\n \n /* iteration loop */\n do {\n iter++;\n status = gsl_multifit_fdfsolver_iterate(solver);\n /*if (status) break;???*/\n\n status = gsl_multifit_test_delta (solver->dx, solver->x, \n\t\t\t\t\t(double)arg->minDelta, \n\t\t\t\t\t(double)arg->minDelta);\n } while ((status==GSL_CONTINUE) && (itermaxIter));\n\n /* If it didn't work - bail */\n if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) {\n fprintf (stderr, \"Failed, status = %s\\n\", gsl_strerror(status));\n return;\n }\n \n J = gsl_matrix_alloc(nterm, nterm);\n\n /* normalized Chi squares */\n if (nvalid>nterm) {\n sumwt = (ofloat)gsl_blas_dnrm2(solver->f);\n chi2Test = (sumwt*sumwt)/(nvalid-nterm);\n } else chi2Test = -1.0;\n\n /* Did it significantly improve over lower order? */\n //if (chi2Test<0.9*arg->ChiSq) { \n if (chi2Test<1.5*arg->ChiSq) { /* Not much worse */\n best = nterm;\n arg->ChiSq = chi2Test;\n\n /* Get fitted values */\n for (i=0; icoef[i] = (ofloat)gsl_vector_get(solver->x, i);\n \n /* Errors wanted? */\n if (arg->doError) {\n#ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC\n\tgsl_multifit_fdfsolver_jac(solver, J);\n#else\n\tgsl_matrix_memcpy(J, solver->J);\n#endif\n\tgsl_multifit_covar (J, 0.0, covar);\n\tfor (i=0; icoef[arg->nterm+i] = sqrt(gsl_matrix_get(covar, i, i));\n\t /* Clip to sanity range */\n\t arg->coef[arg->nterm+i] = MAX (-1.0e5, MIN (1.0e5, arg->coef[arg->nterm+i]));\n\t}\n } /* end of get errors */\n \n /* Sanity check on spectral parameters [-3,3]\n\t for (i=1; icoef[i] = MAX(-3.0, MIN(3.0,arg->coef[i])); */\n \n } /* End if better than lower order */\n\n gsl_matrix_free(J);\n\n /* Is this good enough? */\n isDone = (arg->ChiSq<0.0) || (arg->ChiSq<=arg->maxChiSq) || (chi2Test>arg->ChiSq);\n if ((meanSNR>(SNRperTerm*nterm)) && (ntermnterm)) \n isDone = FALSE; /* Always try for high SNR */\n if (isDone) goto done;\n /* if ((arg->ChiSq>0.0) && (arg->ChiSq<=arg->maxChiSq)) goto done;*/\n\n nterm++; /* next term */\n } /* end loop over adding terms */\n#endif /* HAVE_GSL */ \n done:\n if (best==1) arg->coef[0] = avg; /* Only fitted one term? */\n /* sanity check, if flux < sigma, don't include higher order terms */\n if (fabs(arg->coef[0])coef[0] = avg;\n for (i=1; interm; i++) arg->coef[i] = 0.0; \n }\n /* Gonzo higher order fit */\n if ((fabs(arg->coef[1])>3.0) || ((nterm>2) && (fabs(arg->coef[2])>2.0))) {\n arg->coef[0] = avg;\n for (i=1; interm; i++) arg->coef[i] = 0.0; \n }\n\n} /* end NLFit */\n\n/**\n * Do non linear fit to a broken power law spectrum\n * Only fits 3 terms\n * Broken power law version, above nv_b the spectrum steepens by half\n * Parameters:\n * S_0 = Flux density at frequency nu_0\n * alpha = spectral index\n * nu_b = Break frequency\n * When called the S_O and the alpha terms should have been estimated\n * (call to NLFit with 2 terms); the initial break frequency is set to \n * the reference frequency. \n * \\param arg NLFitArg structure\n * fitted parameters returned in arg->in->coef\n */\nstatic void NLFitBP (NLFitArg *arg)\n{\n olong iter=0, i, nterm, nvalid;\n ofloat chi2Test, sigma, fblank = ObitMagicF();\n odouble sum, sumwt;\n int status;\n#ifdef HAVE_GSL\n gsl_multifit_fdfsolver *solver;\n gsl_matrix *covar;\n gsl_vector *work;\n gsl_matrix *J;\n#endif /* HAVE_GSL */ \n \n /* determine weighted average, count valid data */\n sum = sumwt = 0.0;\n nvalid = 0;\n for (i=0; infreq; i++) {\n if ((arg->obs[i]!=fblank) && (arg->weight[i]>0.0)) {\n sum += arg->weight[i] * arg->obs[i];\n sumwt += arg->weight[i];\n nvalid++;\n }\n }\n if (nvalid<=(arg->nterm)) return; /* enough good data? */\n /*avg = sum/sumwt;*/\n \n /* Estimate of noise */\n sigma = 1.0 / sqrt(sumwt);\n\n /* Do nonlinear least-squares fit */\n nterm = 3;\n arg->fitTerm = nterm; /* How many actually being fitted */\n#ifdef HAVE_GSL\n\n /* Set solver and covar */\n solver = arg->solver3;\n covar = arg->covar3;\n work = arg->work3;\n \n /* set initial guess - start with lower order fit */\n /* Initial break frequency is reference freq */\n arg->coef[2] = arg->refFreq;\n for (i=0; icoef[i]);\n arg->funcStruc->n = arg->nfreq;\n arg->funcStruc->p = nterm;\n arg->funcStruc->params = arg;\n gsl_multifit_fdfsolver_set (solver, arg->funcStruc, work);\n iter = 0;\n \n /* iteration loop */\n do {\n iter++;\n status = gsl_multifit_fdfsolver_iterate(solver);\n /*if (status) break;???*/\n \n status = gsl_multifit_test_delta (solver->dx, solver->x, \n\t\t\t\t (double)arg->minDelta, \n\t\t\t\t (double)arg->minDelta);\n } while ((status==GSL_CONTINUE) && (itermaxIter));\n \n /* If it didn't work - bail */\n if ((status!=GSL_SUCCESS) && (status!=GSL_CONTINUE)) {\n fprintf (stderr, \"Failed, status = %s\\n\", gsl_strerror(status));\n return;\n }\n \n /* normalized Chi squares */\n if (nvalid>nterm) {\n sumwt = (ofloat)gsl_blas_dnrm2(solver->f);\n chi2Test = (sumwt*sumwt)/(nvalid-nterm);\n } else chi2Test = -1.0;\n\n /* Is this better than a simple power law? */\n /*if (chi2TestChiSq) {*/\n arg->ChiSq = chi2Test;\n \n /* Get fitted values */\n for (i=0; icoef[i] = (ofloat)gsl_vector_get(solver->x, i);\n \n /* DEBUG \n if (arg->coef[0]>50.0*sigma) {\n fprintf (stdout, \"DEBUG %f %f %f \\n\",arg->coef[0], arg->coef[1], arg->coef[2]);\n }*/\n \n /* Errors wanted? */\n if (arg->doError) {\n J = gsl_matrix_alloc(nterm, nterm);\n#ifdef HAVE_GSL_MULTIFIT_FDFSOLVER_JAC\n gsl_multifit_fdfsolver_jac(solver, J);\n#else\n gsl_matrix_memcpy(J, solver->J);\n#endif\n gsl_multifit_covar (J, 0.0, covar);\n for (i=0; icoef[arg->nterm+i] = sqrt(gsl_matrix_get(covar, i, i));\n /* Clip to sanity range\n arg->coef[arg->nterm+i] = MAX (-1.0e5, MIN (1.0e5, arg->coef[arg->nterm+i])); */\n }\n gsl_matrix_free(J);\n } /* end of get errors */\n \n \n /* Sanity check on spectral parameters [-3,3]\n for (i=1; icoef[i] = MAX(-3.0, MIN(3.0,arg->coef[i])); */\n /* End if better than simple power law */\n /*} else {*/\n /* Worse, use simple power law Make break very high */\n /* arg->coef[2] = 1.0e20;*/\n /*}*/\n \n#endif /* HAVE_GSL */ \n /* sanity check, if flux < sigma, don't include higher order terms */\n if (fabs(arg->coef[0])nterm; i++) arg->coef[i] = 0.0; \n\n /* Gonzo higher order fit \n if ((fabs(arg->coef[1])>3.0) || (arg->coef[2]>arg->nu[arg->nfreq-1])) {\n arg->coef[0] = avg;\n for (i=1; interm; i++) arg->coef[i] = 0.0; \n }*/\n\n} /* end NLFitBP */\n\n#ifdef HAVE_GSL\n/**\n * Function evaluator for spectral fitting solver\n * Evaluates (model-observed) / sigma\n * \\param x Vector of parameters to be fitted\n * Flux,array_of spectral_terms\n * \\param param Function parameter structure (NLFitArg)\n * \\param f Vector of (model-obs)/sigma for data points\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int SpecFitFunc (const gsl_vector *x, void *params, \n\t\t\tgsl_vector *f)\n{\n NLFitArg *args = (NLFitArg*)params;\n ofloat fblank = ObitMagicF();\n double flux, spec[10], func;\n odouble model, arg, argx, isigma, spect;\n size_t i, j;\n\n /* get model parameters */\n flux = gsl_vector_get(x, 0);\n for (j=1; jfitTerm; j++) spec[j-1] = gsl_vector_get(x, j);\n\n /* Loop over spectral points */\n for (i=0; infreq; i++) {\n if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {\n isigma = args->isigma[i];\n arg = 0.0;\n argx = args->logNuOnu0[i];\n for (j=1; jfitTerm; j++) {\n\targ += spec[j-1]*argx;\n\targx *= args->logNuOnu0[i];\n }\n spect = exp(arg);\n model = flux * spect;\n func = (model - args->obs[i]) * isigma;\n gsl_vector_set(f, i, func); /* Save function residual */\n } else { /* Invalid data */\n func = 0.0;\n gsl_vector_set(f, i, func); /* Save function residual */\n }\n } /* End loop over spectral points */\n\n return GSL_SUCCESS;\n} /* end SpecFitFunc */\n\n/**\n * Jacobian evaluator for spectral fitting solver\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x Vector of parameters to be fitted\n * Flux,array_of spectral_terms\n * \\param param Function parameter structure (NLFitArg)\n * \\param J Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int SpecFitJac (const gsl_vector *x, void *params, \n\t\t gsl_matrix *J)\n{\n NLFitArg *args = (NLFitArg*)params;\n ofloat fblank = ObitMagicF();\n double flux, spec[10], jac;\n odouble model, arg, argx, isigma, spect;\n size_t i, j;\n\n /* get model parameters */\n flux = gsl_vector_get(x, 0);\n for (j=1; jfitTerm; j++) spec[j-1] = gsl_vector_get(x, j);\n\n /* Loop over spectral points */\n for (i=0; infreq; i++) {\n if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {\n isigma = args->isigma[i];\n arg = 0.0;\n argx = args->logNuOnu0[i];\n for (j=1; jfitTerm; j++) {\n\targ += spec[j-1]*argx;\n\targx *= args->logNuOnu0[i];\n }\n spect = exp(arg);\n model = flux * spect;\n /* Jacobian terms - first flux */\n jac = spect * isigma;\n gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n argx = args->logNuOnu0[i];\n for (j=1; jfitTerm; j++) {\n\tjac = model * isigma * argx;\n\tgsl_matrix_set(J, i, j, jac); /* Save Jacobian */\n \targx *= args->logNuOnu0[i];\n }\n } else { /* Invalid data */\n jac = 0.0;\n gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n for (j=1; jfitTerm; j++) {\n\tgsl_matrix_set(J, i, j, jac); /* Save Jacobian */\n }\n }\n } /* End loop over spectral points */\n\n return GSL_SUCCESS;\n} /* end SpecFitJac */\n\n/**\n * Function and Jacobian evaluator for spectral fitting solver\n * Function = (model-observed) / sigma\n * Jacobian = partial derivatives of model wrt each parameter\n * \\param x Vector of parameters to be fitted\n * Flux,array_of spectral_terms\n * \\param param Function parameter structure (NLFitArg)\n * \\param f Vector of (model-obs)/sigma for data points\n * \\param J Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int SpecFitFuncJac (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f, gsl_matrix *J)\n{\n NLFitArg *args = (NLFitArg*)params;\n ofloat fblank = ObitMagicF();\n double flux, spec[10], func, jac;\n odouble model, arg, argx, isigma, spect;\n size_t i, j;\n\n /* get model parameters */\n flux = gsl_vector_get(x, 0);\n for (j=1; jfitTerm; j++) spec[j-1] = gsl_vector_get(x, j);\n\n /* Loop over spectral points */\n for (i=0; infreq; i++) {\n if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {\n isigma = args->isigma[i];\n arg = 0.0;\n argx = args->logNuOnu0[i];\n for (j=1; jfitTerm; j++) {\n\targ += spec[j-1]*argx;\n\targx *= args->logNuOnu0[i];\n }\n spect = exp(arg);\n model = flux * spect;\n func = (model - args->obs[i]) * isigma;\n gsl_vector_set(f, i, func); /* Save function residual */\n /* Jacobian terms - first flux */\n jac = spect * isigma;\n gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n argx = args->logNuOnu0[i];\n for (j=1; jfitTerm; j++) {\n\tjac = model * isigma * argx;\n\tgsl_matrix_set(J, i, j, jac); /* Save Jacobian */\n \targx *= args->logNuOnu0[i];\n }\n } else { /* Invalid data */\n func = 0.0;\n gsl_vector_set(f, i, func); /* Save function residual */\n jac = 0.0;\n gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n for (j=1; jfitTerm; j++) {\n\tgsl_matrix_set(J, i, j, jac); /* Save Jacobian */\n }\n }\n } /* End loop over spectral points */\n\n return GSL_SUCCESS;\n} /* end SpecFitFuncJac */\n/**\n * Function evaluator for spectral fitting solver\n * Broken power law version, above nv_b the spectrum steepens by half\n * Parameters:\n * S_0 = Flux density at frequency nu_0\n * alpha = spectral index\n * nu_b = Break frequency\n * Evaluates (model-observed) / sigma\n * \\param x Vector of parameters to be fitted\n * Flux,array_of spectral_terms\n * \\param param Function parameter structure (NLFitArg)\n * \\param f Vector of (model-obs)/sigma for data points\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int SpecFitFuncBP (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f)\n{\n NLFitArg *args = (NLFitArg*)params;\n ofloat fblank = ObitMagicF();\n double flux, spec[10], func;\n odouble model, fluxb, arg, isigma, spect;\n size_t i, j;\n\n /* get model parameters */\n flux = gsl_vector_get(x, 0);\n /* Spectral terms - alpha, nu_b */\n for (j=1; jfitTerm; j++) spec[j-1] = gsl_vector_get(x, j);\n\n /* Loop over spectral points */\n for (i=0; infreq; i++) {\n if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {\n /* Above or below the break? */\n if (args->nu[i]logNuOnu0[i];\n\tspect = exp(arg);\n\tmodel = flux * spect;\n } else { /* above */\n /* Get the flux density at the break */\n\targ = spec[0] * log (spec[1] / args->refFreq);\n\tspect = exp(arg);\n\tfluxb = flux * spect;\n\t/* Flux density at frequency */\n\targ = (spec[0]-0.5) * log (args->nu[i] / spec[1]);\n\tspect = exp(arg);\n\tmodel = fluxb * spect;\n } /* End of above or below the break */\n isigma = args->isigma[i];\n func = (model - args->obs[i]) * isigma;\n gsl_vector_set(f, i, func); /* Save function residual */\n } else { /* Invalid data */\n func = 0.0;\n gsl_vector_set(f, i, func); /* Save function residual */\n }\n } /* End loop over spectral points */\n\n return GSL_SUCCESS;\n} /* end SpecFitFuncBP */\n\n/**\n * Jacobian evaluator for spectral fitting solver\n * Broken power law version, above nv_b the spectrum steepens by half\n * Parameters:\n * S_0 = Flux density at frequency nu_0\n * alpha = spectral index\n * nu_b = Break frequency\n * Evaluates partial derivatives of model wrt each parameter\n * \\param x Vector of parameters to be fitted\n * Flux,array_of spectral_terms\n * \\param param Function parameter structure (NLFitArg)\n * \\param J Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int SpecFitJacBP (const gsl_vector *x, void *params, \n\t\t\t gsl_matrix *J)\n{\n NLFitArg *args = (NLFitArg*)params;\n ofloat fblank = ObitMagicF();\n double flux, spec[10], jac;\n odouble model, fluxb, arg, isigma, spect, spect2;\n odouble logNubONu0, logNuONub;\n size_t i, j;\n\n /* get model parameters */\n flux = gsl_vector_get(x, 0);\n /* Spectral terms - alpha, nu_b */\n for (j=1; jfitTerm; j++) spec[j-1] = gsl_vector_get(x, j);\n\n /* Loop over spectral points */\n for (i=0; infreq; i++) {\n if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {\n isigma = args->isigma[i];\n /* Above or below the break? */\n if (args->nu[i]logNuOnu0[i];\n\tspect = exp(arg);\n\tmodel = flux * spect;\n\t/* Jacobian terms - first flux */\n\tjac = spect * isigma;\n\tgsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n\t/* Spectral index */\n\tjac = model * isigma * args->logNuOnu0[i];\n\tgsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */\n\t/* Break frequency - no dependency */\n\tjac = 0.0;\n\tgsl_matrix_set(J, i, 2, jac); /* Save spectral index Jacobian */\n } else { /* above */\n\t/* Get the flux density at the break */\n\tlogNubONu0 = log (spec[1] / args->refFreq);\n\targ = spec[0] * logNubONu0;\n\tspect = exp(arg);\n\tfluxb = flux * spect;\n\t/* Flux density at frequency */\n\tlogNuONub = log (args->nu[i] / spec[1]);\n\targ = (spec[0]-0.5) * logNuONub;\n\tspect2 = exp(arg);\n\tmodel = fluxb * spect2;\n\t/* Jacobian terms - first flux */\n\tjac = spect * spect2 * isigma;\n\tgsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n\t/* Spectral index */\n\tjac = (fluxb*logNubONu0 + model*logNuONub) * isigma;\n\tgsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */\n\t/* Break frequency */\n\tjac = isigma * (fluxb*spec[0] - model*(spec[0]-0.5)) / spec[1];\n\tgsl_matrix_set(J, i, 2, jac); /* Save break frequency Jacobian */\n } /* End of above or below the break */\n } else { /* Invalid data */\n jac = 0.0;\n gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n for (j=1; jfitTerm; j++) {\n\tgsl_matrix_set(J, i, j, jac); /* Save Jacobian */\n }\n }\n } /* End loop over spectral points */\n\n return GSL_SUCCESS;\n} /* end SpecFitJacBP */\n\n/**\n * Function and Jacobian evaluator for spectral fitting solver\n * Broken power law version, above nv_b the spectrum steepens by half\n * Parameters:\n * S_0 = Flux density at frequency nu_0\n * alpha = spectral index\n * nu_b = Break frequency\n * Function = (model-observed) / sigma\n * Jacobian = partial derivatives of model wrt each parameter\n * \\param x Vector of parameters to be fitted\n * Flux,array_of spectral_terms\n * \\param param Function parameter structure (NLFitArg)\n * \\param f Vector of (model-obs)/sigma for data points\n * \\param J Jacobian matrix J[data_point, parameter]\n * \\return completion code GSL_SUCCESS=OK\n */\nstatic int SpecFitFuncJacBP (const gsl_vector *x, void *params, \n\t\t\t gsl_vector *f, gsl_matrix *J)\n{\n NLFitArg *args = (NLFitArg*)params;\n ofloat fblank = ObitMagicF();\n double flux, spec[10], func, jac;\n odouble model, arg, fluxb, isigma, spect, spect2;\n odouble logNubONu0, logNuONub;\n size_t i, j;\n\n /* get model parameters */\n flux = gsl_vector_get(x, 0);\n /* Spectral terms - alpha, nu_b */\n for (j=1; jfitTerm; j++) spec[j-1] = gsl_vector_get(x, j);\n\n /* Loop over spectral points */\n for (i=0; infreq; i++) {\n if ((args->obs[i]!=fblank) && (args->isigma[i]>0.0)) {\n isigma = args->isigma[i];\n /* Above or below the break? */\n if (args->nu[i]logNuOnu0[i];\n\tspect = exp(arg);\n\tmodel = flux * spect;\n\tfunc = (model - args->obs[i]) * isigma;\n\tgsl_vector_set(f, i, func); /* Save function residual */\n\t/* Jacobian terms - first flux */\n\tjac = spect * isigma;\n\tgsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n\t/* Spectral index */\n\tjac = model * isigma * args->logNuOnu0[i];\n\tgsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */\n\t/* Break frequency - no dependency */\n\tjac = 0.0;\n\tgsl_matrix_set(J, i, 2, jac); /* Save spectral index Jacobian */\n } else { /* above */\n\t/* Get the flux density at the break */\n\tlogNubONu0 = log (spec[1] / args->refFreq);\n\targ = spec[0] * logNubONu0;\n\tspect = exp(arg);\n\tfluxb = flux * spect;\n\t/* Flux density at frequency */\n\tlogNuONub = log (args->nu[i] / spec[1]);\n\targ = (spec[0]-0.5) * logNuONub;\n\tspect2 = exp(arg);\n\tmodel = fluxb * spect2;\n\tfunc = (model - args->obs[i]) * isigma;\n\tgsl_vector_set(f, i, func); /* Save function residual */\n\t/* Jacobian terms - first flux */\n\tjac = spect * spect2 * isigma;\n\tgsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n\t/* Spectral index */\n\tjac = (fluxb*logNubONu0 + model*logNuONub) * isigma;\n\tgsl_matrix_set(J, i, 1, jac); /* Save spectral index Jacobian */\n\t/* Break frequency */\n\tjac = isigma * (fluxb*spec[0] - model*(spec[0]-0.5)) / spec[1];\n\tgsl_matrix_set(J, i, 2, jac); /* Save break frequency Jacobian */\n } /* End of above or below the break */\n } else { /* Invalid data */\n func = 0.0;\n gsl_vector_set(f, i, func); /* Save function residual */\n jac = 0.0;\n gsl_matrix_set(J, i, 0, jac); /* Save flux Jacobian */\n for (j=1; jfitTerm; j++) {\n\tgsl_matrix_set(J, i, j, jac); /* Save Jacobian */\n }\n }\n } /* End loop over spectral points */\n\n return GSL_SUCCESS;\n} /* end SpecFitFuncJacBP */\n#endif /* HAVE_GSL */ \n", "meta": {"hexsha": "8d62e5d93092ed3e21b5e5e89d742e54b345763a", "size": 94373, "ext": "c", "lang": "C", "max_stars_repo_path": "ObitSystem/Obit/src/ObitSpectrumFit.c", "max_stars_repo_name": "kettenis/Obit", "max_stars_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ObitSystem/Obit/src/ObitSpectrumFit.c", "max_issues_repo_name": "kettenis/Obit", "max_issues_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ObitSystem/Obit/src/ObitSpectrumFit.c", "max_forks_repo_name": "kettenis/Obit", "max_forks_repo_head_hexsha": "3f835799918065b149a1e73a6a140cb5eed466c5", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-22T14:07:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-22T14:07:41.000Z", "avg_line_length": 35.2269503546, "max_line_length": 102, "alphanum_fraction": 0.6223390165, "num_tokens": 30396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.5621765008857981, "lm_q2_score": 0.35936413143782797, "lm_q1q2_score": 0.20202606995558214}} {"text": "/*\n * HelloWorld.cpp\n *\n * Created on: 22 August 2016\n * Author: Dr. Corneliu Arsene\n *\n * This software implements the Canonical Variates Analysis method (libhelloworld.jnilib file) for image\n * processing: it reads the multispectral images from the same directory as where the libhelloworld.jnilib \n * file is located and then produces a number of improved colour images in comparison to the original \n * multispectral images.\n *\n *\n *\n *\n *\n */\n\n#include \"jni.h\"\n#include \n#include \"HelloWorld.h\"\n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\n\n\n#include \n#include \n#include \n#include \n#include \n\n\n\n\n#include \n\n\n#include \"gsl/matrix/gsl_matrix.h\"\n#include \"gsl/specfunc/gsl_sf_bessel.h\"\n#include \"gsl_math.h\"\n#include \"gsl/gsl_blas.h\"\n#include \n#include \n#include \n#include \n#include \n\n\n\n\n\nusing namespace cv;\nusing namespace std;\n\n\n// * THIS FILE IS COMPILED TO A LIBRARY WHICH IS CALLED BY A JAVA LIBRARY\n\nJNIEXPORT void JNICALL\nJava_HelloWorld_print(JNIEnv *env, jobject thisObj){\n \n \n \n \n \n int i,j,k;\n int grp1[9];//,grouping_vector[200] ;\n \n \n \n char *dir;\n int depth;\n \n dir =\"/home\";\n depth=0;\n \n DIR * dp1,*dp3;\n struct dirent* ep,*ep3;\n \n \n \n char* text;\n char pattern[6];\n char* text2;\n pattern[0]='\\0';\n pattern[1]='\\0';\n pattern[2]='\\0';\n pattern[3]='\\0';\n pattern[4]='\\0';\n pattern[5]='\\0';\n \n \n clock_t start, end;\n double cpu_time_used;\n \n start = clock();\n // * DETECT HOW MANY CLASS TEXT FILES EXIST (E.G. CLASS MANUSCRIPT, CLASS UNDERWRITING, ETC)\n \n \n text=\"Class\";\n \n dp1 = opendir (\"./\");\n \n int acindex,newacindex;\n acindex = 0;\n newacindex =0;\n \n while (ep = readdir (dp1))\n {\n text2 = ep->d_name;\n \n pattern[0] = text2[0];//ep->d_name[0];\n pattern[1] = text2[1];//ep->d_name[1];\n pattern[2] = text2[2];//ep->d_name[2];\n pattern[3] = text2[3];//ep->d_name[3];\n pattern[4] = text2[4];//ep->d_name[4];\n pattern[5] ='\\0';\n \n if( strcmp(text, pattern) == 0 )\n {\n acindex = acindex +1;\n }\n \n }\n \n (void) closedir (dp1);\n \n \n \n // * ONCE I KNOW HOW MANY CLASSES THERE ARE THEN I MEMORIZE THE PATH TO THE RESPECTIVE CLASS FILES\n \n \n char arrayclass[acindex][2024];\n dp3 = opendir (\"./\");\n \n \n \n while (ep3 = readdir (dp3))\n \n {\n \n text2 = ep3->d_name;\n \n pattern[0] = text2[0];//ep->d_name[0];\n \n pattern[1] = text2[1];//ep->d_name[1];\n \n pattern[2] = text2[2];//ep->d_name[2];\n \n pattern[3] = text2[3];//ep->d_name[3];\n \n pattern[4] = text2[4];//ep->d_name[4];\n \n pattern[5] ='\\0';\n \n if( strcmp(text, pattern) == 0 )\n {\n \n strcpy(arrayclass[newacindex],ep3->d_name);\n \n newacindex = newacindex +1;\n \n }\n }\n \n \n \n // * I AM PREPARING TO READ THE CLASS TEXT FILES WHICH I DETECTED ABOVE\n \n \n (void) closedir (dp3);\n char cwd[1024],cwdtemp[1024];\n getcwd(cwd, sizeof(cwd));\n \n strcat(cwd,\"/\");\n \n FILE *file[acindex];\n \n for (int j=0; j < acindex; j=j+1)\n {\n strcpy(cwdtemp,cwd);\n \n strcat(cwdtemp,arrayclass[j]);\n if((file[j] = fopen(cwdtemp, \"r\"))==NULL) /* open a text file for reading */\n exit(1);\n printf(\"%s\\n\",cwdtemp);\n }\n \n \n int over,over1,over2,over3,over4,over5,over6;\n \n int xx=0;\n double dd=0;\n char str[256],str1[256],str2[256],str3[256],str4[256],str5[256],str6[256],str7[256],str8[256];\n \n int classoverwriting[50][7];\n \n double classoverwriting1[1][7];\n \n \n int classunderwriting[50][7];\n int classmanuscript[50][7];\n int classbothuo[50][7];\n \n \n \n int i1;\n \n int nrclass[acindex];\n \n \n // * I AM DETECTING HOW MANY POINTS HAS EACH CLASS, FOR EXAMPLE CLASS MANUSCRIPT MIGHT HAVE 100 POINTS WHILE CLASS OVERWRITING MIGHT HAVE 120 POINTS, ETC\n \n \n \n for (int j=0; j < acindex; j=j+1)\n {\n fscanf(file[j], \" %s %s %s %s %s %s \\n\", &str,&str1, &str2,&str3,&str4,&str5);\n \n i1=0;\n \n while (!feof(file[j]))\n {\n fscanf(file[j], \" %lf %lf %lf %lf %lf %lf %lf\\n\", &classoverwriting1[1][1], &classoverwriting1[1][2], &classoverwriting1[1][3], &classoverwriting1[1][4], &classoverwriting1[1][5], &classoverwriting1[1][6], &classoverwriting1[1][7]);\n \n \n \n \n i1 =i1+1;\n \n }\n nrclass[j]=i1;\n \n \n \n }\n \n \n \n int sumtotalnrclass;\n sumtotalnrclass = 0;\n \n //exit(1);\n \n for (int j=0; j < acindex; j=j+1)\n {\n sumtotalnrclass = sumtotalnrclass + nrclass[j];\n }\n \n \n\n \n int dummyvar;\n \n int **classtotal = new int*[sumtotalnrclass];\n for (int i = 0; i < sumtotalnrclass; i++)\n {\n classtotal[i] = new int[7];\n }\n \n printf(\" \\n\");\n \n double testclass1,testclass2;\n \n // * I AM READING THE POINTS FROM EACH CLASS FILES\n \n \n \n i1=0;\n for (int j=0; j < acindex; j=j+1)\n {\n fseek( file[j], 0, SEEK_SET );\n fscanf(file[j], \" %s %s %s %s %s %s \\n\", &str,&str1, &str2,&str3,&str4,&str5);\n //printf (\"%s\\n\", str);\n while (!feof(file[j]))\n {\n \n \n fscanf(file[j], \" %s %s %s %s %s %s %s\\n\", &str,&str1, &str2,&str3,&str4,&str5,&str6);\n \n testclass1 = atof(str5);\n testclass2 = atof(str6);\n \n classtotal[i1][6] = round(testclass1);\n classtotal[i1][7] = round(testclass2);\n \n \n \n i1 =i1+1;\n \n }\n \n fclose(file[j]);\n }\n \n \n \n \n \n \n \n char arraytiff[50][2024];//maximum number of images is 50\n \n \n \n \n // * I AM DETECTING THE NUMBER OF MULTISPECTRAL IMAGES AS THERE COULD BE 10 , 16, 23 , ETC MULTISPECTRAL IMAGES\n \n \n \n \n DIR * dp2;\n struct dirent* ep2;\n char* text1;\n char pattern1[6];\n char* text22;\n pattern1[0]='\\0';\n pattern1[1]='\\0';\n pattern1[2]='\\0';\n pattern1[3]='\\0';\n pattern1[4]='\\0';\n pattern1[5]='\\0';\n text1=\".tif\";\n dp2 = opendir (\"./\");\n int acindex1, sn1;\n acindex1 = 0;\n \n \n \n while (ep2 = readdir (dp2))\n {\n text22 = ep2->d_name;\n \n sn1 = strlen(text22);;//sizeof(text22);\n \n pattern1[0] = text22[sn1-4];//ep->d_name[0];\n \n pattern1[1] = text22[sn1-3];//ep->d_name[1];\n \n pattern1[2] = text22[sn1-2];//ep->d_name[2];\n \n pattern1[3] = text22[sn1-1];//ep->d_name[3];\n \n pattern1[4] ='\\0';\n if( strcmp(text1, pattern1) == 0 )\n {\n \n strcpy(arraytiff[acindex1],ep2->d_name);\n printf(\"%s\\n\",arraytiff[acindex1]);\n acindex1 = acindex1 +1;\n \n }\n }\n \n char tiffext[4];\n \n char namefile[40];\n \n strncpy(namefile,arraytiff[0],strlen(arraytiff[0])-4);\n \n \n printf(\" TEST 3333333 \\n \");\n \n \n \n // * I AM COPYING THE PATH TO THE MULTISPECTRAL IMAGES\n \n (void) closedir (dp2);\n \n char cwd1[1024],cwdtemp1[1024],*dfg;\n getcwd(cwd1, sizeof(cwd1));\n \n strcat(cwd1,\"/\");\n char arrayimage[acindex1][2024];\n \n char *arrayimage2[acindex1];\n \n printf(\"%s\\n\",cwd);\n printf(\"%s\\n\",cwd1);\n \n for (int j=0; j < acindex1; j=j+1)\n {\n \n strcpy(cwdtemp1,cwd1);\n \n strcat(cwdtemp1,arraytiff[j]);\n \n strcpy(arrayimage[j],cwdtemp1);\n \n printf(\"%s \\n\",arrayimage[j]);\n \n }\n \n \n \n \n \n double data_matrix[sumtotalnrclass][acindex1];\n \n \n \n //#pragma omp parallel for private(j,i)\n for (int i=0; i < sumtotalnrclass; i=i+1)\n {\n for (int j=0; j < acindex1; j=j+1)\n {\n data_matrix[i][j] = 0;\n }\n }\n\n \n \n std::vector image(acindex1);\n \n \n \n std::vector various_images;\n \n \n // * I AM READING THE IMAGES AND I PUT THEM IN THE VECTOR OF IMAGES CALLED VARIOUS_IMAGES\n \n for (int i=0; i < acindex1; i=i+1)\n {\n \n image[i] = imread(arrayimage[i], 0);\n \n various_images.push_back(image[i]);\n \n }\n \n \n \n s1 = image[0].rows;\n s2 = image[0].cols;\n \n //int s1s2;\n \n s1s2 = s1*s2;\n \n if(! image[0].data ) // Check for invalid input\n {\n cout << \"Could not open or find the image\" << std::endl ;\n // return -1;\n }\n \n \n \n // p o u b\n \n \n int *grouping_vector = new int[sumtotalnrclass] ;\n \n for (int k = 0; k < sumtotalnrclass; k++) {\n grouping_vector[k] = 0;\n \n }\n \n \n \n \n int *grp = new int[sumtotalnrclass] ;\n \n for (int k = 0; k < sumtotalnrclass; k++) {\n grp[k] = 0;\n \n }\n \n // * FROM THE MULTISPECTRAL IMAGES I AM SELECTING THE POINTS BASED ON THE CLASS FILES\n \n \n int indexonc;\n for (int j = 0; j < acindex1; j++) {\n \n indexonc = 0;\n for (int k = 0; k < acindex; k++) {\n \n for (int ss = 0; ss < nrclass[k]; ss++)\n {\n \n data_matrix[indexonc][j] = (double) various_images[j].at(classtotal[indexonc][7]-1,classtotal[indexonc][6]-1);\n \n indexonc = indexonc +1 ;\n \n \n \n }\n }\n }\n \n \n // * I AM COUNTING THE POINTS FROM EACH CLASS\n \n \n indexonc = 0;\n for (int k = 0; k < acindex; k=k+1) {\n \n for (int ss = 0; ss < nrclass[k]; ss=ss+1)\n {\n grouping_vector[indexonc] = 1+k;\n grp[indexonc]=1+k;\n indexonc = indexonc +1 ;\n \n }\n }\n \n printf(\" \\n \");\n\n \n \n double X[sumtotalnrclass][acindex1];\n \n \n for (int i = 0; i < sumtotalnrclass; i++) {\n for (int j = 0; j < acindex1; j++) {\n \n X[i][j] = data_matrix[i][j];\n \n }\n \n \n }\n \n \n int N,D,K;\n \n float nk[acindex1];\n float alpha,xmg[acindex1],xmk[acindex][acindex1];\n int index;\n float xdiff[sumtotalnrclass], transxdiff[sumtotalnrclass][1];\n float sum[acindex1][acindex1], sumare;\n\n \n // * I AM IMPLEMENTING THE CANONICAL VARIATES ANALYSIS METHOD BASED ON THE MATLAB VERSION OF THIS METHOD\n \n \n N = sumtotalnrclass;//sizeof(X);\n D = acindex1;//sizeof(X[0][0])-1;\n \n \n \n for (j=0; j < acindex1; j=j+1)\n {\n xmg[j] = 0;\n \n }\n \n K = grp[0];\n for (int j=1;j(i,j) )*coef1[k][0];\n \n newmatrix2[i][j] = newmatrix2[i][j] + ( (double)various_images[k].at(i,j) )*coef1[k][1];\n \n newmatrix3[i][j] = newmatrix3[i][j] + ( (double)various_images[k].at(i,j) )*coef1[k][2];\n \n \n \n }\n \n \n }\n \n }\n \n \n double minimum1,minimum2,minimum3;\n double maximum1,maximum2,maximum3;\n \n \n double **range_cv1 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n range_cv1[i] = new double[s2];\n }\n \n \n double **range_cv2 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n range_cv2[i] = new double[s2];\n }\n \n double **range_cv3 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n range_cv3[i] = new double[s2];\n }\n \n \n \n \n minimum1= newmatrix1[0][0];\n for(int i=0; i maximum1)\n {\n maximum1=newmatrix1[i][j];\n }\n }\n }\n \n maximum2= newmatrix2[0][0];\n for(int i=0; i maximum2)\n {\n maximum2=newmatrix2[i][j];\n }\n }\n }\n \n maximum3= newmatrix3[0][0];\n for(int i=0; i maximum3)\n {\n maximum3=newmatrix3[i][j];\n }\n }\n }\n \n \n \n range_cv1 = range_map(newmatrix1, minimum1, maximum1);\n \n \n range_cv2 = range_map(newmatrix2, minimum2, maximum2);\n \n range_cv3 = range_map(newmatrix3, minimum3, maximum3);\n \n \n \n int aa,bb,cc;\n \n \n printf(\" \\n\" );\n \n printf(\" A SET OF 8 PICTURES ARE PRODUCED \");\n \n \n cv::Mat img16(s1, s2, CV_8UC3);\n \n vector compression_params;\n compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);\n compression_params.push_back(9);\n \n \n for (int i = 0; i < s1; i++) {\n for (int j = 0; j < s2; j++) {\n \n \n \n img16.at(i,j)[1] = (255-range_cv2[i][j]);\n img16.at(i,j)[2] = (255-range_cv1[i][j]);\n img16.at(i,j)[3] = (255-range_cv3[i][j]);\n \n }\n }\n \n char fileword[100];\n strcpy(fileword,namefile);\n strcat(fileword,\"_image_rangecvasecond.tiff\");\n \n \n //end = clock();\n //cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n //printf(\" \\n\" );\n \n //printf(\" %lf \", cpu_time_used );\n \n //exit(1);\n \n \n cv::imwrite(fileword, img16);\n \n \n cv::Mat img162(s1, s2, CV_8UC3);\n \n \n for (int i = 0; i < s1; i++) {\n for (int j = 0; j < s2; j++) {\n \n \n img162.at(i,j)[1] = range_cv2[i][j];\n img162.at(i,j)[2] = range_cv1[i][j];\n img162.at(i,j)[3] = range_cv3[i][j];\n \n }\n }\n \n char fileword1[100];\n strcpy(fileword1,namefile);\n strcat(fileword1,\"_image_rangecva.tiff\");\n \n \n cv::imwrite(fileword1, img162);\n \n \n \n \n double minscore1,minscore2,minscore3;\n double maxscore1,maxscore2,maxscore3;\n \n \n minscore1=0;\n minscore1= score1[0][0];\n for(int i=0; i maxscore1)\n {\n maxscore1=score1[i][0];\n }\n \n }\n \n maxscore2=0;\n maxscore2= score1[0][1];\n for(int i=0; i maxscore2)\n {\n maxscore2=score1[i][1];\n }\n \n }\n \n maxscore3=0;\n maxscore3= score1[0][2];\n for(int i=0; i maxscore3)\n {\n maxscore3=score1[i][2];\n }\n \n }\n \n \n double **score_cv1 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n score_cv1[i] = new double[s2];\n }\n \n \n double **score_cv2 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n score_cv2[i] = new double[s2];\n }\n \n double **score_cv3 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n score_cv3[i] = new double[s2];\n }\n \n \n score_cv1 = range_map(newmatrix1, minscore1, maxscore1);\n \n score_cv2 = range_map(newmatrix2, minscore2, maxscore2);\n \n score_cv3 = range_map(newmatrix3, minscore3, maxscore3);\n \n \n \n \n cv::Mat img163(s1, s2, CV_8UC3);\n \n \n for (int i = 0; i < s1; i++) {\n for (int j = 0; j < s2; j++) {\n \n \n img163.at(i,j)[1] = score_cv2[i][j];\n img163.at(i,j)[2] = score_cv1[i][j];\n img163.at(i,j)[3] = score_cv3[i][j];\n \n }\n }\n \n char fileword2[100];\n strcpy(fileword2,namefile);\n strcat(fileword2,\"_image_score_rangecva.tiff\");\n \n \n cv::imwrite(fileword2, img163);\n\n \n \n cv::Mat img164(s1, s2, CV_8UC3);\n \n \n \n for (int i = 0; i < s1; i++) {\n for (int j = 0; j < s2; j++) {\n \n \n img164.at(i,j)[1] = (255-score_cv2[i][j]);\n img164.at(i,j)[2] = (255-score_cv1[i][j]);\n img164.at(i,j)[3] = (255-score_cv3[i][j]);\n \n }\n }\n \n \n char fileword3[100];\n strcpy(fileword3,namefile);\n strcat(fileword3,\"_image_score_rangecvasecond.tiff\");\n \n \n cv::imwrite(fileword3, img164);\n \n \n \n // * I AM PRODUCING THE 8 BIT IMAGES OF THE PERCENTILE\n \n double required_percentiles[8];\n \n required_percentiles[0] = 0.01;\n required_percentiles[1] = 0.1;\n required_percentiles[2] = 1;\n required_percentiles[3] = 5;\n required_percentiles[4] = 99.99;\n required_percentiles[5] = 99.9;\n required_percentiles[6] = 99;\n required_percentiles[7] = 95;\n \n \n \n int sizerows,sizecolumns;\n \n \n int n_percentiles;\n \n n_percentiles = (int) 8 / 2;\n \n double *percentiles_cv1 = new double[5];\n double *percentiles_cv2 = new double[5];\n double *percentiles_cv3 = new double[5];\n double *percentiles_cv4 = new double[5];\n double *percentiles_cv5 = new double[5];\n \n for (int i = 0; i < 5; i++)\n {\n percentiles_cv1[i] = 0;\n percentiles_cv2[i] = 0;\n percentiles_cv3[i] = 0;\n percentiles_cv4[i] = 0;\n percentiles_cv5[i] = 0;\n \n \n \n }\n \n percentiles_cv1 = Percentile(newmatrix1, required_percentiles);\n percentiles_cv2 = Percentile(newmatrix2, required_percentiles);\n percentiles_cv3 = Percentile(newmatrix3, required_percentiles);\n \n \n double **per_cv1 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n per_cv1[i] = new double[s2];\n }\n \n \n double **per_cv2 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n per_cv2[i] = new double[s2];\n }\n \n double **per_cv3 = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n per_cv3[i] = new double[s2];\n }\n \n cv::Mat img165(s1, s2, CV_8UC3);\n char str22[35];\n \n \n for (int i = 0; i < n_percentiles ; i++)\n {\n per_cv1 = range_map(newmatrix1,percentiles_cv1[i] , percentiles_cv1[i+n_percentiles]);\n \n per_cv2 = range_map(newmatrix2, percentiles_cv2[i], percentiles_cv2[i+n_percentiles]);\n \n per_cv3 = range_map(newmatrix3, percentiles_cv3[i], percentiles_cv3[i+n_percentiles]);\n \n \n \n \n for (int i = 0; i < s1; i++) {\n for (int j = 0; j < s2; j++) {\n \n img165.at(i,j)[1] = per_cv2[i][j];\n img165.at(i,j)[2] = per_cv1[i][j];\n img165.at(i,j)[3] = per_cv3[i][j];\n \n }\n }\n \n \n sprintf(str22,\"_image_percentile_%lfcva.tiff\", required_percentiles[i]);\n \n \n strcpy(fileword3,namefile);\n strcat(fileword3,str22);\n \n cv::imwrite(fileword3, img165);\n \n \n \n \n }\n \n end = clock();\n cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n \n \n printf(\" %lf \", cpu_time_used );\n \n return;\n}\n\n\n\n\n//double* Percentile(double arr[5412][7216], double percentile[8])\ndouble* Percentile(double** arr, double percentile[8])\n{\n \n int index,size1;\n \n index =0;\n \n \n \n double *resultingvector = new double[s1s2];\n \n size1 = sizeof(percentile);\n \n for(int i = 0; i < s1; i++)\n {\n for(int j = 0; j < s2; j++)\n {\n \n resultingvector[index] = arr[i][j];\n index = index +1;\n }\n \n }\n \n double aa;\n \n \n \n gsl_vector * v = gsl_vector_alloc (s1s2);\n \n for (int i = 0; i < s1s2; i++)\n {\n gsl_vector_set (v, i,resultingvector[i] );\n }\n \n \n \n gsl_sort_vector(v);\n \n for (int i = 0; i < s1s2; i++)\n {\n resultingvector[i] = gsl_vector_get (v, i);\n }\n \n \n int index2;\n \n double *percentile_values = new double[size1];\n \n for(int i = 0; i < size1; i++)\n {\n index2 = round(1 + (percentile[i]/100)*(s1s2-1));\n percentile_values[i] = resultingvector[index2];\n }\n \n return percentile_values;\n}\n\nint compare_doubles (const double * a,\n const double * b)\n{\n if (*a > *b)\n return 1;\n else if (*a < *b)\n return -1;\n else\n return 0;\n}\n\ndouble* quickSort( double a[], long l, long r)\n{\n long j;\n \n //r = 39052992;\n if( l < r )\n {\n // divide and conquer\n j = partition( a, l, r);\n a = quickSort( a, l, j-1);\n a = quickSort( a, j+1, r);\n }\n //for(int i = 0; i < 39052992; i++)\n //{\n printf(\" %d \\n\", j );\n //}\n return a;\n}\n\n\nlong partition(double a[], long l, long r) {\n long i, j;\n double pivot,t;\n pivot = a[l];\n i = l; j = r+1;\n \n while( 1)\n {\n do ++i; while( a[i] <= pivot && i <= r );\n do --j; while( a[j] > pivot );\n if( i >= j ) break;\n t = a[i]; a[i] = a[j]; a[j] = t;\n }\n t = a[l]; a[l] = a[j]; a[j] = t;\n return j;\n}\n\n//double** range_map(double newmatrix[5412][7216], double minimum, double maximum)\ndouble** range_map(double** newmatrix, double minimum, double maximum)\n\n{\n \n \n \n //static double newimage[5412][7216];\n \n double **newimage = new double*[s1];\n for (int i = 0; i < s1; i++)\n {\n newimage[i] = new double[s2];\n }\n \n \n \n double out_low, out_high, out_range_low, out_range_high,v,v2;\n \n out_low = 0;\n out_high =255;\n out_range_low = 0;\n out_range_high = 255;\n \n double in_low,in_high;\n \n in_low = minimum;\n in_high = maximum;\n \n \n for(int i = 0; i < s1; i++)\n {\n for(int j = 0; j < s2; j++)\n {\n v = newmatrix[i][j];\n if (v < in_low)\n v2 = out_range_low;\n else if (v > in_high)\n v2 = out_range_high;\n else\n v2 = ((v - in_low) / (in_high - in_low)) * (out_high - out_low) + out_low;\n \n \n //newimage[i][j] = uint8(floor(v2 + 0.5));\n newimage[i][j] = uint8_t(floor(v2+0.5));\n \n \n \n }\n }\n return newimage;\n}\n\n\n", "meta": {"hexsha": "61d271f830acd04387ba5f8f139a1a4783e773e1", "size": 36631, "ext": "c", "lang": "C", "max_stars_repo_path": "HelloWorld.c", "max_stars_repo_name": "corneliu25/GalenProject", "max_stars_repo_head_hexsha": "8d0ad9b36eb3e0830814a18243c8ac57ddcaf6a6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-08-09T10:10:24.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-09T10:10:24.000Z", "max_issues_repo_path": "HelloWorld.c", "max_issues_repo_name": "corneliu37/GalenProject", "max_issues_repo_head_hexsha": "8d0ad9b36eb3e0830814a18243c8ac57ddcaf6a6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HelloWorld.c", "max_forks_repo_name": "corneliu37/GalenProject", "max_forks_repo_head_hexsha": "8d0ad9b36eb3e0830814a18243c8ac57ddcaf6a6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-12T00:30:12.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-12T00:30:12.000Z", "avg_line_length": 20.8723646724, "max_line_length": 245, "alphanum_fraction": 0.4462886626, "num_tokens": 11081, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.5078118642792046, "lm_q2_score": 0.3960681662740417, "lm_q1q2_score": 0.20112811389726706}}