int ns__bitwiseAnd( struct soap *soap, char *src1, char *src2, char **OutputMatFilename) { double start, end; start = omp_get_wtime(); Mat matSrc1; if(!readMat(src1, matSrc1)) { cerr << "And :: src1 can not read bin file" << endl; return soap_receiver_fault(soap, "And :: src1 can not read bin file", NULL); } Mat matSrc2; if(!readMat(src2, matSrc2)) { cerr << "And :: src2 can not read bin file" << endl; return soap_receiver_fault(soap, "And :: src2 can not read bin file", NULL); } int cols = matSrc1.cols ; int srcType1 = matSrc1.type(); int srcType2 = matSrc2.type(); if(srcType1 != srcType2 ) { matSrc2.convertTo(matSrc2, srcType1); } Mat dst; bitwise_and(matSrc1, matSrc2, dst); /* generate output file name */ *OutputMatFilename = (char*)soap_malloc(soap, 60); getOutputFilename(OutputMatFilename,"_bitwiseAnd"); /* save to bin */ if(!saveMat(*OutputMatFilename, dst)) { cerr << "And:: save mat to binary file" << endl; return soap_receiver_fault(soap, "And :: save mat to binary file", NULL); } matSrc1.release(); matSrc2.release(); dst.release(); end = omp_get_wtime(); cerr<<"ns__And time elapsed "<<end-start<<endl; return SOAP_OK; }
void VisualizerMAT::initData() { VisualizerAbstract::initData(); readMat(mpOMVisualBase->getModelFile(), mpOMVisualBase->getPath()); mpTimeManager->setStartTime(omc_matlab4_startTime(&_matReader)); mpTimeManager->setEndTime(omc_matlab4_stopTime(&_matReader)); }
static dict loadEntry( std::string name ) { std::string sets[] = {"train","val","test"}; std::string im_dir = berkeley_dir+"/images/"; std::string gt_dir = berkeley_dir+"/groundTruth/"; std::string cs_dir = berkeley_dir+"/cache/"; mkdir( cs_dir ); for (std::string s: sets) mkdir( cs_dir+s ); dict r; for (std::string s: sets) { std::string im_name = s+"/"+name+".jpg"; std::shared_ptr<Image8u> im = imreadShared( im_dir + "/" + im_name ); if( im && !im->empty() ) { std::string sname = s+"/"+name+".png", bname = s+"/"+name+"_bnd.png", mname = s+"/"+name+".mat"; std::vector<RMatrixXs> seg; { std::vector<RMatrixXu8> tmp = readAPNG( cs_dir + "/" + sname ); for( auto i: tmp ) seg.push_back( i.cast<short>() ); } std::vector<RMatrixXb> bnd; { std::vector<RMatrixXu8> tmp = readAPNG( cs_dir + "/" + bname ); for( auto i: tmp ) bnd.push_back( i.cast<bool>() ); } if( seg.size()==0 || bnd.size()==0 ) { std::tie(seg,bnd) = readMat( gt_dir + "/" + mname ); { std::vector<RMatrixXu8> tmp; for( auto i: seg ) tmp.push_back( i.cast<uint8_t>() ); writeAPNG( cs_dir + "/" + sname, tmp ); } { std::vector<RMatrixXu8> tmp; for( auto i: bnd ) tmp.push_back( i.cast<uint8_t>() ); writeAPNG( cs_dir + "/" + bname, tmp ); } } if( bnd.size() && seg.size() ) { std::vector<RMatrixXb> bnd_b; for( auto i: bnd ) bnd_b.push_back( i.cast<bool>() ); r["image"] = im; r["segmentation"] = seg; r["boundary"] = bnd_b; r["name"] = name; return r; } } } return r; }
int ns__dilate( struct soap *soap, char *InputMatFilename, char *elementFilename, int iteration=1, char **OutputMatFilename=NULL) { double start, end; start = omp_get_wtime(); Mat src; if(!readMat(InputMatFilename, src)) { cerr << "dilate :: can not read bin file" << endl; return soap_receiver_fault(soap, "dilate :: can not read bin file", NULL); } Mat dst; Mat element; if(!readMat(elementFilename, element)) { cerr<<"dilate :: use default element"<<endl; element.release(); dilate(src, dst, Mat(), Point(-1, -1), iteration); } else { cerr<<"dilate :: use defined element"<<endl; dilate(src, dst, element, Point(-1, -1), iteration); } /* generate output file name */ *OutputMatFilename = (char*)soap_malloc(soap, 60); getOutputFilename(OutputMatFilename,"_dilate"); /* save to bin */ if(!saveMat(*OutputMatFilename, dst)) { cerr << "dilate :: save mat to binary file" << endl; return soap_receiver_fault(soap, "dilate :: save mat to binary file", NULL); } src.release(); dst.release(); element.release(); return SOAP_OK; }
int main(int argc, char **argv){ int** mat_a; int** mat_b; int** mat_c; int rows_mat_a, cols_mat_a, rows_mat_b, cols_mat_b; int i; if(argc < 3){ printf("matmult.out matrix_A_File matrix_B_File\n"); printf("Not enough arguments given.n"); return(1); } //read in matrices readMat(argv[1], &mat_a, &rows_mat_a, &cols_mat_a); readMat(argv[2], &mat_b, &rows_mat_b, &cols_mat_b); //do the multiplication mat_c = matMult(mat_a, rows_mat_a, cols_mat_a, mat_b, rows_mat_b, cols_mat_b); //display solution displayMat(mat_c, rows_mat_a, cols_mat_b); //free up malloced space for(i = 0; i < rows_mat_a; i++){ free(mat_a[i]); } for(i = 0; i < rows_mat_b; i++){ free(mat_b[i]); } for(i = 0; i < rows_mat_a; i++){ free(mat_c[i]); } free(mat_a); free(mat_b); free(mat_c); return 0; }//main
//main int main(int argv, char ** argc) { if(argv != 4 && argv != 1){ perror("Wrong number of parameters");return 0; } if(argv == 1){ mat1FileName = "a.txt"; mat2FileName = "b.txt"; outFileName = "c"; }else{ mat1FileName = argc[1]; mat2FileName = argc[2]; outFileName = argc[3]; } int retVal = readMat(); if(retVal == ERROR_MATRIX_SIZE_MISMATCH){ perror("invalid matrices size"); }else if(retVal == ERROR_RESERVING_MAT){ perror("error reserving matrices"); }else if (retVal == ERROR_FILE_NOT_FOUND){ perror("one of or both input files not found"); }else{ newOutFileName = malloc(strlen(outFileName) + 4); strcpy(newOutFileName,outFileName); strcat(newOutFileName,"_1"); outputFile = fopen(newOutFileName,"w"); execRow(); fclose(outputFile); strcpy(newOutFileName,outFileName); strcat(newOutFileName,"_2"); outputFile = fopen(newOutFileName,"w"); execCell(); fclose(outputFile); } return 0; }
/*Command line entry point of the program*/ int main (int argc, char* argv[]){ /*getopt() variables */ int opt; char* optarg_dup = NULL; /*Command line options*/ uchar cflg=0,gflg=0,kflg=0,lflg=0,mflg=0,oflg=0, sflg=0; uchar pflg=0,tflg=0,vflg=0,xflg=0,zflg=0; InputParams* inputParams = NULL; /*Working variables */ int i,m; int nbPriors; int nbNodes; int nbClass; int nbLabeled; int nbUnlabeled; int nbSimParams; int actualWlen; int start_cpu,stop_cpu; real tmp; uchar* absorbing = NULL; char* labels = NULL; char* featLabels = NULL; char* targets = NULL; char* preds = NULL; int** classes = NULL; real** N = NULL; real* gram = NULL; real** latF = NULL; real** latB = NULL; real** kernel = NULL; SparseMatrix* spmat = NULL; SparseMatrix* dataset = NULL; DataStat* graphStat = NULL; DataStat* featuresStat = NULL; DWInfo* dwInfo = NULL; OptiLen* optiLen = NULL; PerfMeasures* unlabeledPerf = NULL; LSVMDataInfo* dataInfo = NULL; /*Print the program banner*/ printBanner(); /*Scan the command line*/ inputParams = malloc(sizeof(InputParams)); init_InputParams(inputParams); while ((opt = getopt(argc,argv,"c:g:l:xms:k:o:p:rt:v:z:h")) != EOF){ switch(opt){ case 'c': cflg++; inputParams->nbFolds = atoi(optarg); break; case 'g': gflg++; inputParams->graphFname = (char*)malloc(FNAME_LEN*sizeof(char)); strncpy(inputParams->graphFname,optarg,FNAME_LEN); break; case 'k': kflg++; inputParams->gramFname = (char*)malloc(FNAME_LEN*sizeof(char)); strncpy(inputParams->gramFname,optarg,FNAME_LEN); break; case 's': sflg++; optarg_dup = (char*)__strdup(optarg); nbSimParams = getNbTokens(optarg,","); inputParams->simParams = vec_alloc(nbSimParams+1); tokenizeReals(optarg_dup,",",inputParams->simParams); break; case 'l': lflg++; inputParams->wlen = atoi(optarg); break; case 'm': mflg++; break; case 'o': oflg++; inputParams->outFname = (char*)malloc(FNAME_LEN*sizeof(char)); strncpy(inputParams->outFname,optarg,FNAME_LEN); inputParams->outPRED = (char*)malloc(FNAME_LEN*sizeof(char)); inputParams->outLEN = (char*)malloc(FNAME_LEN*sizeof(char)); addExtension(inputParams->outFname,"pred",inputParams->outPRED); addExtension(inputParams->outFname,"len",inputParams->outLEN); break; case 'p': pflg++; optarg_dup = (char*)__strdup(optarg); nbPriors = getNbTokens(optarg,"#"); inputParams->priors = vec_alloc(nbPriors+1); tokenizeReals(optarg_dup,"#",inputParams->priors); break; case 't': tflg++; inputParams->tarFname = (char*)malloc(FNAME_LEN*sizeof(char)); strncpy(inputParams->tarFname,optarg,FNAME_LEN); break; case 'v': vflg++; inputParams->verbose = atoi(optarg); break; case 'x': xflg++; inputParams->crossWalks = 1; break; case 'z': zflg++; inputParams->cvSeed = atoi(optarg); break; case 'h': printHelp(); exit(EXIT_FAILURE); break; } } /*Check mandatory arguments*/ if(!gflg || !lflg || (!oflg && !mflg)){ fprintf(stderr,"Mandatory argument(s) missing\n"); printHelp(); exit(EXIT_FAILURE); } if( (kflg && !sflg) || (!kflg && sflg)){ fprintf(stderr, "Error with 'k' and 's' parameters\n"); printHelp(); exit(EXIT_FAILURE); } /*Check that the walk length is greater than 2*/ if(inputParams->wlen < 2){ fprintf(stderr,"The walkLen must be >= 2\n"); exit(EXIT_FAILURE); } /*Check that there are the right number of similarity parameters*/ if (kflg && sflg){ if(inputParams->simParams){ switch((int)inputParams->simParams[1]){ case 1 : if((int)inputParams->simParams[0] != 1){ fprintf(stderr,"The similarity type 1 must have no parameters\n"); exit(EXIT_FAILURE); } break; case 2 : if((int)inputParams->simParams[0] != 2){ fprintf(stderr,"The similarity type 2 must have exactly 1 parameter\n"); exit(EXIT_FAILURE); } break; case 3 : if((int)inputParams->simParams[0] != 4){ fprintf(stderr,"The similarity type 3 must have exactly 3 parameters\n"); exit(EXIT_FAILURE); } break; case 4 : if((int)inputParams->simParams[0] != 2){ fprintf(stderr,"The similarity type 4 must have exactly 1 parameter\n"); exit(EXIT_FAILURE); } break; default : fprintf(stderr,"Unrecognized similarity type\n"); exit(EXIT_FAILURE); } } } /*Get the number of nodes in the graph*/ nbNodes = readNbNodes(inputParams->graphFname); /*Get the number of distinct classes*/ nbClass = readNbClass(inputParams->graphFname); /*Get info from the LIBSVM data*/ if (kflg){ dataInfo = malloc(sizeof(LSVMDataInfo)); getLSVMDataInfo(inputParams->gramFname,dataInfo); dataset = spmat_alloc(dataInfo->nbLines,dataInfo->nbFeatures,0); init_SparseMat(dataset); featuresStat = DataStat_alloc(dataInfo->nbClass); featLabels = char_vec_alloc(nbNodes); } /*Check if the number of nodes does not exceed the limitation*/ if(nbNodes > MAX_NODES){ fprintf(stderr,"This version is limited to maximum %i nodes\n",MAX_NODES); exit(EXIT_FAILURE); } /*Check that the number of classes is lower than 128*/ if(nbClass > 127){ fprintf(stderr,"The number of classes must be <= 127\n"); exit(EXIT_FAILURE); } /*Check that the number of folds is between 2 and nbNodes*/ if(cflg){ if(inputParams->nbFolds == 1 || inputParams->nbFolds > nbNodes){ fprintf(stderr,"The number of folds must be > 1 and <= number of nodes\n"); exit(EXIT_FAILURE); } } /*Allocate data structure*/ latF = mat_alloc(inputParams->wlen+1,nbNodes); latB = mat_alloc(inputParams->wlen+1,nbNodes); kernel = mat_alloc(nbNodes, nbNodes); classes = (int**)malloc(sizeof(int*)*(nbClass+1)); labels = char_vec_alloc(nbNodes); absorbing = uchar_vec_alloc(nbNodes); if(kflg) gram = vec_alloc((nbNodes*(nbNodes+1))/2); dwInfo = malloc(sizeof(DWInfo)); dwInfo->mass_abs = vec_alloc(nbClass); spmat = spmat_alloc(nbNodes,nbNodes,1); graphStat = DataStat_alloc(nbClass+1); optiLen = malloc(sizeof(OptiLen)); /*Initialize the sparse transition matrix and the dataset if required*/ init_SparseMat(spmat); /*Read the adjacency matrix*/ readMat(inputParams->graphFname,spmat,labels,graphStat,inputParams->verbose); isSymmetric(spmat); /*Get the indices of the nodes in each class */ getClasses(labels,nbNodes,classes,nbClass); /*Get the number of labeled nodes*/ nbUnlabeled = classes[0][0]; nbLabeled = nbNodes - nbUnlabeled; /*If provided, check that the priors match the number of classes*/ if(pflg){ if(nbClass != nbPriors){ printf("The number of priors does not match with the number of classes\n"); exit(EXIT_FAILURE); } /*Check that the priors sum up to 1*/ else{ tmp=0.0; for(i=1;i<=inputParams->priors[0];i++){ tmp += inputParams->priors[i]; } if(ABS(tmp-1.0) > PROB_EPS){ textcolor(BRIGHT,RED,BLACK); printf("WARNING: The class priors do not sum up to 1\n"); textcolor(RESET,WHITE,BLACK); } } } /*If no priors provided, use empirical priors */ else{ inputParams->priors = vec_alloc(nbClass+1); inputParams->priors[0] = (real)nbClass; tmp = 0.0; for(i=1;i<=inputParams->priors[0];i++) tmp += graphStat->classCount[i]; for(i=1;i<=inputParams->priors[0];i++) inputParams->priors[i] = (real)graphStat->classCount[i]/tmp; } /*If provided read the LIBSVM feature matrix*/ if(kflg){ m = readLSVMData(inputParams->gramFname,dataInfo,dataset,featLabels,featuresStat,inputParams->verbose); if (dataInfo->nbLines != nbNodes){ fprintf(stderr,"Number of line on the LIBSVM (%i) file doesn't match the number of nodes (%i)\n", dataInfo->nbLines, nbNodes); exit(EXIT_FAILURE); } /* Multiply a kernel matrix based on the dataset*/ /* TO DO : define a parameters to lower the importance of the features*/ buildKernel2(spmat, dataset, 0.1, inputParams); /*Multiply adjacency matrix*/ } /*Print statistics about the graph, classes, and run-mode*/ if (inputParams->verbose > 0) printInputInfo(spmat,graphStat,nbClass,inputParams); /*Minimum Covering Length mode*/ if (mflg){ computeMCL(spmat,absorbing,labels,classes,nbClass,latF,latB,inputParams); /*Exit after displaying the statistics*/ exit(EXIT_SUCCESS); } /*Start the CPU chronometer*/ start_cpu = clock(); /*If required tune the maximum walk length by cross-validation*/ if(cflg){ crossValidateLength(spmat,absorbing,labels,classes,nbClass,NULL,latF,latB,inputParams,optiLen); actualWlen = optiLen->len; } /*Otherwise use the prescribed length*/ else actualWlen = inputParams->wlen; /************************ALGORITHM STARTS HERE****************************/ if(inputParams->verbose >= 1){ textcolor(BRIGHT,RED,BLACK); printf("Performing discriminative walks up to length %i on full data\n",actualWlen); textcolor(RESET,WHITE,BLACK); } /*Allocate data structure*/ N = mat_alloc(nbUnlabeled,nbClass); preds = char_vec_alloc(nbUnlabeled); init_mat(N,nbUnlabeled,nbClass); /*Launch the D-walks*/ dwalk(spmat,absorbing,classes,nbClass,N,latF,latB,actualWlen,inputParams->crossWalks,dwInfo,inputParams->verbose); /************************ALGORITHM STOPS HERE****************************/ /*Stop the CPU chronometer*/ stop_cpu = clock(); /*Compute the predictions as the argmax on classes for each unlabeled node*/ computePredictions(N,preds,inputParams->priors,nbUnlabeled,nbClass); /*Write the model predictions*/ writePredictions_unlabeled(inputParams->outPRED,preds,N,nbClass,classes[0]); /*Write the class betweeness */ /*If a target file is provided compare predictions and targets*/ if(tflg){ unlabeledPerf = PerfMeasures_alloc(nbClass+1); computeUnlabeledPerf(preds,classes[0],nbUnlabeled,nbClass,inputParams,unlabeledPerf,inputParams->verbose); free_PerfMeasures(unlabeledPerf,nbClass+1); } /*Print informations*/ if (inputParams->verbose >= 1){ for(i=0;i<nbClass;i++) printf("Exploration rate in class %2i : %1.2f %%\n",i+1,100*dwInfo->mass_abs[i]); printf("CPU Time (sec) : %1.4f\n",((double)(stop_cpu - start_cpu)/CLOCKS_PER_SEC)); printLineDelim(); } /*Optionally release memory here*/ #ifdef FREE_MEMORY_AT_END free_classes(classes,nbClass+1); free_InputParams(inputParams); free_DataStat(graphStat); free_DWInfo(dwInfo); free(absorbing); free(labels); free_mat(N,nbUnlabeled); free_mat(latF,inputParams->wlen+1); free_mat(latB,inputParams->wlen+1); free_SparseMatrix(spmat); free(optiLen); free(preds); if(kflg) free(gram); #endif /*Exit successfully :-)*/ exit(EXIT_SUCCESS); }
//* // Get Covariance Matrix of L0 feature int main(int argc, char** argv) { std::string in_path("UW_new_dict"); //std::string in_path("BB_new_dict"); int KK = 128; int T = 10; pcl::console::parse_argument(argc, argv, "--K", KK); pcl::console::parse_argument(argc, argv, "--t", T); std::ostringstream ss; ss << KK; { cv::Mat depth_xyz_center, depth_xyz_range; readMat(in_path+"/depth_xyz_center.cvmat", depth_xyz_center); readMat(in_path+"/depth_xyz_range.cvmat", depth_xyz_range); std::cerr << depth_xyz_center.rows << std::endl; depth_xyz_range = depth_xyz_range.mul(depth_xyz_range); WKmeans depth_clusterer; depth_clusterer.AddData(depth_xyz_center, depth_xyz_range); cv::Mat refined_depth_xyz_center; depth_clusterer.W_Cluster(refined_depth_xyz_center, KK, T); saveMat(in_path+"/refined_depth_xyz_center_"+ss.str()+".cvmat", refined_depth_xyz_center); } { cv::Mat depth_lab_center, depth_lab_range; readMat(in_path+"/depth_lab_center.cvmat", depth_lab_center); readMat(in_path+"/depth_lab_range.cvmat", depth_lab_range); std::cerr << depth_lab_center.rows << std::endl; depth_lab_range = depth_lab_range.mul(depth_lab_range); WKmeans depth_clusterer; depth_clusterer.AddData(depth_lab_center, depth_lab_range); cv::Mat refined_depth_lab_center; depth_clusterer.W_Cluster(refined_depth_lab_center, KK, T); saveMat(in_path+"/refined_depth_lab_center_"+ss.str()+".cvmat", refined_depth_lab_center); } { cv::Mat color_xyz_center, color_xyz_range; readMat(in_path+"/color_xyz_center.cvmat", color_xyz_center); readMat(in_path+"/color_xyz_range.cvmat", color_xyz_range); std::cerr << color_xyz_center.rows << std::endl; color_xyz_range = color_xyz_range.mul(color_xyz_range); WKmeans color_clusterer; color_clusterer.AddData(color_xyz_center, color_xyz_range); cv::Mat refined_color_xyz_center; color_clusterer.W_Cluster(refined_color_xyz_center, KK, T); saveMat(in_path+"/refined_color_xyz_center_"+ss.str()+".cvmat", refined_color_xyz_center); } { cv::Mat color_lab_center, color_lab_range; readMat(in_path+"/color_lab_center.cvmat", color_lab_center); readMat(in_path+"/color_lab_range.cvmat", color_lab_range); std::cerr << color_lab_center.rows << std::endl; color_lab_range = color_lab_range.mul(color_lab_range); WKmeans color_clusterer; color_clusterer.AddData(color_lab_center, color_lab_range); cv::Mat refined_color_lab_center; color_clusterer.W_Cluster(refined_color_lab_center, KK, T); saveMat(in_path+"/refined_color_lab_center_"+ss.str()+".cvmat", refined_color_lab_center); } return 1; }
void mcMigrate (char const **paramFile, int *nrFiles, char const *inputDir, char const *outputDir) { int i, j, k, RepLoop, envChgStep, dispStep, loopID, simulTime,last, action; bool advOutput, habIsSuitable, cellInDispDist, tempResilience, tail; char fileName[128], simulName2[128]; FILE *fp = NULL, *fp2 = NULL; double lddSeedProb; time_t startTime; /* ** These variables are not (yet) used. ** ** int vegResTime, seedBankResTime, *seedBank, tSinceDecol, tWhenCol; */ /* ** Pixel counter variables. These variables allow us to record interesting ** values to be printed into the output file: ** ** ==> Many of these aren't used yet. <== ** ** - nrColonized: The number of pixels in "Colonized" state at ** any given time. ** - nrAbsent: The number of pixels in "Absent" state at any ** given time. ** - nrDecolonized: The number of pixels in "Decolonized" state at ** any given time. ** - nrTmpResilient: The number of pixels that in "Temporary ** Resilience" state at any given time. ** - nrVegResilient: The number of pixels that are in "Vegetative ** Resilience" state at any given time. ** - nrSeedBank: The number of pixels that are in Seed Bank ** Resilience state at any given time. ** - nrStepColonized: The number of pixels which changed to ** "Colonized" state during a given step. ** - nrStepDecolonized: The number of pixels which changed to ** "Decolonized" state during a given step. ** - nrStepTmpResilient: The number of pixels that which changed to ** "Temporary Resilience" state during a given ** step. ** - nrStepVegResilient: The number of pixels that are which changed to ** "Vegetative Resilience" state during a given ** step. ** - nrStepSeedBank: The number of pixels that are which changed to ** "Seed Bank Resilience" state during a given ** step. ** - nrStepLostUnsuit: The number of pixels that were lost due to ** unsuitable habitat conditons during a given ** dispersal step. ** - nrStepLostExtreme: The number of pixels that were lost due to ** "Extreme Event" during a given dispersal step. ** - nrStepLDDSuccess: The number of LDD events that were successful ** (can be any of a "normal" LDD or a River or ** Road LDD). ** - nrStepVegResRecover: The number of "Vegetative Resilience" recovery ** events that occured within a given dispersal ** step. ** - nrStepSeedBankRecover: The number of "Seed Bank Resilience" recovery ** events that occured within a given dispersal ** step. ** - nrTotColonized: \ ** - nrTotLostUnsuit: | ** - nrTotLostExtreme: | Same as above but over the total ** - nrTotLostNatural: > simulation instead of one step. ** - nrTotLDDSuccess: | ** - nrTotVegResRecover: | ** - nrTotSeedBankRecover: / ** - nrInitial: The number of initial pixels that are occupied ** by the species. ** - nrNoDispersal: The number of pixels that would be colonized at ** the end of the simulation under the ** "no-dispersal" hypothesis. ** - nrUnivDispersal: The number of pixels that would be colonized ** at the end of the simulation under the ** "unlimited-dispersal" hypothesis. */ int nrColonized, nrAbsent, nrStepColonized, nrStepDecolonized, nrStepLDDSuccess, nrTotColonized, nrTotLDDSuccess, nrInitial, nrNoDispersal, nrUnivDispersal, nrTotDecolonized; /* As of yet unused count variables: ** int nrTotVegResRecover, nrTotSeedBankRecover, nrStepVegResilient, ** nrStepSeedBank, nrVegResilient, nrStepSeedBankRecover, ** nrStepVegResRecover, nrSeedBank, nrDecolonized; */ /* Matrices: ** - currentState: Values in [-32768;32767]. NoData values are represented by -9999 ** - habSuitability: Values in [0;1000]. ** - barriers: Values in [0;255]. ** - pixelAge: Values in [0;255]. ** - noDispersal: Values in [0;255]. */ int **currentState, **habSuitability, **barriers, **pixelAge, **noDispersal; /* Initialize the variables. */ advOutput = false; currentState = NULL; habSuitability = NULL; barriers = NULL; pixelAge = NULL; noDispersal = NULL; propaguleProd = NULL; dispKernel = NULL; if (mcInit(*paramFile) == -1) /* Reads the "_param.txt" file */ { *nrFiles = -1; goto End_of_Routine; } /* We'll use 'srand' and 'rand' here, as 'srandom' and 'random' do not work on Windows :-( */ srand (time (NULL)+procID); /* Allocate the necessary memory. */ currentState = (int **)malloc (nrRows * sizeof (int *)); habSuitability = (int **)malloc (nrRows * sizeof (int *)); barriers = (int **)malloc (nrRows * sizeof (int *)); pixelAge = (int **)malloc (nrRows * sizeof (int *)); noDispersal = (int **)malloc (nrRows * sizeof (int *)); for (i = 0; i < nrRows; i++) { currentState[i] = (int *)malloc (nrCols * sizeof (int)); habSuitability[i] = (int *)malloc (nrCols * sizeof (int)); barriers[i] = (int *)malloc (nrCols * sizeof (int)); pixelAge[i] = (int *)malloc (nrCols * sizeof (int)); noDispersal[i] = (int *)malloc (nrCols * sizeof (int)); } clock_t begin, end, total_begin, total_end; double time_spent; double total_time_spent; total_begin = clock(); /* Replicate the simulation replicateNb times. If replicateNb > 1 then the ** simulation's output names are "simulName1", "simulName2", etc... */ for (RepLoop = 1; RepLoop <= replicateNb; RepLoop++) { /* Remember the current time */ startTime = time(NULL); /* If replicateNb > 1 then we need to change the simulation name */ if (replicateNb == 1) { strcpy(simulName2, simulName); } else if (replicateNb > 1) { sprintf(simulName2, "%s%d", simulName, RepLoop); /* sprinf(): puts a string into variable simulName2 */ } /* Load and prepare the data. */ /* Species initial distribution */ sprintf(fileName, "%s%s.tif", inputDir, iniDist); /* sprinf(): puts a string into variable fileName */ printf("%s", fileName); if (readMat(fileName, currentState) == -1) { *nrFiles = -1; goto End_of_Routine; } //remove initial occurences /*removeInitial(currentState);*/ /* Barrier options */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { barriers[i][j] = 0; } } if (useBarrier) { sprintf(fileName, "%s.tif", barrier); if (readMat(fileName, barriers) == -1) { *nrFiles = -1; /* if readMat() return -1, an error occured */ goto End_of_Routine; } } /* Filter the barrier matrix in two ways: ** -> reclass any value < 0 as 0 (this is to remove NoData values of -9999). ** -> set the cells with NoData in 'currentState' to NoData in 'barriers' ** so that the NoData in 'currentState' and 'barriers' are identical */ mcFilterMatrix(barriers, currentState, true, false, true); /* Filter the values of current state matrix by the barriers matrix ** (when barriers = 1 we set currentState = 0) */ if (useBarrier) mcFilterMatrix(currentState, barriers, false, true, false); /* Time to reach dispersal maturity. ** ** Before a pixel (= a population) can disperse, it needs to reach a certain ** user-defined age. The "age" is a matrix that keeps track of the age ** of all pixels: ** 0 = pixel is not colonized. ** 1 = pixel is colonized since 1 "dispersal event". ** 2 = pixel is colonized since 2 "dispersal event". ** 3 = etc... ** Fill the "age" to reflect the initial distribution of the species: ** where the species is present, pixels get a value of 'FullMaturity', where ** the species is absent, pixels get a value of 0. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { if (currentState[i][j] == 1) { pixelAge[i][j] = fullMatAge; } else { pixelAge[i][j] = 0; } } } /* The "no dispersal" matrix. ** This Matrix will keep track of the species distribution under the ** "no dispersal" scenario. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { noDispersal[i][j] = currentState[i][j]; } } /* Initialize counter variables. ** Reset pixel counters to zero before we start the dispersal simulation. */ nrInitial = 0; nrColonized = 0; nrAbsent = 0; nrNoDispersal = 0; nrUnivDispersal = 0; nrTotColonized = 0; nrTotDecolonized = 0; nrTotLDDSuccess = 0; tempResilience = true; nrStepColonized = 0; nrStepDecolonized = 0; nrStepLDDSuccess = 0; /* Currently unused counters: ** nrVegResilient = 0; ** nrSeedBank = 0; ** nrTotVegResRecover = 0; ** nrTotSeedBankRecover = 0; */ /* Count the number of initially colonized pixels (i.e. initial species distribution) ** as well as the number of empty (absence) cells. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { if (currentState[i][j] == 1) nrInitial++; if (currentState[i][j] == 0) nrAbsent++; } } nrColonized = nrInitial; nrNoDispersal = nrInitial; nrUnivDispersal = nrInitial; /* Write the initial state to the data file. */ sprintf(fileName, "%s/%s_stats%d.txt", outputDir, simulName2,procID); if ((fp = fopen (fileName, "w")) != NULL) { fprintf (fp, "envChgStep\tdispStep\tstepID\tunivDispersal\tNoDispersal\toccupied\tabsent\tstepColonized\tstepDecolonized\tstepLDDsuccess\n"); fprintf (fp, "0\t0\t1\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", nrUnivDispersal, nrNoDispersal, nrColonized, nrAbsent, nrStepColonized, nrStepDecolonized, nrStepLDDSuccess); } else { *nrFiles = -1; printf ("Could not open statistics file for writing.\n"); goto End_of_Routine; } /* **************************************************************** */ /* Simulate plant dispersal and migration (the core of the method). */ /* **************************************************************** */ printf("Running MigClim simulation %s.\n", simulName2); /* Start of environmental change step loop (if simulation is run without change in environment this loop runs only once). */ for (envChgStep = 1; envChgStep <= envChgSteps; envChgStep++) { /* Print the current environmental change iteration. */ printf (" %d...\n", envChgStep); /* Load the habitat suitability layer for the current envChgStep. */ sprintf (fileName, "%s%s%d.tif", inputDir, hsMap, envChgStep); if (readMat (fileName, habSuitability) == -1) { *nrFiles = -1; goto End_of_Routine; } /* if the user chose a rcThreshold > 0, reclass the habitat suitability into 0 or 1000 ** if rcThreshold == 0 then suitability values are left unchanged. */ if (rcThreshold > 0) { for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { if (habSuitability[i][j] < rcThreshold) { habSuitability[i][j] = 0; } else { habSuitability[i][j] = 1000; } } } } /* Filter the habitat suitability matrix in three ways: ** -> replace any value < 0 by 0 (this removes NoData). ** -> set habitat suitability to 0 where barrier = 1. ** -> set habitat suitability values to NoData where barrier = NoData. ** and also */ mcFilterMatrix(habSuitability, barriers, true, true, true); /* Set the values that will keep track of pixels colonized during the next ** climate change loop. ** "loopID" is the value that will be given to the pixel colonized ** during the current loop. The pixels being decolonized during the ** current loop will be given a value of "-loopID". The limits in ** terms of number of dispersal events and environmental change ** events is the following: ** - Without environmental change, the maximum number of dispStep ** is 29'500. ** - With environmental change, the maximum number of dispStep is ** 98, the number of environmental change loops is limited to 250. ** The coding for the loopID is as follows: envChgStep * 100 + dispStep. */ if (envChgStep == 0) { loopID = 1; } else { loopID = envChgStep * 100; } /* "Unlimited" and "no dispersal" scenario pixel count. Here we compute the number of pixels ** that would be colonized if dispersal was unlimited or null. This is simply the sum of all ** potentially suitable habitats */ nrUnivDispersal = mcUnivDispCnt(habSuitability); updateNoDispMat(habSuitability, noDispersal, &nrNoDispersal); /* Reset number of decolonized cells within current dispersal step pixel counter */ nrStepDecolonized = 0; /* Update for temporarily resilient pixels. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { /* Udate non-suitable pixels. If a pixel turned unsuitable, we update its status to "Temporarily Resilient". */ if ((habSuitability[i][j] == 0) && (currentState[i][j] > 0)) { /* If the user selected TemporaryResilience==T, then the pixel is set to "Temporary Resilient" status. */ if (tempResilience == true) { currentState[i][j] = 29900; } else { /* If not temporary resilience was specified, then the pixel is set to "decolonized" status. */ currentState[i][j] = -1 - loopID; pixelAge[i][j] = 0; /* NOTE: Later we can add "Vegetative" and "SeedBank" resilience options at this location. */ } /* The number of decolonized cells within current step is increased by one */ nrStepDecolonized++; } } } /* *************************************** */ /* Dispersal event step loop starts here. */ /* *************************************** */ for (dispStep = 1; dispStep <= dispSteps; dispStep++) { begin=clock(); /* Set the value of "loopID" for the current iteration of the dispersal loop. */ loopID++; /* Reset pixel counters that count pixels within the current loop. */ nrStepColonized = 0; nrStepLDDSuccess = 0; if (dispStep > 1) nrStepDecolonized = 0; /* Currently unused variables: ** nrStepVegResilient = 0; ** nrStepSeedBank = 0; ** nrStepVegResRecover = 0; ** nrStepSeedBankRecover = 0; */ removeInitial(currentState,dispStep); /* Source cell search: Can the sink pixel be colonized? There are four ** conditions to be met for a sink pixel to become colonized: ** 1. Sink pixel is currently suitable and not already colonised. ** 2. Sink pixel is within dispersal distance of an already colonised ** and mature pixel. ** 3. Source pixel has reached dispersal maturity. ** 4. There is no obstacle (barrier) between the pixel to be colonised ** (sink pixel) and the pixel that is already colonised (source ** pixel). ** ** Loop through the cellular automaton. */ for (i = 0; i < nrRows; i++) { last = 0; for (j = 0; j < nrCols; j++) { /* Reset variables. */ habIsSuitable = false; cellInDispDist = false; /* Remove mature cells for impact control */ if (pixelAge[i][j] >= iniMatAge) { //determine the action for this cell action = cellAction(i,j,dispStep); if (action== IMPACT_CONTROL) { //delete it? double r = UNIF01; if (r <= 0.7) { currentState[i][j] = 0; pixelAge[i][j] = 0; if (aggregates[dispStep-1][i][j] > 0) { aggregates[dispStep-1][i][j]--; } managementImpacts[dispStep-1][IMPACT_CONTROL][procID-1]++; } } } /* 1. Test whether the pixel is a suitable sink (i.e., its habitat ** is suitable, it's unoccupied and is not on a barrier or filter ** pixel). */ if ((habSuitability[i][j] > 0) && (currentState[i][j] <= 0) && checkSuitability(i,j,false)) habIsSuitable = true; //set state from previous state if (currentState[i][j] >= 1) { aggregates[dispStep-1][i][j]++; } /* 2. Test whether there is a source cell within the dispersal ** distance. To be more time efficient, this code runs only if ** the answer to the first question is positive. Additionally, ** if there is a source cell within dispersion distance and if ** a barrier was asked for, then we also check that there is no ** barrier between this source cell and the sink cell (this ** verification is carried out in the "SearchSourceCell" ** function). */ if (habIsSuitable) { /* Now we search if there is a suitable source cell to colonize the sink cell. */ if (mcSrcCell (i, j, currentState, pixelAge, loopID, habSuitability[i][j], barriers, &last)) { cellInDispDist = true; //last=0; } else { //last++; } } /* Update pixel status. */ if (habIsSuitable && cellInDispDist) { /* Only if the 2 conditions are fullfilled the cell's status is set to colonised. */ currentState[i][j] = loopID; nrStepColonized++; //printf("Step: %d, i: %d, j: %d\n",dispStep-1, i, j); aggregates[dispStep-1][i][j]++; /* If the pixel was in seed bank resilience state, then we ** update the corresponding counter. Currently not used. ** if (pixelAge[i][j] == 255) nrStepSeedBank--; */ /* Update "age" value. We do this only now because we needed the old "age" value just before ** to determine whether a pixel was in "Decolonized" or "SeedBank resilience" status. */ pixelAge[i][j] = 0; } } } /* If the LDD frequence is larger than zero, perform it. */ if (lddFreq > 0.0) { /* Loop through the entire cellular automaton. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { /* Check if the pixel is a source cell (i.e. is it colonised since at least 1 dispersal Loop) ** and check if the pixel has reached dispersal maturity. */ if ((currentState[i][j]) > 0 && (currentState[i][j] != loopID)) { if (pixelAge[i][j] >= iniMatAge) { /* Set the probability of generating an LDD event. This ** probability is weighted by the age of the cell. */ if (pixelAge[i][j] >= fullMatAge) { lddSeedProb = lddFreq; } else { lddSeedProb = lddFreq * propaguleProd[pixelAge[i][j] - iniMatAge]; } /* Now we can try to generate a LDD event with the calculated probability. */ if (UNIF01 < lddSeedProb || lddSeedProb == 1.0) { /* Randomly select a pixel within the distance "lddMinDist - lddMaxDist". */ mcRandomPixel (&rndPixel); rndPixel.row = rndPixel.row + i; rndPixel.col = rndPixel.col + j; /* Now we check if this random cell is a suitable sink cell.*/ if (mcSinkCellCheck (rndPixel, currentState, habSuitability) && srcPixel(i,j,rndPixel.row,rndPixel.col,dispStep,true)) { /* if condition is true, the pixel gets colonized.*/ currentState[rndPixel.row][rndPixel.col] = loopID; //include ldd state aggregates[dispStep-1][i][j]++; nrStepColonized++; nrStepLDDSuccess++; /* If the pixel was in seed bank resilience state, then we ** update the corresponding counter. Currently not used. ** if (pixelAge[rndPixel.row][rndPixel.col] == 255) nrStepSeedBank--; */ /* Reset pixel age. */ pixelAge[rndPixel.row][rndPixel.col] = 0; } } } } } } } /* Update pixel age: At the end of a dispersal loop we want to ** increase the "age" of each colonized pixel. ** ** Reminder: pixel "age" structure is as follows: ** 0 = Pixel is either "Absent", "Decolonized" or has just been ** "Colonized" during this dispersal step. ** 1 to 250 = Pixel is in "Colonized" or "Temporarily Resilient" ** status. The value indicates the number of "dispersal events ** (usually years) since when the pixel was colonized. ** 255 = Pixel is in "SeedBank Resilience" state. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { /* If the pixel is in "Colonized" or "Temporarily Resilient" state, update it's age value. */ if (currentState[i][j] > 0) pixelAge[i][j] += 1; /* If a pixel is in "Temporarily Resilient" state, we also increase its "currentState" value by 1 ** so that the pixels gains 1 year of "Temporarily Resilience" age. */ if (currentState[i][j] >= 29900) currentState[i][j] += 1; } } /* Update pixel counters. */ nrColonized = nrColonized + nrStepColonized - nrStepDecolonized; nrAbsent = nrAbsent - nrStepColonized + nrStepDecolonized; nrTotColonized += nrStepColonized; nrTotDecolonized += nrStepDecolonized; nrTotLDDSuccess += nrStepLDDSuccess; /* Currently unused variables: ** nrTotVegResRecover += nrStepVegResRecover; ** nrTotSeedBankRecover += nrStepSeedBankRecover; */ /* Write current iteration data to the statistics file. */ fprintf(fp, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", envChgStep, dispStep, loopID, nrUnivDispersal, nrNoDispersal, nrColonized, nrAbsent, nrStepColonized, nrStepDecolonized, nrStepLDDSuccess); /* If the user has requested full output, also write the current state matrix to file. */ /*if (fullOutput) { sprintf (fileName, "%s/%s_step_%d.asc", outputDir, simulName2, loopID); if (writeMat (fileName, currentState) == -1) { *nrFiles = -1; goto End_of_Routine; } }*/ end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; //fprintf(f,"%lf\n",time_spent); //printf("Step %d completed by proc(%i) in %lf \n",dispStep,procID,time_spent); //increment step tracker if (incrementStepComplete(dispStep-1)) { //print summary int avgColonised = sum(dispStep-1); int d_range=0, p_range=0, r_range=0, c_range=0, ic_range=0, ap_range=0; int proc; for (proc = 0; proc < NUMPROC; proc++) { d_range += managementImpacts[dispStep-1][DELIMITATION][proc]; p_range += managementImpacts[dispStep-1][PREVENTION][proc]; r_range += managementImpacts[dispStep-1][REMOVAL][proc]; c_range += managementImpacts[dispStep-1][CONTAINMENT][proc]; ic_range += managementImpacts[dispStep-1][IMPACT_CONTROL][proc]; ap_range += managementImpacts[dispStep-1][ASSET_PROTECTION][proc]; //printf("IC%i: %i\n",proc,managementImpacts[dispStep-1][ASSET_PROTECTION][proc]); } d_range = d_range / NUMPROC; p_range = p_range / NUMPROC; r_range = r_range / NUMPROC; c_range = c_range / NUMPROC; ic_range = ic_range / NUMPROC; ap_range = ap_range / NUMPROC; //printf("IC: %i : %i\n",managementImpacts[dispStep-1][IMPACT_CONTROL][procID-1], procID-1); //printf("IC Averaged: %i\n",ic_range); char impactStr[128]; sprintf(impactStr,"\"d_range\":%i,\"p_range\":%i,\"r_range\":%i,\"c_range\":%i,\"ic_range\":%i,\"ap_range\":%i",d_range,p_range,r_range,c_range,ic_range,ap_range); //printf("%s",impactStr); printf("StepComplete %i : {\"time\":%lf,\"occupied\":%i,\"new\":%i,%s}\n",dispStep,time_spent,avgColonised,nrStepColonized,impactStr); } } /* END OF: dispStep */ /* Update temporarily resilient pixels. ** Temporarily resilient pixels can be distinguished by: ** -> CurrentState_Matrix = 29'900 to 29'999. Increases by 1 at each year. ** -> Age_Matrix has a positive value. */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { if (currentState[i][j] >= 29900) { currentState[i][j] = dispSteps - loopID - 1; pixelAge[i][j] = 0; } } } } /* END OF: envChgStep loop */ printf("All dispersal steps completed. Final output in progress...\n"); /* Update currentState matrix for pixels that are suitable but ** could not be colonized due to dispersal limitations. ** These pixels are assigned a value of 30'000 */ for (i = 0; i < nrRows; i++) { for (j = 0; j < nrCols; j++) { if ((habSuitability[i][j] > 0) && (currentState[i][j] <= 0)) currentState[i][j] = 30000; } } /* Write the final state matrix to file. */ /* sprintf(fileName, "%s/%s_raster.asc", simulName, simulName2); if (writeMat (fileName, currentState) == -1) { *nrFiles = -1; goto End_of_Routine; }*/ /* Write summary output to file. */ simulTime = time (NULL) - startTime; total_end = clock(); time_spent = (double)(total_end - total_begin) / CLOCKS_PER_SEC; printf("Process Completed after %lf \n",time_spent); sprintf(fileName, "%s/%s_summary.txt", outputDir, simulName2); if ((fp2 = fopen (fileName, "w")) != NULL) { fprintf(fp2, "simulName\tiniCount\tnoDispCount\tunivDispCount\toccupiedCount\tabsentCount\ttotColonized\ttotDecolonized\ttotLDDsuccess\trunTime\n"); fprintf(fp2, "%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", simulName2, nrInitial, nrNoDispersal, nrUnivDispersal, nrColonized, nrAbsent, nrTotColonized, nrTotDecolonized, nrTotLDDSuccess, simulTime); fclose (fp2); } else { *nrFiles = -1; printf ("Could not write summary output to file.\n"); goto End_of_Routine; } /* Close the data file. */ if (fp != NULL) fclose (fp); fp = NULL; } /* end of "RepLoop" */ /* Set the number of output files created. */ *nrFiles = envChgSteps; End_of_Routine: /* Close the data file. */ if (fp != NULL) fclose (fp); //fclose(f); /* Free the allocated memory. */ if (currentState != NULL) { for (i = 0; i < nrRows; i++) free(currentState[i]); free(currentState); } if (habSuitability != NULL) { for (i = 0; i < nrRows; i++) free(habSuitability[i]); free(habSuitability); } if (barriers != NULL) { for (i = 0; i < nrRows; i++) free(barriers[i]); free(barriers); } if (pixelAge != NULL) { for (i = 0; i < nrRows; i++) free(pixelAge[i]); free(pixelAge); } if (noDispersal != NULL) { for (i = 0; i < nrRows; i++) free(noDispersal[i]); free(noDispersal); } if (dispKernel != NULL) free(dispKernel); if (propaguleProd != NULL) free(propaguleProd); /* If an error occured, display failure message to the user... */ if (*nrFiles == -1) printf("MigClim simulation aborted...\n"); }
int ns__trainANN(struct soap *soap, char *inputMatFilename, char *neuralFile, char **OutputMatFilename) { double start, end; start = omp_get_wtime(); Mat src; //must be 3ch image if(!readMat(inputMatFilename, src)) { cerr << "trainANN :: can not read bin file" << endl; soap->fault->faultstring = "trainANN :: can not read bin file"; return SOAP_FAULT; } // convert src to CvMat to use an old-school function CvMat tmp = src; CV_Assert(tmp.cols == src.cols && tmp.rows == src.rows && tmp.data.ptr == (uchar*)src.data && tmp.step == src.step); CvMat *input3Ch = cvCreateMat(src.rows, src.cols, CV_32FC3); cvConvert(&tmp, input3Ch); CvMat *output1Ch = cvCreateMat(src.rows, src.cols, CV_32FC1); CvANN_MLP* neuron = NULL ; if (neuron == NULL ) neuron = new CvANN_MLP(); else neuron->clear(); if(!ByteArrayToANN(neuralFile, neuron)){ cerr << "trainANN :: can not load byte array to neural" << endl; return soap_receiver_fault(soap, "trainANN :: can not load byte array to neural", NULL); } CvMat input_nn = cvMat(input3Ch->height*input3Ch->width, 3, CV_32FC1, input3Ch->data.fl); CvMat output_nn = cvMat(output1Ch->height*output1Ch->width, 1, CV_32FC1, output1Ch->data.fl); neuron->predict(&input_nn, &output_nn); Mat resultNN = cvarrToMat(output1Ch, false); /* generate output file name */ *OutputMatFilename = (char*)soap_malloc(soap, FILENAME_SIZE); time_t now = time(0); strftime(*OutputMatFilename, sizeof(OutputMatFilename)*FILENAME_SIZE, "/home/lluu/dir/%Y%m%d_%H%M%S_trainANN", localtime(&now)); /* save to bin */ if(!saveMat(*OutputMatFilename, resultNN)) { cerr << "trainANN :: save mat to binary file" << endl; return soap_receiver_fault(soap, "trainANN :: save mat to binary file", NULL); } src.release(); resultNN.release(); cvReleaseMat(&output1Ch); end = omp_get_wtime(); cerr<<"ns__trainANN "<<"time elapsed "<<end-start<<endl; return SOAP_OK; }