void write_mat(const char *filename, const char *varname, double *array, size_t *dims) { mat_t *mat; matvar_t *var; mat = Mat_CreateVer(filename, NULL, MAT_FT_DEFAULT); if (!mat) { fprintf(stderr, "Error creating MAT file \"%s\"\n", filename); exit(EXIT_FAILURE); } var = Mat_VarCreate(varname, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, array, 0); if (!var) { fprintf(stderr, "Error creating variable %s.\n", varname); Mat_Close(mat); exit(EXIT_FAILURE); } Mat_VarWrite(mat, var, MAT_COMPRESSION_NONE); Mat_VarFree(var); Mat_Close(mat); }
void CSMatrix<Scalar>::export_to_file(const char *filename, const char *var_name, MatrixExportFormat fmt, char* number_format, bool invert_storage) { switch (fmt) { case EXPORT_FORMAT_MATRIX_MARKET: { FILE* file = fopen(filename, "w"); if(!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); if(Hermes::Helpers::TypeIsReal<Scalar>::value) fprintf(file, "%%%%Matrix<Scalar>Market matrix coordinate real\n"); else fprintf(file, "%%%%Matrix<Scalar>Market matrix coordinate complex\n"); fprintf(file, "%d %d %d\n", this->size, this->size, this->nnz); if(invert_storage) this->switch_orientation(); for (unsigned int j = 0; j < this->size; j++) { for (int i = Ap[j]; i < Ap[j + 1]; i++) { Hermes::Helpers::fprint_coordinate_num(file, i_coordinate(Ai[i] + 1, j + 1, invert_storage), j_coordinate(Ai[i] + 1, j + 1, invert_storage), Ax[i], number_format); fprintf(file, "\n"); } } if(invert_storage) this->switch_orientation(); fclose(file); } break; case EXPORT_FORMAT_MATLAB_MATIO: { #ifdef WITH_MATIO mat_sparse_t sparse; sparse.nzmax = this->nnz; if(invert_storage) this->switch_orientation(); sparse.nir = this->nnz; sparse.ir = Ai; sparse.njc = this->size + 1; sparse.jc = (int *) Ap; sparse.ndata = this->nnz; size_t dims[2]; dims[0] = this->size; dims[1] = this->size; mat_t *mat = Mat_CreateVer(filename, "", MAT_FT_MAT5); matvar_t *matvar; // For complex. No allocation here. double* Ax_re = nullptr; double* Ax_im = nullptr; // For real. if(Hermes::Helpers::TypeIsReal<Scalar>::value) { sparse.data = Ax; matvar = Mat_VarCreate(var_name, MAT_C_SPARSE, MAT_T_DOUBLE, 2, dims, &sparse, MAT_F_DONT_COPY_DATA); } else { // For complex. Ax_re = new double[this->nnz]; Ax_im = new double[this->nnz]; struct mat_complex_split_t z = {Ax_re, Ax_im}; for(int i = 0; i < this->nnz; i++) { Ax_re[i] = ((std::complex<double>)(this->Ax[i])).real(); Ax_im[i] = ((std::complex<double>)(this->Ax[i])).imag(); sparse.data = &z; } matvar = Mat_VarCreate(var_name, MAT_C_SPARSE, MAT_T_DOUBLE, 2, dims, &sparse, MAT_F_DONT_COPY_DATA | MAT_F_COMPLEX); } if (matvar) { Mat_VarWrite(mat, matvar, MAT_COMPRESSION_ZLIB); Mat_VarFree(matvar); } if(invert_storage) this->switch_orientation(); if(Ax_re) delete [] Ax_re; if(Ax_im) delete [] Ax_im; Mat_Close(mat); if(!matvar) throw Exceptions::IOException(Exceptions::IOException::Write, filename); #endif } break; case EXPORT_FORMAT_PLAIN_ASCII: { FILE* file = fopen(filename, "w"); if(!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); if(invert_storage) this->switch_orientation(); for (unsigned int j = 0; j < this->size; j++) { for (int i = Ap[j]; i < Ap[j + 1]; i++) { Helpers::fprint_coordinate_num(file, i_coordinate(Ai[i], j, invert_storage), j_coordinate(Ai[i], j, invert_storage), Ax[i], number_format); fprintf(file, "\n"); } } if(invert_storage) this->switch_orientation(); fclose(file); } } }
void CSMatrix<Scalar>::export_to_file(const char *filename, const char *var_name, MatrixExportFormat fmt, char* number_format, bool invert_storage) { switch (fmt) { case EXPORT_FORMAT_MATRIX_MARKET: { FILE* file = fopen(filename, "w"); if (!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); if (Hermes::Helpers::TypeIsReal<Scalar>::value) fprintf(file, "%%%%MatrixMarket matrix coordinate real general\n"); else fprintf(file, "%%%%MatrixMarket matrix coordinate complex general\n"); fprintf(file, "%d %d %d\n", this->size, this->size, this->nnz); if (invert_storage) this->switch_orientation(); for (unsigned int j = 0; j < this->size; j++) { for (int i = Ap[j]; i < Ap[j + 1]; i++) { Hermes::Helpers::fprint_coordinate_num(file, i_coordinate(Ai[i] + 1, j + 1, invert_storage), j_coordinate(Ai[i] + 1, j + 1, invert_storage), Ax[i], number_format); fprintf(file, "\n"); } } if (invert_storage) this->switch_orientation(); fclose(file); } break; case EXPORT_FORMAT_MATLAB_MATIO: { #ifdef WITH_MATIO mat_sparse_t sparse; sparse.nzmax = this->nnz; if (invert_storage) this->switch_orientation(); sparse.nir = this->nnz; sparse.ir = Ai; sparse.njc = this->size + 1; sparse.jc = (int *)Ap; sparse.ndata = this->nnz; size_t dims[2]; dims[0] = this->size; dims[1] = this->size; mat_t *mat = Mat_CreateVer(filename, "", MAT_FT_MAT5); matvar_t *matvar; // For complex. No allocation here. double* Ax_re = nullptr; double* Ax_im = nullptr; // For real. if (Hermes::Helpers::TypeIsReal<Scalar>::value) { sparse.data = Ax; matvar = Mat_VarCreate(var_name, MAT_C_SPARSE, MAT_T_DOUBLE, 2, dims, &sparse, MAT_F_DONT_COPY_DATA); } else { // For complex. Ax_re = malloc_with_check<CSMatrix<Scalar>, double>(this->nnz, this); Ax_im = malloc_with_check<CSMatrix<Scalar>, double>(this->nnz, this); struct mat_complex_split_t z = { Ax_re, Ax_im }; for (int i = 0; i < this->nnz; i++) { Ax_re[i] = ((std::complex<double>)(this->Ax[i])).real(); Ax_im[i] = ((std::complex<double>)(this->Ax[i])).imag(); sparse.data = &z; } matvar = Mat_VarCreate(var_name, MAT_C_SPARSE, MAT_T_DOUBLE, 2, dims, &sparse, MAT_F_DONT_COPY_DATA | MAT_F_COMPLEX); } if (matvar) { Mat_VarWrite(mat, matvar, MAT_COMPRESSION_ZLIB); Mat_VarFree(matvar); } if (invert_storage) this->switch_orientation(); free_with_check(Ax_re); free_with_check(Ax_im); Mat_Close(mat); if (!matvar) throw Exceptions::IOException(Exceptions::IOException::Write, filename); #endif } break; case EXPORT_FORMAT_PLAIN_ASCII: { FILE* file = fopen(filename, "w"); if (!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); if (invert_storage) this->switch_orientation(); for (unsigned int j = 0; j < this->size; j++) { for (int i = Ap[j]; i < Ap[j + 1]; i++) { Helpers::fprint_coordinate_num(file, i_coordinate(Ai[i], j, invert_storage), j_coordinate(Ai[i], j, invert_storage), Ax[i], number_format); fprintf(file, "\n"); } } if (invert_storage) this->switch_orientation(); fclose(file); } break; #ifdef WITH_BSON case EXPORT_FORMAT_BSON: { // Init bson bson bw; bson_init(&bw); // Matrix size. bson_append_int(&bw, "size", this->size); // Nonzeros. bson_append_int(&bw, "nnz", this->nnz); if (invert_storage) this->switch_orientation(); bson_append_start_array(&bw, "Ap"); for (unsigned int i = 0; i < this->size; i++) bson_append_int(&bw, "p", this->Ap[i]); bson_append_finish_array(&bw); bson_append_start_array(&bw, "Ai"); for (unsigned int i = 0; i < this->nnz; i++) bson_append_int(&bw, "i", this->Ai[i]); bson_append_finish_array(&bw); bson_append_start_array(&bw, "Ax"); for (unsigned int i = 0; i < this->nnz; i++) bson_append_double(&bw, "x", real(this->Ax[i])); bson_append_finish_array(&bw); if (!Hermes::Helpers::TypeIsReal<Scalar>::value) { bson_append_start_array(&bw, "Ax-imag"); for (unsigned int i = 0; i < this->nnz; i++) bson_append_double(&bw, "x-i", imag(this->Ax[i])); bson_append_finish_array(&bw); } bson_append_finish_array(&bw); if (invert_storage) this->switch_orientation(); // Done. bson_finish(&bw); // Write to disk. FILE *fpw; fpw = fopen(filename, "wb"); const char *dataw = (const char *)bson_data(&bw); fwrite(dataw, bson_size(&bw), 1, fpw); fclose(fpw); bson_destroy(&bw); } break; #endif } }
/******************************************************************************* Interface for MATIO function called Mat_Open Scilab function name : matfile_open *******************************************************************************/ int sci_matfile_open(char *fname, void* pvApiCtx) { int nbRow = 0, nbCol = 0; mat_t *matfile; int fileIndex = 0; char * filename = NULL; char * optionStr = NULL; int option = 0, var_type; int * filename_addr = NULL, * option_addr = NULL, * version_addr = NULL; char * versionStr = NULL; int version = MAT_FT_MAT5; // By default, use MAtlab 5 files SciErr sciErr; CheckRhs(1, 3); CheckLhs(1, 1); sciErr = getVarAddressFromPosition(pvApiCtx, 1, &filename_addr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } sciErr = getVarType(pvApiCtx, filename_addr, &var_type); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if (var_type == sci_strings) { getAllocatedSingleString(pvApiCtx, filename_addr, &filename); sciErr = getVarDimension(pvApiCtx, filename_addr, &nbRow, &nbCol); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if (nbCol != 1) { Scierror(999, _("%s: Wrong size for first input argument: string expected.\n"), fname); freeAllocatedSingleString(filename); return FALSE; } } else { Scierror(999, _("%s: Wrong type for first input argument: string expected.\n"), fname); freeAllocatedSingleString(filename); return FALSE; } if (Rhs >= 2) { sciErr = getVarAddressFromPosition(pvApiCtx, 2, &option_addr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } sciErr = getVarType(pvApiCtx, option_addr, &var_type); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if (var_type == sci_strings) { getAllocatedSingleString(pvApiCtx, option_addr, &optionStr); sciErr = getVarDimension(pvApiCtx, option_addr, &nbRow, &nbCol); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if (nbCol != 1) { Scierror(999, _("%s: Wrong size for second input argument: string expected.\n"), fname); freeAllocatedSingleString(filename); freeAllocatedSingleString(optionStr); return FALSE; } if (strcmp(optionStr, "r") == 0) { option = MAT_ACC_RDONLY; } else if (strcmp(optionStr, "w") == 0) { option = MAT_ACC_RDWR; } else { Scierror(999, _("%s: Wrong value for second input argument: 'r' or 'w' expected.\n"), fname); freeAllocatedSingleString(filename); freeAllocatedSingleString(optionStr); return FALSE; } } else { Scierror(999, _("%s: Wrong type for second input argument: string expected.\n"), fname); freeAllocatedSingleString(filename); freeAllocatedSingleString(optionStr); return FALSE; } } else { /* Default option value */ option = MAT_ACC_RDONLY; } if (Rhs >= 3) { sciErr = getVarAddressFromPosition(pvApiCtx, 3, &version_addr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } sciErr = getVarType(pvApiCtx, version_addr, &var_type); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } printf("sci_strings %d %d\n", var_type, sci_strings); if (var_type == sci_strings) { getAllocatedSingleString(pvApiCtx, version_addr, &versionStr); sciErr = getVarDimension(pvApiCtx, version_addr, &nbRow, &nbCol); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } if (nbCol != 1) { Scierror(999, _("%s: Wrong size for input argument #%d: string expected.\n"), fname, 3); freeAllocatedSingleString(filename); freeAllocatedSingleString(optionStr); freeAllocatedSingleString(versionStr); return FALSE; } if (strcmp(versionStr, "7.3") == 0) { version = MAT_FT_MAT73; // Matlab 7.3 file } else { version = MAT_FT_MAT5; // Default, Matlab 5 file } } else { Scierror(999, _("%s: Wrong type for input argument #%d: string expected.\n"), fname, 3); return 0; } } if (option == MAT_ACC_RDWR) // Write, option = "w" { /* create a Matlab 5 or 7.3 file */ matfile = Mat_CreateVer(filename, NULL, version); } else // Read, option = "r" { /* Try to open the file (as a Matlab 5 file) */ matfile = Mat_Open(filename, option); } if (matfile == NULL) /* Opening failed */ { /* Function returns -1 */ fileIndex = -1; } if (matfile != NULL) /* Opening succeed */ { /* Add the file to the manager */ matfile_manager(MATFILEMANAGER_ADDFILE, &fileIndex, &matfile); } /* Return the index */ createScalarDouble(pvApiCtx, Rhs + 1, (double)fileIndex); freeAllocatedSingleString(filename); freeAllocatedSingleString(optionStr); freeAllocatedSingleString(versionStr); LhsVar(1) = Rhs + 1; PutLhsVar(); return TRUE; }
int main (int argc, char *argv[]) { char *str,**str2,*(*qa_records)[4],*line, *oname, *dot, *filename; const char* ext=EXT; int i,j,k,n,n1,n2,cpu_word_size,io_word_size,exo_file,err, num_axes,num_nodes,num_elements,num_blocks, num_side_sets,num_node_sets,num_time_steps, num_qa_lines,num_info_lines,num_global_vars, num_nodal_vars,num_element_vars,num_nodeset_vars, num_sideset_vars, *ids,*iscr,*num_elem_in_block,*junk, *elem_list,*side_list, *nsssides,*nssdfac, *nnsnodes,*nnsdfac, nstr2, has_ss_dfac; float exo_version; double *scr,*x,*y,*z; oname=0; /* process arguments */ for (j=1; j< argc; j++){ if ( strcmp(argv[j],"-t")==0){ /* write text file (*.m) */ del_arg(&argc,argv,j); textfile=1; j--; continue; } if ( strcmp(argv[j],"-o")==0){ /* specify output file name */ del_arg(&argc,argv,j); if ( argv[j] ){ oname=(char*)calloc(strlen(argv[j])+10,sizeof(char)); strcpy(oname,argv[j]); del_arg(&argc,argv,j); printf("output file: %s\n",oname); } else { fprintf(stderr,"Invalid output file specification.\n"); return 2; } j--; continue; } } /* QA Info */ printf("%s: %s, %s\n", qainfo[0], qainfo[2], qainfo[1]); /* usage message*/ if(argc != 2){ printf("%s [options] exodus_file_name.\n",argv[0]); printf(" the exodus_file_name is required (exodusII only).\n"); printf(" Options:\n"); printf(" -t write a text (.m) file rather than a binary .mat\n"); printf(" -o output file name (rather than auto generate)\n"); printf(" ** note **\n"); printf("Binary files are written by default on all platforms with"); printf(" available libraries.\n"); exit(1); } /* open output file */ if ( textfile ) ext=".m"; if ( !oname ){ filename = (char*)malloc( strlen(argv[1])+10); strcpy(filename,argv[1]); dot=strrchr(filename,'.'); if ( dot ) *dot=0; strcat(filename,ext); } else { filename=oname; } if ( textfile ){ m_file = fopen(filename,"w"); if (!m_file ){ fprintf(stderr,"Unable to open %s\n",filename); exit(1); } } else { mat_file = Mat_CreateVer(filename, NULL, MAT_FT_MAT5); if (mat_file == NULL) { fprintf(stderr,"Unable to create matlab file %s\n",filename); exit(1); } } /* word sizes */ cpu_word_size=sizeof(double); io_word_size=0; /* open exodus file */ exo_file=ex_open(argv[1],EX_READ,&cpu_word_size,&io_word_size,&exo_version); if (exo_file < 0){ printf("error opening %s\n",argv[1]); exit(1); } /* print */ fprintf(stderr,"translating %s to %s ...\n",argv[1],filename); /* read database paramters */ line=(char *) calloc ((MAX_LINE_LENGTH+1),sizeof(char)); err = ex_get_init(exo_file,line, &num_axes,&num_nodes,&num_elements,&num_blocks, &num_node_sets,&num_side_sets); num_qa_lines = ex_inquire_int(exo_file,EX_INQ_QA); num_info_lines = ex_inquire_int(exo_file,EX_INQ_INFO); num_time_steps = ex_inquire_int(exo_file,EX_INQ_TIME); err=ex_get_variable_param(exo_file,EX_GLOBAL,&num_global_vars); err=ex_get_variable_param(exo_file,EX_NODAL,&num_nodal_vars); err=ex_get_variable_param(exo_file,EX_ELEM_BLOCK,&num_element_vars); err=ex_get_variable_param(exo_file,EX_NODE_SET,&num_nodeset_vars); err=ex_get_variable_param(exo_file,EX_SIDE_SET,&num_sideset_vars); /* export paramters */ PutInt("naxes", 1, 1,&num_axes); PutInt("nnodes", 1, 1,&num_nodes); PutInt("nelems", 1, 1,&num_elements); PutInt("nblks", 1, 1,&num_blocks); PutInt("nnsets", 1, 1,&num_node_sets); PutInt("nssets", 1, 1,&num_side_sets); PutInt("nsteps", 1, 1,&num_time_steps); PutInt("ngvars", 1, 1,&num_global_vars); PutInt("nnvars", 1, 1,&num_nodal_vars); PutInt("nevars", 1, 1,&num_element_vars); PutInt("nnsvars", 1, 1,&num_nodeset_vars); PutInt("nssvars", 1, 1,&num_sideset_vars); /* allocate -char- scratch space*/ n = num_info_lines; n = (n > num_global_vars) ? n : num_global_vars; n = (n > num_nodal_vars) ? n : num_nodal_vars; n = (n > num_element_vars) ? n : num_element_vars; n = (n > num_blocks) ? n : num_blocks; nstr2 = n; str2= (char **) calloc (n,sizeof(char *)); for (i=0;i<nstr2;i++) str2[i]=(char *) calloc ((MAX_LINE_LENGTH+1),sizeof(char)); str= (char *) calloc ((MAX_LINE_LENGTH+1)*n,sizeof(char)); /* title */ PutStr("Title",line); #if 0 /* QA records */ if (num_qa_lines > 0 ){ qa_records =(char *(*)[4]) calloc (num_qa_lines*4,sizeof(char **)); for (i=0;i<num_qa_lines;i++) for (j=0;j<4;j++) qa_records[i][j]=(char *) calloc ((MAX_STR_LENGTH+1),sizeof(char)); err=ex_get_qa(exo_file,qa_records); str[0]='\0'; for (i=0;i<num_qa_lines;i++){ for (j=0;j<4;j++) sprintf(str+strlen(str),"%s ",qa_records[i][j]); strcat(str,"\n"); } for (i=0;i<num_qa_lines;i++){ for (j=0;j<4;j++) free(qa_records[i][j]); } free(qa_records); } /* information records */ if (num_info_lines > 0 ){ err = ex_get_info(exo_file,str2); str[0]='\0'; for (i=0;i<num_info_lines;i++) sprintf(str+strlen(str),"%s\n",str2[i]); PutStr("info",str); str[0]='\0'; for (i=0;i<num_info_lines;i++) if (strncmp(str2[i],"cavi",4)==0) sprintf(str+strlen(str),"%s\n",str2[i]); PutStr("cvxp",str); } #endif /* nodal coordinates */ x = (double *) calloc(num_nodes,sizeof(double)); y = (double *) calloc(num_nodes,sizeof(double)); if (num_axes == 3) z = (double *) calloc(num_nodes,sizeof(double)); else z = NULL; err = ex_get_coord(exo_file,x,y,z); PutDbl("x0", num_nodes, 1, x); PutDbl("y0", num_nodes, 1, y); free(x); free(y); if (num_axes == 3){ PutDbl("z0",num_nodes,1, z); free(z); } /* side sets */ if(num_side_sets > 0){ ids=(int *) calloc(num_side_sets,sizeof(int)); err = ex_get_ids(exo_file,EX_SIDE_SET,ids); PutInt( "ssids",num_side_sets, 1,ids); nsssides = (int *) calloc(num_side_sets,sizeof(int)); /*dgriffi */ nssdfac = (int *) calloc(num_side_sets,sizeof(int)); /*dgriffi */ for (i=0;i<num_side_sets;i++){ err = ex_get_set_param(exo_file,EX_SIDE_SET, ids[i],&n1,&n2); nsssides[i]=n1; /* dgriffi */ nssdfac[i]=n2; /* dgriffi */ /* * the following provision is from Version 1.6 when there are no * distribution factors in exodus file */ has_ss_dfac = (n2 != 0); if(n2==0 || n1==n2){ printf(" WARNING: Exodus II file does not contain distribution factors.\n"); /* n1=number of faces, n2=number of df */ /* using distribution factors to determine number of nodes in the sideset causes a lot grief since some codes do not output distribution factors if they are all equal to 1. mkbhard: I am using the function call below to figure out the total number of nodes in this sideset. Some redundancy exists, but it works for now */ junk = (int*) calloc(n1,sizeof(int)); err = ex_get_side_set_node_count(exo_file,ids[i],junk); n2=0; /* n2 will be equal to the total number of nodes in the sideset */ for (j=0;j<n1;j++) n2+=junk[j]; free(junk); } iscr = (int *) calloc(n1+n2,sizeof(int)); err = ex_get_side_set_node_list(exo_file,ids[i],iscr,iscr+n1); /* number-of-nodes-per-side list */ sprintf(str,"ssnum%02d",i+1); PutInt(str,n1,1,iscr); /* nodes list */ sprintf(str,"ssnod%02d",i+1); PutInt(str,n2,1,iscr+n1); free(iscr); /* distribution-factors list */ scr = (double *) calloc (n2,sizeof(double)); if (has_ss_dfac) { ex_get_side_set_dist_fact(exo_file,ids[i],scr); } else { for (j=0; j<n2; j++) { scr[j] = 1.0; } } sprintf(str,"ssfac%02d",i+1); PutDbl(str,n2,1,scr); free(scr); /* element and side list for side sets (dgriffi) */ elem_list = (int *) calloc(n1, sizeof(int)); side_list = (int *) calloc(n1, sizeof(int)); err = ex_get_set(exo_file,EX_SIDE_SET,ids[i],elem_list,side_list); sprintf(str,"ssside%02d",i+1); PutInt(str,n1,1,side_list); sprintf(str,"sselem%02d",i+1); PutInt(str,n1,1,elem_list); free(elem_list); free(side_list); } /* Store # sides and # dis. factors per side set (dgriffi) */ PutInt("nsssides",num_side_sets,1,nsssides); PutInt("nssdfac",num_side_sets,1,nssdfac); free(ids); free(nsssides); free(nssdfac); } /* node sets (section by dgriffi) */ if(num_node_sets > 0){ ids=(int *) calloc(num_node_sets,sizeof(int)); err = ex_get_ids(exo_file,EX_NODE_SET, ids); PutInt( "nsids",num_node_sets, 1,ids); nnsnodes = (int *) calloc(num_node_sets,sizeof(int)); nnsdfac = (int *) calloc(num_node_sets,sizeof(int)); for (i=0;i<num_node_sets;i++){ err = ex_get_set_param(exo_file,EX_NODE_SET,ids[i],&n1,&n2); iscr = (int *) calloc(n1,sizeof(int)); err = ex_get_node_set(exo_file,ids[i],iscr); /* nodes list */ sprintf(str,"nsnod%02d",i+1); PutInt(str,n1,1,iscr); free(iscr); /* distribution-factors list */ scr = (double *) calloc (n2,sizeof(double)); ex_get_node_set_dist_fact(exo_file,ids[i],scr); sprintf(str,"nsfac%02d",i+1); PutDbl(str,n2,1,scr); free(scr); nnsnodes[i]=n1; nnsdfac[i]=n2; } /* Store # nodes and # dis. factors per node set */ PutInt("nnsnodes",num_node_sets,1,nnsnodes); PutInt("nnsdfac",num_node_sets,1,nnsdfac); free(ids); free(nnsdfac); free(nnsnodes); } /* element blocks */ ids=(int *) calloc(num_blocks,sizeof(int)); num_elem_in_block=(int *) calloc(num_blocks,sizeof(int)); err = ex_get_ids(exo_file,EX_ELEM_BLOCK,ids); PutInt( "blkids",num_blocks, 1,ids); for (i=0;i<num_blocks;i++) { err = ex_get_elem_block(exo_file,ids[i],str2[i],&n,&n1,&n2); num_elem_in_block[i]=n; iscr = (int *) calloc(n*n1,sizeof(int)); err = ex_get_conn(exo_file,EX_ELEM_BLOCK,ids[i],iscr, NULL, NULL); sprintf(str,"blk%02d",i+1); PutInt(str,n1,n,iscr); free(iscr); } str[0]='\0'; for (i=0;i<num_blocks;i++) sprintf(str+strlen(str),"%s\n",str2[i]); PutStr("blknames",str); /* time values */ if (num_time_steps > 0 ) { scr = (double *) calloc (num_time_steps,sizeof(double)); err= ex_get_all_times (exo_file,scr); PutDbl( "time", num_time_steps, 1,scr); free(scr); } /* global variables */ if (num_global_vars > 0 ) { err = ex_get_variable_names(exo_file,EX_GLOBAL,num_global_vars,str2); str[0]='\0'; for (i=0;i<num_global_vars;i++) sprintf(str+strlen(str),"%s\n",str2[i]); PutStr("gnames",str); scr = (double *) calloc (num_time_steps,sizeof(double)); for (i=0;i<num_global_vars;i++){ sprintf(str,"gvar%02d",i+1); err=ex_get_glob_var_time(exo_file,i+1,1,num_time_steps,scr); PutDbl(str,num_time_steps,1,scr); } free(scr); } /* nodal variables */ if (num_nodal_vars > 0 ) { err = ex_get_variable_names(exo_file,EX_NODAL,num_nodal_vars,str2); str[0]='\0'; for (i=0;i<num_nodal_vars;i++) sprintf(str+strlen(str),"%s\n",str2[i]); PutStr("nnames",str); scr = (double *) calloc (num_nodes*num_time_steps,sizeof(double)); for (i=0;i<num_nodal_vars;i++){ sprintf(str,"nvar%02d",i+1); for (j=0;j<num_time_steps;j++) err=ex_get_nodal_var(exo_file,j+1,i+1,num_nodes, scr+num_nodes*j); PutDbl(str,num_nodes,num_time_steps,scr); } free(scr); } /* element variables */ if (num_element_vars > 0 ) { err = ex_get_variable_names(exo_file,EX_ELEM_BLOCK,num_element_vars,str2); str[0]='\0'; for (i=0;i<num_element_vars;i++) sprintf(str+strlen(str),"%s\n",str2[i]); PutStr("enames",str); /* truth table */ iscr = (int *) calloc(num_element_vars*num_blocks, sizeof(int)); ex_get_elem_var_tab(exo_file,num_blocks,num_element_vars,iscr); for (i=0;i<num_element_vars;i++){ scr = (double *) calloc (num_elements*num_time_steps,sizeof(double)); n=0; sprintf(str,"evar%02d",i+1); for (j=0;j<num_time_steps;j++){ for (k=0;k<num_blocks;k++){ if(iscr[num_element_vars*k+i]==1) ex_get_elem_var(exo_file,j+1,i+1,ids[k],num_elem_in_block[k],scr+n); n=n+num_elem_in_block[k]; } } PutDbl(str,num_elements,num_time_steps,scr); free(scr); } free(iscr); } free(num_elem_in_block); free(ids); /* node and element number maps */ ex_opts(0); /* turn off error reporting. It is not an error to have no map*/ ids = (int *)malloc(num_nodes*sizeof(int)); err = ex_get_node_num_map(exo_file,ids); if ( err==0 ){ PutInt("node_num_map",num_nodes,1,ids); } free(ids); ids = (int *)malloc(num_elements*sizeof(int)); err = ex_get_elem_num_map(exo_file,ids); if ( err==0 ){ PutInt("elem_num_map",num_elements,1,ids); } free(ids); /* close exo file */ ex_close(exo_file); /* close mat file */ if ( textfile ) fclose(m_file); else Mat_Close(mat_file); /* */ fprintf(stderr,"done.\n"); free(filename); free(line); free(str); for (i=0;i<nstr2;i++) free(str2[i]); free(str2); /* exit status */ add_to_log("exo2mat", 0); return(0); }
void Job::run(){ if (Print) cout << endl << "------ new run ------ iRip==" << iRip << endl << endl; // int iTr=0,iTs=0,iVar,iV,iFRip, i,ii, trsz=ds.pr->TrSzD, tssz=ds.pr->TsSzD, valdim=ds.LabelValSelSize; double acc[trsz][tssz][FRip], mse[trsz][tssz][FRip], scc[trsz][tssz][FRip], featNum[FeatSelSize][FRip], *res,trends[valdim][trsz][FRip],actualLabel[valdim],ValidTrend[valdim]; matvar_t *varnameC; // for (iVar=0; iVar<LabelSelSize; ++iVar){ iV=LabelSelIdx[iVar]; // questa e` la variabile che vogliamo decodificare // -------------- cambio il nome del file in modo da coincidere con la variabile -------------------------------------- string resFile_=resFile,VARNAME; // cosi` lo scope e` locale in questo ciclo varnameC = Mat_VarGetCell(VARIABLEs,iV); // recupero il nome di questa variabile VARNAME=(const char*)varnameC->data; // segnalo dove sono a video if (Print) cout << endl << "------ iV=" << VARNAME << endl << endl; // resFile_+=VARNAME; resFile_+="-"; // riporto quale variabile sto esaminando nel filename resFile_+="nF_"; resFile_+=to_string(FeatSelSize); resFile_+="-"; // e quante features resFile_+="res.mat"; // aggiungo l'estensione // elimino gli spazi resFile_.erase(remove_if(resFile_.begin(), resFile_.end(), [](char x){return isspace(x);}), resFile_.end()); // -------------------------------------------------------------------------------------------------------------------- // // ---------------------------- recupero l'andamento della label sul validation set ---------------------------------- for (ii=0; ii<valdim; ++ii){ i=ds.label_valid_selection[ii]; actualLabel[ii]=labels[LabelSize[0]*iV+i]; // prendo l'i-esimo indice del del validation set della variabile iV // LabelSize[0] e` il numero totale delle istanze } // --------------------------------------------------------------------------------------------------------------------- // for (iTr=0; iTr<trsz; ++iTr){ ds.assegnoTrainingSet(iTr); for (iFRip=0; iFRip<FRip; ++iFRip){ if (Print) cout << endl << "------ iTr%=" << (double)iTr/trsz << endl << "------ iFRip%=" << (double)iFRip/FRip << endl << endl; UpdateFeatureSelection(); // cambio, se devo, la selezione delle features // // ----------------------------------------- recupero gli indici delle features --------------------------------------- for (i=0; i<FeatSelSize; ++i) // recupero gli indici delle feature che ho usato featNum[i][iFRip]=(double)(feature_sel[i]+1); // per metterla nel ws di matio // aggiungo 1.0 per come funziona l'indicizzazione su matlab // --------------------------------------------------------------------------------------------------------------------- // // per debug if (0){ cout << endl << "feat idx" << endl; for (int i=0; i<FeatSelSize; ++i) cout << " " << feature_sel[i]; cout << endl; } assegnato_svm=false; // devo riaddestrare per ogni Training Set o per ogni sottocampionamento delle features TrainingFromAssignedProblem(iV); // addestro con lo stesso Training Set ma (forse) diverse Features predictValidationSet(ValidTrend,iV); // Test sul Validation Set // ------------------------------- recupero i trends sul Validation Set ----------------------------------------- for (ii=0; ii<valdim; ++ii) trends[ii][iTr][iFRip]=ValidTrend[ii]; // -------------------------------------------------------------------------------------------------------------- // for (iTs=0; iTs<tssz; ++iTs){ ds.assegnoTestSet(iTs); predictTestSet(iV); // recupero le performance del modello res = (double *)((matvar_t *)RES[1])->data; acc[iTr][iTs][iFRip]=res[0]; mse[iTr][iTs][iFRip]=res[1]; scc[iTr][iTs][iFRip]=res[2]; } } } // -------------- salvo un file per ogni variabile | setto il workspace da salvare -------------------------------------- int WsSize=12; matvar_t *workspace[WsSize]; size_t dims_3[3], dims_2[2], dims_1[1]; dims_3[2]=trsz; dims_3[1]=tssz; dims_3[0]=FRip; dims_2[1]=FeatSelSize; dims_2[0]=FRip; dims_1[0]=1; workspace[0] = Mat_VarCreate("acc",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,acc,0); workspace[1] = Mat_VarCreate("mse",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,mse,0); workspace[2] = Mat_VarCreate("scc",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,scc,0); workspace[3] = Mat_VarCreate("featIdx",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims_2,featNum,0); dims_2[1]=valdim; dims_2[0]=1; workspace[4] = Mat_VarCreate("actualLabel",MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims_2,actualLabel,0); dims_3[2]=valdim; dims_3[1]=trsz; dims_3[0]=FRip; workspace[5] = Mat_VarCreate("trends",MAT_C_DOUBLE,MAT_T_DOUBLE,3,dims_3,trends,0); double FRip_ws[1], trsz_ws[1], tssz_ws[1], FeatSelSize_ws[1], validSz_ws[1]; FRip_ws[0]=FRip; trsz_ws[0]=trsz; tssz_ws[0]=tssz; FeatSelSize_ws[0]=FeatSelSize; validSz_ws[0]=valdim; workspace[6] = Mat_VarCreate("FeatSelectionRip",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,FRip_ws,0); workspace[7] = Mat_VarCreate("NumFeatures",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,FeatSelSize_ws,0); workspace[8] = Mat_VarCreate("TrSz",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,trsz_ws,0); workspace[9] = Mat_VarCreate("TsSz",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,tssz_ws,0); workspace[10] = Mat_VarCreate("ValidationSetSize",MAT_C_DOUBLE,MAT_T_DOUBLE,1,dims_1,validSz_ws,0); string help ="CONTENUTO DEL MATFILE:\n"; help+="{acc,mse,scc}\n"; help+="\tdimensione RxTsxTr\n"; help+="\t(accuratezza,mean squared error ed r2\n\toutput di libsvm)\n"; help+="featIdx\n"; help+="\tdimensione RxN\n"; help+="\t(indice delle features usate per addestrare\n\t il modello ad ogni ricampionamento)\n"; help+="actualLabel\n"; help+="\tdimensione 1xV\n"; help+="\t(valore della label corrispondente al validation set\n\tNB: salvo un file diverso per ogni label)\n"; help+="trends\n"; help+="\tdimensione RxTrxV\n"; help+="\t(predizione della label, ne ho una diverso per ogni modello\n\tNB: ho un modello diverso per ogni\n\t +ricampionamento delle features\n\t +ricampionamento del training set)\n"; help+="***LEGENDA***\n"; help+="\tR=FeatSelectionRip\n"; help+="\tTs=TsSz\n"; help+="\tTr=TrSz\n"; help+="\tN=NumFeatures\n"; help+="\tV=ValidationSetSize\n"; dims_2[1]=help.size(); dims_2[0]=1; workspace[11] = Mat_VarCreate("README",MAT_C_CHAR,MAT_T_UINT8,2,dims_2,(char*)help.c_str(),0); // Apro scrivo e chiudo il matfile mat_t *Out_MATFILE = Mat_CreateVer((const char*)resFile_.c_str(),NULL,MAT_FT_DEFAULT); for (int iWS=0; iWS<WsSize; ++iWS) Mat_VarWrite(Out_MATFILE, workspace[iWS], MAT_COMPRESSION_NONE); Mat_Close(Out_MATFILE); // ---------------------------------------------------------------------------------------------------------------------- } return; }
int main(int argc, char **argv) { char *mdf_filename = NULL; char *mat_filename = NULL; const mdf_t *mdf; filter_t *filter; char *filter_filename = NULL; char *program_name = argv[0]; /* parse arguments */ while (1) { static struct option long_options[] = { /* These options set a flag. */ {"verbose", no_argument, &verbose_level, 1}, {"debug", no_argument, &verbose_level, 2}, {"deep", no_argument, &verbose_level, 3}, {"brief", no_argument, &verbose_level, 0}, {"v5", no_argument, &mat_file_ver, (int)MAT_FT_MAT5}, {"v73", no_argument, &mat_file_ver, (int)MAT_FT_MAT73}, {"compress",no_argument, NULL, 'z'}, /* These options don't set a flag. We distinguish them by their indices. */ {"filter", required_argument, 0, (int)'f'}, {"help", no_argument, NULL, (int)'h'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; int c; c = getopt_long (argc, argv, "a:b:d:f:hm:t:vz", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: break; case 'f': filter_filename = optarg; break; case 'h': help(program_name); exit(EXIT_SUCCESS); break; case 'v': verbose_level = 1; break; case 'd': verbose_level = 2; break; case 'z': mdftomat.compress = MAT_COMPRESSION_ZLIB; break; case '?': /* getopt_long already printed an error message. */ usage_error(program_name); break; default: fprintf(stderr, "error: unknown option %c\n", c); usage_error(program_name); } } /* check structure packing */ assert(offsetof(cn_block_t,link_asam_mcd_name) == 218); /* input files */ if (optind == argc - 2) { mdf_filename = argv[optind++]; mat_filename = argv[optind++]; } else { fprintf(stderr, "error: wrong number of arguments\n"); usage_error(program_name); return 1; } /* print banner */ if(verbose_level >= 1) { fprintf(stderr, "%s (%s, %s, cantools " PACKAGE_VERSION ")\n", program_name, __DATE__, __TIME__); } /* connect to mdf file */ mdf = mdf_attach(mdf_filename, verbose_level); if(mdf == NULL) { return 1; } /* create mat file */ mdftomat.mat = Mat_CreateVer(mat_filename, NULL, (enum mat_ft)mat_file_ver); if(mdftomat.mat == NULL) { fprintf(stderr,"can't write to mat file %s\n",mat_filename); return 1; } /* read filter */ if(filter_filename != NULL) { filter = mdf_filter_create(filter_filename); if(filter == NULL) { return 1; } } else { filter = NULL; } /* process MDF file */ if(verbose_level >= 1) { fprintf(stderr, "converting %s to %sfile %s\n", mdf_filename, (mdftomat.compress == MAT_COMPRESSION_ZLIB)?"compressed ":"", mat_filename); } mdfProcess(mdf, &mdftomat, filter); /* free filter */ filter_free(filter); /* detach from mdf file */ mdf_detach(mdf); /* close mat file */ Mat_Close(mdftomat.mat); /* say goodbye */ if(verbose_level >= 1) { puts("done."); } return 0; }
void SimpleVector<Scalar>::export_to_file(const char *filename, const char *var_name, MatrixExportFormat fmt, char* number_format) { if(!v) throw Exceptions::MethodNotOverridenException("Vector<Scalar>::export_to_file"); switch (fmt) { case EXPORT_FORMAT_MATRIX_MARKET: { FILE* file = fopen(filename, "w"); if(!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); if(Hermes::Helpers::TypeIsReal<Scalar>::value) fprintf(file, "%%%%Matrix<Scalar>Market matrix coordinate real\n"); else fprintf(file, "%%%%Matrix<Scalar>Market matrix coordinate complex\n"); fprintf(file, "%d 1 %d\n", this->size, this->size); for (unsigned int j = 0; j < this->size; j++) { Hermes::Helpers::fprint_coordinate_num(file, j + 1, 1, v[j], number_format); fprintf(file, "\n"); } fclose(file); } break; case EXPORT_FORMAT_MATLAB_MATIO: { #ifdef WITH_MATIO size_t dims[2]; dims[0] = this->size; dims[1] = 1; mat_t *mat = Mat_CreateVer(filename, "", MAT_FT_MAT5); matvar_t *matvar; // For complex. double* v_re = nullptr; double* v_im = nullptr; void* data; if(Hermes::Helpers::TypeIsReal<Scalar>::value) { data = v; matvar = Mat_VarCreate(var_name, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, data, MAT_F_DONT_COPY_DATA); } else { v_re = new double[this->size]; v_im = new double[this->size]; struct mat_complex_split_t z = {v_re, v_im}; for(int i = 0; i < this->size; i++) { v_re[i] = ((std::complex<double>)(this->v[i])).real(); v_im[i] = ((std::complex<double>)(this->v[i])).imag(); data = &z; } matvar = Mat_VarCreate(var_name, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, data, MAT_F_DONT_COPY_DATA | MAT_F_COMPLEX); } if (matvar) { Mat_VarWrite(mat, matvar, MAT_COMPRESSION_ZLIB); Mat_VarFree(matvar); } if(v_re) delete [] v_re; if(v_im) delete [] v_im; Mat_Close(mat); if(!matvar) throw Exceptions::IOException(Exceptions::IOException::Write, filename); #else throw Exceptions::Exception("MATIO not included."); #endif } break; case EXPORT_FORMAT_PLAIN_ASCII: { FILE* file = fopen(filename, "w"); if(!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); for (unsigned int i = 0; i < this->size; i++) { Hermes::Helpers::fprint_num(file, v[i], number_format); fprintf(file, "\n"); } fclose(file); } } }
void SimpleVector<Scalar>::export_to_file(const char *filename, const char *var_name, MatrixExportFormat fmt, char* number_format) { if (!v) throw Exceptions::MethodNotOverridenException("Vector<Scalar>::export_to_file"); switch (fmt) { case EXPORT_FORMAT_MATRIX_MARKET: { FILE* file = fopen(filename, "w"); if (!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); if (Hermes::Helpers::TypeIsReal<Scalar>::value) fprintf(file, "%%%%MatrixMarket matrix coordinate real general\n"); else fprintf(file, "%%%%MatrixMarket matrix coordinate complex general\n"); fprintf(file, "%d 1 %d\n", this->size, this->size); for (unsigned int j = 0; j < this->size; j++) { Hermes::Helpers::fprint_coordinate_num(file, j + 1, 1, v[j], number_format); fprintf(file, "\n"); } fclose(file); } break; case EXPORT_FORMAT_MATLAB_MATIO: { #ifdef WITH_MATIO size_t dims[2]; dims[0] = this->size; dims[1] = 1; mat_t *mat = Mat_CreateVer(filename, "", MAT_FT_MAT5); matvar_t *matvar; // For complex. double* v_re = nullptr; double* v_im = nullptr; void* data; if (Hermes::Helpers::TypeIsReal<Scalar>::value) { data = v; matvar = Mat_VarCreate(var_name, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, data, MAT_F_DONT_COPY_DATA); } else { v_re = malloc_with_check<SimpleVector<Scalar>, double>(this->size, this); v_im = malloc_with_check<SimpleVector<Scalar>, double>(this->size, this); struct mat_complex_split_t z = { v_re, v_im }; for (int i = 0; i < this->size; i++) { v_re[i] = ((std::complex<double>)(this->v[i])).real(); v_im[i] = ((std::complex<double>)(this->v[i])).imag(); data = &z; } matvar = Mat_VarCreate(var_name, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, data, MAT_F_DONT_COPY_DATA | MAT_F_COMPLEX); } if (matvar) { Mat_VarWrite(mat, matvar, MAT_COMPRESSION_ZLIB); Mat_VarFree(matvar); } free_with_check(v_re); free_with_check(v_im); Mat_Close(mat); if (!matvar) throw Exceptions::IOException(Exceptions::IOException::Write, filename); #else throw Exceptions::Exception("MATIO not included."); #endif } break; case EXPORT_FORMAT_PLAIN_ASCII: case EXPORT_FORMAT_MATLAB_SIMPLE: { FILE* file = fopen(filename, "w"); if (!file) throw Exceptions::IOException(Exceptions::IOException::Write, filename); for (unsigned int i = 0; i < this->size; i++) { Hermes::Helpers::fprint_num(file, v[i], number_format); fprintf(file, "\n"); } fclose(file); } break; #ifdef WITH_BSON case EXPORT_FORMAT_BSON: { // Init bson bson bw; bson_init(&bw); // Matrix size. bson_append_int(&bw, "size", this->size); bson_append_start_array(&bw, "v"); for (unsigned int i = 0; i < this->size; i++) bson_append_double(&bw, "v_i", real(this->v[i])); bson_append_finish_array(&bw); if (!Hermes::Helpers::TypeIsReal<Scalar>::value) { bson_append_start_array(&bw, "v-imag"); for (unsigned int i = 0; i < this->size; i++) bson_append_double(&bw, "v_i", imag(this->v[i])); bson_append_finish_array(&bw); } // Done. bson_finish(&bw); // Write to disk. FILE *fpw; fpw = fopen(filename, "wb"); const char *dataw = (const char *)bson_data(&bw); fwrite(dataw, bson_size(&bw), 1, fpw); fclose(fpw); bson_destroy(&bw); } #endif } }
int main (int argc, char *argv[]) { char *oname = nullptr, *dot = nullptr, *filename = nullptr; char str[32]; const char* ext=EXT; int n, n1,n2,err, num_axes,num_blocks, num_side_sets,num_node_sets,num_time_steps, num_info_lines,num_global_vars, num_nodal_vars,num_element_vars,num_nodeset_vars, num_sideset_vars; size_t num_nodes = 0; size_t num_elements = 0; int mat_version = 73; /* process arguments */ for (int j=1; j< argc; j++){ if ( strcmp(argv[j],"-t")==0){ /* write text file (*.m) */ del_arg(&argc,argv,j); textfile=1; j--; continue; } if ( strcmp(argv[j],"-h")==0){ /* write help info */ del_arg(&argc,argv,j); usage(); exit(1); } if ( strcmp(argv[j],"-d")==0){ /* write help info */ del_arg(&argc,argv,j); j--; debug = 1; continue; } if ( strcmp(argv[j],"-v73")==0){ /* Version 7.3 */ del_arg(&argc,argv,j); mat_version = 73; j--; continue; } // This matches the option used in matlab if ( (strcmp(argv[j],"-v7.3")==0) || (strcmp(argv[j],"-V7.3")==0)){ /* Version 7.3 */ del_arg(&argc,argv,j); mat_version = 73; j--; continue; } if ( strcmp(argv[j],"-v5")==0){ /* Version 5 (default) */ del_arg(&argc,argv,j); mat_version = 50; j--; continue; } if ( strcmp(argv[j],"-o")==0){ /* specify output file name */ del_arg(&argc,argv,j); if ( argv[j] ){ oname=(char*)calloc(strlen(argv[j])+10,sizeof(char)); strcpy(oname,argv[j]); del_arg(&argc,argv,j); std::cout << "output file: " << oname << "\n"; } else { std::cerr << "ERROR: Invalid output file specification.\n"; return 2; } j--; continue; } } /* QA Info */ printf("%s: %s, %s\n", qainfo[0], qainfo[2], qainfo[1]); /* usage message*/ if (argc != 2){ usage(); exit(1); } /* open output file */ if ( textfile ) ext=".m"; if ( !oname ){ filename = (char*)malloc( strlen(argv[1])+10); strcpy(filename,argv[1]); dot=strrchr(filename,'.'); if ( dot ) *dot='\0'; strcat(filename,ext); } else { filename=oname; } if ( textfile ){ m_file = fopen(filename,"w"); if (!m_file ){ std::cerr << "ERROR: Unable to open " << filename << "\n"; exit(1); } } else { if (mat_version == 50) { mat_file = Mat_CreateVer(filename, nullptr, MAT_FT_MAT5); } else if (mat_version == 73) { mat_file = Mat_CreateVer(filename, nullptr, MAT_FT_MAT73); } if (mat_file == nullptr) { std::cerr << "ERROR: Unable to create matlab file " << filename << "\n"; exit(1); } } /* word sizes */ int cpu_word_size=sizeof(double); int io_word_size=0; /* open exodus file */ float exo_version; int exo_file=ex_open(argv[1],EX_READ,&cpu_word_size,&io_word_size,&exo_version); if (exo_file < 0){ std::cerr << "ERROR: Cannot open " << argv[1] << "\n"; exit(1); } /* print */ std::cout << "\ttranslating " << argv[1] << " to " << filename << "...\n"; /* read database paramters */ char *line=(char *) calloc ((MAX_LINE_LENGTH+1),sizeof(char)); ex_get_init(exo_file,line, &num_axes,&num_nodes,&num_elements,&num_blocks, &num_node_sets,&num_side_sets); num_info_lines = ex_inquire_int(exo_file,EX_INQ_INFO); num_time_steps = ex_inquire_int(exo_file,EX_INQ_TIME); ex_get_variable_param(exo_file,EX_GLOBAL,&num_global_vars); ex_get_variable_param(exo_file,EX_NODAL,&num_nodal_vars); ex_get_variable_param(exo_file,EX_ELEM_BLOCK,&num_element_vars); ex_get_variable_param(exo_file,EX_NODE_SET,&num_nodeset_vars); ex_get_variable_param(exo_file,EX_SIDE_SET,&num_sideset_vars); /* export paramters */ PutInt("naxes", num_axes); PutInt("nnodes", num_nodes); PutInt("nelems", num_elements); PutInt("nblks", num_blocks); PutInt("nnsets", num_node_sets); PutInt("nssets", num_side_sets); PutInt("nsteps", num_time_steps); PutInt("ngvars", num_global_vars); PutInt("nnvars", num_nodal_vars); PutInt("nevars", num_element_vars); PutInt("nnsvars",num_nodeset_vars); PutInt("nssvars",num_sideset_vars); /* allocate -char- scratch space*/ int nstr2 = num_info_lines; nstr2 = std::max(nstr2, num_blocks); nstr2 = std::max(nstr2, num_node_sets); nstr2 = std::max(nstr2, num_side_sets); char **str2 = get_exodus_names(nstr2, 512); /* title */ PutStr("Title",line); /* information records */ if (num_info_lines > 0 ){ ex_get_info(exo_file,str2); std::string ostr; for (int i=0;i<num_info_lines;i++) { if (strlen(str2[i]) > 0) { ostr += str2[i]; ostr += "\n"; } } PutStr("info",ostr.c_str()); ostr = ""; for (int i=0;i<num_info_lines;i++) { if (strlen(str2[i]) > 0 && strncmp(str2[i],"cavi",4)==0) { ostr += str2[i]; ostr += "\n"; } } PutStr("cvxp",ostr.c_str()); } /* nodal coordinates */ { if (debug) {logger("Coordinates");} std::vector<double> x, y, z; x.resize(num_nodes); if (num_axes >= 2) y.resize(num_nodes); if (num_axes == 3) z.resize(num_nodes); ex_get_coord(exo_file,TOPTR(x), TOPTR(y), TOPTR(z)); PutDbl("x0", num_nodes, 1, TOPTR(x)); if (num_axes >= 2) { PutDbl("y0", num_nodes, 1, TOPTR(y)); } if (num_axes == 3){ PutDbl("z0",num_nodes,1, TOPTR(z)); } } /* side sets */ std::vector<int> num_sideset_sides(num_side_sets); std::vector<int> ids; if (num_side_sets > 0) { if (debug) {logger("Side Sets");} ids.resize(num_side_sets); ex_get_ids(exo_file,EX_SIDE_SET,TOPTR(ids)); PutInt( "ssids",num_side_sets, 1,TOPTR(ids)); std::vector<int> nssdfac(num_side_sets); std::vector<int> iscr; std::vector<int> jscr; std::vector<double> scr; std::vector<int> elem_list; std::vector<int> side_list; std::vector<int> junk; for (int i=0;i<num_side_sets;i++) { ex_get_set_param(exo_file,EX_SIDE_SET, ids[i],&n1,&n2); num_sideset_sides[i]=n1; nssdfac[i]=n2; /* * the following provision is from Version 1.6 when there are no * distribution factors in exodus file */ bool has_ss_dfac = (n2 != 0); if (n2==0 || n1==n2){ std::cerr << "WARNING: Exodus II file does not contain distribution factors.\n"; /* n1=number of faces, n2=number of df */ /* using distribution factors to determine number of nodes in the sideset causes a lot grief since some codes do not output distribution factors if they are all equal to 1. mkbhard: I am using the function call below to figure out the total number of nodes in this sideset. Some redundancy exists, but it works for now */ junk.resize(n1); ex_get_side_set_node_count(exo_file,ids[i],TOPTR(junk)); n2=0; /* n2 will be equal to the total number of nodes in the sideset */ for (int j=0; j<n1; j++) n2+=junk[j]; } iscr.resize(n1); jscr.resize(n2); ex_get_side_set_node_list(exo_file,ids[i],TOPTR(iscr),TOPTR(jscr)); /* number-of-nodes-per-side list */ sprintf(str,"ssnum%02d",i+1); PutInt(str,n1,1,TOPTR(iscr)); /* nodes list */ sprintf(str,"ssnod%02d",i+1); PutInt(str,n2,1,TOPTR(jscr)); /* distribution-factors list */ scr.resize(n2); if (has_ss_dfac) { ex_get_side_set_dist_fact(exo_file,ids[i], TOPTR(scr)); } else { for (int j=0; j<n2; j++) { scr[j] = 1.0; } } sprintf(str,"ssfac%02d",i+1); PutDbl(str,n2,1,TOPTR(scr)); /* element and side list for side sets (dgriffi) */ elem_list.resize(n1); side_list.resize(n1); ex_get_set(exo_file,EX_SIDE_SET,ids[i],TOPTR(elem_list),TOPTR(side_list)); sprintf(str,"ssside%02d",i+1); PutInt(str,n1,1,TOPTR(side_list)); sprintf(str,"sselem%02d",i+1); PutInt(str,n1,1,TOPTR(elem_list)); } /* Store # sides and # dis. factors per side set (dgriffi) */ PutInt("nsssides",num_side_sets,1,TOPTR(num_sideset_sides)); PutInt("nssdfac",num_side_sets,1,TOPTR(nssdfac)); } /* node sets (section by dgriffi) */ std::vector<int> num_nodeset_nodes(num_node_sets); if (num_node_sets > 0){ if (debug) {logger("Node Sets");} std::vector<int> iscr; std::vector<double> scr; ids.resize(num_node_sets); ex_get_ids(exo_file,EX_NODE_SET, TOPTR(ids)); PutInt( "nsids",num_node_sets, 1,TOPTR(ids)); std::vector<int> num_nodeset_df(num_node_sets); for (int i=0;i<num_node_sets;i++){ ex_get_set_param(exo_file,EX_NODE_SET,ids[i],&n1,&n2); iscr.resize(n1); ex_get_node_set(exo_file,ids[i],TOPTR(iscr)); /* nodes list */ sprintf(str,"nsnod%02d",i+1); PutInt(str,n1,1,TOPTR(iscr)); { /* distribution-factors list */ scr.resize(n2); ex_get_node_set_dist_fact(exo_file,ids[i],TOPTR(scr)); sprintf(str,"nsfac%02d",i+1); PutDbl(str,n2,1,TOPTR(scr)); } num_nodeset_nodes[i]=n1; num_nodeset_df[i]=n2; } /* Store # nodes and # dis. factors per node set */ PutInt("nnsnodes",num_node_sets,1,TOPTR(num_nodeset_nodes)); PutInt("nnsdfac",num_node_sets,1,TOPTR(num_nodeset_df)); } /* element blocks */ if (debug) {logger("Element Blocks");} std::vector<int> num_elem_in_block(num_blocks); { ids.resize(num_blocks); std::vector<int> iscr; ex_get_ids(exo_file,EX_ELEM_BLOCK,TOPTR(ids)); PutInt( "blkids",num_blocks, 1,TOPTR(ids)); for (int i=0;i<num_blocks;i++) { ex_get_elem_block(exo_file,ids[i],str2[i],&n,&n1,&n2); num_elem_in_block[i]=n; iscr.resize(n*n1); ex_get_conn(exo_file,EX_ELEM_BLOCK,ids[i],TOPTR(iscr), nullptr, nullptr); sprintf(str,"blk%02d",i+1); PutInt(str,n1,n,TOPTR(iscr)); } str[0]='\0'; for (int i=0;i<num_blocks;i++) { strcat(str, str2[i]); strcat(str, "\n"); } PutStr("blknames",str); } /* time values */ if (num_time_steps > 0 ) { if (debug) {logger("Time Steps");} std::vector<double> scr(num_time_steps); ex_get_all_times (exo_file, TOPTR(scr)); PutDbl( "time", num_time_steps, 1, TOPTR(scr)); } /* global variables */ if (num_global_vars > 0 ) { if (debug) {logger("Global Variables");} get_put_names(exo_file, EX_GLOBAL, num_global_vars, "gnames"); std::vector<double> scr(num_time_steps); for (int i=0;i<num_global_vars;i++){ sprintf(str,"gvar%02d",i+1); ex_get_glob_var_time(exo_file,i+1,1,num_time_steps,TOPTR(scr)); PutDbl(str,num_time_steps,1,TOPTR(scr)); } } /* nodal variables */ if (num_nodal_vars > 0 ) { if (debug) {logger("Nodal Variables");} if (debug) {logger("\tNames");} get_put_names(exo_file, EX_NODAL, num_nodal_vars, "nnames"); std::vector<double> scr(num_nodes*num_time_steps); for (int i=0; i<num_nodal_vars; i++){ sprintf(str,"nvar%02d",i+1); if (debug) {logger("\tReading");} for (int j=0; j<num_time_steps; j++) { ex_get_nodal_var(exo_file,j+1,i+1,num_nodes, &scr[num_nodes*j]); } if (debug) {logger("\tWriting");} PutDbl(str,num_nodes,num_time_steps,TOPTR(scr)); } } /* element variables */ if (num_element_vars > 0 ) { if (debug) {logger("Element Variables");} get_put_names(exo_file, EX_ELEM_BLOCK, num_element_vars, "enames"); get_put_vars(exo_file, EX_ELEM_BLOCK, num_blocks, num_element_vars, num_time_steps, num_elem_in_block, "evar%02d"); } /* nodeset variables */ if (num_nodeset_vars > 0 ) { if (debug) {logger("Nodeset Variables");} get_put_names(exo_file, EX_NODE_SET, num_nodeset_vars, "nsnames"); get_put_vars(exo_file, EX_NODE_SET, num_node_sets, num_nodeset_vars, num_time_steps, num_nodeset_nodes, "nsvar%02d"); } /* sideset variables */ if (num_sideset_vars > 0 ) { if (debug) {logger("Sideset Variables");} get_put_names(exo_file, EX_SIDE_SET, num_sideset_vars, "ssnames"); get_put_vars(exo_file, EX_SIDE_SET, num_side_sets, num_sideset_vars, num_time_steps, num_sideset_sides, "ssvar%02d"); } /* node and element number maps */ if (debug) {logger("Node and Element Number Maps");} ex_opts(0); /* turn off error reporting. It is not an error to have no map*/ ids.resize(num_nodes); err = ex_get_node_num_map(exo_file,TOPTR(ids)); if ( err==0 ){ PutInt("node_num_map",num_nodes,1,TOPTR(ids)); } ids.resize(num_elements); err = ex_get_elem_num_map(exo_file,TOPTR(ids)); if ( err==0 ){ PutInt("elem_num_map",num_elements,1,TOPTR(ids)); } if (debug) {logger("Closing file");} ex_close(exo_file); if ( textfile ) fclose(m_file); else Mat_Close(mat_file); std::cout << "done...\n"; free(filename); free(line); delete_exodus_names(str2, nstr2); /* exit status */ add_to_log("exo2mat", 0); return(0); }