static np::ndarray bnread( const std::string & name ) { np::ndarray r(np::empty(make_tuple(0), np::dtype::get_builtin<unsigned char>())); mat_t * mat = Mat_Open(name.c_str(),MAT_ACC_RDONLY); if(mat) { matvar_t * gt = Mat_VarRead( mat, (char*)"groundTruth" ); if(!gt) return r; int nSeg = gt->dims[1]; if(!nSeg) return r; for( int s = 0; s < nSeg; s++ ) { matvar_t * cl = Mat_VarGetCell(gt, s); matvar_t * bnd = Mat_VarGetStructField( cl, (void*)"Boundaries", MAT_BY_NAME, 0 ); int W = bnd->dims[1], H = bnd->dims[0]; if( bnd->data_type != MAT_T_UINT8 ) printf("Unexpected boundary type! Continuing in denial and assuming uint8_t\n"); if( r.shape(0) <= 0 ) r = np::empty(make_tuple(nSeg,H,W), np::dtype::get_builtin<unsigned char>()); assert( r.shape(1) == H && r.shape(2) == W ); const unsigned char * pdata = static_cast<const unsigned char*>(bnd->data); unsigned char * pr = reinterpret_cast<unsigned char*>(r.get_data()+s*W*H); for( int j=0; j<H; j++ ) for( int i=0; i<W; i++ ) pr[j*W+i] = pdata[i*H+j]; } Mat_VarFree( gt ); Mat_Close(mat); } return r; }
template <> bool DataOutputNode<lbfloat>::mat_write(std::string file_path, std::string var_name) { //Copy data to buffer lbfloat* buf = nullptr; size_t buf_size; contract(buf,buf_size,false); std::cout << "Output matrix will be [" << _n_samples << "] x [" << _n_channels << "]." << std::endl; //setup the output mat_t *mat; matvar_t *matvar; size_t dims[2] = {_n_samples,_n_channels}; mat = Mat_Open(file_path.c_str(),MAT_ACC_RDWR); if(mat) { //output matrix matvar = Mat_VarCreate(var_name.c_str(),MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims,buf,0); Mat_VarWrite(mat, matvar, MAT_COMPRESSION_NONE); Mat_Close(mat); Mat_VarFree(matvar); std::cout << "Output data to " << var_name << " variable in file " << file_path << "!" << std::endl; delete [] buf; return true; } std::cerr << "Couldn't output to file." << std::endl; delete [] buf; return false; }
void readHeightAndTopSurfaceFromMATLABFile(const char* filename, CpuPtr_2D& H, CpuPtr_2D& top_surface, int& nx, int& ny){ mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if ( NULL == matfp ) { fprintf(stderr,"Error opening MAT file"); } matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); nx = matvar->dims[0]; ny = matvar->dims[1]; int size = nx*ny; H = CpuPtr_2D(nx, ny, 0, true); memcpy(H.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); top_surface = CpuPtr_2D(nx, ny, 0, true); memcpy(top_surface.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; }
static std::tuple< std::vector<RMatrixXs>, std::vector<RMatrixXb> > readMat( const std::string & name ) { std::vector<RMatrixXs> seg; std::vector<RMatriXb> bnd; mat_t * mat = Mat_Open(name.c_str(),MAT_ACC_RDONLY); if(mat) { matvar_t * gt = Mat_VarRead( mat, (char*)"groundTruth" ); if(!gt) return std::make_tuple(seg,bnd); int nSeg = gt->dims[1]; if(!nSeg) return std::make_tuple(seg,bnd); for( int s = 0; s < nSeg; s++ ) { const char * names[2] = {"Segmentation","Boundaries"}; const int types[2] = {MAT_T_UINT16,MAT_T_UINT8}; for( int it=0; it<2; it++ ) { matvar_t * cl = Mat_VarGetCell(gt, s); matvar_t * arr = Mat_VarGetStructField( cl, (void*)names[it], MAT_BY_NAME, 0 ); int W = arr->dims[1], H = arr->dims[0]; if( arr->data_type != types[it] ) printf("Unexpected %s type! Continuing in denial ...\n",names[it]); if(it==0) seg.push_back( MatrixXus::Map((const uint16_t*)arr->data,H,W)-1 ); else bnd.push_back( RMatrixXb::Map((const bool*)arr->data,H,W) ); } } Mat_VarFree( gt ); Mat_Close(mat); } return std::make_tuple(seg,bnd); }
/** \brief save Array-struct as MATLAB .mat file. Currently, the function converts all arrays to double-arrays. Should be easy to implement for arbitrary types if needed. \param a the Array \param varname MATLAB-name of the array \param file the filename \param append if TRUE, the function tries to open() the file, else it is overwritten \return error code */ int write_array_matlab( const Array *a, const char *varname, const char *file, bool append ){ mat_t *mfile; matvar_t *marr=NULL; int i; if( append ){ if( !(mfile=Mat_Open( file, MAT_ACC_RDWR )) ){ errprintf("Could not open '%s', creating new file\n", file); } } if( !mfile ){ if( !(mfile=Mat_Create( file, NULL )) ){ errprintf("Could not open '%s' for writing\n", file); return -1; } } int ndim = MAX(2, a->ndim); int *size = (int*)malloc( ndim*sizeof(int)); if( a->ndim==1 ){ size[0]=1; size[1]=a->size[0]; } else { memcpy( size, a->size, ndim*sizeof(int)); } dprintf("Writing to file '%s' variable '%s', ndim=%i\n", file, varname, ndim); /* convert to column major for MATLAB */ Array *b=array_convert_rowcolmajor( (Array*)a, TRUE ); dprintf("Up-cast, b->ndim=%i, b->size=%p, b->size[0]=%i\n", b->ndim, b->size, b->size[0]); /* up-cast to DOUBLE - copy of b */ Array *c=array_new( DOUBLE, b->ndim, b->size ); dprintf("casting\n"); for( i=0; i<array_NUMEL(b); i++ ){ array_dtype_to_double( array_INDEXMEM1(c,i), array_INDEXMEM1(b,i), b->dtype ); } array_free( b ); dprintf("Creating MATLAB-rep\n"); marr = Mat_VarCreate( varname, MAT_C_DOUBLE, MAT_T_DOUBLE, ndim, size, c->data, MEM_CONSERVE /* Array remains owner */ ); dprintf("mfile=%p, marr=%p, rank=%i,\n", mfile, marr, marr->rank ); int succ=Mat_VarWrite( mfile, marr, 0 ); dprintf("done writing with succ=%i\n", succ); Mat_Close( mfile ); Mat_VarFree( marr ); array_free( c ); free( size ); return 0; }
// Recommended constructor MatFileIO::MatFileIO(std::string _filename, const mat_acc mode) { mat = Mat_Open(_filename.c_str(),mode); if (mat == NULL && mode == MAT_ACC_RDONLY) { fthrow(Exception, "MatFileIO::MatFileIO(const char * _filename, int mode): mat-file does not exist"); } }
static int ismat( const char *filename ) { mat_t *mat; if( !(mat = Mat_Open( filename, MAT_ACC_RDONLY )) ) return( 0 ); Mat_Close( mat ); return( 1 ); }
int vips__mat_ismat( const char *filename ) { mat_t *mat; vips_error_freeze(); mat = Mat_Open( filename, MAT_ACC_RDONLY ); Mat_Close( mat ); vips_error_thaw(); return( mat != NULL ); }
bool annoRead(std::string annoName, BOWImg &dst) { mat_t *matfp = Mat_Open(annoName.c_str(),MAT_ACC_RDONLY); if(matfp == NULL) { std::cerr<<"Cannot open file '"<<annoName<<"'."<<std::endl; return false; } char varName[] = "box_coord"; readNumber<int>(matfp,varName,dst.box); //readNumber<double>(matfp,"obj_contour",dst.objContour); Mat_Close(matfp); return true; }
TData read_data() { const char * fileName = "../data/mnist_uint8.mat"; TData res; mat_t *mat = nullptr; scope_guard _l([&mat, fileName](){ mat = Mat_Open(fileName, MAT_ACC_RDONLY); }, [&mat](){Mat_Close(mat);}); if(!mat){ std::cout <<"cannot open "<<fileName<<std::endl; return res; } matvar_t *var = 0; int read_items = 0; while((var = Mat_VarReadNextInfo(mat)) != nullptr){ if(strcmp(var->name, "train_x") == 0) { res.train_x = read_matrix_in_mat(mat, var->name); read_items ++ ; } else if(strcmp(var->name, "train_y") == 0) { res.train_y = read_matrix_in_mat(mat, var->name); read_items ++; } else if(strcmp(var->name, "test_x") == 0) { res.test_x = read_matrix_in_mat(mat, var->name); read_items ++; } else if(strcmp(var->name, "test_y" ) == 0) { res.test_y = read_matrix_in_mat(mat, var->name); read_items ++; } else{ //nothing here, just for fun... } Mat_VarFree(var); } if(read_items != 4) { std::cout<<"ooooooops, cannot read "<< fileName<<std::endl; } return res; }
static Read * read_new( const char *filename, VipsImage *out ) { Read *read; if( !(read = VIPS_NEW( NULL, Read )) ) return( NULL ); read->filename = vips_strdup( NULL, filename ); read->out = out; read->mat = NULL; read->var = NULL; if( !(read->mat = Mat_Open( filename, MAT_ACC_RDONLY )) ) { vips_error( "mat2vips", _( "unable to open \"%s\"" ), filename ); read_destroy( read ); return( NULL ); } for(;;) { if( !(read->var = Mat_VarReadNextInfo( read->mat )) ) { vips_error( "mat2vips", _( "no matrix variables in \"%s\"" ), filename ); read_destroy( read ); return( NULL ); } #ifdef DEBUG printf( "mat2vips: seen:\n" ); printf( "var->name == %s\n", read->var->name ); printf( "var->class_type == %d\n", read->var->class_type ); printf( "var->rank == %d\n", read->var->rank ); #endif /*DEBUG*/ /* Vector to colour image is OK for us. */ if( read->var->rank >= 1 && read->var->rank <= 3 ) break; VIPS_FREEF( Mat_VarFree, read->var ); } return( read ); }
template <> bool DataOutputNode<lbcomplex>::mat_write(std::string file_path, std::string var_name) { //Copy data to buffer lbcomplex* buf = nullptr; size_t buf_size; contract(buf,buf_size,false); std::cout << "Output matrix will be [" << _n_samples << "] x [" << _n_channels << "]." << std::endl; //setup the output mat_t *mat; matvar_t *matvar; mat_complex_split_t data; data.Re = malloc(buf_size*sizeof(lbfloat)); data.Im = malloc(buf_size*sizeof(lbfloat)); for(size_t ii=0; ii<buf_size; ++ii) { reinterpret_cast<lbfloat*>(data.Re)[ii] = std::real(buf[ii]); reinterpret_cast<lbfloat*>(data.Im)[ii] = std::imag(buf[ii]); } size_t dims[2] = {_n_samples,_n_channels}; mat = Mat_Open(file_path.c_str(),MAT_ACC_RDWR); if(mat) { //output matrix matvar = Mat_VarCreate(var_name.c_str(),MAT_C_DOUBLE,MAT_T_DOUBLE,2,dims,&data,MAT_F_COMPLEX); Mat_VarWrite(mat, matvar, MAT_COMPRESSION_NONE); Mat_Close(mat); Mat_VarFree(matvar); std::cout << "Output data to " << var_name << " variable in file " << file_path << "!" << std::endl; delete [] buf; return true; } std::cerr << "Couldn't output to file." << std::endl; delete [] buf; return false; }
void readPermFromMATLABFile(const char* filename, CpuPtr_3D& perm3D){ mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if ( NULL == matfp ) { fprintf(stderr,"Error opening MAT file"); } matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); int nx = matvar->dims[0]; int ny = matvar->dims[1]; int nz = matvar->dims[2]; nz = 20; int size = nx*ny*nz; perm3D = CpuPtr_3D(nx, ny, nz, 0, true); memcpy(perm3D.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; }
double *read_mat(const char *filename, const char *varname, size_t *dims) { mat_t *mat; matvar_t *var; double *array; size_t nbytes; mat = Mat_Open(filename, MAT_ACC_RDONLY); if (!mat) { fprintf(stderr, "Error opening MAT file \"%s\"!\n", filename); exit(EXIT_FAILURE); } var = Mat_VarRead(mat, varname); if (!var) { fprintf(stderr, "Error reading the variable %s.\n", varname); Mat_Close(mat); exit(EXIT_FAILURE); } if (var->data_type != MAT_T_DOUBLE || var->class_type != MAT_C_DOUBLE || var->rank != 2) { fprintf(stderr, "%s is not a double-precision matrix.\n", varname); Mat_VarFree(var); Mat_Close(mat); exit(EXIT_FAILURE); } nbytes = var->dims[0] * var->dims[1] * sizeof(double); array = (double *)malloc(nbytes); memcpy(array, var->data, nbytes); memcpy(dims, var->dims, 2 * sizeof(size_t)); Mat_VarFree(var); Mat_Close(mat); return array; }
/******************************************************************************* 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; }
// load a .mat matlab matrix // will load the first matrix (sparse or dense) in the file // returns 0 on success static int read_mat(char const *const filename, matrix_t *const A) { #ifndef HAVE_MATIO return 1; #else const int LOCAL_DEBUG = 0; mat_t* matfp; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if(matfp == NULL) return 1; // failed to open file matvar_t* t; int more_data = 1; while (more_data) { t = Mat_VarReadNextInfo(matfp); if(t == NULL) { return 2; // no suitable variable found } // TODO decide if this is the one: if(t-> if(1) { more_data = 0; } else { // keep going Mat_VarFree(t); t = NULL; } } { // load the selected variable, including data Mat_Rewind(matfp); matvar_t* tt = Mat_VarRead(matfp, t->name); Mat_VarFree(t); t = tt; if(LOCAL_DEBUG) Mat_VarPrint(tt, 1); } // debug info if(LOCAL_DEBUG && t->name != NULL) printf("%s: loaded variable %s\n", filename, t->name); // checks and data handling int ret = 0; if(t->rank > 2 || t->rank <= 0) { // number of dimensions ret = 2; } else if(t->data_type != MAT_T_DOUBLE) { if(LOCAL_DEBUG) printf("data_type=%d\n",t->data_type); ret = 3; } else if(t->isComplex) { ret = 10; // TODO can't handle complex matrices yet } else if(t->isLogical) { ret = 11; // TODO can't handle logicals yet } else { if(t->rank == 1) { A->m = t->dims[0]; // rows A->n = 1; // cols } else { A->m = t->dims[0]; // rows A->n = t->dims[1]; // cols } A->sym = SM_UNSYMMETRIC; //if(t->data_type == MAT_T_DOUBLE) { A->data_type = REAL_DOUBLE; //} // TODO complex, single precision, various sized integers if(t->class_type == MAT_C_SPARSE) { // t.data = sparse_t in CSC format // Note that Matlab will save('-v4'...) a sparse matrix // to version 4 format without complaint but it appears // to be gibberish as far as MatIO is concerned sparse_t* st = t->data; A->nz = st->ndata; //st->nzmax has the actual size of the allocated st->data A->format = SM_CSC; // transfer the data pointer into our strucut // TODO check for negative values in ir/jc before throwing away their signs A->ii = (unsigned int*) st->ir; st->ir = NULL; A->jj = (unsigned int*) st->jc; st->jc = NULL; A->dd = st->data; st->data = NULL; } else if(t->class_type == MAT_C_DOUBLE) { A->nz = A->m * A->n; A->format = DCOL; // transfer the data pointer into our struct A->dd = t->data; t->data = NULL; } else { ret = 4; // unknown class of data structure } } // DEBUG if(LOCAL_DEBUG && validate_matrix(A) != 0) { ret = 50; fprintf(stderr, "problem loading .mat matrix file\n"); printf_matrix(" ", A); } // sanity checks // t.dims[] is don't-care // t.isGlobal is don't-care Mat_Close(matfp); Mat_VarFree(t); return ret; // success? #endif }
void readFormationDataFromMATLABFile(const char* filename, CpuPtr_2D& H, CpuPtr_2D& top_surface, CpuPtr_2D& h, CpuPtr_2D& z_normal, CpuPtr_3D& perm3D, float* poro3D, CpuPtr_2D& pv, CpuPtr_2D& north_flux, CpuPtr_2D& east_flux, CpuPtr_2D& north_grav, CpuPtr_2D& east_grav, float& dz, int&nz, int& nx, int& ny){ mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if ( NULL == matfp ) { fprintf(stderr,"Error opening MAT file"); } matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); nz = *(float*)matvar->data; Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); nx = matvar->dims[0]; ny = matvar->dims[1]; int size = nx*ny; H = CpuPtr_2D(nx, ny, 0, true); memcpy(H.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); h = CpuPtr_2D(nx, ny, 0, true); memcpy(h.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); top_surface = CpuPtr_2D(nx, ny, 0, true); memcpy(top_surface.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); pv = CpuPtr_2D(nx, ny, 0, true); memcpy(pv.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); east_flux = CpuPtr_2D(nx, ny, 1, true); memcpy(east_flux.getPtr(), matvar->data,sizeof(float)*(nx+1)*(ny+1)); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); north_flux = CpuPtr_2D(nx, ny, 1, true); memcpy(north_flux.getPtr(), matvar->data,sizeof(float)*(nx+1)*(ny+1)); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); z_normal = CpuPtr_2D(nx, ny, 0, true); memcpy(z_normal.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; //perm3D = CpuPtr_3D(nx, ny, nz, 0, true); matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); nx = matvar->dims[0]; ny = matvar->dims[1]; nz = matvar->dims[2]; printf("3D dims: nx %i ny %i nz %i\n", nx, ny, nz); //memcpy(perm3D.getPtr(), matvar->data,sizeof(float)*nx*ny*nz); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); //poro3D = CpuPtr_3D(nx, ny, nz, 0, true); memcpy(poro3D, matvar->data,sizeof(float)*nx*ny*nz); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); dz = *(float*)matvar->data; Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); north_grav = CpuPtr_2D(nx, ny, 0, true); memcpy(north_grav.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; matvar = Mat_VarReadNextInfo(matfp); Mat_VarReadDataAll(matfp, matvar); printf("Variable: %s\n",matvar->name); east_grav = CpuPtr_2D(nx, ny, 0, true); memcpy(east_grav.getPtr(), matvar->data,sizeof(float)*size); Mat_VarFree(matvar); matvar = NULL; }
void CSMatrix<Scalar>::import_from_file(const char *filename, const char *var_name, MatrixExportFormat fmt, bool invert_storage) { this->free(); switch (fmt) { case EXPORT_FORMAT_MATRIX_MARKET: throw Exceptions::MethodNotOverridenException("CSMatrix<Scalar>::import_from_file - Matrix Market"); break; case EXPORT_FORMAT_MATLAB_MATIO: { #ifdef WITH_MATIO mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if (!matfp) throw Exceptions::IOException(Exceptions::IOException::Read, filename); matvar = Mat_VarRead(matfp, var_name); if (matvar) { mat_sparse_t *sparse = (mat_sparse_t *)matvar->data; this->nnz = sparse->nir; this->Ax = malloc_with_check<CSMatrix<Scalar>, Scalar>(this->nnz, this); this->Ai = malloc_with_check<CSMatrix<Scalar>, int>(this->nnz, this); this->size = sparse->njc; this->Ap = malloc_with_check<CSMatrix<Scalar>, int>(this->size + 1, this); void* data = nullptr; if (Hermes::Helpers::TypeIsReal<Scalar>::value) data = sparse->data; else { std::complex<double>* complex_data = malloc_with_check<CSMatrix<Scalar>, std::complex<double> >(this->nnz, this); double* real_array = (double*)((mat_complex_split_t*)sparse->data)->Re; double* imag_array = (double*)((mat_complex_split_t*)sparse->data)->Im; for (int i = 0; i < this->nnz; i++) complex_data[i] = std::complex<double>(real_array[i], imag_array[i]); data = (void*)complex_data; } memcpy(this->Ax, data, this->nnz * sizeof(Scalar)); if (!Hermes::Helpers::TypeIsReal<Scalar>::value) free_with_check(data); memcpy(this->Ap, sparse->jc, this->size * sizeof(int)); this->Ap[this->size] = this->nnz; memcpy(this->Ai, sparse->ir, this->nnz * sizeof(int)); if (invert_storage) this->switch_orientation(); } Mat_Close(matfp); if (!matvar) throw Exceptions::IOException(Exceptions::IOException::Read, filename); #else throw Exceptions::Exception("MATIO not included."); #endif } break; case EXPORT_FORMAT_PLAIN_ASCII: throw Exceptions::MethodNotOverridenException("CSMatrix<Scalar>::import_from_file - Simple format"); #ifdef WITH_BSON case EXPORT_FORMAT_BSON: { FILE *fpr; fpr = fopen(filename, "rb"); // file size: fseek(fpr, 0, SEEK_END); int size = ftell(fpr); rewind(fpr); // allocate memory to contain the whole file: char *datar = malloc_with_check<char>(size); fread(datar, size, 1, fpr); fclose(fpr); bson br; bson_init_finished_data(&br, datar, 0); bson_iterator it; bson sub; bson_find(&it, &br, "size"); this->size = bson_iterator_int(&it); bson_find(&it, &br, "nnz"); this->nnz = bson_iterator_int(&it); this->Ap = malloc_with_check<CSMatrix<Scalar>, int>(this->size + 1, this); this->Ai = malloc_with_check<CSMatrix<Scalar>, int>(nnz, this); this->Ax = malloc_with_check<CSMatrix<Scalar>, Scalar>(nnz, this); // coeffs bson_iterator it_coeffs; bson_find(&it_coeffs, &br, "Ap"); bson_iterator_subobject_init(&it_coeffs, &sub, 0); bson_iterator_init(&it, &sub); int index_coeff = 0; while (bson_iterator_next(&it)) this->Ap[index_coeff++] = bson_iterator_int(&it); this->Ap[this->size] = this->nnz; bson_find(&it_coeffs, &br, "Ai"); bson_iterator_subobject_init(&it_coeffs, &sub, 0); bson_iterator_init(&it, &sub); index_coeff = 0; while (bson_iterator_next(&it)) this->Ai[index_coeff++] = bson_iterator_int(&it); bson_find(&it_coeffs, &br, "Ax"); bson_iterator_subobject_init(&it_coeffs, &sub, 0); bson_iterator_init(&it, &sub); index_coeff = 0; while (bson_iterator_next(&it)) this->Ax[index_coeff++] = bson_iterator_double(&it); if (!Hermes::Helpers::TypeIsReal<Scalar>::value) { bson_find(&it_coeffs, &br, "Ax-imag"); bson_iterator_subobject_init(&it_coeffs, &sub, 0); bson_iterator_init(&it, &sub); index_coeff = 0; while (bson_iterator_next(&it)) ((std::complex<double>)this->Ax[index_coeff++]).imag(bson_iterator_double(&it)); } if (invert_storage) this->switch_orientation(); bson_destroy(&br); free_with_check(datar); } #endif break; } }
void SimpleVector<Scalar>::import_from_file(const char *filename, const char *var_name, MatrixExportFormat fmt) { switch (fmt) { case EXPORT_FORMAT_PLAIN_ASCII: { std::vector<Scalar> data; std::ifstream input (filename); if(input.bad()) throw Exceptions::IOException(Exceptions::IOException::Read, filename); std::string lineData; while(getline(input, lineData)) { Scalar d; std::stringstream lineStream(lineData); lineStream >> d; data.push_back(d); } this->alloc(data.size()); memcpy(this->v, &data[0], sizeof(Scalar)*data.size()); } break; case EXPORT_FORMAT_MATLAB_MATIO: #ifdef WITH_MATIO mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename,MAT_ACC_RDONLY); if (!matfp ) { throw Exceptions::IOException(Exceptions::IOException::Read, filename); return; } matvar = Mat_VarRead(matfp, var_name); if (matvar) { this->alloc(matvar->dims[0]); if(Hermes::Helpers::TypeIsReal<Scalar>::value) memcpy(this->v, matvar->data, sizeof(Scalar)*this->size); else { std::complex<double>* complex_data = new std::complex<double>[this->size]; double* real_array = (double*)((mat_complex_split_t*)matvar->data)->Re; double* imag_array = (double*)((mat_complex_split_t*)matvar->data)->Im; for(int i = 0; i < this->size; i++) complex_data[i] = std::complex<double>(real_array[i], imag_array[i]); memcpy(this->v, complex_data, sizeof(Scalar)*this->size); delete [] complex_data; } } Mat_Close(matfp); if(!matvar) throw Exceptions::IOException(Exceptions::IOException::Read, filename); #else throw Exceptions::Exception("MATIO not included."); #endif break; case EXPORT_FORMAT_MATRIX_MARKET: throw Hermes::Exceptions::MethodNotImplementedException("SimpleVector<Scalar>::import_from_file - Matrix Market"); } }
void SimpleVector<Scalar>::import_from_file(const char *filename, const char *var_name, MatrixExportFormat fmt) { switch (fmt) { case EXPORT_FORMAT_PLAIN_ASCII: { std::vector<Scalar> data; std::ifstream input(filename); if (input.bad()) throw Exceptions::IOException(Exceptions::IOException::Read, filename); std::string lineData; while (getline(input, lineData)) { Scalar d; std::stringstream lineStream(lineData); lineStream >> d; data.push_back(d); } this->alloc(data.size()); memcpy(this->v, &data[0], sizeof(Scalar)*data.size()); } break; case EXPORT_FORMAT_MATLAB_MATIO: #ifdef WITH_MATIO mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename, MAT_ACC_RDONLY); if (!matfp) { throw Exceptions::IOException(Exceptions::IOException::Read, filename); return; } matvar = Mat_VarRead(matfp, var_name); if (matvar) { this->alloc(matvar->dims[0]); if (Hermes::Helpers::TypeIsReal<Scalar>::value) memcpy(this->v, matvar->data, sizeof(Scalar)*this->size); else { std::complex<double>* complex_data = malloc_with_check<SimpleVector<Scalar>, std::complex<double> >(this->size, this); double* real_array = (double*)((mat_complex_split_t*)matvar->data)->Re; double* imag_array = (double*)((mat_complex_split_t*)matvar->data)->Im; for (int i = 0; i < this->size; i++) complex_data[i] = std::complex<double>(real_array[i], imag_array[i]); memcpy(this->v, complex_data, sizeof(Scalar)*this->size); free_with_check(complex_data); } } Mat_Close(matfp); if (!matvar) throw Exceptions::IOException(Exceptions::IOException::Read, filename); #else throw Exceptions::Exception("MATIO not included."); #endif break; case EXPORT_FORMAT_MATRIX_MARKET: throw Hermes::Exceptions::MethodNotImplementedException("SimpleVector<Scalar>::import_from_file - Matrix Market"); break; #ifdef WITH_BSON case EXPORT_FORMAT_BSON: { FILE *fpr; fpr = fopen(filename, "rb"); // file size: fseek(fpr, 0, SEEK_END); int size = ftell(fpr); rewind(fpr); // allocate memory to contain the whole file: char *datar = malloc_with_check<char>(size); fread(datar, size, 1, fpr); fclose(fpr); bson br; bson_init_finished_data(&br, datar, 0); bson_iterator it; bson sub; bson_find(&it, &br, "size"); this->size = bson_iterator_int(&it); this->v = malloc_with_check<SimpleVector<Scalar>, Scalar>(this->size, this); bson_iterator it_coeffs; bson_find(&it_coeffs, &br, "v"); bson_iterator_subobject_init(&it_coeffs, &sub, 0); bson_iterator_init(&it, &sub); int index_coeff = 0; while (bson_iterator_next(&it)) this->v[index_coeff++] = bson_iterator_double(&it); if (!Hermes::Helpers::TypeIsReal<Scalar>::value) { bson_find(&it_coeffs, &br, "v-imag"); bson_iterator_subobject_init(&it_coeffs, &sub, 0); bson_iterator_init(&it, &sub); index_coeff = 0; while (bson_iterator_next(&it)) ((std::complex<double>)this->v[index_coeff++]).imag(bson_iterator_double(&it)); } bson_destroy(&br); free_with_check(datar); } break; #endif } }
int main (int argc, char *argv[]){ char **str2,*line,*curr; const char* ext=".exo"; int i,j,k,n,n1,cpu_word_size,io_word_size,exo_file, num_axes,num_nodes,num_elements,num_blocks, num_side_sets,num_node_sets,num_time_steps, num_global_vars, num_nodal_vars,num_element_vars,*ids,*iscr, *nsssides,*nssdfac,*elem_list,*side_list, *nnsnodes,*nnsdfac,*node_list; double *scr,*x,*y,*z, *escr; char * blknames = NULL; int *num_elem_in_block = NULL; /* QA Info */ printf("%s: %s, %s\n", qainfo[0], qainfo[2], qainfo[1]); /* usage message*/ if(argc != 2){ printf("%s matlab_file_name.\n",argv[0]); printf(" the matlab_file_name is required\n"); printf("%d", argc); exit(1); } /*open input file*/ mat_file = Mat_Open(argv[1], MAT_ACC_RDONLY); if (mat_file == NULL) { printf("Error opening matlab file %s\n", argv[1]); return(1); } /*open output file*/ cpu_word_size=sizeof(double); io_word_size=sizeof(double); /* QA records */ ext=".exo"; line = (char *) calloc (2049,sizeof(char)); strcpy(line,argv[1]); strtok(line,"."); strcat(line,ext); exo_file = ex_create(line,EX_CLOBBER,&cpu_word_size,&io_word_size); if (exo_file < 0){ printf("error creating %s\n",line); exit(1); } /* print */ fprintf(stderr,"translating %s to %s ... ",argv[1],line); /* read database parameters */ matGetInt("naxes", 1, 1,&num_axes); matGetInt("nnodes", 1, 1,&num_nodes); matGetInt("nelems", 1, 1,&num_elements); matGetInt("nblks", 1, 1,&num_blocks); matGetInt("nnsets", 1, 1,&num_node_sets); matGetInt("nssets", 1, 1,&num_side_sets); matGetInt("nsteps", 1, 1,&num_time_steps); matGetInt("ngvars", 1, 1,&num_global_vars); matGetInt("nnvars", 1, 1,&num_nodal_vars); matGetInt("nevars", 1, 1,&num_element_vars); /*export parameters */ ex_put_init(exo_file,line, num_axes,num_nodes,num_elements,num_blocks, num_node_sets,num_side_sets); free(line); if ( num_global_vars > 0 ){ ex_put_variable_param(exo_file,EX_GLOBAL,num_global_vars); } if ( num_nodal_vars > 0 ){ ex_put_variable_param(exo_file,EX_NODAL,num_nodal_vars); } if ( num_element_vars > 0 ){ ex_put_variable_param(exo_file,EX_ELEM_BLOCK,num_element_vars); } /* 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; matGetDbl("x0", num_nodes, 1, x); matGetDbl("y0", num_nodes, 1, y); if (num_axes == 3) matGetDbl("z0", num_nodes,1,z); ex_put_coord(exo_file,x,y,z); free(x); free(y); if (num_axes == 3){ free(z); } /* side sets (section by dgriffi) */ if(num_side_sets > 0){ /* ssids */ ids = (int *) calloc(num_side_sets,sizeof(int)); matGetInt("ssids",num_side_sets, 1,ids); /* nsssides */ nsssides = (int *) calloc(num_side_sets,sizeof(int)); matGetInt("nsssides",num_side_sets,1,nsssides); /* nssdfac */ nssdfac = (int *) calloc(num_side_sets,sizeof(int)); matGetInt("nssdfac",num_side_sets,1,nssdfac); for(i=0;i<num_side_sets;i++){ char name[32]; ex_put_set_param(exo_file,EX_SIDE_SET,ids[i],nsssides[i],nssdfac[i]); elem_list = (int *) calloc(nsssides[i],sizeof(int)); side_list = (int *) calloc(nsssides[i],sizeof(int)); escr = (double *) calloc(nssdfac[i],sizeof(double)); sprintf(name,"sselem%02d",i+1); matGetInt(name,nsssides[i],1,elem_list); sprintf(name,"ssside%02d",i+1); matGetInt(name,nsssides[i],1,side_list); ex_put_set(exo_file,EX_SIDE_SET,ids[i],elem_list,side_list); free(elem_list); free(side_list); sprintf(name,"ssfac%02d",i+1); matGetDbl(name,nssdfac[i],1,escr); ex_put_set_dist_fact(exo_file,EX_SIDE_SET,ids[i],escr); free(escr); } free(nsssides); free(nssdfac); free(ids); } /* node sets (section by dgriffi) */ if(num_node_sets > 0){ /* nsids */ ids = (int *) calloc(num_node_sets,sizeof(int)); matGetInt("nsids",num_node_sets, 1,ids); /* nnsnodes */ nnsnodes = (int *) calloc(num_node_sets,sizeof(int)); matGetInt("nnsnodes",num_node_sets,1,nnsnodes); /* nnsdfac */ nnsdfac = (int *) calloc(num_node_sets,sizeof(int)); matGetInt("nnsdfac",num_node_sets,1,nnsdfac); for(i=0;i<num_node_sets;i++){ char name[32]; ex_put_set_param(exo_file,EX_NODE_SET,ids[i],nnsnodes[i],nnsdfac[i]); node_list = (int *) calloc(nnsnodes[i],sizeof(int)); escr = (double *) calloc(nnsdfac[i],sizeof(double)); sprintf(name,"nsnod%02d",i+1); matGetInt(name,nnsnodes[i],1,node_list); ex_put_set(exo_file,EX_NODE_SET,ids[i],node_list,NULL); free(node_list); sprintf(name,"nsfac%02d",i+1); matGetDbl(name,nnsdfac[i],1,escr); ex_put_set_dist_fact(exo_file,EX_NODE_SET,ids[i],escr); free(escr); } free(nnsdfac); free(nnsnodes); free(ids); } /* element blocks */ /* get elem block ids */ ids = (int *) calloc(num_blocks,sizeof(int)); matGetInt("blkids",num_blocks,1,ids); /* get elem block types */ blknames = (char *) calloc(num_blocks*(MAX_STR_LENGTH+1),sizeof(char)); matGetStr("blknames",blknames); num_elem_in_block = (int *) calloc(num_blocks,sizeof(int)); curr = blknames; curr = strtok(curr,"\n"); for(i=0;i<num_blocks;i++){ char name[32]; sprintf(name,"blk%02d",i+1); n1 = matArrNRow(name); n = matArrNCol(name); iscr = (int *) calloc(n*n1,sizeof(int)); matGetInt(name,n1,n,iscr); num_elem_in_block[i]=n; ex_put_elem_block(exo_file,ids[i],curr,n,n1,0); ex_put_conn(exo_file,EX_ELEM_BLOCK,ids[i],iscr,NULL,NULL); free(iscr); curr = strtok(NULL, "\n"); } free(blknames); /* time values */ if (num_time_steps > 0 ) { scr = (double *) calloc(num_time_steps,sizeof(double)); matGetDbl( "time", num_time_steps, 1,scr); for (i=0;i<num_time_steps;i++){ ex_put_time(exo_file,i+1,&scr[i]); } free(scr); } /* global variables */ if (num_global_vars > 0 ){ int max_name_length = ex_inquire_int(exo_file, EX_INQ_DB_MAX_USED_NAME_LENGTH); char *str = (char *) calloc(num_global_vars * (max_name_length+1), sizeof(char)); matGetStr("gnames",str); str2 = (char **) calloc(num_global_vars,sizeof(char*)); curr = strtok(str,"\n"); for(i=0;i<num_global_vars;i++){ str2[i]=curr; curr = strtok(NULL,"\n"); } ex_put_variable_names(exo_file, EX_GLOBAL, num_global_vars, str2); free(str); free(str2); { double * global_var_vals; double * temp; global_var_vals = (double *) calloc(num_global_vars*num_time_steps,sizeof(double)); temp = (double *) calloc(num_time_steps,sizeof(double)); for (j=0;j<num_global_vars;j++) { char name[32]; sprintf(name,"gvar%02d",j+1); matGetDbl(name,num_time_steps,1,temp); for (i=0; i < num_time_steps; i++) { global_var_vals[num_global_vars*i+j]=temp[i]; } } for (i=0; i<num_time_steps; i++) { size_t offset = num_global_vars * i; ex_put_var(exo_file,i+1,EX_GLOBAL,1,0,num_global_vars,&global_var_vals[offset]); } free(temp); free(global_var_vals); } } /* nodal variables */ /* section by dtg */ if (num_nodal_vars > 0){ int max_name_length = ex_inquire_int(exo_file, EX_INQ_DB_MAX_USED_NAME_LENGTH); char *str = (char *) calloc(num_nodal_vars * (max_name_length+1), sizeof(char)); matGetStr("nnames",str); str2 = (char **) calloc(num_nodal_vars,sizeof(char*)); curr = strtok(str,"\n"); for(i=0;i<num_nodal_vars;i++){ str2[i]=curr; curr = strtok(NULL,"\n"); } ex_put_variable_names(exo_file, EX_NODAL, num_nodal_vars, str2); free(str); free(str2); { double * nodal_var_vals; for (i=0;i<num_nodal_vars;i++) { char name[32]; nodal_var_vals = (double *) calloc(num_nodes*num_time_steps,sizeof(double)); sprintf(name,"nvar%02d",i+1); matGetDbl(name,num_nodes,num_time_steps,nodal_var_vals); for (j=0;j<num_time_steps;j++) { ex_put_var(exo_file,j+1,EX_NODAL,i+1,num_nodes,1,nodal_var_vals+num_nodes*j); } free(nodal_var_vals); } } } /* elemental variables */ /* section by dtg */ if (num_element_vars > 0){ int max_name_length = ex_inquire_int(exo_file, EX_INQ_DB_MAX_USED_NAME_LENGTH); char *str = (char *) calloc(num_element_vars * (max_name_length+1), sizeof(char)); matGetStr("enames",str); str2 = (char **) calloc(num_element_vars,sizeof(char*)); curr = strtok(str,"\n"); for(i=0;i<num_element_vars;i++){ str2[i]=curr; curr = strtok(NULL,"\n"); } ex_put_variable_names(exo_file, EX_ELEM_BLOCK, num_element_vars, str2); free(str); free(str2); { double * element_var_vals; for (i=0;i<num_element_vars;i++) { char name[32]; element_var_vals = (double *) calloc(num_elements*num_time_steps,sizeof(double)); sprintf(name,"evar%02d",i+1); matGetDbl(name,num_elements,num_time_steps,element_var_vals); n=0; for (j=0;j<num_time_steps;j++) { for (k=0;k<num_blocks;k++) { ex_put_var(exo_file,j+1,EX_ELEM_BLOCK, i+1,ids[k],num_elem_in_block[k],element_var_vals+n); n=n+num_elem_in_block[k]; } } free(element_var_vals); } } } free(ids); /* node and element number maps */ ids = (int *) calloc (num_nodes,sizeof(int)); if ( !matGetInt("node_num_map",num_nodes,1,ids)){ ex_put_node_num_map(exo_file,ids); } free(ids); ids = (int *) calloc (num_elements,sizeof(int)); if ( !matGetInt("elem_num_map",num_elements,1,ids)){ ex_put_elem_num_map(exo_file,ids); } free(ids); free(num_elem_in_block); /* close exo file */ ex_close(exo_file); /* close mat file */ Mat_Close(mat_file); /* */ fprintf(stderr,"done.\n"); /* exit status */ add_to_log("mat2exo", 0); return(0); }
int main (int argc, char *argv[]) { char *prog_name = "matdump"; int i, c, err = EXIT_SUCCESS; mat_t *mat; matvar_t *matvar; int version[3]; Mat_GetLibraryVersion(version, version+1, version+2); if ( MATIO_MAJOR_VERSION != version[0] || MATIO_MINOR_VERSION != version[1] || MATIO_RELEASE_LEVEL != version[2] ) { fprintf(stderr,"matio version in header does not match runtime " "version\n"); return EXIT_FAILURE; } Mat_LogInitFunc(prog_name,default_printf_func); printfunc = print_default; while ((c = getopt_long(argc,argv,optstring,options,NULL)) != EOF) { switch (c) { case 'd': printdata = 1; Mat_VerbMessage(1,"Printing data\n"); break; case 'f': if ( NULL != optarg && !strcmp(optarg,"whos") ) { printfunc = print_whos; break; } Mat_Warning("%s is not a recognized output format. " "Using default\n", optarg); break; case 'h': human_readable = 1; break; case 'v': Mat_SetVerbose(1,0); break; case 'H': Mat_Help(helpstr); exit(EXIT_SUCCESS); case 'V': printf("%s %s\nWritten by Christopher Hulbert\n\n" "Copyright(C) 2006-2013 Christopher C. Hulbert\n", prog_name,MATIO_VERSION_STR); exit(EXIT_SUCCESS); default: printf("%c not a valid option\n", c); break; } } if ( (argc-optind) < 1 ) Mat_Error("Must specify at least one argument"); mat = Mat_Open( argv[optind],MAT_ACC_RDONLY ); if ( NULL == mat ) { Mat_Error("Error opening %s\n", argv[optind]); return EXIT_FAILURE; } optind++; if ( optind < argc ) { /* variables specified on the command line */ for ( i = optind; i < argc; i++ ) { char *next_tok_pos, next_tok = 0; next_tok_pos = get_next_token(argv[i]); if ( next_tok_pos != argv[i] ) { next_tok = *next_tok_pos; *next_tok_pos = '\0'; } matvar = Mat_VarReadInfo(mat,argv[i]); if ( matvar ) { if ( printdata ) { if ( next_tok == '\0' ) { /* No indexing tokens found, so read all of the data */ Mat_VarReadDataAll(mat,matvar); } else { *next_tok_pos = next_tok; read_selected_data(mat,matvar,next_tok_pos); } } (*printfunc)(matvar); Mat_VarFree(matvar); matvar = NULL; } else { Mat_Warning("Couldn't find variable %s in the MAT file", argv[i]); } } /* for ( i = optind; i < argc; i++ ) */ } else { /* print all variables */ if ( printdata ) { while ( (matvar = Mat_VarReadNext(mat)) != NULL ) { (*printfunc)(matvar); Mat_VarFree(matvar); matvar = NULL; } } else { while ( (matvar = Mat_VarReadNextInfo(mat)) != NULL ) { (*printfunc)(matvar); Mat_VarFree(matvar); matvar = NULL; } } } Mat_Close(mat); Mat_LogClose(); return err; }
G_MODULE_EXPORT void save_as(const char *filename, int type) { FILE *fp; unsigned int i, j; double freq, k; mat_t *mat; matvar_t *matvar; int dims[2]; char tmp[20]; GdkPixbuf *pixbuf; GError *err=NULL; GdkColormap *cmap; gint width, height; gboolean ret = true; char *name; gdouble *tmp_data; name = malloc(strlen(filename) + 5); switch(type) { /* Response Codes encoded in glade file */ case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_CANCEL: break; case SAVE_VSA: /* Allow saving data when only in Time Domanin */ if ((gtk_combo_box_get_active(GTK_COMBO_BOX(plot_domain)) != TIME_PLOT) && (gtk_combo_box_get_active(GTK_COMBO_BOX(plot_domain)) != XY_PLOT)) { create_blocking_popup(GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, "Invalid Plot Type", "Please make sure to set the Plot Type to \"Time Domanin\" before saving data."); return; } /* Save as Agilent VSA formatted file */ if (!strncasecmp(&filename[strlen(filename)-4], ".txt", 4)) strcpy(name, filename); else sprintf(name, "%s.txt", filename); fp = fopen(name, "w"); if (!fp) break; fprintf(fp, "InputZoom\tTRUE\n"); fprintf(fp, "InputCenter\t0\n"); fprintf(fp, "InputRange\t1\n"); fprintf(fp, "InputRefImped\t50\n"); fprintf(fp, "XStart\t0\n"); if (!strcmp(adc_scale, "M")) freq = adc_freq * 1000000; else if (!strcmp(adc_scale, "k")) freq = adc_freq * 1000; else { printf("error in writing\n"); break; } fprintf(fp, "XDelta\t%-.17f\n", 1.0/freq); fprintf(fp, "XDomain\t2\n"); fprintf(fp, "XUnit\tSec\n"); fprintf(fp, "YUnit\tV\n"); fprintf(fp, "FreqValidMax\t%e\n", freq / 2); fprintf(fp, "FreqValidMin\t-%e\n", freq / 2); fprintf(fp, "Y\n"); for (j = 0; j < num_samples; j++) { for (i = 0; i < num_active_channels ; i++) { fprintf(fp, "%g", channel_data[i][j]); if (i < (num_active_channels - 1)) fprintf(fp, "\t"); } fprintf(fp, "\n"); } fprintf(fp, "\n"); fclose(fp); break; case SAVE_MAT: /* Allow saving data when only in Time Domanin */ if (gtk_combo_box_get_active(GTK_COMBO_BOX(plot_domain)) != TIME_PLOT) { create_blocking_popup(GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, "Invalid Plot Type", "Please make sure to set the Plot Type to \"Time Domanin\" before saving data."); return; } /* Matlab file * http://na-wiki.csc.kth.se/mediawiki/index.php/MatIO */ if (!strncasecmp(&filename[strlen(filename)-4], ".mat", 4)) strcpy(name, filename); else sprintf(name, "%s.mat", filename); dims[1] = 1; dims[0] = num_samples; mat = Mat_Open(name, MAT_ACC_RDWR); if(mat) { for (i = 0; i < num_active_channels; i++) { sprintf(tmp, "in_voltage%d", i); if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(save_mat_scale))) { matvar = Mat_VarCreate(tmp, MAT_C_SINGLE, MAT_T_SINGLE, 2, dims, channel_data[i], 0); } else { tmp_data = g_new(gdouble, num_samples); if (channels[i].is_signed) k = channels[i].bits_used - 1; else k = channels[i].bits_used; for (j = 0; j < num_samples; j++) { tmp_data[j] = (gdouble)channel_data[i][j] / (pow(2.0, k)); } matvar = Mat_VarCreate(tmp, MAT_C_DOUBLE, MAT_T_DOUBLE, 2, dims, tmp_data, 0); g_free(tmp_data); } if (!matvar) printf("error creating matvar on channel %i\n", i); else { Mat_VarWrite(mat, matvar, 0); Mat_VarFree(matvar); } } Mat_Close(mat); } break; case SAVE_CSV: /* Allow saving data when only in Time Domanin */ if (gtk_combo_box_get_active(GTK_COMBO_BOX(plot_domain)) != TIME_PLOT) { create_blocking_popup(GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, "Invalid Plot Type", "Please make sure to set the Plot Type to \"Time Domanin\" before saving data."); return; } /* save comma seperated valus (csv) */ if (!strncasecmp(&filename[strlen(filename)-4], ".csv", 4)) strcpy(name, filename); else sprintf(name, "%s.csv", filename); fp = fopen(name, "w"); if (!fp) break; for (j = 0; j < num_samples; j++) { for (i = 0; i < num_active_channels ; i++) { fprintf(fp, "%g", channel_data[i][j]); if (i < (num_active_channels - 1)) fprintf(fp, ", "); } fprintf(fp, "\n"); } fprintf(fp, "\n"); fclose(fp); break; case SAVE_PNG: /* save_png */ if (!strncasecmp(&filename[strlen(filename)-4], ".png", 4)) strcpy(name, filename); else sprintf(name, "%s.png", filename); cmap = gdk_window_get_colormap( GDK_DRAWABLE(gtk_widget_get_window(capture_graph))); gdk_drawable_get_size(GDK_DRAWABLE(gtk_widget_get_window(capture_graph)), &width, &height); pixbuf = gdk_pixbuf_get_from_drawable(NULL, GDK_DRAWABLE(gtk_widget_get_window(capture_graph)), cmap, 0, 0, 0, 0, width, height); if (pixbuf) ret = gdk_pixbuf_save(pixbuf, name, "png", &err, NULL); if (!pixbuf || !ret) printf("error creating %s\n", name); break; default: printf("ret : %i\n", ret); } free(name); }
/** \brief read EEG struct from EEGlab (MATLAB) .set-file. This reader uses MatIO to parse EEGlab files and construct a LibEEGTools EEG struct. It was developed with EEGlab version 6.01b. Currently, the EEGlab set must be "epoched", that means that the data must be three-dimensional with channels x n x trials. Continuous data is not yet supported and the reader will fail. The reader currently works only if the storage is in single .set file (as opposed to a pair of .set and .dat file). \param file eeglab .set file \return the EEG struct */ EEG* read_eeglab_file( const char *file ){ mat_t *mat; matvar_t *meeg; /* contains the struct 'EEG' from EEGlab */ matvar_t *tmp, *tmp2, *event, *epoch; int nfields; int c,i,j; EEG *eeg; int nbchan, ntrials, n; dprintf("Reading file: '%s'\n", file); mat = Mat_Open( file, MAT_ACC_RDONLY); if( !mat ){ errprintf("Error opening MATLAB file '%s'\n", file ); return NULL; } meeg = Mat_VarRead( mat, "EEG" ); if( meeg->class_type!=MAT_C_STRUCT ){ errprintf("EEG does not appear to be a struct\n" ); return NULL; } nfields = Mat_VarGetNumberOfFields( meeg ); #ifdef DEBUG dprintf( "There are %i fields in the EEG struct\n", nfields ); for( i=1; i<=nfields; i++ ){ /* MATLAB 1-relative indices */ tmp = Mat_VarGetStructField( meeg, &i, BY_INDEX, 0 ); dprintf("Found field: '%s'\n", tmp->name); } #endif /* dimensions */ nbchan = (int)get_double_from_struct_field( meeg, "nbchan",0 ); ntrials= (int)get_double_from_struct_field( meeg, "trials",0 ); n = (int)get_double_from_struct_field( meeg, "pnts",0 ); dprintf("dim=(%i,%i,%i)\n", nbchan,ntrials,n); eeg = eeg_init( nbchan, ntrials, n ); /* filename */ eeg->filename=(char*)malloc( (strlen(file)+2)*sizeof(char) ); strcpy( eeg->filename, file ); /* comments */ tmp = Mat_VarGetStructField( meeg, "comments", BY_NAME, 0 ); eeg->comment=(char*)malloc( tmp->dims[0]*sizeof(char) ); for( i=0; i<tmp->dims[0]+1; i++ ){ eeg->comment[i]='\0'; } memcpy( eeg->comment, tmp->data, tmp->dims[0]*sizeof(char)); /* sampling rate */ eeg->sampling_rate = get_double_from_struct_field( meeg, "srate", 0); /* times */ tmp = Mat_VarGetStructField( meeg, "times", BY_NAME, 0 ); if( tmp->dims[1]==0 && ntrials == 1){ // continuous data dprintf("Continuous data, skipping times-array\n"); } else if( tmp->dims[1]!=n ){ errprintf("times-array should be of length n: %i != %i\n", tmp->dims[1], n ); eeg_free( eeg ); return NULL; } else { if( tmp->data_size != sizeof(double) ){ errprintf("times is not double format, %i!=%li\n", tmp->data_size, sizeof(double)); eeg_free( eeg ); return NULL; } eeg->times=array_new2( DOUBLE, 1, n ); memcpy(eeg->times->data, tmp->data, n*sizeof(double) ); } /* channel info */ eeg->chaninfo = (ChannelInfo*)malloc( nbchan*sizeof(ChannelInfo) ); tmp = Mat_VarGetStructField( meeg, "chanlocs", BY_NAME, 0 ); dprintf("chanlocs: %i,%i\n", tmp->dims[0], tmp->dims[1]); for( i=0; i<nbchan; i++ ){ tmp2 = Mat_VarGetStructField( tmp, "labels", BY_NAME, i ); eeg->chaninfo[i].num = i; eeg->chaninfo[i].num_chans = nbchan; strcpy(eeg->chaninfo[i].label, (char*)tmp2->data); eeg->chaninfo[i].x = get_double_from_struct_field( tmp, "X", i); eeg->chaninfo[i].y = get_double_from_struct_field( tmp, "Y", i); eeg->chaninfo[i].z = get_double_from_struct_field( tmp, "Z", i); } /* data */ tmp = Mat_VarGetStructField( meeg, "data", BY_NAME, 0 ); if( ntrials==1 ) { // continuous data if( tmp->dims[0]!=nbchan || tmp->dims[1]!=n ){ errprintf("(nbchan,n)=(%i,%i), should be (%i,%i)\n", tmp->dims[0], tmp->dims[1], nbchan, n ); eeg_free( eeg ); return NULL; } } else if( tmp->dims[0]!=nbchan || tmp->dims[1]!=n || tmp->dims[2]!=ntrials ){ errprintf("(nbchan,ntrials,n)=(%i,%i,%i), should be (%i,%i,%i)\n", tmp->dims[0], tmp->dims[2], tmp->dims[1], nbchan, ntrials, n ); eeg_free( eeg ); return NULL; } if( tmp->data_size != sizeof(float) ){ errprintf("data is not in float format, sizeof(data)=%i, sizeof(float)=%li\n", tmp->data_size, sizeof(float)); eeg_free( eeg ); return NULL; } float x; for( c=0; c<nbchan; c++ ){ for( i=0; i<ntrials; i++ ){ for( j=0; j<n; j++ ){ x=((float*)tmp->data)[ c + (j*nbchan) + (i*n*nbchan) ]; array_INDEX3(eeg->data,double,c,i,j) = (double)x; } } } /* TODO CONTINUE HERE */ /* /\* markers *\/ */ /* epoch = Mat_VarGetStructField( meeg, "epoch", BY_NAME, 0 ); */ /* if( epoch->dims[0] == 0 || epoch->dims[1] < ntrials ){ */ /* warnprintf("no epoch field, or wrong dimensions (%i,%i), skipping...\n", */ /* epoch->dims[0],epoch->dims[1]); */ /* } else { */ /* eeg->nmarkers = (unsigned int*) malloc( ntrials*sizeof(unsigned int) ); */ /* eeg->markers = (unsigned int**) malloc( ntrials*sizeof(unsigned int*) ); */ /* eeg->marker_labels = (char***) malloc( ntrials*sizeof(char**) ); */ /* for( i=0; i<ntrials; i++ ){ */ /* tmp = Mat_VarGetStructField( epoch, "eventlatency", BY_NAME, i ); */ /* tmp2 = Mat_VarGetStructField( epoch, "eventtype", BY_NAME, i ); */ /* dprintf("%i, %i\n", i, tmp->dims[1]); */ /* eeg->nmarkers[i] = tmp->dims[1]; */ /* eeg->markers[i] = (unsigned int*) malloc( eeg->nmarkers[i]*sizeof(unsigned int) ); */ /* eeg->marker_labels[i] = (char**) malloc( eeg->nmarkers[i]*sizeof(char*) ); */ /* for( j=0; j<eeg->nmarkers[i]; j++ ){ */ /* /\* label *\/ */ /* event = Mat_VarGetCell( tmp2, j ); /\* MATLAB index *\/ */ /* eeg->marker_labels[i][j] = (char*)malloc( (strlen((char*)event->data)+1)*sizeof(char) ); */ /* strcpy( eeg->marker_labels[i][j], (char*)event->data ); */ /* /\* latency *\/ */ /* event = Mat_VarGetCell( tmp, j ); /\* MATLAB index *\/ */ /* eeg->markers[i][j] = closest_index( eeg->times, n, ((double*)event->data)[0] ); */ /* } */ /* } */ /* } */ dprintf("Finished reading '%s'\n", file ); return eeg; }
void CSMatrix<Scalar>::import_from_file(const char *filename, const char *var_name, MatrixExportFormat fmt, bool invert_storage) { switch (fmt) { case EXPORT_FORMAT_MATRIX_MARKET: throw Exceptions::MethodNotOverridenException("CSMatrix<Scalar>::import_from_file - Matrix Market"); break; case EXPORT_FORMAT_MATLAB_MATIO: { #ifdef WITH_MATIO mat_t *matfp; matvar_t *matvar; matfp = Mat_Open(filename,MAT_ACC_RDONLY); if (!matfp ) { throw Exceptions::IOException(Exceptions::IOException::Read, filename); return; } matvar = Mat_VarRead(matfp, var_name); if (matvar) { mat_sparse_t *sparse = (mat_sparse_t *)matvar->data; this->nnz = sparse->nir; this->Ax = new Scalar[this->nnz]; this->Ai = new int[this->nnz]; this->size = sparse->njc - 1; this->Ap = new int[this->size + 1]; void* data = nullptr; if(Hermes::Helpers::TypeIsReal<Scalar>::value) data = sparse->data; else { std::complex<double>* complex_data = new std::complex<double>[this->nnz]; double* real_array = (double*)((mat_complex_split_t*)sparse->data)->Re; double* imag_array = (double*)((mat_complex_split_t*)sparse->data)->Im; for(int i = 0; i < this->nnz; i++) complex_data[i] = std::complex<double>(real_array[i], imag_array[i]); data = (void*)complex_data; } memcpy(this->Ax, data, this->nnz * sizeof(Scalar)); if(!Hermes::Helpers::TypeIsReal<Scalar>::value) delete [] data; memcpy(this->Ap, sparse->jc, (this->size + 1) * sizeof(Scalar)); memcpy(this->Ai, sparse->ir, this->nnz * sizeof(int)); if(invert_storage) this->switch_orientation(); } Mat_Close(matfp); if(!matvar) throw Exceptions::IOException(Exceptions::IOException::Read, filename); #else throw Exceptions::Exception("MATIO not included."); #endif } break; case EXPORT_FORMAT_PLAIN_ASCII: throw Exceptions::MethodNotOverridenException("CSMatrix<Scalar>::import_from_file - Simple format"); break; } }
/** \brief read a MATLAB-array from a .mat file. \todo Currently, the returned array is always DOUBLE. \param file the .mat file \param varname the name of the variable in the .mat file; can be NULL, in this case the first variable is read. \return the Array-struct or NULL in case an error occurred */ Array* read_array_matlab( const char *file, const char *varname ){ mat_t *mfile; matvar_t *marr=NULL; dprintf("Reading variable '%s' from file: '%s'\n", varname, file); mfile = Mat_Open( file, MAT_ACC_RDONLY); if( !mfile ){ errprintf("Error opening MATLAB file '%s'\n", file ); return NULL; } if( varname ){ marr = Mat_VarRead( mfile, varname ); } else { marr = Mat_VarReadNext( mfile ); } Mat_Close( mfile ); dprintf("Done\n"); if( !marr ){ errprintf("Something is wrong, could not read variable\n"); return NULL; } Array *out=array_new( DOUBLE, marr->rank, marr->dims ); ulong i; uint *index=(uint*)malloc( out->ndim*sizeof(uint)); for( i=0; i<marr->nbytes/marr->data_size; i++ ){ array_calc_colindex( i, out->size, out->ndim, index ); switch( marr->data_type ){ case MAT_T_INT8: *((double*)array_index(out,index))=(double)(*(int8_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_UINT8: *((double*)array_index(out,index))=(double)(*(uint8_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_INT16: *((double*)array_index(out,index))=(double)(*(int16_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_UINT16: *((double*)array_index(out,index))=(double)(*(uint16_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_INT32: *((double*)array_index(out,index))=(double)(*(int32_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_UINT32: *((double*)array_index(out,index))=(double)(*(uint32_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_INT64: *((double*)array_index(out,index))=(double)(*(int64_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_UINT64: *((double*)array_index(out,index))=(double)(*(uint64_t*)(marr->data+(i*marr->data_size))); break; case MAT_T_SINGLE: *((double*)array_index(out,index))=(double)(*(float*)(marr->data+(i*marr->data_size))); break; case MAT_T_DOUBLE: *((double*)array_index(out,index))=(double)(*(double*)(marr->data+(i*marr->data_size))); break; default: errprintf("Unknown Data-Type in MATLAB-file!\n"); break; } } free(index); return out; }