Esempio n. 1
0
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);
}
Esempio n. 2
0
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;
}
Esempio n. 3
0
/**
 *  @brief Execute commands to read data from a Matlab file
 *  @param pMatFile pointer to an open Matlab file
 *  @param refLaws Reference to a vector of ControlLaw pointers. As control laws are read
 *  from the Matlab file, unique control laws are constructed and allocated on the stack.
 *  The user must manually delete the ControlLaw objects to avoid memory leaks.
 */
void Arcset_bc4bp::readCmds_fromFile(mat_t *pMatFile, std::vector<ControlLaw*> &refLaws){
	Arcset::readCmds_fromFile(pMatFile, refLaws);

	matvar_t *pEpochDeriv = Mat_VarRead(pMatFile, VARNAME_STATE_EPOCH_DERIV);
	if(readVar_NodeExtraParamVec(pEpochDeriv, PARAMKEY_STATE_EPOCH_DERIV, 6, Save_tp::SAVE_ALL)){
		Mat_VarFree(pEpochDeriv);
	}
}//====================================================
Esempio n. 4
0
/**
 *  @brief Execute commands to read data from a Matlab file
 *  @param pMatFile pointer to an open Matlab file
 *  @param refLaws Reference to a vector of ControlLaw pointers. As control laws 
 *  are read from the Matlab file, unique control laws are constructed and 
 *  allocated on the stack. The user must manually delete the ControlLaw objects 
 *  to avoid memory leaks.
 */
void Arcset_cr3bp::readCmds_fromFile(mat_t *pMatFile, 
	std::vector<ControlLaw*> &refLaws){

	Arcset::readCmds_fromFile(pMatFile, refLaws);

	matvar_t *pJacobi = Mat_VarRead(pMatFile, VARNAME_JACOBI);
	if(readVar_NodeExtraParam(pJacobi, PARAMKEY_JACOBI, Save_tp::SAVE_ALL)){
		Mat_VarFree(pJacobi);
	}
}//====================================================
Esempio n. 5
0
int matArrNCol (char *name)
{
  int ncol = 0;
  matvar_t *matvar = Mat_VarRead(mat_file, name);
  if (matvar == NULL)
    return -1;

  ncol = matvar->dims[1];
  Mat_VarFree(matvar);
  return ncol;
}
Esempio n. 6
0
int matArrNRow (char *name)
{
  int nrow = 0;
  matvar_t *matvar = Mat_VarRead(mat_file, name);
  if (matvar == NULL)
    return -1;

  nrow = matvar->dims[0];
  Mat_VarFree(matvar);
  return nrow;
}
Esempio n. 7
0
int matGetInt (char *name,int n1,int n2, int *data)
{
    matvar_t *matvar;
    matvar = Mat_VarRead(mat_file, name);
    if (matvar == NULL)
      return -1;

    memcpy(data, matvar->data, n1*n2*sizeof(int));
    
    Mat_VarFree(matvar);
    return 0;
}
Esempio n. 8
0
 static FMatrix_ptr read_matrix_in_mat(mat_t * mat, const char *varname)
 {
   matvar_t  * tvar = Mat_VarRead(mat, varname);
   int rows = tvar->dims[0];
   int columns = tvar->dims[1];
   std::cout<<rows<<"   "<<columns<<std::endl;
   uint8_t * pData = static_cast<uint8_t *>(tvar->data);
   FMatrix_ptr res = std::make_shared<FMatrix>(rows, columns);
   for(int k = 0; k < rows; ++k)
   {
     for(int i = 0; i < columns; ++i)
     {
       res->operator()(k, i) = static_cast<double>(pData[rows * i + k]);
     }
   }
   Mat_VarFree(tvar);
   return res;
 }
Esempio n. 9
0
int matGetStr (char *name,char *data)
{
  int strlen;

  matvar_t *matvar;
  matvar = Mat_VarRead(mat_file, name);
  if (matvar == NULL)
    return -1;

  strlen = matvar->nbytes;

  if (matvar->dims[0] != 1)
    printf("Error: Multiline string copy attempted\n");

  memcpy(data, matvar->data, strlen);

  Mat_VarFree(matvar);
  return 0;
}
Esempio n. 10
0
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;
}
Esempio n. 11
0
// 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
}
Esempio n. 12
0
      matvar_t * MatFileIO::getVariableViaName(std::string _name) {
      
        return Mat_VarRead(mat,_name.c_str());
	
      }
Esempio n. 13
0
/** \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;
}
Esempio n. 14
0
    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
      }
    }
Esempio n. 15
0
    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;
      }
    }
Esempio n. 16
0
    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");
      }

    }
Esempio n. 17
0
    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;
      }
    }
Esempio n. 18
0
/** \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;
}