{"text": "/*\nCopyright (C) 2019-2020 JingWeiZhangHuai \nLicensed under the Apache License, Version 2.0; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.\n*/\n \n#include \n#include \n#include \n#include \n\n#include \n#include \"morn_tensor.h\"\n\nstruct TensorBatchNormPara\n{\n MLayer *prev;\n \n int res_valid;\n \n float rate;\n float decay;\n float momentum;\n};\n\nvoid *mTensorBatchNormPara(MList *ini,char *name)\n{\n struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)mMalloc(sizeof(struct TensorBatchNormPara));\n \n char *value = mINIRead(ini,name,\"prev\");\n para->prev = mNetworkLayer(ini,value);\n mException((para->prev == NULL),EXIT,\"invalid prev\");\n \n para->res_valid = (strcmp(\"Input\",mLayerType(para->prev))!=0);\n \n value = mINIRead(ini,name,\"rate\");\n if(value != NULL) para->rate = atof(value);\n else\n {\n value = mINIRead(ini,\"para\",\"rate\");\n if(value != NULL) para->rate = atof(value);\n else para->rate = 0.001;\n }\n \n value = mINIRead(ini,name,\"decay\");\n if(value != NULL) para->decay = atof(value);\n else\n {\n value = mINIRead(ini,\"para\",\"decay\");\n if(value != NULL) para->decay = atof(value);\n else para->decay = 0.01;\n }\n mException((para->decay<0.0f)||(para->decay>=1.0f),EXIT,\"invalid para decay\");\n \n value = mINIRead(ini,name,\"momentum\");\n if(value != NULL) para->momentum = atof(value); \n else\n {\n value = mINIRead(ini,\"para\",\"momentum\");\n if(value != NULL) para->momentum = atof(value);\n else para->momentum = 0.9;\n }\n \n return para;\n}\n\nstruct HandleTensorBatchNorm\n{\n float *k;\n float *b;\n \n float *k_update;\n float *b_update;\n \n double *mean;\n double *var;\n float *roll_mean;\n float *roll_var;\n};\nvoid endTensorBatchNorm(void *info)\n{\n struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)info;\n if(handle->k != NULL) mFree(handle->k);\n if(handle->b != NULL) mFree(handle->b);\n if(handle->mean != NULL) mFree(handle->mean);\n if(handle->var != NULL) mFree(handle->var );\n if(handle->roll_mean!= NULL) mFree(handle->roll_mean);\n if(handle->roll_var != NULL) mFree(handle->roll_var );\n}\n#define HASH_TensorBatchNorm 0xde8952f6\n\nvoid TensorBatchNormSet(MLayer *layer)\n{\n if(layer->state != DFLT) return;\n struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)(layer->para);\n MTensor *in = para->prev->tns;\n MTensor *res= para->prev->res;\n MTensor *out=layer->tns;\n \n MHandle *hdl=mHandle(out,TensorBatchNorm);\n struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)(hdl->handle);\n \n if(handle->k != NULL) {mFree(handle->k);} handle->k =(float *)mMalloc(in->channel*sizeof(float));\n if(handle->b != NULL) {mFree(handle->b);} handle->b =(float *)mMalloc(in->channel*sizeof(float));\n \n if(handle->mean!= NULL) {mFree(handle->mean);} handle->mean=(double *)mMalloc(in->channel*sizeof(double));\n if(handle->var != NULL) {mFree(handle->var );} handle->var =(double *)mMalloc(in->channel*sizeof(double));\n \n if(handle->roll_mean!= NULL) {mFree(handle->roll_mean);} handle->roll_mean=(float *)mMalloc(in->channel*sizeof(float));\n if(handle->roll_var != NULL) {mFree(handle->roll_var );} handle->roll_var =(float *)mMalloc(in->channel*sizeof(float));\n \n mTensorRedefine(out,in->batch,in->channel,in->height,in->width,NULL);\n if(morn_network_flag == MORN_TRAIN)\n {\n if(INVALID_TENSOR(res)) mTensorRedefine(res,in->batch,in->channel,in->height,in->width,out->data);\n else mTensorRedefine(res,in->batch,in->channel,in->height,in->width,NULL);\n \n handle->k_update = handle->roll_mean;\n handle->b_update = handle->roll_var ;\n memset(handle->k_update,0,in->channel*sizeof(float));\n memset(handle->b_update,0,in->channel*sizeof(float));\n }\n \n if(morn_network_parafile==NULL)\n {\n for(int i=0;ichannel;i++){handle->k[i] = 1.0f;handle->b[i] = 1.0f;}\n // printf(\"handle->k[0] is %f\\n\",handle->k[0]);\n // printf(\"handle->b[0] is %f\\n\",handle->b[0]);\n }\n else\n {\n mNetworkParaRead(layer,\"scale\",handle->k,in->channel*sizeof(float));\n mNetworkParaRead(layer,\"bias\" ,handle->b,in->channel*sizeof(float));\n // printf(\"handle->k[0] is %f\\n\",handle->k[0]);\n // printf(\"handle->b[0] is %f\\n\",handle->b[0]);\n }\n hdl->valid = 1;\n}\n\nvoid mTensorBatchNormForward(MLayer *layer)\n{\n mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n mException(strcmp(\"BatchNorm\",mLayerType(layer)),EXIT,\"invalid layer type\");\n struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)(layer->para);\n MTensor *in = para->prev->tns;\n MTensor *out=layer->tns;\n \n TensorBatchNormSet(layer);\n \n MHandle *hdl=mHandle(out,TensorBatchNorm);\n struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)(hdl->handle);\n \n int in_size = in->height*in->width;\n \n memset(handle->mean,0,in->channel*sizeof(double));\n memset(handle->var ,0,in->channel*sizeof(double));\n for(int b=0;bbatch;b++)for(int c=0;cchannel;c++)for(int i=0;idata[b][c*in_size+i]);\n handle->mean[c] += data;\n handle->var [c] += data*data;\n }\n for(int c=0;cchannel;c++)\n {\n handle->mean[c] = handle->mean[c]/(double)(in->batch*in_size);\n handle->var [c] = handle->var [c]/(double)(in->batch*in_size);\n handle->var [c]-= (handle->mean[c]*handle->mean[c]);\n handle->var [c] = (handle->var[c]<=0.0f)?0.00001f:sqrt(handle->var[c]);\n // printf(\"handle->mean[c] is %f,handle->var[c] is %f\\n\",handle->mean[c],handle->var[c]);\n }\n \n if(morn_network_flag == MORN_PREDICT)\n {\n for(int c=0;cchannel;c++)\n {\n if(layer->state == DFLT)\n {\n handle->roll_mean[c] = handle->mean[c];\n handle->roll_var [c] = handle->var [c];\n }\n \n handle->mean[c] = handle->roll_mean[c]*0.99f+handle->mean[c]*0.01;\n handle->var [c] = handle->roll_var [c]*0.99f+handle->var [c]*0.01;\n handle->roll_mean[c] = handle->mean[c];\n handle->roll_var [c] = handle->var [c];\n }\n }\n \n for(int b=0;bbatch;b++)for(int c=0;cchannel;c++)for(int i=0;idata[b][c*in_size+i];\n out->data[b][c*in_size+i] = ((data-handle->mean[c])/handle->var[c])*handle->k[c]+handle->b[c];\n }\n \n layer->state = MORN_FORWARD;\n}\n\nvoid mTensorBatchNormBackward(MLayer *layer)\n{\n mException(INVALID_POINTER(layer),EXIT,\"invalid input\");\n mException(strcmp(\"BatchNorm\",mLayerType(layer)),EXIT,\"invalid layer type\");\n struct TensorBatchNormPara *para = (struct TensorBatchNormPara *)(layer->para);\n MTensor *in = para->prev->tns;\n MTensor *res= para->prev->res;\n MTensor *out= layer->res;\n \n MHandle *hdl=mHandle(layer->tns,TensorBatchNorm);\n struct HandleTensorBatchNorm *handle = (struct HandleTensorBatchNorm *)(hdl->handle);\n mException((hdl->valid == 0),EXIT,\"no forward operate\");\n \n mNetworkParaWrite(layer,\"scale\",handle->k,in->channel*sizeof(float));\n mNetworkParaWrite(layer,\"bias\" ,handle->b,in->channel*sizeof(float));\n \n int in_size = in->height*in->width;\n \n for(int c=0;cchannel;c++)\n {\n handle->k_update[c] *= para->momentum;\n handle->b_update[c] *= para->momentum;\n }\n for(int b=0;bbatch;b++)for(int c=0;cchannel;c++)for(int i=0;ik_update[c] += out->data[b][idx]*((in->data[b][idx]-handle->mean[c])/handle->var[c]);\n handle->b_update[c] += out->data[b][idx];\n }\n for(int c=0;cchannel;c++)\n {\n handle->k[c] = (handle->k[c]*(1.0f-(para->decay*para->rate)))-(handle->k_update[c]*para->rate/(float)(in->batch*in_size));\n handle->b[c] = (handle->b[c]*(1.0f-(para->decay*para->rate)))-(handle->b_update[c]*para->rate/(float)(in->batch*in_size));\n }\n \n if(para->res_valid==0) return;\n \n for(int b=0;bbatch;b++)for(int c=0;cchannel;c++)for(int i=0;idata[b][idx] - handle->mean[c])/handle->var[c];\n data = (out->data[b][idx]*handle->k[c]/handle->var[c])*(1.0+(1.0f-data*data)/((float)(in->batch*in_size)));\n \n res->data[b][idx]=(para->prev->state == MORN_FORWARD)?data:(res->data[b][idx]+data);\n }\n \n para->prev->state = MORN_BACKWARD;\n}\n", "meta": {"hexsha": "ad4982a1d814a11e94acdd8b4175f8f906f3540a", "size": 9268, "ext": "c", "lang": "C", "max_stars_repo_path": "src/deep_learning/morn_tensor_batch_normlize.c", "max_stars_repo_name": "ishine/Morn", "max_stars_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 121.0, "max_stars_repo_stars_event_min_datetime": "2019-09-24T05:53:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:23:49.000Z", "max_issues_repo_path": "src/deep_learning/morn_tensor_batch_normlize.c", "max_issues_repo_name": "ishine/Morn", "max_issues_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-09-29T02:52:41.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-07T15:05:18.000Z", "max_forks_repo_path": "src/deep_learning/morn_tensor_batch_normlize.c", "max_forks_repo_name": "ishine/Morn", "max_forks_repo_head_hexsha": "4aacf6dfff67d0fbed75048dc4f2b571f52185b0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2019-09-26T05:09:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T11:34:47.000Z", "avg_line_length": 37.674796748, "max_line_length": 501, "alphanum_fraction": 0.606279672, "num_tokens": 2666, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.47268347662043286, "lm_q1q2_score": 0.3498681907539132}} {"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 \"SIShift.h\"\n\nstatic int verbose = FALSE;\n\nstatic int nLines = 10;\n\nstatic char *usage[] = {\"SIShift - \\n\",\n \"Required parameters:\\n\",\n\t\t\t\" -a abundance data\\n\",\n\t\t\t\" -in filename parameter file \\n\",\n \"Optional:\\n\",\n\t\t\t\" -b integer length of sample file to ignore\\n\",\n\t\t\t\" -s integer sampling frequency\\n\",\n\t\t\t\" -seed long seed random number generator\\n\",\n\t\t\t\" -v verbose\\n\"};\n\nvoid updateExpectations(double* adExpect, int nMax, double dAlpha, double dBeta, double dGamma, int nS, t_Data *ptData)\n{\n int i = 0;\n\n for(i = 1; i <= nMax; i++){\n int nA = i;\n double dLog = 0.0, dP = 0.0;\n\n dLog = logLikelihood(nA, dAlpha, dBeta, dGamma);\n\n dP = exp(dLog);\n\n adExpect[i - 1] += dP*nS;\n }\n}\n\nint main(int argc, char* argv[]){\n t_Params tParams;\n t_SIParams* atSIParams;\n int i = 0, nSamples = 0, nMax = 0; \n t_Data tData;\n double* adExpect = NULL;\n double dShift = 0.0;\n\n gsl_set_error_handler_off();\n\n getCommandLineParams(&tParams, argc, argv);\n\n /*allocate memory for samples*/\n atSIParams = (t_SIParams *) malloc(MAX_SAMPLES*sizeof(t_SIParams));\n if(!atSIParams)\n goto memoryError;\n \n /*read in Monte-Carlo samples*/\n readSamples(&tParams, atSIParams, &nSamples);\n\n readAbundanceData(tParams.szAbundFile, &tData);\n\n nMax = 1000;//tData.aanAbund[tData.nNA - 1][0];\n nMax = floor(pow(2.0,ceil(log((double) nMax)/log(2.0)) + 2.0) + 1.0e-7);\n\n adExpect = (double *) malloc(sizeof(double)*nMax);\n\n for(i = 0; i < nMax; i++){\n adExpect[i] = 0.0;\n }\n\n dShift = 5.0e5/(double) tData.nJ;\n for(i = 0; i < nSamples; i++){\n updateExpectations(adExpect, nMax, \n\t\t atSIParams[i].dAlpha*sqrt(dShift), \n\t\t atSIParams[i].dBeta*dShift, \n\t\t atSIParams[i].dGamma,\n\t\t atSIParams[i].nS, \n\t\t &tData);\n }\n\n for(i = 1; i <= nMax; i++){\n printf(\"%d %f\\n\",i,adExpect[i - 1]/((double) nSamples));\n }\n\n free(adExpect);\n exit(EXIT_SUCCESS);\n \n memoryError:\n fprintf(stderr, \"Failed to allocate memory in main aborting ...\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\n\n\nint intCompare(const void *pvA, const void *pvB)\n{\n int* pnA = (int *) pvA, *pnB = (int *) pvB;\n\n if(*pnA < *pnB)\n return +1;\n else if(*pnA == *pnB){\n return 0;\n }\n else{\n return -1;\n }\n}\n\nint doubleCompare(const void *pvA, const void *pvB)\n{\n double* pnA = (double *) pvA, *pnB = (double *) pvB;\n\n if(*pnA < *pnB)\n return +1;\n else if(*pnA == *pnB){\n return 0;\n }\n else{\n return -1;\n }\n}\n\nvoid writeUsage(FILE* ofp)\n{\n int i = 0;\n char *line;\n\n for(i = 0; i < nLines; i++){\n line = usage[i];\n fputs(line,ofp);\n }\n}\n\nchar *extractParameter(int argc, char **argv, char *param,int when)\n{\n int i = 0;\n\n while((i < argc) && (strcmp(param,argv[i]))){\n i++;\n }\n\n if(i < argc - 1){\n return(argv[i + 1]);\n }\n\n if((i == argc - 1) && (when == OPTION)){\n return \"\";\n }\n\n if(when == ALWAYS){\n fprintf(stdout,\"Can't find asked option %s\\n\",param);\n }\n\n return (char *) NULL;\n}\n\nvoid getCommandLineParams(t_Params *ptParams,int argc,char *argv[])\n{\n char *szTemp = NULL;\n char *cError = NULL;\n\n /*get parameter file name*/\n ptParams->szInputFile = extractParameter(argc,argv, INPUT_FILE,ALWAYS); \n if(ptParams->szInputFile == NULL)\n goto error;\n\n /*get abundance file name*/\n ptParams->szAbundFile = extractParameter(argc,argv, ABUND_FILE,ALWAYS); \n if(ptParams->szAbundFile == NULL)\n goto error;\n\n /*get long seed*/\n szTemp = extractParameter(argc,argv,SEED,OPTION); \n if(szTemp != NULL){\n ptParams->lSeed = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->lSeed = 0;\n }\n\n /*get burn*/\n szTemp = extractParameter(argc, argv, BURN, OPTION); \n if(szTemp != NULL){\n ptParams->nBurn = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->nBurn = DEF_BURN;\n }\n\n /*get long seed*/\n szTemp = extractParameter(argc, argv, SAMPLE, OPTION); \n if(szTemp != NULL){\n ptParams->nSample = strtol(szTemp,&cError,10);\n if(*cError != '\\0'){\n goto error;\n }\n }\n else{\n ptParams->nSample = DEF_SAMPLE;\n }\n \n /*verbosity*/\n szTemp = extractParameter(argc, argv, VERBOSE, OPTION);\n if(szTemp != NULL){\n verbose = TRUE;\n }\n\n return;\n\n error:\n writeUsage(stdout);\n exit(EXIT_FAILURE);\n}\n\nvoid readSamples(t_Params *ptParams, t_SIParams *atSIParams, int *pnSamples)\n{\n int nSamples = 0;\n char *szInputFile = ptParams->szInputFile;\n char szLine[MAX_LINE_LENGTH];\n FILE *ifp = NULL;\n\n ifp = fopen(szInputFile, \"r\");\n\n if(ifp){\n while(fgets(szLine, MAX_LINE_LENGTH, ifp)){\n char *szTok = NULL, *szBrk = NULL, *pcError = NULL;\n int nTime = 0;\n\n /*remove trailing new line*/\n szBrk = strpbrk(szLine, \"\\n\"); (*szBrk) = '\\0';\n \n szTok = strtok(szLine, DELIM);\n\n nTime = strtol(szTok, &pcError, 10);\n if(*pcError != '\\0') goto fileFormatError;\n\n if(nTime > ptParams->nBurn && nTime % ptParams->nSample == 0){\n\t\n\tszTok = strtok(NULL,DELIM);\n\tatSIParams[nSamples].dAlpha = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatSIParams[nSamples].dBeta = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tszTok = strtok(NULL,DELIM);\n\tatSIParams[nSamples].dGamma = strtod(szTok, &pcError);\n\tif(*pcError != '\\0') goto fileFormatError;\t\n\n\tszTok = strtok(NULL,DELIM);\n\tatSIParams[nSamples].nS = strtol(szTok, &pcError, 10);\n\tif(*pcError != '\\0') goto fileFormatError;\n\n\tnSamples++;\n }\n }\n\n fclose(ifp);\n }\n else{\n fprintf(stderr, \"Failed to open file %s aborting\\n\", szInputFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n (*pnSamples) = nSamples;\n return;\n\n fileFormatError:\n fprintf(stderr, \"Incorrectly formatted input file aborting\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid readAbundanceData(const char *szFile, t_Data *ptData)\n{\n int **aanAbund = NULL;\n int i = 0, nNA = 0, nA = 0, nC = 0;\n int nL = 0, nJ = 0;\n char szLine[MAX_LINE_LENGTH];\n FILE* ifp = NULL;\n\n ifp = fopen(szFile, \"r\");\n\n if(ifp){\n char* szTok = NULL;\n char* pcError = NULL;\n\n fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n szTok = strtok(szLine, DELIM2);\n \n nNA = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n goto formatError;\n }\n \n aanAbund = (int **) malloc(nNA*sizeof(int*));\n\n for(i = 0; i < nNA; i++){\n aanAbund[i] = (int *) malloc(sizeof(int)*2);\n\n fgets(szLine, MAX_LINE_LENGTH, ifp);\n\n szTok = strtok(szLine, DELIM2);\n\n nA = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n\n szTok = strtok(NULL, DELIM2);\n\n nC = strtol(szTok,&pcError,10);\n if(*pcError != '\\0'){\n\tgoto formatError;\n }\n \n nL += nC;\n nJ += nC*nA;\n\n aanAbund[i][0] = nA;\n aanAbund[i][1] = nC; \n }\n }\n else{\n fprintf(stderr, \"Failed to open abundance data file %s aborting\\n\", szFile);\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n\n ptData->nJ = nJ;\n ptData->nL = nL;\n ptData->aanAbund = aanAbund;\n ptData->nNA = nNA;\n return;\n\n formatError:\n fprintf(stderr, \"Incorrectly formatted abundance data file\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\ndouble fX(double x, double dA, double dB, double dNDash)\n{\n double dTemp1 = (dA*(x - dB)*(x - dB))/x;\n\n return log(x) - (1.0/dNDash)*(x + dTemp1);\n}\n\ndouble f2X(double x, double dA, double dB, double dNDash)\n{\n double dRet = 0.0, dTemp = 2.0*dA*dB*dB;\n\n dRet = (1.0/(x*x))*(1.0 + (1.0/dNDash)*(dTemp/x));\n\n return -dRet;\n}\n\n\ndouble sd(int n, double dAlpha, double dBeta, double dGamma)\n{\n double dA = 0.5*(-1.0 + sqrt(1.0 + (dAlpha*dAlpha)/(dBeta*dBeta)));\n double dN = (double) n, dNDash = dN + dGamma - 1.0, dRN = 1.0/dN;\n double dTemp1 = (0.5*dN)/(1.0 + dA), dTemp2 = 4.0*dRN*dRN*(1.0 + dA)*dA*dBeta*dBeta;\n double dXStar = dTemp1*(1.0 + sqrt(1.0 + dTemp2));\n double dFX = fX(dXStar, dA, dBeta, dNDash);\n double d2FX = -dNDash*f2X(dXStar, dA, dBeta, dNDash);\n double dLogK = 0.0, dGamma1 = dGamma;\n\n if(dGamma1 < 0.0){\n dGamma1 *= -1.0;\n }\n\n dLogK = gsl_sf_bessel_lnKnu(dGamma1,2.0*dA*dBeta);\n\n return -2.0*dA*dBeta -log(2.0) -dLogK -dGamma*log(dBeta) + dNDash*dFX + 0.5*log(2.0*M_PI) - 0.5*log(d2FX);\n}\n\nint bessel(double* pdResult, int n, double dAlpha, double dBeta, double dGamma)\n{\n double dResult = 0.0;\n double dOmega = 0.0, dGamma2 = 0.0;\n double dLogK1 = 0.0, dLogK2 = 0.0;\n double dN = (double) n, dNu = dGamma + dN;\n double dTemp1 = 0.0;\n \n if(dNu < 0.0){\n dNu = -dNu;\n }\n\n if(dGamma < 0.0){\n dGamma2 = -dGamma;\n }\n else{\n dGamma2 = dGamma;\n }\n\n dOmega = sqrt(dBeta*dBeta + dAlpha*dAlpha) - dBeta;\n\n dLogK2 = gsl_sf_bessel_lnKnu(dNu, dAlpha);\n\n if(!gsl_finite(dLogK2)){\n if(dAlpha < 0.1*sqrt(dNu + 1.0)){\n //printf(\"l \");\n dLogK2 = gsl_sf_lngamma(dNu) + (dNu - 1.0)*log(2.0) - dNu*log(dAlpha);\n }\n else{\n //printf(\"sd \");\n (*pdResult) = dResult;\n return FALSE;\n }\n }\n \n dLogK1 = dGamma*log(dOmega/dAlpha) -gsl_sf_bessel_lnKnu(dGamma2,dOmega);\n \n dTemp1 = log((dBeta*dOmega)/dAlpha);\n\n dResult = dN*dTemp1 + dLogK2 + dLogK1;\n (*pdResult) = dResult;\n return TRUE;\n}\n\ndouble logLikelihood(int n, double dAlpha, double dBeta, double dGamma)\n{\n double dLogFacN = 0.0;\n int status = 0;\n double dRet = 0.0;\n\n if(n < 50){\n dLogFacN = gsl_sf_fact(n);\n dLogFacN = log(dLogFacN);\n }\n else{\n dLogFacN = gsl_sf_lngamma(((double) n) + 1.0);\n }\n\n status = bessel(&dRet,n, dAlpha,dBeta,dGamma);\n if(status == FALSE){\n dRet = sd(n, dAlpha,dBeta,dGamma);\n }\n \n return dRet - dLogFacN;\n}\n", "meta": {"hexsha": "036f1eb74c42dbfdd19f8493b88011af301a6953", "size": 10092, "ext": "c", "lang": "C", "max_stars_repo_path": "SIShift/SIShift.c", "max_stars_repo_name": "chrisquince/DiversityEstimates", "max_stars_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-18T17:56:16.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-19T13:22:59.000Z", "max_issues_repo_path": "SIShift/SIShift.c", "max_issues_repo_name": "chrisquince/DiversityEstimates", "max_issues_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SIShift/SIShift.c", "max_forks_repo_name": "chrisquince/DiversityEstimates", "max_forks_repo_head_hexsha": "f8ce1a8afd10311420227a6259739c7938695b79", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9869281046, "max_line_length": 119, "alphanum_fraction": 0.5927467301, "num_tokens": 3464, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.727975460709318, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3497766870129292}} {"text": "#include \n#include \n#include \n#include \"global.h\"\n#include \"utility.h\"\n#include \"constants.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"steppmethods.h\"\n\n#define NUMBER_SAMPLES 1\n#define NUMBER_VOLUMES 1\t\n#define SHIFT_LATE 200\n#define BINS 100\t\t\t\n#define PDF_NR 12\n\n\n\n// regular main but with multiple sampling runs over multiple volume fractions phi.\n\n\nint\nmain (void){\n\tFILE *source, *target;\n \tsource = fopen(\"global.h\", \"r\"); // get source global.h at program start so as to not copy edits during run\n\n \tif( source == NULL )\n \t{\n \t\tprintf(\"cannot open global.h\\n\");\n \t\texit(EXIT_FAILURE);\n \t}\n \tSETNUMTHREADS\n \tint i,j,l,k,m ,n;\n\tConstants();\t\t\t\t\t\t\t\t\t// draw coupling constants and other derived constants\n\tdouble *t = calloc(LENGTH_T, sizeof(double));\n\ttime_t tme = time(NULL);\n\tchar ordnerLABEL[300];\n\tchar ueberordnerLABEL[300];\n\tchar ordnerLABEL_original[300];\n\tstrftime(ordnerLABEL, sizeof ordnerLABEL, \"%A %c\", localtime(&tme));\n \tdouble squares_all_calcs[LENGTH_T][NUMBER_SAMPLES];\t\t\t// for printing all squares in shared table\n \ti = 0;\n \tprintf(\"\\n%s\\n\", ordnerLABEL);\n \tdeleteSpaces(ordnerLABEL,ordnerLABEL);\n \tstrcpy (ordnerLABEL_original, ordnerLABEL); \t// keep original, change ordnerLABEL per run\n \tdouble alpha_global = ALPHA;\n \tdouble temp_global = TEMP;\t\t\t\t\t\t// macros from global make trouble when used as print arguments, hence copy to memory\n \tsprintf(ueberordnerLABEL,\"N=%d_SIM=%d_T=%1.1E_ALPH=%1.1f\", OSSZI, SIMULATIONEN, temp_global, alpha_global);\n \tchar tempLABEL[300];\n \tstrcpy (tempLABEL, ordnerLABEL);\n \tstrcat(tempLABEL, LABELPREFIX);\n \tstrcat(tempLABEL, ueberordnerLABEL);\n \tstrcpy (ueberordnerLABEL, tempLABEL);\n \tstruct stat st2 = {0};\n\n \tdouble prob_density[BINS][PDF_NR];\n \tfor (i = 0; i < BINS ; i++)\n \t{\n \t\tfor (j = 0; j < PDF_NR; j++)\n \t\t{\n \t\t\tprob_density[i][j] = 0.0;\n \t\t}\n \t}\n \tint check_times[PDF_NR];\n \tfor (j = 0; j < PDF_NR; j++)\n \t{\n \t\tcheck_times[j] = (int) ( 10.0 * (j+1)) ;\n \t}\n \tcheck_times[PDF_NR-1] = LENGTH_T - 1;\n \tfor (j = 0; j < PDF_NR; j++)\n \t{\n \t\tprintf(\"check times nr %d is %d \\n\", j, check_times[j]);\n \t}\n \tprintf(\"\\nprint results into \");\n \tprintf(ueberordnerLABEL);\n\n \tif (stat(ueberordnerLABEL, &st2) == -1)\n\t{\t\t\t\t\t\t\t\t\t\t\t\t//Teste ob Ordner existiert, erstelle Ordner\n\t\tmkdir(ueberordnerLABEL, 0700);\t\n\t}\n\tif (chdir(ueberordnerLABEL))\t\t\t\t\t\t// change into directory of simulation\n\t{\n\t\tprintf(\"Error changing directory\");\n\t\treturn 1;\n\t}\n\n \t// reserviere speicher fuer eine Vollständige trajektorie ------------------\n\tm = LENGTH_T; n = ORDER;\n\tdouble **z = (double **) malloc(m * sizeof(double *));\n\tz[0] = (double *) malloc(m* n * sizeof(double));\n\tfor (i=1; i MAX_NR_PLOTS ) n_zplots = MAX_NR_PLOTS; // speichere maximal 30*DIM trajectorien\n \t// reserviere speicher fuer samplepfade massives Teilchen zum plotten ------------------\t\n\tm = LENGTH_T; n = DIM*n_zplots;\n\tdouble **zplots = (double **) malloc(m * sizeof(double *));\n\tzplots[0] = (double *) malloc(m* n * sizeof(double));\n\tfor (i=1; i 0.95)\n \t{\n \t\tDIFF_COEFF = KBOLTZ * TEMP/GAMMA;\n \t}\n \tLATTICE_SPACING = sqrt(2*DIM*DIFF_COEFF * pow( TIME_ARRIVAL, ALPHA) );\n \tprintf(\"LATTICE_SPACING = %3.3E\\n\", LATTICE_SPACING);\n \tdouble latlength = LATTICE_SPACING;\n\n\t\t//------------------------------EIGENTLICHE SIMULATION ------------------------------------------------------------------\n \tint sim_count = 0;\n \tstart = clock();\n \ttime_first_contact = 0.0;\n \tint error_count = 0;\n\t\t// \n \tfor (i = 0; i < SIMULATIONEN; i++)\n \t{\n\n\t\tvec_zero_i(lattice_position,DIM);\t\t// set stating cell to zero !\n\t\tTARGET_CONTACT = 0;\n\t\tFLAG_DUMP_VALUE = 0;\t\t\t\t\t// set to 1 if error occures\n\t\t// -------------------------BAD\n\t\tBath_Setup(y, LABEL, r);\t\t\t\t// draw intial conditions\n\t\t//---------------------Bad aufgesetzt\t\n\t\tVVerlet_parallel(ORDER, y, z, t, Poti_Handle);\n\t\tend = clock();\n\t\t//------------------------------auswertung Integrationsergebnisse\n\t\tif ( !(FLAG_DUMP_VALUE))\t\t\t// only count result without err\n\t\t{\n\t\t \tdouble *kahan_c = calloc(LENGTH_T, sizeof(double)); //\n\t\t \tdouble *kahan_t = calloc(LENGTH_T, sizeof(double));\n\t\t \tdouble *kahan_y = calloc(LENGTH_T, sizeof(double));\n\t\t \t#pragma omp parallel for\n\t\t \tfor(l = 0; l < LENGTH_T; l++)\n\t\t \t{\n\t\t \t\tif (l>10)\n\t\t \t\t{\n\t\t \t\t\tlong_correlation_x[l] += z[1][0] *z[l][0]/((double) SIMULATIONEN);\n\t\t \t\t\tlong_correlation_y[l] += z[1][1] *z[l][1]/((double) SIMULATIONEN);\n\t\t \t\t}\n\t\t \t\tkahan_y[l] = z[10][DIM] * z[l][DIM] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP)\\\n\t\t \t\t\t\t\t- kahan_c[l];\n\t\t \t\tkahan_t[l] = px_correlation[l] + kahan_y[l];\n\t\t \t\tkahan_c[l] = (kahan_y[l] - px_correlation[l]) - kahan_y[l];\n\t\t \t\tpx_correlation[l] = kahan_t[l];\n\t\t \t\tpy_correlation[l] += z[10][DIM + 1] * z[l][DIM + 1] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP);\n\t\t \t\tpx_correlation_late[l] += z[SHIFT_LATE][DIM] * z[l][DIM] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP);\n\t\t \t\tpx_correlation_late2[l] += z[SHIFT_LATE * 2][DIM] * z[l][DIM] / ((double) SIMULATIONEN) / (mass * KBOLTZ * TEMP);\n\t\t \t\tfor(j=0; j< DIM; j++)\n\t\t \t\t{\n\t\t \t\t\tif (i < n_zplots)\n\t\t \t\t\t{\n\t\t \t\t\t\tzplots[l][DIM * i + j] = z[l][j];\n\t\t \t\t\t\tqplots[l][DIM * i + j] = z[l][2*DIM + j];\n\t\t \t\t\t\tdouble Force_TEMP = 0.0;\n\t\t \t\t\t\tfor(int os = 0; os < OSSZI; os++)\n\t\t \t\t\t\t\t{\n\t\t \t\t\t\t\t\tForce_TEMP += (pow(coupling[os],2.0)/pow(ommega[os],2.0) - coupling[os]) * z[l][(2 + 2 * os) * DIM + j];\n\t\t \t\t\t\t\t}\n\t\t \t\t\t\t\tZwanzig_Force[l][DIM * i + j]=Force_TEMP;\n\t\t \t\t\t\t\tint i_last = OSSZI -1;\n\t\t \t\t\t\t\tqlplots[l][DIM * i + j] = z[l][2*OSSZI*DIM + j];\n\t\t \t\t\t} \n\t\t \t\t\tsquares[l] = squares[l] + pow(z[l][j],2.0)/((double) SIMULATIONEN);\n\t\t \t\t\tEKIN[l] = EKIN[l] + pow(z[l][DIM+j],2.0)/(mass * SIMULATIONEN * KBOLTZ *TEMP * DIM);\n\t\t \t\t\tfor(k=0;k lower) \n\t\t\t \t\t\t\t)\n\t\t\t \t\t\t{\n\t\t\t \t\t\t\tprob_density[i_bin][j] += 1.0/sims;\n\t\t\t \t\t\t}\n\t\t\t \t\t}\n\t\t\t \t}\n\t\t\t}\n\t\t\tsim_count += 1;\n\t\t\t//printf(\"%d und t %4.2f \\n\", i ,((double) (end - start)));\n\t\t\tprintf(\"\\r%d von %d mit t/count = %4.2f s und average t_rest =%4.2f h \", sim_count , SIMULATIONEN, (double) (end - start) / sim_count/ THREADS / CLOCKS_PER_SEC ,\\\n\t\t\t \t\t((double) (end - start) / sim_count/ THREADS/ CLOCKS_PER_SEC * (SIMULATIONEN - sim_count)/3600));\n\t\t\tprintf(\" %d hits on Lat and avrgtcntct = %4.2f\",TARGET_CONTACT, time_first_contact/(i+1) );\n\t\t\tfflush(stdout);\n\t\t\tfor(l = 0; l < LENGTH_T; l++)\n\t\t\t{\n\t\t\t \tfor (int oss_i=0; oss_i < OSSZI; oss_i++)\n\t\t\t \t{\n\t\t\t \t\ttotal_momentum_x[l] += z[l][(3 + 2*oss_i) *DIM + 0];\n\t\t\t \t\ttotal_momentum_y[l] += z[l][(3 + 2*oss_i) *DIM + 1];\n\t\t\t \t}\n\t\t\t \ttotal_momentum_x[l] += z[l][(0 + 2*0) *DIM + 0];\n\t\t\t \ttotal_momentum_y[l] += z[l][(0 + 2*0) *DIM + 1];\n\t\t\t} \n\t\t\t// -------------- end evaluation if----------------------\n\t\t\tfree(kahan_y); free(kahan_t); free(kahan_c);\n\t\t}else\n\t\t{\n\t\t\terror_count++;\n\t\t\tprintf(\"\\n err occured at calc %d, calculation dumped, %d totatl errors\\n\", i,error_count );\n\t\t\ti -= 1;\t\t// do one more calculation\n\t\t}\n\n\t}\n\ttme = time(NULL);\n\tchar end_label[90];\n\tstrftime( end_label, sizeof end_label, \"%A %c\", localtime(&tme));\n\tprintf(\"\\n%s\\n\", end_label);\n\tfor(l = 0; l < LENGTH_T; l++)\n\t{\n\t\tETOT[l] = EKIN[l] + EBAD[l];\n\t\t\t \tPTOT[l] = sqrt(pow(PTOT[l]/((double) SIMULATIONEN),2.0) + pow(PTOTY[l]/((double) SIMULATIONEN),2.0)); \n\t}\n\tfor(l = 1; l < LENGTH_T; l++)\n\t{\n\t\tsquares_increase[l] = (squares[l]- squares[l-1])/(t[l] - t[l-1]);\n\t}\n\t\t\t//------------------------------ENDE SIMULATION, speichere daten ------------------------------------------------------------------\n\tfor(m=0; m<80; m++)\n\t{\n\t\tfor(n=0; n<80; n++)\n\t\t{\n\t\t\tP_density[m][n] *= 1.0/DENSITY_POINTS;\n\t\t}\n\t}\n\tFILE *fp;\n\n\tstruct stat st = {0}; \t\t\t\n\n\tif (stat(ordnerLABEL, &st) == -1){\t\t//Teste ob Ordner existiert, erstelle Ordner\n\t\tmkdir(ordnerLABEL, 0700);\t\n\t}\n\n\tfp = fopen (\"shellscript.sh\", \"w\");\t\t//create Shellscript to start Gnuplot from c main()\n\tfprintf(fp, \"cd %s\\n\", ordnerLABEL);\n\tfprintf(fp, \"gnuplot gnuplot.txt\\n\");\n\tfprintf(fp, \"cd ..\");\n\tfclose (fp);\n\n\n\t // copy global.h \t/\n\n\n \t// copy to same name into directory, clould be anything different\n\n \tif (chdir(ordnerLABEL))\t\t\t// change into directory of simulation\n \t{\n \t\tprintf(\"Error changing directory\");\n \t\treturn 1;\n \t}\n\n \tmkdir(\"plots\", 0700);\n \tmkdir(\"trajec\", 0700);\n\n \ttarget = fopen(\"global.h\", \"w\");\n\n \tif( target == NULL )\n \t{\n \t\tfclose(source);\n \t\tprintf(\"Press any key to exit...\\n\");\n \t\texit(EXIT_FAILURE);\n \t}\n \tchar ch;\n \twhile( ( ch = fgetc(source) ) != EOF )\n \t{\n \t\tfputc(ch, target);\n \t}\n\n \tprintf(\"File copied successfully.\\n\");\n\n\n \tfclose(target);\n\n \tfp = fopen (\"latlength.dat\", \"w\");\n \tfprintf(fp, \"%lf \\n\", latlength);\n \tfclose (fp);\n\n\n \tfp = fopen (\"squares_rohdaten.dat\", \"w\");\n \tfor(l = 0; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l], squares[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"ekin.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, EKIN[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"ekinbath.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, bathp[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"ommega.dat\", \"w\");\n \tfor(l = 0; l < OSSZI; l++){\n \t\tfprintf(fp, \"%lf\\n\", ommega[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PTOT.dat\", \"w\");\n \tfor(l = 0; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, PTOT[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"P_X.dat\", \"w\");\n \tfor(l = 0; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %1.3e\\n\", t[l]/TIME_ARRIVAL, total_momentum_x[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"P_Y.dat\", \"w\");\n \tfor(l = 0; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %1.3e\\n\", t[l]/TIME_ARRIVAL, total_momentum_y[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"xshortcorellation.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, short_correlation_x[l]/latlength/latlength);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"yshortcorellation.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, short_correlation_y[l]/latlength/latlength);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"xlongcorellation.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, long_correlation_x[l]/latlength/latlength);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"ylongcorellation.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l]/TIME_ARRIVAL, long_correlation_y[l]/latlength/latlength);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PX_corr.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, px_correlation[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PY_corr.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, py_correlation[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PX_corr_late.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, px_correlation_late[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PX_corr_late2.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, px_correlation_late2[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PX_corr_abs.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, fabs(px_correlation[l]));\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PX_corr_late_abs.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, fabs(px_correlation_late[l]));\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"PX_corr_late2_abs.dat\", \"w\");\n \tfor(l = 1; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%1.3E %1.3E\\n\", t[l]/TIME_ARRIVAL, fabs(px_correlation_late2[l]));\n \t}\n \tfclose (fp);\n\n\n \tif (DIM == 1)\n \t{\n \t\tfp = fopen (\"PDF_1D.dat\", \"w\");\n \t\tfor (int pos = 0; pos < BINS; pos++)\n \t\t{\n \t\t\tfprintf(fp, \"%1.3E \", -LATTICE_SPACING/2.0 + pos*LATTICE_SPACING/((double) BINS));\n \t\t\tfor(j = 0; j < PDF_NR; j++)\n \t\t\t{\n \t\t\t\tfprintf(fp, \"%1.3E \", prob_density[pos][j]);\n \t\t\t}\n \t\t\tfprintf(fp,\"\\n\");\n \t\t}\n \t\tfclose (fp);\n \t}\n\n\n\t// finde größtes s^2/t^alpha zum endzeitpunkt\n \tint t_start = 10;\n \tdouble temp_ende = 0.0;\n \tfor(int i_alpha = 1; i_alpha < 12; i_alpha ++){\n \t\tdouble alpha_temp = 0.45 + 0.05 * i_alpha;\n \t\tl = LENGTH_T-1;\n \t\tif (temp_ende < (squares[l] / (pow(t[l], alpha_temp))) )\n \t\t{\n \t\t\ttemp_ende = squares[l] / (pow(t[l], alpha_temp));\n \t\t}\n \t}\n \tif (DIM>1) \n \t{\n\n \t\tchar zplotsLABEL[30];\n \t\tfor (i = 0; i < n_zplots; i++)\n \t\t{\n \t\t\tsprintf(zplotsLABEL, \"trajec/zplots%d.dat\",i);\n \t\t\tfp = fopen (zplotsLABEL, \"w\");\n \t\t\tfor(l = 0; l < LENGTH_T; l++){\n \t\t\t\tfor (j = 0; j < DIM ; j++){\n \t\t\t\t\tfprintf(fp, \"%lf \", ((zplots[l][j +i*DIM])/latlength) );\n \t\t\t\t}\t\n \t\t\t\tfprintf(fp, \"\\n\");\n \t\t\t}\n \t\t\tfclose (fp);\n \t\t}\n \t\tfor (i = 0; i < n_zplots; i++)\n \t\t{\n \t\t\tsprintf(zplotsLABEL, \"trajec/qplots%d.dat\",i);\n \t\t\tfp = fopen (zplotsLABEL, \"w\");\n \t\t\tfor(l = 0; l < LENGTH_T; l++){\n \t\t\t\tfor (j = 0; j < DIM ; j++){\n \t\t\t\t\tfprintf(fp, \"%lf \", ((qplots[l][j +i*DIM])) );\n \t\t\t\t}\t\n \t\t\t\tfprintf(fp, \"\\n\");\n \t\t\t}\n \t\t\tfclose (fp);\n \t\t}\n \t\tfor (i = 0; i < n_zplots; i++)\n \t\t{\n \t\t\tsprintf(zplotsLABEL, \"trajec/Zwanzig_Force%d.dat\",i);\n \t\t\tfp = fopen (zplotsLABEL, \"w\");\n \t\t\tfor(l = 0; l < LENGTH_T; l++){\n \t\t\t\tfor (j = 0; j < DIM ; j++){\n \t\t\t\t\tfprintf(fp, \"%lf \", ((Zwanzig_Force[l][j +i*DIM])) );\n \t\t\t\t}\t\n \t\t\t\tfprintf(fp, \"\\n\");\n \t\t\t}\n \t\t\tfclose (fp);\n \t\t}\n \t\tfor (i = 0; i < n_zplots; i++)\n \t\t{\n \t\t\tsprintf(zplotsLABEL, \"trajec/qlplots%d.dat\",i);\n \t\t\tfp = fopen (zplotsLABEL, \"w\");\n \t\t\tfor(l = 0; l < LENGTH_T; l++){\n \t\t\t\tfor (j = 0; j < DIM ; j++){\n \t\t\t\t\tfprintf(fp, \"%lf \", ((qlplots[l][j +i*DIM])) );\n \t\t\t\t}\t\n \t\t\t\tfprintf(fp, \"\\n\");\n \t\t\t}\n \t\t\tfclose (fp);\n \t\t}\n \t}\n \tif (DIM==1) \n \t{\n\n \t\tchar zplotsLABEL[30];\n \t\tfor (i = 0; i < n_zplots; i++)\n \t\t{\n \t\t\tsprintf(zplotsLABEL, \"trajec/zplots%d.dat\",i);\n \t\t\tfp = fopen (zplotsLABEL, \"w\");\n \t\t\tfor(l = 0; l < LENGTH_T; l++){\n \t\t\t\tfprintf(fp, \" %lf %lf \\n\" ,t[l]/TIME_ARRIVAL, zplots[l][i*DIM]/latlength);\n \t\t\t}\n \t\t\tfclose (fp);\n \t\t}\n \t}\n\n\n\n \tfp = fopen (\"ETOT.dat\", \"w\");\n \tfor(l = 0; l < LENGTH_T; l++){\n \t\tfprintf(fp, \"%lf %lf\\n\", t[l], ETOT[l]);\n \t}\n \tfclose (fp);\n\n \tfp = fopen (\"DENSITY.dat\", \"w\");\n \tfor(m=0; m<80; m++)\n \t{\n \t\tfor(n=0; n<80; n++)\n \t\t{\n \t\t\tfprintf(fp, \"%1.2e \", P_density[m][n]);\n \t\t}\n \t\tfprintf(fp, \"\\n\");\n \t}\n \tfclose (fp);\n\n\n\tgsl_rng_free (r); gsl_rng_free (RAND_GLOBAL);\n\tfree(zplots[0]); free(zplots);\n\tfree(qplots[0]); free(qplots);\n\tfree(Zwanzig_Force[0]); free(Zwanzig_Force);\n\tfree(qlplots[0]); free(qlplots);\n\tfree (P_density[0]); free (P_density);\n\tfree(t);\n\tfree(bathp); free(bathq);\n\tfree(squares_increase);\n\tfree(short_correlation_x);\n\tfree(total_momentum_x);\n\tfree(total_momentum_y);\n\tfree(short_correlation_y);\n\tfree(long_correlation_x);\n\tfree(px_correlation); free(py_correlation);\n\tfree(px_correlation_late);\n\tfree(px_correlation_late2);\n\tfree(long_correlation_y);\n\tfree(ETOT); free(EKIN); free(EBAD);\n\tfree(PTOT); free(PTOTY);free(LTOT);\n\tfree(squares);\n\tfree(z[0]); free(z);\n}\n", "meta": {"hexsha": "398f90c5ecbb1d6f68f6e6cf754d2bb0209fd717", "size": 20921, "ext": "c", "lang": "C", "max_stars_repo_path": "main_github.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": "main_github.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": "main_github.c", "max_forks_repo_name": "nowottnm/KAC_ZWANZIG_SIM", "max_forks_repo_head_hexsha": "b8cacd50b7d307aeaa503b5a2f41cef4300f15a3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6984848485, "max_line_length": 166, "alphanum_fraction": 0.5600114717, "num_tokens": 7166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217431943271999, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.349598029294549}} {"text": "/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef EKF_TYPES_H\n#define EKF_TYPES_H\n\n#include \n#include \n#include \"ukf_math.h\"\n\n/**\n * @short Extended Kalman Filter in the case of additive noise, the notations follow Van Der Merwe, phD, p. 36\n */\nnamespace ekf\n{\n\n class EvolutionNoise;\n\n /**\n * @short Structure holding the parameters of the statistical linearization\n *\n */\n typedef struct\n {\n\n /**\n * @short Evolution noise type\n */\n EvolutionNoise *evolution_noise;\n\n /**\n * @short Covariance of the observation noise\n */\n double observation_noise;\n\n /**\n * @short Prior estimate of the covariance matrix\n */\n double prior_pk;\n\n /**\n * @short Number of parameters to estimate\n */\n int n;\n\n /**\n * @short Dimension of the output\n */\n int no;\n\n /**\n * @short Is the observation gradient diagonal ? In that case, simplifications can be introduced\n */\n bool observation_gradient_is_diagonal;\n\n } ekf_param;\n\n typedef struct\n {\n /**\n * @short Current estimate of the state\n */\n gsl_vector * xk;\n\n /**\n * @short Predicted state\n */\n gsl_vector * xkm;\n\n /**\n * @short Variance-Covariance of the state\n */\n gsl_matrix * Pxk;\n\n /**\n * @short Jacobian of the evolution function\n */\n gsl_matrix *Fxk;\n\n /**\n * @short Variance covariance of the evolution noise\n */\n gsl_matrix * Rv;\n\n /**\n * @short Current observation\n */\n gsl_vector * yk;\n\n /**\n * @short Current innovations\n */\n gsl_vector * ino_yk;\n\n /**\n * @short Jacobian of the observation function\n */\n gsl_matrix *Hyk;\n\n /**\n * @short Variance covariance of the observation noise\n */\n gsl_matrix * Rn;\n\n /**\n * @short Kalman gain\n */\n gsl_matrix *Kk;\n\n /**\n * @short Temporary matrices\n */\n gsl_matrix * temp_n_n;\n gsl_matrix * temp_n_1;\n gsl_matrix * temp_no_no;\n gsl_matrix * temp_n_no;\n gsl_matrix * temp_2_n_n;\n gsl_vector * temp_no;\n\n /**\n * @short Optional parameters (this must be allocated and initialized from the user side!\n */\n gsl_vector * params;\n\n\n\n } ekf_state;\n\n /**\n * @short Mother class from which the evolution noises inherit\n */\n class EvolutionNoise\n {\n protected:\n double _initial_value;\n public:\n EvolutionNoise(double initial_value) : _initial_value(initial_value) {};\n void init(ekf_param &p, ekf_state &s)\n {\n gsl_matrix_set_identity(s.Rv);\n gsl_matrix_scale(s.Rv, _initial_value);\n }\n\n virtual void updateEvolutionNoise(ekf_param &p, ekf_state &s) = 0;\n };\n\n /**\n * @short Annealing type evolution noise\n */\n class EvolutionAnneal : public EvolutionNoise\n {\n double _decay, _lower_bound;\n public:\n EvolutionAnneal(double initial_value, double decay, double lower_bound) : EvolutionNoise(initial_value),\n _decay(decay),\n _lower_bound(lower_bound)\n { };\n\n void updateEvolutionNoise(ekf_param &p, ekf_state &s)\n {\n for(int i = 0 ; i < p.n ; ++i)\n\t{\n\t for(int j = 0 ; j < p.n ; ++j)\n\t {\n\t if(i == j)\n\t\tgsl_matrix_set(s.Rv, i, i, ukf::math::max(_decay * gsl_matrix_get(s.Rv,i,i),_lower_bound));\n\t else\n\t\tgsl_matrix_set(s.Rv, i, j, 0.0);\n\t }\n\t}\n }\n };\n\n /**\n * @short Forgetting type evolution noise\n */\n class EvolutionRLS : public EvolutionNoise\n {\n double _decay;\n public:\n EvolutionRLS(double initial_value, double decay) : EvolutionNoise(initial_value), _decay(decay)\n {\n if(ukf::math::cmp_equal(_decay, 0.0))\n\tprintf(\"Forgetting factor should not be null !!\\n\");\n };\n\n void updateEvolutionNoise(ekf_param &p, ekf_state &s)\n {\n gsl_matrix_memcpy(s.Rv, s.Pxk);\n gsl_matrix_scale(s.Rv, 1.0 / _decay - 1.0);\n }\n };\n\n /**\n * @short Robbins-Monro evolution noise\n */\n class EvolutionRobbinsMonro : public EvolutionNoise\n {\n double _alpha;\n public:\n EvolutionRobbinsMonro(double initial_value, double alpha) : EvolutionNoise(initial_value),\n _alpha(alpha)\n { };\n\n void updateEvolutionNoise(ekf_param &p, ekf_state &s)\n {\n // Compute Kk * ino_yk\n gsl_matrix_view mat_view = gsl_matrix_view_array(s.ino_yk->data, p.no, 1);\n gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, s.Kk, &mat_view.matrix, 0.0, s.temp_n_1);\n // Compute : Rv = (1 - alpha) Rv + alpha . (Kk * ino_yk) * (Kk * ino_yk)^T\n gsl_blas_dgemm(CblasNoTrans, CblasTrans, _alpha, s.temp_n_1, s.temp_n_1, (1.0 - _alpha),s.Rv);\n }\n };\n\n}\n\n#endif // EKF_TYPES_H\n", "meta": {"hexsha": "4130849aefcbb55a7654ed715246f9d899bf2ef8", "size": 6106, "ext": "h", "lang": "C", "max_stars_repo_path": "src/ekf_types.h", "max_stars_repo_name": "bahia14/C-Kalman-filtering", "max_stars_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 101.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T05:30:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-21T15:24:07.000Z", "max_issues_repo_path": "src/ekf_types.h", "max_issues_repo_name": "bahia14/C-Kalman-filtering", "max_issues_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-10-16T10:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-17T21:45:18.000Z", "max_forks_repo_path": "src/ekf_types.h", "max_forks_repo_name": "bahia14/C-Kalman-filtering", "max_forks_repo_head_hexsha": "7c01a11359bdd2e2b89ae8a8de88db215d8e061a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 52.0, "max_forks_repo_forks_event_min_datetime": "2015-03-10T01:02:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-13T02:47:35.000Z", "avg_line_length": 25.6554621849, "max_line_length": 158, "alphanum_fraction": 0.6541107108, "num_tokens": 1579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6261241772283034, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.34958202995258786}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tz_error.h\"\n#include \"tz_constant.h\"\n#include \"tz_voxel_linked_list.h\"\n#include \"tz_stack_sampling.h\"\n#include \"tz_voxel_graphics.h\"\n#include \"tz_stack_code.h\"\n#include \"tz_stack_math.h\"\n#include \"tz_stack_utils.h\"\n#include \"tz_objdetect.h\"\n#include \"tz_voxeltrans.h\"\n#include \"tz_stack_stat.h\"\n#include \"tz_stack_draw.h\"\n#include \"tz_geo3d_vector.h\"\n#include \"tz_stack_bwmorph.h\"\n#include \"tz_stack_bwdist.h\"\n#include \"tz_neurotrace.h\"\n#include \"tz_stack_threshold.h\"\n#include \"tz_iarray.h\"\n#include \"tz_darray.h\"\n\n/*\n * trace_neuron - trace neuron from given seeds\n *\n * trace_neuron [!wtr] seed_file -Dsave_dir\n * -r: write intermediate results\n *\n */\nint main(int argc, char* argv[])\n{\n static char *Spec[] = {\n \"[!wtr] [-canvas ] [-mask ] [-res ] [-minr ]\",\n \"-minlen \",\n \" -S -D\",\n NULL};\n \n Process_Arguments(argc, argv, Spec, 1);\n \n char *dir = Get_String_Arg(\"-D\");\n \n char file_path[100];\n sprintf(file_path, \"%s/%s\", dir, Get_String_Arg(\"-S\"));\n printf(\"%s\\n\", file_path);\n\n Geo3d_Scalar_Field *seed = Read_Geo3d_Scalar_Field(file_path);\n\n int idx;\n\n sprintf(file_path, \"%s/%s.bn\", dir, \"max_r\");\n double max_r;\n int tmp;\n if (fexist(file_path)) {\n darray_read2(file_path, &max_r, &tmp);\n } else {\n max_r = darray_max(seed->values, seed->size, &idx);\n }\n\n printf(\"%g\\n\", max_r);\n\n max_r *= 1.5;\n\n /*\n sprintf(file_path, \"%s/%s\", dir, \"soma0.bn\");\n if (!fexist(file_path)) {\n max_r *= 2.0;\n }\n */\n \n Set_Neuroseg_Max_Radius(max_r);\n\n Stack *signal = Read_Stack(Get_String_Arg(\"image\"));\n\n dim_type dim[3];\n dim[0] = signal->width;\n dim[1] = signal->height;\n dim[2] = signal->depth;\n /* \n IMatrix *chord = Make_IMatrix(dim, 3);\n \n Stack *code = Make_Stack(GREY16, \n\t\t\t signal->width, signal->height, signal->depth);\n */\n Rgb_Color color;\n Set_Color(&color, 255, 0, 0);\n\n Stack *canvas = NULL;\n\n char trace_file_path[100];\n sprintf(trace_file_path, \"%s/%s\", dir, Get_String_Arg(\"-canvas\"));\n \n if (fexist(trace_file_path) == 1) {\n canvas = Read_Stack((char *) trace_file_path);\n } else {\n canvas = Copy_Stack(signal);\n Stretch_Stack_Value_Q(canvas, 0.999);\n Translate_Stack(canvas, COLOR, 1);\n }\n\n Stack *traced = NULL;\n \n char trace_mask_path[100];\n sprintf(trace_mask_path, \"%s/%s\", dir, Get_String_Arg(\"-mask\"));\n\n if (fexist(trace_mask_path) == 1) {\n traced = Read_Stack((char *) trace_mask_path);\n } else {\n traced = Make_Stack(GREY, signal->width, signal->height, signal->depth);\n One_Stack(traced);\n }\n \n\n //Object_3d *obj = NULL;\n int seed_offset = -1;\n\n Neurochain *chain = NULL;\n\n double z_scale = 1.0;\n\n if (Is_Arg_Matched(\"-res\")) {\n sprintf(file_path, \"%s\", Get_String_Arg(\"-res\"));\n\n if (fexist(file_path)) {\n double res[3];\n int length;\n darray_read2(file_path, res, &length);\n if (res[0] != res[1]) {\n\tperror(\"Different X-Y resolutions.\");\n\tTZ_ERROR(ERROR_DATA_VALUE);\n }\n z_scale = res[0] / res[2];\n }\n }\n\n //sprintf(file_path, \"%s/%s\", dir, Get_String_Arg(\"-M\"));\n //Stack *stack = Read_Stack(file_path);\n\n tic();\n\n FILE *fp = NULL;\n char chain_file_path[100];\n char vrml_file_path[100];\n\n double min_chain_length = 25.0;\n\n if (Is_Arg_Matched(\"-minlen\")) {\n min_chain_length = Get_Double_Arg(\"-minlen\");\n }\n\n int *indices = iarray_malloc(seed->size);\n double *values = darray_malloc(seed->size);\n int i;\n\n Local_Neuroseg *locseg = (Local_Neuroseg *) \n malloc(seed->size * sizeof(Local_Neuroseg));\n\n int index = 0;\n for (i = 0; i < seed->size; i++) {\n printf(\"-----------------------------> seed: %d / %d\\n\", i, seed->size);\n indices[i] = i;\n index = i;\n int x = (int) seed->points[index][0];\n int y = (int) seed->points[index][1];\n int z = (int) seed->points[index][2];\n\n double width = seed->values[index];\n\n chain = New_Neurochain();\n\n seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,\n\t\t\t\t signal->depth);\n\n if (width < 3.0) {\n width += 0.5;\n }\n Set_Neuroseg(&(locseg[i].seg), width, width, 12.0, \n\t\t 0.0, 0.0, 0.0);\n\n double cpos[3];\n cpos[0] = x;\n cpos[1] = y;\n cpos[2] = z;\n cpos[2] *= z_scale;\n \n Set_Neuroseg_Position(&(locseg[i]), cpos, NEUROSEG_CENTER);\n Stack_Fit_Score fs;\n fs.n = 1;\n fs.options[0] = 1;\n values[i] = Local_Neuroseg_Orientation_Search_C(&(locseg[i]), signal, z_scale, &fs);\n }\n\n darray_qsort(values, indices, seed->size);\n\n /*\n for (i = 0; i < seed->size; i++) {\n indices[i] = i;\n }\n darraycpy(values, seed->values, 0, seed->size);\n darray_qsort(values, indices, seed->size);\n */\n\n int counter = 0;\n\n // for (i = seed->size - 1; i >= seed->size - 231; i--) {\n for (i = seed->size - 1; i >= 0; i--) {\n index = indices[i];\n\n printf(\"-----------------------------> seed: %d / %d\\n\", i, seed->size);\n \n sprintf(chain_file_path, \"%s/chain%d.bn\", dir, index);\n sprintf(vrml_file_path, \"%s/chain%d.wrl\", dir, index);\n\n if (fexist(chain_file_path) == 1) {\n chain = Read_Neurochain(chain_file_path);\n if (Neurochain_Geolen(chain) >= min_chain_length) {\n\tWrite_Neurochain_Vrml(vrml_file_path, chain);\n\tNeurochain_Label(canvas, chain, z_scale);\n\tNeurochain_Erase_E(traced, chain, z_scale, 0,\n\t\t\t Neurochain_Length(chain, FORWARD),\n\t\t\t 1.5, 0.0);\n }\n\n Free_Neurochain(chain);\n printf(\"chain exists\\n\");\n continue;\n }\n \n \n int x = (int) seed->points[index][0];\n int y = (int) seed->points[index][1];\n int z = (int) seed->points[index][2];\n\n if (*STACK_PIXEL_8(traced, x, y, z, 0) == 0) {\n printf(\"traced \\n\");\n continue;\n }\n\n double width = seed->values[index];\n\n if (width > max_r) {\n printf(\"too thick\\n\");\n continue;\n }\n \n if (Is_Arg_Matched(\"-minr\")) {\n int max_level = (int) (width + 0.5);\n if (max_level <= Get_Int_Arg(\"-minr\")) {\n\tprintf(\"too thin\\n\");\n\tcontinue;\n }\n }\n /*\n seed_offset = Stack_Util_Offset(x, y, z, signal->width, signal->height,\n\t\t\t\t signal->depth);\n */\n\n chain = New_Neurochain();\n /*\n Stack_Level_Code_Constraint(stack, code, chord->array, &seed_offset, 1, \n\t\t\t\tmax_level + 1);\n\n Voxel_t v;\n v[0] = x;\n v[1] = y;\n v[2] = z;\n\n Stack *tmp_stack = Copy_Stack(stack);\n obj = Stack_Grow_Object_Constraint(tmp_stack, 1, v, chord, code, \n\t\t\t\t max_level);\n Free_Stack(tmp_stack);\n\n Print_Object_3d_Info(obj);\n \n double vec[3];\n Object_3d_Orientation_Zscale(obj, vec, MAJOR_AXIS, z_scale);\n\n double theta, psi;\n Geo3d_Vector obj_vec;\n Set_Geo3d_Vector(&obj_vec, vec[0], vec[1], vec[2]);\n\n Geo3d_Vector_Orientation(&obj_vec, &theta, &psi);\n */\n\n /*\n if (width < 3.0) {\n width += 0.5;\n }\n Set_Neuroseg(&(chain->locseg.seg), width, width, 12.0, \n\t\t 0.0, 0.0, 0.0);\n\n double cpos[3];\n cpos[0] = x;\n cpos[1] = y;\n cpos[2] = z;\n cpos[2] *= z_scale;\n \n //Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_BOTTOM);\n Set_Neuroseg_Position(&(chain->locseg), cpos, NEUROSEG_CENTER);\n Stack_Fit_Score fs;\n fs.n = 1;\n fs.options[0] = 1;\n Local_Neuroseg_Orientation_Search_C(&(chain->locseg), signal, z_scale,\n\t\t\t\t\t&fs); \n //fs.options[0] = 1;\n */\n\n Copy_Local_Neuroseg(&(chain->locseg), &(locseg[index]));\n Neurochain *chain_head = chain;\n \n \n if (Initialize_Tracing(signal, chain, NULL, z_scale) >= MIN_SCORE) {\n if ((Neuroseg_Hit_Traced(&(chain->locseg), traced, z_scale) == FALSE) &&\n\t (chain->locseg.seg.r1 < max_r) && \n\t (chain->locseg.seg.r2 < max_r)) {\n\t//Initialize_Tracing(signal, chain, NULL, z_scale);\n\tchain = Trace_Neuron2(signal, chain, BOTH, traced, z_scale, 500);\n\n\t//Neurochain *chain_head = Neurochain_Head(chain);\n\tchain_head = Neurochain_Remove_Overlap_Segs(chain);\n\tchain_head = Neurochain_Remove_Turn_Ends(chain_head, 0.5);\n\t/*\n\tif (i == seed->size - 231) {\n\t Print_Neurochain(chain_head);\n\t}\n\t*/\n\n\tfp = fopen(chain_file_path, \"w\");\n\tNeurochain_Fwrite(chain_head, fp);\n\tfclose(fp);\n\tif (Neurochain_Geolen(chain_head) >= min_chain_length) {\n\t Write_Neurochain_Vrml(vrml_file_path, chain_head);\n\n\t Neurochain_Erase_E(traced, chain_head, z_scale, 0,\n\t\t\t Neurochain_Length(chain_head, FORWARD),\n\t\t\t 1.5, 0.0);\n\t Neurochain_Label(canvas, chain_head, z_scale);\n\n\t counter += Neurochain_Length(chain_head, FORWARD);\n\t if (counter > 500) {\n\t if (Is_Arg_Matched(\"-r\")) {\n\t Write_Stack((char *) trace_mask_path, traced);\n\t }\n\t \n\t if (Is_Arg_Matched(\"-r\")) {\n\t Write_Stack((char *) trace_file_path, canvas);\n\t }\n\n\t counter = 0;\n\t }\n\t}\n }\n }\n\n Free_Neurochain(chain_head);\n\n //Kill_Object_3d(obj);\n }\n\n Write_Stack((char *) trace_file_path, canvas);\n if (Is_Arg_Matched(\"-r\")) {\n Write_Stack((char *) trace_mask_path, traced);\n }\n\n Kill_Geo3d_Scalar_Field(seed);\n\n printf(\"Time passed: %lld\\n\", toc());\n\n \n return 0;\n}\n", "meta": {"hexsha": "7a1f429361d5d8eb97d42bdc4475d9d0bd085d1f", "size": 9156, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_neuron.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_neuron.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_neuron.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3510638298, "max_line_length": 88, "alphanum_fraction": 0.6135867191, "num_tokens": 2903, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.43782349911420193, "lm_q1q2_score": 0.3494649321803662}} {"text": "/*\n C code for the adiabatic approximation\n*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef _OPENMP\n#include \n#endif\n#define CHUNKSIZE 10\n//Potentials\n#include \n#include \n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n/*\n Structure Declarations\n*/\nstruct JRAdiabaticArg{\n double ER;\n double Lz22;\n int nargs;\n struct potentialArg * actionAngleArgs;\n};\nstruct JzAdiabaticArg{\n double Ez;\n double R;\n int nargs;\n struct potentialArg * actionAngleArgs;\n};\n/*\n Function Declarations\n*/\nvoid actionAngleAdiabatic_actions(int,double *,double *,double *,double *,\n\t\t\t\t double *,int,int *,double *,double,\n\t\t\t\t double *,double *,int *);\nvoid calcJRAdiabatic(int,double *,double *,double *,double *,double *,\n\t\t int,struct potentialArg *,int);\nvoid calcJzAdiabatic(int,double *,double *,double *,double *,int,\n\t\t struct potentialArg *,int);\nvoid calcRapRperi(int,double *,double *,double *,double *,double *,\n\t\t int,struct potentialArg *);\nvoid calcZmax(int,double *,double *,double *,double *,int,\n\t struct potentialArg *);\ndouble JRAdiabaticIntegrandSquared(double,void *);\ndouble JRAdiabaticIntegrand(double,void *);\ndouble JzAdiabaticIntegrandSquared(double,void *);\ndouble JzAdiabaticIntegrand(double,void *);\ndouble evaluateVerticalPotentials(double, double,int, struct potentialArg *);\n/*\n Actual functions, inlines first\n*/\ninline void calcEREzL(int ndata,\n\t\t double *R,\n\t\t double *vR,\n\t\t double *vT,\n\t\t double *z,\n\t\t double *vz,\n\t\t double *ER,\n\t\t double *Ez,\n\t\t double *Lz,\n\t\t int nargs,\n\t\t struct potentialArg * actionAngleArgs){\n int ii;\n UNUSED int chunk= CHUNKSIZE;\n#pragma omp parallel for schedule(static,chunk) private(ii)\n for (ii=0; ii < ndata; ii++){\n *(ER+ii)= evaluatePotentials(*(R+ii),0.,\n\t\t\t\t nargs,actionAngleArgs)\n + 0.5 * *(vR+ii) * *(vR+ii)\n + 0.5 * *(vT+ii) * *(vT+ii);\n *(Ez+ii)= evaluateVerticalPotentials(*(R+ii),*(z+ii),\n\t\t\t\t\t nargs,actionAngleArgs) \n + 0.5 * *(vz+ii) * *(vz+ii);\n *(Lz+ii)= *(R+ii) * *(vT+ii);\n }\n}\n/*\n MAIN FUNCTIONS\n */\nvoid actionAngleAdiabatic_actions(int ndata,\n\t\t\t\t double *R,\n\t\t\t\t double *vR,\n\t\t\t\t double *vT,\n\t\t\t\t double *z,\n\t\t\t\t double *vz,\n\t\t\t\t int npot,\n\t\t\t\t int * pot_type,\n\t\t\t\t double * pot_args,\n\t\t\t\t double gamma,\n\t\t\t\t double *jr,\n\t\t\t\t double *jz,\n\t\t\t\t int * err){\n int ii;\n //Set up the potentials\n struct potentialArg * actionAngleArgs= (struct potentialArg *) malloc ( npot * sizeof (struct potentialArg) );\n parse_actionAngleArgs(npot,actionAngleArgs,pot_type,pot_args);\n //ER, Ez, Lz\n double *ER= (double *) malloc ( ndata * sizeof(double) );\n double *Ez= (double *) malloc ( ndata * sizeof(double) );\n double *Lz= (double *) malloc ( ndata * sizeof(double) );\n calcEREzL(ndata,R,vR,vT,z,vz,ER,Ez,Lz,npot,actionAngleArgs);\n //Calculate peri and apocenters\n double *rperi= (double *) malloc ( ndata * sizeof(double) );\n double *rap= (double *) malloc ( ndata * sizeof(double) );\n double *zmax= (double *) malloc ( ndata * sizeof(double) );\n calcZmax(ndata,zmax,z,R,Ez,npot,actionAngleArgs);\n calcJzAdiabatic(ndata,jz,zmax,R,Ez,npot,actionAngleArgs,10);\n //Adjust planar effective potential for gamma\n UNUSED int chunk= CHUNKSIZE;\n#pragma omp parallel for schedule(static,chunk) private(ii)\n for (ii=0; ii < ndata; ii++){\n *(Lz+ii)= fabs( *(Lz+ii) ) + gamma * *(jz+ii);\n *(ER+ii)+= 0.5 * *(Lz+ii) * *(Lz+ii) / *(R+ii) / *(R+ii) \n - 0.5 * *(vT+ii) * *(vT+ii);\n }\n calcRapRperi(ndata,rperi,rap,R,ER,Lz,npot,actionAngleArgs);\n calcJRAdiabatic(ndata,jr,rperi,rap,ER,Lz,npot,actionAngleArgs,10);\n for (ii=0; ii < npot; ii++) {\n if ( (actionAngleArgs+ii)->i2d )\n interp_2d_free((actionAngleArgs+ii)->i2d) ;\n if ((actionAngleArgs+ii)->accx )\n gsl_interp_accel_free ((actionAngleArgs+ii)->accx);\n if ((actionAngleArgs+ii)->accy )\n gsl_interp_accel_free ((actionAngleArgs+ii)->accy);\n free((actionAngleArgs+ii)->args);\n }\n free(actionAngleArgs);\n free(ER);\n free(Ez);\n free(Lz);\n free(rperi);\n free(rap);\n free(zmax);\n}\nvoid calcJRAdiabatic(int ndata,\n\t\t double * jr,\n\t\t double * rperi,\n\t\t double * rap,\n\t\t double * ER,\n\t\t double * Lz,\n\t\t int nargs,\n\t\t struct potentialArg * actionAngleArgs,\n\t\t int order){\n int ii, tid, nthreads;\n#ifdef _OPENMP\n nthreads = omp_get_max_threads();\n#else\n nthreads = 1;\n#endif\n gsl_function * JRInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );\n struct JRAdiabaticArg * params= (struct JRAdiabaticArg *) malloc ( nthreads * sizeof (struct JRAdiabaticArg) );\n for (tid=0; tid < nthreads; tid++){\n (params+tid)->nargs= nargs;\n (params+tid)->actionAngleArgs= actionAngleArgs;\n }\n //Setup integrator\n gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);\n UNUSED int chunk= CHUNKSIZE;\n#pragma omp parallel for schedule(static,chunk)\t\t\t\t\\\n private(tid,ii)\t\t\t\t\t\t\t\\\n shared(jr,rperi,rap,JRInt,params,T,ER,Lz)\n for (ii=0; ii < ndata; ii++){\n#ifdef _OPENMP\n tid= omp_get_thread_num();\n#else\n tid = 0;\n#endif\n if ( *(rperi+ii) == -9999.99 || *(rap+ii) == -9999.99 ){\n *(jr+ii)= 9999.99;\n continue;\n }\n if ( (*(rap+ii) - *(rperi+ii)) / *(rap+ii) < 0.000001 ){//circular\n *(jr+ii) = 0.;\n continue;\n }\n //Setup function\n (params+tid)->ER= *(ER+ii);\n (params+tid)->Lz22= 0.5 * *(Lz+ii) * *(Lz+ii);\n (JRInt+tid)->function = &JRAdiabaticIntegrand;\n (JRInt+tid)->params = params+tid;\n //Integrate\n *(jr+ii)= gsl_integration_glfixed (JRInt+tid,*(rperi+ii),*(rap+ii),T)\n * sqrt(2.) / M_PI;\n }\n free(JRInt);\n free(params);\n gsl_integration_glfixed_table_free ( T );\n}\nvoid calcJzAdiabatic(int ndata,\n\t\t double * jz,\n\t\t double * zmax,\n\t\t double * R,\n\t\t double * Ez,\n\t\t int nargs,\n\t\t struct potentialArg * actionAngleArgs,\n\t\t int order){\n int ii, tid, nthreads;\n#ifdef _OPENMP\n nthreads = omp_get_max_threads();\n#else\n nthreads = 1;\n#endif\n gsl_function * JzInt= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );\n struct JzAdiabaticArg * params= (struct JzAdiabaticArg *) malloc ( nthreads * sizeof (struct JzAdiabaticArg) );\n for (tid=0; tid < nthreads; tid++){\n (params+tid)->nargs= nargs;\n (params+tid)->actionAngleArgs= actionAngleArgs;\n }\n //Setup integrator\n gsl_integration_glfixed_table * T= gsl_integration_glfixed_table_alloc (order);\n UNUSED int chunk= CHUNKSIZE;\n#pragma omp parallel for schedule(static,chunk)\t\t\t\t\\\n private(tid,ii)\t\t\t\t\t\t\t\\\n shared(jz,zmax,JzInt,params,T,Ez,R)\n for (ii=0; ii < ndata; ii++){\n#ifdef _OPENMP\n tid= omp_get_thread_num();\n#else\n tid = 0;\n#endif\n if ( *(zmax+ii) == -9999.99 ){\n *(jz+ii)= 9999.99;\n continue;\n }\n if ( *(zmax+ii) < 0.000001 ){//circular\n *(jz+ii) = 0.;\n continue;\n }\n //Setup function\n (params+tid)->Ez= *(Ez+ii);\n (params+tid)->R= *(R+ii);\n (JzInt+tid)->function = &JzAdiabaticIntegrand;\n (JzInt+tid)->params = params+tid;\n //Integrate\n *(jz+ii)= gsl_integration_glfixed (JzInt+tid,0.,*(zmax+ii),T)\n * 2 * sqrt(2.) / M_PI;\n }\n free(JzInt);\n free(params);\n gsl_integration_glfixed_table_free ( T );\n}\nvoid calcRapRperi(int ndata,\n\t\t double * rperi,\n\t\t double * rap,\n\t\t double * R,\n\t\t double * ER,\n\t\t double * Lz,\n\t\t int nargs,\n\t\t struct potentialArg * actionAngleArgs){\n int ii, tid, nthreads;\n#ifdef _OPENMP\n nthreads = omp_get_max_threads();\n#else\n nthreads = 1;\n#endif\n double peps, meps;\n gsl_function * JRRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );\n struct JRAdiabaticArg * params= (struct JRAdiabaticArg *) malloc ( nthreads * sizeof (struct JRAdiabaticArg) );\n //Setup solver\n int status;\n int iter, max_iter = 100;\n const gsl_root_fsolver_type *T;\n double R_lo, R_hi;\n struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );\n T = gsl_root_fsolver_brent;\n for (tid=0; tid < nthreads; tid++){\n (params+tid)->nargs= nargs;\n (params+tid)->actionAngleArgs= actionAngleArgs;\n (s+tid)->s= gsl_root_fsolver_alloc (T);\n }\n UNUSED int chunk= CHUNKSIZE;\n gsl_set_error_handler_off();\n#pragma omp parallel for schedule(static,chunk)\t\t\t\t\\\n private(tid,ii,iter,status,R_lo,R_hi,meps,peps)\t\t\t\\\n shared(rperi,rap,JRRoot,params,s,R,ER,Lz,max_iter)\n for (ii=0; ii < ndata; ii++){\n#ifdef _OPENMP\n tid= omp_get_thread_num();\n#else\n tid = 0;\n#endif\n //Setup function\n (params+tid)->ER= *(ER+ii);\n (params+tid)->Lz22= 0.5 * *(Lz+ii) * *(Lz+ii);\n (JRRoot+tid)->params = params+tid;\n (JRRoot+tid)->function = &JRAdiabaticIntegrandSquared;\n //Find starting points for minimum\n if ( fabs(GSL_FN_EVAL(JRRoot+tid,*(R+ii))) < 0.0000001){ //we are at rap or rperi\n peps= GSL_FN_EVAL(JRRoot+tid,*(R+ii)+0.0000001);\n meps= GSL_FN_EVAL(JRRoot+tid,*(R+ii)-0.0000001);\n if ( fabs(peps) < 0.00000001 && fabs(meps) < 0.00000001 && peps*meps >= 0.) {//circular\n\t*(rperi+ii) = *(R+ii);\n\t*(rap+ii) = *(R+ii);\n }\n else if ( peps < 0. && meps > 0. ) {//umax\n\t*(rap+ii)= *(R+ii);\n\tR_lo= 0.9 * (*(R+ii) - 0.0000001);\n\tR_hi= *(R+ii) - 0.00000001;\n\twhile ( GSL_FN_EVAL(JRRoot+tid,R_lo) >= 0. && R_lo > 0.000000001){\n\t R_hi= R_lo; //this makes sure that brent evaluates using previous\n\t R_lo*= 0.9;\n\t}\n\t//Find root\n\tstatus = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi);\n\tif (status == GSL_EINVAL) {\n\t *(rperi+ii) = 0.;//Assume zero if below 0.000000001\n\t continue;\n\t}\n\titer= 0;\n\tdo\n\t {\n\t iter++;\n\t status = gsl_root_fsolver_iterate ((s+tid)->s);\n\t R_lo = gsl_root_fsolver_x_lower ((s+tid)->s);\n\t R_hi = gsl_root_fsolver_x_upper ((s+tid)->s);\n\t status = gsl_root_test_interval (R_lo, R_hi,\n\t\t\t\t\t 9.9999999999999998e-13,\n\t\t\t\t\t 4.4408920985006262e-16);\n\t }\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t// LCOV_EXCL_START\n\tif (status == GSL_EINVAL) {//Shouldn't ever get here\n\t *(rperi+ii) = -9999.99;\n\t *(rap+ii) = -9999.99;\n\t continue;\n\t}\n\t// LCOV_EXCL_STOP\n\t*(rperi+ii) = gsl_root_fsolver_root ((s+tid)->s);\n }\n else if ( peps > 0. && meps < 0. ){//umin\n\t*(rperi+ii)= *(R+ii);\n\tR_lo= *(R+ii) + 0.0000001;\n\tR_hi= 1.1 * (*(R+ii) + 0.0000001);\n\twhile ( GSL_FN_EVAL(JRRoot+tid,R_hi) >= 0. && R_hi < 37.5) {\n\t R_lo= R_hi; //this makes sure that brent evaluates using previous\n\t R_hi*= 1.1;\n\t}\n\t//Find root\n\tstatus = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi);\n\tif (status == GSL_EINVAL) {\n\t *(rperi+ii) = -9999.99;\n\t *(rap+ii) = -9999.99;\n\t continue;\n\t}\n\titer= 0;\n\tdo\n\t {\n\t iter++;\n\t status = gsl_root_fsolver_iterate ((s+tid)->s);\n\t R_lo = gsl_root_fsolver_x_lower ((s+tid)->s);\n\t R_hi = gsl_root_fsolver_x_upper ((s+tid)->s);\n\t status = gsl_root_test_interval (R_lo, R_hi,\n\t\t\t\t\t 9.9999999999999998e-13,\n\t\t\t\t\t 4.4408920985006262e-16);\n\t }\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t// LCOV_EXCL_START\n\tif (status == GSL_EINVAL) {//Shouldn't ever get here \n\t *(rperi+ii) = -9999.99;\n\t *(rap+ii) = -9999.99;\n\t continue;\n\t}\n\t// LCOV_EXCL_STOP\n\t*(rap+ii) = gsl_root_fsolver_root ((s+tid)->s);\n }\n }\n else {\n R_lo= 0.9 * *(R+ii);\n R_hi= *(R+ii);\n while ( GSL_FN_EVAL(JRRoot+tid,R_lo) >= 0. && R_lo > 0.000000001){\n\tR_hi= R_lo; //this makes sure that brent evaluates using previous\n\tR_lo*= 0.9;\n }\n R_hi= (R_lo < 0.9 * *(R+ii)) ? R_lo / 0.9 / 0.9: *(R+ii);\n //Find root\n status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi);\n if (status == GSL_EINVAL) {\n\t*(rperi+ii) = 0.;//Assume zero if below 0.000000001\n } else {\n\titer= 0;\n\tdo\n\t {\n\t iter++;\n\t status = gsl_root_fsolver_iterate ((s+tid)->s);\n\t R_lo = gsl_root_fsolver_x_lower ((s+tid)->s);\n\t R_hi = gsl_root_fsolver_x_upper ((s+tid)->s);\n\t status = gsl_root_test_interval (R_lo, R_hi,\n\t\t\t\t\t 9.9999999999999998e-13,\n\t\t\t\t\t 4.4408920985006262e-16);\n\t }\n\twhile (status == GSL_CONTINUE && iter < max_iter);\n\t// LCOV_EXCL_START\n\tif (status == GSL_EINVAL) {//Shouldn't ever get here\n\t *(rperi+ii) = -9999.99;\n\t *(rap+ii) = -9999.99;\n\t continue;\n\t}\n\t// LCOV_EXCL_STOP\n\t*(rperi+ii) = gsl_root_fsolver_root ((s+tid)->s);\n }\n //Find starting points for maximum\n R_lo= *(R+ii);\n R_hi= 1.1 * *(R+ii);\n while ( GSL_FN_EVAL(JRRoot+tid,R_hi) > 0. && R_hi < 37.5) {\n\tR_lo= R_hi; //this makes sure that brent evaluates using previous\n\tR_hi*= 1.1;\n }\n R_lo= (R_hi > 1.1 * *(R+ii)) ? R_hi / 1.1 / 1.1: *(R+ii);\n //Find root\n status = gsl_root_fsolver_set ((s+tid)->s, JRRoot+tid, R_lo, R_hi);\n if (status == GSL_EINVAL) {\n\t*(rperi+ii) = -9999.99;\n\t*(rap+ii) = -9999.99;\n\tcontinue;\n }\n iter= 0;\n do\n\t{\n\t iter++;\n\t status = gsl_root_fsolver_iterate ((s+tid)->s);\n\t R_lo = gsl_root_fsolver_x_lower ((s+tid)->s);\n\t R_hi = gsl_root_fsolver_x_upper ((s+tid)->s);\n\t status = gsl_root_test_interval (R_lo, R_hi,\n\t\t\t\t\t 9.9999999999999998e-13,\n\t\t\t\t\t 4.4408920985006262e-16);\n\t}\n while (status == GSL_CONTINUE && iter < max_iter);\n // LCOV_EXCL_START\n if (status == GSL_EINVAL) {//Shouldn't ever get here \n\t*(rperi+ii) = -9999.99;\n\t*(rap+ii) = -9999.99;\n\tcontinue;\n }\n // LCOV_EXCL_STOP\n *(rap+ii) = gsl_root_fsolver_root ((s+tid)->s);\n }\n }\n gsl_set_error_handler (NULL);\n for (tid=0; tid < nthreads; tid++)\n gsl_root_fsolver_free( (s+tid)->s);\n free(s);\n free(JRRoot);\n free(params);\n}\nvoid calcZmax(int ndata,\n\t double * zmax,\n\t double * z,\n\t double * R,\n\t double * Ez,\n\t int nargs,\n\t struct potentialArg * actionAngleArgs){\n int ii, tid, nthreads;\n#ifdef _OPENMP\n nthreads = omp_get_max_threads();\n#else\n nthreads = 1;\n#endif\n gsl_function * JzRoot= (gsl_function *) malloc ( nthreads * sizeof(gsl_function) );\n struct JzAdiabaticArg * params= (struct JzAdiabaticArg *) malloc ( nthreads * sizeof (struct JzAdiabaticArg) );\n //Setup solver\n int status;\n int iter, max_iter = 100;\n const gsl_root_fsolver_type *T;\n double z_lo, z_hi;\n struct pragmasolver *s= (struct pragmasolver *) malloc ( nthreads * sizeof (struct pragmasolver) );\n T = gsl_root_fsolver_brent;\n for (tid=0; tid < nthreads; tid++){\n (params+tid)->nargs= nargs;\n (params+tid)->actionAngleArgs= actionAngleArgs;\n (s+tid)->s= gsl_root_fsolver_alloc (T);\n }\n UNUSED int chunk= CHUNKSIZE;\n gsl_set_error_handler_off();\n#pragma omp parallel for schedule(static,chunk)\t\t\t\t\\\n private(tid,ii,iter,status,z_lo,z_hi)\t\t\t\t\\\n shared(zmax,JzRoot,params,s,z,Ez,R,max_iter)\n for (ii=0; ii < ndata; ii++){\n#ifdef _OPENMP\n tid= omp_get_thread_num();\n#else\n tid = 0;\n#endif\n //Setup function\n (params+tid)->Ez= *(Ez+ii);\n (params+tid)->R= *(R+ii);\n (JzRoot+tid)->function = &JzAdiabaticIntegrandSquared;\n (JzRoot+tid)->params = params+tid;\n //Find starting points for minimum\n if ( fabs(GSL_FN_EVAL(JzRoot+tid,*(z+ii))) < 0.0000001){ //we are at zmax\n *(zmax+ii)= fabs( *(z+ii) );\n }\n else {\n z_lo= fabs ( *(z+ii) );\n z_hi= ( *(z+ii) == 0. ) ? 0.1: 1.1 * fabs( *(z+ii) );\n while ( GSL_FN_EVAL(JzRoot+tid,z_hi) >= 0. && z_hi < 37.5) {\n\tz_lo= z_hi; //this makes sure that brent evaluates using previous\n\tz_hi*= 1.1;\n }\n //Find root\n status = gsl_root_fsolver_set ((s+tid)->s, JzRoot+tid, z_lo, z_hi);\n if (status == GSL_EINVAL) {\n\t*(zmax+ii) = -9999.99;\n\tcontinue;\n }\n iter= 0;\n do\n\t{\n\t iter++;\n\t status = gsl_root_fsolver_iterate ((s+tid)->s);\n\t z_lo = gsl_root_fsolver_x_lower ((s+tid)->s);\n\t z_hi = gsl_root_fsolver_x_upper ((s+tid)->s);\n\t status = gsl_root_test_interval (z_lo, z_hi,\n\t\t\t\t\t 9.9999999999999998e-13,\n\t\t\t\t\t 4.4408920985006262e-16);\n\t}\n while (status == GSL_CONTINUE && iter < max_iter);\n // LCOV_EXCL_START\n if (status == GSL_EINVAL) {//Shouldn't ever get here\n\t*(zmax+ii) = -9999.99;\n\tcontinue;\n }\n // LCOV_EXCL_STOP\n *(zmax+ii) = gsl_root_fsolver_root ((s+tid)->s);\n }\n }\n gsl_set_error_handler (NULL);\n for (tid=0; tid < nthreads; tid++)\n gsl_root_fsolver_free( (s+tid)->s);\n free(s);\n free(JzRoot);\n free(params);\n}\ndouble JRAdiabaticIntegrand(double R,\n\t\t\t void * p){\n return sqrt(JRAdiabaticIntegrandSquared(R,p));\n}\ndouble JRAdiabaticIntegrandSquared(double R,\n\t\t\t\t void * p){\n struct JRAdiabaticArg * params= (struct JRAdiabaticArg *) p;\n return params->ER - evaluatePotentials(R,0.,params->nargs,params->actionAngleArgs) - params->Lz22 / R / R;\n}\ndouble JzAdiabaticIntegrand(double z,\n\t\t\t void * p){\n return sqrt(JzAdiabaticIntegrandSquared(z,p));\n}\ndouble JzAdiabaticIntegrandSquared(double z,\n\t\t\t\t void * p){\n struct JzAdiabaticArg * params= (struct JzAdiabaticArg *) p;\n return params->Ez - evaluateVerticalPotentials(params->R,z,\n\t\t\t\t\t\t params->nargs,\n\t\t\t\t\t\t params->actionAngleArgs);\n}\ndouble evaluateVerticalPotentials(double R, double z,\n\t\t\t\t int nargs, \n\t\t\t\t struct potentialArg * actionAngleArgs){\n return evaluatePotentials(R,z,nargs,actionAngleArgs)\n -evaluatePotentials(R,0.,nargs,actionAngleArgs);\n}\n", "meta": {"hexsha": "81e69ac7a3542d7e1e0a27320f34dd48474cea56", "size": 17291, "ext": "c", "lang": "C", "max_stars_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngleAdiabatic.c", "max_stars_repo_name": "fardal/galpy", "max_stars_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngleAdiabatic.c", "max_issues_repo_name": "fardal/galpy", "max_issues_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "galpy/actionAngle_src/actionAngle_c_ext/actionAngleAdiabatic.c", "max_forks_repo_name": "fardal/galpy", "max_forks_repo_head_hexsha": "93a1b6fc8d138899922127086cc66184919c8cba", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4955908289, "max_line_length": 113, "alphanum_fraction": 0.6272049043, "num_tokens": 5833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7772998611746911, "lm_q2_score": 0.4493926344647597, "lm_q1q2_score": 0.3493128323823864}} {"text": "/* Copyright (c) 2011-2017, NVIDIA CORPORATION. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of NVIDIA CORPORATION nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#pragma once\n\nnamespace amgx\n{\ntemplate typename Matrix::value_type estimate_largest_eigen_value(Matrix &A);\n}\n\n#include \n#include \n#include \n\nnamespace amgx\n{\n\ntemplate \ntypename Matrix::value_type estimate_largest_eigen_value(Matrix &A)\n{\n typedef typename Matrix::TConfig TConfig;\n typedef typename Matrix::value_type ValueTypeA;\n typedef typename TConfig::VecPrec ValueTypeB;\n typedef Vector VVector;\n VVector x(A.get_num_rows()), y(A.get_num_rows());\n fill(x, 1);\n\n for (int i = 0; i < 20; i++)\n {\n ValueTypeB Lmax = get_norm(A, x, LMAX);\n scal(x, ValueTypeB(1) / Lmax);\n multiply(A, x, y);\n x.swap(y);\n }\n\n ValueTypeB retval = get_norm(A, x, L2) / get_norm(A, y, L2);\n return retval;\n}\n\n} // namespace amgx\n", "meta": {"hexsha": "14443ca7d4dc6db7ba0b2fe0a30789b47c38ec17", "size": 2409, "ext": "h", "lang": "C", "max_stars_repo_path": "base/include/miscmath.h", "max_stars_repo_name": "fizmat/AMGX", "max_stars_repo_head_hexsha": "11af85608ea0f4720e03cbcc920521745f9e40e5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 278.0, "max_stars_repo_stars_event_min_datetime": "2017-10-13T18:28:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:54:04.000Z", "max_issues_repo_path": "3rd_party/AMGX/base/include/miscmath.h", "max_issues_repo_name": "neams-th-coe/nekRS", "max_issues_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 143.0, "max_issues_repo_issues_event_min_datetime": "2017-10-18T10:30:34.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T21:13:16.000Z", "max_forks_repo_path": "3rd_party/AMGX/base/include/miscmath.h", "max_forks_repo_name": "neams-th-coe/nekRS", "max_forks_repo_head_hexsha": "5d2c8ab3d14b3fb16db35682336a1f96000698bb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 112.0, "max_forks_repo_forks_event_min_datetime": "2017-10-16T11:00:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T21:46:46.000Z", "avg_line_length": 37.0615384615, "max_line_length": 93, "alphanum_fraction": 0.7301784973, "num_tokens": 545, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.34902656926909287}} {"text": "#include \n\n#include \n#include \n\n/****************************************************************************/\n/* test function from M. J. Box, \"A new method of constrained optimization\n and a comparison with other methods,\" Computer J. 8 (1), 42-52 (1965) */\n\nint testfuncs_verbose = 1;\nint testfuncs_counter = 0;\n\nstatic double testfuncs_status(int n, const double *x, double f)\n{\n ++testfuncs_counter;\n if (testfuncs_verbose) {\n int i;\n printf(\"f_%d (%g\", testfuncs_counter, x[0]);\n for (i = 1; i < n; ++i)\n printf(\", %g\", x[i]);\n printf(\") = %g\\n\", f);\n }\n return f;\n}\n\n#define RETURN(f) return testfuncs_status(n, x, f);\n\nstatic const double k1 = -145421.402, k2 = 2931.1506, k3 = -40.427932, k4 = 5106.192,\n k5 = 15711.36, k6 = -161622.577, k7 = 4176.15328, k8 = 2.8260078,\n k9 = 9200.476, k10 = 13160.295, k11 = -21686.9194, k12 = 123.56928,\n k13 = -21.1188894, k14 = 706.834, k15 = 2898.573, k16 = 28298.388,\n k17 = 60.81096, k18 = 31.242116, k19 = 329.574, k20 = -2882.082,\n k21 = 74095.3845, k22 = -306.262544, k23 = 16.243649, k24 = -3094.252,\n k25 = -5566.2628, k26 = -26237, k27 = 99, k28 = -0.42, k29 = 1300, k30 = 2100, k31 = 925548.252, k32 = -61968.8432, k33 = 23.3088196, k34 = -27096.648, k35 = -50843.766;\n\nstatic double box(int n, const double *x, double *grad, void *data)\n{\n double x1 = x[0], x2 = x[1], x3 = x[2], x4 = x[3], x5 = x[4];\n double b, x6, y1, y2, y3, y4, u;\n const double a0 = 9, a1 = 15, a2 = 50, a3 = 9.583, a4 = 20, a5 = 15, a6 = 6, a7 = 0.75;\n b = x2 + 0.01 * x3;\n x6 = (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5) * x1;\n y1 = k6 + k7 * x2 + k8 * x3 + k9 * x4 + k10 * x5;\n y2 = k11 + k12 * x2 + k13 * x3 + k14 * x4 + k15 * x5;\n y3 = k16 + k17 * x2 + k18 * x3 + k19 * x4 + k20 * x5;\n y4 = k21 + k22 * x2 + k23 * x3 + k24 * x4 + k25 * x5;\n u = a2 * y1 + a3 * y2 + a4 * y3 + a5 * y4 + 7840 * a6 - 100000 * a0 - 50800 * b * a7 + k31 + k32 * x2 + k33 * x3 + k34 * x4 + k35 * x5;\n if (grad) {\n int i;\n grad[0] = u + a1 * (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5);\n grad[1] = x1 * (a2 * k7 + a3 * k12 + a4 * k17 + a5 * k22 - 50800 * a7 + k32) + a1 * (k2 * x1);\n grad[2] = x1 * (a2 * k8 + a3 * k13 + a4 * k18 + a5 * k23 - 50800 * a7 * 0.01) + a1 * x1 * k3;\n grad[3] = x1 * (a2 * k9 + a3 * k14 + a4 * k19 + a5 * k24) + a1 * x1 * k4;\n grad[4] = x1 * (a2 * k10 + a3 * k15 + a4 * k20 + a5 * k25) + a1 * x1 * k5;\n for (i = 0; i < 5; ++i)\n grad[i] = -grad[i];\n }\n RETURN(-(u * x1 - 24345 + a1 * x6));\n}\n\nstatic double box_constraint(int n, const double *x, double *grad, void *data)\n{\n int which_constraint = *((int *) data);\n double x1 = x[0], x2 = x[1], x3 = x[2], x4 = x[3], x5 = x[4];\n double x6, y1, y2, y3, x7, x8;\n int i;\n\n x6 = (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5) * x1;\n y1 = k6 + k7 * x2 + k8 * x3 + k9 * x4 + k10 * x5;\n y2 = k11 + k12 * x2 + k13 * x3 + k14 * x4 + k15 * x5;\n y3 = k16 + k17 * x2 + k18 * x3 + k19 * x4 + k20 * x5;\n x7 = (y1 + y2 + y3) * x1;\n x8 = (k26 + k27 * x2 + k28 * x3 + k29 * x4 + k30 * x5) * x1 + x6 + x7;\n\n if (grad) {\n grad[0] = grad[1] = grad[2] = grad[3] = grad[4] = 0;\n\n if (which_constraint != 2 && which_constraint != -2) {\n /* grad x6 */\n grad[0] += (k1 + k2 * x2 + k3 * x3 + k4 * x4 + k5 * x5);\n grad[1] += x1 * k2;\n grad[2] += x1 * k3;\n grad[3] += x1 * k4;\n grad[4] += x1 * k5;\n }\n if (which_constraint != 1 && which_constraint != -1) {\n /* grad x7 */\n grad[0] += (y1 + y2 + y3);\n grad[1] += x1 * (k7 + k12 + k17);\n grad[2] += x1 * (k8 + k13 + k18);\n grad[3] += x1 * (k9 + k14 + k19);\n grad[4] += x1 * (k10 + k15 + k20);\n }\n if (which_constraint == 3 || which_constraint == -3) {\n /* grad (x8 - x6 - x7) */\n grad[0] += k26 + k27 * x2 + k28 * x3 + k29 * x4 + k30 * x5;\n grad[1] += x1 * k27;\n grad[2] += x1 * k28;\n grad[3] += x1 * k29;\n grad[4] += x1 * k30;\n }\n }\n\n if (which_constraint == -1) {\n if (grad)\n for (i = 0; i < 5; ++i)\n grad[i] = -grad[i];\n return -x6;\n } else if (which_constraint == 1) {\n return x6 - 294000;\n } else if (which_constraint == -2) {\n if (grad)\n for (i = 0; i < 5; ++i)\n grad[i] = -grad[i];\n return -x7;\n } else if (which_constraint == 2) {\n return x7 - 294000;\n } else if (which_constraint == -3) {\n if (grad)\n for (i = 0; i < 5; ++i)\n grad[i] = -grad[i];\n return -x8;\n } else if (which_constraint == 3) {\n return x8 - 277200;\n }\n return 0;\n}\n\nint main(void)\n{\n const double box_lb[5] = { 0, 1.2, 20, 9, 6.5 };\n const double box_ub[5] = { HUGE_VAL, 2.4, 60, 9.3, 7.0 };\n const double box_xmin[5] = { 4.53743, 2.4, 60, 9.3, 7.0 };\n\n int cdata[6] = { -1, 1, -2, 2, -3, 3 };\n double x[5] = { 2.52, 2, 37.5, 9.25, 6.8 };\n double minf;\n\n nlopt_minimize_constrained(NLOPT_LN_COBYLA, 5, box, NULL, 6, box_constraint, cdata, sizeof(int), box_lb, box_ub, x, &minf, -HUGE_VAL, 1e-10, 0, 0, NULL, 0, 0);\n printf(\"found f(%g,%g,%g,%g,%g) = %0.8f after %d iters\\n\", x[0], x[1], x[2], x[3], x[4], minf, testfuncs_counter);\n return 0;\n}\n", "meta": {"hexsha": "3f92320779b872b96d1e78b3fff9ad534f4be5c6", "size": 5500, "ext": "c", "lang": "C", "max_stars_repo_path": "recipes/nlopt/all/test_package/test_package.c", "max_stars_repo_name": "rockandsalt/conan-center-index", "max_stars_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 562.0, "max_stars_repo_stars_event_min_datetime": "2019-09-04T12:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:41:43.000Z", "max_issues_repo_path": "recipes/nlopt/all/test_package/test_package.c", "max_issues_repo_name": "rockandsalt/conan-center-index", "max_issues_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9799.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T12:02:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:45.000Z", "max_forks_repo_path": "recipes/nlopt/all/test_package/test_package.c", "max_forks_repo_name": "rockandsalt/conan-center-index", "max_forks_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1126.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T11:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:43:38.000Z", "avg_line_length": 38.4615384615, "max_line_length": 173, "alphanum_fraction": 0.4609090909, "num_tokens": 2348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7634837635542925, "lm_q2_score": 0.45713671682749485, "lm_q1q2_score": 0.34901646102230865}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace thrustshift {\n\nnamespace permutation {\n\n/*! \\brief Return \\f$ P_b P_a^T \\f$\n *\n * \\param result `result[i]` is the index of element \\f$ a_i \\f$\n * after permutation \\f$ P_b \\f$ is applied to the natural order.\n */\ntemplate \nvoid multiply(PermutationA&& a,\n PermutationB&& b,\n ResultPermutation&& result,\n MemoryResource& memory_resource) {\n\n\tgsl_Expects(a.size() == b.size());\n\tgsl_Expects(result.size() == a.size());\n\n\tusing ResultIndex =\n\t typename std::remove_reference::type::value_type;\n\n\tauto [__, tmp] =\n\t make_not_a_vector_and_span(result.size(), memory_resource);\n\n\tauto cit_begin = thrust::make_counting_iterator(ResultIndex(0));\n\tauto cit_end = thrust::make_counting_iterator(\n\t gsl_lite::narrow(result.size()));\n\n\t// Rather use `.data()` in case the iterator class is not defined\n\t// in device code\n\tthrust::scatter(thrust::device, cit_begin, cit_end, b.data(), tmp.data());\n\tthrust::gather(thrust::device,\n\t a.data(),\n\t a.data() + a.size(),\n\t tmp.data(),\n\t result.data());\n}\n\n/*! \\brief Multiply successive permutations\n *\n * Assume you have \\f$N\\f$ permutations \\f$P_{N-1},...,P_0\\f$\n * and \\f$N\\f$ linear maps \\f$M_{N-1},...,M_0\\f$ where each\n * linear map \\f$M_i\\f$ operates on the new order described by\n * \\f$P_i\\f$ relatively to the natural order. If every\n * linear map is applied to a vector \\f$x\\f$ in natural order\n * it yields to:\n *\n * \\f[\n * P_{N-1}^T M_{N-1} P_{N-1} P_{N-2}^T M^{N-2} ... P_0^T M_0 P_0 x\n * \\f]\n *\n * The \\f$P_i\\f$ permutation matrices are given in vectorial form \\f$p_i\\f$\n * such that \\f$(P_i)_mn = 1\\f$ if \\f$(p_i)_m = n\\f$.\n *\n * \\param input_permutations Range of size N with ranges of length L each\n * \\param merged_permutations Range of size N - 1 with ranges of length L each.\n * merged_permutations[i] = \\f$P_{i+1} P_{i}^T\\f$\n */\ntemplate \nvoid multiply_successive(InputPermutations&& input_permutations,\n MergedPermutations&& multiplied_permutations,\n MemoryResource& memory_resource) {\n\n\tconst auto N = input_permutations.size();\n\n\tif (N == 0) {\n\t\treturn;\n\t}\n\n\tgsl_Expects(N > 0);\n\tgsl_Expects(N == multiplied_permutations.size() + 1);\n\n\tfor (size_t i = 0; i < input_permutations.size() - 1; ++i) {\n\t\tmultiply(input_permutations[i],\n\t\t input_permutations[i + 1],\n\t\t multiplied_permutations[i],\n\t\t memory_resource);\n\t}\n}\n\n/*! \\brief Bitoptimized successive pairwise permutation\n *\n * This class saves a permutation of `I = {0,...,N-1}`, which\n * is created by successive pairwise swaps of the sequence `I`:\n *\n * ```cpp\n * for (int j = 1; j < N; ++j) {\n * if (do_swap[j - 1]) {\n * swap(I[j - 1], I[j]);\n * }\n * }\n * ```\n *\n * The array `do_swap[]` saves if two values are swapped and is saved in\n * a bit pattern within this class.\n * This can also be seen as a path in a binary tree with `N` levels because\n * the internal representation is a bit pattern, which sets the bit if the\n * swap is not done. `N` is limited by the amount of Bits in `BitPatternT`.\n * If `operator[]` is called once, no function to change the `do_swap`\n * array should be called by the user. The state of the class is then a\n * read-only mode. Moreover the array `I` can only be read successively\n * by the `operator[]`. Thus reading the pattern starts with the last element\n * `i = N - 1` and in the next call `i = i - 1` must be used as a function argument.\n * This is an highly unsafe class design, which is chosen to avoid the\n * usage of additional registers. E.g. the safety of the class can be\n * greatly improved if one register is added, which is avoided here\n * due to performance reasons.\n *\n * \\note When `std::bitset` is supported for device code. This should be\n * used to save the bit pattern\n * \\note When compiled for device code CUDA currently supports built-in\n * function to count leading zeros `clz` for `int` and `long long int`, which\n * then must be used for `BitPatternT`.\n */\ntemplate \nclass bit_successive_permutation_t {\n\n public:\n\tCUDA_FHD bit_successive_permutation_t(int N)\n\t : bit_pattern_(BitPatternT(1) << (N - 1)) {\n\t\tgsl_Expects(N <= sizeof(BitPatternT) * 8);\n#ifndef NDEBUG\n\t\tN_ = N;\n#endif\n\t}\n\n\tCUDA_FHD void do_swap(int j) {\n\t\tgsl_Expects(j < sizeof(BitPatternT) * 8);\n#ifndef NDEBUG\n\t\tgsl_Expects(!read_only_mode_);\n\t\tgsl_Expects(j < N_ - 1);\n#endif\n\t\tbit_pattern_ &= ~(BitPatternT(1) << j);\n\t}\n\n\tCUDA_FHD void do_not_swap(int j) {\n\t\tgsl_Expects(j < sizeof(BitPatternT) * 8);\n#ifndef NDEBUG\n\t\tgsl_Expects(!read_only_mode_);\n\t\tgsl_Expects(j < N_ - 1);\n#endif\n\t\tbit_pattern_ |= (BitPatternT(1) << j);\n\t}\n\n\tCUDA_FHD void set(int j, bool do_swap_) {\n\t\tif (do_swap_) {\n\t\t\tdo_swap(j);\n\t\t}\n\t\telse {\n\t\t\tdo_not_swap(j);\n\t\t}\n\t}\n\n\tCUDA_FHD int operator[](int i) {\n\t\tgsl_Expects(i < sizeof(BitPatternT) * 8);\n#ifndef NDEBUG\n\t\tgsl_Expects(i < N_);\n\t\tif (!read_only_mode_) {\n\t\t\tread_only_mode_ = true;\n\t\t\tlast_i_ = N_;\n\t\t}\n\t\tgsl_Expects(i == last_i_ - 1);\n\t\tlast_i_ = i;\n#endif\n\t\tgsl_Expects(i >= 0);\n\t\tconst bool flag = (1ll << i) & bit_pattern_;\n\t\tbit_pattern_ &= ~(1ll << i);\n\n\t\tif (flag) {\n\t\t\tconst int lz = count_leading_zeros(bit_pattern_);\n\t\t\treturn sizeof(BitPatternT) * 8 - lz;\n\t\t}\n\t\telse {\n\t\t\treturn i + 1;\n\t\t}\n\t}\n\n private:\n#ifndef NDEBUG\n\tbool read_only_mode_ = false;\n\tint N_;\n\tint last_i_;\n#endif\n\tBitPatternT bit_pattern_;\n};\n\n} // namespace permutation\n\n} // namespace thrustshift\n", "meta": {"hexsha": "924738cf1ac8422f2ae7fd582082fcd254b58779", "size": 6251, "ext": "h", "lang": "C", "max_stars_repo_path": "include/thrustshift/permutation.h", "max_stars_repo_name": "pauleonix/thrustshift", "max_stars_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T13:01:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T13:01:46.000Z", "max_issues_repo_path": "include/thrustshift/permutation.h", "max_issues_repo_name": "pauleonix/thrustshift", "max_issues_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-03-23T14:12:08.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-17T11:40:04.000Z", "max_forks_repo_path": "include/thrustshift/permutation.h", "max_forks_repo_name": "pauleonix/thrustshift", "max_forks_repo_head_hexsha": "763805f862e3121374286c927dd6949960bffb84", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0744186047, "max_line_length": 85, "alphanum_fraction": 0.6550951848, "num_tokens": 1785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.588889130767832, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.3490149188820786}} {"text": "/***************************************************************************/\n/* */\n/* QR_decomp.c - LU Decomposition class for mruby */\n/* Copyright (C) 2015 Paolo Bosetti */\n/* paolo[dot]bosetti[at]unitn.it */\n/* Department of Industrial Engineering, University of Trento */\n/* */\n/* This library is free software. You can redistribute it and/or */\n/* modify it under the terms of the GNU GENERAL PUBLIC LICENSE 2.0. */\n/* */\n/* This library is distributed in the hope that it will be useful, */\n/* but WITHOUT ANY WARRANTY; without even the implied warranty of */\n/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */\n/* Artistic License 2.0 for more details. */\n/* */\n/* See the file LICENSE */\n/* */\n/***************************************************************************/\n\n#include \n#include \n#include \"matrix.h\"\n#include \"vector.h\"\n#include \"QR_decomp.h\"\n\n#ifndef MIN\n#define MAX(a, b) \\\n ({ \\\n __typeof__(a) _a = (a); \\\n __typeof__(b) _b = (b); \\\n _a < _b ? _a : _b; \\\n })\n#endif\n\n#pragma mark -\n#pragma mark • Utilities\n\n// Garbage collector handler, for play_data struct\n// if play_data contains other dynamic data, free it too!\n// Check it with GC.start\nvoid qr_decomp_destructor(mrb_state *mrb, void *p_) {\n qr_decomp_data_s *lu = (qr_decomp_data_s *)p_;\n gsl_matrix_free(lu->mat);\n gsl_vector_free(lu->tau);\n free(lu);\n};\n\n// Creating data type and reference for GC, in a const struct\nconst struct mrb_data_type qr_decomp_data_type = {\"qr_decomp_data\",\n qr_decomp_destructor};\n\n// Utility function for getting the struct out of the wrapping IV @data\nvoid mrb_qr_decomp_get_data(mrb_state *mrb, mrb_value self,\n qr_decomp_data_s **data) {\n mrb_value data_value;\n data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@data\"));\n\n // Loading data from data_value into p_data:\n Data_Get_Struct(mrb, data_value, &qr_decomp_data_type, *data);\n if (!*data)\n mrb_raise(mrb, E_RUNTIME_ERROR, \"Could not access @data\");\n}\n\n#pragma mark -\n#pragma mark • Initializations\n\n// Data Initializer C function (not exposed!)\nstatic mrb_value mrb_qr_initialize(mrb_state *mrb, mrb_value self) {\n mrb_value data_value; // this IV holds the data\n qr_decomp_data_s *p_data = NULL; // pointer to the C struct\n mrb_value matrix;\n gsl_matrix *p_mat = NULL;\n mrb_int size1, size2;\n\n mrb_get_args(mrb, \"o\", &matrix);\n if (!mrb_obj_is_kind_of(mrb, matrix, mrb_class_get(mrb, \"Matrix\"))) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"Argument must be a Matrix\");\n }\n\n mrb_matrix_get_data(mrb, matrix, &p_mat);\n // if (p_mat->size1 < p_mat->size2) {\n // mrb_raise(mrb, E_ARGUMENT_ERROR, \"Argument must be square or horizontal\n // Matrix\");\n // }\n size1 = p_mat->size1;\n size2 = p_mat->size2;\n\n data_value = mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@data\"));\n // if @data already exists, free its content:\n if (!mrb_nil_p(data_value)) {\n Data_Get_Struct(mrb, data_value, &qr_decomp_data_type, p_data);\n free(p_data);\n }\n // Allocate and zero-out the data struct:\n p_data = (qr_decomp_data_s *)malloc(sizeof(qr_decomp_data_s));\n if (!p_data) {\n mrb_raise(mrb, E_RUNTIME_ERROR, \"Could not allocate @data\");\n }\n p_data->size1 = size1;\n p_data->size2 = size2;\n p_data->minsize = MIN(size1, size2);\n p_data->mat = gsl_matrix_calloc(size1, size2);\n p_data->tau = gsl_vector_calloc(p_data->minsize);\n\n // copy argument matrix into local object data\n gsl_matrix_memcpy(p_data->mat, p_mat);\n // invert in-place\n gsl_linalg_QR_decomp(p_data->mat, p_data->tau);\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@size1\"), mrb_fixnum_value(size1));\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@size2\"), mrb_fixnum_value(size2));\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@minsize\"),\n mrb_fixnum_value(p_data->minsize));\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@residuals\"), mrb_nil_value());\n // Wrap struct into @data:\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@data\"), // set @data\n mrb_obj_value( // with value hold in struct\n Data_Wrap_Struct(mrb, mrb->object_class, &qr_decomp_data_type,\n p_data)));\n return mrb_nil_value();\n}\n\n#pragma mark -\n#pragma mark • Accessors\n\nstatic mrb_value mrb_qr_residuals(mrb_state *mrb, mrb_value self) {\n return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@residuals\"));\n}\n\nstatic mrb_value mrb_qr_minsize(mrb_state *mrb, mrb_value self) {\n return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@minsize\"));\n}\n\nstatic mrb_value mrb_qr_size1(mrb_state *mrb, mrb_value self) {\n return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@size1\"));\n}\n\nstatic mrb_value mrb_qr_size2(mrb_state *mrb, mrb_value self) {\n return mrb_iv_get(mrb, self, mrb_intern_lit(mrb, \"@size2\"));\n}\n\nstatic mrb_value mrb_qr_matrix(mrb_state *mrb, mrb_value self) {\n mrb_value result;\n qr_decomp_data_s *p_data = NULL;\n gsl_matrix *p_res = NULL;\n mrb_value args[2];\n\n // call utility for unwrapping @data into p_data:\n mrb_qr_decomp_get_data(mrb, self, &p_data);\n args[0] = mrb_fixnum_value(p_data->size1);\n args[1] = mrb_fixnum_value(p_data->size2);\n result = mrb_obj_new(mrb, mrb_class_get(mrb, \"Matrix\"), 2, args);\n mrb_matrix_get_data(mrb, result, &p_res);\n gsl_matrix_memcpy(p_res, p_data->mat);\n return result;\n}\n\nstatic mrb_value mrb_qr_tau(mrb_state *mrb, mrb_value self) {\n mrb_value result;\n qr_decomp_data_s *p_data = NULL;\n gsl_vector *p_res = NULL;\n mrb_value args[1];\n\n // call utility for unwrapping @data into p_data:\n mrb_qr_decomp_get_data(mrb, self, &p_data);\n args[0] = mrb_fixnum_value(p_data->minsize);\n result = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n mrb_vector_get_data(mrb, result, &p_res);\n gsl_vector_memcpy(p_res, p_data->tau);\n return result;\n}\n\n#pragma mark -\n#pragma mark • Operations\n\n// int gsl_linalg_QR_solve (const gsl_matrix * QR, const gsl_vector * tau, const\n// gsl_vector * b, gsl_vector * x)\nstatic mrb_value mrb_qr_solve(mrb_state *mrb, mrb_value self) {\n mrb_value result, b_vec;\n qr_decomp_data_s *p_data = NULL;\n gsl_vector *p_result = NULL, *p_b = NULL;\n mrb_value args[1];\n\n mrb_get_args(mrb, \"o\", &b_vec);\n if (!mrb_obj_is_kind_of(mrb, b_vec, mrb_class_get(mrb, \"Vector\"))) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"Argument must be a Vector\");\n }\n\n // call utility for unwrapping @data into p_data:\n mrb_qr_decomp_get_data(mrb, self, &p_data);\n if (p_data->size1 != p_data->size2) {\n mrb_raise(mrb, E_QR_DECOMP_ERROR, \"Matrix must be square\");\n }\n\n args[0] = mrb_fixnum_value(p_data->tau->size);\n result = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n mrb_vector_get_data(mrb, result, &p_result);\n mrb_vector_get_data(mrb, b_vec, &p_b);\n\n if (gsl_linalg_QR_solve(p_data->mat, p_data->tau, p_b, p_result)) {\n mrb_raise(mrb, E_QR_DECOMP_ERROR, \"Singular matrix\");\n }\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@residuals\"), mrb_nil_value());\n return result;\n}\n\n// int gsl_linalg_QR_lssolve (const gsl_matrix * QR, const gsl_vector * tau,\n// const gsl_vector * b, gsl_vector * x, gsl_vector * residual)\nstatic mrb_value mrb_qr_lssolve(mrb_state *mrb, mrb_value self) {\n mrb_value result, b_vec, residuals;\n qr_decomp_data_s *p_data = NULL;\n gsl_vector *p_result = NULL, *p_b = NULL, *p_residuals;\n mrb_value args[1];\n\n mrb_get_args(mrb, \"o\", &b_vec);\n if (!mrb_obj_is_kind_of(mrb, b_vec, mrb_class_get(mrb, \"Vector\"))) {\n mrb_raise(mrb, E_ARGUMENT_ERROR, \"Argument must be a Vector\");\n }\n\n // call utility for unwrapping @data into p_data:\n mrb_qr_decomp_get_data(mrb, self, &p_data);\n if (p_data->size1 <= p_data->size2) {\n mrb_raise(mrb, E_QR_DECOMP_ERROR,\n \"Matrix must have more rows than columns\");\n }\n\n args[0] = mrb_fixnum_value(p_data->size2);\n result = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n mrb_vector_get_data(mrb, result, &p_result);\n mrb_vector_get_data(mrb, b_vec, &p_b);\n\n args[0] = mrb_fixnum_value(p_b->size);\n residuals = mrb_obj_new(mrb, mrb_class_get(mrb, \"Vector\"), 1, args);\n mrb_vector_get_data(mrb, residuals, &p_residuals);\n mrb_iv_set(mrb, self, mrb_intern_lit(mrb, \"@residuals\"), residuals);\n\n if (gsl_linalg_QR_lssolve(p_data->mat, p_data->tau, p_b, p_result,\n p_residuals)) {\n mrb_raise(mrb, E_QR_DECOMP_ERROR, \"Singular matrix\");\n }\n return result;\n}\n\n#pragma mark -\n#pragma mark • Gem setup\n\nvoid mrb_gsl_qr_decomp_init(mrb_state *mrb) {\n struct RClass *lu;\n\n mrb_load_string(mrb, \"class QRDecompError < Exception; end\");\n\n lu = mrb_define_class(mrb, \"QRDecomp\", mrb->object_class);\n mrb_define_method(mrb, lu, \"residuals\", mrb_qr_residuals, MRB_ARGS_NONE());\n mrb_define_method(mrb, lu, \"matrix\", mrb_qr_matrix, MRB_ARGS_NONE());\n mrb_define_method(mrb, lu, \"tau\", mrb_qr_tau, MRB_ARGS_NONE());\n mrb_define_method(mrb, lu, \"size1\", mrb_qr_size1, MRB_ARGS_NONE());\n mrb_define_method(mrb, lu, \"size2\", mrb_qr_size2, MRB_ARGS_NONE());\n mrb_define_method(mrb, lu, \"minsize\", mrb_qr_minsize, MRB_ARGS_NONE());\n\n mrb_define_method(mrb, lu, \"initialize\", mrb_qr_initialize, MRB_ARGS_REQ(1));\n mrb_define_method(mrb, lu, \"solve\", mrb_qr_solve, MRB_ARGS_REQ(1));\n mrb_define_method(mrb, lu, \"lssolve\", mrb_qr_lssolve, MRB_ARGS_REQ(1));\n}\n", "meta": {"hexsha": "3f767de5f3058bf3d5e76d817e4bad30547638a9", "size": 10243, "ext": "c", "lang": "C", "max_stars_repo_path": "src/QR_decomp.c", "max_stars_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_stars_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_stars_repo_licenses": ["MIT"], "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/QR_decomp.c", "max_issues_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_issues_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/QR_decomp.c", "max_forks_repo_name": "UniTN-Mechatronics/mruby-gsl", "max_forks_repo_head_hexsha": "0961ef3b88bb8ed9e9223b2678ece281acaa0f4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9467680608, "max_line_length": 80, "alphanum_fraction": 0.6288196817, "num_tokens": 2794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858118, "lm_q2_score": 0.6039318337259583, "lm_q1q2_score": 0.34876783486490925}} {"text": "///\n/// @file\n///\n/// @author Angelika Schwarz (angies@cs.umu.se), Umeå University\n///\n/// @internal LICENSE\n///\n/// Copyright (c) 2019-2020, Umeå Universitet\n///\n/// Redistribution and use in source and binary forms, with or without\n/// modification, are permitted provided that the following conditions are met:\n///\n/// 1. Redistributions of source code must retain the above copyright notice,\n/// this list of conditions and the following disclaimer.\n///\n/// 2. Redistributions in binary form must reproduce the above copyright notice,\n/// this list of conditions and the following disclaimer in the documentation\n/// and/or other materials provided with the distribution.\n///\n/// 3. Neither the name of the copyright holder nor the names of its\n/// contributors may be used to endorse or promote products derived from this\n/// software without specific prior written permission.\n///\n/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n/// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n/// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n/// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n/// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n/// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n/// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n/// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n/// POSSIBILITY OF SUCH DAMAGE.\n///\n\n#include \n#include \n\n#include \"typedefs.h\"\n#include \"cpu.h\"\n// #include \"tasks.h\" // <--- moved to misc/\n#include \"robust.h\"\n\n#include \"../../common/common.h\"\n#include \"../../common/tiles.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstatic double vec_real_infnorm(int n, const double *x)\n{\n double norm = 0.0;\n for (int i = 0; i < n; ++i) {\n double abs = fabs(x[i]);\n if (abs > norm)\n norm = abs;\n }\n\n return norm;\n}\n\nstatic double vec_cmplx_infnorm(int n, const double *x_re, const double *x_im)\n{\n double norm = 0.0;\n for (int i = 0; i < n; ++i) {\n // Compute len = sqrt(x_re[i]*x_re[i]+x_im[i]*x_im[i]) robustly.\n double maxabs = MAX(fabs(x_re[i]), fabs(x_im[i]));\n double len = maxabs*sqrt( (x_re[i]/maxabs)*(x_re[i]/maxabs)\n + (x_im[i]/maxabs)*(x_im[i]/maxabs));\n\n if (len > norm)\n norm = len;\n }\n\n return norm;\n}\n\nstatic double mat_infnorm(int m, int n, const double *A, int ldA)\n{\n#define A(i,j) A[(i) + (j) * (size_t)ldA]\n\n double *rowsums = calloc(m, sizeof(double));\n\n for (int j = 0; j < n; ++j)\n for (int i = 0; i < m; i++)\n rowsums[i] += fabs(A(i,j));\n\n double norm = rowsums[0];\n for (int i = 1; i < m; i++)\n if (rowsums[i] > norm)\n norm = rowsums[i];\n\n free(rowsums);\n\n return norm;\n\n#undef A\n}\n\n\nstatic void find_max(\n int num_rows, int num_selected, int n,\n const double *restrict const X, int ldX,\n const int *restrict const lambda_type, const int *restrict const selected,\n double *restrict emax)\n{\n int si = num_selected-1;\n for (int ki = n-1; ki >= 0; ki--) {\n if (!selected[ki]) {\n // Proceed with the next eigenvalue.\n if (lambda_type[ki] == 1) { // CMPLX\n // A complex conjugate pair of eigenvalues is not selected, so\n // skip the next diagonal entry.\n ki--;\n }\n }\n else { // ki-th eigenvalue is selected\n if (lambda_type[ki] == 0) { // REAL\n // Locate eigenvector to ki-th eigenvalue.\n const double *X_re = X+si*(size_t)ldX;\n\n // Find max entry.\n emax[si] = vec_real_infnorm(num_rows, X_re);\n si--;\n }\n else { // CMPLX\n // Locate real and imaginary part of complex eigenvector for\n // complex conjugate pair of eigenvalues (ki, ki-1).\n const double *X_re = X+(si-1)*(size_t)ldX;\n const double *X_im = X+si*(size_t)ldX;\n\n // Find max entry.\n emax[si] = 0.0;\n for (int i = 0; i < num_rows; i++)\n if (fabs(X_re[i])+fabs(X_im[i]) > emax[si])\n emax[si] = fabs(X_re[i])+fabs(X_im[i]);\n\n // Duplicate max entry for real and imaginary column.\n emax[si-1] = emax[si];\n\n ki--;\n si -= 2;\n }\n }\n }\n}\n\n\n\n\nvoid starneig_eigvec_std_unify_scaling(int num_tiles, int *first_row, int *first_col,\n scaling_t *restrict scales,\n double *restrict X, int ldX,\n const int *restrict lambda_type, const int *restrict selected)\n{\n // TODO: Is it possible to add a #pragma parallel for here?\n\n const int num_selected = first_col[num_tiles];\n\n //\n // Compute the most constraining scaling factor.\n //\n scaling_t *smin = (scaling_t *) malloc(num_selected*sizeof(scaling_t));\n starneig_eigvec_std_init_scaling_factor(num_selected, smin);\n\n starneig_eigvec_std_find_smallest_scaling(num_tiles, num_selected, scales, smin);\n\n#ifndef STARNEIG_ENABLE_INTEGER_SCALING\n\n //\n // Check if the range of double-precision scaling factors was sufficient\n // and replace flushed entries with 1/Omega to avoid NaNs.\n //\n\n for (int i = 0; i < num_selected; i++) {\n if (smin[i] == 0.0) {\n if (lambda_type[i] == 1) { // CMPLX\n starneig_warning(\"Scaling factor of complex eigenvector \"\n \"X(:,%d:%d) was flushed. Rerun with integer \"\n \"scaling factors.\", i, i+1);\n smin[i] = DBL_MIN;\n smin[i+1] = DBL_MIN;\n i++;\n }\n else { // REAL\n starneig_warning(\"Scaling factor of real eigenvector X(:,%d) \"\n \"was flushed. Rerun with integer \"\n \"scaling factors.\", i);\n smin[i] = DBL_MIN;\n\n }\n }\n }\n\n for (int i = 0; i < (size_t)num_tiles*num_selected;i++)\n if (scales[i] == 0.0)\n scales[i] = DBL_MIN;\n\n#endif\n\n double *tmp = (double *) malloc(num_selected * sizeof(double));\n double *emax = (double *) malloc(num_selected * sizeof(double));\n memset(emax, 0.0, num_selected * sizeof(double));\n\n#define scales(col, tilerow) scales[(col) + (tilerow) * (size_t)num_selected]\n\n for (int blkj = 0; blkj < num_tiles; blkj++) {\n for (int blki = 0; blki <= blkj; blki++) {\n const int num_rows = first_row[blki+1]-first_row[blki];\n const int num_sel = first_col[blkj+1]-first_col[blkj];\n const int num_cols = first_row[blkj+1]-first_row[blkj];\n\n double *tile = X+(size_t)first_col[blkj]*ldX+first_row[blki];\n const int *lambda_type_tile = lambda_type+first_row[blkj];\n const int *selected_tile = selected+first_row[blkj];\n double *tmp_tile = tmp+first_col[blkj];\n memset(tmp_tile, 0.0, num_sel*sizeof(double));\n\n find_max(num_rows, num_sel, num_cols,\n tile, ldX, lambda_type_tile, selected_tile, tmp_tile);\n\n // Reduce to maximum normalization factor.\n for (int j = first_col[blkj]; j < first_col[blkj+1]; j++) {\n // Compute normalization factor simulating consistent scaling.\n double s = starneig_eigvec_std_compute_upscaling(smin[j], scales(j, blki));\n emax[j] = MAX(s * tmp[j], emax[j]);\n }\n }\n\n // Apply scaling.\n for (int blki = 0; blki <= blkj; blki++) {\n const int num_rows = first_row[blki+1]-first_row[blki];\n const int num_cols = first_col[blkj+1]-first_col[blkj];\n\n // Scale column.\n for (int j = 0; j < num_cols; j++) {\n // The current column index.\n size_t col = (size_t)first_col[blkj]+j;\n\n // The current column.\n double *x = X+col*ldX+first_row[blki];\n double s =\n starneig_eigvec_std_compute_upscaling(smin[col], scales(col, blki));\n\n // Avoid oo.\n if (isinf(s))\n s = DBL_MIN;\n\n for (int i = 0; i < num_rows; i++)\n x[i] = (s*x[i])/emax[col];\n }\n }\n }\n\n free(tmp);\n free(emax);\n#undef scales\n}\n\n\nvoid starneig_eigvec_std_cpu_bound_DM(void *buffers[], void *cl_args)\n{\n struct packing_info packing_info;\n starpu_codelet_unpack_args(cl_args, &packing_info);\n\n // extract tile dimensions from the packing information struct\n int m = packing_info.rend - packing_info.rbegin;\n int n = packing_info.cend - packing_info.cbegin;\n\n int k = 0;\n\n double *norm = (double *) STARPU_VARIABLE_GET_PTR(buffers[k]);\n k++;\n\n double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[k]);\n int ldT = STARPU_MATRIX_GET_LD(buffers[k]);\n k++;\n\n struct starpu_matrix_interface **A_i =\n (struct starpu_matrix_interface **)buffers + k;\n k += packing_info.handles;\n\n starneig_join_diag_window(&packing_info, ldT, A_i, T, 0);\n\n *norm = mat_infnorm(m, n, T, ldT);\n}\n\n\nvoid starneig_eigvec_std_cpu_bound(void *buffers[], void *cl_args)\n{\n double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);\n int ldT = STARPU_MATRIX_GET_LD(buffers[0]);\n int m = STARPU_MATRIX_GET_NX(buffers[0]);\n int n = STARPU_MATRIX_GET_NY(buffers[0]);\n\n double *tnorm = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);\n double ub = mat_infnorm(m, n, T, ldT);\n *tnorm = ub;\n}\n\n\n\nstatic void backsolve(\n int n, const double *restrict T, int ldT, double tnorm,\n double *restrict X, int ldX, scaling_t *restrict const scales,\n double *restrict Xnorms, const int *restrict lambda_type,\n const int *restrict selected, int num_selected,\n double smlnum, int *restrict infos)\n{\n#define T(i,j) T[(i) + (j) * (size_t)ldT]\n\n // Solve T * X = X * \\Lambda.\n\n // The i-th selected eigenvalue.\n int si = num_selected-1;\n\n // Loop over eigenvalues from bottom to top.\n for (int ki = n-1; ki >= 0; ki--) {\n if (!selected[ki]) {\n // Proceed with the next eigenvalue.\n if (lambda_type[ki] == 1) { // CMPLX\n // A complex conjugate pair of eigenvalues is not selected,\n // so skip the next diagonal entry.\n ki--;\n }\n }\n else { // ki-th eigenvalue is selected\n\n // Error flag.\n int info = 0;\n\n if (lambda_type[ki] == 0) {\n // Compute a real right eigenvector.\n double lambda = T(ki,ki);\n\n // Locate eigenvector to ki-th eigenvalue.\n double *X_re = X+si*(size_t)ldX;\n\n // Locate corresponding scaling factor.\n scaling_t *beta = scales+si;\n\n // Critical threshold to detect unsafe divisions.\n const double smin = MAX(DBL_EPSILON/2*fabs(lambda), smlnum);\n\n // Form right-hand side.\n X_re[ki] = 1.0;\n for (int i = 0; i < ki; i++)\n X_re[i] = -T(i, ki);\n for (int i = ki+1; i < n; i++)\n X_re[i] = 0.0;\n\n // Compute norm of entire vector.\n double norm = vec_real_infnorm(ki+1, X_re);\n\n // Solve the upper quasi-triangular system.\n // (T(0:ki-1,0:ki-1) - lambda I) \\ X.\n for (int j = ki-1; j >= 0; j--) {\n // if next block is 1-by-1 diagonal block:\n if (lambda_type[j] == 0) { // REAL\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_1x1_real_system(\n smin, T(j,j), lambda, X_re+j, &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale remaining parts of the vector.\n starneig_eigvec_std_scale(j, X_re, &phi);\n starneig_eigvec_std_scale(ki-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the linear update.\n phi =\n starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply the scaling to the whole eigenvector.\n starneig_eigvec_std_scale(ki+1, X_re, &phi);\n\n // Now it is safe to execute the linear update.\n for (int i = 0; i < j; i++)\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n\n // Recompute norm excluding the entries j:n.\n norm = vec_real_infnorm(j, X_re);\n }\n // if next block is 2-by-2 diagonal block:\n else {\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_2x2_real_system(smin,\n &T(j-1,j-1), ldT, lambda, &X_re[j-1], &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale remaining parts of vector.\n starneig_eigvec_std_scale(j-1, X_re, &phi);\n starneig_eigvec_std_scale(ki-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the first linear update.\n phi = starneig_eigvec_std_protect_update(\n tnorm, fabs(X_re[j-1]), norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply the scaling to the whole eigenvector.\n starneig_eigvec_std_scale(ki+1, X_re, &phi);\n\n // Now it is safe to execute the first linear update.\n for (int i = 0; i < j-1; i++)\n X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];\n\n // Recompute norm excluding the entries j:n.\n norm = vec_real_infnorm(j, X_re);\n\n // Protect against overflow in the second linear update.\n phi =\n starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply the scaling to the whole eigenvector.\n starneig_eigvec_std_scale(ki+1, X_re, &phi);\n\n // Now it is safe to execute the second linear update.\n for (int i = 0; i < j-1; i++)\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n\n // Recompute norm excluding the entries j-1:n.\n norm = vec_real_infnorm(j-1, X_re);\n\n // We processed a 2-by-2 block, so skip the next entry.\n j--;\n }\n }\n\n // The ki-th real eigenvector has been computed. Recompute norm.\n Xnorms[si] = vec_real_infnorm(ki+1, X_re);\n\n // Record error flag.\n infos[si] = info;\n\n // This eigenvector spans 1 column. Update selected counter.\n si--;\n }\n else { // lambda_type[ki] == CMPLX\n // Locate real and imaginary part of complex eigenvector for\n // complex conjugate pair of eigenvalues (ki, ki-1).\n double *X_re = X+(si-1)*(size_t)ldX;\n double *X_im = X+si*(size_t)ldX;\n\n // Locate corresponding scaling factor, one per complex pair.\n scaling_t *beta = scales+si;\n\n // Compute eigenvalue as lambda = lambda_re + i * lambda_im.\n // A 2-by-2 block in canonical Schur form has the shape\n // [ T(ki-1,ki-1) T(ki-1,ki) ] = [ a b ] or [ a -b ]\n // [ T(ki, ki-1) T(ki, ki) ] [-c a ] [ c a ].\n double lambda_re = T(ki,ki);\n double lambda_im =\n sqrt(fabs(T(ki,ki-1)))*sqrt(fabs(T(ki-1,ki)));\n\n // Critical threshold to detect unsafe divisions.\n const double smin = MAX(\n DBL_EPSILON/2*(fabs(lambda_re)+fabs(lambda_im)), smlnum);\n\n // Form right-hand side.\n if (fabs(T(ki-1,ki)) >= fabs(T(ki,ki-1))) {\n X_re[ki-1] = 1.0;\n X_im[ki] = lambda_im/T(ki-1,ki);\n }\n else {\n X_re[ki-1] = -lambda_im/T(ki,ki-1);\n X_im[ki] = 1.0;\n }\n X_re[ki] = 0.0;\n X_im[ki-1] = 0.0;\n for (int i = 0; i < ki-1; i++) {\n X_re[i] = -X_re[ki-1]*T(i,ki-1);\n X_im[i] = -X_im[ki]*T(i,ki);\n }\n for (int i = ki+1; i < n; i++) {\n X_re[i] = 0.0;\n X_im[i] = 0.0;\n }\n\n // Compute norm of the entire vector.\n double norm = vec_cmplx_infnorm(ki+1, X_re, X_im);\n\n // Solve the upper quasi-triangular system\n // (T(0:ki-2,0:ki-2) - (lambda * I) \\ (X_re + i * X_im).\n\n // Loop over triangular matrix above the eigenvalue. Note ki-2!\n for (int j = ki-2; j >= 0; j--) {\n // If next block is 1-by-1 diagonal bock:\n if (lambda_type[j] == 0) { // REAL\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_1x1_cmplx_system(\n smin, T(j,j), lambda_re, lambda_im,\n X_re+j, X_im+j, &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale the remaining parts of the vector.\n starneig_eigvec_std_scale(j, X_re, &phi);\n starneig_eigvec_std_scale(ki-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_scale(j, X_im, &phi);\n starneig_eigvec_std_scale(ki-(j+1), X_im+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the linear update.\n double absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));\n phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply scaling to the whole eigenvector.\n starneig_eigvec_std_scale(ki+1, X_re, &phi);\n starneig_eigvec_std_scale(ki+1, X_im, &phi);\n\n // Now it is safe to execute the linear update.\n for (int i = 0; i < j; i++) {\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n X_im[i] = X_im[i]-T(i,j)*X_im[j];\n }\n\n // Recompute norm excluding the entries j:n.\n norm = vec_cmplx_infnorm(j, X_re, X_im);\n }\n // If next block is 2-by-2 diagonal block:\n else {\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_2x2_cmplx_system(\n smin, &T(j-1,j-1), ldT, lambda_re, lambda_im,\n X_re+j-1, X_im+j-1, &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale the remaining parts of the vector.\n starneig_eigvec_std_scale(j-1, X_re, &phi);\n starneig_eigvec_std_scale(ki-j, X_re+(j+1), &phi);\n starneig_eigvec_std_scale(j-1, X_im, &phi);\n starneig_eigvec_std_scale(ki-j, X_im+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the first linear update.\n double absmax = MAX(fabs(X_re[j-1]), fabs(X_im[j-1]));\n phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply scaling to the whole eigenvector.\n starneig_eigvec_std_scale(ki+1, X_re, &phi);\n starneig_eigvec_std_scale(ki+1, X_im, &phi);\n\n // Now it is safe to execute the first linear update.\n for (int i = 0; i < j-1; i++) {\n X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];\n X_im[i] = X_im[i]-T(i,j-1)*X_im[j-1];\n }\n\n // Recompute norm excluding the entries j+1:n.\n norm = vec_cmplx_infnorm(j+1, X_re, X_im);\n\n // Protect against overflow in the second linear update.\n absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));\n phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply scaling to the whole eigenvector.\n starneig_eigvec_std_scale(ki+1, X_re, &phi);\n starneig_eigvec_std_scale(ki+1, X_im, &phi);\n\n // Now it is safe to execute the second linear update.\n for (int i = 0; i < j-1; i++) {\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n X_im[i] = X_im[i]-T(i,j)*X_im[j];\n }\n\n // Recompute norm excluding the entries j:n.\n norm = vec_cmplx_infnorm(j-1, X_re, X_im);\n\n // We processed a 2-by-2 block, so skip the next entry.\n j--;\n }\n }\n\n // Note that the second column of a complex conjugate pair is\n // never allocated or computed. Obtaining it is left to the\n // user. If the positions si - 1, si mark a 2-by-2 block, then\n // the eigenvector corresponding to lambda = alpha + i beta\n // is X(:, si - 1) + i * X(:, si).\n // The complex conjugate eigenvector corresponding to\n // lambda = alpha - i beta can be derived as\n // conj(X) := X(:, si -1) - i * X(:, si).\n\n // The real part and the imaginary part are scaled alike.\n scales[si-1] = scales[si];\n\n // The ki-th complex eigenvector has been computed. Recompute\n // norm of the complex eigenvector.\n Xnorms[si] = vec_cmplx_infnorm(ki+1, X_re, X_im);\n Xnorms[si-1] = Xnorms[si];\n\n // Record error flag.\n infos[si] = info;\n infos[si-1] = info;\n\n // We processed a complex conjugate pair of eigenvalues,\n // so skip the next entry.\n ki--;\n\n // This eigenvector spans 2 columns. Update selected counter.\n si -= 2;\n }\n }\n }\n\n // Note that the eigenvectors are not normalized.\n\n#undef T\n\n\n}\n\n\n\n\nvoid starneig_eigvec_std_cpu_backsolve(void *buffers[], void *cl_args)\n{\n double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);\n int n = STARPU_MATRIX_GET_NX(buffers[0]);\n int ldT = STARPU_MATRIX_GET_LD(buffers[0]);\n\n double *ubT = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);\n double tnorm = *ubT;\n\n double *X = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);\n int num_selected = STARPU_MATRIX_GET_NY(buffers[2]);\n int ldX = STARPU_MATRIX_GET_LD(buffers[2]);\n\n scaling_t *scales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[3]);\n\n double *Xnorms = (double *) STARPU_VECTOR_GET_PTR(buffers[4]);\n\n int *lambda_type = (int *) STARPU_VECTOR_GET_PTR(buffers[5]);\n\n int *selected = (int *) STARPU_VECTOR_GET_PTR(buffers[6]);\n\n int *infos = (int *) STARPU_VECTOR_GET_PTR(buffers[7]);\n\n double smlnum;\n starpu_codelet_unpack_args(cl_args, &smlnum);\n\n backsolve(n, T, ldT, tnorm, X, ldX, scales, Xnorms, lambda_type,\n selected, num_selected, smlnum, infos);\n}\n\n\nvoid starneig_eigvec_std_cpu_solve(void *buffers[], void *cl_args)\n{\n double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);\n int n = STARPU_MATRIX_GET_NX(buffers[0]);\n int ldT = STARPU_MATRIX_GET_LD(buffers[0]);\n\n double *ubT = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);\n double tnorm = *ubT;\n\n double *X = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);\n int num_selected = STARPU_MATRIX_GET_NY(buffers[2]);\n int ldX = STARPU_MATRIX_GET_LD(buffers[2]);\n\n scaling_t *scales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[3]);\n\n double *Xnorms = (double *) STARPU_VECTOR_GET_PTR(buffers[4]);\n\n double *lambda = (double *) STARPU_VECTOR_GET_PTR(buffers[5]);\n int num_rhs = STARPU_VECTOR_GET_NX(buffers[5]);\n\n int *lambda_type = (int *) STARPU_VECTOR_GET_PTR(buffers[6]);\n\n int *selected = (int *) STARPU_VECTOR_GET_PTR(buffers[7]);\n\n int *diag_type = (int *) STARPU_VECTOR_GET_PTR(buffers[8]);\n\n int *infos = (int *) STARPU_VECTOR_GET_PTR(buffers[9]);\n\n double smlnum;\n starpu_codelet_unpack_args(cl_args, &smlnum);\n\n#define T(i,j) T[(i) + (j) * (size_t)ldT]\n // The i-th selected eigenvalue.\n int si = num_selected-1;\n\n // Loop over eigenvalues.\n for (int k = num_rhs-1; k >= 0; k--) {\n if (!selected[k]) {\n // Proceed with the next eigenvalue.\n if (lambda_type[k] == 1) { // CMPLX\n // A complex conjugate pair of eigenvalues is not selected,\n // so skip the next diagonal entry.\n k--;\n }\n }\n else { // k-th eigenvalue is selected\n\n // Error flag.\n int info = 0;\n\n if (lambda_type[k] == 0) { // REAL\n // Locate eigenvector to k-th eigenvalue.\n double *X_re = X+si*(size_t)ldX;\n\n // Locate corresponding scaling factor.\n scaling_t *beta = scales+si;\n\n // Compute norm of entire vector.\n double norm = vec_real_infnorm(n, X_re);\n\n // Critical threshold to detect unsafe divisions.\n const double smin = MAX(DBL_EPSILON/2*fabs(lambda[k]), smlnum);\n\n\n for (int j = n-1; j >= 0; j--) {\n // if next block is 1-by-1 diagonal block:\n if (diag_type[j] == 0) { // REAL\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_1x1_real_system(\n smin, T(j,j), lambda[k], X_re+j, &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale remaining parts of vector.\n starneig_eigvec_std_scale(j, X_re, &phi);\n starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the linear update.\n phi =\n starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply the scaling to the whole eigenvector.\n starneig_eigvec_std_scale(n, X_re, &phi);\n\n // Now it is safe to execute the linear update.\n for (int i = 0; i < j; i++)\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n\n // Recompute norm excluding the entries j:n.\n norm = vec_real_infnorm(j, X_re);\n }\n // if next block is 2-by-2 block:\n else {\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_2x2_real_system(smin,\n &T(j-1,j-1), ldT, lambda[k], &X_re[j-1], &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale remaining parts of vector.\n starneig_eigvec_std_scale(j-1, X_re, &phi);\n starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect first linear update against overflow.\n phi = starneig_eigvec_std_protect_update(\n tnorm, fabs(X_re[j-1]), norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply the scaling to the whole eigenvector.\n starneig_eigvec_std_scale(n, X_re, &phi);\n\n // Now it is safe to execute the linear udpate.\n for (int i = 0; i < j-1; i++)\n X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];\n\n // Recompute norm excluding the entries j:n.\n norm = vec_real_infnorm(j, X_re);\n\n // Protect second linear update against overflow.\n phi =\n starneig_eigvec_std_protect_update(tnorm, fabs(X_re[j]), norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply the scaling to the whole eigenvector.\n starneig_eigvec_std_scale(n, X_re, &phi);\n\n // Now it is safe to execute the linear update.\n for (int i = 0; i < j - 1; i++)\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n\n // Recompute norm excluding the entries j-1:n.\n norm = vec_real_infnorm(j-1, X_re);\n\n // We processed a 2-by-2 block, so skip the next\n // diagonal entry.\n j--;\n }\n }\n\n // The k-th real eigenvector has been computed.\n // Recompute norm.\n Xnorms[si] = vec_real_infnorm(n, X_re);\n\n // Record error flag.\n infos[si] = info;\n\n // This eigenvalue spans 1 column. Update selected counter.\n si--;\n }\n else { // lambda_type[k] == CMPLX\n // Locate real and imaginary part of complex eigenvector\n // for complex conjugate pair of eigenvalues (k, k-1).\n double *X_re = X+(si-1)*(size_t)ldX;\n double *X_im = X+si*(size_t)ldX;\n\n // The eigenvalue is lambda = lambda_re+i*lambda_im.\n double lambda_re = lambda[k-1];\n double lambda_im = fabs(lambda[k]);\n\n // Locate corresponding scaling factor.\n scaling_t *beta = scales+si;\n\n // Compute norm of entire vector.\n double norm = vec_cmplx_infnorm(n, X_re, X_im);\n\n // Critical threshold to detect unsafe divisions.\n const double smin = MAX(\n DBL_EPSILON/2*(fabs(lambda_re)+fabs(lambda_im)), smlnum);\n\n for (int j = n-1; j >= 0; j--) {\n // if the next block is 1-by-1 diagonal block:\n if (diag_type[j] == 0) { // REAL\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_1x1_cmplx_system(smin, T(j,j),\n lambda_re, lambda_im, X_re+j, X_im+j, &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale the remaining parts of the 2 columns.\n starneig_eigvec_std_scale(j, X_re, &phi);\n starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_scale(j, X_im, &phi);\n starneig_eigvec_std_scale(n-(j+1), X_im+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the linear update.\n double absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));\n phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply scaling to the whole eigenvector.\n starneig_eigvec_std_scale(n, X_re, &phi);\n starneig_eigvec_std_scale(n, X_im, &phi);\n\n // Now it is safe to execute the linear update.\n for (int i = 0; i < j; i++) {\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n X_im[i] = X_im[i]-T(i,j)*X_im[j];\n }\n\n // Recompute norm excluding the entries j:n.\n norm = vec_cmplx_infnorm(j, X_re, X_im);\n }\n // if next block is 2-by-2 diagonal block:\n else {\n scaling_t phi;\n starneig_eigvec_std_init_scaling_factor(1, &phi);\n info |= starneig_eigvec_std_solve_2x2_cmplx_system(smin,\n &T(j-1,j-1), ldT, lambda_re, lambda_im,\n X_re+j-1, X_im+j-1, &phi);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Scale remaining parts of vector.\n starneig_eigvec_std_scale(j-1, X_re, &phi);\n starneig_eigvec_std_scale(n-(j+1), X_re+(j+1), &phi);\n starneig_eigvec_std_scale(j-1, X_im, &phi);\n starneig_eigvec_std_scale(n-(j+1), X_im+(j+1), &phi);\n starneig_eigvec_std_update_norm(&norm, phi);\n\n // Protect against overflow in the first linear update.\n double absmax = MAX(fabs(X_re[j-1]), fabs(X_im[j-1]));\n phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply scaling to the whole eigenvector.\n starneig_eigvec_std_scale(n, X_re, &phi);\n starneig_eigvec_std_scale(n, X_im, &phi);\n\n // Now it is safe to execute the first linear update.\n for (int i = 0; i < j-1; i++) {\n X_re[i] = X_re[i]-T(i,j-1)*X_re[j-1];\n X_im[i] = X_im[i]-T(i,j-1)*X_im[j-1];\n }\n\n // Recompute norm excluding the entries j+1:n.\n norm = vec_cmplx_infnorm(j+1, X_re, X_im);\n\n // Protect against overflow in the second linear update.\n absmax = MAX(fabs(X_re[j]), fabs(X_im[j]));\n phi = starneig_eigvec_std_protect_update(tnorm, absmax, norm);\n starneig_eigvec_std_update_global_scaling(beta, phi);\n\n // Apply scaling to the whole eigenvector.\n starneig_eigvec_std_scale(n, X_re, &phi);\n starneig_eigvec_std_scale(n, X_im, &phi);\n\n // Now it is safe to execute the second linear update.\n for (int i = 0; i < j-1; i++) {\n X_re[i] = X_re[i]-T(i,j)*X_re[j];\n X_im[i] = X_im[i]-T(i,j)*X_im[j];\n }\n\n // Recompute norm excluding the entries j-1:n.\n norm = vec_cmplx_infnorm(j-1, X_re, X_im);\n\n // We processed a 2-by-2 block, so skip the next\n // diagonal entry.\n j--;\n }\n }\n\n // Note that the second column of a complex conjugate pair is\n // never allocated or computed. Obtaining it is left to the\n // user. If the positions si - 1, si mark a 2-by-2 block, then\n // the eigenvector corresponding to lambda = alpha + i beta\n // is X(:, si - 1) + i * X(:, si).\n // The complex conjugate eigenvector corresponding to\n // lambda = alpha - i beta can be derived as\n // conj(X) := X(:, si -1) - i * X(:, si).\n\n // The real part and the imaginary part are scaled alike.\n scales[si-1] = scales[si];\n\n // The ki-th complex eigenvector has been computed.\n // Recompute norm of the complex eigenvector.\n Xnorms[si] = vec_cmplx_infnorm(n, X_re, X_im);\n Xnorms[si-1] = Xnorms[si];\n\n // Record error flag.\n infos[si] = info;\n infos[si-1] = info;\n\n // We processed a complex conjugate pair of eigenvalues,\n // so skip the next entry.\n k--;\n\n // This eigenvector spans 2 cols. Update selected counter.\n si -= 2;\n }\n }\n }\n\n#undef T\n}\n\n\n\nvoid starneig_eigvec_std_cpu_update(void *buffers[], void *cl_args)\n{\n // T is n-by-m.\n double *T = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);\n int ldT = STARPU_MATRIX_GET_LD(buffers[0]);\n int n = STARPU_MATRIX_GET_NX(buffers[0]);\n int m = STARPU_MATRIX_GET_NY(buffers[0]);\n\n double *ubT = (double *) STARPU_VARIABLE_GET_PTR(buffers[1]);\n double tnorm = *ubT;\n\n double *Xin = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);\n int num_rhs = STARPU_MATRIX_GET_NY(buffers[2]);\n int ldX = STARPU_MATRIX_GET_LD(buffers[2]);\n\n scaling_t *Xscales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[3]);\n\n double *Xinnorms = (double *) STARPU_VECTOR_GET_PTR(buffers[4]);\n\n double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[5]);\n int ldY = STARPU_MATRIX_GET_LD(buffers[5]);\n\n scaling_t *Yscales = (scaling_t *) STARPU_VECTOR_GET_PTR(buffers[6]);\n\n double *Ynorms = (double *) STARPU_VECTOR_GET_PTR(buffers[7]);\n\n int *lambda_type = (int *) STARPU_VECTOR_GET_PTR(buffers[8]);\n\n // Pointer to X - either a copy or the original memory.\n double *X;\n\n // Pointer to norms of X - either a copy or the original memory.\n double *Xnorms;\n\n // Status flag if X has to be rescaled.\n int rescale_X = 0;\n\n // Status flag if Y has to be rescaled.\n int rescale_Y = 0;\n\n // Indicator if xinnorms has to be rescaled. Note that this only affects\n // consistency scaling and not overflow protection.\n int rescale_xnorms = 0;\n\n // Workspace to store locally computed scaling factors.\n scaling_t tmp_scales[num_rhs];\n\n\n //\n // Compute scaling factor.\n //\n\n for (int k = 0; k < num_rhs; k++) {\n if (Yscales[k] < Xscales[k]) {\n rescale_xnorms = 1;\n break;\n }\n }\n\n if (rescale_xnorms) {\n // As X is read-only, copy xnorms.\n Xnorms = (double *) malloc(num_rhs * sizeof(double));\n memcpy(Xnorms, Xinnorms, num_rhs * sizeof(double));\n\n // Simulate the consistency scaling.\n for (int k = 0; k < num_rhs; k++) {\n if (Yscales[k] < Xscales[k]) {\n // The common scaling factor is Yscales[k].\n const double s =\n starneig_eigvec_std_compute_upscaling(Yscales[k], Xscales[k]);\n\n // Mark X for scaling. Physical rescaling is deferred.\n rescale_X = 1;\n\n // Update norm.\n Xnorms[k] = s*Xinnorms[k];\n }\n else if (Xscales[k] < Yscales[k]) {\n // The common scaling factor is Xscales[k].\n const double s =\n starneig_eigvec_std_compute_upscaling(Xscales[k], Yscales[k]);\n\n // Mark Y for scaling. Physical rescaling is deferred.\n rescale_Y = 1;\n\n // Update norm: norm(s * Y) = s * norm(Y).\n Ynorms[k] = s*Ynorms[k];\n }\n }\n }\n else { // !rescale_xnorms\n // No changes to Xinnorms necessary. Operate on original memory.\n Xnorms = Xinnorms;\n\n // Xnorms does not need scaling, but Ynorms may do.\n for (int k = 0; k < num_rhs; k++) {\n if (Xscales[k] < Yscales[k]) {\n // The common scaling factor is Xscales[k].\n const double s =\n starneig_eigvec_std_compute_upscaling(Xscales[k], Yscales[k]);\n\n // Mark Y for scaling. Phyiscal rescaling is deferred.\n rescale_Y = 1;\n\n // Update norm: norm(s * Y) = s * norm(Y).\n Ynorms[k] = s*Ynorms[k];\n }\n }\n }\n\n\n\n //\n // Apply scaling.\n //\n\n // Status flag if update is safe to execute or if rescaling is required.\n int rescale;\n\n // Compute scaling factors needed to survive the linear update.\n rescale = starneig_eigvec_std_protect_multi_rhs_update(\n Xnorms, num_rhs, tnorm, Ynorms, lambda_type, tmp_scales);\n\n if (rescale) {\n rescale_X = 1;\n rescale_Y = 1;\n }\n\n // If X has to be rescaled, take a copy of X and do scaling on the copy.\n if (rescale_X) {\n X = (double *) malloc((size_t)ldX * num_rhs * sizeof(double));\n\n for (int k = 0; k < num_rhs; k++) {\n if (Yscales[k] < Xscales[k]) {\n // Copy X and simultaneously rescale.\n const double s = starneig_eigvec_std_compute_combined_upscaling(\n Yscales[k], Xscales[k], tmp_scales[k]);\n for (int i = 0; i < m; i++)\n X[(size_t)ldX*k+i] = s*Xin[(size_t)ldX*k+i];\n }\n else if (Xscales[k] < Yscales[k]) {\n // Copy X and simultaneously rescale with robust update factor.\n const double s = starneig_eigvec_std_convert_scaling(tmp_scales[k]);\n for (int i = 0; i < m; i++)\n X[(size_t)ldX*k+i] = s*Xin[(size_t)ldX*k+i];\n }\n else {\n // Xscales[k] == Yscales[k].\n\n // Copy X and simultaneously rescale with robust update factor.\n const double s = starneig_eigvec_std_convert_scaling(tmp_scales[k]);\n for (int i = 0; i < m; i++)\n X[(size_t)ldX*k+i] = s*Xin[(size_t)ldX*k+i];\n }\n }\n }\n else { // !rescale_X\n // No changes to X necessary. Operate on original memory.\n X = Xin;\n }\n\n\n // If Y has to be rescaled, directly modify Y.\n if (rescale_Y) {\n for (int k = 0; k < num_rhs; k++) {\n if (Yscales[k] < Xscales[k]) {\n // The common scaling factor is Yscales[k]. Rescale Y with\n // robust update factor, if necessary.\n starneig_eigvec_std_scale(n, Y+(size_t)ldY*k, tmp_scales+k);\n }\n else if (Xscales[k] < Yscales[k]) {\n // The common scaling factor is Xscales[k]. Combine with\n // robust update scaling factor.\n const double s = starneig_eigvec_std_compute_combined_upscaling(\n Xscales[k], Yscales[k], tmp_scales[k]);\n for (int i = 0; i < n; i++)\n Y[(size_t)ldY*k+i] = s*Y[(size_t)ldY*k+i];\n }\n else {\n // Xscales[k] == Yscales[k].\n\n // Rescale Y with robust update factor, if necessary.\n starneig_eigvec_std_scale(n, Y+(size_t)ldY*k, tmp_scales+k);\n }\n }\n }\n\n\n //\n // Update global scaling of Y.\n //\n\n#ifdef STARNEIG_ENABLE_INTEGER_SCALING\n for (int k = 0; k < num_rhs; k++)\n Yscales[k] = MIN(Yscales[k], Xscales[k])+tmp_scales[k];\n#else\n for (int k = 0; k < num_rhs; k++)\n Yscales[k] = MIN(Yscales[k], Xscales[k])*tmp_scales[k];\n#endif\n\n\n //\n // Compute update.\n //\n\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n n, num_rhs, m, -1.0, T, ldT, X, ldX, 1.0, Y, ldY);\n\n\n //\n // Recompute norms.\n //\n\n for (int k = 0; k < num_rhs; k++) {\n if (lambda_type[k] == 1) { // CMPLX\n // We store only one scaling factor per complex eigenvector pair.\n // So interpret columns as real and imaginary part.\n const double *Y_re = Y+(size_t)k*ldY;\n const double *Y_im = Y+(size_t)(k+1)*ldY;\n\n Ynorms[k] = vec_cmplx_infnorm(n, Y_re, Y_im);\n\n // Duplicate norm for real and imaginary column.\n Ynorms[k+1] = Ynorms[k];\n\n k++;\n }\n else { // lambda_type[k] == REAL\n Ynorms[k] = vec_real_infnorm(n, Y+(size_t)k*ldY);\n }\n }\n\n\n //\n // Clean up.\n //\n\n if (rescale_X)\n free(X);\n\n if (rescale_xnorms)\n free(Xnorms);\n}\n\n\n\nvoid starneig_eigvec_std_cpu_backtransform(void *buffers[], void *cl_args)\n{\n double *Q = (double *) STARPU_MATRIX_GET_PTR(buffers[0]);\n int ldQ = STARPU_MATRIX_GET_LD(buffers[0]);\n\n double *X = (double *) STARPU_MATRIX_GET_PTR(buffers[1]);\n int ldX = STARPU_MATRIX_GET_LD(buffers[1]);\n\n double *Y = (double *) STARPU_MATRIX_GET_PTR(buffers[2]);\n int ldY = STARPU_MATRIX_GET_LD(buffers[2]);\n int m = STARPU_MATRIX_GET_NX(buffers[2]);\n int n = STARPU_MATRIX_GET_NY(buffers[2]);\n\n int k;\n starpu_codelet_unpack_args(cl_args, &k);\n\n // Yij := Qi: * X:j\n // (m x n) (m x k) (k x n)\n\n cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans,\n m, n, k, 1.0, Q, ldQ, X, ldX, 0.0, Y, ldY);\n\n}\n", "meta": {"hexsha": "b968012e9057e7c9963bb5a30a84c7ce785c3932", "size": 47451, "ext": "c", "lang": "C", "max_stars_repo_path": "src/eigenvectors/standard/cpu.c", "max_stars_repo_name": "NLAFET/StarNEig", "max_stars_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2019-04-28T17:13:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-24T12:30:19.000Z", "max_issues_repo_path": "src/eigenvectors/standard/cpu.c", "max_issues_repo_name": "NLAFET/StarNEig", "max_issues_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigenvectors/standard/cpu.c", "max_forks_repo_name": "NLAFET/StarNEig", "max_forks_repo_head_hexsha": "d47ed4dfbcdaec52e44f0b02d14a6e0cde64d286", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-04-30T12:14:12.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-14T09:41:23.000Z", "avg_line_length": 38.6094385679, "max_line_length": 91, "alphanum_fraction": 0.5146150766, "num_tokens": 11857, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.34839763850849137}} {"text": "#include \n#include \n\n#ifdef HAS_MKL\n#include \n#else\n#include \n#endif\n\n#ifdef __SSE4_2__\n#include \n#endif\n\ntypedef double Real;\n\n\ninline void GetTotalTraction_(Real *TotalTraction,\n const Real *ElectricDisplacementx, int ndim) {\n // if (ndim==3) {\n // TotalTraction[0] = ElectricDisplacementx[0];\n // TotalTraction[1] = ElectricDisplacementx[1];\n // TotalTraction[2] = ElectricDisplacementx[2];\n // }\n // else if (ndim == 2) {\n // TotalTraction[0] = ElectricDisplacementx[0];\n // TotalTraction[1] = ElectricDisplacementx[1];\n // }\n std::copy(ElectricDisplacementx,ElectricDisplacementx+ndim,TotalTraction);\n}\n\n\ninline void FillConstitutiveB_(Real *B, const Real* SpatialGradient,\n int ndim, int rows, int cols) {\n int i = 0;\n\n if (ndim == 3) {\n\n for (; i\ninline void _ConstitutiveStiffnessLaplacian_Filler_(Real *stiffness, Real *traction,\n const Real* SpatialGradient,\n const Real* ElectricDisplacementx,\n const Real* H_Voigt,\n const Real* detJ,\n int ngauss,\n int noderpelem,\n int ndim,\n int nvar,\n int H_VoigtSize,\n int requires_geometry_update) {\n\n\n int local_size = nvar*noderpelem;\n\n Real *t;\n\n#ifdef __SSE4_2__\n t = (Real*)_mm_malloc(ndim*sizeof(Real),32);\n Real *B = (Real*)_mm_malloc(H_VoigtSize*local_size*sizeof(Real),32);\n Real *HBT = (Real*)_mm_malloc(H_VoigtSize*local_size*sizeof(Real),32);\n Real *BDB_1 = (Real*)_mm_malloc(local_size*local_size*sizeof(Real),32);\n#else\n t = (Real*)malloc(ndim*sizeof(Real));\n Real *B = (Real*)malloc(H_VoigtSize*local_size*sizeof(Real));\n Real *HBT = (Real*)malloc(H_VoigtSize*local_size*sizeof(Real));\n Real *BDB_1 = (Real*)malloc(local_size*local_size*sizeof(Real));\n#endif\n\n std::fill(B,B+H_VoigtSize*local_size,0.);\n\n for (int igauss = 0; igauss < ngauss; ++igauss) {\n\n FillConstitutiveB_(B,&SpatialGradient[igauss*ndim*noderpelem],ndim,noderpelem,H_VoigtSize);\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans,\n H_VoigtSize, local_size, H_VoigtSize, 1.0, &H_Voigt[igauss*H_VoigtSize*H_VoigtSize], H_VoigtSize, B, H_VoigtSize, 0.0, HBT, local_size);\n\n cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,\n local_size, local_size, H_VoigtSize, 1.0, B, H_VoigtSize, HBT, local_size, 0.0, BDB_1, local_size);\n\n // Multiply stiffness with detJ\n const Real detJ_igauss = detJ[igauss];\n for (int i=0; i amat {{1,2}, {2, 4}};\n * The matrix can also initialize with the MatrixShape and the initialize value.\n * For example:\n * Matrix bmat({2,2}, 0);\n *\n */\n#ifndef MATRIX_H_\n#define MATRIX_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"expr.h\"\n#include \"matrix_shape.h\"\n#include \"sub_matrix.h\"\n\n//#define DEBUG\nnamespace matrix {\n\n// ============================================================================\n// recursive initializer_list for Matrix Class\ntemplate\nstruct MatrixInit {\n using type = std::initializer_list::type>;\n};\n\ntemplate\nstruct MatrixInit {\n using type = std::initializer_list;\n};\n\ntemplate\nstruct MatrixInit ;\n\ntemplate\nusing matrix_initializer_list = typename MatrixInit::type;\n\ntemplate\nclass Matrix : public ExprBase, DataType> {\n public:\n\n /**\n * default constructor\n */\n Matrix()\n : data(nullptr),\n stride(size_t(0)),\n capicity(size_t(0)),\n row(size_t(0)),\n column(size_t(0)) {\n }\n ;\n\n /**\n * constructor with matrix shape and initial value\n * @param s is shape of matrix\n * @param n is initial value for the elements in the matrix\n */\n inline Matrix(const MatrixShape &s, const DataType n);\n\n /**\n * constructor with matrix shape, stride and initial value\n * @param s is shape of the matrix\n * @param st is stride for each row of the multi-array(Note that: change the shape[N-1] memeory )\n * @param n is initial value for the elements in the matrix\n */\n inline Matrix(const MatrixShape &s, const size_t st, const DataType n);\n\n /**\n * copy constructor\n * @param m is another matrix to be cloned to this matrix\n */\n inline Matrix(const Matrix &m);\n\n /**\n * copy assignment\n * @param m is another matrix to be cloned to this matrix\n * @return the matrix that has copied data from another matrix\n */\n inline Matrix & operator =(const Matrix &m);\n\n /**\n * copy constructor from SubMatrix\n * @param m is the submatrix to be cloned to this matrix\n */\n inline Matrix(const SubMatrix &m);\n\n /**\n * copy assignment from SubMatrix\n * @param m is another submatrix to be cloned to this matrix\n * @return the matrix that has copied data from another matrix\n */\n inline Matrix & operator =(const SubMatrix &m);\n\n /**\n * move constructor\n * @param m is another matrix to be moved to this matrix\n */\n inline Matrix(Matrix &&m);\n\n /**\n * move assignment operator\n * @param m is matrix to be moved to this matrix\n * @return the matrix that has gotten data from another matrix\n */\n inline Matrix & operator =(Matrix &&m);\n\n /**\n * constructor with matrix_initializer_list\n * @param t is initializer_list for the matrix\n */\n inline Matrix(matrix_initializer_list t);\n\n /**\n * assignment operator with matrix_initializer_list\n * @param t is initializer_list for the matrix\n * @return the matrix that has filled the data with the initializer_list\n */\n inline Matrix & operator =(matrix_initializer_list t);\n template\n inline Matrix(std::initializer_list t) = delete;\n template\n inline Matrix & operator =(std::initializer_list t) = delete;\n\n /**\n * de-constructor: delete the array\n */\n ~Matrix() {\n#ifdef DEBUG\n std::cout<<\"decons!!!!!!!!!!!!!!!!!!!!\" << this << std::endl;\n#endif\n delete[] data;\n }\n\n /**\n * index operation for the matrix\n * @param i is the index\n * @return a SubMatrix Object which is refer to some elements in the Matrix Object\n */\n inline SubMatrix operator[](size_t i) const;\n inline SubMatrix operator[](size_t i);\n /**\n * slice function for the matrix\n * @param i is the start index\n * @param j is the end index\n * @return a SubMatrix Object which is refer to some elements in the Matrix Object\n */\n inline SubMatrix slice(size_t i, size_t j) const;\n inline SubMatrix slice(size_t i, size_t j);\n\n /**\n * Scalar add Operator\n * @param n is the scalar added to matrix\n * @return the matrix in which the elements are all added the scalar value\n */\n inline Matrix & operator +=(const DataType & n);\n\n /**\n * Scalar sub Operator\n * @param n is the scalar subscribed to matrix\n * @return the matrix in which the elements are all subscribed the scalar value\n */\n inline Matrix & operator -=(const DataType & n);\n\n /**\n * Scalar multiply Operator\n * @param n is the scalar multiplied to matrix\n * @return the matrix in which the elements are all multiplied the scalar value\n */\n inline Matrix & operator *=(const DataType & n);\n\n /**\n * Scalar devision Operator\n * @param n is the scalar divided to matrix\n * @return the matrix in which the elements are all devided the scalar value\n */\n inline Matrix & operator /=(const DataType & n);\n\n /**\n * add Operator\n * @param t is the matrix added to this matrix\n * @return the matrix in which the elements: m1(i,j) += m2(i,j)\n */\n inline Matrix & operator +=(const Matrix & t);\n\n /**\n * sub Operator\n * @param t is the matrix subscribed to this matrix\n * @return the matrix in which the elements: m1(i,j) -= m2(i,j)\n */\n inline Matrix & operator -=(const Matrix & t);\n\n /**\n * multiply Operator\n * @param t is the matrix multiplied to this matrix\n * @return the matrix in which the elements: m1(i,j) *= m2(i,j)\n */\n inline Matrix & operator *=(const Matrix & t);\n\n /**\n * division opertor\n * @param t is the matrix divided to this matrix\n * @return the matrix in which the elements: m1(i,j) /= m2(i,j)\n */\n inline Matrix& operator /=(const Matrix & t);\n\n /**\n * Assign Operator\n * @param e is the right matrix object or a scalar\n * @return the result matrix\n */\n template\n inline Matrix& operator=(const ExprBase &e);\n\n /**\n * get the basic element in index (i,j)\n * @param i is the row index\n * @param j is the column index\n * @return the element in the index(i,j)\n */\n inline DataType eval(size_t i, size_t j) const;\n\n inline void set_row_ele(int i, const Matrix & s);\n\n /**\n * get the column size\n * @return the column size\n */\n inline size_t getColumn() const {\n return column;\n }\n\n /**\n * get the row size\n * @return the row size\n */\n inline size_t getRow() const {\n return row;\n }\n\n /**\n * get the capicity of the matrix\n * @return the capicity of the matrix\n */\n inline size_t getCapicity() const {\n return capicity;\n }\n\n /**\n * get the memory length for the matrix\n * @return the capicity of the matrix\n */\n inline int get_capicity() const;\n /**\n * get the number of the elemments in the matrix\n * @return the matrix elements number\n */\n inline int get_size() const;\n /**\n * get the length of the shape\n * @param s is the shape object\n * @param stride is the row length\n * @return the length of the shape with the stride\n */\n inline size_t get_length(const MatrixShape &s, size_t stride) const;\n /**\n * @return the pointer to the data of the matrix\n */\n inline DataType * get_data() {\n return data;\n }\n /**\n * @return the pointer to the data of the matrix\n */\n inline DataType * get_data() const {\n return data;\n }\n //private:\n MatrixShape shape;\n size_t stride;\n size_t capicity;\n DataType * data;\n size_t row;\n size_t column;\n};\n\n//=============================================================================\n/**\n * One-dimension Matrix Class\n * For example:\n * Matrix m {1,2,3,4}\n * support operator [], such as m[0].\n */\ntemplate\nclass Matrix : public ExprBase, DataType> {\n public:\n Matrix()\n : data(nullptr),\n stride(size_t(0)) {\n }\n ;\n inline Matrix(const MatrixShape<1> &s, const DataType n);\n inline Matrix(const MatrixShape<1> &s, const size_t st, const DataType n);\n inline Matrix(const Matrix &m);\n inline Matrix & operator =(const Matrix &m);\n inline Matrix(const SubMatrix &m);\n inline Matrix & operator =(const SubMatrix &m);\n inline Matrix(Matrix &&m);\n inline Matrix & operator =(Matrix &&m);\n inline Matrix(matrix_initializer_list t);\n inline Matrix & operator =(matrix_initializer_list t);\n ~Matrix() {\n delete[] data;\n }\n inline int get_capicity() const;\n inline int get_size() const;\n inline size_t get_length(const MatrixShape<1> &s, size_t stride) const;\n inline DataType * get_data() {\n return data;\n }\n inline DataType * get_data() const {\n return data;\n }\n inline const DataType & operator[](size_t i) const;\n inline DataType & operator[](size_t i);\n inline SubMatrix slice(size_t i, size_t j) const;\n inline SubMatrix slice(size_t i, size_t j);\n inline Matrix & operator +=(const DataType & n);\n inline Matrix & operator -=(const DataType & n);\n inline Matrix & operator *=(const DataType & n);\n inline Matrix & operator /=(const DataType & n);\n inline Matrix & operator +=(const Matrix & t);\n inline Matrix & operator -=(const Matrix & t);\n inline Matrix & operator *=(const Matrix & t);\n inline Matrix& operator /=(const Matrix & t);\n template\n inline Matrix& operator=(const ExprBase &e);\n inline DataType eval(size_t i, size_t j) const;\n inline void set_row_ele(int i, const Matrix & s);\n inline size_t getColumn() const {\n return column;\n }\n inline size_t getRow() const {\n return row;\n }\n inline size_t getCapicity() const {\n return capicity;\n }\n //private:\n MatrixShape<1> shape;\n size_t stride;\n size_t capicity;\n DataType * data;\n size_t row;\n size_t column;\n};\n\n//=============================================================================\n//matrix operation for two dimensional Matrix and SubMatrix\n// matrix multiplication operator\n\n// overload equal Operator\n// Ruturn true if all elements in the matrix is equal and stride is equal\ntemplate\ninline bool operator==(const Matrix& m1,\n const Matrix& m2) {\n DataType * d1 = m1.data;\n DataType * d2 = m2.data;\n if (m1.get_size() != m2.get_size())\n return false;\n for (int i = 0; i < m1.get_size(); ++i) {\n if (d1[i] != d2[i])\n return false;\n }\n return true;\n}\n\ntemplate\ninline bool operator==(const SubMatrix& m1,\n const Matrix& m2) {\n DataType * d1 = m1.data;\n DataType * d2 = m2.data;\n if (m1.get_size() != m2.get_size())\n return false;\n for (int i = 0; i < m1.get_size(); ++i) {\n if (d1[i] != d2[i])\n return false;\n }\n return true;\n}\n\ntemplate\ninline bool operator==(const Matrix& m1,\n const SubMatrix& m2) {\n DataType * d1 = m1.data;\n DataType * d2 = m2.data;\n if (m1.get_size() != m2.get_size())\n return false;\n for (int i = 0; i < m1.get_size(); ++i) {\n if (d1[i] != d2[i])\n return false;\n }\n return true;\n}\n\ntemplate\ninline bool operator==(const SubMatrix& m1,\n const SubMatrix& m2) {\n DataType * d1 = m1.data;\n DataType * d2 = m2.data;\n if (m1.get_size() != m2.get_size())\n return false;\n for (int i = 0; i < m1.get_size(); ++i) {\n if (d1[i] != d2[i])\n return false;\n }\n return true;\n}\n\n} //namespace matrix\n#ifdef MATRIX_SCALAR_TYPE_\n#error \"MATRIX_SCALAR_TYPE_ Should not be defined!\"\n#endif\n#define MATRIX_SCALAR_TYPE_ float\n#include \"expr-inl.h\"\n#undef MATRIX_SCALAR_TYPE_\n#define MATRIX_SCALAR_TYPE_ double\n#include \"expr-inl.h\"\n#undef MATRIX_SCALAR_TYPE_\n#define MATRIX_SCALAR_TYPE_ int\n#include \"expr-inl.h\"\n#undef MATRIX_SCALAR_TYPE_\n#include \"matrix-inl.h\"\n#include \"sub_matrix-inl.h\"\n#include \"matrix_math.h\"\n#include \"random.h\"\n#endif // MATRIX_MATRIX_H\n\n", "meta": {"hexsha": "ce633147b928863ba46c2946a8d67150241f295c", "size": 13228, "ext": "h", "lang": "C", "max_stars_repo_path": "snoopy/matrix/matrix.h", "max_stars_repo_name": "seaslee/snoopy", "max_stars_repo_head_hexsha": "35655f925f687382f9d141c5f43dc392170507df", "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": "snoopy/matrix/matrix.h", "max_issues_repo_name": "seaslee/snoopy", "max_issues_repo_head_hexsha": "35655f925f687382f9d141c5f43dc392170507df", "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": "snoopy/matrix/matrix.h", "max_forks_repo_name": "seaslee/snoopy", "max_forks_repo_head_hexsha": "35655f925f687382f9d141c5f43dc392170507df", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0725274725, "max_line_length": 99, "alphanum_fraction": 0.6514212277, "num_tokens": 3520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5312093733737562, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.3478862222182328}} {"text": "/////////////////////////////////////////////////////////////////////////////////\n// \n// Solution of linear systems involved in the Levenberg - Marquardt\n// minimization algorithm\n// Copyright (C) 2004 Manolis Lourakis (lourakis at ics forth gr)\n// Institute of Computer Science, Foundation for Research & Technology - Hellas\n// Heraklion, Crete, Greece.\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/////////////////////////////////////////////////////////////////////////////////\n\n\n/* Solvers for the linear systems Ax=b. Solvers should NOT modify their A & B arguments! */\n\n\n#ifndef LM_REAL // not included by Axb.c\n#error This file should not be compiled directly!\n#endif\n\n\n#ifdef LINSOLVERS_RETAIN_MEMORY\n#define __STATIC__ static\n#else\n#define __STATIC__ // empty\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n#ifdef HAVE_LAPACK\n\n/* prototypes of LAPACK routines */\n\n#define GEQRF LM_MK_LAPACK_NAME(geqrf)\n#define ORGQR LM_MK_LAPACK_NAME(orgqr)\n#define TRTRS LM_MK_LAPACK_NAME(trtrs)\n#define POTF2 LM_MK_LAPACK_NAME(potf2)\n#define POTRF LM_MK_LAPACK_NAME(potrf)\n#define POTRS LM_MK_LAPACK_NAME(potrs)\n#define GETRF LM_MK_LAPACK_NAME(getrf)\n#define GETRS LM_MK_LAPACK_NAME(getrs)\n#define GESVD LM_MK_LAPACK_NAME(gesvd)\n#define GESDD LM_MK_LAPACK_NAME(gesdd)\n#define SYTRF LM_MK_LAPACK_NAME(sytrf)\n#define SYTRS LM_MK_LAPACK_NAME(sytrs)\n#define PLASMA_POSV LM_CAT_(PLASMA_, LM_ADD_PREFIX(posv))\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n/* QR decomposition */\nextern int GEQRF(int *m, int *n, LM_REAL *a, int *lda, LM_REAL *tau, LM_REAL *work, int *lwork, int *info);\nextern int ORGQR(int *m, int *n, int *k, LM_REAL *a, int *lda, LM_REAL *tau, LM_REAL *work, int *lwork, int *info);\n\n/* solution of triangular systems */\nextern int TRTRS(char *uplo, char *trans, char *diag, int *n, int *nrhs, LM_REAL *a, int *lda, LM_REAL *b, int *ldb, int *info);\n\n/* Cholesky decomposition and systems solution */\nextern int POTF2(char *uplo, int *n, LM_REAL *a, int *lda, int *info);\nextern int POTRF(char *uplo, int *n, LM_REAL *a, int *lda, int *info); /* block version of dpotf2 */\nextern int POTRS(char *uplo, int *n, int *nrhs, LM_REAL *a, int *lda, LM_REAL *b, int *ldb, int *info);\n\n/* LU decomposition and systems solution */\nextern int GETRF(int *m, int *n, LM_REAL *a, int *lda, int *ipiv, int *info);\nextern int GETRS(char *trans, int *n, int *nrhs, LM_REAL *a, int *lda, int *ipiv, LM_REAL *b, int *ldb, int *info);\n\n/* Singular Value Decomposition (SVD) */\nextern int GESVD(char *jobu, char *jobvt, int *m, int *n, LM_REAL *a, int *lda, LM_REAL *s, LM_REAL *u, int *ldu,\n LM_REAL *vt, int *ldvt, LM_REAL *work, int *lwork, int *info);\n\n/* lapack 3.0 new SVD routine, faster than xgesvd().\n * In case that your version of LAPACK does not include them, use the above two older routines\n */\nextern int GESDD(char *jobz, int *m, int *n, LM_REAL *a, int *lda, LM_REAL *s, LM_REAL *u, int *ldu, LM_REAL *vt, int *ldvt,\n LM_REAL *work, int *lwork, int *iwork, int *info);\n\n/* LDLt/UDUt factorization and systems solution */\nextern int SYTRF(char *uplo, int *n, LM_REAL *a, int *lda, int *ipiv, LM_REAL *work, int *lwork, int *info);\nextern int SYTRS(char *uplo, int *n, int *nrhs, LM_REAL *a, int *lda, int *ipiv, LM_REAL *b, int *ldb, int *info);\n#ifdef __cplusplus\n}\n#endif\n\n/* precision-specific definitions */\n#define AX_EQ_B_QR LM_ADD_PREFIX(Ax_eq_b_QR)\n#define AX_EQ_B_QRLS LM_ADD_PREFIX(Ax_eq_b_QRLS)\n#define AX_EQ_B_CHOL LM_ADD_PREFIX(Ax_eq_b_Chol)\n#define AX_EQ_B_LU LM_ADD_PREFIX(Ax_eq_b_LU)\n#define AX_EQ_B_SVD LM_ADD_PREFIX(Ax_eq_b_SVD)\n#define AX_EQ_B_BK LM_ADD_PREFIX(Ax_eq_b_BK)\n#define AX_EQ_B_PLASMA_CHOL LM_ADD_PREFIX(Ax_eq_b_PLASMA_Chol)\n\n/*\n * This function returns the solution of Ax = b\n *\n * The function is based on QR decomposition with explicit computation of Q:\n * If A=Q R with Q orthogonal and R upper triangular, the linear system becomes\n * Q R x = b or R x = Q^T b.\n * The last equation can be solved directly.\n *\n * A is mxm, b is mx1\n *\n * The function returns 0 in case of error, 1 if successful\n *\n * This function is often called repetitively to solve problems of identical\n * dimensions. To avoid repetitive malloc's and free's, allocated memory is\n * retained between calls and free'd-malloc'ed when not of the appropriate size.\n * A call with NULL as the first argument forces this memory to be released.\n */\nint AX_EQ_B_QR(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)\n{\n__STATIC__ LM_REAL *buf=NULL;\n__STATIC__ int buf_sz=0;\n\nstatic int nb=0; /* no __STATIC__ decl. here! */\n\nLM_REAL *a, *tau, *r, *work;\nint a_sz, tau_sz, r_sz, tot_sz;\nregister int i, j;\nint info, worksz, nrhs=1;\nregister LM_REAL sum;\n\n if(!A)\n#ifdef LINSOLVERS_RETAIN_MEMORY\n {\n if(buf) free(buf);\n buf=NULL;\n buf_sz=0;\n\n return 1;\n }\n#else\n return 1; /* NOP */\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n \n /* calculate required memory size */\n a_sz=m*m;\n tau_sz=m;\n r_sz=m*m; /* only the upper triangular part really needed */\n if(!nb){\n LM_REAL tmp;\n\n worksz=-1; // workspace query; optimal size is returned in tmp\n GEQRF((int *)&m, (int *)&m, NULL, (int *)&m, NULL, (LM_REAL *)&tmp, (int *)&worksz, (int *)&info);\n nb=((int)tmp)/m; // optimal worksize is m*nb\n }\n worksz=nb*m;\n tot_sz=a_sz + tau_sz + r_sz + worksz;\n\n#ifdef LINSOLVERS_RETAIN_MEMORY\n if(tot_sz>buf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_QR) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_QR) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n tau=a+a_sz;\n r=tau+tau_sz;\n work=r+r_sz;\n\n /* store A (column major!) into a */\n\tfor(i=0; ibuf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_QRLS) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_QRLS) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n tau=a+a_sz;\n r=tau+tau_sz;\n work=r+r_sz;\n\n /* store A (column major!) into a */\n\tfor(i=0; ibuf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_CHOL) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_CHOL) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n\n /* store A into a and B into x. A is assumed symmetric,\n * hence no transposition is needed\n */\n memcpy(a, A, a_sz*sizeof(LM_REAL));\n memcpy(x, B, m*sizeof(LM_REAL));\n\n /* Cholesky decomposition of A */\n //POTF2(\"L\", (int *)&m, a, (int *)&m, (int *)&info);\n POTRF(\"L\", (int *)&m, a, (int *)&m, (int *)&info);\n /* error treatment */\n if(info!=0){\n if(info<0){\n printf(RCAT(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", POTF2) \"/\", POTRF) \" in \",\n AX_EQ_B_CHOL) \"()\\n\", -info);\n exit(1);\n }\n else{\n printf(RCAT(RCAT(RCAT(\"LAPACK error: the leading minor of order %d is not positive definite,\\nthe factorization could not be completed for \", POTF2) \"/\", POTRF) \" in \", AX_EQ_B_CHOL) \"()\\n\", info);\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n return 0;\n }\n }\n\n /* solve using the computed Cholesky in one lapack call */\n POTRS(\"L\", (int *)&m, (int *)&nrhs, a, (int *)&m, x, (int *)&m, &info);\n if(info<0){\n printf(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", POTRS) \" in \", AX_EQ_B_CHOL) \"()\\n\", -info);\n exit(1);\n }\n\n#if 0\n /* alternative: solve the linear system L y = b ... */\n TRTRS(\"L\", \"N\", \"N\", (int *)&m, (int *)&nrhs, a, (int *)&m, x, (int *)&m, &info);\n /* error treatment */\n if(info!=0){\n if(info<0){\n printf(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", TRTRS) \" in \", AX_EQ_B_CHOL) \"()\\n\", -info);\n exit(1);\n }\n else{\n printf(RCAT(\"LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in \", AX_EQ_B_CHOL) \"()\\n\", info);\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n return 0;\n }\n }\n\n /* ... solve the linear system L^T x = y */\n TRTRS(\"L\", \"T\", \"N\", (int *)&m, (int *)&nrhs, a, (int *)&m, x, (int *)&m, &info);\n /* error treatment */\n if(info!=0){\n if(info<0){\n printf(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", TRTRS) \"in \", AX_EQ_B_CHOL) \"()\\n\", -info);\n exit(1);\n }\n else{\n printf(RCAT(\"LAPACK error: the %d-th diagonal element of A is zero (singular matrix) in \", AX_EQ_B_CHOL) \"()\\n\", info);\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n return 0;\n }\n }\n#endif /* 0 */\n\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n\treturn 1;\n}\n\n#ifdef HAVE_PLASMA\n\n/* Linear algebra using PLASMA parallel library for multicore CPUs.\n * http://icl.cs.utk.edu/plasma/\n *\n * WARNING: BLAS multithreading should be disabled, e.g. setenv MKL_NUM_THREADS 1\n */\n\n#ifndef _LM_PLASMA_MISC_\n/* avoid multiple inclusion of helper code */\n#define _LM_PLASMA_MISC_\n\n#include \n#include \n#include \n#include \n#include \n\n/* programmatically determine the number of cores on the current machine */\n#ifdef _WIN32\n#include \n#elif __linux\n#include \n#endif\nstatic int getnbcores()\n{\n#ifdef _WIN32\n SYSTEM_INFO sysinfo;\n GetSystemInfo(&sysinfo);\n return sysinfo.dwNumberOfProcessors;\n#elif __linux\n return sysconf(_SC_NPROCESSORS_ONLN);\n#else // unknown system\n return 2<<1; // will be halved by right shift below\n#endif\n}\n\nstatic int PLASMA_ncores=-(getnbcores()>>1); // >0 if PLASMA initialized, <0 otherwise\n\n/* user-specified number of cores */\nvoid levmar_PLASMA_setnbcores(int cores)\n{\n PLASMA_ncores=(cores>0)? -cores : ((cores)? cores : -2);\n}\n#endif /* _LM_PLASMA_MISC_ */\n\n/*\n * This function returns the solution of Ax=b\n *\n * The function assumes that A is symmetric & positive definite and employs the\n * Cholesky decomposition implemented by PLASMA for homogeneous multicore processors.\n *\n * A is mxm, b is mx1\n *\n * The function returns 0 in case of error, 1 if successfull\n *\n * This function is often called repetitively to solve problems of identical\n * dimensions. To avoid repetitive malloc's and free's, allocated memory is\n * retained between calls and free'd-malloc'ed when not of the appropriate size.\n * A call with NULL as the first argument forces this memory to be released.\n */\nint AX_EQ_B_PLASMA_CHOL(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)\n{\n__STATIC__ LM_REAL *buf=NULL;\n__STATIC__ int buf_sz=0;\n\nLM_REAL *a;\nint a_sz, tot_sz;\nint info, nrhs=1;\n\n if(A==NULL){\n#ifdef LINSOLVERS_RETAIN_MEMORY\n if(buf) free(buf);\n buf=NULL;\n buf_sz=0;\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n PLASMA_Finalize();\n PLASMA_ncores=-PLASMA_ncores;\n\n return 1;\n }\n\n /* calculate required memory size */\n a_sz=m*m;\n tot_sz=a_sz;\n\n#ifdef LINSOLVERS_RETAIN_MEMORY\n if(tot_sz>buf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_PLASMA_CHOL) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz*sizeof(LM_REAL));\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_PLASMA_CHOL) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n\n /* store A into a and B into x; A is assumed to be symmetric,\n * hence no transposition is needed\n */\n memcpy(a, A, a_sz*sizeof(LM_REAL));\n memcpy(x, B, m*sizeof(LM_REAL));\n\n /* initialize PLASMA */\n if(PLASMA_ncores<0){\n PLASMA_ncores=-PLASMA_ncores;\n PLASMA_Init(PLASMA_ncores);\n printf(RCAT(\"\\n\", AX_EQ_B_PLASMA_CHOL) \"(): PLASMA is running on %d cores.\\n\\n\", PLASMA_ncores);\n }\n \n /* Solve the linear system */\n info=PLASMA_POSV(PlasmaLower, m, 1, a, m, x, m);\n /* error treatment */\n if(info!=0){\n if(info<0){\n printf(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", PLASMA_POSV) \" in \",\n AX_EQ_B_PLASMA_CHOL) \"()\\n\", -info);\n exit(1);\n }\n else{\n printf(RCAT(RCAT(\"LAPACK error: the leading minor of order %d is not positive definite,\\n\"\n \"the factorization could not be completed for \", PLASMA_POSV) \" in \", AX_EQ_B_CHOL) \"()\\n\", info);\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n return 0;\n }\n }\n\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n\treturn 1;\n}\n#endif /* HAVE_PLASMA */\n\n/*\n * This function returns the solution of Ax = b\n *\n * The function employs LU decomposition:\n * If A=L U with L lower and U upper triangular, then the original system\n * amounts to solving\n * L y = b, U x = y\n *\n * A is mxm, b is mx1\n *\n * The function returns 0 in case of error, 1 if successful\n *\n * This function is often called repetitively to solve problems of identical\n * dimensions. To avoid repetitive malloc's and free's, allocated memory is\n * retained between calls and free'd-malloc'ed when not of the appropriate size.\n * A call with NULL as the first argument forces this memory to be released.\n */\nint AX_EQ_B_LU(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)\n{\n__STATIC__ LM_REAL *buf=NULL;\n__STATIC__ int buf_sz=0;\n\nint a_sz, ipiv_sz, tot_sz;\nregister int i, j;\nint info, *ipiv, nrhs=1;\nLM_REAL *a;\n \n if(!A)\n#ifdef LINSOLVERS_RETAIN_MEMORY\n {\n if(buf) free(buf);\n buf=NULL;\n buf_sz=0;\n\n return 1;\n }\n#else\n return 1; /* NOP */\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n \n /* calculate required memory size */\n ipiv_sz=m;\n a_sz=m*m;\n tot_sz=a_sz*sizeof(LM_REAL) + ipiv_sz*sizeof(int); /* should be arranged in that order for proper doubles alignment */\n\n#ifdef LINSOLVERS_RETAIN_MEMORY\n if(tot_sz>buf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_LU) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_LU) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n ipiv=(int *)(a+a_sz);\n\n /* store A (column major!) into a and B into x */\n\t for(i=0; ibuf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_SVD) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_SVD) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n u=a+a_sz;\n s=u+u_sz;\n vt=s+s_sz;\n work=vt+vt_sz;\n iwork=(int *)(work+worksz);\n\n /* store A (column major!) into a */\n for(i=0; i0.0; eps*=LM_CNST(0.5))\n ;\n eps*=LM_CNST(2.0);\n }\n\n /* compute the pseudoinverse in a */\n\tfor(i=0; ithresh; rank++){\n one_over_denom=LM_CNST(1.0)/s[rank];\n\n for(j=0; jbuf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_BK) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(LM_REAL *)malloc(buf_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_BK) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n work=a+a_sz;\n ipiv=(int *)(work+work_sz);\n\n /* store A into a and B into x; A is assumed to be symmetric, hence\n * the column and row major order representations are the same\n */\n memcpy(a, A, a_sz*sizeof(LM_REAL));\n memcpy(x, B, m*sizeof(LM_REAL));\n\n /* LDLt factorization for A */\n\tSYTRF(\"L\", (int *)&m, a, (int *)&m, ipiv, work, (int *)&work_sz, (int *)&info);\n\tif(info!=0){\n\t\tif(info<0){\n printf(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", SYTRF) \" in \", AX_EQ_B_BK) \"()\\n\", -info);\n\t\t\texit(1);\n\t\t}\n\t\telse{\n printf(RCAT(RCAT(\"LAPACK error: singular block diagonal matrix D for\", SYTRF) \" in \", AX_EQ_B_BK)\"() [D(%d, %d) is zero]\\n\", info, info);\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n\t\t\treturn 0;\n\t\t}\n\t}\n\n /* solve the system with the computed factorization */\n SYTRS(\"L\", (int *)&m, (int *)&nrhs, a, (int *)&m, ipiv, x, (int *)&m, (int *)&info);\n if(info<0){\n printf(RCAT(RCAT(\"LAPACK error: illegal value for argument %d of \", SYTRS) \" in \", AX_EQ_B_BK) \"()\\n\", -info);\n exit(1);\n\t}\n\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n\treturn 1;\n}\n\n/* undefine all. IT MUST REMAIN IN THIS POSITION IN FILE */\n#undef AX_EQ_B_QR\n#undef AX_EQ_B_QRLS\n#undef AX_EQ_B_CHOL\n#undef AX_EQ_B_LU\n#undef AX_EQ_B_SVD\n#undef AX_EQ_B_BK\n#undef AX_EQ_B_PLASMA_CHOL\n\n#undef GEQRF\n#undef ORGQR\n#undef TRTRS\n#undef POTF2\n#undef POTRF\n#undef POTRS\n#undef GETRF\n#undef GETRS\n#undef GESVD\n#undef GESDD\n#undef SYTRF\n#undef SYTRS\n#undef PLASMA_POSV\n\n#else // no LAPACK\n\n/* precision-specific definitions */\n#define AX_EQ_B_LU LM_ADD_PREFIX(Ax_eq_b_LU_noLapack)\n\n/*\n * This function returns the solution of Ax = b\n *\n * The function employs LU decomposition followed by forward/back substitution (see \n * also the LAPACK-based LU solver above)\n *\n * A is mxm, b is mx1\n *\n * The function returns 0 in case of error, 1 if successful\n *\n * This function is often called repetitively to solve problems of identical\n * dimensions. To avoid repetitive malloc's and free's, allocated memory is\n * retained between calls and free'd-malloc'ed when not of the appropriate size.\n * A call with NULL as the first argument forces this memory to be released.\n */\nint AX_EQ_B_LU(LM_REAL *A, LM_REAL *B, LM_REAL *x, int m)\n{\n__STATIC__ void *buf=NULL;\n__STATIC__ int buf_sz=0;\n\nregister int i, j, k;\nint *idx, maxi=-1, idx_sz, a_sz, work_sz, tot_sz;\nLM_REAL *a, *work, max, sum, tmp;\n\n if(!A)\n#ifdef LINSOLVERS_RETAIN_MEMORY\n {\n if(buf) free(buf);\n buf=NULL;\n buf_sz=0;\n\n return 1;\n }\n#else\n return 1; /* NOP */\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n \n /* calculate required memory size */\n idx_sz=m;\n a_sz=m*m;\n work_sz=m;\n tot_sz=(a_sz+work_sz)*sizeof(LM_REAL) + idx_sz*sizeof(int); /* should be arranged in that order for proper doubles alignment */\n\n#ifdef LINSOLVERS_RETAIN_MEMORY\n if(tot_sz>buf_sz){ /* insufficient memory, allocate a \"big\" memory chunk at once */\n if(buf) free(buf); /* free previously allocated memory */\n\n buf_sz=tot_sz;\n buf=(void *)malloc(tot_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_LU) \"() failed!\\n\");\n exit(1);\n }\n }\n#else\n buf_sz=tot_sz;\n buf=(void *)malloc(tot_sz);\n if(!buf){\n printf(RCAT(\"memory allocation in \", AX_EQ_B_LU) \"() failed!\\n\");\n exit(1);\n }\n#endif /* LINSOLVERS_RETAIN_MEMORY */\n\n a=buf;\n work=a+a_sz;\n idx=(int *)(work+work_sz);\n\n /* avoid destroying A, B by copying them to a, x resp. */\n memcpy(a, A, a_sz*sizeof(LM_REAL));\n memcpy(x, B, m*sizeof(LM_REAL));\n\n /* compute the LU decomposition of a row permutation of matrix a; the permutation itself is saved in idx[] */\n\tfor(i=0; imax)\n max=tmp;\n\t\t if(max==0.0){\n printf(RCAT(\"Singular matrix A in \", AX_EQ_B_LU) \"()!\\n\");\n#ifndef LINSOLVERS_RETAIN_MEMORY\n free(buf);\n#endif\n\n return 0;\n }\n\t\t work[i]=LM_CNST(1.0)/max;\n\t}\n\n\tfor(j=0; j=max){\n\t\t\t\tmax=tmp;\n\t\t\t\tmaxi=i;\n\t\t\t}\n\t\t}\n\t\tif(j!=maxi){\n\t\t\tfor(k=0; k=0; --i){\n\t\tsum=x[i];\n\t\tfor(j=i+1; j\n#include \n#include \n#include \n\n#define DISCARD_STATUS(s) if ((s) != GSL_SUCCESS) { GSL_ERROR_VAL(\"interpolation error\", (s), GSL_NAN); }\n\ngsl_interp *\ngsl_interp_alloc (const gsl_interp_type * T, size_t size)\n{\n gsl_interp * interp;\n\n if (size < T->min_size)\n {\n GSL_ERROR_NULL (\"insufficient number of points for interpolation type\",\n GSL_EINVAL);\n }\n\n interp = (gsl_interp *) malloc (sizeof(gsl_interp));\n \n if (interp == NULL)\n {\n GSL_ERROR_NULL (\"failed to allocate space for interp struct\", \n GSL_ENOMEM);\n }\n \n interp->type = T;\n interp->size = size;\n\n if (interp->type->alloc == NULL)\n {\n interp->state = NULL;\n return interp;\n }\n\n interp->state = interp->type->alloc(size);\n \n if (interp->state == NULL)\n {\n free (interp); \n GSL_ERROR_NULL (\"failed to allocate space for interp state\", GSL_ENOMEM);\n };\n \n return interp;\n}\n\nint\ngsl_interp_init (gsl_interp * interp, const double x_array[], const double y_array[], size_t size)\n{\n if (size != interp->size)\n {\n GSL_ERROR (\"data must match size of interpolation object\", GSL_EINVAL);\n }\n \n interp->xmin = x_array[0];\n interp->xmax = x_array[size - 1];\n\n {\n int status = interp->type->init(interp->state, x_array, y_array, size);\n return status;\n }\n}\n\nconst char *\ngsl_interp_name(const gsl_interp * interp)\n{\n return interp->type->name;\n}\n\nunsigned int\ngsl_interp_min_size(const gsl_interp * interp)\n{\n return interp->type->min_size;\n}\n\nvoid\ngsl_interp_free (gsl_interp * interp)\n{\n if (interp->type->free)\n interp->type->free (interp->state);\n free (interp);\n}\n\n\n\nint\ngsl_interp_eval_e (const gsl_interp * interp,\n const double xa[], const double ya[], double x,\n gsl_interp_accel * a, double *y)\n{\n if (x < interp->xmin)\n {\n *y = ya[0];\n return GSL_EDOM;\n }\n else if (x > interp->xmax)\n {\n *y = ya[interp->size - 1];\n return GSL_EDOM;\n }\n\n return interp->type->eval (interp->state, xa, ya, interp->size, x, a, y);\n}\n\ndouble\ngsl_interp_eval (const gsl_interp * interp,\n const double xa[], const double ya[], double x,\n gsl_interp_accel * a)\n{\n double y;\n int status = interp->type->eval (interp->state, xa, ya, interp->size, x, a, &y);\n\n DISCARD_STATUS(status);\n\n return y;\n}\n\n\nint\ngsl_interp_eval_deriv_e (const gsl_interp * interp,\n const double xa[], const double ya[], double x,\n gsl_interp_accel * a,\n double *dydx)\n{\n if (x < interp->xmin)\n {\n *dydx = 0.0;\n return GSL_EDOM;\n }\n else if (x > interp->xmax)\n {\n *dydx = 0.0;\n return GSL_EDOM;\n }\n\n return interp->type->eval_deriv (interp->state, xa, ya, interp->size, x, a, dydx);\n}\n\ndouble\ngsl_interp_eval_deriv (const gsl_interp * interp,\n const double xa[], const double ya[], double x,\n gsl_interp_accel * a)\n{\n double dydx;\n int status = interp->type->eval_deriv (interp->state, xa, ya, interp->size, x, a, &dydx);\n\n DISCARD_STATUS(status);\n\n return dydx;\n}\n\n\nint\ngsl_interp_eval_deriv2_e (const gsl_interp * interp,\n const double xa[], const double ya[], double x,\n gsl_interp_accel * a,\n double * d2)\n{\n if (x < interp->xmin)\n {\n *d2 = 0.0;\n return GSL_EDOM;\n }\n else if (x > interp->xmax)\n {\n *d2 = 0.0;\n return GSL_EDOM;\n }\n\n return interp->type->eval_deriv2 (interp->state, xa, ya, interp->size, x, a, d2);\n}\n\ndouble\ngsl_interp_eval_deriv2 (const gsl_interp * interp,\n const double xa[], const double ya[], double x,\n gsl_interp_accel * a)\n{\n double d2;\n int status = interp->type->eval_deriv2 (interp->state, xa, ya, interp->size, x, a, &d2);\n\n DISCARD_STATUS(status);\n\n return d2;\n}\n\n\nint\ngsl_interp_eval_integ_e (const gsl_interp * interp,\n const double xa[], const double ya[],\n double a, double b,\n gsl_interp_accel * acc,\n double * result)\n{\n if (a > b || a < interp->xmin || b > interp->xmax)\n {\n *result = 0.0;\n return GSL_EDOM;\n }\n else if(a == b)\n {\n *result = 0.0;\n return GSL_SUCCESS;\n }\n\n return interp->type->eval_integ (interp->state, xa, ya, interp->size, acc, a, b, result);\n}\n\n\ndouble\ngsl_interp_eval_integ (const gsl_interp * interp,\n const double xa[], const double ya[],\n double a, double b,\n gsl_interp_accel * acc)\n{\n double result;\n int status = interp->type->eval_integ (interp->state, xa, ya, interp->size, acc, a, b, &result);\n\n DISCARD_STATUS(status);\n\n return result;\n}\n\n\n", "meta": {"hexsha": "036173084e52d01e3cd37e88faf4d0490634735b", "size": 5815, "ext": "c", "lang": "C", "max_stars_repo_path": "pkgs/libs/gsl/src/interpolation/interp.c", "max_stars_repo_name": "manggoguy/parsec-modified", "max_stars_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 64.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T00:30:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T13:26:53.000Z", "max_issues_repo_path": "pkgs/libs/gsl/src/interpolation/interp.c", "max_issues_repo_name": "manggoguy/parsec-modified", "max_issues_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T08:30:19.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-13T03:54:24.000Z", "max_forks_repo_path": "pkgs/libs/gsl/src/interpolation/interp.c", "max_forks_repo_name": "manggoguy/parsec-modified", "max_forks_repo_head_hexsha": "d14edfb62795805c84a4280d67b50cca175b95af", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 40.0, "max_forks_repo_forks_event_min_datetime": "2015-02-26T15:31:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-03T23:23:37.000Z", "avg_line_length": 23.7346938776, "max_line_length": 106, "alphanum_fraction": 0.5932932072, "num_tokens": 1531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251201477016, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34722653010511845}} {"text": "/* sum/levin_u.c\n * \n * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Gerard Jungman, Brian Gough\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or (at\n * your option) any later version.\n * \n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n */\n\n#include \n#include \n#include \n#include \n#include \n\nint\ngsl_sum_levin_u_accel (const double *array, const size_t array_size,\n gsl_sum_levin_u_workspace * w, \n double *sum_accel, double *abserr)\n{\n return gsl_sum_levin_u_minmax (array, array_size,\n 0, array_size - 1, w, sum_accel, abserr);\n}\n\nint\ngsl_sum_levin_u_minmax (const double *array, const size_t array_size,\n const size_t min_terms, const size_t max_terms,\n gsl_sum_levin_u_workspace * w,\n double *sum_accel, double *abserr)\n{\n /* Ignore any trailing zeros in the array */\n size_t size = array_size;\n\n while (size > 0 && array[size - 1] == 0) {\n size--;\n }\n\n if (size == 0)\n {\n *sum_accel = 0.0;\n *abserr = 0.0;\n w->sum_plain = 0.0;\n w->terms_used = 0;\n return GSL_SUCCESS;\n }\n else if (size == 1)\n {\n *sum_accel = array[0];\n *abserr = 0.0;\n w->sum_plain = array[0];\n w->terms_used = 1;\n return GSL_SUCCESS;\n }\n else\n {\n const double SMALL = 0.01;\n const size_t nmax = GSL_MAX (max_terms, array_size) - 1;\n double noise_n = 0.0, noise_nm1 = 0.0;\n double trunc_n = 0.0, trunc_nm1 = 0.0;\n double actual_trunc_n = 0.0, actual_trunc_nm1 = 0.0;\n double result_n = 0.0, result_nm1 = 0.0;\n double variance = 0;\n size_t n;\n unsigned int i;\n int better = 0;\n int before = 0;\n int converging = 0;\n double least_trunc = GSL_DBL_MAX;\n double least_trunc_noise = GSL_DBL_MAX;\n double least_trunc_result;\n\n /* Calculate specified minimum number of terms. No convergence\n tests are made, and no truncation information is stored. */\n\n for (n = 0; n < min_terms; n++)\n {\n const double t = array[n];\n result_nm1 = result_n;\n gsl_sum_levin_u_step (t, n, nmax, w, &result_n);\n }\n\n least_trunc_result = result_n;\n\n variance = 0;\n for (i = 0; i < n; i++)\n {\n double dn = w->dsum[i] * GSL_MACH_EPS * array[i];\n variance += dn * dn;\n }\n noise_n = sqrt (variance);\n\n /* Calculate up to maximum number of terms. Check truncation\n condition. */\n\n for (; n <= nmax; n++)\n {\n const double t = array[n];\n\n result_nm1 = result_n;\n gsl_sum_levin_u_step (t, n, nmax, w, &result_n);\n\n /* Compute the truncation error directly */\n\n actual_trunc_nm1 = actual_trunc_n;\n actual_trunc_n = fabs (result_n - result_nm1);\n\n /* Average results to make a more reliable estimate of the\n real truncation error */\n\n trunc_nm1 = trunc_n;\n trunc_n = 0.5 * (actual_trunc_n + actual_trunc_nm1);\n\n noise_nm1 = noise_n;\n variance = 0;\n\n for (i = 0; i <= n; i++)\n {\n double dn = w->dsum[i] * GSL_MACH_EPS * array[i];\n variance += dn * dn;\n }\n\n noise_n = sqrt (variance);\n\n /* Determine if we are in the convergence region. */\n\n better = (trunc_n < trunc_nm1 || trunc_n < SMALL * fabs (result_n));\n converging = converging || (better && before);\n before = better;\n\n if (converging)\n {\n if (trunc_n < least_trunc)\n {\n /* Found a low truncation point in the convergence\n region. Save it. */\n\n least_trunc_result = result_n;\n least_trunc = trunc_n;\n least_trunc_noise = noise_n;\n }\n\n if (noise_n > trunc_n / 3.0)\n break;\n\n if (trunc_n < 10.0 * GSL_MACH_EPS * fabs (result_n))\n break;\n }\n\n }\n\n if (converging)\n {\n /* Stopped in the convergence region. Return result and\n error estimate. */\n\n *sum_accel = least_trunc_result;\n *abserr = GSL_MAX_DBL (least_trunc, least_trunc_noise);\n w->terms_used = n;\n return GSL_SUCCESS;\n }\n else\n {\n /* Never reached the convergence region. Use the last\n calculated values. */\n\n *sum_accel = result_n;\n *abserr = GSL_MAX_DBL (trunc_n, noise_n);\n w->terms_used = n;\n return GSL_SUCCESS;\n }\n }\n}\n\n\nint\ngsl_sum_levin_u_step (const double term, const size_t n, const size_t nmax,\n gsl_sum_levin_u_workspace * w, double *sum_accel)\n{\n\n#define I(i,j) ((i)*(nmax+1) + (j))\n\n if (n == 0)\n {\n *sum_accel = term;\n w->sum_plain = term;\n\n w->q_den[0] = 1.0 / term;\n w->q_num[0] = 1.0;\n\n w->dq_den[I (0, 0)] = -1.0 / (term * term);\n w->dq_num[I (0, 0)] = 0.0;\n\n w->dsum[0] = 1.0;\n\n return GSL_SUCCESS;\n }\n else\n {\n double result;\n double factor = 1.0;\n double ratio = (double) n / (n + 1.0);\n unsigned int i;\n int j;\n\n w->sum_plain += term;\n\n w->q_den[n] = 1.0 / (term * (n + 1.0) * (n + 1.0));\n w->q_num[n] = w->sum_plain * w->q_den[n];\n\n for (i = 0; i < n; i++)\n {\n w->dq_den[I (i, n)] = 0;\n w->dq_num[I (i, n)] = w->q_den[n];\n }\n\n w->dq_den[I (n, n)] = -w->q_den[n] / term;\n w->dq_num[I (n, n)] =\n w->q_den[n] + w->sum_plain * (w->dq_den[I (n, n)]);\n\n for (j = n - 1; j >= 0; j--)\n {\n double c = factor * (j + 1) / (n + 1);\n factor *= ratio;\n w->q_den[j] = w->q_den[j + 1] - c * w->q_den[j];\n w->q_num[j] = w->q_num[j + 1] - c * w->q_num[j];\n\n for (i = 0; i < n; i++)\n {\n w->dq_den[I (i, j)] =\n w->dq_den[I (i, j + 1)] - c * w->dq_den[I (i, j)];\n w->dq_num[I (i, j)] =\n w->dq_num[I (i, j + 1)] - c * w->dq_num[I (i, j)];\n }\n\n w->dq_den[I (n, j)] = w->dq_den[I (n, j + 1)];\n w->dq_num[I (n, j)] = w->dq_num[I (n, j + 1)];\n }\n\n result = w->q_num[0] / w->q_den[0];\n\n *sum_accel = result;\n\n for (i = 0; i <= n; i++)\n {\n w->dsum[i] =\n (w->dq_num[I (i, 0)] -\n result * w->dq_den[I (i, 0)]) / w->q_den[0];\n }\n\n return GSL_SUCCESS;\n }\n}\n", "meta": {"hexsha": "81dcc75eeaa33c30732d4b629bab75362f59b360", "size": 7293, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.6/sum/levin_u.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/sum/levin_u.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/sum/levin_u.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 14.0, "max_forks_repo_forks_event_min_datetime": "2015-07-21T04:47:52.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-12T12:31:25.000Z", "avg_line_length": 27.7300380228, "max_line_length": 85, "alphanum_fraction": 0.5139174551, "num_tokens": 2147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442251064863697, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3472265227418897}} {"text": "/*\nCopyright (c) 2015, Patrick Weltevrede\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"gsl/gsl_roots.h\"\n#include \"psrsalsa.h\"\nint minimize_1D_double_refine_borders(int findroot, double (*funk)(double, void *), void *params, int gridsearch, int investigateLocalMinima, double *x_lower, double *x_upper, int debug_verbose)\n{\n double x, y, ymin[3], ymin_new[3], dy[3], ymax, x_lower_new, x_upper_new, sign_old, gridsearch_margin, imin_new[3], i_originalgrid, imin1, imin2;\n int imin[3], unset[3], i, minima;\n unset[0] = unset[1] = unset[2] = 1;\n for(i = 0; i < gridsearch; i++) {\n x = *x_lower + i*(*x_upper - *x_lower)/(double)(gridsearch-1);\n y = funk(x, params);\n if(debug_verbose) {\n fflush(stdout); fprintf(stderr, \"x=%f y=%f\\n\", x, y);\n }\n if(findroot) {\n if(i == 0) {\n sign_old = y;\n imin[0] = 0;\n }else {\n if(y < 0 && sign_old > 0) {\n imin[0] = i;\n }else if(y > 0 && sign_old < 0) {\n imin[0] = i;\n }\n if(imin[0] != 0)\n break;\n }\n }else {\n if(unset[0]) {\n imin[0] = i;\n ymin[0] = y;\n unset[0] = 0;\n }else if(unset[1]) {\n imin[1] = i;\n ymin[1] = y;\n unset[1] = 0;\n }else if(unset[2]) {\n imin[2] = i;\n ymin[2] = y;\n unset[2] = 0;\n }else {\n for(minima = 0; minima < 3; minima++) {\n dy[minima] = ymin[minima] - y;\n }\n if(dy[0] > dy[1] && dy[0] > dy[2]) {\n if(dy[0] > 0) {\n imin[0] = i;\n ymin[0] = y;\n }\n }else if(dy[1] > dy[0] && dy[1] > dy[2]) {\n if(dy[1] > 0) {\n imin[1] = i;\n ymin[1] = y;\n }\n }else {\n if(dy[2] > 0) {\n imin[2] = i;\n ymin[2] = y;\n }\n }\n }\n if(i == 0 || y > ymax) {\n ymax = y;\n }\n }\n }\n if(findroot == 0) {\n imin1 = imin[0];\n imin2 = imin[0];\n if(imin[1] < imin1)\n imin1 = imin[1];\n if(imin[2] < imin1)\n imin1 = imin[2];\n if(imin[1] > imin2)\n imin2 = imin[1];\n if(imin[2] > imin2)\n imin2 = imin[2];\n if(imin2-imin1 != 2 && debug_verbose) {\n fflush(stdout); fprintf(stderr, \"Found more than one possible minima (range = %.2f .. %.2f)\\n\", imin1, imin2);\n }\n if(imin2-imin1 > 0.3*gridsearch) {\n if(investigateLocalMinima == 0) {\n imin1 = imin[0];\n imin2 = imin[0];\n if(ymin[1] < ymin[0]) {\n imin1 = imin[1];\n imin2 = imin[1];\n }else if(ymin[2] < ymin[0] && ymin[2] < ymin[1]) {\n imin1 = imin[2];\n imin2 = imin[2];\n }\n }else {\n if(debug_verbose) {\n fflush(stdout); fprintf(stderr, \"Refining gridsearch around local minima\\n\");\n }\n unset[0] = unset[1] = unset[2] = 1;\n for(minima = 0; minima < 3; minima++) {\n for(x = *x_lower + (imin[minima]-1.5)*(*x_upper - *x_lower)/(double)(gridsearch-1); x < *x_lower + (imin[minima]+1.5)*(*x_upper - *x_lower)/(double)(gridsearch-1); x += 0.09*(*x_upper - *x_lower)/(double)(gridsearch-1)) {\n y = funk(x, params);\n if(debug_verbose) {\n fflush(stdout); fprintf(stderr, \"x=%f y=%f\\n\", x, y);\n }\n i_originalgrid = (x - *x_lower)*(double)(gridsearch-1)/(*x_upper - *x_lower);\n if(unset[0] || y < ymin_new[0]) {\n imin_new[0] = i_originalgrid;\n ymin_new[0] = y;\n unset[0] = 0;\n }else if(unset[1] || y < ymin_new[1]) {\n imin_new[1] = i_originalgrid;\n ymin_new[1] = y;\n unset[1] = 0;\n }else if(unset[2] || y < ymin_new[2]) {\n imin_new[2] = i_originalgrid;\n ymin_new[2] = y;\n unset[2] = 0;\n }\n }\n }\n imin1 = imin_new[0];\n imin2 = imin_new[0];\n if(imin_new[1] < imin1)\n imin1 = imin_new[1];\n if(imin_new[2] < imin1)\n imin1 = imin_new[2];\n if(imin_new[1] > imin2)\n imin2 = imin_new[1];\n if(imin_new[2] > imin2)\n imin2 = imin_new[2];\n if(imin2-imin1 != 2 && debug_verbose) {\n fflush(stdout); fprintf(stderr, \"Found more than one possible minima (range = %.2f .. %.2f)\\n\", imin1, imin2);\n }\n if(imin2-imin1 > 0.3*gridsearch) {\n fflush(stdout); fprintf(stderr, \"minimize_1D_double_refine_borders: Refining gridsearch around local minima failed\\n\");\n exit(0);\n }\n }\n }\n }\n gridsearch_margin = 0.1*(double)gridsearch;\n if(gridsearch_margin < 1)\n gridsearch_margin = 1;\n if(findroot) {\n if(imin[0] == 0) {\n return 2;\n }\n x_lower_new = *x_lower + (imin[0]-gridsearch_margin)*(*x_upper - *x_lower)/(double)(gridsearch-1);\n x_upper_new = *x_lower + (imin[0]+gridsearch_margin-1)*(*x_upper - *x_lower)/(double)(gridsearch-1);\n *x_lower = x_lower_new;\n *x_upper = x_upper_new;\n }else {\n x_lower_new = *x_lower + (imin1-gridsearch_margin)*(*x_upper - *x_lower)/(double)(gridsearch-1);\n x_upper_new = *x_lower + (imin2+gridsearch_margin)*(*x_upper - *x_lower)/(double)(gridsearch-1);\n *x_lower = x_lower_new;\n *x_upper = x_upper_new;\n }\n return 0;\n}\nint minimize_1D_double(int findroot, double (*funk)(double, void *), void *params, double x_lower, double x_upper, int gridsearch, int investigateLocalMinima, int nested, double *x_minimum, int max_iter, double epsabs, double epsrel, int verbose, int debug_verbose)\n{\n const gsl_min_fminimizer_type *T_minimizer;\n gsl_min_fminimizer *s_minimizer;\n const gsl_root_fsolver_type *T_root;\n gsl_root_fsolver *s_root;\n int status;\n int iter, i, ret, nest;\n gsl_function F;\n F.function = funk;\n F.params = params;\n iter = 0;\n#if GSL_VERSION_NUMBER < 102\n printerror(0, \"ERROR minimize_1D_double: Not supported for GSL < 1.2\");\n exit(0);\n#endif\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n if(findroot == 0)\n printf(\"Minimising function between %f and %f\\n\", x_lower, x_upper);\n else\n printf(\"Finding root of function between %f and %f\\n\", x_lower, x_upper);\n }\n if(gridsearch > 1) {\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Refining boundaries with a %d point grid search\\n\", gridsearch);\n }\n for(nest = 0; nest < 1+nested; nest++) {\n ret = minimize_1D_double_refine_borders(findroot, funk, params, gridsearch, investigateLocalMinima, &x_lower, &x_upper, debug_verbose);\n if(ret != 0) {\n if(ret == 1) {\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Maximum itterations (%d) exceeded while refining borders\\n\", max_iter);\n }\n }\n return ret;\n }\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Refined boundaries are %f and %f\\n\", x_lower, x_upper);\n }\n }\n }\n *x_minimum = 0.5*(x_upper+x_lower);\n if(findroot == 0) {\n T_minimizer = gsl_min_fminimizer_brent;\n s_minimizer = gsl_min_fminimizer_alloc(T_minimizer);\n fflush(stdout);\n gsl_min_fminimizer_set(s_minimizer, &F, *x_minimum, x_lower, x_upper);\n }else {\n T_root = gsl_root_fsolver_brent;\n s_root = gsl_root_fsolver_alloc(T_root);\n if(gridsearch == 0) {\n double val1, val2;\n val1 = funk(x_lower, params);\n val2 = funk(x_upper, params);\n if((val1 > 0 && val2 > 0) || (val1 < 0 && val2 < 0)) {\n return 3;\n }\n }\n gsl_root_fsolver_set(s_root, &F, x_lower, x_upper);\n }\n do {\n iter++;\n if(findroot == 0) {\n status = gsl_min_fminimizer_iterate(s_minimizer);\n#if GSL_VERSION_NUMBER >= 102\n *x_minimum = gsl_min_fminimizer_x_minimum (s_minimizer);\n#endif\n x_lower = gsl_min_fminimizer_x_lower(s_minimizer);\n x_upper = gsl_min_fminimizer_x_upper(s_minimizer);\n }else {\n status = gsl_root_fsolver_iterate(s_root);\n *x_minimum = gsl_root_fsolver_root(s_root);\n x_lower = gsl_root_fsolver_x_lower(s_root);\n x_upper = gsl_root_fsolver_x_upper(s_root);\n }\n status = gsl_min_test_interval (x_lower, x_upper, epsabs, epsrel);\n }while(status == GSL_CONTINUE && iter < max_iter);\n if(findroot)\n gsl_root_fsolver_free(s_root);\n else\n gsl_min_fminimizer_free(s_minimizer);\n if(status == GSL_SUCCESS) {\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n if(findroot)\n printf(\" Root found at %f with error %f\\n\", *x_minimum, fabs(x_upper - x_lower));\n else\n printf(\" Minimum found at %f with error %f\\n\", *x_minimum, fabs(x_upper - x_lower));\n }\n return 0;\n }else if(iter == max_iter) {\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Maximum itterations (%d) exceeded. Value confined to [%f, %f]\\n\", max_iter, x_lower, x_upper);\n }\n return 1;\n }else {\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Unknown error during minimization\\n\");\n }\n return 5;\n }\n return status;\n}\ndouble (*internal_funk_provided_by_user)(double *, void *);\nint internal_paramnr;\ndouble *internal_xminimum;\ndouble internal_desired_chi2;\ndouble internal_find_1D_error_funk(double x, void *params)\n{\n double chi2;\n internal_xminimum[internal_paramnr] = x;\n chi2 = internal_funk_provided_by_user(internal_xminimum, params);\n chi2 -= internal_desired_chi2;\n return chi2;\n}\nint find_1D_error(double (*funk)(double *, void *), double *xminimum, int paramnr, int nrparameters, double dx, double dxmax, void *params, double sigma, double chi2min, int max_itr, double epsabs, double epsrel, double *errorbar, int verbose)\n{\n int ittr, i, ret, debug_verbose;\n double x_lower, x_upper, diff, xval, *xminimum_fiddle;\n debug_verbose = 0;\n dx = fabs(dx);\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\"Finding error at value %f with stepsize %f\\n\", xminimum[paramnr], dx);\n }\n xminimum_fiddle = malloc(nrparameters*sizeof(double));\n if(xminimum_fiddle == NULL) {\n fflush(stdout);\n fprintf(stderr, \"ERROR find_1D_error: Memory allocation error\\n\");\n return 4;\n }\n memcpy(xminimum_fiddle, xminimum, nrparameters*sizeof(double));\n internal_paramnr = paramnr;\n internal_xminimum = xminimum_fiddle;\n internal_funk_provided_by_user = funk;\n internal_desired_chi2 = chi2min*(1+fabs(sigma));\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Mimimum chi2 = %f, so %f sigma point corresponds to %f\\n\", chi2min, fabs(sigma), internal_desired_chi2);\n }\n x_lower = xminimum[paramnr];\n x_upper = xminimum[paramnr];\n ittr = 0;\n diff = internal_find_1D_error_funk(x_upper, params);\n if(diff > 0) {\n fflush(stdout);\n fprintf(stderr, \"ERROR find_1D_error: Function called with initial parameters outside specified sigma limit: chi2 = %f higher than sigma border (%f).\\n\", diff, internal_desired_chi2);\n exit(0);\n }\n do {\n if(sigma >= 0) {\n x_upper += dx;\n if(dxmax >= 0) {\n if(fabs(x_upper - xminimum[paramnr]) > dxmax) {\n *errorbar = dxmax;\n free(xminimum_fiddle);\n return 0;\n }\n }\n diff = internal_find_1D_error_funk(x_upper, params);\n }else {\n x_lower -= dx;\n if(dxmax >= 0) {\n if(fabs(x_lower - xminimum[paramnr]) > dxmax) {\n *errorbar = dxmax;\n free(xminimum_fiddle);\n return 0;\n }\n }\n diff = internal_find_1D_error_funk(x_lower, params);\n }\n ittr++;\n if(ittr == max_itr) {\n free(xminimum_fiddle);\n return 1;\n }\n }while(diff < 0);\n if(verbose) {\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n printf(\" Found brackets: [%f %f]\\n\", x_lower, x_upper);\n verbose += 2;\n }\n ret = minimize_1D_double(1, internal_find_1D_error_funk, params, x_lower, x_upper, 0, 0, 0, &xval, max_itr, epsabs, epsrel, verbose, debug_verbose);\n *errorbar = fabs(xval - xminimum[paramnr]);\n if(verbose) {\n verbose -= 2;\n for(i = 0; i < verbose - 1; i++)\n printf(\" \");\n if(ret == 0)\n printf(\" Found errorbar: %f\\n\", *errorbar);\n else if(ret == 1)\n printf(\" Maximum nr of itterations reached, did not converge fully\\n\");\n else if(ret == 2)\n printf(\" Did not find root in specified range\\n\");\n else if(ret == 3)\n printf(\" Lower and upper limit do not bracket a root\\n\");\n else {\n ret = 5;\n printf(\" Other unspecified error\\n\");\n }\n }\n free(xminimum_fiddle);\n return ret;\n}\n", "meta": {"hexsha": "f4bda75a0080a41a5d800021b1eabd1838e91981", "size": 13385, "ext": "c", "lang": "C", "max_stars_repo_path": "src/lib/minimize.c", "max_stars_repo_name": "David-McKenna/psrsalsa", "max_stars_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2017-09-05T23:22:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-11T14:12:18.000Z", "max_issues_repo_path": "src/lib/minimize.c", "max_issues_repo_name": "David-McKenna/psrsalsa", "max_issues_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-04-26T13:35:30.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T08:49:57.000Z", "max_forks_repo_path": "src/lib/minimize.c", "max_forks_repo_name": "David-McKenna/psrsalsa", "max_forks_repo_head_hexsha": "e5074b552d1c404123dee058d5cee79ea230b5a9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-09T09:04:46.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-16T15:24:07.000Z", "avg_line_length": 33.5463659148, "max_line_length": 755, "alphanum_fraction": 0.6340679866, "num_tokens": 4199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6584175139669997, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.34719443439729586}} {"text": "#include \n#include \n#include \n#include \n\n/* Calculate the exponential integral function by invoking the GNU scientific\n library */\n/* Only intended to be used with R; not the most elegant integration but it\n may do for now */\n\n/* One argument, the value (double) at which to evaluate Ei(x) */\n\ndouble x, ei; /* argument to exponential integral, value */\nchar *program_name; /* name program is invoked under, for errors */\n\nint main(int argc, char* argv[]) {\n void usage(void);\t/* Warn users about proper usage */\n\n program_name = argv[0];\n if (argc != 2) {\n usage();\n }\n x = atof(&argv[1][0]);\n ei = gsl_sf_expint_E1(x);\n printf(\"%.18e\\n\",ei);\n return(0);\n}\n\nvoid usage(void) {\n (void) fprintf(stderr, \"Usage is %s [floating-point argument]\\n\", program_name);\n exit(8);\n}\n", "meta": {"hexsha": "fc547bcf167f05fbd4eb0ae81a8e7a62454527a6", "size": 837, "ext": "c", "lang": "C", "max_stars_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/exponential-integral/exp_int.c", "max_stars_repo_name": "jguerber/spatialwarnings", "max_stars_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709", "max_stars_repo_licenses": ["Unlicense", "MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-07-06T14:32:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T11:21:19.000Z", "max_issues_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/exponential-integral/exp_int.c", "max_issues_repo_name": "jguerber/spatialwarnings", "max_issues_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709", "max_issues_repo_licenses": ["Unlicense", "MIT"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2017-03-07T07:53:48.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-10T16:25:24.000Z", "max_forks_repo_path": "tests/testthat/pli-R-v0.0.3-2007-07-25/exponential-integral/exp_int.c", "max_forks_repo_name": "jguerber/spatialwarnings", "max_forks_repo_head_hexsha": "86bf0ff11882069b47c5663fa8a4ae386e8cb709", "max_forks_repo_licenses": ["Unlicense", "MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-05-12T08:50:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T10:29:33.000Z", "avg_line_length": 25.3636363636, "max_line_length": 82, "alphanum_fraction": 0.6654719235, "num_tokens": 225, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.3468958035175102}} {"text": "/* Copyright (c) 2011-2012, Jérémy Fix. All rights reserved. */\n\n/* Redistribution and use in source and binary forms, with or without */\n/* modification, are permitted provided that the following conditions are met: */\n\n/* * Redistributions of source code must retain the above copyright notice, */\n/* this list of conditions and the following disclaimer. */\n/* * Redistributions in binary form must reproduce the above copyright notice, */\n/* this list of conditions and the following disclaimer in the documentation */\n/* and/or other materials provided with the distribution. */\n/* * None of the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. */\n\n/* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND */\n/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */\n/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */\n/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE */\n/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL */\n/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR */\n/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */\n/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */\n/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */\n/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */\n\n#ifndef UKF_MATH_H\n#define UKF_MATH_H\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace ukf\n{\n namespace math\n {\n\n inline double min(double a, double b)\n {\n return a < b ? a : b;\n }\n\n inline double max(double a, double b)\n {\n return a < b ? b : a;\n }\n\n inline double signof(double x)\n {\n return x <= 0.0 ? -1.0 : 1.0;\n }\n\n inline bool cmp_equal(double x, double y)\n {\n return fabs(x - y) <= 1e-10;\n }\n inline bool cmp_diff(double x, double y)\n {\n return fabs(x - y) >= 1e-10;\n }\n\n /**\n * @brief This function performs a cholesky update according to Strange et al.(2007)\n * @author Mathieu.Geist@Supelec.fr\n *\n */\n void choleskyUpdate(gsl_matrix * sigmaTheta, double alpha, gsl_vector *x) {\n\n /*\n This function performs a cholesky update of the\n cholesky factorization sigmaTheta, that is it replaces\n the Cholesky factorization sigmaTheta by the cholesky factorization of\n\n sigmaTheta*sigmaTheta^T + alpha * x * x^T\n\n The algorithm is an adaptation of a LU factorization rank one update.\n\n Reference is :\n\n Peter Strange, Andreas Griewank and Matthias Bollhöfer.\n On the Efficient Update of Rectangular LU Factorizations subject to Low Rank Modifications.\n Electronic Transactions on Numerical Analysis, 26:161-177, 2007.\n alg. is given in left part of fig.2.1.\n\n Perhaps a more efficient algorithm exists, however it should do the work for now. And the code is probably not optimal...\n */\n\n if (sigmaTheta->size1 != sigmaTheta->size2)\n std::cout<<\"ERROR ukf::math::choleskyUpdate Cannot use CholeskyUpdate on non-squared matrices\"<size1 ;\n double tmp ;\n gsl_matrix *U = gsl_matrix_alloc(n,n) ;\n gsl_vector *D = gsl_vector_alloc(n) ;\n gsl_vector *y = gsl_vector_alloc(n) ;\n\n // A first thing is to set SS' (chol factor) in a LU form, L being unitriangular\n // Compute U = L^T and D = diag(L)\n gsl_matrix_set_zero(U) ;\n for (i=0; i1]\n\n*/\n\n#include \n#include \"defines.h\"\n#include \n#include \n#include \"/opt/local/cfitsio/cfitsio-3.350/include/fitsio.h\" ///opt/local/cfitsio/cfitsio-3.350/include/\n#include \"utilsFits.h\"\n#include \"milosUtils.h\"\n#include \"lib.h\"\n#include \"readConfig.h\"\n#include \n#include \n#include //siempre a continuacion de complex.h\n#include \n#include \n#include \n#include \n\nint NTERMS = 11;\nCuantic *cuantic; // Variable global, está hecho así, de momento,para parecerse al original\n\n\nPRECISION **PUNTEROS_CALCULOS_COMPARTIDOS;\nint POSW_PUNTERO_CALCULOS_COMPARTIDOS;\nint POSR_PUNTERO_CALCULOS_COMPARTIDOS;\n\nREAL *dtaux, *etai_gp3, *ext1, *ext2, *ext3, *ext4;\nREAL *gp1, *gp2, *dt, *dti, *gp3, *gp4, *gp5, *gp6, *etai_2;\nREAL *gp4_gp2_rhoq, *gp5_gp2_rhou, *gp6_gp2_rhov;\nREAL *dgp1, *dgp2, *dgp3, *dgp4, *dgp5, *dgp6, *d_dt;\nREAL *d_ei, *d_eq, *d_eu, *d_ev, *d_rq, *d_ru, *d_rv;\nREAL *dfi, *dshi;\nREAL CC, CC_2, sin_gm, azi_2, sinis, cosis, cosis_2, cosi, sina, cosa, sinda, cosda, sindi, cosdi, sinis_cosa, sinis_sina;\nREAL *fi_p, *fi_b, *fi_r, *shi_p, *shi_b, *shi_r;\nREAL *etain, *etaqn, *etaun, *etavn, *rhoqn, *rhoun, *rhovn;\nREAL *etai, *etaq, *etau, *etav, *rhoq, *rhou, *rhov;\nREAL *parcial1, *parcial2, *parcial3;\nREAL *nubB, *nupB, *nurB;\nREAL **uuGlobalInicial;\nREAL **HGlobalInicial;\nREAL **FGlobalInicial;\n\n\nPRECISION *GMAC,* GMAC_DERIV;\nPRECISION * dirConvPar;\nREAL *resultConv;\nPRECISION * G = NULL;\n\n\nREAL * opa;\nint FGlobal, HGlobal, uuGlobal;\n\nREAL *d_spectra, *spectra, *spectra_mac, *spectra_slight;\n\n// GLOBAL variables to use for FFT calculation \nfftw_complex * inSpectraFwPSF, *inSpectraBwPSF, *outSpectraFwPSF, *outSpectraBwPSF;\nfftw_complex * inSpectraFwMAC, *inSpectraBwMAC, *outSpectraFwMAC, *outSpectraBwMAC;\nfftw_plan planForwardPSF, planBackwardPSF;\nfftw_plan planForwardMAC, planBackwardMAC;\nfftw_complex * inFilterMAC, * inFilterMAC_DERIV, * outFilterMAC, * outFilterMAC_DERIV;\nfftw_plan planFilterMAC, planFilterMAC_DERIV;\n\n\nfftw_complex * fftw_G_PSF, * fftw_G_MAC_PSF, * fftw_G_MAC_DERIV_PSF;\nfftw_complex * inPSF_MAC, * inMulMacPSF, * inPSF_MAC_DERIV, *inMulMacPSFDeriv, *outConvFilters, * outConvFiltersDeriv;\nfftw_plan planForwardPSF_MAC, planForwardPSF_MAC_DERIV,planBackwardPSF_MAC, planBackwardPSF_MAC_DERIV;\n\n\n//Convolutions values\nint sizeG = 0;\nPRECISION FWHM = 0;\n\nConfigControl configCrontrolFile;\n\n// fvoigt memory consuption\n _Complex double *z,* zden, * zdiv;\n \ngsl_vector *eval;\ngsl_matrix *evec;\ngsl_eigen_symmv_workspace * workspace;\n\nint main(int argc, char **argv)\n{\n\tint i; // for indexes\n\tPRECISION *wlines;\n\tint nlambda;\n\tInit_Model *vModels;\n\tfloat chisqrf, * vChisqrf;\n\tint * vNumIter; // to store the number of iterations used to converge for each pixel\n\tint indexLine, free_params; // index to identify central line to read it \n\n\t//*****\n\tInit_Model INITIAL_MODEL;\n\tPRECISION * deltaLambda, * PSF;\n\tPRECISION initialLambda, step, finalLambda;\n\tint N_SAMPLES_PSF;\n\tint posWL=0;\n\t//----------------------------------------------\n\n\tfloat * slight = NULL;\n\tint nl_straylight, ns_straylight, nx_straylight=0,ny_straylight=0;\n\tconst char * nameInputFileSpectra ;\n\tchar nameOutputFilePerfiles [4096];\n\tconst char\t* nameInputFileLines;\n\tconst char\t* nameInputFilePSF ;\t\n FitsImage * fitsImage;\n\tPRECISION dat[7];\n\n\t/********************* Read data input from file ******************************/\n\n\t/* Read data input from file */\n\n\tloadInitialValues(&configCrontrolFile);\n\treadTrolFile(argv[1],&configCrontrolFile,1);\n\n\tnameInputFileSpectra = configCrontrolFile.ObservedProfiles;\n\tnameInputFileLines = configCrontrolFile.AtomicParametersFile;\n\t\n\tnameInputFilePSF = configCrontrolFile.PSFFile;\n\tFWHM = configCrontrolFile.FWHM;\n\n\t/***************** READ INIT MODEL ********************************/\n\tif(configCrontrolFile.InitialGuessModel[0]!='\\0' && !readInitialModel(&INITIAL_MODEL,configCrontrolFile.InitialGuessModel)){\n\t\tprintf(\"\\nERROR READING GUESS MODEL 1 FILE\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\tcheckInitialModel(&INITIAL_MODEL);\n\n\tif(INITIAL_MODEL.alfa<1 && access(configCrontrolFile.StrayLightFile,F_OK)){\n\t\tprintf(\"\\nERROR. Filling factor in Initial model is less than 1 and Stray Light file %s can not be accessed\\n\",configCrontrolFile.StrayLightFile);\n\t\texit(EXIT_FAILURE);\n\t}\n\t\n\tif(configCrontrolFile.fix[10]==0) NTERMS--;\n\tif(INITIAL_MODEL.mac ==0 && configCrontrolFile.fix[9]==0){\n\t\t NTERMS--;\n\t}\n\t\n\t// allocate memory for eigen values\n\teval = gsl_vector_alloc (NTERMS);\n \tevec = gsl_matrix_alloc (NTERMS, NTERMS);\n\tworkspace = gsl_eigen_symmv_alloc (NTERMS);\n\n\t/***************** READ WAVELENGHT FROM GRID OR FITS ********************************/\n\tPRECISION * vLambda, *vOffsetsLambda;\n\n\tif(configCrontrolFile.useMallaGrid){ // read lambda from grid file\n\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\tprintf(\"\\nMALLA GRID FILE READ: %s\",configCrontrolFile.MallaGrid);\n\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\tindexLine = readMallaGrid(configCrontrolFile.MallaGrid, &initialLambda, &step, &finalLambda, 1); \n\t\tprintf(\"--------------------------------------------------------------------------------\\n\");\n\t\tnlambda = ((finalLambda-initialLambda)/step)+1;\n\t\tvOffsetsLambda = calloc(nlambda,sizeof(PRECISION));\n\t\tvOffsetsLambda[0] = initialLambda;\n\t\tfor(i=1;i 0){\n\t\t\tG = fgauss_WL(FWHM,vLambda[1]-vLambda[0],vLambda[0],vLambda[nlambda/2],nlambda,&sizeG);\n\t\t\t//char nameAux [4096];\n\t\t\t//char obsAux [4096];\n\t\t\t//if(configCrontrolFile.ObservedProfiles[0]!='\\0'){\n\t\t\t//\tstrcpy(obsAux,configCrontrolFile.ObservedProfiles);\n\t\t\t//\tstrcpy(nameAux,dirname(obsAux));\n\t\t\t//}\n\t\t\t//else{\n\t\t\t//\tstrcpy(obsAux,configCrontrolFile.InitialGuessModel);\n\t\t\t//\tstrcpy(nameAux,dirname(obsAux));\t\t\n\t\t\t//}\n\t\t\t//strcat(nameAux,\"/gaussian.psf\");\n\t\t\t//FILE *fptr = fopen(nameAux, \"w\");\n\n\t\t\tFILE *fptr = fopen(\"gaussian.psf\", \"w\");\n\n\t\t\tif(fptr!=NULL){\n\t\t\t printf(\"\\n Gaussian PSF will be saved to file gaussian.psf\"); \n\t\t\t\tint kk;\n\t\t\t\tfor (kk = 0; kk < nlambda; kk++)\n\t\t\t\t{\n\t\t\t\t\tfprintf(fptr,\"\\t%f\\t%e\\n\", (vLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, G[kk]);\n\t\t\t\t}\n\t\t\t\tfclose(fptr);\n\t\t\t}\n\t\t\telse{\n\t\t\t //\tprintf(\"\\n ERROR !!! The output file cannot be opened: %s\",nameAux);\n\t\t\t\tprintf(\"\\n ERROR !!! The output file cannot be opened: gaussian.psf\");\n\t\t\t}\t\t\t\n\t\t}else{\n\t\t\t// read the number of lines \n\t\t\tFILE *fp;\n\t\t\tchar ch;\n\t\t\tN_SAMPLES_PSF=0;\n\t\t\t//open file in read more\n\t\t\tfp=fopen(nameInputFilePSF,\"r\");\n\t\t\tif(fp==NULL)\n\t\t\t{\n\t\t\t\tprintf(\"File \\\"%s\\\" does not exist!!!\\n\",nameInputFilePSF);\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\t//read character by character and check for new line\t\n\t\t\twhile((ch=fgetc(fp))!=EOF)\n\t\t\t{\n\t\t\t\tif(ch=='\\n')\n\t\t\t\t\tN_SAMPLES_PSF++;\n\t\t\t}\n\t\t\t\n\t\t\t//close the file\n\t\t\tfclose(fp);\n\t\t\tif(N_SAMPLES_PSF>0){\n\t\t\t\tdeltaLambda = calloc(N_SAMPLES_PSF,sizeof(PRECISION));\n\t\t\t\tPSF = calloc(N_SAMPLES_PSF,sizeof(PRECISION));\n\t\t\t\treadPSFFile(deltaLambda,PSF,nameInputFilePSF,configCrontrolFile.CentralWaveLenght);\n\t\t\t\t// CHECK if values of deltaLambda are in the same range of vLambda. For do that we truncate to 4 decimal places \n\t\t\t\tif( (trunc(vOffsetsLambda[0])) < (trunc(deltaLambda[0])) || (trunc(vOffsetsLambda[nlambda-1])) > (trunc(deltaLambda[N_SAMPLES_PSF-1])) ){\n\t\t\t\t\tprintf(\"\\n\\n ERROR: The wavelength range given in the PSF file is smaller than the range in the mesh file [%lf,%lf] [%lf,%lf] \\n\\n\",deltaLambda[0],vOffsetsLambda[0],deltaLambda[N_SAMPLES_PSF-1],vOffsetsLambda[nlambda-1]);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t\tG = malloc(nlambda * sizeof(PRECISION));\n\t\t\t\t\n\t\t\t\tdouble offset=0;\n\t\t\t\tfor(i=0;i WE USE CLASSICAL ESTIMATES \n\t// IF NUMBER OF CYCLES IS 0 THEN --> DO SYNTHESIS FROM THE INIT MODEL \n\t// IF NUMBER OF CYCLES IS GREATER THAN 0 --> READ FITS FILE OR PER FILE AND PROCESS DO INVERSION WITH N CYCLES \n\n\n\tif(configCrontrolFile.NumberOfCycles<0){\n\t\t// read fits or per \n \n\t\tAllocateMemoryDerivedSynthesis(nlambda);\n\t\tif(strcmp(file_ext(configCrontrolFile.ObservedProfiles),PER_FILE)==0){ // invert only per file\n\t\t\tfloat * spectroPER = calloc(nlambda*NPARMS,sizeof(float));\n\t\t\tFILE * fReadSpectro;\n\t\t\tchar * line = NULL;\n\t\t\tsize_t len = 0;\n\t\t\tssize_t read;\n\t\t\tfReadSpectro = fopen(configCrontrolFile.ObservedProfiles, \"r\");\n\t\t\t\n\t\t\tint contLine=0;\n\t\t\tif (fReadSpectro == NULL)\n\t\t\t{\n\t\t\t\tprintf(\"Error opening the file of parameters, it's possible that the file doesn't exist. Please verify it. \\n\");\n\t\t\t\tprintf(\"\\n ******* THIS IS THE NAME OF THE FILE RECEVIED : %s \\n\", configCrontrolFile.ObservedProfiles);\n\t\t\t\tfclose(fReadSpectro);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\tfloat aux1, aux2,aux3,aux4,aux5,aux6;\n\t\t\twhile ((read = getline(&line, &len, fReadSpectro)) != -1 && contLinenumPixels , sizeof(Init_Model));\n\t\t\tvChisqrf = calloc (fitsImage->numPixels , sizeof(float));\n\t\t\tvNumIter = calloc (fitsImage->numPixels , sizeof(int));\n\t\t\tfor(indexPixel = 0; indexPixel < fitsImage->numPixels; indexPixel++){\n\n\t\t\t\t//Initial Model\n\t\t\t\tInit_Model initModel;\n\t\t\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\t\t\tinitModel.B = INITIAL_MODEL.B; //200 700\n\t\t\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\t\t\tinitModel.az = INITIAL_MODEL.az;\n\t\t\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\t\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\t\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\t\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\t\t\tinitModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor\n\t\t\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\t\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\t\t\t\testimacionesClasicas(wlines[1],vLambda, nlambda, fitsImage->pixels[indexPixel].spectro, &initModel,0);\n\t\t\t\tvModels[indexPixel] = initModel;\n\n\t\t\t}\n\t\t\tchar nameAuxOutputModel [4096];\n\t\t\tif(configCrontrolFile.ObservedProfiles[0]!='\\0')\n\t\t\t\tstrcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\t\telse\n\t\t\t\tstrcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel));\n\t\t\tstrcat(nameAuxOutputModel,\"_model_ce\");\n\t\t\tstrcat(nameAuxOutputModel,FITS_FILE);\t\t\t\n\t\t\tif(!writeFitsImageModels(nameAuxOutputModel,fitsImage->rows,fitsImage->cols,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){\n\t\t\t\t\tprintf(\"\\n ERROR WRITING FILE OF MODELS: %s\",nameAuxOutputModel);\n\t\t\t}\n\t\t\tfree(vModels);\n\t\t\tfree(vChisqrf);\n\t\t\tfree(vNumIter);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"\\n OBSERVED PROFILES DOESN'T HAVE CORRECT EXTENSION .PER or .FITS \");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\telse if(configCrontrolFile.NumberOfCycles==0){ // synthesis\n\t\t\n\t\tif(access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ // IF NOT EMPTY READ stray light file \n\t\t\tif(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){\n\t\t\t\tslight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nSTRAY LIGHT FILE READ: %s \", configCrontrolFile.StrayLightFile);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t}\n\t\t\telse if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){\n\t\t\t\tslight= readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight);\n\t\t\t\tif(nx_straylight!=0 || ny_straylight!=0){\n\t\t\t\t\tprintf(\"\\n Stray light file has 4 dimensions and for Synthesis only 2 dimensiones file is accepted, henceforth, stray light will not used for synthesis. \\n\");\n\t\t\t\t\tfree(slight);\n\t\t\t\t\tslight= NULL;\n\t\t\t\t}\n\t\t\t\tif(nl_straylight!=nlambda){\n\t\t\t\t\tprintf(\"\\n The number of wavelengths is different in the stray light file: %d and malla grid file %d. \\n. Stray light will not used for synthesis.\", nl_straylight,nlambda);\n\t\t\t\t\tfree(slight);\n\t\t\t\t\tslight= NULL;\n\t\t\t\t}\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nSTRAY LIGHT FILE READ: %s \", configCrontrolFile.StrayLightFile);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t}\n\t\t\telse{\n\t\t\t\tprintf(\"\\n Stray light file hasn't extension .PER or .FITS, review it. \\n. Stray light will not used for synthesis.\\n\");\n\t\t\t\tfree(slight);\n\t\t\t\tslight= NULL;\t\t\t\t\n\t\t\t}\n\t\t}\n\n\t\tInit_Model initModel;\n\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\tinitModel.B = INITIAL_MODEL.B; //200 700\n\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\tinitModel.az = INITIAL_MODEL.az;\n\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\tinitModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor\n\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\tprintf(\"\\nATMOSPHERE MODEL FILE READ: %s \",configCrontrolFile.InitialGuessModel);\n\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\tprintf(\"\\nINITAL MODEL ATMOSPHERE: \\n\\n\");\n\t\tprintf(\"eta_0 :%lf\\n\",initModel.eta0);\n\t\tprintf(\"magnetic field [G] :%lf\\n\",initModel.B);\n\t\tprintf(\"LOS velocity[km/s] :%lf\\n\",initModel.vlos);\n\t\tprintf(\"Doppler width [A] :%lf\\n\",initModel.dopp);\n\t\tprintf(\"damping :%lf\\n\",initModel.aa);\n\t\tprintf(\"gamma [deg] :%lf\\n\",initModel.gm);\n\t\tprintf(\"phi [deg] :%lf\\n\",initModel.az);\n\t\tprintf(\"S_0 :%lf\\n\",initModel.S0);\n\t\tprintf(\"S_1 :%lf\\n\",initModel.S1);\n\t\tprintf(\"v_mac [km/s] :%lf\\n\",initModel.mac);\n\t\tprintf(\"filling factor :%lf\\n\",initModel.alfa);\n\t\tprintf(\"--------------------------------------------------------------------------------\\n\");\n\n\t\tAllocateMemoryDerivedSynthesis(nlambda);\n\n\t\tif(configCrontrolFile.ConvolveWithPSF && initModel.mac>0){\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nThe program needs to use convolution. Filter PSF activated and macroturbulence greater than zero. \");\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t}\n\t\telse if(configCrontrolFile.ConvolveWithPSF){\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nThe program needs to use convolution. Filter PSF activated. \");\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t}\n\t\telse if(initModel.mac>0){\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nThe program needs to use convolution. Macroturbulence in initial atmosphere model greater than zero.\");\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t}\n\t\t// synthesis\n\t\tmil_sinrf(cuantic, &initModel, wlines, vLambda, nlambda, spectra, configCrontrolFile.mu, slight,spectra_mac,spectra_slight, configCrontrolFile.ConvolveWithPSF);\n\t\tme_der(cuantic, &initModel, wlines, vLambda, nlambda, d_spectra, spectra_mac, spectra_slight, configCrontrolFile.mu, slight, configCrontrolFile.ConvolveWithPSF,configCrontrolFile.fix);\t\n\n\t\t// in this case basenamefile is from initmodel\n\t\tchar nameAux [4096];\n\t\t\n\t\tif(configCrontrolFile.ObservedProfiles[0]!='\\0')\n\t\t\tstrcpy(nameAux,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\telse\n\t\t\tstrcpy(nameAux,get_basefilename(configCrontrolFile.InitialGuessModel));\t\t\n\t\tstrcat(nameAux,PER_FILE);\n\t\tFILE *fptr = fopen(nameAux, \"w\");\n\t\tif(fptr!=NULL){\n\t\t\tint kk;\n\t\t\tfor (kk = 0; kk < nlambda; kk++)\n\t\t\t{\n\t\t\t\tfprintf(fptr,\"%d\\t%f\\t%e\\t%e\\t%e\\t%e\\n\", indexLine, (vLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, spectra[kk], spectra[kk + nlambda], spectra[kk + nlambda * 2], spectra[kk + nlambda * 3]);\n\t\t\t}\n\t\t\tfclose(fptr);\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\n------------------SYNTHESIS DONE: %s\",nameAux);\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t}\n\t\telse{\n\t\t\tprintf(\"\\n ERROR !!! The output file can not be open: %s\",nameAux);\n\t\t}\n\n\t\t/*int number_parametros = 0;\n\t\tfor (number_parametros = 0; number_parametros < NTERMS; number_parametros++)\n\t\t{\n\t\t\tstrcpy(nameAux,get_basefilename(configCrontrolFile.InitialGuessModel));\n\t\t\tstrcat(nameAux,\"_C_\");\n\t\t\tchar extension[10];\n\t\t\tsprintf(extension, \"%d%s\", number_parametros,\".per\");\n\t\t\tstrcat(nameAux,extension);\n\t\t\tFILE *fptr = fopen(nameAux, \"w\");\n\t\t\t//printf(\"\\n FUNCION RESPUESTA: %d \\n\",number_parametros);\n\t\t\tint kk;\n\t\t\tfor (kk = 0; kk < nlambda; kk++)\n\t\t\t{\n\t\t\tfprintf(fptr,\"1\\t%lf\\t%le\\t%le\\t%le\\t%le\\n\", vLambda[kk],\n\t\t\td_spectra[kk + nlambda * number_parametros],\n\t\t\td_spectra[kk + nlambda * number_parametros + nlambda * NTERMS],\n\t\t\td_spectra[kk + nlambda * number_parametros + nlambda * NTERMS * 2],\n\t\t\td_spectra[kk + nlambda * number_parametros + nlambda * NTERMS * 3]);\n\t\t\t}\n\t\t\tfclose(fptr);\n\t\t}\n\t\tprintf(\"\\n\");*/\n\n\t}\n\telse{ // INVERT PIXEL FROM PER FILE OR IMAGE FROM FITS FILE\n\n\t\tif(strcmp(file_ext(configCrontrolFile.ObservedProfiles),PER_FILE)==0){ // invert only per file\n\t\t\tfloat * spectroPER = calloc(nlambda*NPARMS,sizeof(float));\n\t\t\tFILE * fReadSpectro;\n\t\t\tchar * line = NULL;\n\t\t\tsize_t len = 0;\n\t\t\tssize_t read;\n\t\t\tfReadSpectro = fopen(configCrontrolFile.ObservedProfiles, \"r\");\n\t\t\t\n\t\t\tint contLine=0;\n\t\t\tif (fReadSpectro == NULL)\n\t\t\t{\n\t\t\t\tprintf(\"Error opening the file of parameters, it's possible that the file doesn't exist. Please verify it. \\n\");\n\t\t\t\tprintf(\"\\n ******* THIS IS THE NAME OF THE FILE RECEVIED : %s \\n\", configCrontrolFile.ObservedProfiles);\n\t\t\t\tfclose(fReadSpectro);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\t\n\t\t\tfloat aux1, aux2, aux3, aux4, aux5, aux6;\n\t\t\twhile ((read = getline(&line, &len, fReadSpectro)) != -1) {\n\t\t\t\tsscanf(line,\"%e %e %e %e %e %e\",&aux1,&aux2,&aux3,&aux4,&aux5,&aux6);\n\t\t\t\tif(contLine0){\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nThe program needs to use convolution. Filter PSF activated and macroturbulence greater than zero. \");\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t}\n\t\t\telse if(configCrontrolFile.ConvolveWithPSF){\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nThe program needs to use convolution. Filter PSF activated. \");\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t}\n\t\t\telse if(initModel.mac>0){\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nThe program needs to use convolution. Macroturbulence in initial atmosphere model greater than zero.\");\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t}\n \t\tint numIter =0;\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nNumber of free parameters for inversion: %d\", free_params);\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n \t\tlm_mils(cuantic, wlines, vLambda, nlambda, spectroPER, nlambda, &initModel, spectra, &chisqrf, slight, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,\n configCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise, configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&numIter,configCrontrolFile.mu, configCrontrolFile.logclambda);\n\n\t\t\t// SAVE OUTPUT MODEL \n\t\t\tchar nameAuxOutputModel [4096];\n\n\t\t\tif(configCrontrolFile.ObservedProfiles[0]!='\\0')\n\t\t\t\tstrcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\t\telse\n\t\t\t\tstrcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel));\n\t\t\t\t\t\t\t\n\t\t\tstrcat(nameAuxOutputModel,\"_model\");\n\t\t\tstrcat(nameAuxOutputModel,MOD_FILE);\n\n\t\t\tFILE *fptr = fopen(nameAuxOutputModel, \"w\");\n\t\t\tif(fptr!=NULL){\n\t\t\t\tfprintf(fptr,\"eta_0 :%lf\\n\",initModel.eta0);\n\t\t\t\tfprintf(fptr,\"magnetic field [G] :%lf\\n\",initModel.B);\n\t\t\t\tfprintf(fptr,\"LOS velocity[km/s] :%lf\\n\",initModel.vlos);\n\t\t\t\tfprintf(fptr,\"Doppler width [A] :%lf\\n\",initModel.dopp);\n\t\t\t\tfprintf(fptr,\"damping :%lf\\n\",initModel.aa);\n\t\t\t\tfprintf(fptr,\"gamma [deg] :%lf\\n\",initModel.gm);\n\t\t\t\tfprintf(fptr,\"phi [deg] :%lf\\n\",initModel.az);\n\t\t\t\tfprintf(fptr,\"S_0 :%lf\\n\",initModel.S0);\n\t\t\t\tfprintf(fptr,\"S_1 :%lf\\n\",initModel.S1);\n\t\t\t\tfprintf(fptr,\"v_mac [km/s] :%lf\\n\",initModel.mac);\n\t\t\t\tfprintf(fptr,\"filling factor :%lf\\n\",initModel.alfa);\n\t\t\t\tfprintf(fptr,\"# Iterations :%d\\n\",numIter);\n\t\t\t\tfprintf(fptr,\"chisqr :%le\\n\",chisqrf);\n\t\t\t\tfprintf(fptr,\"\\n\\n\");\n\t\t\t\tfclose(fptr);\n\t\t\t\tprintf(\"\\n\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nINVERTED MODEL SAVED IN FILE: %s\",nameAuxOutputModel);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t}\n\t\t\telse{\n\t\t\t\tprintf(\"\\n ¡¡¡¡¡ ERROR: OUTPUT MODEL FILE CAN NOT BE OPENED\\n !!!!! \");\n\t\t\t}\n\n\n\t\t\t// SAVE OUTPUT ADJUST SYNTHESIS PROFILES \n\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\tchar nameAuxOutputStokes [4096];\n\t\t\t\tif(configCrontrolFile.ObservedProfiles[0]!='\\0')\n\t\t\t\t\tstrcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\t\t\telse\n\t\t\t\t\tstrcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.InitialGuessModel));\t\t\t\t\n\t\t\t\tstrcat(nameAuxOutputStokes,STOKES_PER_EXT);\n\t\t\t\tFILE *fptr = fopen(nameAuxOutputStokes, \"w\");\n\t\t\t\tif(fptr!=NULL){\n\t\t\t //printf(\"\\n valores de spectro sintetizado\\n\");\n\t\t\t\t\tint kk;\n\t\t\t\t\tfor (kk = 0; kk < nlambda; kk++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfprintf(fptr,\"%d\\t%f\\t%e\\t%e\\t%e\\t%e\\n\", indexLine, (vLambda[kk]-configCrontrolFile.CentralWaveLenght)*1000, spectra[kk], spectra[kk + nlambda], spectra[kk + nlambda * 2], spectra[kk + nlambda * 3]);\n\t\t\t\t\t}\n\t\t\t\t\t//printf(\"\\nVALORES DE LAS FUNCIONES RESPUESTA \\n\");\n\t\t\t\t\tfclose(fptr);\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nOutput profiles: %s\",nameAuxOutputStokes);\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tprintf(\"\\n ¡¡¡¡¡ ERROR: OUTPUT SYNTHESIS PROFILE ADJUSTED FILE CAN NOT BE OPENED\\n !!!!! \");\n\t\t\t\t}\n\t\t\t}\n\t\t\tfree(spectroPER);\t\n\t\t}\n\t\telse if(strcmp(file_ext(configCrontrolFile.ObservedProfiles),FITS_FILE)==0){ // invert image from fits file \n\n\t\t\t// check if read stray light\n\t\t\tif(configCrontrolFile.fix[10] && access(configCrontrolFile.StrayLightFile,F_OK)!=-1){ // IF NOT EMPTY READ stray light file \n\t\t\t\tif(strcmp(file_ext(configCrontrolFile.StrayLightFile),PER_FILE)==0){\n\t\t\t\t\tslight = readPerStrayLightFile(configCrontrolFile.StrayLightFile,nlambda,vOffsetsLambda);\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nSTRAY LIGHT FILE READ: %s \", configCrontrolFile.StrayLightFile);\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\telse if(strcmp(file_ext(configCrontrolFile.StrayLightFile),FITS_FILE)==0){\n\t\t\t\t\tslight = readFitsStrayLightFile(&configCrontrolFile,&nl_straylight,&ns_straylight,&nx_straylight, &ny_straylight);\n\t\t\t\t\tif(nl_straylight!=nlambda){\n\t\t\t\t\t\tprintf(\"\\n The number of wavelengths is different in the stray light file: %d and malla grid file %d. \\n. Stray light will not used for inversion.\", nl_straylight,nlambda);\n\t\t\t\t\t\tfree(slight);\n\t\t\t\t\t\tslight= NULL;\n\t\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t\t}\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nSTRAY LIGHT FILE READ: %s\", configCrontrolFile.StrayLightFile);\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tprintf(\"\\n Stray light file hasn't extension .PER or .FITS, review it. \\n. Stray light will not used for inversion.\\n\");\n\t\t\t\t\tfree(slight);\n\t\t\t\t\tslight= NULL;\t\t\t\t\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t\t// READ PIXELS FROM IMAGE \n\t\t\tPRECISION timeReadImage;\n\t\t\tclock_t t;\n\t\t\tt = clock();\n\t\t\tfitsImage = readFitsSpectroImage(nameInputFileSpectra,0,nlambda);\n\t\t\tt = clock() - t;\n\t\t\ttimeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nOBSERVED PROFILES FILE READ: %s\", nameInputFileSpectra);\n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\tprintf(\"\\nTIME TO READ FITS IMAGE: %f seconds to execute \", timeReadImage); \n\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\n\n\t\t\tif(fitsImage!=NULL){\n\t\t\t\tFitsImage * imageStokesAdjust = NULL;\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\timageStokesAdjust = malloc(sizeof(FitsImage));\n\t\t\t\t\timageStokesAdjust->rows = fitsImage->rows;\n\t\t\t\t\timageStokesAdjust->cols = fitsImage->cols;\n\t\t\t\t\timageStokesAdjust->nLambdas = fitsImage->nLambdas;\n\t\t\t\t\timageStokesAdjust->numStokes = fitsImage->numStokes;\n\t\t\t\t\timageStokesAdjust->pos_col = fitsImage->pos_col;\n\t\t\t\t\timageStokesAdjust->pos_row = fitsImage->pos_row;\n\t\t\t\t\timageStokesAdjust->pos_lambda = fitsImage->pos_lambda;\n\t\t\t\t\timageStokesAdjust->pos_stokes_parameters = fitsImage->pos_stokes_parameters;\n\t\t\t\t\timageStokesAdjust->numPixels = fitsImage->numPixels;\n\t\t\t\t\timageStokesAdjust->pixels = calloc(imageStokesAdjust->numPixels, sizeof(vpixels));\n\t\t\t\t\timageStokesAdjust->naxes = fitsImage->naxes;\n\t\t\t\t\timageStokesAdjust->vCard = fitsImage->vCard;\n\t\t\t\t\timageStokesAdjust->vKeyname = fitsImage->vKeyname;\n\t\t\t\t\timageStokesAdjust->nkeys = fitsImage->nkeys;\n\t\t\t\t\timageStokesAdjust->naxis = fitsImage->naxis;\n\t\t\t\t\timageStokesAdjust->bitpix = fitsImage->bitpix;\n\t\t\t\t\tfor( i=0;inumPixels;i++){\n\t\t\t\t\t\timageStokesAdjust->pixels[i].spectro = calloc ((imageStokesAdjust->numStokes*imageStokesAdjust->nLambdas),sizeof(float));\n\t\t\t\t\t}\n\t\t\t\t}\t\t\t\t\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nATMOSPHERE MODEL FILE READ: %s \",configCrontrolFile.InitialGuessModel);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nINITAL MODEL ATMOSPHERE: \\n\\n\");\n\t\t\t\tprintf(\"eta_0 :%lf\\n\",INITIAL_MODEL.eta0);\n\t\t\t\tprintf(\"magnetic field [G] :%lf\\n\",INITIAL_MODEL.B);\n\t\t\t\tprintf(\"LOS velocity[km/s] :%lf\\n\",INITIAL_MODEL.vlos);\n\t\t\t\tprintf(\"Doppler width [A] :%lf\\n\",INITIAL_MODEL.dopp);\n\t\t\t\tprintf(\"damping :%lf\\n\",INITIAL_MODEL.aa);\n\t\t\t\tprintf(\"gamma [deg] :%lf\\n\",INITIAL_MODEL.gm);\n\t\t\t\tprintf(\"phi [deg] :%lf\\n\",INITIAL_MODEL.az);\n\t\t\t\tprintf(\"S_0 :%lf\\n\",INITIAL_MODEL.S0);\n\t\t\t\tprintf(\"S_1 :%lf\\n\",INITIAL_MODEL.S1);\n\t\t\t\tprintf(\"v_mac [km/s] :%lf\\n\",INITIAL_MODEL.mac);\n\t\t\t\tprintf(\"filling factor :%lf\\n\",INITIAL_MODEL.alfa);\n\t\t\t\tprintf(\"--------------------------------------------------------------------------------\\n\");\n\n\t\t\t\tif(configCrontrolFile.ConvolveWithPSF && INITIAL_MODEL.mac>0){\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nThe program needs to use convolution. Filter PSF activated and macroturbulence greater than zero. \");\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\telse if(configCrontrolFile.ConvolveWithPSF){\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nThe program needs to use convolution. Filter PSF activated. \");\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\telse if(INITIAL_MODEL.mac>0){\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\tprintf(\"\\nThe program needs to use convolution. Macroturbulence in initial atmosphere model greater than zero.\");\n\t\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t}\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nNumber of free parameters for inversion: %d\", free_params);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t//***************************************** INIT MEMORY WITH SIZE OF LAMBDA ****************************************************//\n\t\t\t\tAllocateMemoryDerivedSynthesis(nlambda);\n\t\t\t\tint indexPixel = 0;\n\n\t\t\t\t// ALLOCATE MEMORY FOR STORE THE RESULTS \n\n\t\t\t\tvModels = calloc (fitsImage->numPixels , sizeof(Init_Model));\n\t\t\t\tvChisqrf = calloc (fitsImage->numPixels , sizeof(float));\n\t\t\t\tvNumIter = calloc (fitsImage->numPixels , sizeof(int));\n\t\t\t\tt = clock();\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\n----------------------- IMAGE INVERSION IN PROGRESS ----------------------------\");\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\\n\");\n\t\t\t\t\n\n\t\t\t\tfor(indexPixel = 0; indexPixel < fitsImage->numPixels; indexPixel++){\n\n\t\t\t\t\t//Initial Model\n\t\t\t\t\tInit_Model initModel;\n\t\t\t\t\tinitModel.eta0 = INITIAL_MODEL.eta0;\n\t\t\t\t\tinitModel.B = INITIAL_MODEL.B; //200 700\n\t\t\t\t\tinitModel.gm = INITIAL_MODEL.gm;\n\t\t\t\t\tinitModel.az = INITIAL_MODEL.az;\n\t\t\t\t\tinitModel.vlos = INITIAL_MODEL.vlos; //km/s 0\n\t\t\t\t\tinitModel.mac = INITIAL_MODEL.mac;\n\t\t\t\t\tinitModel.dopp = INITIAL_MODEL.dopp;\n\t\t\t\t\tinitModel.aa = INITIAL_MODEL.aa;\n\t\t\t\t\tinitModel.alfa = INITIAL_MODEL.alfa; //0.38; //stray light factor\n\t\t\t\t\tinitModel.S0 = INITIAL_MODEL.S0;\n\t\t\t\t\tinitModel.S1 = INITIAL_MODEL.S1;\n\t\t\t\t\t\n\t\t\t\t\t// CLASSICAL ESTIMATES TO GET B, GAMMA\n\t\t\t\t\testimacionesClasicas(wlines[1], vLambda, nlambda, fitsImage->pixels[indexPixel].spectro, &initModel,1);\n\t\t\t\t\tif (isnan(initModel.B))\n\t\t\t\t\t\tinitModel.B = 1;\n\t\t\t\t\tif (isnan(initModel.vlos))\n\t\t\t\t\t\tinitModel.vlos = 1e-3;\n\t\t\t\t\tif (isnan(initModel.gm))\n\t\t\t\t\t\tinitModel.gm = 1;\t\t\t\t\t\t\n\t\t\t\t\tif (isnan(initModel.az))\n\t\t\t\t\t\tinitModel.az = 1;\n\t\t\t\t\t// INVERSION RTE\n\n\t\t\t\t\tfloat * slightPixel;\n\t\t\t\t\tif(slight==NULL) \n\t\t\t\t\t\tslightPixel = NULL;\n\t\t\t\t\telse{\n\t\t\t\t\t\tif(nx_straylight && ny_straylight){\n\t\t\t\t\t\t\tslightPixel = slight+ (nlambda*NPARMS*indexPixel);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tslightPixel = slight;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tvNumIter[indexPixel] = indexPixel;\n\t\t\t\t\tlm_mils(cuantic, wlines, vLambda, nlambda, fitsImage->pixels[indexPixel].spectro, nlambda, &initModel, spectra, &vChisqrf[indexPixel], slightPixel, configCrontrolFile.toplim, configCrontrolFile.NumberOfCycles,\n\t\t\t\t\t\t\tconfigCrontrolFile.WeightForStokes, configCrontrolFile.fix, vSigma, configCrontrolFile.noise,configCrontrolFile.InitialDiagonalElement,&configCrontrolFile.ConvolveWithPSF,&vNumIter[indexPixel],configCrontrolFile.mu,configCrontrolFile.logclambda);\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\tvModels[indexPixel] = initModel;\n\t\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t\tint kk;\n\t\t\t\t\t\tfor (kk = 0; kk < (nlambda * NPARMS); kk++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\timageStokesAdjust->pixels[indexPixel].spectro[kk] = spectra[kk] ;\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tt = clock() - t;\n\t\t\t\ttimeReadImage = ((PRECISION)t)/CLOCKS_PER_SEC; // in seconds \n\t\t\t\tprintf(\"\\n\\n--------------------------------------------------------------------------------\");\n\t\t\t\tprintf(\"\\nFINISH EXECUTION OF INVERSION: %f seconds to execute \", timeReadImage);\n\t\t\t\tprintf(\"\\n--------------------------------------------------------------------------------\");\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tchar nameAuxOutputModel [4096];\n\t\t\t\tif(configCrontrolFile.ObservedProfiles[0]!='\\0')\n\t\t\t\t\tstrcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\t\t\telse\n\t\t\t\t\tstrcpy(nameAuxOutputModel,get_basefilename(configCrontrolFile.InitialGuessModel));\t\t\t\t\n\n\t\t\t\tstrcat(nameAuxOutputModel,MOD_FITS);\n\t\t\t\tif(!writeFitsImageModels(nameAuxOutputModel,fitsImage->rows,fitsImage->cols,vModels,vChisqrf,vNumIter,configCrontrolFile.saveChisqr)){\n\t\t\t\t\t\tprintf(\"\\n ERROR WRITING FILE OF MODELS: %s\",nameAuxOutputModel);\n\t\t\t\t}\n\t\t\t\t// PROCESS FILE OF SYNTETIC PROFILES\n\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted){\n\t\t\t\t\t// WRITE SINTHETIC PROFILES TO FITS FILE\n\t\t\t\t\tchar nameAuxOutputStokes [4096];\n\t\t\t\t\tif(configCrontrolFile.ObservedProfiles[0]!='\\0')\n\t\t\t\t\t\tstrcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.ObservedProfiles));\n\t\t\t\t\telse\n\t\t\t\t\t\tstrcpy(nameAuxOutputStokes,get_basefilename(configCrontrolFile.InitialGuessModel));\t\t\t\t\t\n\t\t\t\t\tstrcat(nameAuxOutputStokes,STOKES_FIT_EXT);\n\t\t\t\t\tif(!writeFitsImageProfiles(nameAuxOutputStokes,nameInputFileSpectra,imageStokesAdjust)){\n\t\t\t\t\t\tprintf(\"\\n ERROR WRITING FILE OF SINTHETIC PROFILES: %s\",nameOutputFilePerfiles);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(configCrontrolFile.SaveSynthesisAdjusted)\n\t\t\t\t\tfree(imageStokesAdjust);\n\t\t\t\tfree(vModels);\n\t\t\t\tfree(vChisqrf);\n\t\t\t\tfree(vNumIter);\t\t\t\t\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\tprintf(\"\\n\\n ***************************** FITS FILE WITH THE SPECTRO IMAGE CAN NOT BE READ IT ******************************\\n\");\n\t\t\t}\t\t\t\n\n\t\t\tfreeFitsImage(fitsImage);\n\t\t}\n\t\telse{\n\t\t\tprintf(\"\\n OBSERVED PROFILES DOESN'T HAVE CORRECT EXTENSION .PER or .FITS \");\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n\n\tfftw_free(inFilterMAC);\n\tfftw_free(outFilterMAC);\n\tfftw_destroy_plan(planFilterMAC);\n\tfftw_free(inFilterMAC_DERIV);\n\tfftw_free(outFilterMAC_DERIV);\n\tfftw_destroy_plan(planFilterMAC_DERIV);\n\tfftw_free(inSpectraFwMAC);\n\tfftw_free(outSpectraFwMAC);\n\tfftw_destroy_plan(planForwardMAC);\n\tfftw_free(inSpectraBwMAC);\n\tfftw_free(outSpectraBwMAC);\n\tfftw_destroy_plan(planBackwardMAC);\n\n\tif(configCrontrolFile.ConvolveWithPSF){\n\t\tfftw_free(inSpectraFwPSF);\n\t\tfftw_free(outSpectraFwPSF);\n\t\tfftw_destroy_plan(planForwardPSF);\n\t\tfftw_free(inSpectraBwPSF);\n\t\tfftw_free(outSpectraBwPSF);\n\t\tfftw_destroy_plan(planBackwardPSF);\n\n\t\tfftw_free(fftw_G_PSF);\n\t\tfftw_free(fftw_G_MAC_PSF);\n\t\tfftw_free(fftw_G_MAC_DERIV_PSF);\n\n\t\tfftw_free(inPSF_MAC);\n\t\tfftw_free(inMulMacPSF);\n\t\tfftw_free(inPSF_MAC_DERIV);\n\t\tfftw_free(inMulMacPSFDeriv);\n\t\tfftw_free(outConvFilters);\n\t\tfftw_free(outConvFiltersDeriv);\t\n\n\t\tfftw_destroy_plan(planForwardPSF_MAC);\n\t\tfftw_destroy_plan(planForwardPSF_MAC_DERIV);\n\t\tfftw_destroy_plan(planBackwardPSF_MAC);\n\t\tfftw_destroy_plan(planBackwardPSF_MAC_DERIV);\t\t\n\t}\n\n\tfree(cuantic);\n\tfree(wlines);\n\tfree(vSigma);\n\tFreeMemoryDerivedSynthesis();\n\tif(G!=NULL) free(G);\n\tgsl_eigen_symmv_free (workspace);\n\tgsl_vector_free(eval);\n\tgsl_matrix_free(evec);\n\n\treturn 0;\n}\n", "meta": {"hexsha": "0bae2d261a2dd53ef00669b83dc2ffd3a231143a", "size": 50180, "ext": "c", "lang": "C", "max_stars_repo_path": "p-milos/src/milos.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/milos.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/milos.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": 45.2888086643, "max_line_length": 260, "alphanum_fraction": 0.5961538462, "num_tokens": 13495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.34678222165192774}} {"text": "#if !defined(DECAY_H)\n#define DECAY_H\n\n#include \"SM.h\"\n#include \"THDM.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\n/**\n* @brief Calculates the decay modes of 2HDM Higgs bosons\n* \n* Given a THDM object, a DecayTable can be generated. From this table, the\n* Higgs boson decay widths and branching ratios are obtained. For the complete\n* list of available decay modes, we refer to the complete documentation, or\n* the list of member methods below.\n*/\nclass DecayTable {\n\n public: \n \n /**\n * @brief Default constructor\n * \n * This default constructor takes a THDM object as argument for which \n * the decays are to be calculated. %SM properties are taken from the SM\n * object in the THDM.\n * \n * @param mod Two-Higgs doublet model for which to calculate decay modes\n */\n DecayTable(THDM mod);\n\n\n /**\n * @brief Sets underlying 2HDM\n * \n * This method sets the THDM underlying the DecayTable.\n * \n * @param model Two-Higgs doublet model for which to calculate decay modes\n */\n\tvoid set_model(THDM model);\n\n\n /**\n * @brief Underlying 2HDM\n * \n * Use to obtain the underlying THDM object\n * \n * @returns The THDM object on which this DecayTable operates\n */\n\tTHDM get_model(); \n\n\n /**\n * @brief Decay width \\f$\\Gamma(h\\to u_1\\overline{u}_2) \\f$\n * \n * This method calculates the on-shell decay width for the decay of Higgs\n * boson \\a h to a pair of up-type quarks. QCD corrections have been included.\n * \n * @param h Index of Higgs boson (1,2,3 = h,H,A)\n * @param u1 Index of up-type quark (1,2,3 = \\f$ u,c,t \\f$)\n * @param u2 Index of up-type antiquark (1,2,3 = \\f$ \\bar{u},\\bar{c},\\bar{t} \\f$)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_huu(int h, int u1, int u2);\n\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to d_1\\overline{d}_2) \\f$\n * \n * This method calculates the on-shell decay width for the decay of Higgs\n * boson \\a h to a pair of down-type quarks. QCD corrections have been included.\n * \n * @param h Index of Higgs boson (1,2,3 = h,H,A)\n * @param d1 Index of down-type quark (1,2,3 = \\f$ d,s,b \\f$)\n * @param d2 Index of down-type antiquark (1,2,3 = \\f$ \\bar{d},\\bar{s},\\bar{b} \\f$)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_hdd(int h, int d1, int d2);\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to l_1\\overline{l}_2) \\f$\n * \n * This method calculates the on-shell decay width for the decay of Higgs\n * boson \\a h to a pair of charged leptons.\n * \n * @param h Index of Higgs boson (1,2,3 = h,H,A)\n * @param l1 Index of lepton (1,2,3 = \\f$ e,\\mu,\\tau \\f$)\n * @param l2 Index of antilepton (1,2,3 = \\f$ \\bar{e},\\bar{\\mu},\\bar{\\tau} \\f$)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_hll(int h, int l1, int l2);\n\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to u\\overline{d}) \\f$\n * \n * This method calculates the on-shell decay width for the decay of Higgs\n * boson \\a h to a pair of quarks. QCD corrections have been included.\n * \n * @param h Index of Higgs boson (4 = H+)\n * @param d Index of down-type antiquark (1,2,3 = \\f$ \\bar{d},\\bar{s},\\bar{b} \\f$)\n * @param u Index of up-type quark (1,2,3 = \\f$ u,c,t \\f$)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_hdu(int h, int d, int u);\n\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to l\\overline{\\nu}_{l'}) \\f$\n * \n * This method calculates the on-shell decay width for the decay of Higgs\n * boson \\a h to lepton-neutrino.\n * \n * @param h Index of Higgs boson (4 = H+)\n * @param l Index of charged lepton (1,2,3 = \\f$ e^+,\\mu^+,\\tau^+ \\f$)\n * @param n Index of neutrino (1,2,3 = \\f$ \\nu_e,\\nu_\\mu,\\nu_\\tau \\f$)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_hln(int h, int l, int n); \n \n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to H_1 H_2) \\f$\n * \n * This method calculates the on-shell decay width for the decay of Higgs\n * boson \\a h to a pair of Higgs bosons\n * \n * @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)\n * @param h1 Index of first Higgs boson (1,2,3,4 = h,H,A,H+)\n * @param h2 Index of second Higgs boson (1,2,3,4 = h,H,A,H+)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_hhh(int h, int h1, int h2);\n\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to VV) \\f$\n * \n * This method calculates the decay width for the Higgs boson \\a h \n * to a pair of vector bosons. The decay mode with one vector\n * boson off-shell is included.\n * \n * @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)\n * @param v Index of vector bosons (1,2,3 = \\f$\\gamma \\f$,Z,W)\n * \n * @returns The decay width in GeV\n */\n double get_gamma_hvv(int h, int v);\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to VH) \\f$\n * \n * This method calculates the decay width for the Higgs boson \\a h \n * to one massive vector and one Higgs boson. Decay with the vector\n * boson off-shell is included.\n * \n * @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)\n * @param V Index of vector boson (2,3 = \\f$\\gamma \\f$,Z,W)\n * @param H Index of final-state Higgs boson (1,2,3,4 = h,H,A,H+)\n\t*\n * @returns The decay width in GeV\n */\n double get_gamma_hvh(int H, int V, int h);\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to gg) \\f$\n * \n * This method calculates the decay width for the Higgs boson \\a h \n * to a pair of gluons. LO QCD corrections are included.\n * \n * @param h Index of decaying Higgs boson (1,2,3,4 = h,H,A,H+)\n\t*\n * @returns The decay width in GeV\n */\n double get_gamma_hgg(int h);\n\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to \\gamma\\gamma) \\f$\n * \n * This method calculates the decay width for the neutral\n * Higgs boson \\a h to a pair of photons.\n * \n * @param h Index of decaying Higgs boson (1,2,3 = h,H,A)\n\t*\n * @returns The decay width in GeV\n */\n\tdouble get_gamma_hgaga(int h);\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to Z\\gamma) \\f$\n * \n * This method calculates the decay width for the neutral\n * Higgs boson \\a h to a Z and a photon.\n * \n * @param h Index of decaying Higgs boson (1,2,3 = h,H,A)\n\t*\n * @returns The decay width in GeV\n */\n\tdouble get_gamma_hZga(int h);\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to WZ) \\f$\n * \n * This method calculates the decay width for the neutral\n * Higgs boson \\a h to a Z and a photon.\n * \n * @param h Index of decaying Higgs boson (4 = H+-)\n *\n * @returns The decay width in GeV\n */\n double get_gamma_hWZ(int h);\n\n /**\n * @brief Decay width \\f$ \\Gamma(h\\to W\\gamma) \\f$\n * \n * This method calculates the decay width for the neutral\n * Higgs boson \\a h to a Z and a photon.\n * \n * @param h Index of decaying Higgs boson (4 = H+-)\n *\n * @returns The decay width in GeV\n */\n double get_gamma_hWga(int h);\n\n /**\n * @brief Total width \\f$ \\Gamma_h \\f$\n * \n * Calculates the total decay width of Higgs boson \\a h \n * \n * @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n\t*\n * @returns Total width in GeV\n */\n double get_gammatot_h(int h);\n\n /**\n * @brief Total width \\f$ \\Gamma_V \\f$\n * \n * Returns the total decay width of vector boson \\a v \n * \n * @param v Index of vector boson (2,3 = Z,W)\n\t*\n * @returns Total width in GeV\n */\n double get_gammatot_v(int v);\n\n /**\n * @brief Total width \\f$ \\Gamma_t \\f$\n * \n * Returns the total decay width of the top quark \n * \n * @returns Total width in GeV\n */\n double get_gammatot_top();\n\n\n /**\n * @brief Decay width for \\f$ t \\to H^+X \\f$\n * \n * Returns the decay width of the top quark in the charged Higgs mode\n * \n * @returns Decay width in GeV\n * \n * @param u Index of decaying quark (1,2,3 = \\f$ u,c,t \\f$)\n * @param h Index of Higgs boson (4 = H+)\n\t* @param d Index of down-type quark (1,2,3 = \\f$ d,s,b \\f$)\n */\n double get_gamma_uhd(int u, int h, int d);\n\n\n double get_gamma_uhu(int u1, int h, int u2);\n\n \n /**\n *\t@brief Prints the decay modes of a Higgs boson\n *\n * The decay modes of Higgs boson \\a h are printed to stdout\n * \n * @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n */\n void print_decays(int h);\n\n /**\n *\t@brief Prints the total width of a Higgs boson\n *\n * The total decay width of Higgs boson \\a h are printed to stdout\n * \n * @param h Index of Higgs boson (1,2,3,4 = h,H,A,H+)\n */\n void print_width(int h);\n\n /**\n *\t@brief Prints the decay modes of the top quark\n *\n * The decay modes of the top quark are printed to stdout\n */\n void print_top_decays();\n\n /**\n *\t@brief Prints decay information for a Higgs boson in LesHouches format\n *\n * The decay information for Higgs boson \\a h are printed to a file in\n * LesHouches format\n *\n * @param output The name of the output file to write\n * @param h \t\t\tIndex of Higgs boson (1,2,3,4 = h,H,A,H+)\n * @param full \tIf \\a true, all decay modes are printed, if \\a false only the total width\n */\n void print_decays_LesHouches(FILE* output, int h, bool full);\n\n /**\n *\t@brief Prints decay information for the top quark in LesHouches format\n *\n * The decay information for the top quark are printed to a file in\n * LesHouches format\n *\n * @param output The name of the output file to write\n * @param full \tIf \\a true, all decay modes are printed, if \\a false only the total width\n */\n void print_top_decays_LesHouches(FILE* output, bool full);\n\n /**\n * @brief Turns QCD corrections on or off\n *\n * This method is used to turn QCD corrections on or off. If the output is \n * meant to be used with the MadGraph/MadEvent 2HDMC model \n * QCD corrections should be turned off to get a consistent result. \n *\n * @param set If \\a true QCD corrections are turned on, \n * if \\a false QCD corrections are turned off\n */\n void set_qcd(bool set);\n\n static double DHp(double ui, double uj, double xi, double xj, double sqL);\n static double DHm(double ui, double uj, double xi, double xj, double sqL);\n static double BHp(double ui, double uj, double xi, double xj, double sqL);\n\n\n private:\n THDM model;\n SM sm;\n \n complex F_sf(double t);\n complex F_pf(double t);\n complex F_0(double t);\n complex F_1(double t);\n complex ftau(double t);\n complex gtau(double t);\n complex I_1(double tau, double lambda);\n complex I_2(double tau, double lambda);\n complex FF_s(double tau, double lambda);\n complex FF_p(double tau, double lambda);\n complex FW(double tau, double lambda);\n complex FHp(double tau, double lambda);\n\n double gammatot_h[5];\n double gamma_uhd[5][5][5];\n double gamma_uhu[5][5][5];\n double gamma_hdd[5][5][5];\n double gamma_huu[5][5][5];\n double gamma_hdu[5][5][5];\n double gamma_hll[5][5][5];\n double gamma_hln[5][5][5];\n double gamma_hgg[5];\n double gamma_hgaga[5];\n double gamma_hZga[5];\n double gamma_hWga[5]; // For H+- only\n double gamma_hWZ[5]; // For H+- only\n double gamma_hvv[5][5];\n double gamma_hvh[5][5][5];\n double gamma_hhh[5][5][5];\n\n double br(double dG, double G);\n\n double hvv_onshell(int h, int V, double M);\n double hvv_offshell(int h, int V, double M);\n double hvv_all(int h, int V, double M);\n double hff_onshell(double M, double m1, double m1run, double m2, double m2run, complex cs, complex cp, int Nc, int h, bool tt);\n double hpff_onshell(double M, double m1, double m1run, double m2, double m2run, complex cs, complex cp, int Nc, int h);\n double htt_onshell(double M, double m1, double m2, int Nc, int h);\n double htt_offshell(double M, double m1, double m2, int Nc, int h);\n double htb_offshell(double M, double m1, double m1run, double m2, double m2run, complex cs, complex cp, int Nc);\n\n double hvh_onshell(int H, int V, int h, double M);\n double hvh_offshell(int H, int V, int h, double M);\n double hdu_offshell(int h, int d, int u, double M);\n double hgaga(int h);\n double hZga(int h);\n double hWga(int h);\n double hWZ(int h);\n double hgg(int h);\n double PS2(double M, double m1, double m2);\n double LAM(double m12, double m22, double m32);\n \n double interp(double R, double x, double y, double c);\n\n bool qcd_on;\n int err_code;\n\n void print_decay_LesHouches(FILE* output, double br, int id1, int id2);\n void print_decay(const char *h, const char *id1, const char *id2, double g, double br);\n void print_decays(FILE* output, int h, bool full, bool lh);\n\n\n\n};\n\n#endif\n", "meta": {"hexsha": "190d626ad1d7e028bbe0c73eb95d4ff1dcb55687", "size": 12460, "ext": "h", "lang": "C", "max_stars_repo_path": "src/DecayTable.h", "max_stars_repo_name": "ycwu1030/2HDMC-NLO", "max_stars_repo_head_hexsha": "2202e80479749b521a384f68aee27611b323dc74", "max_stars_repo_licenses": ["MIT"], "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/DecayTable.h", "max_issues_repo_name": "ycwu1030/2HDMC-NLO", "max_issues_repo_head_hexsha": "2202e80479749b521a384f68aee27611b323dc74", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DecayTable.h", "max_forks_repo_name": "ycwu1030/2HDMC-NLO", "max_forks_repo_head_hexsha": "2202e80479749b521a384f68aee27611b323dc74", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-27T14:59:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-27T14:59:29.000Z", "avg_line_length": 29.7374701671, "max_line_length": 146, "alphanum_fraction": 0.641011236, "num_tokens": 4235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7520125737597972, "lm_q2_score": 0.46101677931231594, "lm_q1q2_score": 0.34669041475710716}} {"text": "/*\n * Copyright (c) 1997-1999 Massachusetts Institute of Technology\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\n */\n\n/* This file was automatically generated --- DO NOT EDIT */\n/* Generated on Mon Mar 8 17:45:11 EST 1999 */\n\n#include \n#include \n\n/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -notwiddleinv 32 */\n\n/*\n * This function contains 372 FP additions, 84 FP multiplications,\n * (or, 340 additions, 52 multiplications, 32 fused multiply/add),\n * 92 stack variables, and 128 memory accesses\n */\nstatic const fftw_real K195090322 = FFTW_KONST(+0.195090322016128267848284868477022240927691618);\nstatic const fftw_real K980785280 = FFTW_KONST(+0.980785280403230449126182236134239036973933731);\nstatic const fftw_real K831469612 = FFTW_KONST(+0.831469612302545237078788377617905756738560812);\nstatic const fftw_real K555570233 = FFTW_KONST(+0.555570233019602224742830813948532874374937191);\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.36 1999/02/19 17:22:11 athena Exp $\n * $Id: fft.ml,v 1.41 1999/02/19 17:22:13 athena Exp $\n * $Id: to_c.ml,v 1.24 1999/02/19 17:22:17 athena Exp $\n */\n\nvoid fftwi_no_twiddle_32(const fftw_complex *input, fftw_complex *output, int istride, int ostride)\n{\n fftw_real tmp7;\n fftw_real tmp339;\n fftw_real tmp70;\n fftw_real tmp313;\n fftw_real tmp97;\n fftw_real tmp215;\n fftw_real tmp179;\n fftw_real tmp241;\n fftw_real tmp14;\n fftw_real tmp314;\n fftw_real tmp77;\n fftw_real tmp340;\n fftw_real tmp182;\n fftw_real tmp216;\n fftw_real tmp104;\n fftw_real tmp242;\n fftw_real tmp153;\n fftw_real tmp236;\n fftw_real tmp53;\n fftw_real tmp60;\n fftw_real tmp287;\n fftw_real tmp336;\n fftw_real tmp360;\n fftw_real tmp290;\n fftw_real tmp293;\n fftw_real tmp294;\n fftw_real tmp170;\n fftw_real tmp233;\n fftw_real tmp333;\n fftw_real tmp359;\n fftw_real tmp164;\n fftw_real tmp234;\n fftw_real tmp173;\n fftw_real tmp237;\n fftw_real tmp22;\n fftw_real tmp318;\n fftw_real tmp343;\n fftw_real tmp85;\n fftw_real tmp112;\n fftw_real tmp185;\n fftw_real tmp220;\n fftw_real tmp245;\n fftw_real tmp29;\n fftw_real tmp321;\n fftw_real tmp342;\n fftw_real tmp92;\n fftw_real tmp119;\n fftw_real tmp184;\n fftw_real tmp223;\n fftw_real tmp244;\n fftw_real tmp126;\n fftw_real tmp229;\n fftw_real tmp38;\n fftw_real tmp45;\n fftw_real tmp278;\n fftw_real tmp329;\n fftw_real tmp357;\n fftw_real tmp281;\n fftw_real tmp284;\n fftw_real tmp285;\n fftw_real tmp143;\n fftw_real tmp226;\n fftw_real tmp326;\n fftw_real tmp356;\n fftw_real tmp137;\n fftw_real tmp227;\n fftw_real tmp146;\n fftw_real tmp230;\n ASSERT_ALIGNED_DOUBLE();\n {\n\t fftw_real tmp3;\n\t fftw_real tmp177;\n\t fftw_real tmp66;\n\t fftw_real tmp96;\n\t fftw_real tmp6;\n\t fftw_real tmp95;\n\t fftw_real tmp69;\n\t fftw_real tmp178;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp1;\n\t fftw_real tmp2;\n\t fftw_real tmp64;\n\t fftw_real tmp65;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp1 = c_re(input[0]);\n\t tmp2 = c_re(input[16 * istride]);\n\t tmp3 = tmp1 + tmp2;\n\t tmp177 = tmp1 - tmp2;\n\t tmp64 = c_im(input[0]);\n\t tmp65 = c_im(input[16 * istride]);\n\t tmp66 = tmp64 + tmp65;\n\t tmp96 = tmp64 - tmp65;\n\t }\n\t {\n\t fftw_real tmp4;\n\t fftw_real tmp5;\n\t fftw_real tmp67;\n\t fftw_real tmp68;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp4 = c_re(input[8 * istride]);\n\t tmp5 = c_re(input[24 * istride]);\n\t tmp6 = tmp4 + tmp5;\n\t tmp95 = tmp4 - tmp5;\n\t tmp67 = c_im(input[8 * istride]);\n\t tmp68 = c_im(input[24 * istride]);\n\t tmp69 = tmp67 + tmp68;\n\t tmp178 = tmp67 - tmp68;\n\t }\n\t tmp7 = tmp3 + tmp6;\n\t tmp339 = tmp3 - tmp6;\n\t tmp70 = tmp66 + tmp69;\n\t tmp313 = tmp66 - tmp69;\n\t tmp97 = tmp95 + tmp96;\n\t tmp215 = tmp96 - tmp95;\n\t tmp179 = tmp177 - tmp178;\n\t tmp241 = tmp177 + tmp178;\n }\n {\n\t fftw_real tmp10;\n\t fftw_real tmp98;\n\t fftw_real tmp73;\n\t fftw_real tmp99;\n\t fftw_real tmp13;\n\t fftw_real tmp102;\n\t fftw_real tmp76;\n\t fftw_real tmp101;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp8;\n\t fftw_real tmp9;\n\t fftw_real tmp71;\n\t fftw_real tmp72;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp8 = c_re(input[4 * istride]);\n\t tmp9 = c_re(input[20 * istride]);\n\t tmp10 = tmp8 + tmp9;\n\t tmp98 = tmp8 - tmp9;\n\t tmp71 = c_im(input[4 * istride]);\n\t tmp72 = c_im(input[20 * istride]);\n\t tmp73 = tmp71 + tmp72;\n\t tmp99 = tmp71 - tmp72;\n\t }\n\t {\n\t fftw_real tmp11;\n\t fftw_real tmp12;\n\t fftw_real tmp74;\n\t fftw_real tmp75;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp11 = c_re(input[28 * istride]);\n\t tmp12 = c_re(input[12 * istride]);\n\t tmp13 = tmp11 + tmp12;\n\t tmp102 = tmp11 - tmp12;\n\t tmp74 = c_im(input[28 * istride]);\n\t tmp75 = c_im(input[12 * istride]);\n\t tmp76 = tmp74 + tmp75;\n\t tmp101 = tmp74 - tmp75;\n\t }\n\t tmp14 = tmp10 + tmp13;\n\t tmp314 = tmp10 - tmp13;\n\t tmp77 = tmp73 + tmp76;\n\t tmp340 = tmp76 - tmp73;\n\t {\n\t fftw_real tmp180;\n\t fftw_real tmp181;\n\t fftw_real tmp100;\n\t fftw_real tmp103;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp180 = tmp98 - tmp99;\n\t tmp181 = tmp102 + tmp101;\n\t tmp182 = K707106781 * (tmp180 + tmp181);\n\t tmp216 = K707106781 * (tmp180 - tmp181);\n\t tmp100 = tmp98 + tmp99;\n\t tmp103 = tmp101 - tmp102;\n\t tmp104 = K707106781 * (tmp100 + tmp103);\n\t tmp242 = K707106781 * (tmp103 - tmp100);\n\t }\n }\n {\n\t fftw_real tmp49;\n\t fftw_real tmp149;\n\t fftw_real tmp169;\n\t fftw_real tmp288;\n\t fftw_real tmp52;\n\t fftw_real tmp166;\n\t fftw_real tmp152;\n\t fftw_real tmp289;\n\t fftw_real tmp56;\n\t fftw_real tmp154;\n\t fftw_real tmp157;\n\t fftw_real tmp291;\n\t fftw_real tmp59;\n\t fftw_real tmp159;\n\t fftw_real tmp162;\n\t fftw_real tmp292;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp47;\n\t fftw_real tmp48;\n\t fftw_real tmp167;\n\t fftw_real tmp168;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp47 = c_re(input[31 * istride]);\n\t tmp48 = c_re(input[15 * istride]);\n\t tmp49 = tmp47 + tmp48;\n\t tmp149 = tmp47 - tmp48;\n\t tmp167 = c_im(input[31 * istride]);\n\t tmp168 = c_im(input[15 * istride]);\n\t tmp169 = tmp167 - tmp168;\n\t tmp288 = tmp167 + tmp168;\n\t }\n\t {\n\t fftw_real tmp50;\n\t fftw_real tmp51;\n\t fftw_real tmp150;\n\t fftw_real tmp151;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp50 = c_re(input[7 * istride]);\n\t tmp51 = c_re(input[23 * istride]);\n\t tmp52 = tmp50 + tmp51;\n\t tmp166 = tmp50 - tmp51;\n\t tmp150 = c_im(input[7 * istride]);\n\t tmp151 = c_im(input[23 * istride]);\n\t tmp152 = tmp150 - tmp151;\n\t tmp289 = tmp150 + tmp151;\n\t }\n\t {\n\t fftw_real tmp54;\n\t fftw_real tmp55;\n\t fftw_real tmp155;\n\t fftw_real tmp156;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp54 = c_re(input[3 * istride]);\n\t tmp55 = c_re(input[19 * istride]);\n\t tmp56 = tmp54 + tmp55;\n\t tmp154 = tmp54 - tmp55;\n\t tmp155 = c_im(input[3 * istride]);\n\t tmp156 = c_im(input[19 * istride]);\n\t tmp157 = tmp155 - tmp156;\n\t tmp291 = tmp155 + tmp156;\n\t }\n\t {\n\t fftw_real tmp57;\n\t fftw_real tmp58;\n\t fftw_real tmp160;\n\t fftw_real tmp161;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp57 = c_re(input[27 * istride]);\n\t tmp58 = c_re(input[11 * istride]);\n\t tmp59 = tmp57 + tmp58;\n\t tmp159 = tmp57 - tmp58;\n\t tmp160 = c_im(input[27 * istride]);\n\t tmp161 = c_im(input[11 * istride]);\n\t tmp162 = tmp160 - tmp161;\n\t tmp292 = tmp160 + tmp161;\n\t }\n\t {\n\t fftw_real tmp334;\n\t fftw_real tmp335;\n\t fftw_real tmp331;\n\t fftw_real tmp332;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp153 = tmp149 - tmp152;\n\t tmp236 = tmp149 + tmp152;\n\t tmp53 = tmp49 + tmp52;\n\t tmp60 = tmp56 + tmp59;\n\t tmp287 = tmp53 - tmp60;\n\t tmp334 = tmp49 - tmp52;\n\t tmp335 = tmp292 - tmp291;\n\t tmp336 = tmp334 - tmp335;\n\t tmp360 = tmp334 + tmp335;\n\t tmp290 = tmp288 + tmp289;\n\t tmp293 = tmp291 + tmp292;\n\t tmp294 = tmp290 - tmp293;\n\t tmp170 = tmp166 + tmp169;\n\t tmp233 = tmp169 - tmp166;\n\t tmp331 = tmp288 - tmp289;\n\t tmp332 = tmp56 - tmp59;\n\t tmp333 = tmp331 - tmp332;\n\t tmp359 = tmp332 + tmp331;\n\t {\n\t\t fftw_real tmp158;\n\t\t fftw_real tmp163;\n\t\t fftw_real tmp171;\n\t\t fftw_real tmp172;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp158 = tmp154 - tmp157;\n\t\t tmp163 = tmp159 + tmp162;\n\t\t tmp164 = K707106781 * (tmp158 + tmp163);\n\t\t tmp234 = K707106781 * (tmp158 - tmp163);\n\t\t tmp171 = tmp154 + tmp157;\n\t\t tmp172 = tmp162 - tmp159;\n\t\t tmp173 = K707106781 * (tmp171 + tmp172);\n\t\t tmp237 = K707106781 * (tmp172 - tmp171);\n\t }\n\t }\n }\n {\n\t fftw_real tmp18;\n\t fftw_real tmp106;\n\t fftw_real tmp81;\n\t fftw_real tmp110;\n\t fftw_real tmp21;\n\t fftw_real tmp109;\n\t fftw_real tmp84;\n\t fftw_real tmp107;\n\t fftw_real tmp316;\n\t fftw_real tmp317;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp16;\n\t fftw_real tmp17;\n\t fftw_real tmp79;\n\t fftw_real tmp80;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp16 = c_re(input[2 * istride]);\n\t tmp17 = c_re(input[18 * istride]);\n\t tmp18 = tmp16 + tmp17;\n\t tmp106 = tmp16 - tmp17;\n\t tmp79 = c_im(input[2 * istride]);\n\t tmp80 = c_im(input[18 * istride]);\n\t tmp81 = tmp79 + tmp80;\n\t tmp110 = tmp79 - tmp80;\n\t }\n\t {\n\t fftw_real tmp19;\n\t fftw_real tmp20;\n\t fftw_real tmp82;\n\t fftw_real tmp83;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp19 = c_re(input[10 * istride]);\n\t tmp20 = c_re(input[26 * istride]);\n\t tmp21 = tmp19 + tmp20;\n\t tmp109 = tmp19 - tmp20;\n\t tmp82 = c_im(input[10 * istride]);\n\t tmp83 = c_im(input[26 * istride]);\n\t tmp84 = tmp82 + tmp83;\n\t tmp107 = tmp82 - tmp83;\n\t }\n\t tmp22 = tmp18 + tmp21;\n\t tmp316 = tmp18 - tmp21;\n\t tmp317 = tmp81 - tmp84;\n\t tmp318 = tmp316 - tmp317;\n\t tmp343 = tmp316 + tmp317;\n\t tmp85 = tmp81 + tmp84;\n\t {\n\t fftw_real tmp108;\n\t fftw_real tmp111;\n\t fftw_real tmp218;\n\t fftw_real tmp219;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp108 = tmp106 - tmp107;\n\t tmp111 = tmp109 + tmp110;\n\t tmp112 = (K923879532 * tmp108) - (K382683432 * tmp111);\n\t tmp185 = (K923879532 * tmp111) + (K382683432 * tmp108);\n\t tmp218 = tmp106 + tmp107;\n\t tmp219 = tmp110 - tmp109;\n\t tmp220 = (K382683432 * tmp218) - (K923879532 * tmp219);\n\t tmp245 = (K382683432 * tmp219) + (K923879532 * tmp218);\n\t }\n }\n {\n\t fftw_real tmp25;\n\t fftw_real tmp116;\n\t fftw_real tmp88;\n\t fftw_real tmp114;\n\t fftw_real tmp28;\n\t fftw_real tmp113;\n\t fftw_real tmp91;\n\t fftw_real tmp117;\n\t fftw_real tmp319;\n\t fftw_real tmp320;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp23;\n\t fftw_real tmp24;\n\t fftw_real tmp86;\n\t fftw_real tmp87;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp23 = c_re(input[30 * istride]);\n\t tmp24 = c_re(input[14 * istride]);\n\t tmp25 = tmp23 + tmp24;\n\t tmp116 = tmp23 - tmp24;\n\t tmp86 = c_im(input[30 * istride]);\n\t tmp87 = c_im(input[14 * istride]);\n\t tmp88 = tmp86 + tmp87;\n\t tmp114 = tmp86 - tmp87;\n\t }\n\t {\n\t fftw_real tmp26;\n\t fftw_real tmp27;\n\t fftw_real tmp89;\n\t fftw_real tmp90;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp26 = c_re(input[6 * istride]);\n\t tmp27 = c_re(input[22 * istride]);\n\t tmp28 = tmp26 + tmp27;\n\t tmp113 = tmp26 - tmp27;\n\t tmp89 = c_im(input[6 * istride]);\n\t tmp90 = c_im(input[22 * istride]);\n\t tmp91 = tmp89 + tmp90;\n\t tmp117 = tmp89 - tmp90;\n\t }\n\t tmp29 = tmp25 + tmp28;\n\t tmp319 = tmp25 - tmp28;\n\t tmp320 = tmp88 - tmp91;\n\t tmp321 = tmp319 + tmp320;\n\t tmp342 = tmp320 - tmp319;\n\t tmp92 = tmp88 + tmp91;\n\t {\n\t fftw_real tmp115;\n\t fftw_real tmp118;\n\t fftw_real tmp221;\n\t fftw_real tmp222;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp115 = tmp113 + tmp114;\n\t tmp118 = tmp116 - tmp117;\n\t tmp119 = (K382683432 * tmp115) + (K923879532 * tmp118);\n\t tmp184 = (K923879532 * tmp115) - (K382683432 * tmp118);\n\t tmp221 = tmp114 - tmp113;\n\t tmp222 = tmp116 + tmp117;\n\t tmp223 = (K923879532 * tmp221) + (K382683432 * tmp222);\n\t tmp244 = (K382683432 * tmp221) - (K923879532 * tmp222);\n\t }\n }\n {\n\t fftw_real tmp34;\n\t fftw_real tmp122;\n\t fftw_real tmp142;\n\t fftw_real tmp279;\n\t fftw_real tmp37;\n\t fftw_real tmp139;\n\t fftw_real tmp125;\n\t fftw_real tmp280;\n\t fftw_real tmp41;\n\t fftw_real tmp127;\n\t fftw_real tmp130;\n\t fftw_real tmp282;\n\t fftw_real tmp44;\n\t fftw_real tmp132;\n\t fftw_real tmp135;\n\t fftw_real tmp283;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp32;\n\t fftw_real tmp33;\n\t fftw_real tmp140;\n\t fftw_real tmp141;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp32 = c_re(input[istride]);\n\t tmp33 = c_re(input[17 * istride]);\n\t tmp34 = tmp32 + tmp33;\n\t tmp122 = tmp32 - tmp33;\n\t tmp140 = c_im(input[istride]);\n\t tmp141 = c_im(input[17 * istride]);\n\t tmp142 = tmp140 - tmp141;\n\t tmp279 = tmp140 + tmp141;\n\t }\n\t {\n\t fftw_real tmp35;\n\t fftw_real tmp36;\n\t fftw_real tmp123;\n\t fftw_real tmp124;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp35 = c_re(input[9 * istride]);\n\t tmp36 = c_re(input[25 * istride]);\n\t tmp37 = tmp35 + tmp36;\n\t tmp139 = tmp35 - tmp36;\n\t tmp123 = c_im(input[9 * istride]);\n\t tmp124 = c_im(input[25 * istride]);\n\t tmp125 = tmp123 - tmp124;\n\t tmp280 = tmp123 + tmp124;\n\t }\n\t {\n\t fftw_real tmp39;\n\t fftw_real tmp40;\n\t fftw_real tmp128;\n\t fftw_real tmp129;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp39 = c_re(input[5 * istride]);\n\t tmp40 = c_re(input[21 * istride]);\n\t tmp41 = tmp39 + tmp40;\n\t tmp127 = tmp39 - tmp40;\n\t tmp128 = c_im(input[5 * istride]);\n\t tmp129 = c_im(input[21 * istride]);\n\t tmp130 = tmp128 - tmp129;\n\t tmp282 = tmp128 + tmp129;\n\t }\n\t {\n\t fftw_real tmp42;\n\t fftw_real tmp43;\n\t fftw_real tmp133;\n\t fftw_real tmp134;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp42 = c_re(input[29 * istride]);\n\t tmp43 = c_re(input[13 * istride]);\n\t tmp44 = tmp42 + tmp43;\n\t tmp132 = tmp42 - tmp43;\n\t tmp133 = c_im(input[29 * istride]);\n\t tmp134 = c_im(input[13 * istride]);\n\t tmp135 = tmp133 - tmp134;\n\t tmp283 = tmp133 + tmp134;\n\t }\n\t {\n\t fftw_real tmp327;\n\t fftw_real tmp328;\n\t fftw_real tmp324;\n\t fftw_real tmp325;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp126 = tmp122 - tmp125;\n\t tmp229 = tmp122 + tmp125;\n\t tmp38 = tmp34 + tmp37;\n\t tmp45 = tmp41 + tmp44;\n\t tmp278 = tmp38 - tmp45;\n\t tmp327 = tmp34 - tmp37;\n\t tmp328 = tmp283 - tmp282;\n\t tmp329 = tmp327 - tmp328;\n\t tmp357 = tmp327 + tmp328;\n\t tmp281 = tmp279 + tmp280;\n\t tmp284 = tmp282 + tmp283;\n\t tmp285 = tmp281 - tmp284;\n\t tmp143 = tmp139 + tmp142;\n\t tmp226 = tmp142 - tmp139;\n\t tmp324 = tmp279 - tmp280;\n\t tmp325 = tmp41 - tmp44;\n\t tmp326 = tmp324 - tmp325;\n\t tmp356 = tmp325 + tmp324;\n\t {\n\t\t fftw_real tmp131;\n\t\t fftw_real tmp136;\n\t\t fftw_real tmp144;\n\t\t fftw_real tmp145;\n\t\t ASSERT_ALIGNED_DOUBLE();\n\t\t tmp131 = tmp127 - tmp130;\n\t\t tmp136 = tmp132 + tmp135;\n\t\t tmp137 = K707106781 * (tmp131 + tmp136);\n\t\t tmp227 = K707106781 * (tmp131 - tmp136);\n\t\t tmp144 = tmp127 + tmp130;\n\t\t tmp145 = tmp135 - tmp132;\n\t\t tmp146 = K707106781 * (tmp144 + tmp145);\n\t\t tmp230 = K707106781 * (tmp145 - tmp144);\n\t }\n\t }\n }\n {\n\t fftw_real tmp277;\n\t fftw_real tmp301;\n\t fftw_real tmp304;\n\t fftw_real tmp306;\n\t fftw_real tmp296;\n\t fftw_real tmp300;\n\t fftw_real tmp299;\n\t fftw_real tmp305;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp275;\n\t fftw_real tmp276;\n\t fftw_real tmp302;\n\t fftw_real tmp303;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp275 = tmp70 - tmp77;\n\t tmp276 = tmp22 - tmp29;\n\t tmp277 = tmp275 - tmp276;\n\t tmp301 = tmp276 + tmp275;\n\t tmp302 = tmp278 + tmp285;\n\t tmp303 = tmp294 - tmp287;\n\t tmp304 = K707106781 * (tmp302 + tmp303);\n\t tmp306 = K707106781 * (tmp303 - tmp302);\n\t }\n\t {\n\t fftw_real tmp286;\n\t fftw_real tmp295;\n\t fftw_real tmp297;\n\t fftw_real tmp298;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp286 = tmp278 - tmp285;\n\t tmp295 = tmp287 + tmp294;\n\t tmp296 = K707106781 * (tmp286 - tmp295);\n\t tmp300 = K707106781 * (tmp286 + tmp295);\n\t tmp297 = tmp7 - tmp14;\n\t tmp298 = tmp92 - tmp85;\n\t tmp299 = tmp297 + tmp298;\n\t tmp305 = tmp297 - tmp298;\n\t }\n\t c_im(output[28 * ostride]) = tmp277 - tmp296;\n\t c_im(output[12 * ostride]) = tmp277 + tmp296;\n\t c_re(output[20 * ostride]) = tmp299 - tmp300;\n\t c_re(output[4 * ostride]) = tmp299 + tmp300;\n\t c_im(output[20 * ostride]) = tmp301 - tmp304;\n\t c_im(output[4 * ostride]) = tmp301 + tmp304;\n\t c_re(output[28 * ostride]) = tmp305 - tmp306;\n\t c_re(output[12 * ostride]) = tmp305 + tmp306;\n }\n {\n\t fftw_real tmp31;\n\t fftw_real tmp311;\n\t fftw_real tmp310;\n\t fftw_real tmp312;\n\t fftw_real tmp62;\n\t fftw_real tmp63;\n\t fftw_real tmp94;\n\t fftw_real tmp307;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp15;\n\t fftw_real tmp30;\n\t fftw_real tmp308;\n\t fftw_real tmp309;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp15 = tmp7 + tmp14;\n\t tmp30 = tmp22 + tmp29;\n\t tmp31 = tmp15 + tmp30;\n\t tmp311 = tmp15 - tmp30;\n\t tmp308 = tmp281 + tmp284;\n\t tmp309 = tmp290 + tmp293;\n\t tmp310 = tmp308 + tmp309;\n\t tmp312 = tmp309 - tmp308;\n\t }\n\t {\n\t fftw_real tmp46;\n\t fftw_real tmp61;\n\t fftw_real tmp78;\n\t fftw_real tmp93;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp46 = tmp38 + tmp45;\n\t tmp61 = tmp53 + tmp60;\n\t tmp62 = tmp46 + tmp61;\n\t tmp63 = tmp46 - tmp61;\n\t tmp78 = tmp70 + tmp77;\n\t tmp93 = tmp85 + tmp92;\n\t tmp94 = tmp78 - tmp93;\n\t tmp307 = tmp78 + tmp93;\n\t }\n\t c_re(output[16 * ostride]) = tmp31 - tmp62;\n\t c_re(output[0]) = tmp31 + tmp62;\n\t c_im(output[8 * ostride]) = tmp63 + tmp94;\n\t c_im(output[24 * ostride]) = tmp94 - tmp63;\n\t c_im(output[16 * ostride]) = tmp307 - tmp310;\n\t c_im(output[0]) = tmp307 + tmp310;\n\t c_re(output[24 * ostride]) = tmp311 - tmp312;\n\t c_re(output[8 * ostride]) = tmp311 + tmp312;\n }\n {\n\t fftw_real tmp121;\n\t fftw_real tmp189;\n\t fftw_real tmp187;\n\t fftw_real tmp193;\n\t fftw_real tmp148;\n\t fftw_real tmp190;\n\t fftw_real tmp175;\n\t fftw_real tmp191;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp105;\n\t fftw_real tmp120;\n\t fftw_real tmp183;\n\t fftw_real tmp186;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp105 = tmp97 - tmp104;\n\t tmp120 = tmp112 - tmp119;\n\t tmp121 = tmp105 - tmp120;\n\t tmp189 = tmp105 + tmp120;\n\t tmp183 = tmp179 - tmp182;\n\t tmp186 = tmp184 - tmp185;\n\t tmp187 = tmp183 + tmp186;\n\t tmp193 = tmp183 - tmp186;\n\t }\n\t {\n\t fftw_real tmp138;\n\t fftw_real tmp147;\n\t fftw_real tmp165;\n\t fftw_real tmp174;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp138 = tmp126 - tmp137;\n\t tmp147 = tmp143 - tmp146;\n\t tmp148 = (K555570233 * tmp138) - (K831469612 * tmp147);\n\t tmp190 = (K831469612 * tmp138) + (K555570233 * tmp147);\n\t tmp165 = tmp153 - tmp164;\n\t tmp174 = tmp170 - tmp173;\n\t tmp175 = (K555570233 * tmp165) + (K831469612 * tmp174);\n\t tmp191 = (K555570233 * tmp174) - (K831469612 * tmp165);\n\t }\n\t {\n\t fftw_real tmp176;\n\t fftw_real tmp188;\n\t fftw_real tmp192;\n\t fftw_real tmp194;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp176 = tmp148 - tmp175;\n\t c_im(output[29 * ostride]) = tmp121 - tmp176;\n\t c_im(output[13 * ostride]) = tmp121 + tmp176;\n\t tmp188 = tmp148 + tmp175;\n\t c_re(output[21 * ostride]) = tmp187 - tmp188;\n\t c_re(output[5 * ostride]) = tmp187 + tmp188;\n\t tmp192 = tmp190 + tmp191;\n\t c_im(output[21 * ostride]) = tmp189 - tmp192;\n\t c_im(output[5 * ostride]) = tmp189 + tmp192;\n\t tmp194 = tmp191 - tmp190;\n\t c_re(output[29 * ostride]) = tmp193 - tmp194;\n\t c_re(output[13 * ostride]) = tmp193 + tmp194;\n\t }\n }\n {\n\t fftw_real tmp197;\n\t fftw_real tmp209;\n\t fftw_real tmp207;\n\t fftw_real tmp213;\n\t fftw_real tmp200;\n\t fftw_real tmp210;\n\t fftw_real tmp203;\n\t fftw_real tmp211;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp195;\n\t fftw_real tmp196;\n\t fftw_real tmp205;\n\t fftw_real tmp206;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp195 = tmp97 + tmp104;\n\t tmp196 = tmp185 + tmp184;\n\t tmp197 = tmp195 - tmp196;\n\t tmp209 = tmp195 + tmp196;\n\t tmp205 = tmp179 + tmp182;\n\t tmp206 = tmp112 + tmp119;\n\t tmp207 = tmp205 + tmp206;\n\t tmp213 = tmp205 - tmp206;\n\t }\n\t {\n\t fftw_real tmp198;\n\t fftw_real tmp199;\n\t fftw_real tmp201;\n\t fftw_real tmp202;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp198 = tmp126 + tmp137;\n\t tmp199 = tmp143 + tmp146;\n\t tmp200 = (K980785280 * tmp198) - (K195090322 * tmp199);\n\t tmp210 = (K195090322 * tmp198) + (K980785280 * tmp199);\n\t tmp201 = tmp153 + tmp164;\n\t tmp202 = tmp170 + tmp173;\n\t tmp203 = (K980785280 * tmp201) + (K195090322 * tmp202);\n\t tmp211 = (K980785280 * tmp202) - (K195090322 * tmp201);\n\t }\n\t {\n\t fftw_real tmp204;\n\t fftw_real tmp208;\n\t fftw_real tmp212;\n\t fftw_real tmp214;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp204 = tmp200 - tmp203;\n\t c_im(output[25 * ostride]) = tmp197 - tmp204;\n\t c_im(output[9 * ostride]) = tmp197 + tmp204;\n\t tmp208 = tmp200 + tmp203;\n\t c_re(output[17 * ostride]) = tmp207 - tmp208;\n\t c_re(output[ostride]) = tmp207 + tmp208;\n\t tmp212 = tmp210 + tmp211;\n\t c_im(output[17 * ostride]) = tmp209 - tmp212;\n\t c_im(output[ostride]) = tmp209 + tmp212;\n\t tmp214 = tmp211 - tmp210;\n\t c_re(output[25 * ostride]) = tmp213 - tmp214;\n\t c_re(output[9 * ostride]) = tmp213 + tmp214;\n\t }\n }\n {\n\t fftw_real tmp323;\n\t fftw_real tmp347;\n\t fftw_real tmp350;\n\t fftw_real tmp352;\n\t fftw_real tmp338;\n\t fftw_real tmp346;\n\t fftw_real tmp345;\n\t fftw_real tmp351;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp315;\n\t fftw_real tmp322;\n\t fftw_real tmp348;\n\t fftw_real tmp349;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp315 = tmp313 - tmp314;\n\t tmp322 = K707106781 * (tmp318 - tmp321);\n\t tmp323 = tmp315 + tmp322;\n\t tmp347 = tmp315 - tmp322;\n\t tmp348 = (K382683432 * tmp329) - (K923879532 * tmp326);\n\t tmp349 = (K923879532 * tmp333) + (K382683432 * tmp336);\n\t tmp350 = tmp348 - tmp349;\n\t tmp352 = tmp348 + tmp349;\n\t }\n\t {\n\t fftw_real tmp330;\n\t fftw_real tmp337;\n\t fftw_real tmp341;\n\t fftw_real tmp344;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp330 = (K382683432 * tmp326) + (K923879532 * tmp329);\n\t tmp337 = (K382683432 * tmp333) - (K923879532 * tmp336);\n\t tmp338 = tmp330 + tmp337;\n\t tmp346 = tmp337 - tmp330;\n\t tmp341 = tmp339 - tmp340;\n\t tmp344 = K707106781 * (tmp342 - tmp343);\n\t tmp345 = tmp341 - tmp344;\n\t tmp351 = tmp341 + tmp344;\n\t }\n\t c_im(output[22 * ostride]) = tmp323 - tmp338;\n\t c_im(output[6 * ostride]) = tmp323 + tmp338;\n\t c_re(output[30 * ostride]) = tmp345 - tmp346;\n\t c_re(output[14 * ostride]) = tmp345 + tmp346;\n\t c_im(output[30 * ostride]) = tmp347 - tmp350;\n\t c_im(output[14 * ostride]) = tmp347 + tmp350;\n\t c_re(output[22 * ostride]) = tmp351 - tmp352;\n\t c_re(output[6 * ostride]) = tmp351 + tmp352;\n }\n {\n\t fftw_real tmp355;\n\t fftw_real tmp367;\n\t fftw_real tmp370;\n\t fftw_real tmp372;\n\t fftw_real tmp362;\n\t fftw_real tmp366;\n\t fftw_real tmp365;\n\t fftw_real tmp371;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp353;\n\t fftw_real tmp354;\n\t fftw_real tmp368;\n\t fftw_real tmp369;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp353 = tmp314 + tmp313;\n\t tmp354 = K707106781 * (tmp343 + tmp342);\n\t tmp355 = tmp353 + tmp354;\n\t tmp367 = tmp353 - tmp354;\n\t tmp368 = (K923879532 * tmp357) - (K382683432 * tmp356);\n\t tmp369 = (K382683432 * tmp359) + (K923879532 * tmp360);\n\t tmp370 = tmp368 - tmp369;\n\t tmp372 = tmp368 + tmp369;\n\t }\n\t {\n\t fftw_real tmp358;\n\t fftw_real tmp361;\n\t fftw_real tmp363;\n\t fftw_real tmp364;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp358 = (K923879532 * tmp356) + (K382683432 * tmp357);\n\t tmp361 = (K923879532 * tmp359) - (K382683432 * tmp360);\n\t tmp362 = tmp358 + tmp361;\n\t tmp366 = tmp361 - tmp358;\n\t tmp363 = tmp339 + tmp340;\n\t tmp364 = K707106781 * (tmp318 + tmp321);\n\t tmp365 = tmp363 - tmp364;\n\t tmp371 = tmp363 + tmp364;\n\t }\n\t c_im(output[18 * ostride]) = tmp355 - tmp362;\n\t c_im(output[2 * ostride]) = tmp355 + tmp362;\n\t c_re(output[26 * ostride]) = tmp365 - tmp366;\n\t c_re(output[10 * ostride]) = tmp365 + tmp366;\n\t c_im(output[26 * ostride]) = tmp367 - tmp370;\n\t c_im(output[10 * ostride]) = tmp367 + tmp370;\n\t c_re(output[18 * ostride]) = tmp371 - tmp372;\n\t c_re(output[2 * ostride]) = tmp371 + tmp372;\n }\n {\n\t fftw_real tmp225;\n\t fftw_real tmp249;\n\t fftw_real tmp247;\n\t fftw_real tmp253;\n\t fftw_real tmp232;\n\t fftw_real tmp250;\n\t fftw_real tmp239;\n\t fftw_real tmp251;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp217;\n\t fftw_real tmp224;\n\t fftw_real tmp243;\n\t fftw_real tmp246;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp217 = tmp215 - tmp216;\n\t tmp224 = tmp220 - tmp223;\n\t tmp225 = tmp217 + tmp224;\n\t tmp249 = tmp217 - tmp224;\n\t tmp243 = tmp241 - tmp242;\n\t tmp246 = tmp244 - tmp245;\n\t tmp247 = tmp243 - tmp246;\n\t tmp253 = tmp243 + tmp246;\n\t }\n\t {\n\t fftw_real tmp228;\n\t fftw_real tmp231;\n\t fftw_real tmp235;\n\t fftw_real tmp238;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp228 = tmp226 - tmp227;\n\t tmp231 = tmp229 - tmp230;\n\t tmp232 = (K195090322 * tmp228) + (K980785280 * tmp231);\n\t tmp250 = (K195090322 * tmp231) - (K980785280 * tmp228);\n\t tmp235 = tmp233 - tmp234;\n\t tmp238 = tmp236 - tmp237;\n\t tmp239 = (K195090322 * tmp235) - (K980785280 * tmp238);\n\t tmp251 = (K980785280 * tmp235) + (K195090322 * tmp238);\n\t }\n\t {\n\t fftw_real tmp240;\n\t fftw_real tmp248;\n\t fftw_real tmp252;\n\t fftw_real tmp254;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp240 = tmp232 + tmp239;\n\t c_im(output[23 * ostride]) = tmp225 - tmp240;\n\t c_im(output[7 * ostride]) = tmp225 + tmp240;\n\t tmp248 = tmp239 - tmp232;\n\t c_re(output[31 * ostride]) = tmp247 - tmp248;\n\t c_re(output[15 * ostride]) = tmp247 + tmp248;\n\t tmp252 = tmp250 - tmp251;\n\t c_im(output[31 * ostride]) = tmp249 - tmp252;\n\t c_im(output[15 * ostride]) = tmp249 + tmp252;\n\t tmp254 = tmp250 + tmp251;\n\t c_re(output[23 * ostride]) = tmp253 - tmp254;\n\t c_re(output[7 * ostride]) = tmp253 + tmp254;\n\t }\n }\n {\n\t fftw_real tmp257;\n\t fftw_real tmp269;\n\t fftw_real tmp267;\n\t fftw_real tmp273;\n\t fftw_real tmp260;\n\t fftw_real tmp270;\n\t fftw_real tmp263;\n\t fftw_real tmp271;\n\t ASSERT_ALIGNED_DOUBLE();\n\t {\n\t fftw_real tmp255;\n\t fftw_real tmp256;\n\t fftw_real tmp265;\n\t fftw_real tmp266;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp255 = tmp215 + tmp216;\n\t tmp256 = tmp245 + tmp244;\n\t tmp257 = tmp255 + tmp256;\n\t tmp269 = tmp255 - tmp256;\n\t tmp265 = tmp241 + tmp242;\n\t tmp266 = tmp220 + tmp223;\n\t tmp267 = tmp265 - tmp266;\n\t tmp273 = tmp265 + tmp266;\n\t }\n\t {\n\t fftw_real tmp258;\n\t fftw_real tmp259;\n\t fftw_real tmp261;\n\t fftw_real tmp262;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp258 = tmp226 + tmp227;\n\t tmp259 = tmp229 + tmp230;\n\t tmp260 = (K831469612 * tmp258) + (K555570233 * tmp259);\n\t tmp270 = (K831469612 * tmp259) - (K555570233 * tmp258);\n\t tmp261 = tmp233 + tmp234;\n\t tmp262 = tmp236 + tmp237;\n\t tmp263 = (K831469612 * tmp261) - (K555570233 * tmp262);\n\t tmp271 = (K555570233 * tmp261) + (K831469612 * tmp262);\n\t }\n\t {\n\t fftw_real tmp264;\n\t fftw_real tmp268;\n\t fftw_real tmp272;\n\t fftw_real tmp274;\n\t ASSERT_ALIGNED_DOUBLE();\n\t tmp264 = tmp260 + tmp263;\n\t c_im(output[19 * ostride]) = tmp257 - tmp264;\n\t c_im(output[3 * ostride]) = tmp257 + tmp264;\n\t tmp268 = tmp263 - tmp260;\n\t c_re(output[27 * ostride]) = tmp267 - tmp268;\n\t c_re(output[11 * ostride]) = tmp267 + tmp268;\n\t tmp272 = tmp270 - tmp271;\n\t c_im(output[27 * ostride]) = tmp269 - tmp272;\n\t c_im(output[11 * ostride]) = tmp269 + tmp272;\n\t tmp274 = tmp270 + tmp271;\n\t c_re(output[19 * ostride]) = tmp273 - tmp274;\n\t c_re(output[3 * ostride]) = tmp273 + tmp274;\n\t }\n }\n}\n\nfftw_codelet_desc fftwi_no_twiddle_32_desc =\n{\n \"fftwi_no_twiddle_32\",\n (void (*)()) fftwi_no_twiddle_32,\n 32,\n FFTW_BACKWARD,\n FFTW_NOTW,\n 521,\n 0,\n (const int *) 0,\n};\n", "meta": {"hexsha": "bda4c376d5f1ed86a746a734c6540855246de05b", "size": 30888, "ext": "c", "lang": "C", "max_stars_repo_path": "jlp_numeric/old/fftw2_src/fni_32.c", "max_stars_repo_name": "jlprieur/jlplib", "max_stars_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jlp_numeric/old/fftw2_src/fni_32.c", "max_issues_repo_name": "jlprieur/jlplib", "max_issues_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jlp_numeric/old/fftw2_src/fni_32.c", "max_forks_repo_name": "jlprieur/jlplib", "max_forks_repo_head_hexsha": "6073d7a7eb76d916662b1f8a4eb54f345cf7c772", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-09T00:20:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-09T00:20:49.000Z", "avg_line_length": 29.6145733461, "max_line_length": 124, "alphanum_fraction": 0.5841750842, "num_tokens": 9442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723316860482763, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.3466676072981252}} {"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#include \n#include \n#include \n#include \n#include \"Solvers/KSPSolvers/KSPSolvers.h\"\n\n#include \"common-driver-utils.h\"\n#include \"BSSCR.h\" /* includes StokesBlockKSPInterface.h */\n\n#define KSPBSSCR \"bsscr\"\n\n\nvoid bsscr_summary(KSP_BSSCR * bsscrp_self, KSP ksp_S, KSP ksp_inner,\n\t\t Mat K,Mat K2,Mat D,Mat G,Mat C,Vec u,Vec p,Vec f,Vec h,Vec t,\n\t\t double penaltyNumber,PetscTruth KisJustK,\n\t\t\t double mgSetupTime,\n\t\t\t double RHSSolveTime,\n\t\t\t double scrSolveTime,\n\t\t\t double a11SingleSolveTime){\n PetscTruth flg, found;\n PetscInt uSize, pSize, lmax, lmin, iterations;\n PetscReal rNorm, fNorm, uNorm, uNormInf, pNorm, pNormInf, p_sum, min, max;\n Vec q, qq, t2, t3;\n double solutionAnalysisTime;\n\n PetscPrintf( PETSC_COMM_WORLD, \"\\n\\nSCR Solver Summary:\\n\\n\");\n if(bsscrp_self->mg)\n\t PetscPrintf( PETSC_COMM_WORLD, \" Multigrid setup: = %.4g secs \\n\", mgSetupTime);\n\n\t\t\titerations = bsscrp_self->solver->stats.velocity_presolve_its;\n PetscPrintf( PETSC_COMM_WORLD, \" RHS V Solve: = %.4g secs / %d its\\n\", RHSSolveTime, iterations);\n\n KSPGetIterationNumber( ksp_S, &iterations);\n bsscrp_self->solver->stats.pressure_its = iterations;\n\n PetscPrintf( PETSC_COMM_WORLD, \" Pressure Solve: = %.4g secs / %d its\\n\", scrSolveTime, iterations);\n KSPGetIterationNumber( ksp_inner, &iterations);\n\n bsscrp_self->solver->stats.velocity_backsolve_its = iterations;\n PetscPrintf( PETSC_COMM_WORLD, \" Final V Solve: = %.4g secs / %d its\\n\\n\", a11SingleSolveTime, iterations);\n\n /***************************************************************************************************************/\n\n flg = PETSC_FALSE; /* Off by default */\n\t PetscOptionsGetTruth( PETSC_NULL, \"-scr_ksp_solution_summary\", &flg, &found );\n\n if(flg) {\n\t PetscScalar KuNorm;\n\t solutionAnalysisTime = MPI_Wtime();\n\t VecGetSize( u, &uSize );\n\t VecGetSize( p, &pSize );\n\t VecDuplicate( u, &t2 );\n\t VecDuplicate( u, &t3 );\n\t MatMult( K, u, t3); VecNorm( t3, NORM_2, &KuNorm );\n\t double angle, kdot;\n\t if(penaltyNumber > 1e-10){/* should change this to ifK2built maybe */\n MatMult( K2, u, t2); VecNorm( t2, NORM_2, &rNorm );\n VecDot(t2,t3,&kdot);\n angle = (kdot/(rNorm*KuNorm));\n PetscPrintf( PETSC_COMM_WORLD, \" /(|K u| |K2 u|) = %.6e\\n\", angle);\n\t }\n\t VecNorm( t, NORM_2, &rNorm ); /* t = f- G p should be the formal residual vector, calculated on line 267 in auglag-driver-DGTGD.c */\n\t VecDot(t3,t,&kdot);\n\t angle = (kdot/(rNorm*KuNorm));\n PetscPrintf( PETSC_COMM_WORLD, \" /(|K u| |f- G p|) = %.6e\\n\\n\", angle);\n\n\t MatMult( K, u, t2); VecNorm(t2, NORM_2, &KuNorm);\n\t VecAYPX( t2, -1.0, t ); /* t2 <- -t2 + t : t = f- G p should be the formal residual vector, calculated on line 267 in auglag-driver-DGTGD.c*/\n\t VecNorm( t2, NORM_2, &rNorm );\n\t VecNorm( f, NORM_2, &fNorm );\n\t if(KisJustK){\n PetscPrintf( PETSC_COMM_WORLD,\"Velocity back-solve with original K matrix\\n\");\n PetscPrintf( PETSC_COMM_WORLD,\"Solved K u = G p -f\\n\");\n PetscPrintf( PETSC_COMM_WORLD,\"Residual with original K matrix\\n\");\n PetscPrintf( PETSC_COMM_WORLD, \" |f - K u - G p| = %.12e\\n\", rNorm);\n PetscPrintf( PETSC_COMM_WORLD, \" |f - K u - G p|/|f| = %.12e\\n\", rNorm/fNorm);\n if(penaltyNumber > 1e-10){/* means the restore_K flag was used */\n //if(K2 && f2){\n MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);/* Computes K = penaltyNumber*K2 + K */\n //VecAXPY(f,penaltyNumber,f2); /* f = penaltyNumber*f2 + f */\n KisJustK=PETSC_FALSE;\n MatMult( K, u, t2);\n MatMult( G, p, t);\n VecAYPX( t, -1.0, f ); /* t <- -t + f */\n VecAYPX( t2, -1.0, t ); /* t2 <- -t2 + t */\n VecNorm( t2, NORM_2, &rNorm );\n PetscPrintf( PETSC_COMM_WORLD,\"Residual with K+K2 matrix and f rhs vector\\n\");\n PetscPrintf( PETSC_COMM_WORLD, \" |(f) - (K + K2) u - G p| = %.12e\\n\", rNorm);\n //}\n }\n\t }\n\t else{\n PetscPrintf( PETSC_COMM_WORLD,\"Velocity back-solve with K+K2 matrix\\n\");\n PetscPrintf( PETSC_COMM_WORLD,\"Solved (K + K2) u = G p - (f)\\n\");\n PetscPrintf( PETSC_COMM_WORLD,\"Residual with K+K2 matrix and f rhs vector\\n\");\n PetscPrintf( PETSC_COMM_WORLD, \" |(f) - (K + K2) u - G p| = %.12e\\n\", rNorm);\n PetscReal KK2Norm,KK2Normf;\n MatNorm(K,NORM_1,&KK2Norm);\n MatNorm(K,NORM_FROBENIUS,&KK2Normf);\n penaltyNumber = -penaltyNumber;\n MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);/* Computes K = penaltyNumber*K2 + K */\n //VecAXPY(f,penaltyNumber,f2); /* f = penaltyNumber*f2 + f */\n KisJustK=PETSC_FALSE;\n MatMult( K, u, t2); /* t2 = K*u */\n MatMult( G, p, t); /* t = G*p */\n VecAYPX( t, -1.0, f ); /* t <- f - t ; t = f - G*p */\n VecAYPX( t2, -1.0, t ); /* t2 <- t - t2; t2 = f - G*p - K*u */\n VecNorm( t2, NORM_2, &rNorm );\n PetscPrintf( PETSC_COMM_WORLD,\"Residual with original K matrix\\n\");\n PetscPrintf( PETSC_COMM_WORLD, \" |f - K u - G p| = %.12e\\n\", rNorm);\n PetscPrintf( PETSC_COMM_WORLD, \" |f - K u - G p|/|f| = %.12e\\n\", rNorm/fNorm);\n PetscReal KNorm, K2Norm;\n MatNorm(K,NORM_1,&KNorm);\t MatNorm(K2,NORM_1,&K2Norm);\n PetscPrintf( PETSC_COMM_WORLD,\"K and K2 norm_1 %.12e %.12e ratio %.12e\\n\",KNorm,K2Norm,K2Norm/KNorm);\n MatNorm(K,NORM_INFINITY,&KNorm); MatNorm(K2,NORM_INFINITY,&K2Norm);\n PetscPrintf( PETSC_COMM_WORLD,\"K and K2 norm_inf %.12e %.12e ratio %.12e\\n\",KNorm,K2Norm,K2Norm/KNorm);\n MatNorm(K,NORM_FROBENIUS,&KNorm); MatNorm(K2,NORM_FROBENIUS,&K2Norm);\n PetscPrintf( PETSC_COMM_WORLD,\"K and K2 norm_frob %.12e %.12e ratio %.12e\\n\",KNorm,K2Norm,K2Norm/KNorm);\n PetscPrintf( PETSC_COMM_WORLD,\"K+r*K2 norm_1 %.12e\\n\",KK2Norm);\n PetscPrintf( PETSC_COMM_WORLD,\"K+r*K2 norm_frob %.12e\\n\",KK2Normf);\n penaltyNumber = -penaltyNumber;\n MatAXPY(K,penaltyNumber,K2,DIFFERENT_NONZERO_PATTERN);/* Computes K = penaltyNumber*K2 + K */\n }\n PetscPrintf( PETSC_COMM_WORLD,\"\\n\");\n PetscPrintf( PETSC_COMM_WORLD, \" |K u| = %.12e\\n\", KuNorm);\n if(penaltyNumber > 1e-10){\n MatMult( K2, u, t2); VecNorm( t2, NORM_2, &rNorm );\n PetscPrintf( PETSC_COMM_WORLD, \" |K2 u| = %.12e\\n\", rNorm);\n PetscPrintf( PETSC_COMM_WORLD,\"\\n\");\n\t }\n\n\n\n\t VecDuplicate( p, &q );\n\t MatMult( D, u, q ); /* q = G'*u = D*u */\n\t VecNorm( u, NORM_2, &uNorm );\n\t VecNorm( q, NORM_2, &rNorm );\n\n\t PetscPrintf( PETSC_COMM_WORLD, \" |G^T u|_2 = %.6e\\n\", rNorm );\n\t PetscPrintf( PETSC_COMM_WORLD, \" |G^T u|_2/|u|_2 = %.6e\\n\", sqrt( (double) uSize / (double) pSize ) * rNorm / uNorm);\n\n\t VecDuplicate( p, &qq );\n\t MatMultTranspose( G, u, qq );\n\t VecNorm( qq, NORM_2, &rNorm );\n\t PetscPrintf( PETSC_COMM_WORLD, \" |G^T u|/|u| = %.8e\\n\", rNorm/uNorm ); /* to compare directly with Uzawa */\n\n\t VecNorm( q, NORM_INFINITY, &rNorm );\n\t PetscPrintf( PETSC_COMM_WORLD, \" |G^T u|_infty/|u|_2 = %.6e\\n\", sqrt( (double) uSize ) * rNorm / uNorm);\n\t /* create G'*u+C*p-h to check on this constraint */\n\t /* already have q = D*u */\n\t VecZeroEntries(qq);\n\t if(C){\n MatMult( C, p, qq );\n\t }\n\t VecAYPX( q, 1.0, qq ); /* q = q+qq; G'*u + C*p*/\n\t VecAXPY( q, -1.0, h ); /* q = q-h; G'*u + C*p - h */\n\t VecNorm( q, NORM_2, &rNorm );\n\t PetscPrintf( PETSC_COMM_WORLD, \" |G^T u + C p - h| = %.8e :constraint\\n\", rNorm );\n\n\t VecNorm( u, NORM_INFINITY, &uNormInf );\n\t VecNorm( u, NORM_2, &uNorm );\n\t VecGetSize( u, &uSize );\n\n\t VecNorm( p, NORM_INFINITY, &pNormInf );\n\t VecNorm( p, NORM_2, &pNorm );\n\n\t PetscPrintf( PETSC_COMM_WORLD, \" |u|_{\\\\infty} = %.6e , u_rms = %.6e\\n\",\n\t uNormInf, uNorm / sqrt( (double) uSize ) );\n\n\t PetscPrintf( PETSC_COMM_WORLD, \" |p|_{\\\\infty} = %.6e , p_rms = %.6e\\n\",\n\t pNormInf, pNorm / sqrt( (double) pSize ) );\n\n\t VecMax( u, &lmax, &max );\n\t VecMin( u, &lmin, &min );\n\t PetscPrintf( PETSC_COMM_WORLD, \" min/max(u) = %.6e [%d] / %.6e [%d]\\n\",min,lmin,max,lmax);\n bsscrp_self->solver->stats.vmin = min;\n bsscrp_self->solver->stats.vmax = max;\n\n\t VecMax( p, &lmax, &max );\n\t VecMin( p, &lmin, &min );\n\t PetscPrintf( PETSC_COMM_WORLD, \" min/max(p) = %.6e [%d] / %.6e [%d]\\n\",min,lmin,max,lmax);\n bsscrp_self->solver->stats.pmin = min;\n bsscrp_self->solver->stats.pmax = max;\n\n\t VecSum( p, &p_sum );\n\t PetscPrintf( PETSC_COMM_WORLD, \" \\\\sum_i p_i = %.6e \\n\", p_sum );\n bsscrp_self->solver->stats.p_sum=p_sum;\n\n\t solutionAnalysisTime = MPI_Wtime() - solutionAnalysisTime;\n\n\t PetscPrintf( PETSC_COMM_WORLD, \"\\n Time for this analysis = %.4g secs\\n\\n\",solutionAnalysisTime);\n\n\t Stg_VecDestroy(&t2 );\n\t Stg_VecDestroy(&t3 );\n\t Stg_VecDestroy(&q );\n\t Stg_VecDestroy(&qq );\n }\n\n}\n", "meta": {"hexsha": "77d513d9dd55664db1b61adb8ea02056260d9f18", "size": 10350, "ext": "c", "lang": "C", "max_stars_repo_path": "underworld/libUnderworld/Solvers/KSPSolvers/src/BSSCR/summary.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/summary.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/summary.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": 48.3644859813, "max_line_length": 148, "alphanum_fraction": 0.5457971014, "num_tokens": 3446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804478040616, "lm_q2_score": 0.5583269943353744, "lm_q1q2_score": 0.3454818275759387}} {"text": "/* Modified Cholesky Decomposition\n *\n * Copyright (C) 2016 Patrick Alken\n *\n * This is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by the\n * Free Software Foundation; either version 3, or (at your option) any\n * later version.\n *\n * This source is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * for more details.\n */\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cholesky_common.c\"\n\n/*\n * This module contains routines related to the Modified Cholesky\n * Decomposition, which factors a symmetric indefinite matrix A as\n *\n * P (A + E) P^T = L D L^T\n *\n * where:\n * P: permutation matrix\n * E: small, non-negative diagonal matrix\n * L: unit lower triangular matrix\n * D: strictly positive diagonal matrix\n *\n * These routines follow these works closely:\n *\n * [1] P. E. Gill, W. Murray, M. H. Wright, Practical Optimization,\n * Academic Press, 1981.\n *\n * [2] Dennis and Schnabel, Numerical Methods for Unconstrained Optimization\n * and Nonlinear Equations, SIAM, 1996\n */\n\nstatic size_t mcholesky_maxabs(const gsl_vector * v, double *maxabs);\n\n/*\ngsl_linalg_mcholesky_decomp()\n Perform Pivoted Modified Cholesky LDLT decomposition of a symmetric positive\nindefinite matrix:\n\nP (A + E) P^T = L D L^T\n\nInputs: A - (input) symmetric, positive indefinite matrix,\n stored in lower triangle\n (output) lower triangle contains L; diagonal contains D\n p - (output) permutation matrix P\n E - (output) perturbation matrix E\n\nReturn: success/error\n\nNotes:\n1) Based on algorithm 4.2.2 (Outer Product LDLT with Pivoting) of\nGolub and Van Loan, Matrix Computations (4th ed), with modifications\ndescribed in [1] and [2]\n\n2) E can be set to NULL if not required\n*/\n\nint\ngsl_linalg_mcholesky_decomp (gsl_matrix * A, gsl_permutation * p,\n gsl_vector * E)\n{\n const size_t N = A->size1;\n\n if (N != A->size2)\n {\n GSL_ERROR(\"LDLT decomposition requires square matrix\", GSL_ENOTSQR);\n }\n else if (p->size != N)\n {\n GSL_ERROR (\"permutation length must match matrix size\", GSL_EBADLEN);\n }\n else\n {\n const double delta = GSL_DBL_EPSILON;\n double beta;\n double gamma = 0.0;\n double xi = 0.0;\n gsl_vector_view diag = gsl_matrix_diagonal(A);\n size_t i, j;\n\n /* save a copy of A in upper triangle (for later rcond calculation) */\n gsl_matrix_transpose_tricpy('L', 0, A, A);\n\n gsl_permutation_init(p);\n\n /* compute:\n * gamma = max | A_{ii} |\n * xi = max_{i \\ne j} | A_{ij} |\n */\n for (i = 0; i < N; ++i)\n {\n double aii = gsl_matrix_get(A, i, i);\n\n gamma = GSL_MAX(gamma, fabs(aii));\n\n for (j = 0; j < i; ++j)\n {\n double aij = gsl_matrix_get(A, i, j);\n xi = GSL_MAX(xi, fabs(aij));\n }\n }\n\n /* compute:\n * beta = sqrt[ max { gamma, xi/nu, eps } ]\n * with: nu = max{ sqrt(N^2 - 1), 1 }\n */\n if (N == 1)\n {\n beta = GSL_MAX(GSL_MAX(gamma, xi), GSL_DBL_EPSILON);\n }\n else\n {\n double nu = sqrt(N*N - 1.0);\n beta = GSL_MAX(GSL_MAX(gamma, xi / nu), GSL_DBL_EPSILON);\n }\n\n beta = sqrt(beta);\n\n for (j = 0; j < N; ++j)\n {\n double ajj, thetaj, u, alpha, alphainv;\n gsl_vector_view w;\n size_t q;\n\n /* compute q = max_idx { A_jj, ..., A_nn } */\n w = gsl_vector_subvector(&diag.vector, j, N - j);\n q = mcholesky_maxabs(&w.vector, NULL) + j;\n\n gsl_permutation_swap(p, q, j);\n cholesky_swap_rowcol(A, q, j);\n\n /* theta_j = max_{j+1 <= i <= n} |A_{ij}| */\n if (j < N - 1)\n {\n w = gsl_matrix_subcolumn(A, j, j + 1, N - j - 1);\n mcholesky_maxabs(&w.vector, &thetaj);\n }\n else\n {\n thetaj = 0.0;\n }\n\n u = thetaj / beta;\n\n /* compute alpha = d_j */\n ajj = gsl_matrix_get(A, j, j);\n alpha = GSL_MAX(GSL_MAX(delta, fabs(ajj)), u * u);\n alphainv = 1.0 / alpha;\n\n if (j < N - 1)\n {\n /* v = A(j+1:n, j) */\n gsl_vector_view v = gsl_matrix_subcolumn(A, j, j + 1, N - j - 1);\n\n /* m = A(j+1:n, j+1:n) */\n gsl_matrix_view m = gsl_matrix_submatrix(A, j + 1, j + 1, N - j - 1, N - j - 1);\n\n /* m = m - v v^T / alpha */\n gsl_blas_dsyr(CblasLower, -alphainv, &v.vector, &m.matrix);\n\n /* v = v / alpha */\n gsl_vector_scale(&v.vector, alphainv);\n\n }\n\n if (E)\n gsl_vector_set(E, j, alpha - ajj);\n\n gsl_matrix_set(A, j, j, alpha);\n }\n\n if (E)\n {\n /* we currently have: P A P^T + E = L D L^T, permute E\n * so that we have: P (A + E) P^T = L D L^T */\n gsl_permute_vector_inverse(p, E);\n }\n\n return GSL_SUCCESS;\n }\n}\n\nint\ngsl_linalg_mcholesky_solve(const gsl_matrix * LDLT,\n const gsl_permutation * p,\n const gsl_vector * b,\n gsl_vector * x)\n{\n int status = gsl_linalg_pcholesky_solve(LDLT, p, b, x);\n return status;\n}\n\nint\ngsl_linalg_mcholesky_svx(const gsl_matrix * LDLT,\n const gsl_permutation * p,\n gsl_vector * x)\n{\n int status = gsl_linalg_pcholesky_svx(LDLT, p, x);\n return status;\n}\n\nint\ngsl_linalg_mcholesky_rcond (const gsl_matrix * LDLT, const gsl_permutation * p,\n double * rcond, gsl_vector * work)\n{\n int status = gsl_linalg_pcholesky_rcond(LDLT, p, rcond, work);\n return status;\n}\n\nint\ngsl_linalg_mcholesky_invert(const gsl_matrix * LDLT, const gsl_permutation * p,\n gsl_matrix * Ainv)\n{\n int status = gsl_linalg_pcholesky_invert(LDLT, p, Ainv);\n return status;\n}\n\n/*\nmcholesky_maxabs()\n Compute:\n\nval = max_i |v_i|\n\nInputs: v - vector\n maxabs - (output) max abs value\n\nReturn: index corresponding to max_i |v_i|\n*/\n\nstatic size_t\nmcholesky_maxabs(const gsl_vector * v, double *maxabs)\n{\n const size_t n = v->size;\n size_t i;\n size_t idx = 0;\n double max = gsl_vector_get(v, idx);\n\n for (i = 1; i < n; ++i)\n {\n double vi = gsl_vector_get(v, i);\n double absvi = fabs(vi);\n\n if (absvi > max)\n {\n max = absvi;\n idx = i;\n }\n }\n\n if (maxabs)\n *maxabs = max;\n\n return idx;\n}\n", "meta": {"hexsha": "e02b5aceba625b0ea420da99ea77863f04f4466b", "size": 6964, "ext": "c", "lang": "C", "max_stars_repo_path": "gsl-2.4/linalg/mcholesky.c", "max_stars_repo_name": "peterahrens/FillEstimationIPDPS2017", "max_stars_repo_head_hexsha": "857b6ee8866a2950aa5721d575d2d7d0797c4302", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-13T05:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-13T05:01:59.000Z", "max_issues_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/mcholesky.c", "max_issues_repo_name": "Brian-ning/HMNE", "max_issues_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/BaselineMethods/MNE/C++/gsl-2.4/linalg/mcholesky.c", "max_forks_repo_name": "Brian-ning/HMNE", "max_forks_repo_head_hexsha": "1b4ee4c146f526ea6e2f4f8607df7e9687204a9e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6029411765, "max_line_length": 94, "alphanum_fraction": 0.5637564618, "num_tokens": 1998, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.640635854839898, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.34529197632961595}} {"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:49 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 10 */\n\n/*\n * This function contains 168 FP additions, 84 FP multiplications,\n * (or, 126 additions, 42 multiplications, 42 fused multiply/add),\n * 43 stack variables, and 80 memory accesses\n */\nstatic const fftw_real K587785252 = FFTW_KONST(+0.587785252292473129168705954639072768597652438);\nstatic const fftw_real K951056516 = FFTW_KONST(+0.951056516295153572116439333379382143405698634);\nstatic const fftw_real K250000000 = FFTW_KONST(+0.250000000000000000000000000000000000000000000);\nstatic const fftw_real K559016994 = FFTW_KONST(+0.559016994374947424102293417182819058860154590);\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_10(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 + (10 * iostride);\n {\n\t fftw_real tmp170;\n\t fftw_real tmp181;\n\t fftw_real tmp162;\n\t fftw_real tmp175;\n\t fftw_real tmp165;\n\t fftw_real tmp176;\n\t fftw_real tmp166;\n\t fftw_real tmp183;\n\t fftw_real tmp155;\n\t fftw_real tmp178;\n\t fftw_real tmp158;\n\t fftw_real tmp179;\n\t fftw_real tmp159;\n\t fftw_real tmp182;\n\t fftw_real tmp168;\n\t fftw_real tmp169;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp168 = X[0];\n\t tmp169 = X[5 * iostride];\n\t tmp170 = tmp168 - tmp169;\n\t tmp181 = tmp168 + tmp169;\n\t {\n\t fftw_real tmp160;\n\t fftw_real tmp161;\n\t fftw_real tmp163;\n\t fftw_real tmp164;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp160 = X[4 * iostride];\n\t tmp161 = X[9 * iostride];\n\t tmp162 = tmp160 - tmp161;\n\t tmp175 = tmp160 + tmp161;\n\t tmp163 = X[6 * iostride];\n\t tmp164 = X[iostride];\n\t tmp165 = tmp163 - tmp164;\n\t tmp176 = tmp163 + tmp164;\n\t }\n\t tmp166 = tmp162 + tmp165;\n\t tmp183 = tmp175 + tmp176;\n\t {\n\t fftw_real tmp153;\n\t fftw_real tmp154;\n\t fftw_real tmp156;\n\t fftw_real tmp157;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp153 = X[2 * iostride];\n\t tmp154 = X[7 * iostride];\n\t tmp155 = tmp153 - tmp154;\n\t tmp178 = tmp153 + tmp154;\n\t tmp156 = X[8 * iostride];\n\t tmp157 = X[3 * iostride];\n\t tmp158 = tmp156 - tmp157;\n\t tmp179 = tmp156 + tmp157;\n\t }\n\t tmp159 = tmp155 + tmp158;\n\t tmp182 = tmp178 + tmp179;\n\t {\n\t fftw_real tmp167;\n\t fftw_real tmp171;\n\t fftw_real tmp172;\n\t fftw_real tmp186;\n\t fftw_real tmp184;\n\t fftw_real tmp185;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp167 = K559016994 * (tmp159 - tmp166);\n\t tmp171 = tmp159 + tmp166;\n\t tmp172 = tmp170 - (K250000000 * tmp171);\n\t X[iostride] = tmp167 + tmp172;\n\t X[3 * iostride] = tmp172 - tmp167;\n\t X[5 * iostride] = tmp170 + tmp171;\n\t tmp186 = K559016994 * (tmp182 - tmp183);\n\t tmp184 = tmp182 + tmp183;\n\t tmp185 = tmp181 - (K250000000 * tmp184);\n\t X[2 * iostride] = tmp185 - tmp186;\n\t X[4 * iostride] = tmp186 + tmp185;\n\t X[0] = tmp181 + tmp184;\n\t }\n\t {\n\t fftw_real tmp173;\n\t fftw_real tmp174;\n\t fftw_real tmp177;\n\t fftw_real tmp180;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp173 = tmp155 - tmp158;\n\t tmp174 = tmp162 - tmp165;\n\t Y[-iostride] = -((K951056516 * tmp173) + (K587785252 * tmp174));\n\t Y[-3 * iostride] = (K587785252 * tmp173) - (K951056516 * tmp174);\n\t tmp177 = tmp175 - tmp176;\n\t tmp180 = tmp178 - tmp179;\n\t Y[-2 * iostride] = (K951056516 * tmp177) - (K587785252 * tmp180);\n\t Y[-4 * iostride] = (K951056516 * tmp180) + (K587785252 * tmp177);\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 + 9) {\n\t fftw_real tmp39;\n\t fftw_real tmp87;\n\t fftw_real tmp132;\n\t fftw_real tmp144;\n\t fftw_real tmp73;\n\t fftw_real tmp84;\n\t fftw_real tmp85;\n\t fftw_real tmp91;\n\t fftw_real tmp92;\n\t fftw_real tmp93;\n\t fftw_real tmp100;\n\t fftw_real tmp103;\n\t fftw_real tmp128;\n\t fftw_real tmp121;\n\t fftw_real tmp122;\n\t fftw_real tmp142;\n\t fftw_real tmp50;\n\t fftw_real tmp61;\n\t fftw_real tmp62;\n\t fftw_real tmp88;\n\t fftw_real tmp89;\n\t fftw_real tmp90;\n\t fftw_real tmp107;\n\t fftw_real tmp110;\n\t fftw_real tmp127;\n\t fftw_real tmp118;\n\t fftw_real tmp119;\n\t fftw_real tmp141;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t fftw_real tmp33;\n\t fftw_real tmp131;\n\t fftw_real tmp38;\n\t fftw_real tmp130;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp33 = X[0];\n\t tmp131 = Y[-9 * iostride];\n\t {\n\t\t fftw_real tmp35;\n\t\t fftw_real tmp37;\n\t\t fftw_real tmp34;\n\t\t fftw_real tmp36;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp35 = X[5 * iostride];\n\t\t tmp37 = Y[-4 * iostride];\n\t\t tmp34 = c_re(W[4]);\n\t\t tmp36 = c_im(W[4]);\n\t\t tmp38 = (tmp34 * tmp35) - (tmp36 * tmp37);\n\t\t tmp130 = (tmp36 * tmp35) + (tmp34 * tmp37);\n\t }\n\t tmp39 = tmp33 - tmp38;\n\t tmp87 = tmp33 + tmp38;\n\t tmp132 = tmp130 + tmp131;\n\t tmp144 = tmp131 - tmp130;\n\t }\n\t {\n\t fftw_real tmp67;\n\t fftw_real tmp98;\n\t fftw_real tmp83;\n\t fftw_real tmp102;\n\t fftw_real tmp72;\n\t fftw_real tmp99;\n\t fftw_real tmp78;\n\t fftw_real tmp101;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp64;\n\t\t fftw_real tmp66;\n\t\t fftw_real tmp63;\n\t\t fftw_real tmp65;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp64 = X[4 * iostride];\n\t\t tmp66 = Y[-5 * iostride];\n\t\t tmp63 = c_re(W[3]);\n\t\t tmp65 = c_im(W[3]);\n\t\t tmp67 = (tmp63 * tmp64) - (tmp65 * tmp66);\n\t\t tmp98 = (tmp65 * tmp64) + (tmp63 * tmp66);\n\t }\n\t {\n\t\t fftw_real tmp80;\n\t\t fftw_real tmp82;\n\t\t fftw_real tmp79;\n\t\t fftw_real tmp81;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp80 = X[iostride];\n\t\t tmp82 = Y[-8 * iostride];\n\t\t tmp79 = c_re(W[0]);\n\t\t tmp81 = c_im(W[0]);\n\t\t tmp83 = (tmp79 * tmp80) - (tmp81 * tmp82);\n\t\t tmp102 = (tmp81 * tmp80) + (tmp79 * tmp82);\n\t }\n\t {\n\t\t fftw_real tmp69;\n\t\t fftw_real tmp71;\n\t\t fftw_real tmp68;\n\t\t fftw_real tmp70;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp69 = X[9 * iostride];\n\t\t tmp71 = Y[0];\n\t\t tmp68 = c_re(W[8]);\n\t\t tmp70 = c_im(W[8]);\n\t\t tmp72 = (tmp68 * tmp69) - (tmp70 * tmp71);\n\t\t tmp99 = (tmp70 * tmp69) + (tmp68 * tmp71);\n\t }\n\t {\n\t\t fftw_real tmp75;\n\t\t fftw_real tmp77;\n\t\t fftw_real tmp74;\n\t\t fftw_real tmp76;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp75 = X[6 * iostride];\n\t\t tmp77 = Y[-3 * iostride];\n\t\t tmp74 = c_re(W[5]);\n\t\t tmp76 = c_im(W[5]);\n\t\t tmp78 = (tmp74 * tmp75) - (tmp76 * tmp77);\n\t\t tmp101 = (tmp76 * tmp75) + (tmp74 * tmp77);\n\t }\n\t tmp73 = tmp67 - tmp72;\n\t tmp84 = tmp78 - tmp83;\n\t tmp85 = tmp73 + tmp84;\n\t tmp91 = tmp67 + tmp72;\n\t tmp92 = tmp78 + tmp83;\n\t tmp93 = tmp91 + tmp92;\n\t tmp100 = tmp98 + tmp99;\n\t tmp103 = tmp101 + tmp102;\n\t tmp128 = tmp100 + tmp103;\n\t tmp121 = tmp98 - tmp99;\n\t tmp122 = tmp101 - tmp102;\n\t tmp142 = tmp121 + tmp122;\n\t }\n\t {\n\t fftw_real tmp44;\n\t fftw_real tmp105;\n\t fftw_real tmp60;\n\t fftw_real tmp109;\n\t fftw_real tmp49;\n\t fftw_real tmp106;\n\t fftw_real tmp55;\n\t fftw_real tmp108;\n\t ASSERT_ALIGNED_DOUBLE;\n\t {\n\t\t fftw_real tmp41;\n\t\t fftw_real tmp43;\n\t\t fftw_real tmp40;\n\t\t fftw_real tmp42;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp41 = X[2 * iostride];\n\t\t tmp43 = Y[-7 * iostride];\n\t\t tmp40 = c_re(W[1]);\n\t\t tmp42 = c_im(W[1]);\n\t\t tmp44 = (tmp40 * tmp41) - (tmp42 * tmp43);\n\t\t tmp105 = (tmp42 * tmp41) + (tmp40 * tmp43);\n\t }\n\t {\n\t\t fftw_real tmp57;\n\t\t fftw_real tmp59;\n\t\t fftw_real tmp56;\n\t\t fftw_real tmp58;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp57 = X[3 * iostride];\n\t\t tmp59 = Y[-6 * iostride];\n\t\t tmp56 = c_re(W[2]);\n\t\t tmp58 = c_im(W[2]);\n\t\t tmp60 = (tmp56 * tmp57) - (tmp58 * tmp59);\n\t\t tmp109 = (tmp58 * tmp57) + (tmp56 * tmp59);\n\t }\n\t {\n\t\t fftw_real tmp46;\n\t\t fftw_real tmp48;\n\t\t fftw_real tmp45;\n\t\t fftw_real tmp47;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp46 = X[7 * iostride];\n\t\t tmp48 = Y[-2 * iostride];\n\t\t tmp45 = c_re(W[6]);\n\t\t tmp47 = c_im(W[6]);\n\t\t tmp49 = (tmp45 * tmp46) - (tmp47 * tmp48);\n\t\t tmp106 = (tmp47 * tmp46) + (tmp45 * tmp48);\n\t }\n\t {\n\t\t fftw_real tmp52;\n\t\t fftw_real tmp54;\n\t\t fftw_real tmp51;\n\t\t fftw_real tmp53;\n\t\t ASSERT_ALIGNED_DOUBLE;\n\t\t tmp52 = X[8 * iostride];\n\t\t tmp54 = Y[-iostride];\n\t\t tmp51 = c_re(W[7]);\n\t\t tmp53 = c_im(W[7]);\n\t\t tmp55 = (tmp51 * tmp52) - (tmp53 * tmp54);\n\t\t tmp108 = (tmp53 * tmp52) + (tmp51 * tmp54);\n\t }\n\t tmp50 = tmp44 - tmp49;\n\t tmp61 = tmp55 - tmp60;\n\t tmp62 = tmp50 + tmp61;\n\t tmp88 = tmp44 + tmp49;\n\t tmp89 = tmp55 + tmp60;\n\t tmp90 = tmp88 + tmp89;\n\t tmp107 = tmp105 + tmp106;\n\t tmp110 = tmp108 + tmp109;\n\t tmp127 = tmp107 + tmp110;\n\t tmp118 = tmp105 - tmp106;\n\t tmp119 = tmp108 - tmp109;\n\t tmp141 = tmp118 + tmp119;\n\t }\n\t {\n\t fftw_real tmp115;\n\t fftw_real tmp86;\n\t fftw_real tmp116;\n\t fftw_real tmp124;\n\t fftw_real tmp126;\n\t fftw_real tmp120;\n\t fftw_real tmp123;\n\t fftw_real tmp125;\n\t fftw_real tmp117;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp115 = K559016994 * (tmp62 - tmp85);\n\t tmp86 = tmp62 + tmp85;\n\t tmp116 = tmp39 - (K250000000 * tmp86);\n\t tmp120 = tmp118 - tmp119;\n\t tmp123 = tmp121 - tmp122;\n\t tmp124 = (K951056516 * tmp120) + (K587785252 * tmp123);\n\t tmp126 = (K951056516 * tmp123) - (K587785252 * tmp120);\n\t Y[-5 * iostride] = tmp39 + tmp86;\n\t tmp125 = tmp116 - tmp115;\n\t Y[-7 * iostride] = tmp125 - tmp126;\n\t X[3 * iostride] = tmp125 + tmp126;\n\t tmp117 = tmp115 + tmp116;\n\t Y[-9 * iostride] = tmp117 - tmp124;\n\t X[iostride] = tmp117 + tmp124;\n\t }\n\t {\n\t fftw_real tmp148;\n\t fftw_real tmp143;\n\t fftw_real tmp149;\n\t fftw_real tmp147;\n\t fftw_real tmp151;\n\t fftw_real tmp145;\n\t fftw_real tmp146;\n\t fftw_real tmp152;\n\t fftw_real tmp150;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp148 = K559016994 * (tmp141 - tmp142);\n\t tmp143 = tmp141 + tmp142;\n\t tmp149 = tmp144 - (K250000000 * tmp143);\n\t tmp145 = tmp50 - tmp61;\n\t tmp146 = tmp73 - tmp84;\n\t tmp147 = (K951056516 * tmp145) + (K587785252 * tmp146);\n\t tmp151 = (K587785252 * tmp145) - (K951056516 * tmp146);\n\t X[5 * iostride] = -(tmp143 + tmp144);\n\t tmp152 = tmp149 - tmp148;\n\t X[7 * iostride] = tmp151 - tmp152;\n\t Y[-3 * iostride] = tmp151 + tmp152;\n\t tmp150 = tmp148 + tmp149;\n\t X[9 * iostride] = -(tmp147 + tmp150);\n\t Y[-iostride] = tmp150 - tmp147;\n\t }\n\t {\n\t fftw_real tmp96;\n\t fftw_real tmp94;\n\t fftw_real tmp95;\n\t fftw_real tmp112;\n\t fftw_real tmp114;\n\t fftw_real tmp104;\n\t fftw_real tmp111;\n\t fftw_real tmp113;\n\t fftw_real tmp97;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp96 = K559016994 * (tmp90 - tmp93);\n\t tmp94 = tmp90 + tmp93;\n\t tmp95 = tmp87 - (K250000000 * tmp94);\n\t tmp104 = tmp100 - tmp103;\n\t tmp111 = tmp107 - tmp110;\n\t tmp112 = (K951056516 * tmp104) - (K587785252 * tmp111);\n\t tmp114 = (K951056516 * tmp111) + (K587785252 * tmp104);\n\t X[0] = tmp87 + tmp94;\n\t tmp113 = tmp96 + tmp95;\n\t X[4 * iostride] = tmp113 - tmp114;\n\t Y[-6 * iostride] = tmp113 + tmp114;\n\t tmp97 = tmp95 - tmp96;\n\t X[2 * iostride] = tmp97 - tmp112;\n\t Y[-8 * iostride] = tmp97 + tmp112;\n\t }\n\t {\n\t fftw_real tmp134;\n\t fftw_real tmp129;\n\t fftw_real tmp133;\n\t fftw_real tmp138;\n\t fftw_real tmp140;\n\t fftw_real tmp136;\n\t fftw_real tmp137;\n\t fftw_real tmp139;\n\t fftw_real tmp135;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp134 = K559016994 * (tmp127 - tmp128);\n\t tmp129 = tmp127 + tmp128;\n\t tmp133 = tmp132 - (K250000000 * tmp129);\n\t tmp136 = tmp91 - tmp92;\n\t tmp137 = tmp88 - tmp89;\n\t tmp138 = (K951056516 * tmp136) - (K587785252 * tmp137);\n\t tmp140 = (K951056516 * tmp137) + (K587785252 * tmp136);\n\t Y[0] = tmp129 + tmp132;\n\t tmp139 = tmp134 + tmp133;\n\t X[6 * iostride] = -(tmp139 - tmp140);\n\t Y[-4 * iostride] = tmp140 + tmp139;\n\t tmp135 = tmp133 - tmp134;\n\t X[8 * iostride] = -(tmp135 - tmp138);\n\t Y[-2 * iostride] = tmp138 + tmp135;\n\t }\n }\n if (i == m) {\n\t fftw_real tmp1;\n\t fftw_real tmp24;\n\t fftw_real tmp8;\n\t fftw_real tmp10;\n\t fftw_real tmp25;\n\t fftw_real tmp26;\n\t fftw_real tmp14;\n\t fftw_real tmp28;\n\t fftw_real tmp23;\n\t fftw_real tmp17;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp1 = X[0];\n\t tmp24 = X[5 * iostride];\n\t {\n\t fftw_real tmp2;\n\t fftw_real tmp3;\n\t fftw_real tmp4;\n\t fftw_real tmp5;\n\t fftw_real tmp6;\n\t fftw_real tmp7;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp2 = X[4 * iostride];\n\t tmp3 = X[6 * iostride];\n\t tmp4 = tmp2 - tmp3;\n\t tmp5 = X[8 * iostride];\n\t tmp6 = X[2 * iostride];\n\t tmp7 = tmp5 - tmp6;\n\t tmp8 = tmp4 + tmp7;\n\t tmp10 = K559016994 * (tmp4 - tmp7);\n\t tmp25 = tmp2 + tmp3;\n\t tmp26 = tmp5 + tmp6;\n\t }\n\t {\n\t fftw_real tmp12;\n\t fftw_real tmp13;\n\t fftw_real tmp22;\n\t fftw_real tmp15;\n\t fftw_real tmp16;\n\t fftw_real tmp21;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp12 = X[iostride];\n\t tmp13 = X[9 * iostride];\n\t tmp22 = tmp12 + tmp13;\n\t tmp15 = X[3 * iostride];\n\t tmp16 = X[7 * iostride];\n\t tmp21 = tmp15 + tmp16;\n\t tmp14 = tmp12 - tmp13;\n\t tmp28 = K559016994 * (tmp22 + tmp21);\n\t tmp23 = tmp21 - tmp22;\n\t tmp17 = tmp15 - tmp16;\n\t }\n\t X[2 * iostride] = tmp1 + tmp8;\n\t {\n\t fftw_real tmp18;\n\t fftw_real tmp20;\n\t fftw_real tmp11;\n\t fftw_real tmp19;\n\t fftw_real tmp9;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp18 = (K587785252 * tmp14) - (K951056516 * tmp17);\n\t tmp20 = (K951056516 * tmp14) + (K587785252 * tmp17);\n\t tmp9 = tmp1 - (K250000000 * tmp8);\n\t tmp11 = tmp9 - tmp10;\n\t tmp19 = tmp10 + tmp9;\n\t X[3 * iostride] = tmp11 - tmp18;\n\t X[iostride] = tmp11 + tmp18;\n\t X[4 * iostride] = tmp19 - tmp20;\n\t X[0] = tmp19 + tmp20;\n\t }\n\t Y[-2 * iostride] = tmp23 - tmp24;\n\t {\n\t fftw_real tmp27;\n\t fftw_real tmp32;\n\t fftw_real tmp30;\n\t fftw_real tmp31;\n\t fftw_real tmp29;\n\t ASSERT_ALIGNED_DOUBLE;\n\t tmp27 = (K951056516 * tmp25) + (K587785252 * tmp26);\n\t tmp32 = (K951056516 * tmp26) - (K587785252 * tmp25);\n\t tmp29 = (K250000000 * tmp23) + tmp24;\n\t tmp30 = tmp28 + tmp29;\n\t tmp31 = tmp29 - tmp28;\n\t Y[0] = -(tmp27 + tmp30);\n\t Y[-4 * iostride] = tmp27 - tmp30;\n\t Y[-iostride] = tmp31 - tmp32;\n\t Y[-3 * iostride] = tmp32 + tmp31;\n\t }\n }\n}\n\nstatic const int twiddle_order[] =\n{1, 2, 3, 4, 5, 6, 7, 8, 9};\nfftw_codelet_desc fftw_hc2hc_forward_10_desc =\n{\n \"fftw_hc2hc_forward_10\",\n (void (*)()) fftw_hc2hc_forward_10,\n 10,\n FFTW_FORWARD,\n FFTW_HC2HC,\n 223,\n 9,\n twiddle_order,\n};\n", "meta": {"hexsha": "19640e2b30a29081a6ec2f66fe2f4c509c176068", "size": 16471, "ext": "c", "lang": "C", "max_stars_repo_path": "original/lib/fftw-2.1.3/rfftw/fhf_10.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_10.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_10.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.3078291815, "max_line_length": 125, "alphanum_fraction": 0.5634144861, "num_tokens": 5274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.6959583376458152, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.34526063687492764}} {"text": "#include \n#include \n#include \n#include \n#define ARRAYD(p) ((double *) (((PyArrayObject *)p)->data)) \n\n/* \n * [INITIALIZATION]\n * ------------------ PROTOTYPES FOR FUNCTIONS AND EXTERNAL VARIABLES -----------------------\n *\n */\n\nint CheckAperture(double* center, int len_rows, int len_cen, double S, int CentralAperture);\ndouble Polyval(double x,double* coeffs, int len_coeffs);\ndouble** MakeArray(int rows, int columns); /* Function that makes/allocates an array of pointers */\ndouble* MakeVector(int nelements); /* Function that makes/allocates a pointer in memory */\ndouble* RangeDetector(double *v,double C,double S,int len_v,int K,int len_rows,int len_cols,int range); /* Detects the range of the calculations */\ndouble* SimpleRangeDetector(double *v,double Length,int len_v,int len_rows,int len_cols,int range);\nvoid FreeArray(double** theArray,int rows); /* Function that frees an array of pointers from memory */\nvoid PixelResampling(double** A,double* pmin,double* pmax,int len_cols); /* Algorithm for pixel resampling */\nvoid BPixelResampling(double** A,double** B,double* pmin,double* pmax,int len_cols); /* Algorithm for pixel resampling */\nvoid SimplePixelResampling(double** A,double* pmin,double* pmax,int len_cols);\nvoid LinearSolver(double** A,double* b,double* x,int length); /* Linear-algebra system solver (returns the solution\n in the x vector) */\ndouble** getQ(double *v,double C,double S,int len_v,int K,int len_cols,int range,double* pmin,double* pmax,int mode); /* Function that gets the Q values (returns a matrix) */\nvoid getJ(double** J,int N,int len_cols); /* Function that calculates the powers of j, the columns */\nvoid getC(double** A,double** Q,double** VarE,double** C_qp,double** J,double* pmin,double* pmax,int K,int N,int len_cols); /* Function that gets the C values (For the L.S.) */\nvoid getX(double** A,double** Q,double** E,double** VarE,double* X,double** J,double* pmin,double* pmax,int K,int N,int len_cols); /* Function that gets the X values */\nvoid getP(double* B,double** Q,double** P,double** J,double* pmin,double* pmax,int K,int N,int len_rows,int len_cols,int mode); /* Computes the light fraction matrix (matrix) */\nvoid getRowSum(double** A,double* RS,double *v,double* pmin,double* pmax,int len_cols,int len_v); /* Computes the sum of the vertical elements in a row */\nvoid getE(double** A,double* RS,double** E,double* pmin,double* pmax,double *v,int len_rows,int len_cols); /* Computes the light fraction estimates E_{ij} */\nvoid getVarRowSum(double** A,double** V,double* VarRS,double* pmin,double* pmax,double RON,double GAIN,int len_cols); /* Same as RowSum but for variances */\nvoid getVarE(double** A,double** E,double* RS,double* VarRS,double** VarE,double** V,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols); /* Same as E for Var(E) */\ndouble CalculateQ(double *v,int k,int i,int j,double C,double S,int len_v,int range); /* Calculates the value of Q for given parameters */\ndouble CalculateC(double** A,double** Q,double** VarE,int m, int l, int n, int k,double** J,double* pmin,double* pmax,int len_cols); /* Same as above for C */\ndouble CalculateX(double** A,double** Q,double** E,double** VarE,int n, int k,double** J,double* pmin,double* pmax,int len_cols); /* Same as above for X */\ndouble Trace(int x,double *v,int len_v,int range); /* Computes the trace for a given value of x */\nvoid getMinMax(double* pmin,double* pmax,double *v,double C, double S,int K,int len_v,int len_cols,int range);\nvoid getSimpleMinMax(double* pmin,double* pmax,double *v,int len_v,int len_cols,int range,double Length);\n\ndouble** MarshIteration(double** M,double** VarImage,double* pmin,double* pmax,double *v,double C,double S,double RON,double GAIN,int len_v,int len_rows,int len_cols,int N,int K,int mode,int range,int debug,double NSigma,int isvarimage); /* Function that iterates the whole Marsh's algorithm */\ndouble** Transpose(double** O,int rowsIN, int colsIN); /* Function that obtains the tranpose of a matrix */\nvoid Renormalize(double** P,double* pmin,double* pmax,int len_rows,int len_cols); \nvoid VarRevision(double** A,double** VarImage,double** V,double* RS,double** P,double* pmin,double* pmax,int len_cols,double RON,double GAIN,int isvarimage); /* Function that revise the variance estimates */\nint OutlierRejection(double** A,double** V,double** P,double** E,double** VarE,double* RS,double* pmin,double* pmax,double NSigma,int len_cols,int debug); /* Out. Rej. algorithm */\ndouble** getSpectrum(double** A,double** VarImage,double** P,double *v,int len_v,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols,double CosmicSigma,int debug,int isvarimage); /* Function that returns the 1-D spectrum matrix given P.\n The first row of the matrix are the pixel values in \n matrix coordinates (lambda), the second row is F_{lambda}\n and the third is var(F_{lambda}) */\ndouble** BgetSpectrum(double** A,double** B,double** P,double *v,int len_v,double* pmin,double* pmax,double RON,double GAIN,int len_rows,int len_cols,double CosmicSigma,int debug); /* Function that returns the 1-D spectrum matrix given P.\n The first row of the matrix are the pixel values in \n matrix coordinates (lambda), the second row is F_{lambda}\n and the third is var(F_{lambda}) */\nvoid getImageVariances(double** A,double** V,double** VarImage,double* pmin,double* pmax,double RON,double GAIN,int len_cols,int isvarimage); /* Function that returns a matrix with the values of the \n initial variances in each pixel */\nvoid getRowSumW(double** A,double** V,double** P,double* pmin,double* pmax,double* RSW,int len_cols); /* Function that returns the denominator in eq. (4) of\n Marsh (1989) */\nvoid getW(double** A,double** P,double** V,double* RSW,double** W,double* pmin,double* pmax,int len_cols); /* Function that returns the weigths for the weighted \n averaged spectra */\nvoid getF(double** W,double** A,double* F,double* pmin,double* pmax,int len_cols); /* Vector containing the fluxes calculated from the \n weighted average */\nvoid getBF(double** W,double** B,double* BF,double* pmin,double* pmax,int len_cols); /* Vector containing the fluxes calculated from the \n weighted average */\nvoid getVarF(double** A,double** W,double** V,double* VarF,double* pmin,double* pmax,int len_cols); /* Vector containing the variances of fluxes calculated \n from the weighted average */\nint CosmicRayRejection(double** A,double** V,double** P,double* F,double* VarF,double CosmicSigma,double* pmin,double* pmax,int len_cols,int debug); /* Cosmic Rays rejection algorithm */\n\nint BCosmicRayRejection(double** A,double** B,double** V,double** P,double* F,double* VarF,double CosmicSigma,double* pmin,double* pmax,int len_cols,int debug); /* Cosmic Rays rejection algorithm */\n\n/* [INITIALIZATION OF A METHOD]\n*------------------------THE OBTAINP METHOD-----------------------------\n* PyObject initialization: We define a PyObject which defines a Method \n* for the Marsh module: The ObtainP method which returns the P[i][j] spatial\n* light fractions back to Python. BE CAREFUL WITH THE INDEXES, remember\n* that i=rows, j=columns. According to Marsh's (1989) variables, j=X and\n* i=Y.\n*----------------------------------------------------------------------\n*/\n\nstatic PyObject *Marsh_ObtainP(PyObject *self, PyObject *args){\n struct timeval tim;\n gettimeofday(&tim, NULL);\n double t1=tim.tv_sec+(tim.tv_usec/1000000.0);\n\tdouble *m,dvalue=0;\n double *v,*pmin,*pmax; // pmin,pmax: FREED (on the MarshIteration function)\n double C,S,Length,RON,GAIN,NSigma;\n int len_v,K,N,len_cols,len_rows,mode,range=-1,debug,isvarimage=0;\n int i,j,real_cols,real_rows,col_min,col_max;\n\tPyObject *marray, *varray;\n\t\n/* \n *--------------------------------THE DATA---------------------------------------\n * After initialization of the PyObject pointers, we wish to recover the following inputs:\n *\n * marray: Vector of the flattened-matrix of the Echelle Spectra data.\n *\n * varray: Vector containing the coefficients of the trace of the spectrum.\n *\n * len_rows: Length of the rows of the flattened-matrix.\n *\n * len_cols: Length of the columns of the flattened-matrix.\n *\n * len_v: Length of the coefficient-vector.\n *\n * Length: Given that the trace is centered on the spectrum, Length gives the length,\n * in pixels from the center, where we'll consider the spectrum.\n *\n * RON: The Read Out Noise of our measurements in electrons.\n *\n * GAIN: The Gain of the detector, in electrons/ADU.\n * \n * mode: Set this to 0 to apply Marsh's Algorithm (curved trace) to the data.\n * Set this to 1 to apply Horne's Algorithm (trace paralell to the rows) to the data.\n *\n * ------------------------------------------------------------------------------\n*/\n\tPyArg_ParseTuple(args,\"OOiiidddddiiii\",&marray,&varray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&NSigma,&S,&N,&mode,&col_min,&col_max);\n if(col_min!=0){\n col_min=col_min+1;\n }\n if(col_max!=0){\n col_max=col_max-1;\n }\n debug=0;\n\tm = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */\n\tv = ARRAYD(varray);\n real_cols=len_cols;\n real_rows=len_rows;\n if(mode!=0)\n\t S=1.0; /* If Horne's algorithm is used, the spacing between\n\t polynomials is 1 */\n Length = CheckAperture(v, len_rows, len_v, S, Length);\n\tK=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S \n\t polynomials, rounding the decimal number, from the center.\n\t Then we multiply this number by 2 (to get the total number\n\t of polynomials up and down the center) and add 1 to get the\n\t middle polynomial (the one corresponding to the center). */\n if(debug!=0){\n\t printf(\"Number of polynomial to fit: %d \\n\",K);\n }\n C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number\n is the polynomial number of the center. */\n\n double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting \n and final column pixels that \"swims in\" and \"out\" of the image, respectively\n (FREED here, later). */\n if(debug!=0){\n printf(\"Range[0]: %f\\n\",Range[0]);\n printf(\"Range[1]: %f\\n\",Range[1]);\n printf(\"len_cols=%d, len_rows=%d \\n\",len_cols,len_rows);\n }\n range=Range[0];\n\n if(Range[0]!=-1){\n if(col_min==0 && col_max==0){\n len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a \n cutted image */\n }\n else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){\n if(Range[0]>=col_min && Range[1]<=col_max){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]col_max){\n range=col_min;\n Range[0]=col_min;\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]>=col_min && Range[1]>col_max){\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n }\n else if(col_min!=0 && col_max==0){\n if(Range[0]>=col_min){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]1){\n theArray[i*len_cols+j]=0;\n }\n } \n }\n FreeArray(PFinal,len_rows);\n free(Range);\n/* End of the matrix-to-vector conversion part of the code. Everything's ok up to here...now I have my theArray[i][j] array (matrix) ready to be called...*/\n\n\n/* Finally, we create a Python \"Object\" List that contains the P coefficients and return it back to Python */\n\n PyObject *lst = PyList_New(len_rows*len_cols);\n PyObject *num;\n if (!lst)\n return NULL;\n for (i = 0; i < len_rows*len_cols; i++) {\n num=PyFloat_FromDouble(theArray[i]);\n if (!num) {\n Py_DECREF(lst);\n return NULL;\n }\n PyList_SET_ITEM(lst, i, num);\n }\n free(theArray);\n PyObject *MyResult = Py_BuildValue(\"O\",lst);\n Py_DECREF(lst);\n return MyResult;\n}\n\n/* [INITIALIZATION OF A METHOD]\n * ------------------------THE OBTAINSpectrum METHOD-----------------------------\n */\n\nstatic PyObject *Marsh_ObtainSpectrum(PyObject *self, PyObject *args){\n struct timeval tim;\n gettimeofday(&tim, NULL);\n\tint i,j,real_cols,real_rows,col_min,col_max;\n double t1=tim.tv_sec+(tim.tv_usec/1000000.0),dvalue=0;\n\tdouble *mflat,*pflat;\n double *v,*pmin,*pmax; // (pmin,pmax) freed here, later.\n double Length,RON,GAIN,CosmicSigma,S,C;\n int len_v,len_cols,len_rows,K,range=-1,debug,isvarimage=0;\n\tPyObject *parray, *marray,*varray;\n/* \n *--------------------------------THE DATA---------------------------------------\n * After initialization of the PyObject pointers, we wish to recover the following inputs:\n *\n * marray: Vector of the flattened-matrix of the Echelle Spectra data.\n *\n * varray: Vector containing the coefficients of the trace of the spectrum.\n *\n * parray: Vector of the flattened-matrix of the Echelle Spectra P_{ij} coefficents.\n *\n * len_rows: Length of the rows of the flattened-matrix.\n *\n * len_cols: Length of the columns of the flattened-matrix.\n *\n * len_v: Length of the coefficient-vector.\n * \n * Length: Aperture to be used in the obtention of the spectrum.\n *\n * RON: The Read Out Noise of our measurements.\n * \n * GAIN: The Gain of the detector, in electrons/ADU.\n * \n * S: Spacing of the polynomials obtained in the ObtainP function.\n * \n * CosmicSigma: Number of times sigma is multiplied by to reject Cosmic Rays.\n *\n * ------------------------------------------------------------------------------\n*/\n\tPyArg_ParseTuple(args,\"OOOiiidddddii\",&marray,&varray,&parray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&S,&CosmicSigma,&col_min,&col_max);\n if(col_min!=0){\n col_min=col_min+1;\n }\n if(col_max!=0){\n col_max=col_max-1;\n }\n debug=0;\n\tpflat = ARRAYD(parray); /* We convert our PyObject struct pointers to C-vector array */\n\tmflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */\n\tv = ARRAYD(varray);\n real_cols=len_cols;\n real_rows=len_rows;\n Length = CheckAperture(v, len_rows, len_v, S, Length);\n/* Start of the algorithm for the spectrum obtention (faster with the transpose!): */\n\t\n\tK=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S \n\t polynomials, rounding the decimal number, from the center.\n\t Then we multiply this number by 2 (to get the total number\n\t of polynomials up and down the center) and add 1 to get the\n\t middle polynomial (the one corresponding to the center). */\n C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number\n is the polynomial number of the center. */\n range=0;\n double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the\n detected starting and final column pixels that \"swims in\" and \"out\" of the image, respectively (FREED here) */\n range=Range[0];\n if(debug!=0){\n printf(\"Range[0]: %f\\n\",Range[0]);\n printf(\"Range[1]: %f\\n\",Range[1]);\n dvalue=1018.0;\n } \n\n if(Range[0]!=-1){\n if(col_min==0 && col_max==0){\n len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a \n cutted image */\n }\n else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){\n if(Range[0]>=col_min && Range[1]<=col_max){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]col_max){\n range=col_min;\n Range[0]=col_min;\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]>=col_min && Range[1]>col_max){\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n }\n else if(col_min!=0 && col_max==0){\n if(Range[0]>=col_min){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]Range[1])\n\t\t theArray[i*real_cols+j]=0;\n\t\telse\n theArray[i*real_cols+j]=Spectrum[i][j-range];\n }\n } \n }\n\n FreeArray(Spectrum,3);\n free(Range);\n\n/* Finally, we create a Python \"Object\" List that contains the P coefficients and return it back to Python */\n\n PyObject *lst = PyList_New(real_cols*3);\n if (!lst)\n return NULL;\n for (i = 0; i < 3*real_cols; i++) {\n PyObject *num = PyFloat_FromDouble(theArray[i]);\n if (!num) {\n Py_DECREF(lst);\n return NULL;\n }\n PyList_SET_ITEM(lst, i, num);\n }\n free(theArray);\n free(pmin); \n free(pmax);\n PyObject *MyResult = Py_BuildValue(\"Oi\",lst,real_cols);\n Py_DECREF(lst);\n return MyResult;\n}\n\n\n/* [INITIALIZATION OF A METHOD]\n*------------------------THE SOBTAINP METHOD-----------------------------\n* PyObject initialization: We define a PyObject which defines a Method \n* for the Marsh module: The ObtainP method which returns the P[i][j] spatial\n* light fractions back to Python. BE CAREFUL WITH THE INDEXES, remember\n* that i=rows, j=columns. According to Marsh's (1989) variables, j=X and\n* i=Y.\n*----------------------------------------------------------------------\n*/\n\nstatic PyObject *Marsh_SObtainP(PyObject *self, PyObject *args){\n struct timeval tim;\n gettimeofday(&tim, NULL);\n double t1=tim.tv_sec+(tim.tv_usec/1000000.0);\n\tdouble *m,*varianceimage,*bimage,dvalue=0;\n double *v,*pmin,*pmax; // pmin,pmax: FREED (on the MarshIteration function)\n double C,S,Length,RON,GAIN,NSigma;\n int len_v,K,N,len_cols,len_rows,mode,range=-1,debug,isvarimage=1;\n int i,j,real_cols,real_rows,col_min,col_max;\n\tPyObject *marray, *varray,*vararray,*barray;\n\t\n/* \n *--------------------------------THE DATA---------------------------------------\n * After initialization of the PyObject pointers, we wish to recover the following inputs:\n *\n * marray: Vector of the flattened-matrix of the Echelle Spectra data.\n *\n * varray: Vector containing the coefficients of the trace of the spectrum.\n *\n * len_rows: Length of the rows of the flattened-matrix.\n *\n * len_cols: Length of the columns of the flattened-matrix.\n *\n * len_v: Length of the coefficient-vector.\n *\n * Length: Given that the trace is centered on the spectrum, Length gives the length,\n * in pixels from the center, where we'll consider the spectrum.\n *\n * RON: The Read Out Noise of our measurements in electrons.\n *\n * GAIN: The Gain of the detector, in electrons/ADU.\n * \n * mode: Set this to 0 to apply Marsh's Algorithm (curved trace) to the data.\n * Set this to 1 to apply Horne's Algorithm (trace paralell to the rows) to the data.\n *\n * ------------------------------------------------------------------------------\n*/\n\tPyArg_ParseTuple(args,\"OOOOiiidddddiiii\",&marray,&barray,&vararray,&varray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&NSigma,&S,&N,&mode,&col_min,&col_max);\n if(col_min!=0){\n col_min=col_min+1;\n }\n if(col_max!=0){\n col_max=col_max-1;\n }\n debug=0;\n\tm = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */\n\tv = ARRAYD(varray);\n\tvarianceimage = ARRAYD(vararray);\n\tbimage = ARRAYD(barray);\n real_cols=len_cols;\n real_rows=len_rows; \n if(mode!=0)\n\t S=1.0; /* If Horne's algorithm is used, the spacing between\n\t polynomials is 1 */\n Length = CheckAperture(v, len_rows, len_v, S, Length);\n\tK=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S \n\t polynomials, rounding the decimal number, from the center.\n\t Then we multiply this number by 2 (to get the total number\n\t of polynomials up and down the center) and add 1 to get the\n\t middle polynomial (the one corresponding to the center). */\n if(debug!=0){\n\t printf(\"Number of polynomial to fit: %d \\n\",K);\n dvalue=1018.0;\n }\n C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number\n is the polynomial number of the center. */\n\n double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the detected starting \n and final column pixels that \"swims in\" and \"out\" of the image, respectively\n (FREED here, later). */\n if(debug!=0){\n printf(\"Range[0]: %f\\n\",Range[0]);\n printf(\"Range[1]: %f\\n\",Range[1]);\n printf(\"len_cols=%d, len_rows=%d \\n\",len_cols,len_rows);\n }\n range=Range[0];\n\n if(Range[0]!=-1){\n if(col_min==0 && col_max==0){\n len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a \n cutted image */\n }\n else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){\n if(Range[0]>=col_min && Range[1]<=col_max){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]col_max){\n range=col_min;\n Range[0]=col_min;\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]>=col_min && Range[1]>col_max){\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n }\n else if(col_min!=0 && col_max==0){\n if(Range[0]>=col_min){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]1){\n theArray[i*len_cols+j]=0;\n }\n } \n }\n FreeArray(PFinal,len_rows);\n free(Range);\n/* End of the matrix-to-vector conversion part of the code. Everything's ok up to here...now I have my theArray[i][j] array (matrix) ready to be called...*/\n\n\n/* Finally, we create a Python \"Object\" List that contains the P coefficients and return it back to Python */\n\n PyObject *lst = PyList_New(len_rows*len_cols);\n PyObject *num;\n if (!lst)\n return NULL;\n for (i = 0; i < len_rows*len_cols; i++) {\n num=PyFloat_FromDouble(theArray[i]);\n if (!num) {\n Py_DECREF(lst);\n return NULL;\n }\n PyList_SET_ITEM(lst, i, num);\n }\n free(theArray);\n PyObject *MyResult = Py_BuildValue(\"O\",lst);\n Py_DECREF(lst);\n return MyResult;\n}\n\n/* [INITIALIZATION OF A METHOD]\n * ------------------------THE SOBTAINSpectrum METHOD-----------------------------\n */\n\nstatic PyObject *Marsh_SObtainSpectrum(PyObject *self, PyObject *args){\n struct timeval tim;\n gettimeofday(&tim, NULL);\n\tint i,j,real_cols,real_rows,col_min,col_max;\n double t1=tim.tv_sec+(tim.tv_usec/1000000.0),dvalue=0;\n\tdouble *mflat,*varflat,*pflat,*bflat;\n double *v,*pmin,*pmax; // (pmin,pmax) freed here, later.\n double Length,RON,GAIN,CosmicSigma,S,C;\n int len_v,len_cols,len_rows,K,range=-1,debug,isvarimage=1;\n\tPyObject *parray, *marray,*varray,*vararray,*barray;\n/* \n *--------------------------------THE DATA---------------------------------------\n * After initialization of the PyObject pointers, we wish to recover the following inputs:\n *\n * marray: Vector of the flattened-matrix of the Echelle Spectra data.\n *\n * varray: Vector containing the coefficients of the trace of the spectrum.\n *\n * parray: Vector of the flattened-matrix of the Echelle Spectra P_{ij} coefficents.\n *\n * len_rows: Length of the rows of the flattened-matrix.\n *\n * len_cols: Length of the columns of the flattened-matrix.\n *\n * len_v: Length of the coefficient-vector.\n * \n * Length: Aperture to be used in the obtention of the spectrum.\n *\n * RON: The Read Out Noise of our measurements.\n * \n * GAIN: The Gain of the detector, in electrons/ADU.\n * \n * S: Spacing of the polynomials obtained in the ObtainP function.\n * \n * CosmicSigma: Number of times sigma is multiplied by to reject Cosmic Rays.\n *\n * ------------------------------------------------------------------------------\n*/\n\tPyArg_ParseTuple(args,\"OOOOOiiidddddii\",&marray,&barray,&vararray,&varray,&parray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&S,&CosmicSigma,&col_min,&col_max);\n if(col_min!=0){\n col_min=col_min+1;\n }\n if(col_max!=0){\n col_max=col_max-1;\n }\n debug=0;\n\tpflat = ARRAYD(parray); /* We convert our PyObject struct pointers to C-vector array */\n\tmflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */\n varflat = ARRAYD(vararray);\n\tbflat = ARRAYD(barray);\n\tv = ARRAYD(varray);\n real_cols=len_cols;\n real_rows=len_rows;\n Length = CheckAperture(v, len_rows, len_v, S, Length);\n/* Start of the algorithm for the spectrum obtention (faster with the transpose!): */\n\t\n\tK=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S \n\t polynomials, rounding the decimal number, from the center.\n\t Then we multiply this number by 2 (to get the total number\n\t of polynomials up and down the center) and add 1 to get the\n\t middle polynomial (the one corresponding to the center). */\n C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number\n is the polynomial number of the center. */\n range=0;\n double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the\n detected starting and final column pixels that \"swims in\" and \"out\" of the image, respectively (FREED here) */\n range=Range[0];\n if(debug!=0){\n printf(\"Range[0]: %f\\n\",Range[0]);\n printf(\"Range[1]: %f\\n\",Range[1]);\n dvalue=1018.0;\n } \n\n if(Range[0]!=-1){\n if(col_min==0 && col_max==0){\n len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a \n cutted image */\n }\n else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){\n if(Range[0]>=col_min && Range[1]<=col_max){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]col_max){\n range=col_min;\n Range[0]=col_min;\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]>=col_min && Range[1]>col_max){\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n }\n else if(col_min!=0 && col_max==0){\n if(Range[0]>=col_min){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]Range[1])\n\t\t theArray[i*real_cols+j]=0;\n\t\telse\n theArray[i*real_cols+j]=Spectrum[i][j-range];\n }\n } \n }\n\n FreeArray(Spectrum,3);\n free(Range);\n\n/* Finally, we create a Python \"Object\" List that contains the P coefficients and return it back to Python */\n\n PyObject *lst = PyList_New(real_cols*3);\n if (!lst)\n return NULL;\n for (i = 0; i < 3*real_cols; i++) {\n PyObject *num = PyFloat_FromDouble(theArray[i]);\n if (!num) {\n Py_DECREF(lst);\n return NULL;\n }\n PyList_SET_ITEM(lst, i, num);\n }\n free(theArray);\n free(pmin); \n free(pmax);\n PyObject *MyResult = Py_BuildValue(\"Oi\",lst,real_cols);\n Py_DECREF(lst);\n return MyResult;\n}\n\nstatic PyObject *Marsh_BObtainSpectrum(PyObject *self, PyObject *args){\n struct timeval tim;\n gettimeofday(&tim, NULL);\n\tint i,j,real_cols,real_rows,col_min,col_max;\n double t1=tim.tv_sec+(tim.tv_usec/1000000.0),dvalue=0;\n\tdouble *mflat,*pflat,*bflat;\n double *v,*pmin,*pmax; // (pmin,pmax) freed here, later.\n double Length,RON,GAIN,CosmicSigma,S,C;\n int len_v,len_cols,len_rows,K,range=-1,debug;\n\tPyObject *parray, *marray,*varray,*barray;\n/* \n *--------------------------------THE DATA---------------------------------------\n * After initialization of the PyObject pointers, we wish to recover the following inputs:\n *\n * marray: Vector of the flattened-matrix of the Echelle Spectra data.\n *\n * varray: Vector containing the coefficients of the trace of the spectrum.\n *\n * parray: Vector of the flattened-matrix of the Echelle Spectra P_{ij} coefficents.\n *\n * len_rows: Length of the rows of the flattened-matrix.\n *\n * len_cols: Length of the columns of the flattened-matrix.\n *\n * len_v: Length of the coefficient-vector.\n * \n * Length: Aperture to be used in the obtention of the spectrum.\n *\n * RON: The Read Out Noise of our measurements.\n * \n * GAIN: The Gain of the detector, in electrons/ADU.\n * \n * S: Spacing of the polynomials obtained in the ObtainP function.\n * \n * CosmicSigma: Number of times sigma is multiplied by to reject Cosmic Rays.\n *\n * ------------------------------------------------------------------------------\n*/\n\tPyArg_ParseTuple(args,\"OOOOiiidddddii\",&marray,&varray,&parray,&barray,&len_rows,&len_cols,&len_v,&Length,&RON,&GAIN,&S,&CosmicSigma,&col_min,&col_max);\n\tif(col_min!=0){\n col_min=col_min+1;\n }\n if(col_max!=0){\n col_max=col_max-1;\n }\n debug=0;\n\tpflat = ARRAYD(parray); /* We convert our PyObject struct pointers to C-vector array */\n\tmflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */\n\tbflat = ARRAYD(barray); /* We convert our PyObject struct pointers to C-vector array */\n\tv = ARRAYD(varray);\n real_cols=len_cols;\n real_rows=len_rows;\n Length = CheckAperture(v, len_rows, len_v, S, Length);\n/* Start of the algorithm for the spectrum obtention (faster with the transpose!): */\n\t\n\tK=(int)(2*(int)((Length/S)+0.5)+1); /* The number of polynomials. The idea is to form n=Length/S \n\t polynomials, rounding the decimal number, from the center.\n\t Then we multiply this number by 2 (to get the total number\n\t of polynomials up and down the center) and add 1 to get the\n\t middle polynomial (the one corresponding to the center). */\n C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number\n is the polynomial number of the center. */\n range=0;\n double* Range = RangeDetector(v,C,S,len_v,K,len_rows,len_cols,range); /* This vector containts the\n detected starting and final column pixels that \"swims in\" and \"out\" of the image, respectively (FREED here) */\n range=Range[0];\n if(debug!=0){\n printf(\"Range[0]: %f\\n\",Range[0]);\n printf(\"Range[1]: %f\\n\",Range[1]);\n dvalue=0.0;\n } \n\n if(Range[0]!=-1){\n if(col_min==0 && col_max==0){\n len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a \n cutted image */\n }\n else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){\n if(Range[0]>=col_min && Range[1]<=col_max){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]col_max){\n range=col_min;\n Range[0]=col_min;\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]>=col_min && Range[1]>col_max){\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n }\n else if(col_min!=0 && col_max==0){\n if(Range[0]>=col_min){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]Range[1])\n\t\t theArray[i*real_cols+j]=0;\n\t\telse\n theArray[i*real_cols+j]=Spectrum[i][j-range];\n }\n } \n }\n\n FreeArray(Spectrum,4);\n free(Range);\n\n/* Finally, we create a Python \"Object\" List that contains the P coefficients and return it back to Python */\n\n PyObject *lst = PyList_New(real_cols*4);\n if (!lst)\n return NULL;\n for (i = 0; i < 4*real_cols; i++) {\n PyObject *num = PyFloat_FromDouble(theArray[i]);\n if (!num) {\n Py_DECREF(lst);\n return NULL;\n }\n PyList_SET_ITEM(lst, i, num);\n }\n free(theArray);\n free(pmin); \n free(pmax);\n PyObject *MyResult = Py_BuildValue(\"Oi\",lst,real_cols);\n Py_DECREF(lst);\n return MyResult;\n}\n\nstatic PyObject *Marsh_SimpleExtraction(PyObject *self, PyObject *args){\n struct timeval tim;\n gettimeofday(&tim, NULL);\n\tint i,j,real_cols,debug=0,col_min,col_max;\n double t1=tim.tv_sec+(tim.tv_usec/1000000.0),vMin,vMax,dvalue=0;\n\tdouble *mflat;\n double *v;\n double Length,C,S;\n int len_v,len_cols,len_rows,K,range;\n\tPyObject *marray,*varray;\n/* \n *--------------------------------THE DATA---------------------------------------\n * After initialization of the PyObject pointers, we wish to recover the following inputs:\n *\n * marray: Vector of the flattened-matrix of the Echelle Spectra data.\n *\n * varray: Vector containing the coefficients of the trace of the spectrum.\n *\n * len_rows: Length of the rows of the flattened-matrix.\n *\n * len_cols: Length of the columns of the flattened-matrix.\n *\n * len_v: Length of the coefficient-vector.\n * \n * Length: Aperture (in pixels) to be taken from the center to cover the entire spectrum.\n *\n * ------------------------------------------------------------------------------\n*/\n\tPyArg_ParseTuple(args,\"OOiiidii\",&marray,&varray,&len_rows,&len_cols,&len_v,&Length,&col_min,&col_max);\n if(col_min!=0){\n col_min=col_min+1;\n }\n if(col_max!=0){\n col_max=col_max-1;\n }\n range=0;\n\tmflat = ARRAYD(marray); /* We convert our PyObject struct pointers to C-vector array */\n\tv = ARRAYD(varray);\n\treal_cols=len_cols;\n\tS=1.0;\n Length = CheckAperture(v, len_rows, len_v, S, Length);\n\tK=(int)(2*(int)((Length/S))+1);\n\n C=-(S*(1.0+(((double)K-1.0)/2.0))); /* We get the C constant for the Q coefficients. This number\n is the polynomial number of the center. */\n\n double* Range = SimpleRangeDetector(v,Length,len_v,len_rows,len_cols,range); /* This vector\n containts the detected starting and final column pixels that \"swims in\" and \"out\" of the image, respectively (F) */\n range=Range[0];\n\n if(debug!=0){\n printf(\"Range[0]: %f\\n\",Range[0]);\n printf(\"Range[1]: %f\\n\",Range[1]);\n dvalue=1018.0;\n } \n\n if(Range[0]!=-1){\n if(col_min==0 && col_max==0){\n len_cols=Range[1]-Range[0]+1; /* If the column presents problems, we start by creating a \n cutted image */\n }\n else if((col_min!=0 && col_max!=0) || (col_min==0 && col_max!=0)){\n if(Range[0]>=col_min && Range[1]<=col_max){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]col_max){\n range=col_min;\n Range[0]=col_min;\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]>=col_min && Range[1]>col_max){\n Range[1]=col_max;\n len_cols=Range[1]-Range[0]+1;\n }\n }\n else if(col_min!=0 && col_max==0){\n if(Range[0]>=col_min){\n len_cols=Range[1]-Range[0]+1;\n }\n else if(Range[0]=range && i= 0.5+S)\n return 0.0;\n else if(d+S <= 0.5)\n return S;\n else if(d <= 0.5){\n return ((S/2.0)+(0.5-d)-(pow(0.5-d,2.0)/(2.0*S)));\n }\n else if(d > 0.5){\n return ((0.5-d)+(pow(0.5-d,2.0)/(2.0*S))+S/2);\n }\n else\n return -999;\n}\n\ndouble** getQ(double *v,double C,double S,int len_v,int K,int len_cols,int range,double* pmin,double* pmax,int mode){\n int i,j,vMin,vMax,contador,k;\n contador=0;\n for(j=0;j=SigmaSquared){\n A[j][i]=-9999;\n counter++;\n }\n }\n }\n }\n if(debug!=0){\n printf(\"Number of outliers found: %d \\n\",counter);\n printf(\"Chi-squared of the fit: %f \\n\",TotalSum);\n }\n if(counter==0){\n return 0;\n }\n return 1;\n}\n/* [FUNCTION]\n * ------------------------ Marsh's algorithm----------------------------------\n * Here we obtain images (analogous to the image of pixel count values, M) for\n * the following:\n * \n * E_ij: Matrix image (same ij coordiantes as M) containing the estimated light\n * fractions (recall this is an estimate of P_ij, the model of this light\n * fraction.\n *\n * Var(E_ij): Matrix image (same ij coordiantes as M) containing the estimated light\n * fraction's variances.\n *\n * P_ij: Matrix image (same ij coordiantes as M) containing the modeled light\n * fractions.\n * ---------------------------------------------------------------------------\n */\n\ndouble** MarshIteration(double** M,double** VarImage,double* pmin,double* pmax,double *v,double C,double S,double RON,double GAIN,int len_v,int len_rows,int len_cols,int N,int K,int mode,int range,int debug,double NSigma, int isvarimage){\nint Iteration=1,IterNum=0;\ndouble** P=MakeArray(len_cols,len_rows); // FREED on Transpose.\ndouble** V=MakeArray(len_cols,len_rows); // FREED here, later.\ndouble** E=MakeArray(len_cols,len_rows); // FREED here, later.\ndouble** VarE=MakeArray(len_cols,len_rows); // FREED here, later.\ndouble** C_qp=MakeArray(N*K,N*K); /* Matrix that contains the coefficients for the linear system (FREED here, later) */\ndouble** J=MakeArray(2*(N-1)+1,len_cols); // FREED here, later.\n\n // All from here to the end, FREED, later.\n\ndouble* B=MakeVector(N*K); /* Vector with the solutions to the linear system. */\ndouble* X=MakeVector(N*K); /* Vector with the coefficients for the linear system. Given \n these elements, we wish to solve the C_qp B_q=X_q system */\ndouble* RS=MakeVector(len_cols); /* Vector that saves the sum of pixel values of the rows\n (columns) of the transposed (untransposed) M matrix. */\ndouble* VarRS=MakeVector(len_cols); /* Vector that saves the sum of pixel values variances of the rows\n (columns) of the transposed (untransposed) M matrix */\nPixelResampling(M,pmin,pmax,len_cols);\ndouble** Q=getQ(v,C,S,len_v,K,len_cols,range,pmin,pmax,mode); /* First we obtain the Q matrix (note: independant of fit) */\ngetJ(J,N,len_cols);\ngetImageVariances(M,V,VarImage,pmin,pmax,RON,GAIN,len_cols,isvarimage);\ngetRowSum(M,RS,v,pmin,pmax,len_cols,len_v);\ngetE(M,RS,E,pmin,pmax,v,len_rows,len_cols);\ngetVarRowSum(M,V,VarRS,pmin,pmax,RON,GAIN,len_cols);\ngetVarE(M,E,RS,VarRS,VarE,V,pmin,pmax,RON,GAIN,len_rows,len_cols); \n while(Iteration != 0){ /* If Iteration=1, we continue iterating! */\n IterNum+=1;\n if(debug!=0){\n printf(\"------------------- \\n\");\n printf(\"Iteration number %d \\n\",IterNum);\n printf(\"------------------- \\n\");\n printf(\"Obtaining the profiles...\\n\"); /* We obtain Var(E_ij), the variances of E_ij on each pixel */\n }\n getC(M,Q,VarE,C_qp,J,pmin,pmax,K,N,len_cols); /* We obtain C_qp, the matrix with the C coefficients for\n the fit */\n getX(M,Q,E,VarE,X,J,pmin,pmax,K,N,len_cols); /* We obtain X_q, the vector with the coefficients for the fit */\n LinearSolver(C_qp,X,B,N*K); /* Solve the linear system C_qp*B_q=X_q, obtaining the\n B_q vector */\n getP(B,Q,P,J,pmin,pmax,K,N,len_rows,len_cols,mode); /* We obtain P, the model light fractions on each pixel */\n Renormalize(P,pmin,pmax,len_rows,len_cols);\n\t VarRevision(M,VarImage,V,RS,P,pmin,pmax,len_cols,RON,GAIN,isvarimage);\n\t getVarRowSum(M,V,VarRS,pmin,pmax,RON,GAIN,len_cols);\n\t getVarE(M,E,RS,VarRS,VarE,V,pmin,pmax,RON,GAIN,len_rows,len_cols); \n\t if(IterNum!=1)\n\t Iteration=OutlierRejection(M,V,P,E,VarE,RS,pmin,pmax,NSigma,len_cols,debug);\n }\nFreeArray(E,len_cols); /* Free our vectors and matrices */\nFreeArray(VarE,len_cols);\nFreeArray(C_qp,N*K);\nFreeArray(Q,K);\nFreeArray(J,2*(N-1)+1);\nFreeArray(M,len_cols);\nFreeArray(VarImage,len_cols);\nFreeArray(V,len_cols);\nfree(B);\nfree(X);\nfree(RS);\nfree(VarRS);\nfree(pmin);\nfree(pmax);\nif(debug!=0){\n printf(\"Going out of MarshIteration...\\n\");\n}\nreturn Transpose(P,len_cols,len_rows);\n}\n\nvoid Renormalize(double** P,double* pmin,double* pmax,int len_rows,int len_cols){\n int vMin,vMax,j,i;\n double PartialSum;\n for(j=0;j=fluxcount){\n Ratio=(count-CosmicSigma*countsigma)-(fluxcount+CosmicSigma*fluxcountsigma);\n if(Ratio>0){\n detection=1;\n }\n }\n else{\n Ratio=(fluxcount-CosmicSigma*fluxcountsigma)-(count+CosmicSigma*countsigma);\n if(Ratio>0){\n detection=1;\n }\n }\n if(detection==1){\n if(DummyRatio=fluxcount){\n Ratio=(count-CosmicSigma*countsigma)-(fluxcount+CosmicSigma*fluxcountsigma);\n if(Ratio>0){\n detection=1;\n }\n }\n else{\n Ratio=(fluxcount-CosmicSigma*fluxcountsigma)-(count+CosmicSigma*countsigma);\n if(Ratio>0){\n detection=1;\n }\n }\n if(detection==1){\n if(DummyRatio=len_rows){\n CentralAperture = CentralAperture - 1;\n K = (int)((int)((CentralAperture/S)+0.5));\n lowrow = (int)(center[i]-S*(K+1.0)-0.5);\n i = i-1;\n } \n if(lowrow<0 && uprow>=len_rows){\n CentralAperture = CentralAperture - 1;\n }\n if(lowrow<0 && uprowTrace(len_cols/2,v,len_v,range) && ((int)(((Trace(0,v,len_v,range)+C)+(double)(K)*S)+0.5)>=len_rows || (int)(((Trace(len_cols-1,v,len_v,range)+C)+(double)(K)*S)+0.5)>=len_rows)){ // The problem is on an upper trace\n for(j=0;j0 ){\n ReturningVector[1]=j-1;\n break;\n }\n }\n }\n else if(Trace(0,v,len_v,range)0 ){\n ReturningVector[1]=j-1;\n break;\n }\n }\n }\n else{\n ReturningVector[0]=-1;\n }\nreturn ReturningVector;\n}\n\ndouble* SimpleRangeDetector(double *v,double Length,int len_v,int len_rows,int len_cols,int range){\nint j,s=0,uplim=0,downlim=0;\ndouble* ReturningVector = MakeVector(2);\nReturningVector[1]=len_cols;\n if(Trace(0,v,len_v,range)>Trace(len_cols/2,v,len_v,range) && ((int)((Trace(0,v,len_v,range)+Length)+0.5)>=len_rows || (int)((Trace(len_cols-1,v,len_v,range)+Length)+0.5)>=len_rows)){ // The problem is on an upper trace\n for(j=0;j0 ){\n ReturningVector[1]=j-1;\n break;\n }\n }\n }\n else if(Trace(0,v,len_v,range)0 ){\n ReturningVector[1]=j-1;\n break;\n }\n }\n }\n else{\n ReturningVector[0]=-1;\n }\nreturn ReturningVector;\n}\n\n", "meta": {"hexsha": "02796a1f2b004152e0bb53d5d1eee78c0cf74626", "size": 97260, "ext": "c", "lang": "C", "max_stars_repo_path": "utils/OptExtract/Marsh.c", "max_stars_repo_name": "afeinstein20/ceres", "max_stars_repo_head_hexsha": "e55150c587782cbecfd45c21ba0ce0023e54c3a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2016-09-09T04:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:25:49.000Z", "max_issues_repo_path": "utils/OptExtract/Marsh.c", "max_issues_repo_name": "afeinstein20/ceres", "max_issues_repo_head_hexsha": "e55150c587782cbecfd45c21ba0ce0023e54c3a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 29.0, "max_issues_repo_issues_event_min_datetime": "2016-09-10T15:30:29.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-02T14:55:53.000Z", "max_forks_repo_path": "utils/OptExtract/Marsh.c", "max_forks_repo_name": "afeinstein20/ceres", "max_forks_repo_head_hexsha": "e55150c587782cbecfd45c21ba0ce0023e54c3a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2016-09-09T23:58:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-20T17:50:35.000Z", "avg_line_length": 41.1944091487, "max_line_length": 329, "alphanum_fraction": 0.5253341559, "num_tokens": 24848, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34488799028809203}} {"text": "/*-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.\n\n File Name : leef.c\n\nPurpose: embedding learning on a weighted graph \n\nCreation Date : 15-01-2017\n\nLast Modified : Wed 15 Mar 2017 03:07:53 PM CDT\n\nCreated By : Huan Gui (huangui2@illinois.edu) \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 \"ransampl.h\"\n\n#define MAX_STRING 100\n#define MAX_SENTENCE 1000\n#define MAX_SIGMOID 8.0\n#define MAX_N_NODE_TYPE 10\n#define MAX_N_EDGE_TYPE 10 // maximum number of edge types\n\ntypedef double real; // Precision of float numbers\n\nconst int mini_batch = 1;\nconst int sigmoid_table_size = 2000;\nconst long hash_size = 30000000; // For each type of nodes, there are 3M nodes\nconst int node_count_inc = 1000, neighbor_initial_count = 10;\nconst long neg_table_size = 1e8;\nconst long edge_table_size = 1e9;\nconst real sigmoid_coeff = sigmoid_table_size / MAX_SIGMOID / 2.0;\nreal sample_power = 0.75; // defined for negative sampling as the power of frequency\nreal prior_power = 1; // defined for negative sampling as the power of frequency\n\nreal max_sim = 0.5;\nreal max_iteration = 10;\n\nstruct ClassNeighbor {\n long node_id;\n long edge_id;\n};\n\nstruct ClassNode {\n char * name; \n real degree;\n real weight; // for the authority of nodes \n int *n_neighbor;\n int * max_n_neighbor;\n ClassNeighbor **neighbors;\n};\n\nstruct ClassEdge {\n long src_id;\n long dst_id;\n real weight;\n real t_weight;\n};\n\nint n_node_type, n_edge_type;\n\n// the node type for source node and dest node\nint edge_node_type[MAX_N_EDGE_TYPE][2];\n\nchar output_folder[MAX_SENTENCE], input_folder[MAX_SENTENCE];\nchar embed_folder[MAX_SENTENCE], weight_folder[MAX_SENTENCE]; \nchar train_network_file[MAX_N_EDGE_TYPE][MAX_SENTENCE];\nchar input_fix_embedding_file[MAX_SENTENCE];\nchar input_node_weight_file[MAX_SENTENCE];\nchar output_embedding[MAX_N_NODE_TYPE][MAX_SENTENCE];\nchar query_file[MAX_SENTENCE];\n\nstruct ClassNode* nodes[MAX_N_NODE_TYPE];\nstruct ClassEdge* edges[MAX_N_EDGE_TYPE];\n\nset::set query;\n\nint author_type, term_type, paper_type, term_paper_edge_type;\nint num_threads = 20, dim = 200;\nint negative_k = 5;\n\n// create hash table and negative table for each type of nodes and edges, respectively\nlong *node_hash_table[MAX_N_NODE_TYPE];\nlong *neg_table[MAX_N_NODE_TYPE];\n\nransampl_ws *edge_alias[MAX_N_EDGE_TYPE];\nransampl_ws *topic_edge_alias;\n\n// The maximum size of each types of nodes, and the current count\nlong max_sz_node[MAX_N_NODE_TYPE], node_cnt[MAX_N_NODE_TYPE];\n\n// total samples of edges to update parameters, and the current samples\nlong total_samples = 15, current_sample, edge_cnt[MAX_N_EDGE_TYPE];\nreal init_alpha = 0.025, alpha;\n\n// the embedding of each type of nodes, relative to different types of nodes\nreal *emb_node[MAX_N_NODE_TYPE];\n\nreal *sigmoid_table;\n\n//specify the types of nodes, and edge names\nchar node_names[MAX_N_NODE_TYPE][MAX_STRING];\nchar edge_names[MAX_N_EDGE_TYPE][MAX_STRING];\n\nbool output_types[MAX_N_NODE_TYPE];\nbool load_types[MAX_N_NODE_TYPE];\nbool node_weight[MAX_N_NODE_TYPE];\nbool edge_weight[MAX_N_NODE_TYPE];\nbool valid_edge[MAX_N_NODE_TYPE][MAX_N_NODE_TYPE];\n\nreal beta[MAX_N_NODE_TYPE];\nreal node_sample_power[MAX_N_NODE_TYPE];\n\nconst gsl_rng_type * gsl_T;\ngsl_rng * gsl_r;\n\nclock_t start;\n\n// the hash function is the same for all types of nodes\ninline unsigned long GetHash(char *input) {\n unsigned long hash = 5381;\n char c;\n while ((c = *input) != '\\0') {\n hash = ((hash << 5) + hash) + c; /* hash * 33 + c */\n ++input;\n }\n return hash % hash_size;\n}\n\n// initialize the hash table for all types of nodes\nvoid InitHashTable() {\n for (int node_type = 0; node_type < n_node_type; ++node_type) {\n node_hash_table[node_type] = (long *) malloc(hash_size * sizeof(long));\n for (long k = 0; k < hash_size; ++k) node_hash_table[node_type][k] = -1;\n }\n}\n\nvoid InsertHashTable(char *key, int value, int type) {\n unsigned long loc = GetHash(key);\n while (node_hash_table[type][loc] != -1) loc = (loc + 1) % hash_size;\n node_hash_table[type][loc] = value;\n}\n\n// hashing based on the name string\nlong SearchHashTable(char *key, int type) {\n unsigned long addr = GetHash(key);\n while (1) {\n if (node_hash_table[type][addr] == -1) return -1;\n if (!strcmp(key, nodes[type][node_hash_table[type][addr]].name))\n return node_hash_table[type][addr];\n addr = (addr + 1) % hash_size;\n }\n return -1;\n}\n\nvoid AddNeighbor(int src_type, int dst_type, long src_id, long dst_id, \n int edge_type, long edge_id) {\n assert(valid_edge[src_type][dst_type]);\n ClassNode &node = nodes[src_type][src_id]; \n int n_neighbor = node.n_neighbor[dst_type];\n\n if (n_neighbor + 2 >= node.max_n_neighbor[dst_type]) {\n node.max_n_neighbor[dst_type] *= 2;\n ClassNeighbor *tmp = (struct ClassNeighbor*) realloc(\n node.neighbors[dst_type], \n node.max_n_neighbor[dst_type] * sizeof(struct ClassNeighbor)); \n if (tmp != NULL) {\n node.neighbors[dst_type] = tmp;\n } else {\n printf(\"Fail to reallocate\\n\");\n exit(1);\n }\n }\n node.neighbors[dst_type][n_neighbor].node_id = dst_id;\n node.neighbors[dst_type][n_neighbor].edge_id = edge_id;\n node.n_neighbor[dst_type] += 1;\n}\n\n// Add a node to the vertex set\nint AddNode(char *name, int node_type) {\n int length = strlen(name) + 1;\n if (length > MAX_STRING) length = MAX_STRING;\n\n ClassNode & node = nodes[node_type][node_cnt[node_type]]; \n // insert the node, and initial the value of name, node_type, and degree;\n node.name = (char *) calloc(length, sizeof(char));\n node.degree = 0;\n node.weight = 1;\n\n node.n_neighbor = (int *) calloc(n_node_type, sizeof(int)); \n node.max_n_neighbor = (int *) calloc(n_node_type, sizeof(int)); \n node.neighbors = (ClassNeighbor **) calloc(n_node_type, sizeof(ClassNeighbor *));\n\n for (int i = 0; i < n_node_type; ++i) {\n if (valid_edge[node_type][i]) {\n node.max_n_neighbor[i] = neighbor_initial_count;\n node.neighbors[i] = (ClassNeighbor *) calloc(neighbor_initial_count, \n sizeof(ClassNeighbor));\n } \n } \n\n if (length < MAX_STRING) {\n strcpy(node.name, name);\n } else {\n strncpy(node.name, name, MAX_STRING - 1);\n node.name[MAX_STRING - 1] = '\\0';\n }\n\n ++node_cnt[node_type];\n if (node_cnt[node_type] + 2 >= max_sz_node[node_type]) {\n max_sz_node[node_type] += node_count_inc;\n struct ClassNode *tmp = (struct ClassNode *) realloc(nodes[node_type],\n max_sz_node[node_type] * sizeof(struct ClassNode));\n if (tmp != NULL) {\n nodes[node_type] = tmp;\n } else {\n printf(\"fail to reallocate\\n\");\n }\n }\n InsertHashTable(name, node_cnt[node_type] - 1, node_type);\n return node_cnt[node_type] - 1;\n}\n\nvoid UpdateEdgeWeight(int edge_type) {\n long src_id, dst_id;\n int src_type = edge_node_type[edge_type][0];\n int dst_type = edge_node_type[edge_type][1];\n\n for (long k = 0; k < edge_cnt[edge_type]; ++k) {\n src_id = edges[edge_type][k].src_id;\n dst_id = edges[edge_type][k].dst_id;\n\n nodes[src_type][src_id].degree -= edges[edge_type][k].weight;\n nodes[dst_type][dst_id].degree -= edges[edge_type][k].weight; \n\n edges[edge_type][k].weight *= \n nodes[src_type][src_id].weight * nodes[dst_type][dst_id].weight;\n\n nodes[src_type][src_id].degree += edges[edge_type][k].weight;\n nodes[dst_type][dst_id].degree += edges[edge_type][k].weight; \n }\n // printf(\"Finish updating edge weight of edge %s \\n\", edge_names[edge_type]);\n}\n\nvoid ReadNodeWeight(int node_type) {\n FILE *fin;\n char field[MAX_STRING], str[10000];\n real weight; \n long node_id, n_lines = 0;\n\n sprintf(input_node_weight_file, \n \"%s/%s.weights\", weight_folder, node_names[node_type]);\n // printf(\"%s\\n\", input_node_weight_file);\n\n fin = fopen(input_node_weight_file, \"rb\");\n while (fgets(str, sizeof(str), fin)) ++n_lines;\n fclose(fin);\n\n fin = fopen(input_node_weight_file, \"rb\");\n for (long k = 0; k < n_lines; ++k) {\n fscanf(fin, \"%s %lf\", field, &weight);\n if (prior_power != 1) {\n weight = pow(weight, prior_power);\n }\n node_id = SearchHashTable(field, node_type);\n if (node_id == -1) {\n printf(\"Invalid node name %s of type %s \\n\", \n field, node_names[node_type]);\n exit(1);\n } \n nodes[node_type][node_id].weight = weight;\n }\n //printf(\"Finish updating the weight for nodes %s \\n\", node_names[node_type]);\n}\n\n/* Read edges of different types in the network */\nvoid ReadEdgeData(int edge_type) {\n FILE *fin;\n real weight;\n\n long src_id, dst_id;\n int src_type = edge_node_type[edge_type][0];\n int dst_type = edge_node_type[edge_type][1];\n char str[MAX_SENTENCE], src_name[MAX_STRING], dst_name[MAX_STRING];\n\n // Get how many number of edges we have\n fin = fopen(train_network_file[edge_type], \"rb\");\n\n printf(\"input: %s \\n\", train_network_file[edge_type]);\n edge_cnt[edge_type] = 0;\n while (fgets(str, sizeof(str), fin)) ++edge_cnt[edge_type];\n fclose(fin);\n printf(\"Number of edges (%s): %ld \\n\", edge_names[edge_type], edge_cnt[edge_type]);\n\n edges[edge_type] = (ClassEdge *) malloc(\n edge_cnt[edge_type] * sizeof(ClassEdge));\n\n fin = fopen(train_network_file[edge_type], \"rb\");\n\n for (long k = 0; k < edge_cnt[edge_type]; ++k) {\n fscanf(fin, \"%s %s %f\", src_name, dst_name, &weight);\n assert(weight > 0);\n\n src_id = SearchHashTable(src_name, src_type);\n if (src_id == -1) {\n src_id = AddNode(src_name, src_type);\n }\n dst_id = SearchHashTable(dst_name, dst_type);\n if (dst_id == -1) {\n dst_id = AddNode(dst_name, dst_type);\n }\n edges[edge_type][k].src_id = src_id;\n edges[edge_type][k].dst_id = dst_id;\n edges[edge_type][k].weight = weight;\n\n if (src_type == author_type || src_type == term_type) {\n AddNeighbor(src_type, dst_type, src_id, dst_id, edge_type, edge_id);\n AddNeighbor(dst_type, src_type, dst_id, src_id, edge_type, edge_id);\n }\n // update node degree\n nodes[src_type][src_id].degree += weight;\n nodes[dst_type][dst_id].degree += weight;\n\n if (k % 50000 == 0) {\n printf(\"Loading edges : %.3lf%%%c\", k / (real)(edge_cnt[edge_type] + 1) * 100, 13);\n fflush(stdout);\n }\n }\n fclose(fin);\n}\n\n/* Read the fixed embedding of terms */\nvoid ReadFixEmbedding(int node_type) {\n FILE *fin;\n char str[(dim + 1) * MAX_STRING + 1000];\n long node_id;\n long fix_node_count = node_cnt[node_type], count = 0;\n char *token;\n\n sprintf(input_fix_embedding_file, \n \"%s/%s.embeddings\", embed_folder, node_names[node_type]);\n\n if (access(input_fix_embedding_file, F_OK) == -1) {\n printf(\"Can't read the file %s \\n\", input_fix_embedding_file);\n exit(1); \n }\n\n // Get how many number of edges we have\n fin = fopen(input_fix_embedding_file, \"rb\");\n\n // printf(\"debug: finish init\\n\");\n if (fgets(str, sizeof(str), fin) == NULL) {\n printf(\"Can't read the file %s \\n\", input_fix_embedding_file);\n exit(1); \n }\n while (fgets(str, sizeof(str), fin)) {\n // printf(\"debug: parse %s\\n\", str);\n if (count >= fix_node_count) break;\n ++count;\n\n token = strtok(str, \" \");\n node_id = SearchHashTable(token, node_type);\n if (node_id == -1) {\n continue;\n }\n for (int k = 0; k < dim; ++k) {\n token = strtok(NULL, \" \");\n if (token == NULL) {\n printf(\"Error: embedding length dismatch!\\n\");\n exit(1);\n }\n emb_node[node_type][node_id * dim + k] = atof(token) / 20;\n }\n }\n fclose(fin);\n printf(\"Embedding of node %s imported!\\n\", node_names[node_type]);\n}\n\nvoid InitNodeVector(int node_type, real *emb_node) {\n long offset = 0;\n for (long i = 0; i < node_cnt[node_type]; ++i) {\n for (int k = 0; k < dim; ++k) {\n emb_node[offset++] = (gsl_rng_uniform(gsl_r) - 0.5) / dim;\n }\n }\n}\n\n/* Initialize the vertex embedding and the context embedding */\nvoid InitVector(){\n printf(\"Initializing node vector ... \\n %c\", 13);\n fflush(stdout);\n // initialize the target and context embedding of each type of node \n for (int node_type = 0; node_type < n_node_type; ++node_type) {\n posix_memalign((void **)& emb_node[node_type], 128, \n node_cnt[node_type] * dim * sizeof(real));\n if (emb_node[node_type] == NULL) {\n printf(\"Error: memory allocation failed\\n\");\n exit(1);\n }\n InitNodeVector(node_type, emb_node[node_type]); \n }\n}\n\n// Given a node type, sample a negative node\nvoid InitNegTable(int node_type) {\n real sum = 0, cur_sum = 0, por = 0;\n long vid = 0;\n printf(\"Initializing negative table for %s ... \\t\\t\\t\\t %c\", node_names[node_type], 13);\n\n fflush(stdout);\n neg_table[node_type] = (long *)malloc(neg_table_size * sizeof(long));\n\n for (long k = 0; k < node_cnt[node_type]; ++k) {\n sum += pow(nodes[node_type][k].degree, \n node_sample_power[node_type]);\n }\n\n for (long k = 0; k < neg_table_size; ++k) {\n if ((real)(k + 1) / neg_table_size > por) {\n cur_sum += pow(nodes[node_type][vid].degree, \n node_sample_power[node_type]);\n por = cur_sum / sum;\n ++vid;\n }\n neg_table[node_type][k] = vid - 1;\n }\n}\n\nvoid InitEdgeAlias(int edge_type) {\n printf(\"Initializing alias table for edge %s ... %c\", \n edge_names[edge_type], 13);\n real *prob = (real *) calloc(edge_cnt[edge_type], sizeof(real));\n real total_weight = 0;\n for (int i = 0; i < edge_cnt[edge_type]; ++i) {\n total_weight += edges[edge_type][i].weight;\n }\n for (int i = 0; i < edge_cnt[edge_type]; ++i) {\n prob[i] = edges[edge_type][i].weight / total_weight;\n }\n edge_alias[edge_type] = ransampl_alloc(edge_cnt[edge_type]);\n ransampl_set(edge_alias[edge_type], prob);\n}\n\n/* Fastly compute sigmoid function */\nvoid InitSigmoidTable() {\n real x;\n printf(\"Initializing sigmoid table ... %c\", 13);\n fflush(stdout);\n sigmoid_table = (real *)malloc((sigmoid_table_size + 1) * sizeof(real));\n for (int k = 0; k < sigmoid_table_size; ++k) {\n x = 2 * (real)(MAX_SIGMOID * k) / sigmoid_table_size - MAX_SIGMOID;\n sigmoid_table[k] = 1 / (1 + exp(-x));\n }\n}\n\ninline real FastSigmoid(real x) {\n if (x > MAX_SIGMOID) return 1;\n else if (x < -MAX_SIGMOID) return 0;\n return sigmoid_table[(int)((x + MAX_SIGMOID) * sigmoid_coeff)];\n}\n\ninline long SampleNegativeNode(int node_type, gsl_rng * & gsl_r_local) {\n // return gsl_rng_uniform_int(gsl_r_local, node_cnt[node_type]);\n return neg_table[node_type][\n gsl_rng_uniform_int(gsl_r_local, neg_table_size)];\n}\n\ninline long SampleEdge(int edge_type, gsl_rng * & gsl_r_local) {\n return ransampl_draw(edge_alias[edge_type], \n gsl_rng_uniform(gsl_r_local),\n gsl_rng_uniform(gsl_r_local)); \n}\n\ninline void Update(int src_type, int dst_type, long src_id, \n long end_id, long *neg_node_ids, real *context_update) {\n long target_id, target_offset, context_offset;\n real f = 0, g = 0, label = 1;\n real decay_target = alpha * beta[dst_type];\n real decay_context = alpha * beta[src_type];\n\n memset(context_update, 0, dim * sizeof(real));\n\n context_offset = src_id * dim;\n for (int i = 0; i <= negative_k; ++i) {\n if (i == negative_k) {\n target_id = end_id;\n label = 1; \n } else {\n target_id = neg_node_ids[i];\n if (target_id == end_id) continue;\n label = 0;\n }\n target_offset = target_id * dim;\n f = 0;\n for (int j = 0; j < dim; j ++) {\n f += emb_node[dst_type][target_offset + j] *\n emb_node[src_type][context_offset + j];\n }\n g = (label - FastSigmoid(f)) * alpha;\n for (int j = 0; j < dim; ++j) {\n context_update[j] += g * emb_node[dst_type][target_offset + j] \n - decay_context * emb_node[src_type][context_offset + j]; \n emb_node[dst_type][target_offset + j] += \n g * emb_node[src_type][context_offset + j] \n - decay_target * emb_node[dst_type][target_offset + j];\n }\n }\n\n for (int j = 0; j < dim; ++j) {\n emb_node[src_type][context_offset + j] += context_update[j];\n }\n\n}\n\nvoid *TrainThread(void *id) {\n long count = 0, last_count = 0;\n long limit = total_samples / num_threads + 2;\n int src_type, dst_type;\n long edge_id, src_id, dst_id;\n long *neg_node_ids;\n\n neg_node_ids = (long *) malloc(negative_k * sizeof(long)); \n\n gsl_rng * gsl_r_local = gsl_rng_alloc(gsl_T);\n gsl_rng_set(gsl_r_local, (unsigned long int) id); \n\n real *err_update = (real *) malloc(dim * sizeof(real));\n\n real ratio;\n clock_t now;\n\n while (1)\n {\n // decide when to exist the learning \n if (count > limit) {\n current_sample += count - last_count; \n break ;\n }\n\n // update output information\n if (count - last_count == 10000) {\n current_sample += count - last_count;\n last_count = count;\n ratio = current_sample / (real)(total_samples + 1);\n if (count % 100000 == 0) {\n now=clock();\n printf(\"%cAlpha: %f Progress: %.2lf%% Events/thread/sec: %.2fk\",\n 13, alpha, ratio * 100,\n current_sample / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000));\n fflush(stdout);\n }\n alpha = init_alpha * (1 - ratio);\n }\n ++count;\n\n for (int edge_type = 0; edge_type < n_edge_type; ++edge_type) {\n src_type = edge_node_type[edge_type][0];\n dst_type = edge_node_type[edge_type][1];\n\n edge_id = SampleEdge(edge_type, gsl_r_local);\n src_id = edges[edge_type][edge_id].src_id; \n dst_id = edges[edge_type][edge_id].dst_id;\n\n //printf(\"%d %d %d %s %s \\n\", edge_type, src_type, dst_type, nodes[src_type][src_id].name, nodes[dst_type][dst_id].name);\n\n for (int i = 0; i < negative_k; ++i) {\n neg_node_ids[i] = SampleNegativeNode(dst_type, gsl_r_local);\n }\n Update(src_type, dst_type, src_id, dst_id, neg_node_ids, err_update);\n }\n }\n free(neg_node_ids);\n free(err_update);\n pthread_exit(NULL);\n}\n\n// output the embeddings of nodes and the context embedding\nvoid Output() {\n // for each type of nodes, output the embeddings\n char file_name[MAX_STRING];\n FILE *fo;\n long offset;\n\n // output the embeddings of nodes\n for (int node_type = 0; node_type < n_node_type; ++node_type) {\n if (!output_types[node_type]) continue;\n printf(\"storing the embedding of nodes %s\\n\", node_names[node_type]);\n sprintf(file_name, \"%s/%s.embeddings\", output_folder, node_names[node_type]);\n fo = fopen(file_name, \"wb\");\n fprintf(fo, \"%ld %d\\n\", node_cnt[node_type], dim);\n offset = 0;\n for (long i = 0; i < node_cnt[node_type]; ++i) {\n fprintf(fo, \"%s \", nodes[node_type][i].name);\n for (int k = 0; k < dim; ++k) {\n fprintf(fo, \"%lf \", emb_node[node_type][offset++]);\n }\n fprintf(fo, \"\\n\");\n }\n fclose(fo);\n }\n}\n\n// query string is delimited by #\nvoid readQuery(char *qString, set::set query) {\n query.clear();\n char delim[] = \"#\";\n char *token = strtok(name, delim);\n long node_id;\n while (token != NULL) {\n node_id = SearchHashTable(token, term_type);\n if (node_id == -1) {\n node_id = AddNode(token, map_node_type);\n }\n query.insert(node_id);\n token = strtok(NULL, delim);\n }\n}\n\nvoid hitPapers(set::set &query, set::set &paper_set) {\n paper_set.clear();\n for (set::set::iterator it = query.begin(); it != query.end(); ++it) { \n long term_id = *it;\n ClassNode &node = nodes[term_type][term_id];\n for (int j = 0; j < node.n_neighbor[paper_type]; ++j) {\n paper_set.insert(node.neighbors[paper_type][j]);\n }\n }\n}\n\nvoid nodeExpansion(int src_type, int dst_type, set::set &src_set, set::set &dst_set) {\n dst_set.clear();\n for (set::set::iterator it = src_set.begin(); it != src_set.end(); ++it) {\n long src_id = *it;\n ClassNode &node = nodes[src_type][src_id];\n for (int j = 0; j < node.n_neighbor[dst_type]; ++j) {\n dst_set.insert(node.neighbors[dst_type][j]);\n }\n }\n}\n\nvoid queryExpansion(set::set &paper_set, set::set &query, set::set &new_query) {\n new_query.clear();\n long t_n_edges = 0;\n std::map topic_edges;\n for (set::set::iterator it = paper_set.begin(), it != paper_set.end(); ++it) {\n long paper_id = *it;\n class &node = *it;\n for (int j = 0; j < node.n_neighbor[term_type]; ++j) {\n long edge_id = node.neighbors[term_type][j].edge_id;\n real weight = edges[term_paper_edge_type][edge_id].weight;\n topic_edges[edge_id] = weight;\n }\n }\n\n long * sample_topic_edges = (long *) malloc(topic_edges.size() * sizeof(long));\n real * sample_prob = (real *) malloc(topic_edges.size() * sizeof(real));\n\n real sum_weight = 0;\n int k = 0;\n for (std::map::iterator it = topic_edges.begin(); it != topic_edges.end(); ++it) {\n sample_topic_edges[k] = it->first;\n sample_prob[k] = it->second;\n sum_weight += sample_prob[k];\n k ++;\n }\n topic_edge_alias = ransampl_alloc(topic_edges.size());\n ransampl_set(topic_edge_alias, sample_prob); \n} \n\nset::set expandDocument(set::set query) {\n long * new_query;\n set::set author_set, paper_set;\n set::set new_query; \n while (true) {\n hitPapers(query, paper_set);\n nodeExpansion(paper_type, author_type, paper_set, author_set);\n nodeExpansion(author_type, paper_type, author_set, paper_set);\n queryExpansion(paper_set, query, new_query); \n }\n hitPapers(query, paper_set);\n return paper_set;\n}\n\nvoid TrainModel() {\n gsl_rng_env_setup();\n gsl_T = gsl_rng_rand48;\n gsl_r = gsl_rng_alloc(gsl_T);\n gsl_rng_set(gsl_r, 314159265);\n\n\n InitHashTable();\n printf(\"HashTable Initialized! \\n\");\n\n for (int edge_type = 0; edge_type < n_edge_type; ++edge_type) {\n printf(\"Start to read edges of %s\\n\", edge_names[edge_type]); \n ReadEdgeData(edge_type);\n }\n\n\n printf(\"Node types: %d \\n\", n_node_type);\n for (int i = 0; i < n_node_type; i ++) {\n printf(\"%s \", node_names[i]);\n }\n printf(\"\\n\");\n\n for (int node_type = 0; node_type < n_node_type; ++node_type) {\n if (node_weight[node_type]) {\n ReadNodeWeight(node_type);\n }\n }\n\n printf(\"Edge types: %d \\n\", n_edge_type);\n for (int i = 0; i < n_edge_type; i ++) {\n printf(\"%s \", edge_names[i]);\n }\n printf(\"\\n\");\n\n\n printf(\"-------------------------------- \\n\");\n for (int k = 0; k < n_node_type; ++k) {\n printf(\"Number of nodes (%s): %ld \\n\", node_names[k], node_cnt[k]);\n }\n // map each ege into corresponding\n total_samples = (long) (1000000 * total_samples);\n printf(\"--------------------------------\\n\");\n printf(\"Dimension: %d\\n\", dim);\n printf(\"Initial alpha: %.3lf\\n\", alpha);\n printf(\"Thread : %d \\n\", num_threads); \n printf(\"--------------------------------\\n\");\n\n printf(\"Load node weight : \\n\");\n for (int node_type = 0; node_type < n_node_type; ++node_type) {\n printf(\"\\t%s : %s \\n\", node_names[node_type], \n node_weight[node_type] ? \"Yes\":\"No\");\n }\n printf(\"\\n\"); \n\n printf(\"Prior power : %f \\n\\n\", prior_power);\n\n printf(\"Update edge weight : \\n\");\n for (int edge_type = 0; edge_type < n_edge_type; ++edge_type) {\n if (edge_weight[edge_type] && (node_weight[edge_node_type[edge_type][0]] \n || node_weight[edge_node_type[edge_type][1]])) {\n printf(\"\\t%s : %s \\n\", edge_names[edge_type], \"Yes\");\n UpdateEdgeWeight(edge_type);\n } \n else {\n printf(\"\\t%s : %s \\n\", edge_names[edge_type], \"No\");\n }\n }\n printf(\"\\n\");\n\n printf(\"Output node types:\");\n for (int m = 0; m < n_node_type; ++m){\n if (output_types[m]) {\n printf(\" %s\", node_names[m]);\n }\n }\n printf(\"\\n\\n\"); \n\n InitVector();\n\n InitSigmoidTable();\n printf(\"Finish initialization! \\n\");\n\n FILE *fin = fopen(query_file, \"rb\");\n char c;\n int nQuery = 0;\n while (fgets(str, sizeof(str), fin)) ++nQuery;\n fclose();\n\n fin = fopen(query_file, \"rb\");\n set::set papers, query;\n char query_string[MAX_SENTENCE];\n for (int q = 0; q < nQuery; q++) {\n int pos = 0;\n do {\n c = fgetc(fin);\n if (c == EOF || c == '\\n') break;\n else if (pos < MAX_SENTENCE - 1) query_string[pos++] = (char) c; \n }\n query_string[pos] = 0;\n readQuery(query_string, query); \n papers.clear();\n papers = expandDocument(query);\n\n }\n\n\n struct timeval t1, t2;\n gettimeofday(&t1, NULL);\n start = clock();\n pthread_t *pt = (pthread_t *)malloc((num_threads) * sizeof(pthread_t));\n\n for (long a = 0; a < num_threads; ++a) {\n pthread_create(&pt[a], NULL, TrainThread, (void *)a);\n }\n for (int a = 0; a < num_threads; ++a) { \n pthread_join(pt[a], NULL);\n }\n\n gettimeofday(&t2, NULL);\n printf(\"\\nTotal optimization time: %.2lf minitues\\n\", (real)(t2.tv_sec - t1.tv_sec) / 60);\n Output();\n}\n\n\nint ArgPos(char *str, int argc, char **argv) {\n for (int a = 0; a < argc; ++a) {\n if (!strcmp(str, argv[a])) {\n if (a == argc - 1) {\n printf(\"Argument missing for %s\\n\", str);\n exit(1);\n }\n return a;\n }\n }\n return -1;\n}\n\nint main(int argc, char **argv) {\n int i, j, k;\n char str[MAX_SENTENCE], source[MAX_SENTENCE], dest[MAX_SENTENCE];\n strcpy(output_folder, \"output\");\n strcpy(input_folder, \"data\");\n InitSigmoidTable();\n\n if (argc == 1) {\n printf(\"\\t leef: Local Embedding for Expert Finding\\n\");\n printf(\"Options:\"); \n printf(\"\\tPlease specify the parameter file!\\n\");\n printf(\"\\t-para \\n\");\n printf(\"\\t\\tProvide the parameter file on edges\\n\");\n printf(\"\\t-size \\n\");\n printf(\"\\t\\tSet dimension of vertex embeddings; default is 200\\n\");\n printf(\"\\t-scoring \\n\");\n printf(\"\\t\\tScoring function, 0: complete element-wise product,\"\n \"1: complete pairwise inner product, 2: pairwise inner product with central type\\n\");\n printf(\"\\t-iter \\n\");\n printf(\"\\t\\tSet the number of training samples as the number of iterations of number of edges\\n\");\n printf(\"\\t-tthread \\n\");\n printf(\"\\t\\tUse threads for tensor updating(default 1)\\n\");\n printf(\"\\t-wthread \\n\");\n printf(\"\\t\\tUse threads for word2vec updating(default 1)\\n\");\n printf(\"\\t-negative \\n\");\n printf(\"\\t\\tSample negative samples for word2vec updating(default 1)\\n\");\n printf(\"\\t-alpha \\n\");\n printf(\"\\t\\tSet the starting learning rate; default is 0.025\\n\");\n printf(\"\\t-input input folder ...\\n\");\n printf(\"\\t\\tSet the folder data which read data\\n\");\n printf(\"\\t-output output folder ...\\n\");\n printf(\"\\t\\tSet the folder to which output data\\n\");\n return 0;\n }\n\n // global parameters shared across all the edges\n if ((i = ArgPos((char *) \"-size\", argc, argv)) > 0)\n dim = atoi(argv[i + 1]);\n if ((i = ArgPos((char *) \"-iter\", argc, argv)) > 0)\n total_samples = atoi(argv[i + 1]);\n if ((i = ArgPos((char *) \"-alpha\", argc, argv)) > 0)\n init_alpha = atof(argv[i + 1]);\n if ((i = ArgPos((char *) \"-thread\", argc, argv)) > 0) {\n num_threads = atoi(argv[i + 1]);\n }\n if ((i = ArgPos((char *) \"-negative\", argc, argv)) > 0) {\n negative_k = atoi(argv[i + 1]);\n }\n\n for (i = 0; i < n_node_type; ++i) {\n for (j = 0; j < n_node_type; ++j) {\n valid_edge[i][j] = false;\n } \n }\n\n if ((i = ArgPos((char *) \"-n_node\", argc, argv)) > 0) {\n n_node_type = atoi(argv[i + 1]);\n }\n\n for (int i = 0; i < n_node_type; ++i) {\n nodes[i] =(struct ClassNode *) calloc(node_count_inc, \n sizeof(struct ClassNode));\n max_sz_node[i] = node_count_inc;\n node_sample_power[i] = sample_power;\n }\n\n if ((i = ArgPos((char *) \"-nodes\", argc, argv)) > 0) {\n for (j = 0; j < n_node_type; ++j) {\n strcpy(node_names[j], argv[i + j + 1]);\n if (!strcmp(node_names[j], \"author\")) {\n author_type = j;\n } else if (!strcmp(node_names[j], \"term\")) {\n term_type = j;\n } else if (!strcmp(node_names[j], \"paper\")) {\n paper_type = j;\n }\n }\n }\n\n if ((i = ArgPos((char *) \"-n_edge\", argc, argv)) > 0) {\n n_edge_type = atoi(argv[i + 1]);\n }\n\n if ((i = ArgPos((char *) \"-output_folder\", argc, argv)) > 0)\n strcpy(output_folder, argv[i + 1]);\n if ((i = ArgPos((char *) \"-input_folder\", argc, argv)) > 0)\n strcpy(input_folder, argv[i + 1]);\n if ((i = ArgPos((char *) \"-embed_folder\", argc, argv)) > 0)\n strcpy(embed_folder, argv[i + 1]);\n if ((i = ArgPos((char *) \"-weight_folder\", argc, argv)) > 0)\n strcpy(weight_folder, argv[i + 1]);\n\n if ((i = ArgPos((char *) \"-edges\", argc, argv)) > 0) {\n for (j = 0; j < n_edge_type; ++j) {\n strcpy(edge_names[j], argv[i + j + 1]);\n sprintf(train_network_file[j], \"%s/%s.net\", input_folder, edge_names[j]);\n printf(\"Input %d: %s\\n\", j, train_network_file[j]); \n strcpy(edge_names[j], argv[i + 1 + j]); \n strcpy(str, edge_names[j]); \n int pch = strchr(str, '_') - str;\n str[pch] = '\\0';\n strcpy(source, str);\n strcpy(dest, &str[pch + 1]);\n for (k = 0; k < n_node_type; ++k) {\n if (strcmp(source, node_names[k]) == 0) {\n edge_node_type[j][0] = k;\n } else if (strcmp(dest, node_names[k]) == 0) {\n edge_node_type[j][1] = k;\n } \n }\n if (edge_node_type[j][0] == term_type && edge_node_type[j][1] == paper_type) {\n term_paper_edge_type = j;\n }\n valid_edge[edge_node_type[j][0]][edge_node_type[j][1]] = true;\n valid_edge[edge_node_type[j][1]][edge_node_type[j][0]] = true;\n }\n }\n\n\n // the regularization parameter for the embeddings \n if ((i = ArgPos((char *) \"-beta\", argc, argv)) >= 0) {\n for (int j = 0; j < n_node_type; ++j) {\n beta[j] = atof(argv[i + 1 + j]);\n }\n }\n\n if ((i = ArgPos((char *) \"-prior_power\", argc, argv)) >= 0) {\n prior_power = atof(argv[i + 1]);\n }\n\n if ((i = ArgPos((char *) \"-sample_power\", argc, argv)) >= 0) {\n for (int j = 0; j < n_node_type; ++j) {\n node_sample_power[j] = atof(argv[i + 1 + j]);\n }\n }\n\n if ((i = ArgPos((char *) \"-choose_output\", argc, argv)) >= 0) {\n for (int j = 0; j < n_node_type; ++j) {\n output_types[j] = (argv[i + 1][j] == '1');\n }\n }\n\n if ((i = ArgPos((char *) \"-load_embed\", argc, argv)) >= 0) {\n printf(\"Loading embeddings is disabled..\\n\");\n for (int j = 0; j < n_node_type; ++j) {\n if (argv[i + 1][j] == '1') {\n load_types[j] = true; \n }\n }\n }\n\n if ((i = ArgPos((char *) \"-load_weight\", argc, argv)) >= 0) {\n for (int j = 0; j < n_node_type; ++j) {\n if (argv[i + 1][j] == '1') {\n node_weight[j] = true; \n }\n }\n }\n\n if ((i = ArgPos((char *) \"-edge_weight\", argc, argv)) >= 0) {\n for (int j = 0; j < n_node_type; ++j) {\n if (argv[i + 1][j] == '1') {\n edge_weight[j] = true; \n } else {\n edge_weight[j] = false;\n }\n }\n }\n\n if ((i = ArgPos((char *) \"-query_file\", argc, argv)) >= 0) {\n strcpy(query_file, argv[i + 1]);\n }\n\n alpha = init_alpha;\n TrainModel();\n return 0;\n}\n", "meta": {"hexsha": "3a514542d10a948c9bf1924cc5f32d94bc358824", "size": 30921, "ext": "c", "lang": "C", "max_stars_repo_path": "code/embedding_deprecated/leef.c", "max_stars_repo_name": "VincentGaoHJ/taxogen-implementation", "max_stars_repo_head_hexsha": "4ffd1c8e45401f2b504a582c1fef6364651810eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-13T09:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-13T09:03:50.000Z", "max_issues_repo_path": "code/embedding_deprecated/leef.c", "max_issues_repo_name": "VincentGaoHJ/taxogen-implementation", "max_issues_repo_head_hexsha": "4ffd1c8e45401f2b504a582c1fef6364651810eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/embedding_deprecated/leef.c", "max_forks_repo_name": "VincentGaoHJ/taxogen-implementation", "max_forks_repo_head_hexsha": "4ffd1c8e45401f2b504a582c1fef6364651810eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T21:46:09.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T21:31:52.000Z", "avg_line_length": 30.6755952381, "max_line_length": 127, "alphanum_fraction": 0.6224248892, "num_tokens": 9028, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722128, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.344887990288092}} {"text": "// Copyright András Vukics 2021. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt)\n/// \\briefFileDefault\n#ifndef CPPQEDCORE_UTILS_ODE_GSL_H_INCLUDED\n#define CPPQEDCORE_UTILS_ODE_GSL_H_INCLUDED\n\n#include \"ArrayTraits.h\"\n#include \"ODE.h\"\n\n#include \n#include \n\n#include \n\nnamespace cppqedutils {\n \n \nnamespace ode_engine {\n\n \ntemplate \nclass ControlledErrorStepperGSL\n{\npublic:\n using state_type=StateType;\n using deriv_type=state_type;\n using time_type=double;\n using value_type=ElementType_t;\n using stepper_category=bno::controlled_stepper_tag;\n \n ControlledErrorStepperGSL(double epsAbs, double epsRel)\n : control_{gsl_odeiv2_control_standard_new(epsAbs,epsRel,1,1), [] (auto* ptr) {if (ptr) gsl_odeiv2_control_free(ptr);}} {}\n \nprivate:\n using ValueVector=std::vector;\n using Aux_t=std::tuple&,Extents_t>>;\n \npublic:\n /// Realizes part of the logic of [gsl_odeiv2_evolve_apply](http://www.gnu.org/software/gsl/doc/html/ode-initval.html#c.gsl_odeiv2_evolve_apply)\n /**\n * Differences:\n * - First-same-as-last steppers not supported (at the moment only RKCK is supported)\n * - There is no guard against the stepsize becoming infinitesimal \n */\n template \n auto try_step(System sys, S&& stateInOut, double& time, double& dtTry)\n {\n auto totalExtent=Size::_(stateInOut);\n \n if (!step_) { // this means that tryStep is called for the first time\n step_.reset(gsl_odeiv2_step_alloc(gsl_odeiv2_step_rkck,totalExtent), [] (auto* ptr) {if (ptr) gsl_odeiv2_step_free(ptr);});\n yerr_=std::make_shared(totalExtent);\n dydt_out_=std::make_shared(totalExtent);\n }\n#ifndef NDEBUG\n else if (!IsStorageContiguous::_(stateInOut)) {\n throw NonContiguousStorageException{\"ControlledErrorStepperGSL::tryStep\"};\n }\n else if (yerr_->size()!=Size::_(stateInOut) || dydt_out_->size()!=Size::_(stateInOut)) {\n throw std::runtime_error(\"Dimensionality mismatch in ControlledErrorStepperGSL::tryStep\");\n }\n#endif // NDEBUG\n \n SystemFunctional_t sysVariable=sys; // it’s important to convert `sys` (which can be a lambda) to a variable of known type\n \n Aux_t aux{sysVariable,Extents::_(stateInOut)};\n \n gsl_odeiv2_system dydt{ControlledErrorStepperGSL::lowLevelSystemFunction,nullptr,totalExtent,&aux};\n \n auto step_status = gsl_odeiv2_step_apply (step_.get(), time, dtTry, Data::_(stateInOut), yerr_->data(), nullptr, dydt_out_->data(), &dydt);\n \n if (step_status == GSL_EFAULT || step_status == GSL_EBADFUNC) throw std::runtime_error(\"GSL bad step_status\");\n\n if (step_status != GSL_SUCCESS) {\n dtTry *= 0.5;\n return bno::fail;\n }\n else {\n time+=dtTry;\n /* const auto hadjust_status = */\n gsl_odeiv2_control_hadjust (control_.get(), step_.get(), Data::_(stateInOut), yerr_->data(), dydt_out_->data(), &dtTry);\n // if (hadjust_status == GSL_ODEIV_HADJ_DEC) throw std::runtime_error{\"Unexpected change of dtTry in ControlledErrorStepperGSL::tryStep\"};\n return bno::success;\n }\n }\n \nprivate:\n static int lowLevelSystemFunction(double t, const double* y, double* dydt, void* aux)\n {\n auto [highLevelSystemFunction,arrayExtents] = *static_cast(aux);\n\n const StateType yInterface(Create_c::_(y,arrayExtents));\n\n StateType dydtInterface(Create::_(dydt,arrayExtents));\n\n highLevelSystemFunction(yInterface,dydtInterface,t);\n\n return GSL_SUCCESS;\n }\n \n std::shared_ptr step_;\n\n const std::shared_ptr control_;\n \n // Needs to be easily copyable, as Steppers are carried around by value\n std::shared_ptr yerr_, dydt_out_;\n \n};\n\n\ntemplate \nstruct MakeControlledErrorStepper>\n{\n static auto _(double epsRel, double epsAbs)\n {\n return ControlledErrorStepperWithParameters>{\n {epsRel,epsAbs},epsRel,epsAbs};\n }\n\n template \n static auto _(const Pars& p)\n {\n return _(p.epsRel,p.epsAbs);\n }\n\n \n};\n\n\ntemplate \ninline const std::string StepperDescriptor> = \"GSL RKCK controlled stepper\";\n\n\n} // ode_engine\n\n\ntemplate \nusing ODE_EngineGSL = ode_engine::Base>;\n\n\n} // cppqedutils\n\n#endif // CPPQEDCORE_UTILS_ODE_GSL_H_INCLUDED\n", "meta": {"hexsha": "5b6fe219404a0007bde5e5f7a56f0a6c5fe891b6", "size": 4743, "ext": "h", "lang": "C", "max_stars_repo_path": "CPPQEDutils/ODE_GSL.h", "max_stars_repo_name": "vukics/cppqed", "max_stars_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-02-21T14:00:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-29T15:12:11.000Z", "max_issues_repo_path": "CPPQEDutils/ODE_GSL.h", "max_issues_repo_name": "vukics/cppqed", "max_issues_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2020-04-14T11:18:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-04T20:11:23.000Z", "max_forks_repo_path": "CPPQEDutils/ODE_GSL.h", "max_forks_repo_name": "vukics/cppqed", "max_forks_repo_head_hexsha": "a933375f53b982b14cebf7cb63de300996ddd00b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-01-25T10:16:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T18:29:01.000Z", "avg_line_length": 33.1678321678, "max_line_length": 154, "alphanum_fraction": 0.7347670251, "num_tokens": 1284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5156199157230157, "lm_q1q2_score": 0.34488798348128824}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"../inc/knnring.h\"\n#include \"mpi.h\"\n\n\n// Application Entry Point\n/*\n * X is this node's points from which distances will be calculated\n * n is the number of points in X and each incoming-outcoming block\n * d is the number of dimensions of each point\n * k is the number of minimum points to calculate\n */\nknnresult distrAllkNN(double * X, int n, int d, int k){\n\n\t// Timers\n\tdouble start = MPI_Wtime();\n\tdouble end;\n\n\t// Get processes number and process id\n\tint p, id;\n\tMPI_Comm_rank(MPI_COMM_WORLD, &id); // Task ID\n\tMPI_Comm_size(MPI_COMM_WORLD, &p); // # tasks\n\n\t// Find IDs of previous and next node in ring\n\tint prev, nxt;\n\tif(id == 0)\n\t\tprev = p - 1;\n\telse\n\t\tprev = id - 1;\n\tif(id == p-1)\n\t\tnxt = 0;\n\telse\n\t\tnxt = id + 1;\n\n\t// MPI variables used for async communication\n MPI_Request reqSend, reqReceive;\n //MPI_Status status;\n\n // Y matrix for receiving points\n\tdouble* Y = calloc(n*d, sizeof(double));\n\n\t// Temporary Y matrix, used for trading in nodes with even ids so that we don't overwrite Y before sending it while receiving\n\tdouble* tempY = calloc(n*d, sizeof(double));\n\n\t// Start pre-fetching and sending data asynchronously\n MPI_Isend(X, n*d, MPI_DOUBLE, nxt, 2, MPI_COMM_WORLD, &reqSend);\n MPI_Irecv(tempY, n*d, MPI_DOUBLE, prev, 2, MPI_COMM_WORLD, &reqReceive);\n\n\t// This is the id that corresponds to the node that initially had the current block of points Y\n\t// It's used to reconstruct the ids array we receive so we don't have to also send ids\n\tint blockID = id;\n\n\t// Generate ids matrix\n\tint* ids = calloc(n, sizeof(int));\n\tfor(int i = 0; i < n; i++){\n\t\t// The first node gets points [0, n], second [n+1, 2n] etc. Node 0 gets the last n points\n\t\tif(id != 0)\n\t\t\tids[i] = (id - 1) * n + i;\n\t\telse\n\t\t\tids[i] = (p-1) * n + i;\n\t}\n\n\t// First calculate using the original dataset, then move on to sending/receiving blocks from others\n\tknnresult results = kNN(X, X, n, n, d, k);\n\n\n\t// IDs in the knnresult structure are relative. They start from 0 and go up to n-1. We need to map them to the actual ids generated above\n\tfor(int i = 0; i < n * k; i++)\n\t\tresults.nidx[i] = ids[results.nidx[i]];\n\n\n\t// Temporary results struct, used for calculations in incoming block\n\tknnresult newResults;\n\n\n\t// Pointers and temporary arrays used for merging results.\n\tint ptrResults = 0;\n\tint ptrNewResults = 0;\n\tdouble* tempResDis = calloc(n * k, sizeof(double));\n\tint* tempResIDs = calloc(n * k, sizeof(int));\n\n\t// Variables to hold minimum and maximum reduction\n\tdouble mindis, maxdis, tempmindis, tempmaxdis;\n\n\n\t// Trade blocks p-1 times in the ring\n\tfor(int i = 0; i < p-1; i++){\n\n\t\t// Wait for sending/receiving to complete before proceeding\n\t\tMPI_Wait(&reqSend, MPI_STATUS_IGNORE);\n\t\tMPI_Wait(&reqReceive, MPI_STATUS_IGNORE);\n\n\t\t// Write the received points into Y so we can start pre-fetching the next ones in tempY\n\t\tmemcpy(Y, tempY, n * d * sizeof(double));\n\n\t\t// Last time we go in data doesn't need to be prefetched\n\t\tif(i < p-2){\n\t\t\t// Start pre-fetching\n\t\t\tMPI_Isend(Y, n*d, MPI_DOUBLE, nxt, 2, MPI_COMM_WORLD, &reqSend);\n\t\t\tMPI_Irecv(tempY, n*d, MPI_DOUBLE, prev, 2, MPI_COMM_WORLD, &reqReceive);\n\t\t}\n\n\t\t// Reconstruct ids array of received block of points based on the node and the number of blocks already traded\n\t\tblockID--;\n\t\tif(blockID < 0)\n\t\t\tblockID = p-1;\n\t\tfor(int j = 0; j < n; j++){\n\t\t\tif(blockID != 0)\n\t\t\t\tids[j] = (blockID - 1) * n + j;\n\t\t\telse\n\t\t\t\tids[j] = (p-1) * n + j;\n\t\t}\n\n\t\t// Run calculations on received points\n\t\tnewResults = kNN(Y, X, n, n, d, k);\n\n\n\t\t// Again map ids as done initially\n\t\tfor(int l = 0; l < n * k; l++)\n\t\t\tnewResults.nidx[l] = ids[newResults.nidx[l]];\n\n\n\t\t// Copy points and ids array of current results to temporary arrays to safely alter the results struct bellow\n\t\tmemcpy(tempResDis, results.ndist, n * k * sizeof(double));\n\t\tmemcpy(tempResIDs, results.nidx, n * k * sizeof(int));\n\n\t\t// Merge results and newResults arrays in a merge-sort fashion\n\t\t// Iterate for each query point\n\t\tfor(int r = 0; r < n; r++){\n\t\t\tptrResults = 0;\n\t\t\tptrNewResults = 0;\n\n\t\t\t// Iterate for each neighbor\n\t\t\tfor(int j = 0; j < k; j++){\n\n\t\t\t\t// If the point in older results is closer than the new one, add it, else add the other one and increment the appropriate array pointer\n\t\t\t\tif(tempResDis[r*k + ptrResults] < newResults.ndist[r*k + ptrNewResults]){\n\t\t\t\t\tresults.ndist[r*k + j] = tempResDis[r*k + ptrResults];\n\t\t\t\t\tresults.nidx[r*k + j] = tempResIDs[r*k + ptrResults];\n\t\t\t\t\tptrResults++;\n\t\t\t\t}else{\n\t\t\t\t\tresults.ndist[r*k + j] = newResults.ndist[r*k + ptrNewResults];\n\t\t\t\t\tresults.nidx[r*k + j] = newResults.nidx[r*k + ptrNewResults];\n\t\t\t\t\tptrNewResults++;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\n\t// Find overall minimum and maximum distances of knn neighbors - excluding initial 0s\n\tmindis = results.ndist[1];\n\tmaxdis = results.ndist[k-1];\n\n\t// Locally reduce minimum and maximum\n\tfor(int i = 0; i < n; i++){\n\t\tif(results.ndist[k*i] < mindis)\n\t\t\tmindis = results.ndist[k*i + 1];\n\t\tif(results.ndist[k*i + k - 1] > maxdis)\n\t\t\tmaxdis = results.ndist[k*i + k - 1];\n\t}\n\t\n\n\tMPI_Reduce(&mindis, &tempmindis, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);\n\tMPI_Reduce(&maxdis, &tempmaxdis, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);\n\n\tend = MPI_Wtime();\n\tprintf(\"Execution time for node %d: %f s\\n\", id, end-start);\n\n\tif(id == 0){\n\n\t\tif(mindis < tempmindis)\n\t\t\ttempmindis = mindis;\n\t\tif(maxdis > tempmaxdis)\n\t\t\ttempmaxdis = maxdis;\n\t\tprintf(\"Minimum distance is %f, maximum is %f\\n\", tempmindis, tempmaxdis);\n\t\tprintf(\"Note: this message is printed twice because the tester runs two tests: one for column major and one for row major in this order.\\n\");\n\t}\n\n\treturn results;\n}\n\n\n// Application Entry Point\nknnresult kNN(double * X, double * Y, int n, int m, int d, int k)\n{\n\n\t// Calculate distances matrix D - D is row-major and nxm\n\tdouble* tempD = calculateD(X, Y, n, m, d, k);\n\n\tdouble* D = calloc(m*n, sizeof(double)); \n\n\t// Transpose D to mxn\n\t//cblas_dimatcopy(CblasRowMajor, CblasTrans, n, m, 1.0, D, m, n);\n\t\n\tdouble* identityMat = calloc(n*n, sizeof(double));\n\tfor(int f=0; f\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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n/*User includes*/\n#include \"c_vbgmm_fit.h\"\n\nvoid c_vbgmm_fit (double* adX, int nN, int nD, int nK, int seed, int* anAssign, int nThreads, int nIter)\n{\n int debug = 0;\n int bAssign = 0;\n\n if (nIter < 1){\n nIter = DEF_MAX_ITER;\n }\n\n driverMP(adX, nN, nD, anAssign, nK, seed, nIter, DEF_EPSILON, debug, bAssign, nThreads);\n\n return;\n}\n\nint driverMP(double *adX, int nN, int nD, int *anAssign, int nKStart, unsigned long lSeed, \n int nMaxIter, double dEpsilon, int debug, int bAssign, int nThreads)\n{\n t_Params tParams;\n t_Data tData;\n gsl_rng *ptGSLRNG = NULL;\n const gsl_rng_type *ptGSLRNGType = NULL;\n t_VBParams tVBParams;\n t_Cluster *ptCluster = NULL;\n int i = 0, nK = nKStart, nNthreads = 0;\n int nT = 0;\n char *szCOutFile = NULL;\n\n /*initialise GSL RNG*/\n gsl_rng_env_setup();\n\n gsl_set_error_handler_off();\n\n ptGSLRNGType = gsl_rng_default;\n ptGSLRNG = gsl_rng_alloc(ptGSLRNGType);\n\n /*set OMP thread number*/\n nNthreads = nThreads;\n nT = nN / 32 + 1;\n printf(\"%d %d %d\\n\",nN,nT,nNthreads);\n if (nT < nNthreads){\n nNthreads = nT;\n }\n \n omp_set_num_threads(nNthreads);\n fprintf(stderr,\"Setting %d OMP threads\\n\",nNthreads);\n\n /*set clusters params*/\n tParams.nKStart = nKStart;\n tParams.nMaxIter = nMaxIter;\n tParams.dEpsilon = dEpsilon;\n tParams.lSeed = lSeed;\n \n fprintf(stderr,\"Generate input data\\n\");\n fflush(stderr);\n generateInputData(adX, nN, nD, &tData);\n\n setVBParams(&tVBParams, &tData);\n\n if(debug>0){\n szCOutFile = (char *) malloc(sizeof(char)*MAX_FILE_NAME_LENGTH);\n \n\t sprintf(szCOutFile,\"%sr%d.csv\",DEF_FILE_STUB,0);\n\t}\n\n if(bAssign > 0){\n nK = 0;\n \n for(i = 0; i < nN; i++){\n if(anAssign[i] > nK){\n nK = anAssign[i];\n }\n }\n }\n ptCluster = malloc(sizeof(t_Cluster));\n allocateCluster(ptCluster,nN,nK,nD,&tData,lSeed,nMaxIter,dEpsilon,szCOutFile);\n\n ptCluster->bAssign = bAssign;\n if(bAssign > 0){ \n for(i = 0; i < nN; i++){\n ptCluster->anMaxZ[i] = anAssign[i];\n }\n }\n\n ptCluster->ptVBParams = &tVBParams;\n \n ptCluster->nThread = 0;\n\n fitEM_MP((void *) ptCluster);\n\n compressCluster(ptCluster);\n\n calcCovarMatrices(ptCluster,&tData);\n\n for(i = 0; i < nN; i++){\n anAssign[i] = ptCluster->anMaxZ[i];\n }\n\n if(debug>0){\n free(szCOutFile);\n\t}\n\n /*free up memory in data object*/\n destroyData(&tData);\n\n /*free up best BIC clusters*/\n\n destroyCluster(ptCluster);\n free(ptCluster);\n\n gsl_rng_free(ptGSLRNG);\n gsl_matrix_free(tVBParams.ptInvW0);\n\n return EXIT_SUCCESS;\n \n memoryError:\n fprintf(stderr, \"Failed allocating memory in driver\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid generateInputData(double *adX, int nN, int nD, t_Data *ptData)\n{\n double **aadX = NULL;\n int i = 0, j = 0;\n\n /*allocate memory for data matrix*/\n aadX = (double **) malloc(nN*sizeof(double*));\n if(!aadX)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n aadX[i] = (double *) malloc(nD*sizeof(double));\n if(!aadX[i])\n\t goto memoryError;\n }\n\n for(i = 0; i < nN; i++){\n for(j = 0; j < nD; j++){\n aadX[i][j] = adX[i*nD + j];\n }\n }\n ptData->nD = nD;\n ptData->nN = nN;\n ptData->aadX = aadX;\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in readInputData\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid destroyData(t_Data *ptData)\n{\n int nN = ptData->nN;\n int i = 0;\n\n for(i = 0; i < nN; i++){\n free(ptData->aadX[i]);\n }\n free(ptData->aadX);\n\n return;\n}\n\nvoid calcSampleVar(t_Data *ptData,double *adVar, double *adMu)\n{\n double **aadX = ptData->aadX;\n int i = 0, n = 0;\n int nD = ptData->nD, nN = ptData->nN;\n /*sample means*/\n double dN = (double) nN;\n\n for(i = 0; i < nD; i++){\n adMu[i] = 0.0;\n adVar[i] = 0.0;\n }\n\n for(i = 0; i < nD; i++){\n for(n = 0; n < nN; n++){\n adMu[i] += aadX[n][i];\n adVar[i] += aadX[n][i]*aadX[n][i];\n }\n\n adMu[i] /= dN;\n\n adVar[i] = (adVar[i] - dN*adMu[i]*adMu[i])/(dN - 1.0);\n }\n\n return;\n}\n\nvoid setVBParams(t_VBParams *ptVBParams, t_Data *ptData)\n{\n int i = 0, nD = ptData->nD;\n double adVar[nD], adMu[nD];\n\n ptVBParams->dBeta0 = DEF_BETA0;\n ptVBParams->dNu0 = (double) nD;\n ptVBParams->ptInvW0 = gsl_matrix_alloc(nD,nD);\n\n calcSampleVar(ptData,adVar, adMu);\n gsl_matrix_set_zero (ptVBParams->ptInvW0);\n\n for(i = 0; i < nD; i++){\n double dRD = adVar[i]*((double) nD);\n\n gsl_matrix_set(ptVBParams->ptInvW0,i,i,dRD);\n }\n\n ptVBParams->dLogWishartB = dLogWishartB(ptVBParams->ptInvW0, nD, ptVBParams->dNu0, TRUE);\n}\n\nvoid allocateCluster(t_Cluster *ptCluster, int nN, int nK, int nD, t_Data *ptData, long lSeed, int nMaxIter, double dEpsilon, char *szCOutFile)\n{\n int i = 0, j = 0, k = 0;\n\n ptCluster->szCOutFile = szCOutFile;\n ptCluster->ptVBParams = NULL;\n ptCluster->lSeed = lSeed;\n ptCluster->nMaxIter = nMaxIter;\n ptCluster->dEpsilon = dEpsilon;\n ptCluster->ptData = ptData;\n\n ptCluster->nN = nN;\n ptCluster->nK = nK;\n ptCluster->nKSize = nK;\n ptCluster->nD = nD;\n\n ptCluster->dVBL = 0.0;\n\n ptCluster->anMaxZ = (int *) malloc(nN*sizeof(int)); /*destroyed*/\n if(!ptCluster->anMaxZ)\n goto memoryError;\n\n ptCluster->anW = (int *) malloc(nK*sizeof(int)); /*destroyed*/\n if(!ptCluster->anW)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n ptCluster->anMaxZ[i] = NOT_SET;\n }\n\n for(i = 0; i < nK; i++){\n ptCluster->anW[i] = 0;\n }\n\n ptCluster->aadZ = (double **) malloc(nN*sizeof(double *)); /*destroyed*/\n if(!ptCluster->aadZ)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n ptCluster->aadZ[i] = (double *) malloc(nK*sizeof(double)); /*destroyed*/\n if(!ptCluster->aadZ[i])\n goto memoryError;\n\n for(j = 0; j < nK; j++){\n ptCluster->aadZ[i][j] = 0.0;\n }\n }\n\n ptCluster->adLDet = (double *) malloc(nK*sizeof(double)); /*all*/\n ptCluster->adPi = (double *) malloc(nK*sizeof(double));\n ptCluster->adBeta = (double *) malloc(nK*sizeof(double));\n ptCluster->adNu = (double *) malloc(nK*sizeof(double)); /*destroyed*/\n\n if(!ptCluster->adLDet || !ptCluster->adPi)\n goto memoryError;\n\n if(!ptCluster->adBeta || !ptCluster->adNu)\n goto memoryError;\n\n for(k = 0; k < nK; k++){\n ptCluster->adLDet[k] = 0.0;\n ptCluster->adPi[k] = 0.0;\n ptCluster->adBeta[k] = 0.0;\n ptCluster->adNu[k] = 0.0;\n }\n\n ptCluster->aadMu = (double **) malloc(nK*sizeof(double *));\n if(!ptCluster->aadMu)\n goto memoryError;\n\n ptCluster->aadM = (double **) malloc(nK*sizeof(double *));\n if(!ptCluster->aadM)\n goto memoryError;\n\n for(i = 0; i < nK; i++){\n ptCluster->aadM[i] = (double*) malloc (nD*sizeof(double));\n if(!ptCluster->aadM[i])\n goto memoryError;\n\n ptCluster->aadMu[i] = (double*) malloc (nD*sizeof(double));\n if(!ptCluster->aadMu[i])\n goto memoryError;\n }\n\n ptCluster->aptSigma = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *));\n if(!ptCluster->aptSigma)\n goto memoryError;\n\n for(i = 0; i < nK ; i++){\n ptCluster->aptSigma[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD);\n }\n\n ptCluster->aptCovar = (gsl_matrix **) malloc(nK*sizeof(gsl_matrix *));\n if(!ptCluster->aptCovar)\n goto memoryError;\n\n for(i = 0; i < nK ; i++){\n ptCluster->aptCovar[i] = (gsl_matrix*) gsl_matrix_alloc (nD, nD);\n }\n\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in allocateCluster\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid destroyCluster(t_Cluster* ptCluster)\n{\n int i = 0, nN = ptCluster->nN, nKSize = ptCluster->nKSize;\n\n if(ptCluster->szCOutFile != NULL){\n\t free(ptCluster->szCOutFile);\n }\n\n free(ptCluster->anMaxZ);\n\n free(ptCluster->anW);\n\n for(i = 0; i < nN; i++){\n free(ptCluster->aadZ[i]);\n }\n free(ptCluster->aadZ);\n\n free(ptCluster->adLDet);\n free(ptCluster->adPi);\n free(ptCluster->adBeta);\n free(ptCluster->adNu);\n\n for(i = 0; i < nKSize; i++){\n free(ptCluster->aadMu[i]);\n free(ptCluster->aadM[i]);\n }\n\n free(ptCluster->aadMu);\n free(ptCluster->aadM);\n\n for(i = 0; i < nKSize ; i++){\n gsl_matrix_free(ptCluster->aptSigma[i]);\n gsl_matrix_free(ptCluster->aptCovar[i]);\n }\n free(ptCluster->aptSigma);\n free(ptCluster->aptCovar);\n return;\n}\n\nvoid* fitEM_MP(void *pvCluster)\n{\n t_Cluster *ptCluster = (t_Cluster *) pvCluster;\n gsl_rng *ptGSLRNG = NULL;\n const gsl_rng_type *ptGSLRNGType = NULL;\n int i = 0, k = 0;\n /*initialise GSL RNG*/\n ptGSLRNGType = gsl_rng_default;\n ptGSLRNG = gsl_rng_alloc(ptGSLRNGType);\n\n gsl_rng_set (ptGSLRNG, ptCluster->lSeed);\n\n if(ptCluster->bAssign == FALSE){\n initKMeans(ptGSLRNG, ptCluster, ptCluster->ptData);\n }\n else{\n for(i = 0; i < ptCluster->nN; i++){\n for(k = 0; k < ptCluster->nK; k++){\n ptCluster->aadZ[i][k] = 0.0;\n }\n ptCluster->aadZ[i][ptCluster->anMaxZ[i]] = 1.0;\n }\n performMStepMP(ptCluster, ptCluster->ptData);\n }\n \n gmmTrainVB_MP(ptCluster, ptCluster->ptData);\n\n gsl_rng_free(ptGSLRNG);\n\n return NULL;\n}\n\nvoid compressCluster(t_Cluster *ptCluster)\n{\n int i = 0, k = 0, nNewK = 0, nN = ptCluster->nN;\n double **aadNewZ = NULL, dN = (double) nN;\n\n for(i = 0; i < ptCluster->nK; i++){\n if(ptCluster->adPi[i] > 0.0){\n nNewK++;\n }\n }\n\n aadNewZ = (double **) malloc(nN*sizeof(double *));\n if(!aadNewZ)\n goto memoryError;\n\n for(i = 0; i < nN; i++){\n aadNewZ[i] = (double *) malloc(nNewK*sizeof(double));\n if(!aadNewZ[i])\n goto memoryError;\n }\n\n for(i = 0; i < nN; i++){\n int nC = 0;\n for(k = 0; k < ptCluster->nK; k++){\n if(ptCluster->adPi[k] > 0.0){\n\t aadNewZ[i][nC] = ptCluster->aadZ[i][k];\n\t nC++;\n }\n }\n }\n\n for(i = 0; i < nN; i++){\n free(ptCluster->aadZ[i]);\n }\n free(ptCluster->aadZ);\n\n /*reset Z and K*/\n ptCluster->aadZ = aadNewZ;\n ptCluster->nK = nNewK;\n\n /*recalculate Pi*/\n for(k = 0; k < ptCluster->nK; k++){\n ptCluster->adPi[k] = 0.0;\n for(i = 0; i < nN; i++){\n ptCluster->adPi[k] += ptCluster->aadZ[i][k];\n }\n ptCluster->adPi[k] /= dN;\n }\n\n /*assign to best clusters*/\n for(i = 0; i < nN; i++){\n double dMaxZ = ptCluster->aadZ[i][0];\n int nMaxK = 0;\n for(k = 1; k < ptCluster->nK; k++){\n if(ptCluster->aadZ[i][k] > dMaxZ){\n\t nMaxK = k;\n\t dMaxZ = ptCluster->aadZ[i][k];\n }\n }\n ptCluster->anMaxZ[i] = nMaxK;\n }\n\n for(k = 0; k < ptCluster->nK; k++){\n ptCluster->anW[k] = 0;\n }\n\n for(i = 0; i < nN; i++){\n ptCluster->anW[ptCluster->anMaxZ[i]]++;\n }\n\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in main\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\ndouble decomposeMatrix(gsl_matrix *ptSigmaMatrix, int nD)\n{\n double dDet = 0.0;\n int status;\n int l = 0;\n\n status = gsl_linalg_cholesky_decomp(ptSigmaMatrix);\n\n if(status == GSL_EDOM){\n fprintf(stderr,\"Failed Cholesky decomposition in decomposeMatrix\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n }\n else{\n for(l = 0; l < nD; l++){\n double dT = gsl_matrix_get(ptSigmaMatrix,l,l);\n dDet += 2.0*log(dT);\n }\n gsl_linalg_cholesky_invert(ptSigmaMatrix);\n return dDet;\n }\n}\n\ndouble mstep(int k, double *adMu, double* adM, int nN, int nD, double** aadZ, double** aadX, double *pdBeta, double *pdNu, double *pdLDet, t_VBParams *ptVBParams, gsl_matrix *ptCovarK, gsl_matrix *ptSigmaMatrix)\n{\n double dPi = 0.0, dBeta = 0.0, dLDet = 0.0, dNu = 0.0;\n int i = 0, j = 0, l = 0, m = 0;\n double dF = 0.0;\n double **aadCovar = NULL;\n double **aadInvWK = NULL;\n \n aadCovar = (double **) malloc(nD*sizeof(double*));\n if(!aadCovar)\n goto memoryError;\n\n for(i = 0; i < nD; i++){\n aadCovar[i] = (double *) malloc(nD*sizeof(double));\n if(!aadCovar[i])\n goto memoryError;\n }\n \n aadInvWK = (double **) malloc(nD*sizeof(double*));\n if(!aadInvWK)\n goto memoryError;\n\n for(i = 0; i < nD; i++){\n aadInvWK[i] = (double *) malloc(nD*sizeof(double));\n if(!aadInvWK[i])\n goto memoryError;\n }\n \n /*recompute mixture weights and means*/\n for(j = 0; j < nD; j++){\n adMu[j] = 0.0;\n for(l = 0; l < nD; l++){\n aadCovar[j][l] = 0.0;\n aadInvWK[j][l] = 0.0;\n }\n }\n\n for(i = 0; i < nN; i++){\n if(aadZ[i][k] > MIN_Z){\n dPi += aadZ[i][k];\n for(j = 0; j < nD; j++){\n adMu[j] += aadZ[i][k]*aadX[i][j];\n }\n }\n }\n\n /*normalise means*/\n if(dPi > MIN_PI){\n /*Equation 10.60*/\n dBeta = ptVBParams->dBeta0 + dPi;\n \n for(j = 0; j < nD; j++){\n /*Equation 10.61*/\n adM[j] = adMu[j]/dBeta;\n adMu[j] /= dPi;\n }\n\n dNu = ptVBParams->dNu0 + dPi;\n\n /*calculate covariance matrices*/\n for(i = 0; i < nN; i++){\n if(aadZ[i][k] > MIN_Z){\n double adDiff[nD];\n\n for(j = 0; j < nD; j++){\n adDiff[j] = aadX[i][j] - adMu[j];\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <=l ; m++){\n aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m];\n }\n }\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = l + 1; m < nD; m++){\n aadCovar[l][m] = aadCovar[m][l];\n }\n }\n\n /*save sample covariances for later use*/\n for(l = 0; l < nD; l++){\n for(m = 0; m < nD; m++){\n double dC = aadCovar[l][m] / dPi;\n gsl_matrix_set(ptCovarK,l,m,dC);\n }\n }\n\n /*Now perform equation 10.62*/\n dF = (ptVBParams->dBeta0*dPi)/dBeta;\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l; m++){\n aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m) + aadCovar[l][m] + dF*adMu[l]*adMu[m];\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l ; m++){\n aadCovar[l][m] /= dPi;\n gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]);\n gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]);\n }\n }\n\n\n /*Implement Equation 10.65*/\n dLDet = ((double) nD)*log(2.0);\n\n for(l = 0; l < nD; l++){\n double dX = 0.5*(dNu - (double) l);\n dLDet += gsl_sf_psi (dX);\n }\n\n dLDet -= decomposeMatrix(ptSigmaMatrix,nD);\n }\n else{\n /*Equation 10.60*/\n dPi = 0.0;\n\n dBeta = ptVBParams->dBeta0;\n\n for(j = 0; j < nD; j++){\n /*Equation 10.61*/\n adM[j] = 0.0;\n adMu[j] = 0.0;\n }\n\n dNu = ptVBParams->dNu0;\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l; m++){\n aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m);\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l ; m++){\n aadInvWK[l][m] = gsl_matrix_get(ptVBParams->ptInvW0, l,m);\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m <= l ; m++){\n gsl_matrix_set(ptSigmaMatrix, l, m, aadInvWK[l][m]);\n gsl_matrix_set(ptSigmaMatrix, m, l, aadInvWK[l][m]);\n }\n }\n\n /*Implement Equation 10.65*/\n dLDet = ((double) nD)*log(2.0);\n\n for(l = 0; l < nD; l++){\n double dX = 0.5*(dNu - (double) l);\n dLDet += gsl_sf_psi (dX);\n }\n\n dLDet -= decomposeMatrix(ptSigmaMatrix,nD);\n }\n \n /*free up memory*/\n for(i = 0; i < nD; i++){\n free(aadCovar[i]);\n free(aadInvWK[i]);\n }\n\n free(aadCovar);\n free(aadInvWK);\n \n (*pdBeta) = dBeta;\n (*pdNu) = dNu;\n (*pdLDet) = dLDet;\n return dPi;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in mstep\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid performMStepMP(t_Cluster *ptCluster, t_Data *ptData){\n int k = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX;\n double **aadCovar = NULL, **aadInvWK = NULL;\n t_VBParams *ptVBParams = ptCluster->ptVBParams;\n\n /*perform M step*/\n#pragma omp parallel for\n for(int k = 0; k < nK; k++){ /*loop components*/\n double dPi = 0.0, dBeta = 0.0, dNu = 0.0, dLDet = 0.0;\n\n dPi = mstep(k, ptCluster->aadMu[k],ptCluster->aadM[k], nN, nD, aadZ, aadX, &dBeta, &dNu, &dLDet, ptVBParams, ptCluster->aptCovar[k], ptCluster->aptSigma[k]);\n \n ptCluster->adPi[k] = dPi;\n ptCluster->adBeta[k] = dBeta;\n ptCluster->adNu[k] = dNu;\n ptCluster->adLDet[k] = dLDet;\n }\n\n /*Normalise pi*/\n\n if(1){\n double dNP = 0.0;\n\n for(k = 0; k < nK; k++){\n dNP += ptCluster->adPi[k];\n }\n\n for(k = 0; k < nK; k++){\n ptCluster->adPi[k] /= dNP;\n }\n }\n\n return;\n\n memoryError:\n fprintf(stderr, \"Failed allocating memory in performMStep\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\nvoid initKMeans(gsl_rng *ptGSLRNG, t_Cluster *ptCluster, t_Data *ptData)\n{\n /*very simple initialisation assign each data point to random cluster*/\n int i = 0, k = 0, nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadMu = ptCluster->aadMu, **aadX = ptData->aadX;\n int *anMaxZ = ptCluster->anMaxZ, *anW = ptCluster->anW, nChange = nN;\n int nIter = 0, nMaxIter = ptCluster->nMaxIter;\n for(i = 0; i < nN; i++){\n int nIK = gsl_rng_uniform_int (ptGSLRNG, nK);\n ptCluster->anMaxZ[i] = nIK;\n anW[nIK]++;\n }\n\n updateMeans(ptCluster, ptData);\n\n while(nChange > 0 && nIter < nMaxIter){\n nChange = 0;\n /*reassign vectors*/\n for(i = 0; i < nN; i++){\n double dMinDist = DBL_MAX;\n int nMinK = NOT_SET;\n\n for(k = 0; k < nK; k++){\n\t double dDist = calcDist(aadX[i],aadMu[k],nD);\n\n\t if(dDist < dMinDist){\n\t nMinK = k;\n\t dMinDist = dDist;\n\t }\n }\n\n if(nMinK != anMaxZ[i]){\n int nCurr = anMaxZ[i];\n\t nChange++;\n\t anW[nCurr]--;\n\t anW[nMinK]++;\n\t anMaxZ[i] = nMinK;\n\n\t /*check for empty clusters*/\n\t if(anW[nCurr] == 0){\n\t int nRandI = gsl_rng_uniform_int (ptGSLRNG, nN);\n\t int nKI = 0;\n\t /*select at random from non empty clusters*/\n\n\t while(anW[anMaxZ[nRandI]] == 1){\n\t nRandI = gsl_rng_uniform_int (ptGSLRNG, nN);\n\t }\n\n\t nKI = anMaxZ[nRandI];\n\t anW[nKI]--;\n\t anW[nCurr] = 1;\n\t anMaxZ[nRandI] = nCurr;\n\t }\n }\n }\n //printf(\"%d %d\\n\",nIter,nChange);\n nIter++;\n updateMeans(ptCluster, ptData);\n }\n\n for(i = 0; i < nN; i++){\n for(k = 0; k < nK; k++){\n ptCluster->aadZ[i][k] = 0.0;\n }\n ptCluster->aadZ[i][anMaxZ[i]] = 1.0;\n }\n\n performMStepMP(ptCluster, ptData);\n return;\n}\n\ndouble eqnA(int nD, gsl_matrix *ptCovarK, gsl_matrix *ptSigmaK, double *adMuK, double *adMK, double dLDetK, double dNuK, double logd2Pi, double dBetaK,double dNK)\n{\n int l = 0;\n gsl_matrix *ptRes = gsl_matrix_alloc(nD,nD);\n gsl_vector *ptDiff = gsl_vector_alloc(nD); \n double dT1 = 0.0, dT2 = 0.0, dF = 0.0;\n gsl_vector *ptR = gsl_vector_alloc(nD);\n double dD = (double) nD;\n double dRet = 0.0;\n \n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptCovarK,ptSigmaK,0.0,ptRes);\n\n for(l = 0; l < nD; l++){\n\t dT1 += gsl_matrix_get(ptRes,l,l);\n }\n\n for(l = 0; l < nD; l++){\n gsl_vector_set(ptDiff,l,adMuK[l] - adMK[l]);\n }\n\n gsl_blas_dsymv (CblasLower, 1.0, ptSigmaK, ptDiff, 0.0, ptR);\n\n gsl_blas_ddot (ptDiff, ptR, &dT2);\n\n dF = dLDetK - dNuK*(dT1 + dT2) - dD*(logd2Pi + (1.0/dBetaK));\n\n dRet = 0.5*dNK*dF;\n\n gsl_matrix_free(ptRes);\n gsl_vector_free(ptDiff);\n gsl_vector_free(ptR);\n\n return dRet;\n}\n\ndouble eqnB(int nD, gsl_matrix *ptInvW0, gsl_matrix *ptSigmaK, double* adMK, double dBeta0, double d2Pi, double dLDetK, double dBetaK, double dNuK, double dNu0)\n{\n int l = 0;\n double dD = (double) nD;\n gsl_matrix *ptRes = gsl_matrix_alloc(nD,nD);\n gsl_vector *ptDiff = gsl_vector_alloc(nD);\n gsl_vector *ptR = gsl_vector_alloc(nD); \n double dT1 = 0.0, dT2 = 0.0, dF = 0.0;\n double dRet = 0.0;\n \n gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,ptInvW0,ptSigmaK,0.0,ptRes);\n\n for(l = 0; l < nD; l++){\n dT1 += gsl_matrix_get(ptRes,l,l);\n }\n\n for(l = 0; l < nD; l++){\n\t gsl_vector_set(ptDiff,l,adMK[l]);\n }\n\n gsl_blas_dsymv (CblasLower, 1.0, ptSigmaK, ptDiff, 0.0, ptR);\n\n gsl_blas_ddot (ptDiff, ptR, &dT2);\n\n dF = dD*log(dBeta0/d2Pi) + dLDetK - ((dD*dBeta0)/dBetaK) - dBeta0*dNuK*dT2 - dNuK*dT1;\n\n dRet = 0.5*(dF + (dNu0 - dD - 1.0)*dLDetK);\n\n gsl_matrix_free(ptRes);\n gsl_vector_free(ptDiff);\n gsl_vector_free(ptR);\n \n return dRet;\n}\n\n\ndouble calcVBL_MP(t_Cluster* ptCluster)\n{\n int nN = ptCluster->nN;\n int nK = ptCluster->nK, nD = ptCluster->nD;\n double dBishop1 = 0.0, dBishop2 = 0.0, dBishop3 = 0.0, dBishop4 = 0.0, dBishop5 = 0.0; /*Bishop equations 10.71...*/\n double dD = (double) nD;\n double** aadMu = ptCluster->aadMu, **aadM = ptCluster->aadM, **aadZ = ptCluster->aadZ;\n double* adBeta = ptCluster->adBeta, *adNu = ptCluster->adNu, *adLDet = ptCluster->adLDet, *adPi = ptCluster->adPi;\n double adNK[nK], adRet[nK];\n double d2Pi = 2.0*M_PI, logd2Pi = log(d2Pi), dBeta0 = ptCluster->ptVBParams->dBeta0, dNu0 = ptCluster->ptVBParams->dNu0, dRet = 0.0;\n double dK = 0.0;\n\n for(int k = 0; k < nK; k++){\n adNK[k] = 0.0;\n }\n\n /*Equation 10.72*/\n for(int i = 0; i < nN; i++){\n for(int k = 0; k < nK; k++){\n adNK[k] += aadZ[i][k];\n if(adPi[k] > 0.0){\n\t dBishop2 += aadZ[i][k]*log(adPi[k]);\n }\n }\n }\n\n\n for(int k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n dK++;\n }\n }\n\n /*Equation 10.71*/\n#pragma omp parallel for\n for(int k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n adRet[k] = eqnA(nD, ptCluster->aptCovar[k], ptCluster->aptSigma[k], aadMu[k], aadM[k], adLDet[k], adNu[k], logd2Pi, adBeta[k],adNK[k]);\n }\n else{\n adRet[k] = 0.0;\n }\n }\n \n for(int k = 0; k < nK; k++){\n dBishop1 += adRet[k];\n }\n \n \n /*Equation 10.74*/\n#pragma omp parallel for\n for(int k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n adRet[k] = eqnB(nD, ptCluster->ptVBParams->ptInvW0, ptCluster->aptSigma[k], aadM[k], ptCluster->ptVBParams->dBeta0, d2Pi, adLDet[k], adBeta[k], adNu[k],ptCluster->ptVBParams->dNu0);\n } \n }\n\n for(int k = 0; k < nK; k++){\n dBishop3 += adRet[k];\n }\n\n dBishop3 += dK*ptCluster->ptVBParams->dLogWishartB;\n\n /*Equation 10.75*/\n for(int i = 0; i < nN; i++){\n for(int k = 0; k < nK; k++){\n if(aadZ[i][k] > 0.0){\n\t dBishop4 += aadZ[i][k]*log(aadZ[i][k]);\n }\n }\n }\n\n /*Equation 10.77*/\n for(int k = 0; k < nK; k++){\n if(adNK[k] > 0.0){\n dBishop5 += 0.5*adLDet[k] + 0.5*dD*log(adBeta[k]/d2Pi) - 0.5*dD - dWishartExpectLogDet(ptCluster->aptSigma[k], adNu[k], nD);\n }\n }\n\n dRet = dBishop1 + dBishop2 + dBishop3 - dBishop4 - dBishop5;\n\n return dRet;\n}\n\nvoid calcZ_MP(t_Cluster* ptCluster, t_Data *ptData){\n double **aadX = ptData->aadX, **aadZ = ptCluster->aadZ;\n int nK = ptCluster->nK, nD = ptCluster->nD, nN = ptData->nN;\n double dD = (double) nD;\n double** aadM = ptCluster->aadM, *adPi = ptCluster->adPi;\n\n#pragma omp parallel for\n for(int i = 0; i < nN; i++){\n double dMinDist = DBL_MAX;\n double dTotalZ = 0.0;\n double dNTotalZ = 0.0;\n double adDist[nK];\n int k = 0, l = 0;\n gsl_vector *ptDiff = gsl_vector_alloc(nD);\n gsl_vector *ptRes = gsl_vector_alloc(nD);\n \n\n for(k = 0; k < nK; k++){\n if(adPi[k] > 0.){\n /*set vector to data point*/\n for(l = 0; l < nD; l++){\n gsl_vector_set(ptDiff,l,aadX[i][l] - aadM[k][l]);\n }\n\n gsl_blas_dsymv (CblasLower, 1.0, ptCluster->aptSigma[k], ptDiff, 0.0, ptRes);\n\n gsl_blas_ddot (ptDiff, ptRes, &adDist[k]);\n\n adDist[k] *= ptCluster->adNu[k];\n\n adDist[k] -= ptCluster->adLDet[k];\n\n adDist[k] += dD/ptCluster->adBeta[k];\n\n if(adDist[k] < dMinDist){\n dMinDist = adDist[k];\n }\n }\n }\n\n for(k = 0; k < nK; k++){\n if(adPi[k] > 0.){\n aadZ[i][k] = adPi[k]*exp(-0.5*(adDist[k]-dMinDist));\n dTotalZ += aadZ[i][k];\n }\n else{\n aadZ[i][k] = 0.0;\n }\n }\n\n for(k = 0; k < nK; k++){\n double dF = aadZ[i][k] / dTotalZ;\n if(dF < MIN_Z){\n aadZ[i][k] = 0.0;\n }\n dNTotalZ += aadZ[i][k];\n }\n if(dNTotalZ > 0.){\n for(k = 0; k < nK; k++){\n aadZ[i][k] /= dNTotalZ;\n }\n }\n gsl_vector_free(ptRes);\n gsl_vector_free(ptDiff);\n }\n\n return;\n}\n\nvoid gmmTrainVB_MP(t_Cluster *ptCluster, t_Data *ptData)\n{\n int i = 0, k = 0,nIter = 0;\n int nN = ptData->nN, nK = ptCluster->nK;\n /*change in log-likelihood*/\n double dLastVBL = 0.0, dDelta = DBL_MAX;\n double **aadZ = ptCluster->aadZ;\n int nMaxIter = ptCluster->nMaxIter;\n double dEpsilon = ptCluster->dEpsilon;\n FILE *ofp = NULL;\n\n if(ptCluster->szCOutFile){\n\t ofp = fopen(ptCluster->szCOutFile,\"w\");\n\t if(!ofp){\n\t\t fprintf(stderr, \"Failed to open file %s in gmmTrainVB\\n\",ptCluster->szCOutFile);\n\t\t fflush(stderr);\n\t }\n }\n\n /*calculate data likelihood*/\n calcZ_MP(ptCluster,ptData);\n ptCluster->dVBL = calcVBL_MP(ptCluster);\n\n while(nIter < nMaxIter && dDelta > dEpsilon){\n\n /*update parameter estimates*/\n performMStepMP(ptCluster, ptData);\n\n /*calculate responsibilities*/\n calcZ_MP(ptCluster,ptData);\n\n dLastVBL = ptCluster->dVBL;\n ptCluster->dVBL = calcVBL_MP(ptCluster);\n dDelta = fabs(ptCluster->dVBL - dLastVBL);\n\n fprintf(stderr,\"%d,%f,%f\\n\",nIter, ptCluster->dVBL, dDelta);\n fflush(stderr);\n if(ofp){\n \t fprintf(ofp,\"%d,%f,%f,\",nIter, ptCluster->dVBL, dDelta);\n \t for(k = 0; k < nK-1; k++){\n \t\t fprintf(ofp,\"%f,\",ptCluster->adPi[k]);\n \t }\n \t fprintf(ofp,\"%f\\n\",ptCluster->adPi[nK - 1]);\n\t fflush(ofp);\n }\n nIter++;\n }\n\n if(ofp){\n\t fclose(ofp);\n }\n\n /*assign to best clusters*/\n for(i = 0; i < nN; i++){\n double dMaxZ = aadZ[i][0];\n int nMaxK = 0;\n for(k = 1; k < nK; k++){\n if(aadZ[i][k] > dMaxZ){\n\t nMaxK = k;\n\t dMaxZ = aadZ[i][k];\n }\n }\n ptCluster->anMaxZ[i] = nMaxK;\n }\n\n return;\n}\n\nvoid calcCovarMatrices(t_Cluster *ptCluster, t_Data *ptData)\n{\n int i = 0, j = 0, k = 0, l = 0, m = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n double **aadZ = ptCluster->aadZ,**aadX = ptData->aadX;\n double *adPi = ptCluster->adPi, **aadCovar = NULL;\n double dN = (double) nN;\n\n aadCovar = (double **) malloc(nD*sizeof(double*));\n if(!aadCovar)\n goto memoryError;\n\n for(i = 0; i < nD; i++){\n aadCovar[i] = (double *) malloc(nD*sizeof(double));\n if(!aadCovar[i])\n goto memoryError;\n }\n\n\n for(k = 0; k < nK; k++){ /*loop components*/\n double* adMu = ptCluster->aadMu[k];\n gsl_matrix *ptSigmaMatrix = ptCluster->aptSigma[k];\n /*recompute mixture weights and means*/\n for(j = 0; j < nD; j++){\n adMu[j] = 0.0;\n for(l = 0; l < nD; l++){\n\t aadCovar[j][l] = 0.0;\n }\n /*prevents singularities*/\n aadCovar[j][j] = MIN_COVAR;\n }\n\n /* compute weight associated with component k*/\n adPi[k] = 0.0;\n for(i = 0; i < nN; i++){\n adPi[k] += aadZ[i][k];\n for(j = 0; j < nD; j++){\n\t adMu[j] += aadZ[i][k]*aadX[i][j];\n }\n }\n /*normalise means*/\n for(j = 0; j < nD; j++){\n adMu[j] /= adPi[k];\n }\n\n /*calculate covariance matrices*/\n for(i = 0; i < nN; i++){\n double adDiff[nD];\n\n for(j = 0; j < nD; j++){\n\t adDiff[j] = aadX[i][j] - adMu[j];\n }\n\n for(l = 0; l < nD; l++){\n\t for(m = 0; m <=l ; m++){\n\t aadCovar[l][m] += aadZ[i][k]*adDiff[l]*adDiff[m];\n\t }\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = l + 1; m < nD; m++){\n\t aadCovar[l][m] = aadCovar[m][l];\n }\n }\n\n for(l = 0; l < nD; l++){\n for(m = 0; m < nD; m++){\n\t aadCovar[l][m] /= adPi[k];\n\t gsl_matrix_set(ptSigmaMatrix, l, m, aadCovar[l][m]);\n }\n }\n\n adPi[k] /= dN; /*normalise weights*/\n }\n /*free up memory*/\n for(i = 0; i < nD; i++){\n free(aadCovar[i]);\n }\n\n //gsl_matrix_free(ptSigmaMatrix);\n free(aadCovar);\n\n return;\n memoryError:\n fprintf(stderr, \"Failed allocating memory in performMStep\\n\");\n fflush(stderr);\n exit(EXIT_FAILURE);\n}\n\n/*note assuming you are using inverse W matrix*/\ndouble dLogWishartB(gsl_matrix *ptInvW, int nD, double dNu, int bInv)\n{\n int i = 0;\n double dRet = 0.0, dT = 0.0;\n double dLogDet = 0.0, dD = (double) nD;\n gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD);\n\n gsl_matrix_memcpy(ptTemp, ptInvW);\n\n dLogDet = decomposeMatrix(ptTemp, nD);\n\n if(bInv == TRUE){\n dRet = 0.5*dNu*dLogDet;\n }\n else{\n dRet = -0.5*dNu*dLogDet;\n }\n\n dT = 0.5*dNu*dD*log(2.0);\n\n dT += 0.25*dD*(dD - 1.0)*log(M_PI);\n\n for(i = 0; i < nD; i++){\n dT += gsl_sf_lngamma(0.5*(dNu - (double) i));\n }\n\n gsl_matrix_free(ptTemp);\n\n return dRet - dT;\n}\n\ndouble dWishartExpectLogDet(gsl_matrix *ptW, double dNu, int nD)\n{\n int i = 0;\n double dRet = 0.0, dLogDet = 0.0, dD = (double) nD;\n gsl_matrix* ptTemp = gsl_matrix_alloc(nD,nD);\n\n gsl_matrix_memcpy(ptTemp, ptW);\n\n dLogDet = decomposeMatrix(ptW, nD);\n\n dRet = dD*log(2.0) + dLogDet;\n\n for(i = 0; i < nD; i++){\n dRet += gsl_sf_psi(0.5*(dNu - (double) i));\n }\n\n gsl_matrix_free(ptTemp);\n\n return dRet;\n}\n\nvoid updateMeans(t_Cluster *ptCluster, t_Data *ptData)\n{\n int i = 0, j = 0, k = 0;\n int nN = ptData->nN, nK = ptCluster->nK, nD = ptData->nD;\n int *anMaxZ = ptCluster->anMaxZ;\n int *anW = ptCluster->anW;\n double **aadX = ptData->aadX, **aadMu = ptCluster->aadMu;\n\n for(k = 0; k < nK; k++){\n\n for(j = 0; j < nD; j++){\n aadMu[k][j] = 0.0;\n }\n }\n\n for(i = 0; i < nN; i++){\n int nZ = anMaxZ[i];\n\n for(j = 0; j < nD; j++){\n aadMu[nZ][j] += aadX[i][j];\n }\n }\n\n for(k = 0; k < nK; k++){ /*loop components*/\n\n /*normalise means*/\n if(anW[k] > 0){\n for(j = 0; j < nD; j++){\n\t aadMu[k][j] /= (double) anW[k];\n }\n }\n else{\n for(j = 0; j < nD; j++){\n\t aadMu[k][j] = 0.0;\n }\n }\n }\n\n return;\n}\n\ndouble calcDist(double* adX, double *adMu, int nD)\n{\n double dDist = 0.0;\n int i = 0;\n\n for(i = 0; i < nD; i++){\n double dV = adX[i] - adMu[i];\n dDist += dV*dV;\n }\n\n return sqrt(dDist);\n}\n", "meta": {"hexsha": "0d844c60a5e5424070c3a49f18d1c3521179447f", "size": 32962, "ext": "c", "lang": "C", "max_stars_repo_path": "c-concoct/c_vbgmm_fit.c", "max_stars_repo_name": "merenlab/CONCOCT", "max_stars_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 79.0, "max_stars_repo_stars_event_min_datetime": "2015-01-16T15:08:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:12:15.000Z", "max_issues_repo_path": "c-concoct/c_vbgmm_fit.c", "max_issues_repo_name": "merenlab/CONCOCT", "max_issues_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 156.0, "max_issues_repo_issues_event_min_datetime": "2015-01-07T07:51:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T03:26:12.000Z", "max_forks_repo_path": "c-concoct/c_vbgmm_fit.c", "max_forks_repo_name": "merenlab/CONCOCT", "max_forks_repo_head_hexsha": "78068456416934daea22fa19531b16cdecda6a39", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2015-06-03T18:30:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T08:31:46.000Z", "avg_line_length": 25.1234756098, "max_line_length": 211, "alphanum_fraction": 0.5239063164, "num_tokens": 11365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.41869690935568665, "lm_q1q2_score": 0.3442480515038424}} {"text": "#ifndef UTILS_H\n#define UTILS_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#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#define outlog(format, args...) \\\n fprintf(stderr, format, args); \\\n fprintf(stderr, \"\\n\");\n\nint compare (const void * a, const void * b);\n\ninline double safe_log(double x) {\n if (x <= 0)\n return(-10000);\n else \n return(log(x));\n}\ndouble log_sum(double, double);\n\ninline double vget(const gsl_vector* v, int i) { return(gsl_vector_get(v, i)); }\n\ninline void vset(gsl_vector* v, int i, double x) { gsl_vector_set(v, i, x); }\n\n// Increment a vector element by a double.\ninline void vinc(gsl_vector* v, int i, double x) {\n vset(v, i, vget(v, i) + x);\n}\n\ninline double mget(const gsl_matrix* m, int i, int j)\n{ return(gsl_matrix_get(m, i, j)); }\n\ninline void mset(gsl_matrix* m, int i, int j, double x)\n{ gsl_matrix_set(m, i, j, x); }\n\n// Increment a matrix element by a double.\nvoid minc(gsl_matrix*, int, int, double);\n\nvoid col_sum(const gsl_matrix*, gsl_vector*);\nvoid row_sum(const gsl_matrix*, gsl_vector*);\n\nvoid vct_fprintf(FILE* file, const gsl_vector* v);\nvoid mtx_fprintf(FILE* file, const gsl_matrix* m);\nvoid mtx_fscanf(FILE* file, gsl_matrix* m);\n\ninline bool check_sym(const gsl_matrix *m) {\n for (size_t i = 0; i < m->size1-1; i ++)\n for (size_t j=i; j < m->size2; j ++)\n if (mget(m, i, j) != mget(m, j, i)) {\n printf(\"not sym\\n\");\n return false;\n }\n return true;\n}\n\ndouble log_det(const gsl_matrix*);\n\nvoid matrix_inverse(const gsl_matrix*, gsl_matrix*);\nvoid matrix_vector_solve(const gsl_matrix* m, const gsl_vector* b, gsl_vector* v);\n\nvoid sym_eigen(gsl_matrix*, gsl_vector*, gsl_matrix*);\n\ninline double vsum(const gsl_vector* v) {\n double val = 0;\n int i, size = v->size;\n for (i = 0; i < size; i++)\n val += vget(v, i);\n return(val);\n}\n\ndouble vnorm(const gsl_vector * v);\n\nvoid gsl_vector_apply(gsl_vector* x, double(*fun)(double));\nvoid vct_log(gsl_vector* v);\nvoid mtx_log(gsl_matrix* x);\nvoid vct_exp(gsl_vector* x);\nvoid mtx_exp(gsl_matrix* x);\n\ndouble mahalanobis_distance(const gsl_matrix * m, const gsl_vector* u, const gsl_vector* v);\ndouble mahalanobis_prod(const gsl_matrix * m, const gsl_vector* u, const gsl_vector* v);\ndouble matrix_dot_prod(const gsl_matrix * m1, const gsl_matrix* m2);\n\nvoid choose_k_from_n(int k, int n, int* result, int* src);\n\ndouble log_normalize(gsl_vector* x);\ndouble vnormalize(gsl_vector* x);\n\nint dir_exists(const char *dname);\nbool file_exists(const char * filename);\nvoid make_directory(const char* name);\n\ndouble digamma(double x);\nunsigned int rmultinomial(const gsl_vector* v);\ndouble rgamma(double a, double b);\ndouble rbeta(double a, double b);\nunsigned int rbernoulli(double p);\ndouble runiform();\nvoid rshuffle (void* base, size_t n, size_t size);\nunsigned long int runiform_int(unsigned long int n);\n\n// new and free random number generator\ngsl_rng* new_random_number_generator(long seed);\nvoid free_random_number_generator(gsl_rng * random_number_generator);\n\n#endif\n", "meta": {"hexsha": "c41f4dcc7f2c8c8b8ca0f219ee610cd4aa2b84a9", "size": 3456, "ext": "h", "lang": "C", "max_stars_repo_path": "ctr/utils.h", "max_stars_repo_name": "SergiuTripon/irdm-collaborative-filtering", "max_stars_repo_head_hexsha": "8d214517a1fc3c8fbdf990b9da30f3e9c8b32c5f", "max_stars_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-17T16:08:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-17T16:08:04.000Z", "max_issues_repo_path": "ctr/utils.h", "max_issues_repo_name": "SergiuTripon/irdm-collaborative-filtering", "max_issues_repo_head_hexsha": "8d214517a1fc3c8fbdf990b9da30f3e9c8b32c5f", "max_issues_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ctr/utils.h", "max_forks_repo_name": "SergiuTripon/irdm-collaborative-filtering", "max_forks_repo_head_hexsha": "8d214517a1fc3c8fbdf990b9da30f3e9c8b32c5f", "max_forks_repo_licenses": ["Python-2.0", "OLDAP-2.7"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2016-07-21T09:56:48.000Z", "max_forks_repo_forks_event_max_datetime": "2016-07-21T09:56:48.000Z", "avg_line_length": 27.4285714286, "max_line_length": 92, "alphanum_fraction": 0.708912037, "num_tokens": 992, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982043529715, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.34411647820698654}} {"text": "#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"../cosmolike_core/theory/basics.c\"\n#include \"../cosmolike_core/theory/structs.c\"\n#include \"../cosmolike_core/theory/parameters.c\"\n#include \"../cosmolike_core/emu17/P_cb/emu.c\"\n#include \"../cosmolike_core/theory/recompute.c\"\n#include \"../cosmolike_core/theory/cosmo3D.c\"\n#include \"../cosmolike_core/theory/redshift_spline.c\"\n#include \"../cosmolike_core/theory/halo.c\"\n#include \"../cosmolike_core/theory/HOD.c\"\n#include \"../cosmolike_core/theory/pt.c\"\n#include \"../cosmolike_core/theory/cosmo2D_fourier.c\"\n#include \"../cosmolike_core/theory/IA.c\"\n#include \"../cosmolike_core/theory/cluster.c\"\n#include \"../cosmolike_core/theory/BAO.c\"\n#include \"../cosmolike_core/theory/external_prior.c\"\n#include \"../cosmolike_core/theory/covariances_3D.c\"\n#include \"../cosmolike_core/theory/covariances_fourier.c\"\n#include \"../cosmolike_core/theory/covariances_cluster.c\"\n#include \"init_emu.c\"\n\nvoid run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start);\nvoid run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start);\nvoid run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start);\nvoid run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster);\nvoid run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);\nvoid run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);\nvoid run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);\nvoid run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);\nvoid run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start);\nvoid run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start);\n\nvoid run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_clustering_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_clustering_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_clustering(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_ggl(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\nvoid run_cov_shear_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start);\n\n\nvoid run_cov_N_N (char *OUTFILE, char *PATH, int nzc1, int nzc2,int start)\n{\n int nN1, nN2,i,j;\n double cov;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n i += Cluster.N200_Nbin*nzc1+nN1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n\n cov =cov_N_N(nzc1,nN1, nzc2, nN2);\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,0.0,0.0, nzc1, nN1, nzc2, nN2,cov,0.0);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cgl_N (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int nzc2, int start)\n{\n int nN1, nN2, nl1, nzc1, nzs1,i,j;\n double cov;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzc1 = ZC(N1);\n nzs1 = ZSC(N1);\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n\n cov =cov_cgl_N(ell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2);\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell_Cluster[nl1], 0., nzc1, nzs1, nzc2, nN2,cov,0.);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cgl_cgl (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int start)\n{\n int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j;\n double c_g, c_ng;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzc1 = ZC(N1);\n nzs1 = ZSC(N1);\n nzc2 = ZC(N2);\n nzs2 = ZSC(N2);\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;\n\n c_g = 0;\n c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2);\n if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);}\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nzs1, nzc2, nzs2,c_g, c_ng);\n }\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cgl_cgl_all (char *OUTFILE, char *PATH, double *ell_Cluster, double *dell_Cluster)\n{\n int nN1, nN2, nl1, nzc1, nzs1, nl2, nzc2, nzs2,i,j, N1,N2;\n double c_g, c_ng;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s\",PATH,OUTFILE);\n F1 =fopen(filename,\"w\");\n for (N1 = 0; N1 < tomo.cgl_Npowerspectra; N1 ++){\n for (N2 = 0; N2 < tomo.cgl_Npowerspectra; N2 ++){\n nzc1 = ZC(N1);\n nzs1 = ZSC(N1);\n nzc2 = ZC(N2);\n nzs2 = ZSC(N2);\n for (nN1 = 0; nN1 < Cluster.N200_Nbin; nN1 ++){\n for( nl1 = 0; nl1 < Cluster.lbin; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n i += (N1*Cluster.N200_Nbin+nN1)*Cluster.lbin +nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; \n c_g = 0;\n c_ng = cov_NG_cgl_cgl(ell_Cluster[nl1],ell_Cluster[nl2],nzc1,nN1, nzs1, nzc2, nN2,nzs2);\n if (nl2 == nl1){c_g =cov_G_cgl_cgl(ell_Cluster[nl1],dell_Cluster[nl1],nzc1,nN1, nzs1, nzc2, nN2,nzs2);}\n fprintf(F1,\"%d %d %e %e %d %d %d %d %d %d %e %e\\n\",i,j,ell_Cluster[nl1],ell_Cluster[nl2], nzc1, nN1,nzs1, nzc2, nN2,nzs2,c_g, c_ng);\n }\n }\n }\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_shear_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start)\n{\n int nz1,nz2, nN2, nl1, nzc1, i,j;\n double cov;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nz1 = Z1(N1);\n nz2 = Z2(N1);\n for( nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n cov = 0.;\n i = like.Ncl*N1+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n\n if (ell[nl1] < like.lmax_shear){cov =cov_shear_N(ell[nl1],nz1,nz2, nzc2, nN2);}\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell[nl1], 0., nz1, nz2, nzc2, nN2,cov,0.);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_shear_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)\n{\n int nN1, nN2, nzs1, nzs2,nl2, nzc2, nzs3,i,j;\n double c_g, c_ng;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzs1 = Z1(N1);\n nzs2 = Z2(N1);\n nzc2 = ZC(N2);\n nzs3 = ZSC(N2);\n for(nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*N1+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2; \n c_g = 0.;\n c_ng = 0.;\n if (ell[nl1] < like.lmax_shear){\n c_ng = cov_NG_shear_cgl(ell[nl1],ell_Cluster[nl2],nzs1, nzs2, nzc2, nN2,nzs3);\n if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.001){ \n c_g =cov_G_shear_cgl(ell[nl1],dell_Cluster[nl2],nzs1,nzs2, nzc2, nN2,nzs3);\n }\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], nzs1, nzs2, nzc2, nzs3,c_g, c_ng);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_ggl_N (char *OUTFILE, char *PATH, double *ell, double *dell, int N1, int nzc2, int start)\n{\n int zl,zs, nN2, nl1, nzc1, i,j;\n double cov,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n zl = ZL(N1);\n zs = ZS(N1);\n for( nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n cov = 0.;\n weight = test_kmax(ell[nl1],zl);\n if (weight){\n cov =cov_ggl_N(ell[nl1],zl,zs, nzc2, nN2);\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell[nl1], 0., zl, zs, nzc2, nN2,cov,0.);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_ggl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)\n{\n int nN2, zl, zs, nzs1, nl2, nzc2, nzs3,i,j;\n double c_g, c_ng,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n zl = ZL(N1);\n zs = ZS(N1);\n nzc2 = ZC(N2);\n nzs3 = ZSC(N2);\n for(nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;\n\n c_g = 0; c_ng = 0.;\n weight = test_kmax(ell[nl1],zl);\n if (weight){\n c_ng = cov_NG_ggl_cgl(ell[nl1],ell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);\n if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){c_g =cov_G_ggl_cgl(ell[nl1],dell_Cluster[nl2],zl,zs, nzc2, nN2,nzs3);}\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], zl, zs, nzc2, nzs3,c_g, c_ng);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cl_N (char *OUTFILE, char *PATH, double *ell, double *dell,int N1, int nzc2, int start)\n{\n int zl,zs, nN2, nl1, nzc1, i,j;\n double cov,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n for( nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra);\n j += Cluster.N200_Nbin*nzc2+nN2;\n cov = 0.;\n weight = test_kmax(ell[nl1],N1);\n if (weight){\n cov =cov_cl_N(ell[nl1],N1,N1,nzc2,nN2);\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j, ell[nl1], 0., N1, N1, nzc2, nN2,cov,0.);\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_cl_cgl (char *OUTFILE, char *PATH, double *ell, double *dell, double *ell_Cluster, double *dell_Cluster,int N1, int N2, int nl1, int start)\n{\n int nN2,nzc2, nzs3,i,j,nl2;\n double c_g, c_ng,weight;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\");\n nzc2 = ZC(N2);\n nzs3 = ZSC(N2);\n for(nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nN2 = 0; nN2 < Cluster.N200_Nbin; nN2 ++){\n for( nl2 = 0; nl2 < Cluster.lbin; nl2 ++){\n i = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+N1)+nl1;\n j = like.Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra+tomo.clustering_Npowerspectra)+Cluster.N200_Nbin*tomo.cluster_Nbin;\n j += (N2*Cluster.N200_Nbin+nN2)*Cluster.lbin +nl2;\n\n c_g = 0; c_ng = 0.;\n weight = test_kmax(ell[nl1],N1);\n if (weight){\n c_ng = cov_NG_cl_cgl(ell[nl1],ell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3);\n if (fabs(ell[nl1]/ell_Cluster[nl2] -1.) < 0.1){\n c_g =cov_G_cl_cgl(ell[nl1],dell_Cluster[nl2],N1,N1, nzc2, nN2,nzs3);\n }\n }\n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng);\n //printf(\"%d %d %e %e %d %d %d %d %e %e\\n\",i,j,ell[nl1],ell_Cluster[nl2], N1,N1, nzc2, nzs3,c_g, c_ng);\n }\n }\n }\n fclose(F1);\n}\n\nvoid run_cov_ggl_shear(char *OUTFILE, char *PATH, double *ell, double *dell, int n1, int n2,int start)\n{\n int zl,zs,z3,z4,nl1,nl2,weight;\n double c_ng, c_g;\n FILE *F1;\n char filename[300];\n sprintf(filename,\"%s%s_%d\",PATH,OUTFILE,start);\n F1 =fopen(filename,\"w\"); \n zl = ZL(n1); zs = ZS(n1);\n printf(\"\\nN_ggl = %d (%d, %d)\\n\", n1,zl,zs);\n z3 = Z1(n2); z4 = Z2(n2);\n printf(\"N_shear = %d (%d, %d)\\n\", n2,z3,z4);\n for (nl1 = 0; nl1 < like.Ncl; nl1 ++){\n for (nl2 = 0; nl2 like.lmax_shear && n1!=n2){c_g = 0.;} \n } \n fprintf(F1,\"%d %d %e %e %d %d %d %d %e %e\\n\",like.Ncl*n1+nl1,like.Ncl*(n2)+nl2,ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);\n //printf(\"%d %d %e %e %d %d %d %d %e %e\\n\", like.Ncl*n1+nl1,like.Ncl*(n2)+nl2, ell[nl1],ell[nl2],z1,z2,z3,z4,c_g,c_ng);\n }\n }\n fclose(F1);\n}\n\n\nint main(int argc, char** argv)\n{\n \n int i,l,m,n,o,s,p,nl1,t,k;\n char OUTFILE[400],filename[400],arg1[400],arg2[400];\n \n int N_scenarios=36;\n double area_table[36]={7623.22,14786.3,9931.47,8585.43,17681.8,15126.9,9747.99,8335.08,9533.42,18331.3,12867.8,17418.9,19783.1,12538.8,15260.0,16540.7,19636.8,11112.7,10385.5,16140.2,18920.1,17976.2,11352.0,9214.77,16910.7,11995.6,16199.8,14395.1,8133.86,13510.5,19122.3,15684.5,12014.8,14059.7,10919.3,13212.7};\n double nsource_table[36]={13.991,33.3975,17.069,28.4875,35.3643,10.3802,11.1105,29.5904,31.4608,15.7463,13.3066,9.07218,9.58719,16.3234,25.8327,10.7415,38.0412,32.8821,19.8893,27.0369,15.1711,14.2418,19.1851,26.926,22.0012,12.6553,18.6304,11.9787,36.8728,22.5265,17.4381,12.3424,10.0095,23.5979,20.8771,24.8956};\n \n double nlens_table[36]={22.9726 ,61.5948 ,28.7809 ,51.4354 ,65.7226 ,16.3777 ,17.6899 ,53.6984 ,57.562 ,26.266 ,21.703 ,14.0587 ,14.9667 ,27.36 ,46.0364 ,17.0253 ,71.39 ,60.5184 ,34.2283 ,48.4767 ,25.1812 ,23.44 ,32.8578 ,48.2513 ,38.3766 ,20.5029 ,31.783 ,19.2647 ,68.9094 ,39.4168 ,29.4874 ,19.9292 ,15.7162 ,41.5487 ,36.1616 ,44.148};\n \n char source_zfile[36][400]={\"wl_redshift_model0_WLz01.880307e-01_WLalpha8.485694e-01.txt\", \"wl_redshift_model1_WLz01.731166e-01_WLalpha7.662434e-01.txt\", \"wl_redshift_model2_WLz01.846221e-01_WLalpha8.297540e-01.txt\", \"wl_redshift_model3_WLz01.758423e-01_WLalpha7.812893e-01.txt\", \"wl_redshift_model4_WLz01.721357e-01_WLalpha7.608290e-01.txt\", \"wl_redshift_model5_WLz01.931476e-01_WLalpha8.768147e-01.txt\", \"wl_redshift_model6_WLz01.919821e-01_WLalpha8.703814e-01.txt\", \"wl_redshift_model7_WLz01.751912e-01_WLalpha7.776952e-01.txt\", \"wl_redshift_model8_WLz01.741405e-01_WLalpha7.718958e-01.txt\", \"wl_redshift_model9_WLz01.860048e-01_WLalpha8.373865e-01.txt\", \"wl_redshift_model10_WLz01.888904e-01_WLalpha8.533151e-01.txt\", \"wl_redshift_model11_WLz01.954564e-01_WLalpha8.895592e-01.txt\", \"wl_redshift_model12_WLz01.945099e-01_WLalpha8.843347e-01.txt\", \"wl_redshift_model13_WLz01.853877e-01_WLalpha8.339802e-01.txt\", \"wl_redshift_model14_WLz01.775192e-01_WLalpha7.905458e-01.txt\", \"wl_redshift_model15_WLz01.925611e-01_WLalpha8.735775e-01.txt\", \"wl_redshift_model16_WLz01.708849e-01_WLalpha7.539247e-01.txt\", \"wl_redshift_model17_WLz01.733832e-01_WLalpha7.677150e-01.txt\", \"wl_redshift_model18_WLz01.820009e-01_WLalpha8.152851e-01.txt\", \"wl_redshift_model19_WLz01.767381e-01_WLalpha7.862345e-01.txt\", \"wl_redshift_model20_WLz01.866426e-01_WLalpha8.409073e-01.txt\", \"wl_redshift_model21_WLz01.877261e-01_WLalpha8.468882e-01.txt\", \"wl_redshift_model22_WLz01.826188e-01_WLalpha8.186960e-01.txt\", \"wl_redshift_model23_WLz01.768086e-01_WLalpha7.866234e-01.txt\", \"wl_redshift_model24_WLz01.802711e-01_WLalpha8.057362e-01.txt\", \"wl_redshift_model25_WLz01.897506e-01_WLalpha8.580632e-01.txt\", \"wl_redshift_model26_WLz01.831217e-01_WLalpha8.214720e-01.txt\", \"wl_redshift_model27_WLz01.906926e-01_WLalpha8.632630e-01.txt\", \"wl_redshift_model28_WLz01.714197e-01_WLalpha7.568766e-01.txt\", \"wl_redshift_model29_WLz01.798667e-01_WLalpha8.035040e-01.txt\", \"wl_redshift_model30_WLz01.842554e-01_WLalpha8.277299e-01.txt\", \"wl_redshift_model31_WLz01.901797e-01_WLalpha8.604322e-01.txt\", \"wl_redshift_model32_WLz01.937710e-01_WLalpha8.802561e-01.txt\", \"wl_redshift_model33_WLz01.790701e-01_WLalpha7.991072e-01.txt\", \"wl_redshift_model34_WLz01.811701e-01_WLalpha8.106987e-01.txt\", \"wl_redshift_model35_WLz01.781525e-01_WLalpha7.940419e-01.txt\"};\n\n char lens_zfile[36][400]={\"LSS_redshift_model0_LSSz02.629496e-01_LSSalpha9.285983e-01.txt\",\"LSS_redshift_model1_LSSz02.852923e-01_LSSalpha8.985943e-01.txt\",\"LSS_redshift_model2_LSSz02.664822e-01_LSSalpha9.186036e-01.txt\",\"LSS_redshift_model3_LSSz02.798758e-01_LSSalpha9.014201e-01.txt\",\"LSS_redshift_model4_LSSz02.873873e-01_LSSalpha8.978683e-01.txt\",\"LSS_redshift_model5_LSSz02.593970e-01_LSSalpha9.470921e-01.txt\",\"LSS_redshift_model6_LSSz02.600213e-01_LSSalpha9.425114e-01.txt\",\"LSS_redshift_model7_LSSz02.811155e-01_LSSalpha9.006370e-01.txt\",\"LSS_redshift_model8_LSSz02.831875e-01_LSSalpha8.995165e-01.txt\",\"LSS_redshift_model9_LSSz02.649368e-01_LSSalpha9.224338e-01.txt\",\"LSS_redshift_model10_LSSz02.622058e-01_LSSalpha9.314128e-01.txt\",\"LSS_redshift_model11_LSSz02.584820e-01_LSSalpha9.568082e-01.txt\",\"LSS_redshift_model12_LSSz02.588053e-01_LSSalpha9.527220e-01.txt\",\"LSS_redshift_model13_LSSz02.656075e-01_LSSalpha9.206866e-01.txt\",\"LSS_redshift_model14_LSSz02.768397e-01_LSSalpha9.037492e-01.txt\",\"LSS_redshift_model15_LSSz02.596975e-01_LSSalpha9.447600e-01.txt\",\"LSS_redshift_model16_LSSz02.901709e-01_LSSalpha8.971658e-01.txt\",\"LSS_redshift_model17_LSSz02.847362e-01_LSSalpha8.988183e-01.txt\",\"LSS_redshift_model18_LSSz02.698330e-01_LSSalpha9.121821e-01.txt\",\"LSS_redshift_model19_LSSz02.782257e-01_LSSalpha9.026084e-01.txt\",\"LSS_redshift_model20_LSSz02.642756e-01_LSSalpha9.243038e-01.txt\",\"LSS_redshift_model21_LSSz02.632273e-01_LSSalpha9.276296e-01.txt\",\"LSS_redshift_model22_LSSz02.689934e-01_LSSalpha9.135968e-01.txt\",\"LSS_redshift_model23_LSSz02.780987e-01_LSSalpha9.027073e-01.txt\",\"LSS_redshift_model24_LSSz02.723464e-01_LSSalpha9.085463e-01.txt\",\"LSS_redshift_model25_LSSz02.615210e-01_LSSalpha9.343470e-01.txt\",\"LSS_redshift_model26_LSSz02.683327e-01_LSSalpha9.147934e-01.txt\",\"LSS_redshift_model27_LSSz02.608392e-01_LSSalpha9.376962e-01.txt\",\"LSS_redshift_model28_LSSz02.889655e-01_LSSalpha8.974355e-01.txt\",\"LSS_redshift_model29_LSSz02.729686e-01_LSSalpha9.077654e-01.txt\",\"LSS_redshift_model30_LSSz02.669178e-01_LSSalpha9.176391e-01.txt\",\"LSS_redshift_model31_LSSz02.612016e-01_LSSalpha9.358553e-01.txt\",\"LSS_redshift_model32_LSSz02.591077e-01_LSSalpha9.496317e-01.txt\",\"LSS_redshift_model33_LSSz02.742326e-01_LSSalpha9.063038e-01.txt\",\"LSS_redshift_model34_LSSz02.710103e-01_LSSalpha9.103760e-01.txt\",\"LSS_redshift_model35_LSSz02.757517e-01_LSSalpha9.047459e-01.txt\"};\n\n char survey_designation[1][200]={\"LSST\"};\n char tomo_binning_source[1][200]={\"source_std\"};\n char tomo_binning_lens[1][200]={\"LSST_gold\"};\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n // use this remapping only if files fail !!!!!!!!! \n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n // int fail[5]={1134, 259, 497, 623, 718};\n // hit=fail[hit-1];\n //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n \n int hit=atoi(argv[1]);\n Ntable.N_a=20;\n k=1;\n \n for(t=0;t<1;t++){\n \n //RUN MODE setup\n init_cosmo_runmode(\"emu\");\n init_binning_fourier(15,20.0,3000.0,3000.0,21.0,10,10);\n init_survey(survey_designation[0],nsource_table[t],nlens_table[t],area_table[t]);\n sprintf(arg1,\"zdistris/%s\",source_zfile[t]);\n sprintf(arg2,\"zdistris/%s\",lens_zfile[t]); \n init_galaxies(arg1,arg2,\"gaussian\",\"gaussian\",tomo_binning_source[0],tomo_binning_lens[0]);\n init_IA(\"none\", \"GAMA\"); \n init_probes(\"3x2pt\");\n \n\n //set l-bins for shear, ggl, clustering, clusterWL\n double logdl=(log(like.lmax)-log(like.lmin))/like.Ncl;\n double *ell, *dell, *ell_Cluster, *dell_Cluster;\n ell=create_double_vector(0,like.Ncl-1);\n dell=create_double_vector(0,like.Ncl-1);\n ell_Cluster=create_double_vector(0,Cluster.lbin-1);\n dell_Cluster=create_double_vector(0,Cluster.lbin-1);\n int j=0;\n for(i=0;ilike.lmax_shear){\n ell_Cluster[j]=ell[i];\n dell_Cluster[j]=dell[i];\n printf(\"%le %le\\n\",ell[i],ell_Cluster[j]);\n j++;\n }\n } \n\n\n printf(\"----------------------------------\\n\"); \n survey.area=area_table[t];\n survey.n_gal=nsource_table[t];\n survey.n_lens=nlens_table[t]; \n \n sprintf(survey.name,\"%s_area%le_ng%le_nl%le\",survey_designation[0],survey.area,survey.n_gal,survey.n_lens);\n printf(\"area: %le n_source: %le n_lens: %le\\n\",survey.area,survey.n_gal,survey.n_lens);\n\n// sprintf(covparams.outdir,\"/home/u17/timeifler/covparallel/\"); \n sprintf(covparams.outdir,\"/aurora_nobackup/cosmos/teifler/covparallel/\");\n\n printf(\"----------------------------------\\n\"); \n sprintf(OUTFILE,\"%s_ssss_cov_Ncl%d_Ntomo%d\",survey.name,like.Ncl,tomo.shear_Nbin);\n for (l=0;l\n#include \n#include \n#include \n#include \n#include \n#include \"tz_error.h\"\n#include \"tz_constant.h\"\n#include \"tz_voxel_linked_list.h\"\n#include \"tz_stack_sampling.h\"\n#include \"tz_voxel_graphics.h\"\n#include \"tz_stack_code.h\"\n#include \"tz_stack_math.h\"\n#include \"tz_stack_utils.h\"\n#include \"tz_objdetect.h\"\n#include \"tz_voxeltrans.h\"\n#include \"tz_stack_stat.h\"\n#include \"tz_stack_draw.h\"\n#include \"tz_geo3d_vector.h\"\n#include \"tz_stack_bwmorph.h\"\n#include \"tz_stack_bwdist.h\"\n#include \"tz_neurotrace.h\"\n#include \"tz_locseg_chain.h\"\n#include \"tz_trace_utils.h\"\n#include \"tz_stack_threshold.h\"\n#include \"tz_darray.h\"\n\nINIT_EXCEPTION_MAIN(e)\n\nint main(int argc, char* argv[])\n{\n char neuron_name[100];\n if (argc == 1) {\n strcpy(neuron_name, \"fly_neuron\");\n } else {\n strcpy(neuron_name, argv[1]);\n }\n\n char file_path[100];\n\n#if 1\n sprintf(file_path, \"../data/%s/bundle_seed.tif\", neuron_name);\n Stack *stack = Read_Stack(file_path);\n Voxel_List *list = Stack_To_Voxel_List(stack);\n\n sprintf(file_path, \"../data/%s/bundle_seeds.pa\", neuron_name);\n Pixel_Array *pa = Pixel_Array_Read(file_path);\n\n Voxel *seed;\n\n int i;\n double *pa_array = (double *) pa->array;\n\n printf(\"mean: %g, std: %g\\n\", gsl_stats_mean(pa_array, 1, pa->size), \n\t sqrt(gsl_stats_variance(pa_array, 1, pa->size)));\n \n double threshold = gsl_stats_mean(pa_array, 1, pa->size) + \n 3.0 * sqrt(gsl_stats_variance(pa_array, 1, pa->size));\n\n double max_r = gsl_stats_max(pa_array, 1, pa->size);\n \n printf(\"%g, %g\\n\", threshold, max_r);\n\n max_r = max_r * 2;\n Set_Neuroseg_Max_Radius(max_r / 2.0);\n\n dim_type dim[3];\n dim[0] = stack->width;\n dim[1] = stack->height;\n dim[2] = stack->depth;\n\n Kill_Stack(stack);\n\n sprintf(file_path, \"../data/%s/bundle.tif\", neuron_name);\n stack = Read_Stack(file_path);\n\n Rgb_Color color;\n Set_Color(&color, 255, 0, 0);\n\n sprintf(file_path, \"../data/%s.tif\", neuron_name);\n Stack *signal = Read_Stack(file_path);\n\n Stack *canvas = NULL;\n\n char trace_mask_path[100]; \n sprintf(trace_mask_path, \"../data/%s/trace_mask.tif\", neuron_name);\n char trace_file_path[100];\n sprintf(trace_file_path, \"../data/%s/traced.tif\", neuron_name);\n \n if (fexist(trace_file_path) == 1) {\n canvas = Read_Stack((char *) trace_file_path);\n } else {\n canvas = Translate_Stack(signal, COLOR, 0);\n }\n\n Stack *traced = NULL;\n \n\n if (fexist(trace_mask_path) == 1) {\n traced = Read_Stack((char *) trace_mask_path);\n if (traced->kind != GREY16) {\n Translate_Stack(traced, GREY16, 1);\n }\n } else {\n traced = Make_Stack(GREY16, signal->width, signal->height, signal->depth);\n Zero_Stack(traced);\n }\n \n Neurochain *chain = NULL;\n\n double z_scale = 1.0;\n sprintf(file_path, \"../data/%s.res\", neuron_name);\n if (fexist(file_path)) {\n double res[3];\n int length;\n darray_read2(file_path, res, &length);\n if (res[0] != res[1]) {\n perror(\"Different X-Y resolutions.\");\n TZ_ERROR(ERROR_DATA_VALUE);\n }\n z_scale = res[0] / res[2];\n }\n\n /*\n sprintf(file_path, \"../data/%s/soma.tif\", neuron_name);\n Stack *soma = Read_Stack(file_path);\n Stack_Threshold(soma, 1);\n Stack_Binarize(soma);\n Stack_Not(soma, soma);\n Stack_And(traced, soma, traced);\n Kill_Stack(soma);\n */\n\n tic();\n\n FILE *fp = NULL;\n char chain_file_path[100];\n char vrml_file_path[100];\n int seg_idx = 229;\n int min_chain_length = 4;\n\n#define TRY_NEXT_SEED(current_seed)\t\t\t\\\n Kill_Voxel(current_seed);\t\t\t\t\\\n continue;\n\n#define STOP_TRACING(current_seed)\t\t\t\\\n Kill_Voxel(current_seed);\t\t\t\t\\\n break;\n\n Trace_Workspace *tw = New_Trace_Workspace();\n tw->length = 200;\n tw->fit_first = FALSE;\n tw->tscore_option = 1;\n tw->min_score = 0.4;\n tw->trace_direction = DL_BOTHDIR;\n tw->trace_mask = traced;\n tw->dyvar[0] = max_r;\n tw->test_func = Locseg_Chain_Trace_Test;\n\n int chain_id = 100;\n\n char chain_info_file_path[100];\n sprintf(chain_info_file_path, \"../data/%s/chain_info.txt\", neuron_name);\n FILE *chain_info_file = fopen(chain_info_file_path, \"w\");\n\n for (i = 0; i < pa->size; i++) {\n /* do not skip seed dequeueing */\n seed = Voxel_Queue_De(&list);\n printf(\"---------------------------------> seed: %d / %d\\n\", i, pa->size);\n \n sprintf(chain_file_path, \"../data/%s/chain%d.bn\", neuron_name, i);\n sprintf(vrml_file_path, \"../data/%s/chain%d.wrl\", neuron_name, i);\n\n if (fexist(chain_file_path) == 1) {\n chain = Read_Neurochain(chain_file_path);\n if (Neurochain_Length(chain, FORWARD) >= min_chain_length) {\n\tWrite_Neurochain_Vrml(vrml_file_path, chain);\n }\n Neurochain_Label(canvas, chain, z_scale);\n Free_Neurochain(chain);\n TRY_NEXT_SEED(seed);\n }\n\n /* for debugging */\n if (i < seg_idx) {\n //TRY_NEXT_SEED(seed);\n }\n /****************/\n \n if (*STACK_PIXEL_16(traced, seed->x, seed->y, seed->z, 0) > 0) {\n TRY_NEXT_SEED(seed);\n }\n\n double width = pa_array[i];\n\n if (width > max_r) {\n TRY_NEXT_SEED(seed);\n }\n\n Print_Voxel(seed);\n printf(\"%g\\n\", width);\n \n int max_level = (int) (width + 0.5);\n if (max_level < 1.1) {\n TRY_NEXT_SEED(seed);\n //max_level = 6;\n }\n\n /* for debugging */\n if (i > seg_idx) {\n //STOP_TRACING(seed);\n }\n /****************/\n\n \n double cpos[3];\n cpos[0] = seed->x;\n cpos[1] = seed->y;\n cpos[2] = seed->z;\n cpos[2] *= z_scale;\n \n Local_Neuroseg *startseg = New_Local_Neuroseg();;\n\n Set_Neuroseg_Position(startseg, cpos, NEUROSEG_CENTER);\n Reset_Neuroseg(&(startseg->seg));\n startseg->seg.r1 = width;\n startseg->seg.r2 = width;\n \n Stack_Fit_Score fs;\n fs.n = 1;\n fs.options[0] = tw->tscore_option;\n\n printf(\"Search orientation ...\\n\");\n Local_Neuroseg_Orientation_Search_C(startseg, signal, z_scale, &fs); \n\n Print_Local_Neuroseg(startseg);\n\n printf(\"Start: \\n\");\n\n Locseg_Chain* locseg_chain = \n Locseg_Chain_Trace_Init(signal, z_scale, startseg, &fs);\n \n \n if (fs.scores[0] >= tw->min_score) {\n Locseg_Chain_Iterator_Start(locseg_chain, DL_HEAD);\n Local_Neuroseg *head = Locseg_Chain_Next(locseg_chain);\n if ((head->seg.r1 < max_r) && (head->seg.r2 < max_r)) {\n\tTrace_Locseg(signal, z_scale, locseg_chain, tw);\n\tchain = Neurochain_From_Locseg_Chain(locseg_chain);\n\t//chain = Trace_Neuron2(signal, chain, BOTH, traced, z_scale, 100);\n\n\tprintf(\"Remove ends ...\\n\");\n\tchain = Neurochain_Remove_Overlap_Ends(chain);\n\tchain = Neurochain_Remove_Turn_Ends(chain, 1.0);\n\n\t//Print_Neurochain(Neurochain_Head(chain));\n\t//Stack_Draw_Object_Bwc(canvas, obj, color);\n\tNeurochain *chain_head = Neurochain_Head(chain);\n\n\tprintf(\"Saving ...\\n\");\n\tfp = fopen(chain_file_path, \"w\");\n\tNeurochain_Fwrite(chain_head, fp);\n\tfclose(fp);\n\tif (Neurochain_Length(chain_head, FORWARD) >= min_chain_length) {\n\t printf(\"Labeling ...\\n\");\n\t Write_Neurochain_Vrml(vrml_file_path, chain_head);\n\t Neurochain_Label_G(trac, chain_head, z_scale, 0,\n\t\t\t Neurochain_Length(chain_head, FORWARD),\n\t\t\t 1.5, 0.0, chain_id);\n\t fprintf(chain_info_file, \"%d %d %d\\n\", i, chain_id, \n\t\t Neurochain_Length(chain_head, FORWARD));\n\t chain_id++;\n\t Neurochain_Label(canvas, chain_head, z_scale);\n\t Write_Stack((char *) trace_mask_path, traced);\n\t}\n\t//Neurochain_Erase(traced, Neurochain_Head(chain), z_scale);\n\tFree_Neurochain(chain);\n }\n } else {\n printf(\"Ignored seed:\\n\");\n \n }\n\n Kill_Locseg_Chain(locseg_chain);\n Kill_Voxel(seed);\n }\n\n fclose(chain_info_file);\n\n Write_Stack((char *) trace_file_path, canvas);\n\n Kill_Pixel_Array(pa);\n Voxel_List_Removeall(&list);\n\n printf(\"Time passed: %lld\\n\", toc());\n \n#endif\n\n \n return 0;\n}\n", "meta": {"hexsha": "45e514888f44841025665ab0d18be8585309d454", "size": 7741, "ext": "c", "lang": "C", "max_stars_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_fly_neuron3.c", "max_stars_repo_name": "zzhmark/vaa3d_tools", "max_stars_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-27T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T19:14:03.000Z", "max_issues_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_fly_neuron3.c", "max_issues_repo_name": "zzhmark/vaa3d_tools", "max_issues_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-12-03T05:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-03T05:33:13.000Z", "max_forks_repo_path": "released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/c/trace_fly_neuron3.c", "max_forks_repo_name": "zzhmark/vaa3d_tools", "max_forks_repo_head_hexsha": "3ca418add85a59ac7e805d55a600b78330d7e53d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6324503311, "max_line_length": 78, "alphanum_fraction": 0.6528872239, "num_tokens": 2341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7577943712746406, "lm_q2_score": 0.45326184801538616, "lm_q1q2_score": 0.34347927713960125}} {"text": "/**\n *\n * @file core_spamm.c\n *\n * PLASMA core_blas kernel\n * PLASMA is a software package provided by Univ. of Tennessee,\n * Univ. of California Berkeley and Univ. of Colorado Denver\n *\n * @version 2.6.0\n * @author Dulceneia Becker\n * @date 2011-06-14\n * @generated s Tue Jan 7 11:44:49 2014\n *\n **/\n#include \n#include \n#include \"common.h\"\n\nstatic inline int CORE_spamm_a2(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,\n int M, int N, int K, int L,\n int vi2, int vi3,\n float *A2, int LDA2,\n const float *V, int LDV,\n float *W, int LDW);\n\nstatic inline int CORE_spamm_w(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,\n int M, int N, int K, int L,\n int vi2, int vi3,\n const float *A1, int LDA1,\n float *A2, int LDA2,\n const float *V, int LDV,\n float *W, int LDW);\n\n/***************************************************************************//**\n *\n * @ingroup CORE_float\n *\n * ZPAMM performs one of the matrix-matrix operations\n *\n * LEFT RIGHT\n * OP PlasmaW : W = A1 + op(V) * A2 or W = A1 + A2 * op(V)\n * OP PlasmaA2 : A2 = A2 - op(V) * W or A2 = A2 - W * op(V)\n *\n * where op( V ) is one of\n *\n * op( V ) = V or op( V ) = V**T or op( V ) = V**T,\n *\n * A1, A2 and W are general matrices, and V is:\n *\n * l = k: rectangle + triangle\n * l < k: rectangle + trapezoid\n * l = 0: rectangle\n *\n * Size of V, both rowwise and columnwise, is:\n *\n * ----------------------\n * side trans size\n * ----------------------\n * left N M x K\n * T K x M\n * right N K x N\n * T N x K\n * ----------------------\n *\n * LEFT (columnwise and rowwise):\n *\n * | K | | M |\n * _ __________ _ _______________ _\n * | | | | | \\\n * V: | | | V': |_____________|___\\ K\n * | | | M-L | |\n * M | | | |__________________| _\n * |____| | _\n * \\ | | | M - L | L |\n * \\ | | L\n * _ \\|____| _\n *\n *\n * RIGHT (columnwise and rowwise):\n *\n * | K | | N |\n * _______________ _ _ __________ _\n * | | \\ | | |\n * V': |_____________|___\\ N V: | | |\n * | | | | | K-L\n * |__________________| _ K | | |\n * |____| | _\n * | K - L | L | \\ | |\n * \\ | | L\n * _ \\|____| _\n *\n * Arguments\n * ==========\n *\n * @param[in] op\n *\n * OP specifies which operation to perform:\n *\n * @arg PlasmaW : W = A1 + op(V) * A2 or W = A1 + A2 * op(V)\n * @arg PlasmaA2 : A2 = A2 - op(V) * W or A2 = A2 - W * op(V)\n *\n * @param[in] side\n *\n * SIDE specifies whether op( V ) multiplies A2\n * or W from the left or right as follows:\n *\n * @arg PlasmaLeft : multiply op( V ) from the left\n * OP PlasmaW : W = A1 + op(V) * A2\n * OP PlasmaA2 : A2 = A2 - op(V) * W\n *\n * @arg PlasmaRight : multiply op( V ) from the right\n * OP PlasmaW : W = A1 + A2 * op(V)\n * OP PlasmaA2 : A2 = A2 - W * op(V)\n *\n * @param[in] storev\n *\n * Indicates how the vectors which define the elementary\n * reflectors are stored in V:\n *\n * @arg PlasmaColumnwise\n * @arg PlasmaRowwise\n *\n * @param[in] M\n * The number of rows of the A1, A2 and W\n * If SIDE is PlasmaLeft, the number of rows of op( V )\n *\n * @param[in] N\n * The number of columns of the A1, A2 and W\n * If SIDE is PlasmaRight, the number of columns of op( V )\n *\n * @param[in] K\n * If SIDE is PlasmaLeft, the number of columns of op( V )\n * If SIDE is PlasmaRight, the number of rows of op( V )\n *\n * @param[in] L\n * The size of the triangular part of V\n *\n * @param[in] A1\n * On entry, the M-by-N tile A1.\n *\n * @param[in] LDA1\n * The leading dimension of the array A1. LDA1 >= max(1,M).\n *\n * @param[in,out] A2\n * On entry, the M-by-N tile A2.\n * On exit, if OP is PlasmaA2 A2 is overwritten\n *\n * @param[in] LDA2\n * The leading dimension of the tile A2. LDA2 >= max(1,M).\n *\n * @param[in] V\n * The matrix V as described above.\n * If SIDE is PlasmaLeft : op( V ) is M-by-K\n * If SIDE is PlasmaRight: op( V ) is K-by-N\n *\n * @param[in] LDV\n * The leading dimension of the array V.\n *\n * @param[in,out] W\n * On entry, the M-by-N matrix W.\n * On exit, W is overwritten either if OP is PlasmaA2 or PlasmaW.\n * If OP is PlasmaA2, W is an input and is used as a workspace.\n *\n * @param[in] LDW\n * The leading dimension of array WORK.\n *\n *******************************************************************************\n *\n * @return\n * \\retval PLASMA_SUCCESS successful exit\n * \\retval <0 if -i, the i-th argument had an illegal value\n *\n ******************************************************************************/\nint\nCORE_spamm(int op, PLASMA_enum side, PLASMA_enum storev,\n int M, int N, int K, int L,\n const float *A1, int LDA1,\n float *A2, int LDA2,\n const float *V, int LDV,\n float *W, int LDW)\n{\n\n\n int vi2, vi3, uplo, trans, info;\n\n /* Check input arguments */\n if ((op != PlasmaW) && (op != PlasmaA2)) {\n coreblas_error(1, \"Illegal value of op\");\n return -1;\n }\n if ((side != PlasmaLeft) && (side != PlasmaRight)) {\n coreblas_error(2, \"Illegal value of side\");\n return -2;\n }\n if ((storev != PlasmaColumnwise) && (storev != PlasmaRowwise)) {\n coreblas_error(3, \"Illegal value of storev\");\n return -3;\n }\n if (M < 0) {\n coreblas_error(4, \"Illegal value of M\");\n return -4;\n }\n if (N < 0) {\n coreblas_error(5, \"Illegal value of N\");\n return -5;\n }\n if (K < 0) {\n coreblas_error(6, \"Illegal value of K\");\n return -6;\n }\n if (L < 0) {\n coreblas_error(7, \"Illegal value of L\");\n return -7;\n }\n if (LDA1 < 0) {\n coreblas_error(9, \"Illegal value of LDA1\");\n return -9;\n }\n if (LDA2 < 0) {\n coreblas_error(11, \"Illegal value of LDA2\");\n return -11;\n }\n if (LDV < 0) {\n coreblas_error(13, \"Illegal value of LDV\");\n return -13;\n }\n if (LDW < 0) {\n coreblas_error(15, \"Illegal value of LDW\");\n return -15;\n }\n\n /* Quick return */\n if ((M == 0) || (N == 0) || (K == 0))\n return PLASMA_SUCCESS;\n\n /*\n * TRANS is set as:\n *\n * -------------------------------------\n * side direct PlasmaW PlasmaA2\n * -------------------------------------\n * left colwise T N\n * rowwise N T\n * right colwise N T\n * rowwise T N\n * -------------------------------------\n */\n\n /* Columnwise*/\n if (storev == PlasmaColumnwise) {\n uplo = CblasUpper;\n if (side == PlasmaLeft) {\n trans = op == PlasmaA2 ? PlasmaNoTrans : PlasmaTrans;\n vi2 = trans == PlasmaNoTrans ? M - L : K - L;\n }\n else {\n trans = op == PlasmaW ? PlasmaNoTrans : PlasmaTrans;\n vi2 = trans == PlasmaNoTrans ? K - L : N - L;\n }\n vi3 = LDV * L;\n }\n\n /* Rowwise */\n else {\n uplo = CblasLower;\n if (side == PlasmaLeft) {\n trans = op == PlasmaW ? PlasmaNoTrans : PlasmaTrans;\n vi2 = trans == PlasmaNoTrans ? K - L : M - L;\n }\n else {\n trans = op == PlasmaA2 ? PlasmaNoTrans : PlasmaTrans;\n vi2 = trans == PlasmaNoTrans ? N - L : K - L;\n }\n vi2 *= LDV;\n vi3 = L;\n }\n\n /**/\n if (op==PlasmaW) {\n info = CORE_spamm_w(\n side, trans, uplo, M, N, K, L, vi2, vi3,\n A1, LDA1, A2, LDA2, V, LDV, W, LDW);\n if (info != 0)\n return info;\n } else if (op==PlasmaA2) {\n info = CORE_spamm_a2(\n side, trans, uplo, M, N, K, L, vi2, vi3,\n A2, LDA2, V, LDV, W, LDW);\n if (info != 0)\n return info;\n }\n\n return PLASMA_SUCCESS;\n}\n\n/***************************************************************************/\nstatic inline int\nCORE_spamm_w(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,\n int M, int N, int K, int L,\n int vi2, int vi3,\n const float *A1, int LDA1,\n float *A2, int LDA2,\n const float *V, int LDV,\n float *W, int LDW)\n{\n\n /*\n * W = A1 + op(V) * A2 or W = A1 + A2 * op(V)\n */\n\n int j;\n static float zone = 1.0;\n static float zzero = 0.0;\n\n if (side == PlasmaLeft) {\n\n if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||\n ((trans == PlasmaNoTrans) && (uplo == CblasLower))) {\n\n /*\n * W = A1 + V' * A2\n */\n\n /* W = A2_2 */\n LAPACKE_slacpy_work(LAPACK_COL_MAJOR,\n lapack_const(PlasmaUpperLower),\n L, N,\n &A2[K-L], LDA2, W, LDW);\n\n /* W = V_2' * W + V_1' * A2_1 (ge+tr, top L rows of V') */\n if (L > 0) {\n /* W = V_2' * W */\n cblas_strmm(\n CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, L, N,\n (zone), &V[vi2], LDV,\n W, LDW);\n\n /* W = W + V_1' * A2_1 */\n if (K > L) {\n cblas_sgemm(\n CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,\n L, N, K-L,\n (zone), V, LDV,\n A2, LDA2,\n (zone), W, LDW);\n }\n }\n\n /* W_2 = V_3' * A2: (ge, bottom M-L rows of V') */\n if (M > L) {\n cblas_sgemm(\n CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,\n (M-L), N, K,\n (zone), &V[vi3], LDV,\n A2, LDA2,\n (zzero), &W[L], LDW);\n }\n\n /* W = A1 + W */\n for(j = 0; j < N; j++) {\n cblas_saxpy(\n M, (zone),\n &A1[LDA1*j], 1,\n &W[LDW*j], 1);\n }\n }\n else {\n printf(\"Left Upper/NoTrans & Lower/ConjTrans not implemented yet\\n\");\n return PLASMA_ERR_NOT_SUPPORTED;\n\n }\n }\n else { //side right\n\n if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||\n ((trans == PlasmaNoTrans) && (uplo == CblasLower))) {\n printf(\"Right Upper/ConjTrans & Lower/NoTrans not implemented yet\\n\");\n return PLASMA_ERR_NOT_SUPPORTED;\n\n }\n else {\n\n /*\n * W = A1 + A2 * V\n */\n\n if (L > 0) {\n\n /* W = A2_2 */\n LAPACKE_slacpy_work(LAPACK_COL_MAJOR,\n lapack_const(PlasmaUpperLower),\n M, L,\n &A2[LDA2*(K-L)], LDA2, W, LDW);\n\n /* W = W * V_2 --> W = A2_2 * V_2 */\n cblas_strmm(\n CblasColMajor, CblasRight, (CBLAS_UPLO)uplo,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, M, L,\n (zone), &V[vi2], LDV,\n W, LDW);\n\n /* W = W + A2_1 * V_1 */\n if (K > L) {\n cblas_sgemm(\n CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,\n M, L, K-L,\n (zone), A2, LDA2,\n V, LDV,\n (zone), W, LDW);\n }\n\n }\n\n /* W = W + A2 * V_3 */\n if (N > L) {\n cblas_sgemm(\n CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,\n M, N-L, K,\n (zone), A2, LDA2,\n &V[vi3], LDV,\n (zzero), &W[LDW*L], LDW);\n }\n\n /* W = A1 + W */\n for (j = 0; j < N; j++) {\n cblas_saxpy(\n M, (zone),\n &A1[LDA1*j], 1,\n &W[LDW*j], 1);\n }\n }\n }\n\n return PLASMA_SUCCESS;\n}\n\n/***************************************************************************/\nstatic inline int\nCORE_spamm_a2(PLASMA_enum side, PLASMA_enum trans, PLASMA_enum uplo,\n int M, int N, int K, int L,\n int vi2, int vi3,\n float *A2, int LDA2,\n const float *V, int LDV,\n float *W, int LDW)\n{\n\n /*\n * A2 = A2 + op(V) * W or A2 = A2 + W * op(V)\n */\n\n int j;\n static float zone = 1.0;\n static float mzone = -1.0;\n\n if (side == PlasmaLeft) {\n\n if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||\n ((trans == PlasmaNoTrans) && (uplo == CblasLower))) {\n\n printf(\"Left Upper/ConjTrans & Lower/NoTrans not implemented yet\\n\");\n return PLASMA_ERR_NOT_SUPPORTED;\n\n }\n else { //trans\n\n /*\n * A2 = A2 - V * W\n */\n\n /* A2_1 = A2_1 - V_1 * W_1 */\n if (M > L) {\n cblas_sgemm(\n CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,\n M-L, N, L,\n (mzone), V, LDV,\n W, LDW,\n (zone), A2, LDA2);\n }\n\n /* W_1 = V_2 * W_1 */\n cblas_strmm(\n CblasColMajor, CblasLeft, (CBLAS_UPLO)uplo,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, L, N,\n (zone), &V[vi2], LDV,\n W, LDW);\n\n /* A2_2 = A2_2 - W_1 */\n for(j = 0; j < N; j++) {\n cblas_saxpy(\n L, (mzone),\n &W[LDW*j], 1,\n &A2[LDA2*j+(M-L)], 1);\n }\n\n /* A2 = A2 - V_3 * W_2 */\n if (K > L) {\n cblas_sgemm(\n CblasColMajor, (CBLAS_TRANSPOSE)trans, CblasNoTrans,\n M, N, (K-L),\n (mzone), &V[vi3], LDV,\n &W[L], LDW,\n (zone), A2, LDA2);\n }\n\n }\n }\n else { //side right\n\n if (((trans == PlasmaTrans) && (uplo == CblasUpper)) ||\n ((trans == PlasmaNoTrans) && (uplo == CblasLower))) {\n\n /*\n * A2 = A2 - W * V'\n */\n\n /* A2 = A2 - W_2 * V_3' */\n if (K > L) {\n cblas_sgemm(\n CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,\n M, N, K-L,\n (mzone), &W[LDW*L], LDW,\n &V[vi3], LDV,\n (zone), A2, LDA2);\n }\n\n /* A2_1 = A2_1 - W_1 * V_1' */\n if (N > L) {\n cblas_sgemm(\n CblasColMajor, CblasNoTrans, (CBLAS_TRANSPOSE)trans,\n M, N-L, L,\n (mzone), W, LDW,\n V, LDV,\n (zone), A2, LDA2);\n }\n\n /* A2_2 = A2_2 - W_1 * V_2' */\n if (L > 0) {\n cblas_strmm(\n CblasColMajor, CblasRight, (CBLAS_UPLO)uplo,\n (CBLAS_TRANSPOSE)trans, CblasNonUnit, M, L,\n (mzone), &V[vi2], LDV,\n W, LDW);\n\n for (j = 0; j < L; j++) {\n cblas_saxpy(\n M, (zone),\n &W[LDW*j], 1,\n &A2[LDA2*(N-L+j)], 1);\n }\n }\n\n }\n else {\n printf(\"Right Upper/NoTrans & Lower/ConjTrans not implemented yet\\n\");\n return PLASMA_ERR_NOT_SUPPORTED;\n }\n }\n\n return PLASMA_SUCCESS;\n}\n", "meta": {"hexsha": "d64e5b39c283b0862a8f0aea055eef9c4d39d073", "size": 17287, "ext": "c", "lang": "C", "max_stars_repo_path": "core_blas/core_spamm.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_spamm.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_spamm.c", "max_forks_repo_name": "zhuangsc/Plasma-ompss1", "max_forks_repo_head_hexsha": "bcc99c164a256bc7df7c936b9c43afd38c12aea2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7597864769, "max_line_length": 86, "alphanum_fraction": 0.3817897842, "num_tokens": 4787, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7090191337850933, "lm_q2_score": 0.48438008427698437, "lm_q1q2_score": 0.34343474777681793}} {"text": "#include \n#include \n#if !defined(__APPLE__)\n#include \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"../cosmolike_core_fast/theory/basics.c\"\n#include \"../cosmolike_core_fast/theory/structs.c\"\n#include \"../cosmolike_core_fast/theory/parameters.c\"\n#include \"../cosmolike_core_fast/emu17/P_cb/emu.c\"\n#include \"../cosmolike_core_fast/theory/recompute.c\"\n#include \"../cosmolike_core_fast/theory/cosmo3D.c\"\n#include \"../cosmolike_core_fast/theory/redshift_spline.c\"\n#include \"../cosmolike_core_fast/theory/halo.c\"\n#include \"../cosmolike_core_fast/theory/HOD.c\"\n#include \"../cosmolike_core_fast/theory/pt.c\"\n#include \"../cosmolike_core_fast/theory/cosmo2D_fourier.c\"\n#include \"../cosmolike_core_fast/theory/IA.c\"\n// #include \"../cosmolike_core_fast/theory/cluster.c\"\n#include \"../cosmolike_core_fast/theory/BAO.c\"\n#include \"../cosmolike_core_fast/theory/external_prior.c\"\n#include \"../cosmolike_core_fast/theory/init_baryon.c\"\n#include \"init_LSSxCMB.c\"\n\n// Naming convention:\n// g = galaxy positions (\"g\" as in \"galaxy\")\n// k = kappa CMB (\"k\" as in \"kappa\")\n// s = kappa from source galaxies (\"s\" as in \"shear\")\n// And alphabetical order\n\ntypedef double (*C_tomo_pointer)(double l, int n1, int n2);\nvoid twopoint_via_hankel(double **xi, double *logthetamin, double *logthetamax, C_tomo_pointer C_tomo, int ni, int nj, int N_Bessel);\n\n#include \"../cosmolike_core_fast/theory/CMBxLSS_fourier.c\"\n\n\ntypedef struct input_cosmo_params_local {\n double omega_m;\n double sigma_8;\n double n_s;\n double w0;\n double wa;\n double omega_b;\n double h0;\n double MGSigma;\n double MGmu;\n} input_cosmo_params_local;\n\ntypedef struct input_nuisance_params_local {\n double bias[10];\n double source_z_bias[10];\n double source_z_s;\n double lens_z_bias[10];\n double lens_z_s;\n double shear_m[10];\n double A_ia;\n double beta_ia;\n double eta_ia;\n double eta_ia_highz;\n double lf[6];\n double m_lambda[6];\n double bary[3];\n} input_nuisance_params_local;\n\ndouble C_shear_tomo_sys(double ell,int z1,int z2);\n// double C_cgl_tomo_sys(double ell_Cluster,int zl,int nN, int zs);\ndouble C_gl_tomo_sys(double ell,int zl,int zs);\ndouble C_ks_sys(double ell, int zs);\nvoid set_data_shear(int Ncl, double *ell, double *data, int start);\nvoid set_data_ggl(int Ncl, double *ell, double *data, int start);\nvoid set_data_clustering(int Ncl, double *ell, double *data, int start);\nvoid set_data_gk(double *ell, double *data, int start);\nvoid set_data_ks(double *ell, double *data, int start);\nvoid set_data_kk(double *ell, double *data, int start);\n// void compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3);\n// double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3);\nvoid compute_data_vector(char *details, double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3);\ndouble log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3);\n\nvoid write_datavector_wrapper(char *details, input_cosmo_params_local ic, input_nuisance_params_local in);\ndouble log_like_wrapper(input_cosmo_params_local ic, input_nuisance_params_local in);\nint get_N_tomo_shear(void);\nint get_N_tomo_clustering(void);\nint get_N_ggl(void);\nint get_N_ell(void);\n\n\nint get_N_tomo_shear(void){\n return tomo.shear_Nbin;\n}\nint get_N_tomo_clustering(void){\n return tomo.clustering_Nbin;\n}\nint get_N_ggl(void){\n return tomo.ggl_Npowerspectra;\n}\nint get_N_ell(void){\n return like.Ncl;\n}\n\ndouble C_shear_tomo_sys(double ell, int z1, int z2)\n{\n double C;\n // C= C_shear_tomo_nointerp(ell,z1,z2);\n // if(like.IA==1) C+=C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);\n \n if(like.IA!=1) C= C_shear_tomo_nointerp(ell,z1,z2);\n //if(like.IA==1) C= C_shear_shear_IA(ell,z1,z2);\n // clock_t t1, t2; t1=clock();\n // if(like.IA==1) C = C_shear_tomo_nointerp(ell,z1,z2)+C_II_nointerp(ell,z1,z2)+C_GI_nointerp(ell,z1,z2);\n if(like.IA==1) C = C_shear_tomo_nointerp_IA1(ell,z1,z2);\n // t2 = clock(); printf(\"shear %d-%d: %le\\n\",z1,z2, (double)(t2-t1)/CLOCKS_PER_SEC);\n if(like.IA==2) C += C_II_lin_nointerp(ell,z1,z2)+C_GI_lin_nointerp(ell,z1,z2); \n if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[z1])*(1.0+nuisance.shear_calibration_m[z2]);\n //printf(\"%le %d %d %le\\n\",ell,z1,z2,C_shear_tomo_nointerp(ell,z1,z2)+C_II_JB_nointerp(ell,z1,z2)+C_GI_JB_nointerp(ell,z1,z2));\nreturn C;\n}\n\ndouble C_gl_tomo_sys(double ell,int zl,int zs)\n{\n double C;\n // C=C_gl_tomo_nointerp(ell,zl,zs); \n // if(like.IA==1) C += C_gI_nointerp(ell,zl,zs);\n \n if(like.IA!=1) C=C_gl_tomo_nointerp(ell,zl,zs);\n if(like.IA==1) C = C_ggl_IA(ell,zl,zs);\n if(like.IA==2) C += C_gI_lin_nointerp(ell,zl,zs);\n if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);\nreturn C;\n}\n\n// double C_cgl_tomo_sys(double ell_Cluster, int zl,int nN, int zs)\n// {\n// double C;\n// C=C_cgl_tomo_nointerp(ell_Cluster,zl,nN,zs);\n// //if(like.IA!=0) C += \n// if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);\n// return C;\n// } \n\ndouble C_ks_sys(double ell, int zs)\n{\n double C;\n C = C_ks_nointerp(ell,zs);\n if(like.shearcalib==1) C *=(1.0+nuisance.shear_calibration_m[zs]);\n return C;\n}\n\nvoid set_data_shear(int Ncl, double *ell, double *data, int start)\n{\n int i,z1,z2,nz;\n double a;\n for (nz = 0; nz < tomo.shear_Npowerspectra; nz++){\n z1 = Z1(nz); z2 = Z2(nz);\n for (i = 0; i < Ncl; i++){\n if (ell[i] < like.lmax_shear){ data[Ncl*nz+i] = C_shear_tomo_sys(ell[i],z1,z2);}\n else {data[Ncl*nz+i] = 0.;}\n }\n }\n}\n\nvoid set_data_ggl(int Ncl, double *ell, double *data, int start)\n{\n int i, zl,zs,nz; \n for (nz = 0; nz < tomo.ggl_Npowerspectra; nz++){\n zl = ZL(nz); zs = ZS(nz);\n#ifdef ONESAMPLE\n if(zl==0){\n for (i = 0; i < Ncl; i++){data[start+(Ncl*nz)+i] = 0.;}\n }\n else{\n#endif\n for (i = 0; i < Ncl; i++){\n if (test_kmax(ell[i],zl)){\n data[start+(Ncl*nz)+i] = C_gl_tomo_sys(ell[i],zl,zs);\n }\n else{\n data[start+(Ncl*nz)+i] = 0.;\n }\n }\n#ifdef ONESAMPLE\n }\n#endif\n }\n}\n\nvoid set_data_clustering(int Ncl, double *ell, double *data, int start){\n int i, nz;\n for (nz = 0; nz < tomo.clustering_Npowerspectra; nz++){\n //printf(\"%d %e %e\\n\",nz, gbias.b[nz][1],pf_photoz(gbias.b[nz][1],nz));\n for (i = 0; i < Ncl; i++){\n if (test_kmax(ell[i],nz)){data[start+(Ncl*nz)+i] = C_cl_tomo_nointerp(ell[i],nz,nz);}\n else{data[start+(Ncl*nz)+i] = 0.;}\n //printf(\"%d %d %le %le\\n\",nz,nz,ell[i],data[Ncl*(tomo.shear_Npowerspectra+tomo.ggl_Npowerspectra + nz)+i]);\n }\n }\n}\n\n\nvoid set_data_gk(double *ell, double *data, int start)\n{\n#ifdef ONESAMPLE\n int nz=0;\n for (int i=0; i 0.6) return 0;\n if (cosmology.omb < 0.04 || cosmology.omb > 0.055) return 0;\n if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0;\n if (cosmology.n_spec < 0.85 || cosmology.n_spec > 1.05) return 0;\n if (cosmology.w0 < -2.0 || cosmology.w0 > -0.0) return 0;\n if (cosmology.wa < -2.5 || cosmology.wa > 2.5) return 0;\n if (cosmology.h0 < 0.4 || cosmology.h0 > 0.9) return 0;\n if (cosmology.MGmu < -3.0 || cosmology.MGmu > 3.0) return 0;\n if (cosmology.MGSigma < -3.0 || cosmology.MGSigma > 3.0) return 0; // DESY1 extension paper flat priors\n //CH BEGINS \n //CH: to use for running planck15_BA0_w0_wa prior alone) \n //printf(\"like_fourier.c from WFIRST_forecasts: cosmology bounds set for running with planck15_BA0_w0_wa prior\\n\");\n //if (cosmology.Omega_m < 0.05 || cosmology.Omega_m > 0.6) return 0; \n //if (cosmology.omb < 0.01 || cosmology.omb > 0.1) return 0; \n //if (cosmology.sigma_8 < 0.5 || cosmology.sigma_8 > 1.1) return 0; \n //if (cosmology.n_spec < 0.84 || cosmology.n_spec > 1.06) return 0; \n //if (cosmology.w0 < -2.1 || cosmology.w0 > 1.5) return 0; \n //if (cosmology.wa < -5.0 || cosmology.wa > 2.6) return 0; \n //if (cosmology.h0 < 0.3 || cosmology.h0 > 0.9) return 0; \n //CH ENDS\n return 1;\n}\n\nvoid set_nuisance_shear_calib(double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10)\n{\n nuisance.shear_calibration_m[0] = M1;\n nuisance.shear_calibration_m[1] = M2;\n nuisance.shear_calibration_m[2] = M3;\n nuisance.shear_calibration_m[3] = M4;\n nuisance.shear_calibration_m[4] = M5;\n nuisance.shear_calibration_m[5] = M6;\n nuisance.shear_calibration_m[6] = M7;\n nuisance.shear_calibration_m[7] = M8;\n nuisance.shear_calibration_m[8] = M9;\n nuisance.shear_calibration_m[9] = M10;\n}\n\nint set_nuisance_shear_photoz(double SP1,double SP2,double SP3,double SP4,double SP5,double SP6,double SP7,double SP8,double SP9,double SP10,double SPS1)\n{\n int i;\n nuisance.bias_zphot_shear[0]=SP1;\n nuisance.bias_zphot_shear[1]=SP2;\n nuisance.bias_zphot_shear[2]=SP3;\n nuisance.bias_zphot_shear[3]=SP4;\n nuisance.bias_zphot_shear[4]=SP5;\n nuisance.bias_zphot_shear[5]=SP6;\n nuisance.bias_zphot_shear[6]=SP7;\n nuisance.bias_zphot_shear[7]=SP8;\n nuisance.bias_zphot_shear[8]=SP9;\n nuisance.bias_zphot_shear[9]=SP10;\n \n for (i=0;i 10.0) return 0;\n if (nuisance.beta_ia < -4.0 || nuisance.beta_ia > 6.0) return 0;\n if (nuisance.eta_ia < -10.0 || nuisance.eta_ia> 10.0) return 0;\n if (nuisance.eta_ia_highz < -1.0 || nuisance.eta_ia_highz> 1.0) return 0;\n // if(like.IA!=0){\n // if (check_LF()) return 0;\n // }\nreturn 1;\n}\n\n// int set_nuisance_cluster_Mobs(double cluster_Mobs_lgN0, double cluster_Mobs_alpha, double cluster_Mobs_beta, double cluster_Mobs_sigma0, double cluster_Mobs_sigma_qm, double cluster_Mobs_sigma_qz)\n// {\n// // nuisance.cluster_Mobs_lgM0 = mass_obs_norm; //fiducial : 1.72+log(1.e+14*0.7); could use e.g. sigma = 0.2 Gaussian prior\n// // nuisance.cluster_Mobs_alpha = mass_obs_slope; //fiducial: 1.08; e.g. sigma = 0.1 Gaussian prior\n// // nuisance.cluster_Mobs_beta = mass_z_slope; //fiducial: 0.0; e.g. sigma = 0.1 Gaussian prior\n// // nuisance.cluster_Mobs_sigma = mass_obs_scatter; //fiducial 0.25; e.g. sigma = 0.05 Gaussian prior\n\n// // fiducial values and priors from Murata et al. (2018) except for redshift-related parameters\n// nuisance.cluster_Mobs_lgN0 = cluster_Mobs_lgN0; //fiducial: 3.207, flat prior [0.5, 5.0]\n// nuisance.cluster_Mobs_alpha = cluster_Mobs_alpha; //fiducial: 0.993, flat prior [0.0, 2.0]\n// nuisance.cluster_Mobs_beta = cluster_Mobs_beta; //fiducial: 0.0, flat prior [-1.5, 1.5]\n// nuisance.cluster_Mobs_sigma0 = cluster_Mobs_sigma0; //fiducial: 0.456, flat prior [0.0, 1.5]\n// nuisance.cluster_Mobs_sigma_qm = cluster_Mobs_sigma_qm; //fiducial: -0.169, flat prior [-1.5, 1.5]\n// nuisance.cluster_Mobs_sigma_qz = cluster_Mobs_sigma_qz; //fiducial: 0.0, flat prior [-1.5, 1.5]\n\n// if (nuisance.cluster_Mobs_lgN0 < 0.5 || nuisance.cluster_Mobs_lgN0 > 5.0) return 0;\n// if (nuisance.cluster_Mobs_alpha < 0.0 || nuisance.cluster_Mobs_alpha > 2.0) return 0;\n// if (nuisance.cluster_Mobs_beta < -1.5 || nuisance.cluster_Mobs_beta > 1.5) return 0;\n// if (nuisance.cluster_Mobs_sigma0 < 0.0|| nuisance.cluster_Mobs_sigma0 > 1.5) return 0;\n// if (nuisance.cluster_Mobs_sigma_qm < -1.5 && nuisance.cluster_Mobs_sigma_qm > 1.5) return 0;\n// if (nuisance.cluster_Mobs_sigma_qz < -1.5 && nuisance.cluster_Mobs_sigma_qz > 1.5)return 0;\n\n// return 1;\n// }\n\n\nint set_nuisance_gbias(double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8,double B9, double B10)\n{\n\n int i;\n gbias.b[0] = B1;\n gbias.b[1] = B2;\n gbias.b[2] = B3;\n gbias.b[3] = B4;\n gbias.b[4] = B5;\n gbias.b[5] = B6;\n gbias.b[6] = B7;\n gbias.b[7] = B8;\n gbias.b[8] = B9;\n gbias.b[9] = B10;\n for (i = 0; i < 10; i++){\n // printf(\"in set routine %d %le\\n\",i,gbias.b[i]);\n#ifdef ONESAMPLE\n if (gbias.b[i] < 0.4 || gbias.b[i] > 5.0) return 0;\n#else\n if (gbias.b[i] < 0.4 || gbias.b[i] > 3.0) return 0;\n#endif\n }\n\n return 1;\n} \n\n// double log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q,double mass_obs_norm, double mass_obs_slope, double mass_z_slope, double mass_obs_scatter_norm, double mass_obs_scatter_mass_slope, double mass_obs_scatter_z_slope, double Q1, double Q2, double Q3)\ndouble log_multi_like(double OMM, double S8, double NS, double W0,double WA, double OMB, double H0, double MGSigma, double MGmu, double B1, double B2, double B3, double B4,double B5, double B6, double B7, double B8, double B9, double B10, double SP1, double SP2, double SP3, double SP4, double SP5, double SP6, double SP7, double SP8, double SP9, double SP10, double SPS1, double CP1, double CP2, double CP3, double CP4, double CP5, double CP6, double CP7, double CP8, double CP9, double CP10, double CPS1, double M1, double M2, double M3, double M4, double M5, double M6, double M7, double M8, double M9, double M10, double A_ia, double beta_ia, double eta_ia, double eta_ia_highz, double LF_alpha, double LF_P, double LF_Q, double LF_red_alpha, double LF_red_P, double LF_red_Q, double Q1, double Q2, double Q3)\n{\n int i,j,k,m=0,l;\n static double *pred;\n static double *ell;\n static double *ell_Cluster;\n static double darg;\n double chisqr,a,log_L_prior=0.0, log_L=0.0;;\n \n if(ell==0){\n pred= create_double_vector(0, like.Ndata-1);\n ell= create_double_vector(0, like.Ncl-1);\n darg=(log(like.lmax)-log(like.lmin))/like.Ncl;\n for (l=0;l