Esempio n. 1
0
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;
}
Esempio n. 2
0
/** \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;
}
Esempio n. 3
0
/*
 * matWrite - write signals from measurement structure to MAT file
 */
int matWrite(measurement_t *measurement, const char *outFileName)
{
  size_t dims[2];
  int err = 0;
  mat_t *mat;
  matvar_t *matvar;

  mat = Mat_Create(outFileName, NULL);
  if (mat != NULL) {

    /* loop over all time series */
    struct hashtable *timeSeriesHash = measurement->timeSeriesHash;

    /* Iterator constructor only returns a valid iterator if
     * the hashtable is not empty */
    if (hashtable_count(timeSeriesHash) > 0) {

      struct hashtable_itr *itr = hashtable_iterator(timeSeriesHash);
      do {
        char         *signalName = hashtable_iterator_key(itr);
        timeSeries_t *timeSeries = hashtable_iterator_value(itr);
        double *timeValue = (double *)malloc(sizeof(double)*2*timeSeries->n);
        unsigned int i;

        /*
         * build up a 1x2n array with time stamps in [0..n-1] and
         * values in [n..2n-1].
         */
        for(i=0;i<timeSeries->n;i++) {
          timeValue[i] = timeSeries->time[i];
        }
        for(i=0;i<timeSeries->n;i++) {
          timeValue[timeSeries->n + i] = timeSeries->value[i];
        }
        dims[0] = timeSeries->n;
        dims[1] = 2;

        /* output signal to mat structure and free up temp array. */
        matvar = Mat_VarCreate(signalName, MAT_C_DOUBLE, MAT_T_DOUBLE,
                               2, dims, timeValue, 0);
        Mat_VarWrite(mat, matvar, 0);
        Mat_VarFree(matvar);

        free(timeValue);
      } while (hashtable_iterator_advance(itr));
      free(itr);
    }

    Mat_Close(mat);
  } else {
    fprintf(stderr, "error: could not create MAT file %s\n", outFileName);
    err = 1;
  }

  return err;
}
Esempio n. 4
0
/* put string in mat file*/
void matPutStr (char *name,char *str)
{
  matvar_t *matvar = NULL;
  size_t dims[2];

  dims[0] = 1;
  dims[1] = strlen(str);

  matvar = Mat_VarCreate(name, MAT_C_CHAR, MAT_T_UINT8, 2, dims, str, MAT_F_DONT_COPY_DATA);
  Mat_VarWrite(mat_file, matvar, MAT_COMPRESSION_NONE);
  Mat_VarFree(matvar);
}
Esempio n. 5
0
/* put integer in mat file*/
void matPutInt (char *name,int n1,int n2, int *pd)
{
  matvar_t *matvar = NULL;
  
  size_t dims[2];
  dims[0] = n1;
  dims[1] = n2;
  
  matvar = Mat_VarCreate(name, MAT_C_INT32, MAT_T_INT32, 2, dims, pd, MAT_F_DONT_COPY_DATA);
  Mat_VarWrite(mat_file, matvar, MAT_COMPRESSION_ZLIB);
  Mat_VarFree(matvar);
}
Esempio n. 6
0
// save a .mat matlab matrix
// will store a single matrix (sparse or dense) in a .mat file
// returns 0 on success
static
  int write_mat(char const *const filename,
               matrix_t *const A) {
#ifndef HAVE_MATIO
  return 1;
#else
  const char created_by[] = "created by " PACKAGE_STRING; // "created by Meagre-Crowd x.y.z"
  mat_t* matfp;
  matfp = Mat_Create(filename, created_by);
  if(matfp == NULL)
    return 1; // failed to open file

  // create a matrix convert into
  matvar_t* t = NULL;
  int ret = 0;
  if(A->format == DCOL || A->format == DROW) { // dense
    ret = convert_matrix(A, DCOL, FIRST_INDEX_ZERO); // DROW -> DCOL if DROW
    if(ret != 0)
      ret = 2; // conversion failure

    if(ret == 0) {
      // TODO check for integer overflow in cast from unsigned int -> int
      size_t dims[] = { A->m, A->n };
      t = Mat_VarCreate( "x",
			 MAT_C_DOUBLE,
			 MAT_T_DOUBLE,
			 2, // always at least rank 2
			 dims,
			 A->dd,
			 0 // MAT_F_COMPLEX if complex, could avoid copying data: MAT_F_DONT_COPY_DATA if not sparse
		       );

      if(t == NULL) {
	ret = 3; // failed to malloc data for storage
      }
      else {
	ret = Mat_VarWrite(matfp, t, 1); // compress
	if(ret != 0)
	  ret = 4; // failed data write
      }
    }
  }
  else { // sparse
    assert(0); // do we ever get sparse results?
  }

  Mat_Close(matfp);
  Mat_VarFree(t);
  return ret; // success?
#endif
}
Esempio n. 7
0
/** \brief write EEG-struct to EEGlab-compatible MATLAB file.

	 This write uses MatIO to create an EEGlab file.
	 It was developed with EEGlab version 6.01b.
	 
	 \todo NOT IMPLEMENTED!

	 \param eeg the struct
	 \param file eeglab .set file
	 \return error code
*/
int write_eeglab_file( EEG* eeg, const char *file ){
  mat_t *mfile;
  matvar_t *meeg=NULL;
  if( !(mfile=Mat_Create( file, NULL )) ){
	 errprintf("Could not open '%s' for writing\n", file);
	 return -1;
  }

  //int dims[2]={1,1}, rank=2;
  //meeg = Mat_VarCreate( "EEG", MAT_T_STRUCT, , rank, dims, NULL, 0 );
  
  Mat_VarWrite( mfile, meeg, 0 );
  return 0;
}
Esempio n. 8
0
/* put string in mat file*/
int matPutStr (const char *name, char *str)
{
  int error = 0;
  matvar_t *matvar = nullptr;
  size_t dims[2];

  dims[0] = 1;
  dims[1] = strlen(str);

  matvar = Mat_VarCreate(name, MAT_C_CHAR, MAT_T_UINT8, 2, dims, str, MAT_F_DONT_COPY_DATA);
  if (matvar != nullptr) {
    error = Mat_VarWrite(mat_file, matvar, MAT_COMPRESSION_NONE);
    Mat_VarFree(matvar);
  } else {
    error = 1;
  }
  return error;
}
Esempio n. 9
0
/* put integer in mat file*/
int matPutInt (const char *name,int n1,int n2, int *pd)
{
  int error = 0;
  matvar_t *matvar = nullptr;

  size_t dims[2];
  dims[0] = n1;
  dims[1] = n2;

  matvar = Mat_VarCreate(name, MAT_C_INT32, MAT_T_INT32, 2, dims, pd, MAT_F_DONT_COPY_DATA);
  if (matvar != nullptr) {
    error = Mat_VarWrite(mat_file, matvar, MAT_COMPRESSION_ZLIB);
    Mat_VarFree(matvar);
  } else {
    error = 1;
  }
  return error;
}
Esempio n. 10
0
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;
}
Esempio n. 11
0
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);
}
Esempio n. 12
0
static void
mat_write_signal(const mdf_t *const mdf, 
                 const uint32_t can_channel,
                 const uint32_t number_of_records,
                 const uint16_t channel_type,
                 const char *const message_name,
                 const char *const signal_name,
                 const double *const timeValue,
                 const filter_t *const filter,
                 const void *const cbData)
{
  char *filter_signal_name_in;
  char *filter_message_name_in;
  char *filter_name_out;
  size_t dims[2];
  mdftomat_t *const mdftomat = (mdftomat_t *)cbData;

  dims[0] = number_of_records;
  dims[1] = 2;

  if(   ((can_channel != 0) && (channel_type == 0)) /* Vector CAN */
     || ((can_channel == 0) && (channel_type == 0)) /* DIM */ ) {
    if(mdf->verbose_level >= 2) {
       uint32_t ir;
       printf("ch=%lu n=%lu m=%s s=%s\n",
              (unsigned long)can_channel,
              (unsigned long)number_of_records,
              message_name,
              signal_name);
      if(mdf->verbose_level >= 3) {
       for(ir=0;ir<number_of_records;ir++) {
          printf("%g %g\n",timeValue[ir],timeValue[ir+number_of_records]);
       }
      }
    }
    /* sanitize variable name */
    filter_signal_name_in = sanitize_name(signal_name);
    filter_message_name_in = sanitize_name(message_name);
    filter_name_out = filter_apply(filter, can_channel,
                                   filter_message_name_in,
                                   filter_signal_name_in);
    if(mdf->verbose_level >= 2) {
      printf("    CNBLOCK can_ch=%lu\n"
             "            message      = %s\n"
             "            signal_name  = %s\n"
             "            filter_input = %s\n"
             "            filter_output= %s\n",
             (unsigned long)can_channel, filter_message_name_in,
             signal_name, filter_signal_name_in,
             (filter_name_out!=NULL)?filter_name_out:"<rejected by filter>" );
      if(filter_name_out != NULL) {
        printf("+ %d %s %s %s\n",
               can_channel,
               filter_message_name_in,
               filter_signal_name_in,
               filter_name_out );
      }
    }
    free(filter_signal_name_in);
    free(filter_message_name_in);

    if(filter_name_out != NULL) {
      matvar_t *matvar;
      int rv;

      /* write matlab variable */
      matvar = Mat_VarCreate(filter_name_out, MAT_C_DOUBLE, MAT_T_DOUBLE,
                             2, dims, (double *)timeValue, 0);
      rv = Mat_VarWrite(mdftomat->mat, matvar, mdftomat->compress);
      assert(rv == 0);
      Mat_VarFree(matvar);
      free(filter_name_out);
    }
  }
}
Esempio n. 13
0
int main(int argn, char **argc){
	if(argn != 3){
		printf("usage: convert infile.bin outfile.mat\n"); 
		exit(0); 
	} else {
		FILE* in = fopen(argc[1], "r"); 
		if(!in) {
			printf("could not open %s\n", argc[1]); 
			exit(0); 
		}
		mat_t *mat;
		mat = Mat_Create(argc[2],NULL);
		if(!mat){
			printf("could not open for writing %s\n", argc[2]); 
			exit(0); 
		}
		//this is (for now) a two-stage process: 
		//have to scan through the file, 
		//determine what's there, allocate memory appropritately, 
		//then fill those structures up and write *that* out.
		unsigned int u; 
		unsigned int pos = 0;
		unsigned int rxpackets = 0; 
		unsigned int txpackets = 0; 
		unsigned int msgpackets = 0; 
		bool done = false; 
		while(!done){
			fread((void*)&u,4,1,in);
			if(ferror(in) || feof(in)) done = true; 
			else {
				if(u == 0xdecafbad){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					rxpackets += (siz-4)/(32+4); 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				}else if(u == 0xc0edfad0){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					txpackets++; 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				}else if(u == 0xb00a5c11){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					msgpackets += 1; 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				} else {
					printf("magic number seems off, is 0x%x, %d bytes, %d packets\n",
						   u,pos,rxpackets);
					exit(0); 
				}
				if(ferror(in) || feof(in)) done = true; 
			}
		}
		printf("total %d rxpackets, %d txpackets, %d messages\n", 
			   rxpackets, txpackets, msgpackets); 
		fseek(in,0, SEEK_SET);
		//okay, allocate appropriate data structs: 
		// time (double), analog(i8), channel (i8), 
		// spike_time (double), spikes(i32)
		double* time; 
		mat_uint32_t* mstimer; 
		mat_int8_t* analog;
		mat_int8_t* channel;
		mat_uint32_t* spike_ts; 
		mat_int8_t* spike_ch; 
		mat_int8_t* spike_unit;
		// store timestamp (in samples), rx time (not necessarily accurate) - one per pkt
		// store channel # and sample 
		// store channel & timestamp for spikes.
		// just ignore dropped packets for now.
		time = (double*)malloc(rxpackets * sizeof(double)); 
		  if(!time){ printf("could not allocate time variable."); exit(0);}
		mstimer = (mat_uint32_t*)malloc(rxpackets * sizeof(int) ); 
		 if(!mstimer){ printf("could not allocate mstimer variable."); exit(0);}
		analog = (mat_int8_t*)malloc(rxpackets * 24 ); 
		  if(!analog){ printf("could not allocate analog variable."); exit(0);}
		channel = (mat_int8_t*)malloc(rxpackets * 24 ); 
		  if(!channel){ printf("could not allocate channel variable."); exit(0);}
		
		spike_ts = (mat_uint32_t*)malloc(rxpackets * sizeof(int)*32); 
		  if(!spike_ts){ printf("could not allocate spike_ts variable."); exit(0);}
		spike_ch = (mat_int8_t*)malloc(rxpackets * 32); 
		  if(!spike_ch){ printf("could not allocate spike_ch variable."); exit(0);}
		spike_unit = (mat_int8_t*)malloc(rxpackets * 32); 
		  if(!spike_unit){ printf("could not allocate spike_unit variable."); exit(0);}
		//also need to inspect the messages, to see exactly when the channels changed.
		rxpackets = 0;
		int tp = 0; // packet position (index time, aka timestamp)
		int sp = 0; // spike position (index spike variables)
		char msgs[16][128]; //use this to save messages ; appy them when their echo appears.
		for(int i=0; i<16*128; i++){
			msgs[0][i] = 0; //yes, you can do that in c! 
		}
		int chans[4] = {0,32,64,96}; 
		done = false; 
		while(!done){
			fread((void*)&u,4,1,in);
			if(ferror(in) || feof(in)) done = true; 
			else {
				if(u == 0xdecafbad){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					int npak = (siz-4)/(4+32);
					//first 4 is for dropped packet count
					//second 4 is for 4 byte bridge milisecond counter
					//printf("npak %d siz %d\n",npak,siz); 
					double rxtime = 0.0; 
					unsigned int dropped = 0; 
					fread((void*)&rxtime,8,1,in); //rx time in seconds. 
					fread((void*)&dropped,4,1,in); 
	
					int channels[32]; char match[32]; 
					for(int i=0;i<npak; i++){
						packet p; 
						fread((void*)&p,sizeof(p),1,in);
						if(ferror(in) || feof(in)) done = true; 
						else{
							/*int headecho = ((p.flag) >> 4) & 0xf; 
							//check to see if we can apply the command that was echoed.
							char m = msgs[headecho][0]; 
							if(m >= 'A' && m <= 'A' + 15){
								printf("applying %s\n", msgs[headecho]); 
								msgs[headecho][0] = 0; 
							}*/
							time[tp] = rxtime + (double)i * 6.0 / 31250.0; 
							mstimer[tp] = p.ms; 
							for(int j=0; j<6; j++){
								for(int k=0; k<4; k++){
									char samp = p.data[j*4+k]; 
									analog[tp*24+j*4+k] = samp; 
									channel[tp*24+j*4+k] = chans[k]; 
								}
							}
							decodePacket(&p, channels, match);
							for(int j=0; j<32; j++){
								if(match[j]){
									spike_ts[sp] = tp; 
									spike_ch[sp] = channel[j]; 
									spike_unit[sp] = match[j]; 
									sp++;
								}
							}
							tp++; 
						}
					}
					pos += 16+siz; 
				} else if( u == 0xc0edfad0){
					//ignore tx packets (for now?)
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					txpackets += (siz)/32; 
					fseek(in,siz+8, SEEK_CUR);
					pos += 16+siz; 
				} else if(u == 0xb00a5c11){
					fread((void*)&u,4,1,in); 
					unsigned int siz = u & 0xffff; 
					//printf("u 0x%x\n",u); 
					double rxtime = 0.0; 
					fread((void*)&rxtime,8,1,in);
					char buf[128]; 
					fread((void*)buf,siz,1,in); 
					buf[siz] = 0; 
					//really need to wait for the echo here.
					//bummish.
					printf("message: %s\n", buf); 
					//first char: A-P (0-15, corresponds to echo); second space
					char* b = buf; b+=2; 
					if(strncmp(b, "chan", 4) == 0){
						int ii = b[5] - 'A'; 
						if(ii >= 0 && ii < 4){
							b += 7;
							chans[ii] = atoi(b); 
							//printf(" chan %d changed to %d\n", ii, chans[ii]); 
						}
					}
					pos += 16+siz; 
				} else {
					printf("magic number seems off, is 0x%x, %d bytes\n",
						u,pos);
					exit(0); 
				}
			}
		}
		printf("finished reading in data file, now writing matlab file.\n"); 
		
		matvar_t *matvar;
		matvar = Mat_VarCreate("time",MAT_C_DOUBLE,MAT_T_DOUBLE,
							   1,&tp,time,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(time); //I wish I had more. 
		
		matvar = Mat_VarCreate("mstimer",MAT_C_UINT32,MAT_T_UINT32,
							   1,&tp,mstimer,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(mstimer); 
		
		int m = tp * 24; 
		matvar = Mat_VarCreate("analog",MAT_C_INT8,MAT_T_INT8,
							   1,&m,analog,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(analog); 
		
		matvar = Mat_VarCreate("channel",MAT_C_INT8,MAT_T_INT8,
							   1,&m,channel,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(channel); 
		
		matvar = Mat_VarCreate("spike_ts",MAT_C_UINT32,MAT_T_UINT32,
							   1,&sp,spike_ts,0); 
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(spike_ts); 
		
		matvar = Mat_VarCreate("spike_ch",MAT_C_UINT32,MAT_T_UINT32,
							   1,&sp,spike_ch,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(spike_ch); 
		
		matvar = Mat_VarCreate("spike_unit",MAT_C_UINT32,MAT_T_UINT32,
							   1,&sp,spike_unit,0);
		Mat_VarWrite( mat, matvar, 0 );
		Mat_VarFree(matvar);
		free(spike_unit); 
		
		Mat_Close(mat); 
		fclose(in); 
	}
}
Esempio n. 14
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, "%%%%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
      }
    }
Esempio n. 15
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);
        }
      }
    }
Esempio n. 16
0
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);
}
Esempio n. 17
0
    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
      }
    }
Esempio n. 18
0
    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);
        }
      }
    }
Esempio n. 19
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; 
}