예제 #1
0
/* This function has all the knowledge about events in the various file types */
LOCAL void 
read_neurofile_build_trigbuffer(transform_info_ptr tinfo) {
 struct read_neurofile_storage *local_arg=(struct read_neurofile_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;

 if (local_arg->triggers.buffer_start==NULL) {
  growing_buf_allocate(&local_arg->triggers, 0);
 } else {
  growing_buf_clear(&local_arg->triggers);
 }
 if (args[ARGS_TRIGFILE].is_set) {
  FILE * const triggerfile=(strcmp(args[ARGS_TRIGFILE].arg.s,"stdin")==0 ? stdin : fopen(args[ARGS_TRIGFILE].arg.s, "r"));
  TRACEMS(tinfo->emethods, 1, "read_neurofile_build_trigbuffer: Reading event file\n");
  if (triggerfile==NULL) {
   ERREXIT1(tinfo->emethods, "read_neurofile_build_trigbuffer: Can't open trigger file >%s<\n", MSGPARM(args[ARGS_TRIGFILE].arg.s));
  }
  while (TRUE) {
   long trigpoint;
   char *description;
   int const code=read_trigger_from_trigfile(triggerfile, tinfo->sfreq, &trigpoint, &description);
   if (code==0) break;
   push_trigger(&local_arg->triggers, trigpoint, code, description);
   free_pointer((void **)&description);
  }
  if (triggerfile!=stdin) fclose(triggerfile);
 } else {
  TRACEMS(tinfo->emethods, 0, "read_neurofile_build_trigbuffer: No trigger source known.\n");
 }
}
예제 #2
0
get_soi (j_decompress_ptr cinfo)
/* Process an SOI marker */
{
  int i;
  
  TRACEMS(cinfo, 1, JTRC_SOI);

  if (cinfo->marker->saw_SOI)
    ERREXIT(cinfo, JERR_SOI_DUPLICATE);

  /* Reset all parameters that are defined to be reset by SOI */

  for (i = 0; i < NUM_ARITH_TBLS; i++) {
    cinfo->arith_dc_L[i] = 0;
    cinfo->arith_dc_U[i] = 1;
    cinfo->arith_ac_K[i] = 5;
  }
  cinfo->restart_interval = 0;

  /* Set initial assumptions for colorspace etc */

  cinfo->jpeg_color_space = JCS_UNKNOWN;
  cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */

  cinfo->saw_JFIF_marker = FALSE;
  cinfo->density_unit = 0;	/* set default JFIF APP0 values */
  cinfo->X_density = 1;
  cinfo->Y_density = 1;
  cinfo->saw_Adobe_marker = FALSE;
  cinfo->Adobe_transform = 0;

  cinfo->marker->saw_SOI = TRUE;

  return TRUE;
}
예제 #3
0
파일: MD2.CPP 프로젝트: johnBradley501/TACT
/* MDMSE: Process marked section end.
          Issue an error if no marked section had started.
*/
int mdmse()
{
     int retcode = 0;         /* Return code: 0=same parse; 1=cancel special. */

     if (mslevel) --mslevel;
     else sgmlerr(26, (struct parse *)0, (UNCH *)0, (UNCH *)0);

     if (msplevel) if (--msplevel==0) retcode = 1;
     TRACEMS(0, retcode, mslevel, msplevel);
     return retcode;
}
예제 #4
0
파일: echo.c 프로젝트: berndf/avg_q
/*{{{  echo(transform_info_ptr tinfo) {*/
METHODDEF DATATYPE *
echo(transform_info_ptr tinfo) {
 struct echo_storage *local_arg=(struct echo_storage *)tinfo->methods->local_storage;

 if (local_arg->outfile==NULL) {
  TRACEMS(tinfo->emethods, -1, local_arg->buf.buffer_start);
 } else {
  fputs(local_arg->buf.buffer_start, local_arg->outfile);
 }
 if (local_arg->outfile!=NULL) fflush(local_arg->outfile);

 return tinfo->tsdata;
}
예제 #5
0
파일: write_rec.c 프로젝트: berndf/avg_q
/*{{{  write_rec(transform_info_ptr tinfo) {*/
METHODDEF DATATYPE *
write_rec(transform_info_ptr tinfo) {
 struct write_rec_storage *local_arg=(struct write_rec_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 FILE *outfptr=local_arg->outfptr;
 short *inbuf;
 array myarray;

 if (tinfo->itemsize!=1) {
  ERREXIT(tinfo->emethods, "write_rec: Only itemsize=1 is supported.\n");
 }
 if (args[ARGS_CLOSE].is_set) {
  write_rec_open_file(tinfo);
  outfptr=local_arg->outfptr;
 }
 /*{{{  Write epoch*/
 tinfo_array(tinfo, &myarray);
 /* We read the data point by point, i.e. channels fastest */
 array_transpose(&myarray);
 /* Within the record, writing is non-interlaced, ie points fastest */
 do {
  do {
   inbuf=local_arg->outbuf+local_arg->samples_per_record*myarray.current_element+local_arg->current_sample;
   *inbuf= (short int)rint(array_scan(&myarray)/local_arg->resolution);
   if (!local_arg->overflow_has_occurred && (*inbuf<local_arg->digmin || *inbuf>local_arg->digmax)) {
    TRACEMS(tinfo->emethods, 0, "write_rec: Some output values exceed digitization bits!\n");
    local_arg->overflow_has_occurred=TRUE;
   }
#ifndef LITTLE_ENDIAN
   Intel_int16(inbuf);
#endif
  } while (myarray.message==ARRAY_CONTINUE);
  if (++local_arg->current_sample>=local_arg->samples_per_record) {
   if ((int)fwrite(local_arg->outbuf, sizeof(short), tinfo->nr_of_channels*local_arg->samples_per_record, outfptr)!=tinfo->nr_of_channels*local_arg->samples_per_record) {
    ERREXIT(tinfo->emethods, "write_rec: Write error on data file.\n");
   }
   /* If nr_of_records was -1 (can only happen while appending),
    * leave it that way */
   if (local_arg->nr_of_records>=0) local_arg->nr_of_records++;
   local_arg->current_sample=0L;
  }
 } while (myarray.message!=ARRAY_ENDOFSCAN);
 /*}}}  */
 if (args[ARGS_CLOSE].is_set) write_rec_close_file(tinfo);
 return tinfo->tsdata;	/* Simply to return something `useful' */
}
예제 #6
0
파일: subtract.c 프로젝트: berndf/avg_q
/*{{{  subtract_init(transform_info_ptr tinfo)*/
METHODDEF void
subtract_init(transform_info_ptr tinfo) {
 struct subtract_storage *local_arg=(struct subtract_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 transform_info_ptr side_tinfo= &local_arg->side_tinfo;

 local_arg->ttest=args[ARGS_TTEST].is_set;
 if (args[ARGS_LEAVE_TPARAMETERS].is_set && !local_arg->ttest) {
  TRACEMS(tinfo->emethods, 0, "subtract_init: Option -u given without -t. Adding -t...\n");
  local_arg->ttest=TRUE;
 }
 if (args[ARGS_TYPE].is_set) {
  local_arg->type=(enum subtract_types)args[ARGS_TYPE].arg.i;
 } else {
  local_arg->type=SUBTRACT_TYPE_SUBTRACT;
 }
 if (local_arg->type!=SUBTRACT_TYPE_SUBTRACT && local_arg->ttest) {
  ERREXIT(tinfo->emethods, "subtract_init: T-test is only useful in subtract mode.\n");
 }
 side_tinfo->emethods=tinfo->emethods;
 side_tinfo->methods= &local_arg->side_method;
 select_readasc(side_tinfo);
 growing_buf_init(&local_arg->side_argbuf);
 growing_buf_allocate(&local_arg->side_argbuf, 0);
 if (args[ARGS_CLOSE].is_set) {
  growing_buf_appendstring(&local_arg->side_argbuf, "-c ");
 }
 if (args[ARGS_FROMEPOCH].is_set) {
#define BUFFER_SIZE 80
  char buffer[BUFFER_SIZE];
  snprintf(buffer, BUFFER_SIZE, "-f %ld ", args[ARGS_FROMEPOCH].arg.i);
  growing_buf_appendstring(&local_arg->side_argbuf, buffer);
 }
 growing_buf_appendstring(&local_arg->side_argbuf, args[ARGS_SUBTRACTFILE].arg.s);

 if (!local_arg->side_argbuf.can_be_freed || !setup_method(side_tinfo, &local_arg->side_argbuf)) {
  ERREXIT(tinfo->emethods, "subtract_init: Error setting readasc arguments.\n");
 }

 (*side_tinfo->methods->transform_init)(side_tinfo);

 side_tinfo->tsdata=NULL;	/* We still have to fetch the data... */

 tinfo->methods->init_done=TRUE;
}
예제 #7
0
GLOBAL void
jopen_backing_store (backing_store_ptr info, long total_bytes_needed)
{
  char tracemsg[TEMP_NAME_LENGTH+40];

  select_file_name(info->temp_name);
  if ((info->temp_file = fopen(info->temp_name, RW_BINARY)) == NULL) {
    /* hack to get around ERREXIT's inability to handle string parameters */
    sprintf(tracemsg, "Failed to create temporary file %s", info->temp_name);
    ERREXIT(methods, tracemsg);
  }
  info->read_backing_store = read_backing_store;
  info->write_backing_store = write_backing_store;
  info->close_backing_store = close_backing_store;
  /* hack to get around TRACEMS' inability to handle string parameters */
  sprintf(tracemsg, "Using temp file %s", info->temp_name);
  TRACEMS(methods, 1, tracemsg);
}
예제 #8
0
파일: MD2.CPP 프로젝트: johnBradley501/TACT
/* MDMS: Process marked section start.
         If already in special parse, bump the level counters and return
         without parsing the declaration.
*/
struct parse *mdms(UNCH *tbuf,        /* Work area for tokenization [NAMELEN+2]. */
						 struct parse *pcb) /* Parse control block for this parse. */
{
     int key;                 /* Index of keyword in mslist. */
     int ptype;               /* Parameter token type. */
     int pcbcode = 0;         /* Parse code: 0=same; 2-4 per defines. */

     if (++mslevel>TAGLVL) {
          --mslevel;
          sgmlerr(27, (struct parse *)0, ntoa(TAGLVL), (UNCH *)0);
     }

     /* If already in IGNORE mode, return without parsing parameters. */
     if (msplevel) {++msplevel; return(pcb);}

     parmno = 0;                   /* No parameters as yet. */
     mdessv = es;                  /* Save es for checking entity nesting. */
     pcbmd.newstate = pcbmdtk;     /* First separator is optional. */

     /* PARAMETERS: TEMP, RCDATA, CDATA, IGNORE, INCLUDE, or MDS. */
     while ((ptype = parsemd(tbuf, NAMECASE, &pcblitp, NAMELEN))==NAS){
          if ((key = mapsrch(mstab, tbuf+1))==0) {
               sgmlerr(64, (struct parse *)0, ntoa(parmno), tbuf+1);
               continue;
          }
          if (key==MSTEMP) continue;       /* TEMP: for documentation. */
          msplevel = 1;                    /* Special parse required. */
          if (key>pcbcode) pcbcode = key;  /* Update if higher priority. */
     }
     if (ptype!=MDS) {
          NEWCC;                           /* Syntax error did REPEATCC. */
          sgmlerr(97, (struct parse *)0, lex.m.dso, (UNCH *)0);
          REPEATCC;                        /* 1st char of marked section. */
     }
     if (es!=mdessv) synerr(37, pcb);
     TRACEMS(1, pcbcode, mslevel, msplevel);
     if (pcbcode==MSIGNORE) pcb = &pcbmsi;
     else if (pcbcode) {
          pcb = pcbcode==MSCDATA  ? &pcbmsc : (rcessv = es, &pcbmsrc);
     }
     return(pcb);              /* Tell caller whether to change the parse. */
}
예제 #9
0
파일: rereference.c 프로젝트: berndf/avg_q
/*{{{  rereference_init(transform_info_ptr tinfo)*/
METHODDEF void
rereference_init(transform_info_ptr tinfo) {
 struct rereference_args_struct *rereference_args=(struct rereference_args_struct *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;

 rereference_args->refchannel_numbers=expand_channel_list(tinfo, args[ARGS_REFCHANS].arg.s);
 if (rereference_args->refchannel_numbers==NULL) {
  ERREXIT(tinfo->emethods, "rereference_init: No reference channel was selected.\n");
 }
 if (args[ARGS_EXCLUDECHANS].is_set) {
  rereference_args->excludechannel_numbers=expand_channel_list(tinfo, args[ARGS_EXCLUDECHANS].arg.s);
  if (rereference_args->excludechannel_numbers==NULL) {
   TRACEMS(tinfo->emethods, 0, "rereference_init: No exclude channels were actually selected!\n");
  }
 } else {
  rereference_args->excludechannel_numbers=NULL;
 }

 tinfo->methods->init_done=TRUE;
}
예제 #10
0
파일: get_mfxepoch.c 프로젝트: berndf/avg_q
/*{{{  get_mfxepoch(transform_info_ptr tinfo)*/
METHODDEF DATATYPE *
get_mfxepoch(transform_info_ptr tinfo) {
 struct get_mfxepoch_storage *local_arg=(struct get_mfxepoch_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 DATATYPE *newepoch;
 int again=FALSE;
 long epochlength;

 if (local_arg->epochs--==0) return NULL;

 do {
  again=FALSE;
  if ((newepoch=(DATATYPE *)mfx_getepoch(local_arg->fileptr, &epochlength, local_arg->beforetrig-local_arg->offset, local_arg->aftertrig+local_arg->offset, local_arg->trigname, args[ARGS_TRIGCODE].arg.i))==NULL) {
   /* MFX_READERR4 is the normal end-of-file 'error' */
   TRACEMS1(tinfo->emethods, (mfx_lasterr==MFX_READERR4 ? 1 : 0), "get_mfxepoch: mfx error >%s<\n", MSGPARM(mfx_errors[mfx_lasterr]));
   /* If the error was due to the beforetrig time being too long, try to
    * skip this epoch and try the next one */
   if (mfx_lasterr==MFX_NEGSEEK) {
    again=TRUE;
    mfx_seektrigger(local_arg->fileptr, local_arg->trigname, args[ARGS_TRIGCODE].arg.i);
    TRACEMS(tinfo->emethods, 1, "get_mfxepoch: Retrying...\n");
   }
  }
 } while (again);
 if (newepoch!=NULL) {
  /* TOUCH TINFO ONLY IF GETEPOCH WAS SUCCESSFUL */
  get_mfxinfo(local_arg->fileptr, tinfo);
  tinfo->z_label=NULL;
  tinfo->nr_of_points=epochlength;
  tinfo->length_of_output_region=epochlength*tinfo->nr_of_channels;
  tinfo->beforetrig=local_arg->beforetrig;
  tinfo->aftertrig=tinfo->nr_of_points-tinfo->beforetrig;
  tinfo->multiplexed=TRUE;
  tinfo->sfreq=1.0/(local_arg->fileptr)->fileheader.sample_period;
  tinfo->data_type=TIME_DATA;
  tinfo->itemsize=1;	/* Still, mfx doesn't support tuple data */
  tinfo->leaveright=0;
  tinfo->nrofaverages=1;
 }
 return newepoch;
}
예제 #11
0
LOCAL boolean
open_file_store (backing_store_ptr info, long total_bytes_needed)
{
  short handle;
  char tracemsg[TEMP_NAME_LENGTH+40];

  select_file_name(info->temp_name);
  if (jdos_open((short far *) & handle, (char far *) info->temp_name)) {
    /* hack to get around TRACEMS' inability to handle string parameters */
    sprintf(tracemsg, "Failed to create temporary file %s", info->temp_name);
    ERREXIT(methods, tracemsg);	/* jopen_backing_store will fail anyway */
    return FALSE;
  }
  info->handle.file_handle = handle;
  info->read_backing_store = read_file_store;
  info->write_backing_store = write_file_store;
  info->close_backing_store = close_file_store;
  /* hack to get around TRACEMS' inability to handle string parameters */
  sprintf(tracemsg, "Opened DOS file %d  %s", handle, info->temp_name);
  TRACEMS(methods, 1, tracemsg);
  return TRUE;			/* succeeded */
}
예제 #12
0
/*{{{  read_freiburg_init(transform_info_ptr tinfo) {*/
METHODDEF void
read_freiburg_init(transform_info_ptr tinfo) {
 struct read_freiburg_storage *local_arg=(struct read_freiburg_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 struct stat statbuf;

 /*{{{  Process options*/
 local_arg->fromepoch=(args[ARGS_FROMEPOCH].is_set ? args[ARGS_FROMEPOCH].arg.i : 1);
 local_arg->epochs=(args[ARGS_EPOCHS].is_set ? args[ARGS_EPOCHS].arg.i : -1);
 /*}}}  */
 local_arg->channelnames=NULL;
 local_arg->uV_per_bit=NULL;
 growing_buf_init(&local_arg->segment_table); /* This sets buffer_start=NULL */
 local_arg->nr_of_channels=0;

 if (args[ARGS_CONTINUOUS].is_set) {
  /*{{{  Open a continuous (sleep, Bernd Tritschler) file*/
  FILE *infile;
  local_arg->in_channels= &sleep_channels[0];

  if (stat(args[ARGS_IFILE].arg.s, &statbuf)!= 0 || !S_ISREG(statbuf.st_mode)) {
   /* File does not exist or isn't a regular file: Try BT format */
#ifdef __GNUC__
   char co_name[strlen(args[ARGS_IFILE].arg.s)+4];
   char coa_name[strlen(args[ARGS_IFILE].arg.s)+5];
#else
   char co_name[MAX_PATHLEN];
   char coa_name[MAX_PATHLEN];
#endif
   char coa_buf[MAX_COALINE];
   FILE *coafile;

   strcpy(co_name, args[ARGS_IFILE].arg.s); strcat(co_name, ".co");
   if((infile=fopen(co_name,"rb"))==NULL) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Can't open file %s\n", MSGPARM(co_name));
   }
   local_arg->infile=infile;
   if (args[ARGS_REPAIR_OFFSET].is_set) {
    fseek(infile, args[ARGS_REPAIR_OFFSET].arg.i, SEEK_SET);
   } else {
   if (read_struct((char *)&local_arg->btfile, sm_BT_file, infile)==0) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Header read error in file %s\n", MSGPARM(co_name));
   }
#  ifndef LITTLE_ENDIAN
   change_byteorder((char *)&local_arg->btfile, sm_BT_file);
#  endif
   }
   strcpy(coa_name, args[ARGS_IFILE].arg.s); strcat(coa_name, ".coa");
   if((coafile=fopen(coa_name,"rb"))==NULL) {
    TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: No file %s found\n", MSGPARM(coa_name));
   } else {
    while (!feof(coafile)) {
     Bool repeat;
     fgets(coa_buf, MAX_COALINE-1, coafile);
     do {
      repeat=FALSE;
      if (strncmp(coa_buf, "Channel_Table ", 14)==0) {
       int havechannels=0, stringlength=0;
       long tablepos=ftell(coafile);
       char *innames;
       while (!feof(coafile)) {
	char *eol;
	fgets(coa_buf, MAX_COALINE-1, coafile);
	if (!isdigit(*coa_buf)) break;
	if (strncmp(coa_buf, "0 0 ", 4)==0) {
	 /* Empty channel descriptors: Don't generate channelnames */
	} else {
	 for (eol=coa_buf+strlen(coa_buf)-1; eol>=coa_buf && (*eol=='\n' || *eol=='\r'); eol--) *eol='\0';
	 /* This includes 1 for the zero at the end: */
	 stringlength+=strlen(strrchr(coa_buf, ' '));
	}
	havechannels++;
       }
       if (havechannels==0) continue;	/* Channel table is unuseable */
       local_arg->nr_of_channels=havechannels;
       innames=NULL;
       if ((stringlength!=0 && 
	   ((local_arg->channelnames=(char **)malloc(havechannels*sizeof(char *)))==NULL || 
	    (innames=(char *)malloc(stringlength))==NULL)) ||
	   (local_arg->uV_per_bit=(float *)malloc(havechannels*sizeof(float)))==NULL) {
	ERREXIT(tinfo->emethods, "read_freiburg_init: Error allocating .coa memory\n");
       }
       fseek(coafile, tablepos, SEEK_SET);
       havechannels=0;
       while (!feof(coafile)) {
	char *eol;
	fgets(coa_buf, MAX_COALINE-1, coafile);
	if (!isdigit(*coa_buf)) break;
	for (eol=coa_buf+strlen(coa_buf)-1; eol>=coa_buf && (*eol=='\n' || *eol=='\r'); eol--) *eol='\0';
	if (innames!=NULL) {
	 strcpy(innames, strrchr(coa_buf, ' ')+1);
	 local_arg->channelnames[havechannels]=innames;
	 innames+=strlen(innames)+1;
	}
	/* The sensitivity in .coa files is given as nV/Bit */
	local_arg->uV_per_bit[havechannels]=atoi(strchr(coa_buf, ' ')+1)/1000.0;
	if (local_arg->uV_per_bit[havechannels]==0.0) {
	 local_arg->uV_per_bit[havechannels]=0.086;
	 TRACEMS1(tinfo->emethods, 1, "read_freiburg_init: Sensitivity for channel %d set to 86 nV/Bit\n", MSGPARM(havechannels));
	}
	havechannels++;
       }
       repeat=TRUE;
      } else if (strncmp(coa_buf, SEGMENT_TABLE_STRING, strlen(SEGMENT_TABLE_STRING))==0) {
       long current_offset=0;
       char *inbuf=coa_buf;
       Bool havesomething=FALSE;

       growing_buf_allocate(&local_arg->segment_table, 0);
       while (!feof(coafile)) {
	int const nextchar=fgetc(coafile);
	if (nextchar=='\r' || nextchar=='\n' || nextchar==' ') {
	 if (havesomething) {
	  *inbuf = '\0';
	  current_offset+=atoi(coa_buf);
	  growing_buf_append(&local_arg->segment_table, (char *)&current_offset, sizeof(long));
	  inbuf=coa_buf;
	  havesomething=FALSE;
	 }
	 if (nextchar=='\n') break;
	} else {
	 *inbuf++ = nextchar;
	 havesomething=TRUE;
	}
       }
       repeat=FALSE;
      }
     } while (repeat);
    }
    fclose(coafile);
    if (local_arg->uV_per_bit==NULL) {
     TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: No channel table found in file %s\n", MSGPARM(coa_name));
    }
    if (local_arg->segment_table.buffer_start==NULL) {
     TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: No segment table found in file %s\n", MSGPARM(coa_name));
    }
    /* Determine the exact number of points in file: Start with the previous
     * segment and add the last segment. */
    fstat(fileno(infile),&statbuf);
    //printf("File size is %ld\n", statbuf.st_size);
    //printf("Last segment (EOF) at %ld\n", ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]);
    while (local_arg->segment_table.current_length>=1 && ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]>=statbuf.st_size) {
     //printf("%ld - Removing last segment!\n", ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]);
     local_arg->segment_table.current_length--;
    }
    /* Size without the last segment */
    tinfo->points_in_file=(local_arg->segment_table.current_length/sizeof(long)-1)*SEGMENT_LENGTH;
    /* Count the points in the last segment */
    {
     array myarray;
     int length_of_last_segment=0;
     myarray.element_skip=tinfo->itemsize=1;
     myarray.nr_of_vectors=1;
     myarray.nr_of_elements=local_arg->nr_of_channels;
     if (array_allocate(&myarray)==NULL) {
      ERREXIT(tinfo->emethods, "read_freiburg_init: Error allocating myarray\n");
     }
     fseek(infile, ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1], SEEK_SET);
     //printf("Seeking to %ld\n", ((long *)local_arg->segment_table.buffer_start)[local_arg->segment_table.current_length/sizeof(long)-1]);
     tinfo->nr_of_channels=local_arg->nr_of_channels; /* This is used by freiburg_get_segment_init! */
     freiburg_get_segment_init(tinfo);
     while (freiburg_get_segment(tinfo, &myarray)==0) length_of_last_segment++;
     freiburg_get_segment_free(tinfo);
     tinfo->points_in_file+=length_of_last_segment;
     TRACEMS1(tinfo->emethods, 1, "read_freiburg_init: Last segment has %ld points\n",length_of_last_segment);
     array_free(&myarray);
    }
   }
   if (local_arg->channelnames==NULL && local_arg->btfile.text[0]=='\0') {
    local_arg->in_channels= &goeppi_channels[0];
    TRACEMS(tinfo->emethods, 0, "read_freiburg_init: Assuming Goeppingen style setup!\n");
   }
   local_arg->continuous_type=SLEEP_BT_TYPE;
   TRACEMS(tinfo->emethods, 1, "read_freiburg_init: Opened file in BT format\n");
  } else {
   if((infile=fopen(args[ARGS_IFILE].arg.s,"rb"))==NULL) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Can't open file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
   }
   if (args[ARGS_REPAIR_OFFSET].is_set) {
    fseek(infile, args[ARGS_REPAIR_OFFSET].arg.i, SEEK_SET);
   } else {
   if (read_struct((char *)&local_arg->btfile, sm_BT_file, infile)==0) {
    ERREXIT1(tinfo->emethods, "read_freiburg_init: Header read error in file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
   }
#  ifdef LITTLE_ENDIAN
   change_byteorder((char *)&local_arg->btfile, sm_BT_file);
#  endif
   }
   local_arg->continuous_type=SLEEP_KL_TYPE;
   /* Year and day are swapped in KL format with respect to BT format... */
   {short buf=local_arg->btfile.start_year; local_arg->btfile.start_year=local_arg->btfile.start_day; local_arg->btfile.start_day=buf;}
   /* Well, sometimes or most of the time, in KL files the sampling interval 
    * was not set correctly... */
   if (!args[ARGS_SFREQ].is_set && local_arg->btfile.sampling_interval_us!=9765 && local_arg->btfile.sampling_interval_us!=9766) {
    TRACEMS1(tinfo->emethods, 0, "read_freiburg_init: sampling_interval_us was %d, corrected!\n", MSGPARM(local_arg->btfile.sampling_interval_us));
    local_arg->btfile.sampling_interval_us=9766;
   }
   TRACEMS(tinfo->emethods, 1, "read_freiburg_init: Opened file in KL format\n");
  }
  if (args[ARGS_REPAIR_CHANNELS].is_set) local_arg->btfile.nr_of_channels=args[ARGS_REPAIR_CHANNELS].arg.i;
  tinfo->nr_of_channels=local_arg->btfile.nr_of_channels;
  if (tinfo->nr_of_channels<=0 || tinfo->nr_of_channels>MAX_NUMBER_OF_CHANNELS_IN_EP) {
   ERREXIT1(tinfo->emethods, "read_freiburg_init: Impossible: %d channels?\n", MSGPARM(tinfo->nr_of_channels));
  }
  if (local_arg->nr_of_channels==0) {
   local_arg->nr_of_channels=tinfo->nr_of_channels;
  } else {
   if (local_arg->nr_of_channels!=tinfo->nr_of_channels) {
    ERREXIT2(tinfo->emethods, "read_freiburg_init: Setup has %d channels, but the file has %d!\n", MSGPARM(local_arg->nr_of_channels), MSGPARM(tinfo->nr_of_channels));
   }
  }
  local_arg->sfreq=(args[ARGS_SFREQ].is_set ? args[ARGS_SFREQ].arg.d : 1.0e6/local_arg->btfile.sampling_interval_us);
  tinfo->sfreq=local_arg->sfreq;
  if (tinfo->sfreq<=0.0 || tinfo->sfreq>MAX_POSSIBLE_SFREQ) {
   ERREXIT1(tinfo->emethods, "read_freiburg_init: Impossible: sfreq=%gHz?\n", MSGPARM(tinfo->sfreq));
  }

  /*{{{  Parse arguments that can be in seconds*/
  tinfo->nr_of_points=gettimeslice(tinfo, args[ARGS_NCHANNELS].arg.s);
  if (tinfo->nr_of_points<=0) {
   /* Read the whole file as one epoch */
   TRACEMS1(tinfo->emethods, 1, "read_freiburg_init: Reading %ld points\n",tinfo->points_in_file);
   tinfo->nr_of_points=tinfo->points_in_file;
  }
  local_arg->offset=(args[ARGS_OFFSET].is_set ? gettimeslice(tinfo, args[ARGS_OFFSET].arg.s) : 0);
  local_arg->epochlength=tinfo->nr_of_points;
  /*}}}  */

  tinfo->beforetrig= -local_arg->offset;
  tinfo->aftertrig=tinfo->nr_of_points+local_arg->offset;
  /*}}}  */
 } else {
  local_arg->in_channels= &freiburg_channels[0];
  local_arg->current_trigger=0;
  if (stat(args[ARGS_IFILE].arg.s, &statbuf)!=0) {
   ERREXIT1(tinfo->emethods, "read_freiburg_init: Can't stat file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
  }
  local_arg->nr_of_channels=atoi(args[ARGS_NCHANNELS].arg.s);
  /* average mode if the name does not belong to a directory */
  local_arg->average_mode= !S_ISDIR(statbuf.st_mode);
  tinfo->nr_of_channels=MAX_NUMBER_OF_CHANNELS_IN_EP;
 }
 freiburg_get_segment_init(tinfo);
 local_arg->current_point=0;

 tinfo->methods->init_done=TRUE;
}
예제 #13
0
파일: read_synamps.c 프로젝트: berndf/avg_q
/* This function has all the knowledge about events in the various file types */
LOCAL void 
read_synamps_build_trigbuffer(transform_info_ptr tinfo) {
 struct read_synamps_storage * const local_arg=(struct read_synamps_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;

 if (local_arg->triggers.buffer_start==NULL) {
  growing_buf_allocate(&local_arg->triggers, 0);
 } else {
  growing_buf_clear(&local_arg->triggers);
 }
 if (args[ARGS_TRIGFILE].is_set) {
  FILE * const triggerfile=(strcmp(args[ARGS_TRIGFILE].arg.s,"stdin")==0 ? stdin : fopen(args[ARGS_TRIGFILE].arg.s, "r"));
  TRACEMS(tinfo->emethods, 1, "read_synamps_build_trigbuffer: Reading event file\n");
  if (triggerfile==NULL) {
   ERREXIT1(tinfo->emethods, "read_synamps_build_trigbuffer: Can't open trigger file >%s<\n", MSGPARM(args[ARGS_TRIGFILE].arg.s));
  }
  while (TRUE) {
   long trigpoint;
   char *description;
   int const code=read_trigger_from_trigfile(triggerfile, tinfo->sfreq, &trigpoint, &description);
   if (code==0) break;
   push_trigger(&local_arg->triggers, trigpoint, code, description);
   free_pointer((void **)&description);
  }
  if (triggerfile!=stdin) fclose(triggerfile);
 } else {
  switch(local_arg->SubType) {
   case NST_CONTINUOUS:
   case NST_SYNAMPS: {
    /*{{{  Read the events header and array*/
    /* We handle errors through setting errormessage, because we want to continue
     * with a warning if we are in continuous mode or read from an event file */
    TEEG TagType;
    EVENT2 event;
    TRACEMS(tinfo->emethods, 1, "read_synamps_build_trigbuffer: Reading event table\n");
    fseek(local_arg->SCAN,local_arg->EEG.EventTablePos,SEEK_SET);
    /* Here we face two evils in one header: Coding enums as chars and
     * allowing longs at odd addresses. Well... */
    if (read_struct((char *)&TagType, sm_TEEG, local_arg->SCAN)==1) {
#    ifndef LITTLE_ENDIAN
     change_byteorder((char *)&TagType, sm_TEEG);
#    endif
     if (TagType.Teeg==TEEG_EVENT_TAB1 || TagType.Teeg==TEEG_EVENT_TAB2) {
      /*{{{  Read the event table*/
      struct_member * const sm_EVENT=(TagType.Teeg==TEEG_EVENT_TAB1 ? sm_EVENT1 : sm_EVENT2);
      int ntags, tag;

      ntags=TagType.Size/sm_EVENT[0].offset;	/* sm_EVENT[0].offset is the size of the structure in file. */
      for (tag=0; tag<ntags; tag++) {
       long trigger_position=0;
       int TrigVal=0, KeyPad=0, KeyBoard=0;
       enum NEUROSCAN_ACCEPTVALUES Accept=(enum NEUROSCAN_ACCEPTVALUES)0;
       if (read_struct((char *)&event, sm_EVENT, local_arg->SCAN)==0) {
	ERREXIT(tinfo->emethods, "read_synamps_build_trigbuffer: Can't read an event table entry.\n");
	break;
       }
#      ifndef LITTLE_ENDIAN
       change_byteorder((char *)&event, sm_EVENT);
#      endif
       trigger_position=offset2point(tinfo,event.Offset);
       TrigVal=event.StimType &0xff;
       KeyBoard=event.KeyBoard&0xf;
       KeyPad=Event_KeyPad_value(event);
       Accept=Event_Accept_value(event);
       if (!args[ARGS_NOREJECTED].is_set || Accept!=NAV_REJECT) {
	read_synamps_push_keys(tinfo, trigger_position, TrigVal, KeyPad, KeyBoard, Accept);
       }
      }
      /*}}}  */
     } else {
      ERREXIT1(tinfo->emethods, "read_synamps_build_trigbuffer: Unknown tag type %d.\n", MSGPARM(TagType.Teeg));
     }
    } else {
     ERREXIT(tinfo->emethods, "read_synamps_build_trigbuffer: Can't read the event table header.\n");
    }
    /*}}}  */
    }
    break;
   case NST_CONT0: {
    /*{{{  CONT0: Two trailing marker channels*/
    long current_triggerpoint=0;
    unsigned short *pdata;
    TRACEMS(tinfo->emethods, 1, "read_synamps_build_trigbuffer: Analyzing CONT0 marker channels\n");
    while (current_triggerpoint<local_arg->EEG.NumSamples) {
     int TrigVal=0, KeyPad=0, KeyBoard=0;
     enum NEUROSCAN_ACCEPTVALUES Accept=(enum NEUROSCAN_ACCEPTVALUES)0;
     read_synamps_seek_point(tinfo, current_triggerpoint);
     pdata=(unsigned short *)local_arg->buffer+current_triggerpoint-local_arg->first_point_in_buffer+local_arg->nchannels;
     TrigVal =pdata[0]&0xff; 
     KeyBoard=pdata[1]&0xf; if (KeyBoard>13) KeyBoard=0;
     if (TrigVal!=0 || KeyBoard!=0) {
      read_synamps_push_keys(tinfo, current_triggerpoint, TrigVal, KeyPad, KeyBoard, Accept);
      current_triggerpoint++;
      while (current_triggerpoint<local_arg->EEG.NumSamples) {
       int This_TrigVal, This_KeyBoard;
       read_synamps_seek_point(tinfo, current_triggerpoint);
       pdata=(unsigned short *)local_arg->buffer+current_triggerpoint-local_arg->first_point_in_buffer+local_arg->nchannels;
       This_TrigVal =pdata[0]&0xff; 
       This_KeyBoard=pdata[1]&0xf; if (This_KeyBoard>13) This_KeyBoard=0;
       if (This_TrigVal!=TrigVal || This_KeyBoard!=KeyBoard) break;
       current_triggerpoint++;
      }
     }
    }
    /*}}}  */
    }
    break;
   case NST_DCMES: { 
    /*{{{  DC-MES: Single, leading marker channel*/
    long current_triggerpoint=0;
    unsigned short *pdata;
    TRACEMS(tinfo->emethods, 1, "read_synamps_build_trigbuffer: Analyzing DCMES marker channel\n");
    while (current_triggerpoint<local_arg->EEG.NumSamples) {
     int TrigVal=0, KeyPad=0, KeyBoard=0;
     enum NEUROSCAN_ACCEPTVALUES Accept=(enum NEUROSCAN_ACCEPTVALUES)0;
     read_synamps_seek_point(tinfo, current_triggerpoint);
     pdata=(unsigned short *)local_arg->buffer+current_triggerpoint-local_arg->first_point_in_buffer;
     TrigVal= *pdata&0xff; 
     KeyBoard=(*pdata>>8)&0xf; if (KeyBoard>13) KeyBoard=0;
     if (TrigVal!=0 || KeyBoard!=0) {
      read_synamps_push_keys(tinfo, current_triggerpoint, TrigVal, KeyPad, KeyBoard, Accept);
      current_triggerpoint++;
      while (current_triggerpoint<local_arg->EEG.NumSamples) {
       int This_TrigVal, This_KeyBoard;
       read_synamps_seek_point(tinfo, current_triggerpoint);
       pdata=(unsigned short *)local_arg->buffer+current_triggerpoint-local_arg->first_point_in_buffer;
       This_TrigVal= *pdata&0xff; 
       This_KeyBoard=(*pdata>>8)&0xf; if (This_KeyBoard>13) This_KeyBoard=0;
       if (This_TrigVal!=TrigVal || This_KeyBoard!=KeyBoard) break;
       current_triggerpoint++;
      }
     }
    }
    /*}}}  */
    }
    break;
   default:
    break;
  }
 }
예제 #14
0
/*{{{  write_synamps_init(transform_info_ptr tinfo) {*/
METHODDEF void
write_synamps_init(transform_info_ptr tinfo) {
 struct write_synamps_storage *local_arg=(struct write_synamps_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 double xmin, xmax, ymin, ymax;
 int NoOfChannels=tinfo->nr_of_channels;
 int channel;

 growing_buf_init(&local_arg->triggers);
 local_arg->output_format=(args[ARGS_OUTPUTFORMAT].is_set ? (enum output_formats)args[ARGS_OUTPUTFORMAT].arg.i : FORMAT_EEGFILE);
 local_arg->SCAN=fopen(args[ARGS_OFILE].arg.s, "r+b");
 if (!args[ARGS_APPEND].is_set || local_arg->SCAN==NULL) {   /* target does not exist*/
 /*{{{  Create file*/
 if (local_arg->SCAN!=NULL) fclose(local_arg->SCAN);
 /*{{{  Calculate the span in x-y channel positions*/
 xmin=ymin=  FLT_MAX; 
 xmax=ymax= -FLT_MAX; 
 for (channel=0; channel<tinfo->nr_of_channels; channel++) {
  const double this_x=tinfo->probepos[3*channel], this_y=tinfo->probepos[3*channel+1];
  if (this_x>xmax) xmax=this_x;
  if (this_x<xmin) xmin=this_x;
  if (this_y>ymax) ymax=this_y;
  if (this_y<ymin) ymin=this_y;
 }
 if (xmax==xmin) {
  xmax+=0.5;
  xmin-=0.5;
 }
 if (ymax==ymin) {
  ymax+=0.5;
  ymin-=0.5;
 }
 /*}}}  */

 if ((local_arg->SCAN=fopen(args[ARGS_OFILE].arg.s, "wb"))==NULL) {
  ERREXIT1(tinfo->emethods, "write_synamps_init: Can't open %s\n", MSGPARM(args[ARGS_OFILE].arg.s));
 }
 /*{{{  Many settings, taken from example files...*/
 strcpy(local_arg->EEG.rev, "Version 3.0");
 local_arg->EEG.AdditionalFiles=local_arg->EEG.NextFile=local_arg->EEG.PrevFile=0;
 switch (local_arg->output_format) {
  case FORMAT_EEGFILE:
   local_arg->EEG.review = 1;
   local_arg->EEG.savemode=NSM_EEGF;
   local_arg->EEG.type = NTY_EPOCHED;
   local_arg->EEG.ContinousType=0;
   local_arg->EEG.nsweeps=local_arg->EEG.compsweeps=local_arg->EEG.acceptcnt=0;
   break;
  case FORMAT_CNTFILE:
   local_arg->EEG.review = 1;
   local_arg->EEG.savemode=NSM_CONT;
   local_arg->EEG.type = 0;
   local_arg->EEG.ContinousType=NST_SYNAMPS-NST_CONT0;
   local_arg->EEG.nsweeps=1;
   local_arg->EEG.compsweeps=local_arg->EEG.acceptcnt=0;
   break;
  case FORMAT_AVGFILE:
   local_arg->EEG.review = 0;
   local_arg->EEG.savemode=NSM_AVGD;
   local_arg->EEG.type = NTY_AVERAGED;
   local_arg->EEG.ContinousType=0;
   local_arg->EEG.nsweeps=local_arg->EEG.compsweeps=local_arg->EEG.acceptcnt=(tinfo->nrofaverages>0 ? tinfo->nrofaverages : 1);
   break;
 }
 /* Since the comment can be of arbitrary length and thus also larger than the
  * rest of the header, we should limit ourselves to the size of the id field */
 strncpy(local_arg->EEG.id, tinfo->comment, sizeof(local_arg->EEG.id));
 /* The date is coded in the comment, and read_synamps appends the date and time
  * from the corresponding fields and the contents of the id field, so that
  * the comment2time reader could be confused by the two date/time fields if we
  * would not somehow invalidate remnants of the date field here... */
 {char *slash;
  while ((slash=strchr(local_arg->EEG.id, '/'))!=NULL) {
   *slash='|';
  }
 }
 strcpy(local_arg->EEG.oper, "Unspecified");
 strcpy(local_arg->EEG.doctor, "Unspecified");
 strcpy(local_arg->EEG.referral, "Unspecified");
 strcpy(local_arg->EEG.hospital, "Unspecified");
 strcpy(local_arg->EEG.patient, "Unspecified");
 local_arg->EEG.age = 0;
 local_arg->EEG.sex = 'U';
 local_arg->EEG.hand = 'U';
 strcpy(local_arg->EEG.med, "Unspecified");
 strcpy(local_arg->EEG.category, "Unspecified");
 strcpy(local_arg->EEG.state, "Unspecified");
 strcpy(local_arg->EEG.label, "Unspecified");
 {short dd, mm, yy, yyyy, hh, mi, ss;
 if (comment2time(tinfo->comment, &dd, &mm, &yy, &yyyy, &hh, &mi, &ss)) {
  char buffer[16]; /* Must be long enough to fit date (10) and time (12) +1 */
  /* This is necessary because the date field was devised for 2-digit years.
   * With 4-digit years it uses all 10 bytes and the trailing zero
   * does not fit in any more. */
  snprintf(buffer, 16, "%02d/%02d/%04d", mm, dd, yyyy);
  strncpy(local_arg->EEG.date, buffer, sizeof(local_arg->EEG.date));
  snprintf(buffer, 16, "%02d:%02d:%02d", hh, mi, ss);
  strncpy(local_arg->EEG.time, buffer, sizeof(local_arg->EEG.time));
 }
 }
 local_arg->EEG.rejectcnt = 0;
 local_arg->EEG.pnts=(tinfo->data_type==FREQ_DATA ? tinfo->nroffreq : tinfo->nr_of_points);
 local_arg->EEG.nchannels=NoOfChannels;
 local_arg->EEG.avgupdate=1;
 local_arg->EEG.domain=(tinfo->data_type==FREQ_DATA ? 1 : 0);
 local_arg->EEG.variance=0;
 local_arg->EEG.rate=(uint16_t)rint(tinfo->sfreq);
 if (tinfo->data_type==FREQ_DATA) {
  /* I know that this field is supposed to contain the taper window size in %,
     but we need some way to store basefreq and 'rate' is only integer... */
  local_arg->EEG.SpectWinLength=tinfo->basefreq;
 }
 if (local_arg->EEG.rate==0) {
  local_arg->EEG.rate=1;
  TRACEMS(tinfo->emethods, 0, "write_synamps_init: Rate was zero, corrected to 1!\n");
 }
 local_arg->EEG.scale=3.4375;	/* This is a common sensitivity factor, used if sensitivities for channels are zero */
 local_arg->EEG.veogcorrect=0;
 local_arg->EEG.heogcorrect=0;
 local_arg->EEG.aux1correct=0;
 local_arg->EEG.aux2correct=0;
 local_arg->EEG.veogtrig=15;	/* Trigger threshold in percent of the maximum */
 local_arg->EEG.heogtrig=10;
 local_arg->EEG.aux1trig=10;
 local_arg->EEG.aux2trig=10;
 local_arg->EEG.veogchnl=find_channel_number(tinfo, "VEOG");
 local_arg->EEG.heogchnl=find_channel_number(tinfo, "HEOG");
 local_arg->EEG.veogdir=0;	/* 0=positive, 1=negative */
 local_arg->EEG.veog_n=10;	/* "Number of points per waveform", really: minimum acceptable # averages */
 local_arg->EEG.heog_n=10;
 local_arg->EEG.veogmaxcnt=(int16_t)rint(0.3*tinfo->sfreq);	/* "Number of observations per point", really: event window size in points */
 local_arg->EEG.heogmaxcnt=(int16_t)rint(0.5*tinfo->sfreq);
 local_arg->EEG.AmpSensitivity=10;	/* External Amplifier gain */
 local_arg->EEG.baseline=0;
 local_arg->EEG.reject=0;
 local_arg->EEG.trigtype=2;	/* 2=Port */
 local_arg->EEG.trigval=255;	/* Hold */
 local_arg->EEG.dir=0;	/* Invert (negative up)=0 */
 local_arg->EEG.dispmin= -1;	/* displayed y range */
 local_arg->EEG.dispmax= +1;
 local_arg->EEG.DisplayXmin=local_arg->EEG.AutoMin=local_arg->EEG.rejstart=local_arg->EEG.offstart=local_arg->EEG.xmin= -tinfo->beforetrig/tinfo->sfreq;
 local_arg->EEG.DisplayXmax=local_arg->EEG.AutoMax=local_arg->EEG.rejstop=local_arg->EEG.offstop=local_arg->EEG.xmax= tinfo->aftertrig/tinfo->sfreq;
 local_arg->EEG.zmin=0.0;
 local_arg->EEG.zmax=0.1;
 strcpy(local_arg->EEG.ref, "A1-A2");
 strcpy(local_arg->EEG.screen,   "--------");
 local_arg->EEG.CalMode=2;
 local_arg->EEG.CalMethod=0;
 local_arg->EEG.CalUpdate=1;
 local_arg->EEG.CalBaseline=0;
 local_arg->EEG.CalSweeps=5;
 local_arg->EEG.CalAttenuator=1;
 local_arg->EEG.CalPulseVolt=1;
 local_arg->EEG.CalPulseStart=0;
 local_arg->EEG.CalPulseStop=0;
 local_arg->EEG.CalFreq=10;
 strcpy(local_arg->EEG.taskfile, "--------");
 strcpy(local_arg->EEG.seqfile,  "--------");	/* Otherwise tries to read a seqfile */
 local_arg->EEG.HeadGain=150;
 local_arg->EEG.FspFValue=2.5;
 local_arg->EEG.FspBlockSize=200;
 local_arg->EEG.fratio=1.0;
 local_arg->EEG.minor_rev=12;	/* Necessary ! Otherwise a different file structure is assumed... */
 local_arg->EEG.eegupdate=1;

 local_arg->EEG.xscale=local_arg->EEG.yscale=0;
 local_arg->EEG.xsize=40;
 local_arg->EEG.ysize=20;
 local_arg->EEG.ACmode=0;

 local_arg->EEG.XScaleValue=XSCALEVALUE;
 local_arg->EEG.XScaleInterval=XSCALEINTERVAL;
 local_arg->EEG.YScaleValue=YSCALEVALUE;
 local_arg->EEG.YScaleInterval=YSCALEINTERVAL;

 local_arg->EEG.ScaleToolX1=20;
 local_arg->EEG.ScaleToolY1=170;
 local_arg->EEG.ScaleToolX2=23.1535;
 local_arg->EEG.ScaleToolY2=153.87;

 local_arg->EEG.port=715;
 local_arg->EEG.NumSamples=0;
 local_arg->EEG.FilterFlag=0;
 local_arg->EEG.LowCutoff=4;
 local_arg->EEG.LowPoles=2;
 local_arg->EEG.HighCutoff=50;
 local_arg->EEG.HighPoles=2;
 local_arg->EEG.FilterType=3;
 local_arg->EEG.FilterDomain=1;
 local_arg->EEG.SnrFlag=0;
 local_arg->EEG.CoherenceFlag=0;
 local_arg->EEG.ContinousSeconds=4;
 local_arg->EEG.ChannelOffset=sizeof(int16_t);
 local_arg->EEG.AutoCorrectFlag=0;
 local_arg->EEG.DCThreshold='F';
 /*}}}  */
 /*{{{  Write SETUP structure*/
# ifndef LITTLE_ENDIAN
 change_byteorder((char *)&local_arg->EEG, sm_SETUP);
# endif
 write_struct((char *)&local_arg->EEG, sm_SETUP, local_arg->SCAN);
# ifndef LITTLE_ENDIAN
 change_byteorder((char *)&local_arg->EEG, sm_SETUP);
# endif
 /*}}}  */

 if ((local_arg->Channels=(ELECTLOC *)calloc(NoOfChannels,sizeof(ELECTLOC)))==NULL) {
  ERREXIT(tinfo->emethods, "write_synamps_init: Error allocating Channels list\n");
 }
 for (channel=0; channel<NoOfChannels; channel++) {
  /*{{{  Settings in the channel structure*/
  strncpy(local_arg->Channels[channel].lab, tinfo->channelnames[channel],sizeof(local_arg->Channels[channel].lab));
  local_arg->Channels[channel].reference=0;
  local_arg->Channels[channel].skip=0;
  local_arg->Channels[channel].reject=0;
  local_arg->Channels[channel].display=1;
  local_arg->Channels[channel].bad=0;
  local_arg->Channels[channel].n=(local_arg->output_format==FORMAT_AVGFILE ? local_arg->EEG.acceptcnt : (local_arg->output_format==FORMAT_CNTFILE ? 0 : 1));
  local_arg->Channels[channel].avg_reference=0;
  local_arg->Channels[channel].ClipAdd=0;
  local_arg->Channels[channel].x_coord= (tinfo->probepos[3*channel  ]-xmin)/(xmax-xmin)*RANGE_TO_COVER+XOFFSET;
  local_arg->Channels[channel].y_coord=((ymax-tinfo->probepos[3*channel+1])/(ymax-ymin)*RANGE_TO_COVER+YOFFSET)/3;
  local_arg->Channels[channel].veog_wt=0;
  local_arg->Channels[channel].veog_std=0;
  local_arg->Channels[channel].heog_wt=0;
  local_arg->Channels[channel].heog_std=0;
  local_arg->Channels[channel].baseline=0;
  local_arg->Channels[channel].Filtered=0;
  local_arg->Channels[channel].sensitivity=204.8/args[ARGS_CONVFACTOR].arg.d; /* This arranges for conv_factor to act as the expected product before integer truncation */
  local_arg->Channels[channel].Gain=5;
  local_arg->Channels[channel].HiPass=0;	/* 0=DC */
  local_arg->Channels[channel].LoPass=4;
  local_arg->Channels[channel].Page=0;
  local_arg->Channels[channel].Size=0;
  local_arg->Channels[channel].Impedance=0;
  local_arg->Channels[channel].PhysicalChnl=channel;	/* Channel mapping */
  local_arg->Channels[channel].Rectify=0;
  local_arg->Channels[channel].calib=1.0;
  /*}}}  */
  /*{{{  Write ELECTLOC struct*/
#  ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->Channels[channel], sm_ELECTLOC);
#  endif
  write_struct((char *)&local_arg->Channels[channel], sm_ELECTLOC, local_arg->SCAN);
#  ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->Channels[channel], sm_ELECTLOC);
#  endif
  /*}}}  */
 }
 local_arg->SizeofHeader = ftell(local_arg->SCAN);
 TRACEMS2(tinfo->emethods, 1, "write_synamps_init: Creating file %s, format `%s'\n", MSGPARM(args[ARGS_OFILE].arg.s), MSGPARM(neuroscan_subtype_names[NEUROSCAN_SUBTYPE(&local_arg->EEG)]));
 /*}}}  */
 } else {
  /*{{{  Append to file*/
  enum NEUROSCAN_SUBTYPES SubType;
  if (read_struct((char *)&local_arg->EEG, sm_SETUP, local_arg->SCAN)==0) {
   ERREXIT(tinfo->emethods, "write_synamps_init: Can't read file header.\n");
  }
#  ifndef LITTLE_ENDIAN
  change_byteorder((char *)&local_arg->EEG, sm_SETUP);
#  endif
  NoOfChannels = local_arg->EEG.nchannels;
  /*{{{  Allocate channel header*/
  if ((local_arg->Channels=(ELECTLOC *)malloc(NoOfChannels*sizeof(ELECTLOC)))==NULL) {
   ERREXIT(tinfo->emethods, "write_synamps_init: Error allocating Channels list\n");
  }
  /*}}}  */
  for (channel=0; channel<NoOfChannels; channel++) {
   if (read_struct((char *)&local_arg->Channels[channel], sm_ELECTLOC, local_arg->SCAN)==0) {
    ERREXIT(tinfo->emethods, "write_synamps_init: Can't read channel headers.\n");
   }
#  ifndef LITTLE_ENDIAN
   change_byteorder((char *)&local_arg->Channels[channel], sm_ELECTLOC);
#  endif
  }
  local_arg->SizeofHeader = ftell(local_arg->SCAN);
  SubType=NEUROSCAN_SUBTYPE(&local_arg->EEG);
  switch (SubType) {
   case NST_EPOCHS:
    if (local_arg->output_format!=FORMAT_EEGFILE) {
     TRACEMS(tinfo->emethods, 0, "write_synamps_init: Appending to epoch file, discarding option -c\n");
     local_arg->output_format=FORMAT_EEGFILE;
    }
    fseek(local_arg->SCAN, 0, SEEK_END);
    break;
   case NST_CONTINUOUS:
   case NST_SYNAMPS: {
    TEEG TagType;
    EVENT1 event;
    if (local_arg->output_format!=FORMAT_CNTFILE) {
     TRACEMS(tinfo->emethods, 0, "write_synamps_init: Appending to continuous file, assuming option -c\n");
     local_arg->output_format=FORMAT_CNTFILE;
    }
    fseek(local_arg->SCAN, local_arg->EEG.EventTablePos, SEEK_SET);
    /* Here we face two evils in one header: Coding enums as chars and
     * allowing longs at odd addresses. Well... */
    if (1==read_struct((char *)&TagType, sm_TEEG, local_arg->SCAN)) {
#    ifndef LITTLE_ENDIAN
     change_byteorder((char *)&TagType, sm_TEEG);
#    endif
     if (TagType.Teeg==TEEG_EVENT_TAB1) {
      /*{{{  Read the event table*/
      int tag;
      int const ntags=TagType.Size/sm_EVENT1[0].offset;	/* sm_EVENT1[0].offset is sizeof(EVENT1) in the file. */
      for (tag=0; tag<ntags; tag++) {
       if (1!=read_struct((char *)&event, sm_EVENT1, local_arg->SCAN)) {
	ERREXIT(tinfo->emethods, "write_synamps_init: Can't read an event table entry.\n");
	break;
       }
#      ifndef LITTLE_ENDIAN
       change_byteorder((char *)&event, sm_EVENT1);
#      endif
       {
       int const TrigVal=event.StimType &0xff;
       int const KeyBoard=event.KeyBoard&0xf;
       int const KeyPad=Event_KeyPad_value(event);
       int const Accept=Event_Accept_value(event);
       int code=TrigVal-KeyPad+neuroscan_accept_translation[Accept];
       if (code==0) {
        code= -((KeyBoard+1)<<4);
       }
       push_trigger(&local_arg->triggers,offset2point(tinfo, event.Offset),code,NULL);
       }
      }
      /*}}}  */
     } else {
      ERREXIT(tinfo->emethods, "write_synamps_init: Type 2 events are not yet supported.\n");
     }
    } else {
     ERREXIT(tinfo->emethods, "write_synamps_init: Can't read the event table header.\n");
    }
    fseek(local_arg->SCAN, local_arg->EEG.EventTablePos, SEEK_SET);
    }
    break;
   default:
    ERREXIT1(tinfo->emethods, "write_synamps: Cannot append to file type `%s'\n", MSGPARM(neuroscan_subtype_names[SubType]));
    break;
  }
  /* Conformance to the incoming epochs is checked in write_synamps */
  TRACEMS1(tinfo->emethods, 1, "write_synamps_init: Appending to file %s\n", MSGPARM(args[ARGS_OFILE].arg.s));
  /*}}}  */
 }

 tinfo->methods->init_done=TRUE;
}
예제 #15
0
jinit_downsampler( j_compress_ptr cinfo )
{
	my_downsample_ptr downsample;
	int ci;
	jpeg_component_info *compptr;
	boolean smoothok = TRUE;
	int h_in_group, v_in_group, h_out_group, v_out_group;
	
	downsample = ( my_downsample_ptr )
				 ( *cinfo->mem->alloc_small )( ( j_common_ptr ) cinfo, JPOOL_IMAGE,
						 SIZEOF( my_downsampler ) );
	cinfo->downsample = ( struct jpeg_downsampler * ) downsample;
	downsample->pub.start_pass = start_pass_downsample;
	downsample->pub.downsample = sep_downsample;
	downsample->pub.need_context_rows = FALSE;
	
	if( cinfo->CCIR601_sampling )
	{
		ERREXIT( cinfo, JERR_CCIR601_NOTIMPL );
	}
	
	/* Verify we can handle the sampling factors, and set up method pointers */
	for( ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
			ci++, compptr++ )
	{
		/* Compute size of an "output group" for DCT scaling.  This many samples
		 * are to be converted from max_h_samp_factor * max_v_samp_factor pixels.
		 */
		h_out_group = ( compptr->h_samp_factor * compptr->DCT_h_scaled_size ) /
					  cinfo->min_DCT_h_scaled_size;
		v_out_group = ( compptr->v_samp_factor * compptr->DCT_v_scaled_size ) /
					  cinfo->min_DCT_v_scaled_size;
		h_in_group = cinfo->max_h_samp_factor;
		v_in_group = cinfo->max_v_samp_factor;
		downsample->rowgroup_height[ci] = v_out_group; /* save for use later */
		if( h_in_group == h_out_group && v_in_group == v_out_group )
		{
#ifdef INPUT_SMOOTHING_SUPPORTED
			if( cinfo->smoothing_factor )
			{
				downsample->methods[ci] = fullsize_smooth_downsample;
				downsample->pub.need_context_rows = TRUE;
			}
			else
#endif
				downsample->methods[ci] = fullsize_downsample;
		}
		else if( h_in_group == h_out_group * 2 &&
				 v_in_group == v_out_group )
		{
			smoothok = FALSE;
			downsample->methods[ci] = h2v1_downsample;
		}
		else if( h_in_group == h_out_group * 2 &&
				 v_in_group == v_out_group * 2 )
		{
#ifdef INPUT_SMOOTHING_SUPPORTED
			if( cinfo->smoothing_factor )
			{
				downsample->methods[ci] = h2v2_smooth_downsample;
				downsample->pub.need_context_rows = TRUE;
			}
			else
#endif
				downsample->methods[ci] = h2v2_downsample;
		}
		else if( ( h_in_group % h_out_group ) == 0 &&
				 ( v_in_group % v_out_group ) == 0 )
		{
			smoothok = FALSE;
			downsample->methods[ci] = int_downsample;
			downsample->h_expand[ci] = ( UINT8 )( h_in_group / h_out_group );
			downsample->v_expand[ci] = ( UINT8 )( v_in_group / v_out_group );
		}
		else
		{
			ERREXIT( cinfo, JERR_FRACT_SAMPLE_NOTIMPL );
		}
	}
	
#ifdef INPUT_SMOOTHING_SUPPORTED
	if( cinfo->smoothing_factor && !smoothok )
	{
		TRACEMS( cinfo, 0, JTRC_SMOOTH_NOTIMPL );
	}
#endif
}
예제 #16
0
GLOBAL void
jinit_downsampler(j_compress_ptr cinfo)
{
	my_downsample_ptr downsample;
	int ci;
	jpeg_component_info *compptr;
	boolean smoothok = TRUE;

	downsample = (my_downsample_ptr)
	             (*cinfo->mem->alloc_small)((j_common_ptr) cinfo, JPOOL_IMAGE,
	                                        SIZEOF(my_downsampler));
	cinfo->downsample = (struct jpeg_downsampler *) downsample;
	downsample->pub.start_pass = start_pass_downsample;
	downsample->pub.downsample = sep_downsample;
	downsample->pub.need_context_rows = FALSE;

	if(cinfo->CCIR601_sampling)
	{
		ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
	}

	/* Verify we can handle the sampling factors, and set up method pointers */
	for(ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
	        ci++, compptr++)
	{
		if(compptr->h_samp_factor == cinfo->max_h_samp_factor &&
		        compptr->v_samp_factor == cinfo->max_v_samp_factor)
		{
#ifdef INPUT_SMOOTHING_SUPPORTED

			if(cinfo->smoothing_factor)
			{
				downsample->methods[ci] = fullsize_smooth_downsample;
				downsample->pub.need_context_rows = TRUE;
			}
			else
#endif
				downsample->methods[ci] = fullsize_downsample;
		}
		else if(compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
		        compptr->v_samp_factor == cinfo->max_v_samp_factor)
		{
			smoothok = FALSE;
			downsample->methods[ci] = h2v1_downsample;
		}
		else if(compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
		        compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor)
		{
#ifdef INPUT_SMOOTHING_SUPPORTED

			if(cinfo->smoothing_factor)
			{
				downsample->methods[ci] = h2v2_smooth_downsample;
				downsample->pub.need_context_rows = TRUE;
			}
			else
#endif
				downsample->methods[ci] = h2v2_downsample;
		}
		else if((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
		        (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0)
		{
			smoothok = FALSE;
			downsample->methods[ci] = int_downsample;
		}
		else
		{
			ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
		}
	}

#ifdef INPUT_SMOOTHING_SUPPORTED

	if(cinfo->smoothing_factor && !smoothok)
	{
		TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
	}

#endif
}
예제 #17
0
/*{{{  write_vitaport_exit(transform_info_ptr tinfo) {*/
METHODDEF void
write_vitaport_exit(transform_info_ptr tinfo) {
    struct write_vitaport_storage *local_arg=(struct write_vitaport_storage *)tinfo->methods->local_storage;
    int channel, NoOfChannels=local_arg->fileheader.knum;
    long point;
    long const channellen=local_arg->total_points*sizeof(uint16_t);
    long const hdlen=local_arg->fileheader.hdlen;
    uint16_t checksum=0;

    local_arg->fileheaderII.dlen=hdlen+NoOfChannels*channellen;
    /*{{{  Write the file headers*/
# ifdef LITTLE_ENDIAN
    change_byteorder((char *)&local_arg->fileheader, sm_vitaport_fileheader);
    change_byteorder((char *)&local_arg->fileheaderII, sm_vitaportII_fileheader);
    change_byteorder((char *)&local_arg->fileext, sm_vitaportII_fileext);
# endif
    write_struct((char *)&local_arg->fileheader, sm_vitaport_fileheader, local_arg->outfile);
    write_struct((char *)&local_arg->fileheaderII, sm_vitaportII_fileheader, local_arg->outfile);
    write_struct((char *)&local_arg->fileext, sm_vitaportII_fileext, local_arg->outfile);
    /*}}}  */

    for (channel=0; channel<NoOfChannels; channel++) {
        /*{{{  Write a channel header*/
        /* This is the factor as we'd like to have it... */
        float factor=((float)(local_arg->channelmax[channel]> -local_arg->channelmin[channel] ? local_arg->channelmax[channel] : -local_arg->channelmin[channel]))/SHRT_MAX;

        if (strncmp(local_arg->channelheaders[channel].kname, VP_MARKERCHANNEL_NAME, 6)==0) {
            strcpy(local_arg->channelheaders[channel].kunit, "mrk");
            local_arg->channelheaders[channel].datype=VP_DATYPE_MARKER;
            /* Since the marker channel is read without the conversion factors,
             * set the conversion to 1.0 for this channel */
            local_arg->channelheaders[channel].mulfac=local_arg->channelheaders[channel].divfac=1;
            local_arg->channelheaders[channel].offset=0;
        } else {
            float const logdiff=log(factor)-TARGET_LOG_SHORTVAL;

            local_arg->channelheaders[channel].offset=0;
            if (logdiff<0) {
                /*{{{  Factor is small: Better to fix divfac and calculate mulfac after that*/
                double const divfac=exp(-logdiff);
                if (divfac>SHRT_MAX) {
                    local_arg->channelheaders[channel].divfac=SHRT_MAX;
                } else {
                    local_arg->channelheaders[channel].divfac=(unsigned short)divfac;
                }
                /* The +1 takes care that we never get below the `ideal' factor computed above. */
                local_arg->channelheaders[channel].mulfac=(unsigned short)(factor*local_arg->channelheaders[channel].divfac+1);
                if (local_arg->channelheaders[channel].mulfac==0) {
                    local_arg->channelheaders[channel].mulfac=1;
                    local_arg->channelheaders[channel].divfac=(unsigned short)(1.0/factor-1);
                }
                /*}}}  */
            } else {
                /*{{{  Factor is large: Better to fix mulfac and calculate divfac after that*/
                double const mulfac=exp(logdiff);
                if (mulfac>SHRT_MAX) {
                    local_arg->channelheaders[channel].mulfac=SHRT_MAX;
                } else {
                    local_arg->channelheaders[channel].mulfac=(unsigned short)mulfac;
                }
                /* The -1 takes care that we never get below the `ideal' factor computed above. */
                local_arg->channelheaders[channel].divfac=(unsigned short)(local_arg->channelheaders[channel].mulfac/factor-1);
                if (local_arg->channelheaders[channel].divfac==0) {
                    local_arg->channelheaders[channel].mulfac=(unsigned short)(factor+1);
                    local_arg->channelheaders[channel].divfac=1;
                }
                /*}}}  */
            }
        }
        /* Now see which factor we actually got constructed */
        factor=((float)local_arg->channelheaders[channel].mulfac)/local_arg->channelheaders[channel].divfac;

        local_arg->channelheadersII[channel].doffs=channel*channellen;
        local_arg->channelheadersII[channel].dlen=channellen;
#  ifdef LITTLE_ENDIAN
        change_byteorder((char *)&local_arg->channelheaders[channel], sm_vitaport_channelheader);
        change_byteorder((char *)&local_arg->channelheadersII[channel], sm_vitaportIIrchannelheader);
#  endif
        write_struct((char *)&local_arg->channelheaders[channel], sm_vitaport_channelheader, local_arg->outfile);
        write_struct((char *)&local_arg->channelheadersII[channel], sm_vitaportIIrchannelheader, local_arg->outfile);
#  ifdef LITTLE_ENDIAN
        change_byteorder((char *)&local_arg->channelheaders[channel], sm_vitaport_channelheader);
        change_byteorder((char *)&local_arg->channelheadersII[channel], sm_vitaportIIrchannelheader);
#  endif
        /*}}}  */
    }
    fwrite(&checksum, sizeof(checksum), 1, local_arg->outfile);

    TRACEMS(tinfo->emethods, 1, "write_vitaport_exit: Copying channels to output file...\n");

    /* We close and re-open the channel file because buffering is much more
     * efficient at least with DJGPP if the file is either only read or written */
    fclose(local_arg->channelfile);
    if ((local_arg->channelfile=fopen(local_arg->channelfilename, "rb"))==NULL) {
        ERREXIT1(tinfo->emethods, "write_vitaport_exit: Can't open temp file %s\n", MSGPARM(local_arg->channelfilename));
    }

    for (channel=0; channel<NoOfChannels; channel++) {
        /*{{{  Copy a channel to the target file */
        float const factor=((float)local_arg->channelheaders[channel].mulfac)/local_arg->channelheaders[channel].divfac;
        unsigned short const offset=local_arg->channelheaders[channel].offset;

        for (point=0; point<local_arg->total_points; point++) {
            DATATYPE dat;
            int16_t s;
            fseek(local_arg->channelfile, (point*NoOfChannels+channel)*sizeof(DATATYPE), SEEK_SET);
            if (fread(&dat, sizeof(DATATYPE), 1, local_arg->channelfile)!=1) {
                ERREXIT(tinfo->emethods, "write_vitaport_exit: Error reading temp file.\n");
            }
            s= (int16_t)rint(dat/factor)-offset;
#   ifdef LITTLE_ENDIAN
            Intel_int16((uint16_t *)&s);
#   endif
            if (fwrite(&s, sizeof(s), 1, local_arg->outfile)!=1) {
                ERREXIT(tinfo->emethods, "write_vitaport_exit: Write error.\n");
            }
        }
        /*}}}  */
    }
    fclose(local_arg->channelfile);
    unlink(local_arg->channelfilename);

    if (local_arg->triggers.current_length!=0) {
        long tagno, n_events;
        uint32_t length, trigpoint;
        int const nevents=local_arg->triggers.current_length/sizeof(struct trigger);
        struct vitaport_idiotic_multiplemarkertablenames *markertable_entry;

        /* Try to keep a security space of at least 20 free events */
        for (markertable_entry=markertable_names; markertable_entry->markertable_name!=NULL && markertable_entry->idiotically_fixed_length<nevents+20; markertable_entry++);
        if (markertable_entry->markertable_name==NULL) {
            if ((markertable_entry-1)->idiotically_fixed_length<=nevents) {
                /* Drop the requirement for at least 20 free events */
                markertable_entry--;
            } else {
                /* No use... */
                ERREXIT1(tinfo->emethods, "write_vitaport_exit: %d events wouldn't fit into the fixed-length VITAGRAPH marker tables!\nBlame the Vitaport people!\n", MSGPARM(nevents));
            }
        }
        n_events=markertable_entry->idiotically_fixed_length;

        fwrite(markertable_entry->markertable_name, 1, VP_TABLEVAR_LENGTH, local_arg->outfile);
        length=n_events*sizeof(length);
#ifdef LITTLE_ENDIAN
        Intel_int32((uint32_t *)&length);
#endif
        fwrite(&length, sizeof(length), 1, local_arg->outfile);
        for (tagno=0; tagno<n_events; tagno++) {
            if (tagno<nevents) {
                struct trigger * const intrig=((struct trigger *)local_arg->triggers.buffer_start)+tagno;
                /* Trigger positions are given in ms units */
                trigpoint=(long)rint(intrig->position*1000.0/local_arg->sfreq);
                /* Make trigpoint uneven if code%2==1 */
                trigpoint=trigpoint-trigpoint%2+(intrig->code-1)%2;
            } else {
                trigpoint= -1;
            }
#ifdef LITTLE_ENDIAN
            Intel_int32((uint32_t *)&trigpoint);
#endif
            fwrite(&trigpoint, sizeof(trigpoint), 1, local_arg->outfile);
        }
        for (; tagno<n_events; tagno++) {
            trigpoint= -1;
#ifdef LITTLE_ENDIAN
            Intel_int32((uint32_t *)&trigpoint);
#endif
            fwrite(&trigpoint, sizeof(trigpoint), 1, local_arg->outfile);
        }
    }

    fclose(local_arg->outfile);

    /*{{{  Free memory*/
    free_pointer((void **)&local_arg->channelfilename);
    free_pointer((void **)&local_arg->channelmax);
    free_pointer((void **)&local_arg->channelmin);
    free_pointer((void **)&local_arg->channelheaders);
    free_pointer((void **)&local_arg->channelheadersII);

    if (local_arg->triggers.buffer_start!=NULL) {
        clear_triggers(&local_arg->triggers);
        growing_buf_free(&local_arg->triggers);
    }
    /*}}}  */

    tinfo->methods->init_done=FALSE;
}
예제 #18
0
파일: trim.c 프로젝트: berndf/avg_q
/*{{{  trim(transform_info_ptr tinfo) {*/
METHODDEF DATATYPE *
trim(transform_info_ptr tinfo) {
 struct trim_storage *local_arg=(struct trim_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 int item, shift, nrofshifts=1;
 long nr_of_input_ranges,nr_of_ranges;
 long output_points;
 long rangeno, current_output_point=0;
 const Bool collapse=args[ARGS_COLLAPSE].is_set || args[ARGS_COLLAPSE_Q].is_set;
 const DATATYPE collapse_quantile=(args[ARGS_COLLAPSE].is_set&&args[ARGS_COLLAPSE].arg.i==COLLAPSE_BY_MEDIAN ? 0.5 : (args[ARGS_COLLAPSE_Q].is_set ? args[ARGS_COLLAPSE_Q].arg.d/100.0 : 0.0));
 array myarray, newarray;
 DATATYPE *oldtsdata;
 DATATYPE *new_xdata=NULL;
 growing_buf ranges, tokenbuf;
 growing_buf triggers;

 growing_buf_init(&ranges);
 growing_buf_init(&tokenbuf);
 growing_buf_init(&triggers);

 if (tinfo->data_type==FREQ_DATA) {
  tinfo->nr_of_points=tinfo->nroffreq;
  nrofshifts=tinfo->nrofshifts;
 }

 /*{{{  Parse the ranges argument */
 nr_of_input_ranges=growing_buf_count_tokens(&local_arg->rangearg);
 if (nr_of_input_ranges<=0 || nr_of_input_ranges%2!=0) {
  ERREXIT(tinfo->emethods, "trim: Need an even number of arguments >=2\n");
 }
 nr_of_input_ranges/=2;
 output_points=0;
 growing_buf_allocate(&ranges, 0);
 growing_buf_allocate(&tokenbuf, 0);
 growing_buf_get_firsttoken(&local_arg->rangearg,&tokenbuf);
 while (tokenbuf.current_length>0) {
  struct range thisrange;
  if (args[ARGS_USE_CHANNEL].is_set) {
   int const channel=find_channel_number(tinfo,args[ARGS_USE_CHANNEL].arg.s);
   if (channel>=0) {
    DATATYPE const minval=get_value(tokenbuf.buffer_start, NULL);
    growing_buf_get_nexttoken(&local_arg->rangearg,&tokenbuf);
    DATATYPE const maxval=get_value(tokenbuf.buffer_start, NULL);
    array indata;
    tinfo_array(tinfo, &indata);
    indata.current_vector=channel;
    thisrange.offset= -1; /* Marks no start recorded yet */
    do {
     DATATYPE const currval=indata.read_element(&indata);
     if (currval>=minval && currval<=maxval) {
      if (thisrange.offset== -1) {
       thisrange.offset=indata.current_element;
       thisrange.length= 1;
      } else {
       thisrange.length++;
      }
     } else {
      if (thisrange.offset!= -1) {
       growing_buf_append(&ranges, (char *)&thisrange, sizeof(struct range));
       output_points+=(collapse ? 1 : thisrange.length);
       thisrange.offset= -1;
      }
     }
     array_advance(&indata);
    } while (indata.message==ARRAY_CONTINUE);
    if (thisrange.offset!= -1) {
     growing_buf_append(&ranges, (char *)&thisrange, sizeof(struct range));
     output_points+=(collapse ? 1 : thisrange.length);
    }
   } else {
    ERREXIT1(tinfo->emethods, "set xdata_from_channel: Unknown channel name >%s<\n", MSGPARM(args[ARGS_USE_CHANNEL].arg.s));
   }
  } else {
   if (args[ARGS_USE_XVALUES].is_set) {
    if (tinfo->xdata==NULL) create_xaxis(tinfo, NULL);
    thisrange.offset=decode_xpoint(tinfo, tokenbuf.buffer_start);
    growing_buf_get_nexttoken(&local_arg->rangearg,&tokenbuf);
    thisrange.length=decode_xpoint(tinfo, tokenbuf.buffer_start)-thisrange.offset+1;
   } else {
    thisrange.offset=gettimeslice(tinfo, tokenbuf.buffer_start);
    growing_buf_get_nexttoken(&local_arg->rangearg,&tokenbuf);
    thisrange.length=gettimeslice(tinfo, tokenbuf.buffer_start);
    if (thisrange.length==0) {
     thisrange.length=tinfo->nr_of_points-thisrange.offset;
    }
   }
   if (thisrange.length<=0) {
    ERREXIT1(tinfo->emethods, "trim: length is %d but must be >0.\n", MSGPARM(thisrange.length));
   }
   growing_buf_append(&ranges, (char *)&thisrange, sizeof(struct range));
   output_points+=(collapse ? 1 : thisrange.length);
  }
  growing_buf_get_nexttoken(&local_arg->rangearg,&tokenbuf);
 }
 /*}}}  */

 nr_of_ranges=ranges.current_length/sizeof(struct range);
 if (nr_of_ranges==0) {
  TRACEMS(tinfo->emethods, 0, "trim: No valid ranges selected, rejecting epoch.\n");
  return NULL;
 }
 TRACEMS2(tinfo->emethods, 1, "trim: nr_of_ranges=%ld, output_points=%ld\n", MSGPARM(nr_of_ranges), MSGPARM(output_points));

 newarray.nr_of_vectors=tinfo->nr_of_channels*nrofshifts;
 newarray.nr_of_elements=output_points;
 newarray.element_skip=tinfo->itemsize;
 if (array_allocate(&newarray)==NULL) {
  ERREXIT(tinfo->emethods, "trim: Error allocating memory.\n");
 }
 oldtsdata=tinfo->tsdata;

 if (tinfo->xdata!=NULL) {
  /* Store xchannelname at the end of xdata, as in create_xaxis(); otherwise we'll have 
   * a problem after free()'ing xdata... */
  new_xdata=(DATATYPE *)malloc(output_points*sizeof(DATATYPE)+strlen(tinfo->xchannelname)+1);
  if (new_xdata==NULL) {
   ERREXIT(tinfo->emethods, "trim: Error allocating xdata memory.\n");
  }
 }

 if (tinfo->triggers.buffer_start!=NULL) {
  struct trigger trig= *(struct trigger *)tinfo->triggers.buffer_start;
  growing_buf_allocate(&triggers, 0);
  /* Record the file position... */
  if (collapse) {
   /* Make triggers in subsequent append() work as expected at least with
    * continuous reading */
   trig.position=local_arg->current_epoch*nr_of_ranges;
   trig.code= -1;
  }
  growing_buf_append(&triggers, (char *)&trig, sizeof(struct trigger));
 }
 
 for (rangeno=0; rangeno<nr_of_ranges; rangeno++) {
  struct range *rangep=((struct range *)(ranges.buffer_start))+rangeno;
  long const old_startpoint=(rangep->offset>0 ?  rangep->offset : 0);
  long const new_startpoint=(rangep->offset<0 ? -rangep->offset : 0);

 /*{{{  Transfer the data*/
 if (old_startpoint<tinfo->nr_of_points 
  /* Skip this explicitly if no "real" point needs copying (length confined within negative offset)
   * since otherwise an endless loop can result as the stop conditions below look at the array 
   * states and no array is touched... */
  && new_startpoint<rangep->length)
 for (item=0; item<tinfo->itemsize; item++) {
  array_use_item(&newarray, item);
  for (shift=0; shift<nrofshifts; shift++) {
   tinfo_array(tinfo, &myarray);
   array_use_item(&myarray, item);
  do {
   DATATYPE sum=0.0;
   long reached_length=new_startpoint;
   myarray.current_element= old_startpoint;
   if (collapse) {
    newarray.current_element=current_output_point;
    newarray.message=ARRAY_CONTINUE;	/* Otherwise the loop below may finish promptly... */
    if (args[ARGS_COLLAPSE].is_set)
    switch (args[ARGS_COLLAPSE].arg.i) {
     case COLLAPSE_BY_HIGHEST:
      sum= -FLT_MAX;
      break;
     case COLLAPSE_BY_LOWEST:
      sum=  FLT_MAX;
      break;
     default:
      break;
    }
   } else {
    newarray.current_element=current_output_point+new_startpoint;
   }
   if (collapse && collapse_quantile>0.0) {
    array helparray=myarray;
    helparray.ringstart=ARRAY_ELEMENT(&myarray);
    helparray.current_element=helparray.current_vector=0;
    helparray.nr_of_vectors=1;
    helparray.nr_of_elements=rangep->length;
    sum=array_quantile(&helparray,collapse_quantile);
    myarray.message=ARRAY_CONTINUE;
   } else
   do {
    if (reached_length>=rangep->length) break;
    if (args[ARGS_COLLAPSE].is_set) {
     DATATYPE const hold=array_scan(&myarray);
     switch (args[ARGS_COLLAPSE].arg.i) {
      case COLLAPSE_BY_SUMMATION:
      case COLLAPSE_BY_AVERAGING:
       sum+=hold;
       break;
      case COLLAPSE_BY_HIGHEST:
       if (hold>sum) sum=hold;
       break;
      case COLLAPSE_BY_LOWEST:
       if (hold<sum) sum=hold;
       break;
      default:
       break;
     }
    } else {
     array_write(&newarray, array_scan(&myarray));
    }
    reached_length++;
   } while (newarray.message==ARRAY_CONTINUE && myarray.message==ARRAY_CONTINUE);
   if (collapse) {
    if (args[ARGS_COLLAPSE].is_set && args[ARGS_COLLAPSE].arg.i==COLLAPSE_BY_AVERAGING && item<tinfo->itemsize-tinfo->leaveright) sum/=reached_length;
    array_write(&newarray, sum);
   }
   if (newarray.message==ARRAY_CONTINUE) {
    array_nextvector(&newarray);
   }
   if (myarray.message==ARRAY_CONTINUE) {
    array_nextvector(&myarray);
   }
  } while (myarray.message==ARRAY_ENDOFVECTOR);
   tinfo->tsdata+=myarray.nr_of_vectors*myarray.nr_of_elements*myarray.element_skip;
  }
  tinfo->tsdata=oldtsdata;
 }
 /*}}}  */

 if (new_xdata!=NULL) {
  /*{{{  Transfer xdata*/
  DATATYPE sum=0.0;
  long reached_length=new_startpoint;
  long point, newpoint;
  if (collapse) {
   newpoint=current_output_point;
  } else {
   newpoint=current_output_point+new_startpoint;
  }
  for (point=old_startpoint;
    point<tinfo->nr_of_points && reached_length<rangep->length;
    point++) {
   if (collapse) {
    sum+=tinfo->xdata[point];
   } else {
    new_xdata[newpoint]=tinfo->xdata[point];
    newpoint++;
   }
   reached_length++;
  }
  if (collapse) {
   /* Summation of x axis values does not appear to make sense, so we always average: */
   new_xdata[newpoint]=sum/reached_length;
  }
  /*}}}  */
  /* Save xchannelname to the end of new_xdata */
  strcpy((char *)(new_xdata+output_points),tinfo->xchannelname);
 }

  if (tinfo->triggers.buffer_start!=NULL) {
   /* Collect triggers... */
   struct trigger *intrig=(struct trigger *)tinfo->triggers.buffer_start+1;
   while (intrig->code!=0) {
    if (intrig->position>=old_startpoint && intrig->position<old_startpoint+rangep->length) {
     struct trigger trig= *intrig;
     if (collapse) {
      trig.position=current_output_point;
     } else {
      trig.position=intrig->position-old_startpoint+current_output_point;
     }
     growing_buf_append(&triggers, (char *)&trig, sizeof(struct trigger));
    }
    intrig++;
   }
  }
  current_output_point+=(collapse ? 1 : rangep->length);
 }

 if (new_xdata!=NULL) {
  free(tinfo->xdata);
  tinfo->xdata=new_xdata;
  tinfo->xchannelname=(char *)(new_xdata+output_points);
 }
 if (tinfo->triggers.buffer_start!=NULL) {
  struct trigger trig;
  /* Write end marker */
  trig.position=0;
  trig.code=0;
  growing_buf_append(&triggers, (char *)&trig, sizeof(struct trigger));
  growing_buf_free(&tinfo->triggers);
  tinfo->triggers=triggers;
 }

 tinfo->multiplexed=FALSE;
 tinfo->nr_of_points=output_points;
 if (tinfo->data_type==FREQ_DATA) {
  tinfo->nroffreq=tinfo->nr_of_points;
 } else {
  tinfo->beforetrig-=((struct range *)(ranges.buffer_start))->offset;
  tinfo->aftertrig=output_points-tinfo->beforetrig;
 }
 tinfo->length_of_output_region=tinfo->nr_of_points*tinfo->nr_of_channels*tinfo->itemsize*nrofshifts;
 local_arg->current_epoch++;

 growing_buf_free(&tokenbuf);
 growing_buf_free(&ranges);

 return newarray.start;
}
예제 #19
0
METHODDEF DATATYPE *
read_freiburg(transform_info_ptr tinfo) {
 struct read_freiburg_storage *local_arg=(struct read_freiburg_storage *)tinfo->methods->local_storage;
 transform_argument *args=tinfo->methods->arguments;
 struct freiburg_channels_struct *in_channels=local_arg->in_channels;
 array myarray;
 FILE *infile;
 int i, point, channel;
 int trial_not_accepted;
 long length_of_data;
 short header[FREIBURG_HEADER_LENGTH/sizeof(short)];
 char const *last_sep=strrchr(args[ARGS_IFILE].arg.s, PATHSEP);
 char const *last_component=(last_sep==NULL ? args[ARGS_IFILE].arg.s : last_sep+1);
 char comment[MAX_COMMENTLEN];

 tinfo->nrofaverages=1;
 if (args[ARGS_CONTINUOUS].is_set) {
  /*{{{  Read an epoch from a continuous file*/
  infile=local_arg->infile;

  if (local_arg->epochs--==0) return NULL;

  /*{{{  Configure myarray*/
  myarray.element_skip=tinfo->itemsize=1;
  myarray.nr_of_vectors=tinfo->nr_of_points=local_arg->epochlength;
  myarray.nr_of_elements=tinfo->nr_of_channels=local_arg->nr_of_channels;
  if (array_allocate(&myarray)==NULL) {
   ERREXIT(tinfo->emethods, "read_freiburg: Error allocating data\n");
  }
  tinfo->multiplexed=TRUE;
  /*}}}  */

  do {
   do {
    if (local_arg->segment_table.buffer_start!=NULL && local_arg->current_point%SEGMENT_LENGTH==0) {
     int const segment=local_arg->current_point/SEGMENT_LENGTH;
     long const nr_of_segments=local_arg->segment_table.current_length/sizeof(long);
     if (segment>=nr_of_segments) {
      array_free(&myarray);
      return NULL;
     }
     fseek(infile, ((long *)local_arg->segment_table.buffer_start)[segment], SEEK_SET);
     local_arg->no_last_values=TRUE;
    }
    if (freiburg_get_segment(tinfo, &myarray)!=0) {
     array_free(&myarray);
     return NULL;
    }
   } while (myarray.message!=ARRAY_ENDOFSCAN);
  } while (--local_arg->fromepoch>0);
  snprintf(comment, MAX_COMMENTLEN, "%s %s %02d/%02d/%04d,%02d:%02d:%02d", (local_arg->continuous_type==SLEEP_BT_TYPE ? "sleep_BT" : "sleep_KL"), last_component, local_arg->btfile.start_month, local_arg->btfile.start_day, local_arg->btfile.start_year, local_arg->btfile.start_hour, local_arg->btfile.start_minute, local_arg->btfile.start_second);
  tinfo->sfreq=local_arg->sfreq;
  /*}}}  */
 } else
 /*{{{  Read an epoch from a single (epoched or averaged) file*/
 do {	/* Return here if trial was not accepted */
 trial_not_accepted=FALSE;

 if (local_arg->epochs--==0 || (local_arg->average_mode && local_arg->current_trigger>=1)) return NULL;

 if (local_arg->average_mode) {
  /*{{{  Prepare reading an averaged file*/
  if((infile=fopen(args[ARGS_IFILE].arg.s,"rb"))==NULL) {
   ERREXIT1(tinfo->emethods, "read_freiburg: Can't open file %s\n", MSGPARM(args[ARGS_IFILE].arg.s));
  }
  fseek(infile, 0, SEEK_END);
  length_of_data=ftell(infile)-FREIBURG_HEADER_LENGTH;
  local_arg->current_trigger++;
  snprintf(comment, MAX_COMMENTLEN, "Freiburg-avg %s", last_component);
  /*}}}  */
 } else {
  /*{{{  Build pathname of the single trial to read*/
  /* A directory name was given. */
  char const * const expnumber=args[ARGS_IFILE].arg.s+strlen(args[ARGS_IFILE].arg.s)-2;
#ifdef __GNUC__
#define NEWFILENAME_SIZE (strlen(args[ARGS_IFILE].arg.s)+strlen(last_component)+20)
#else
#define NEWFILENAME_SIZE MAX_PATHLEN
#endif
  char newfilename[NEWFILENAME_SIZE];
  do {	/* Files from which only the parameter part exists are rejected */
   int div100=local_arg->current_trigger/100, mod100=local_arg->current_trigger%100;
   snprintf(newfilename, NEWFILENAME_SIZE, "%s%c%s%02d%c%c%s%02d%02d", args[ARGS_IFILE].arg.s, PATHSEP, last_component, div100, PATHSEP, tolower(expnumber[-1]), expnumber, div100, mod100);
   TRACEMS1(tinfo->emethods, 1, "read_freiburg: Constructed filename %s\n", MSGPARM(newfilename));

   if((infile=fopen(newfilename,"rb"))==NULL) {
    if (local_arg->current_trigger==0) {
     ERREXIT1(tinfo->emethods, "read_freiburg: Can't open file %s\n", MSGPARM(newfilename));
    } else {
     return NULL;
    }
   }
   fseek(infile, 0, SEEK_END);
   length_of_data=ftell(infile)-FREIBURG_HEADER_LENGTH;
   local_arg->current_trigger++;
  } while (length_of_data==0 || --local_arg->fromepoch>0);
  snprintf(comment, MAX_COMMENTLEN, "Freiburg-raw %s", last_component);
  /*}}}  */
 }

 /*{{{  Read the 64-Byte header*/
 fseek(infile, 0, SEEK_SET);
 fread(header, 1, FREIBURG_HEADER_LENGTH, infile);
 for (i=0; i<18; i++) {
# ifdef LITTLE_ENDIAN
  Intel_int16((uint16_t *)&header[i]);
# endif
  TRACEMS2(tinfo->emethods, 3, "read_freiburg: Header %02d: %d\n", MSGPARM(i), MSGPARM(header[i]));
 }
 /*}}}  */

 if (local_arg->average_mode) {
  if ((length_of_data/sizeof(short))%local_arg->nr_of_channels!=0) {
   ERREXIT2(tinfo->emethods, "read_freiburg: length_of_data=%d does not fit with nr_of_channels=%d\n", MSGPARM(length_of_data), MSGPARM(local_arg->nr_of_channels));
  }
  tinfo->nr_of_points=(length_of_data/sizeof(short))/local_arg->nr_of_channels;
  local_arg->sfreq=(args[ARGS_SFREQ].is_set ? args[ARGS_SFREQ].arg.d : 200.0); /* The most likely value */
 } else {
  local_arg->nr_of_channels=header[14];
  /* Note: In a lot of experiments, one point MORE is available in the data
   * than specified in the header, but this occurs erratically. We could only
   * check for this during decompression, but that's probably too much fuss. */
  tinfo->nr_of_points=header[16]/header[15];
  local_arg->sfreq=(args[ARGS_SFREQ].is_set ? args[ARGS_SFREQ].arg.d : 1000.0/header[15]);
 }
 tinfo->sfreq=local_arg->sfreq;
 /*{{{  Parse arguments that can be in seconds*/
 local_arg->offset=(args[ARGS_OFFSET].is_set ? gettimeslice(tinfo, args[ARGS_OFFSET].arg.s) : 0);
 /*}}}  */
 tinfo->beforetrig= -local_arg->offset;
 tinfo->aftertrig=tinfo->nr_of_points+local_arg->offset;

 /*{{{  Configure myarray*/
 myarray.element_skip=tinfo->itemsize=1;
 myarray.nr_of_vectors=tinfo->nr_of_points;
 myarray.nr_of_elements=tinfo->nr_of_channels=local_arg->nr_of_channels;
 if (array_allocate(&myarray)==NULL) {
  ERREXIT(tinfo->emethods, "read_freiburg: Error allocating data\n");
 }
 tinfo->multiplexed=TRUE;
 /*}}}  */

 fseek(infile, FREIBURG_HEADER_LENGTH, SEEK_SET);
 if (local_arg->average_mode) {
  /*{{{  Read averaged epoch*/
  for (point=0; point<tinfo->nr_of_points; point++) {
#ifdef __GNUC__
   short buffer[tinfo->nr_of_channels];
#else
   short buffer[MAX_NR_OF_CHANNELS];
#endif
   if ((int)fread(buffer, sizeof(short), tinfo->nr_of_channels, infile)!=tinfo->nr_of_channels) {
    ERREXIT1(tinfo->emethods, "read_freiburg: Error reading data point %d\n", MSGPARM(point));
   }
   for (channel=0; channel<tinfo->nr_of_channels; channel++) {
#  ifdef LITTLE_ENDIAN
    Intel_int16((uint16_t *)&buffer[channel]);
#  endif
    array_write(&myarray, (DATATYPE)buffer[channel]);
   }
  }
  /*}}}  */
 } else {
  /*{{{  Read compressed single trial*/
#  ifdef DISPLAY_ADJECTIVES
  char *adjektiv_ende=strchr(((char *)header)+36, ' ');
  if (adjektiv_ende!=NULL) *adjektiv_ende='\0';
  printf("Single trial: nr_of_points=%d, nr_of_channels=%d, Adjektiv=%s\n", tinfo->nr_of_points, tinfo->nr_of_channels, ((char *)header)+36);
#  endif
  local_arg->infile=infile;
  do {
   if (freiburg_get_segment(tinfo, &myarray)!=0) {
    TRACEMS1(tinfo->emethods, 0, "read_freiburg: Decompression out of bounds for trial %d - skipped\n", MSGPARM(local_arg->current_trigger-1));
    array_free(&myarray);
    trial_not_accepted=TRUE;
    break;
   }
  } while (myarray.message!=ARRAY_ENDOFSCAN);
  /*}}}  */
 }
 fclose(infile);
 } while (trial_not_accepted);
 /*}}}  */

 /*{{{  Look for a Freiburg channel setup for this number of channels*/
 /* Force create_channelgrid to really allocate the channel info anew.
  * Otherwise, free_tinfo will free someone else's data ! */
 tinfo->channelnames=NULL; tinfo->probepos=NULL;
 if (local_arg->channelnames!=NULL) {
  copy_channelinfo(tinfo, local_arg->channelnames, NULL);
 } else {
  while (in_channels->nr_of_channels!=0 && in_channels->nr_of_channels!=tinfo->nr_of_channels) in_channels++;
  if (in_channels->nr_of_channels==0) {
   TRACEMS1(tinfo->emethods, 1, "read_freiburg: Don't have a setup for %d channels.\n", MSGPARM(tinfo->nr_of_channels));
  } else {
   copy_channelinfo(tinfo, in_channels->channelnames, NULL);
  }
 }
 create_channelgrid(tinfo); /* Create defaults for any missing channel info */
 /*}}}  */
 
 if ((tinfo->comment=(char *)malloc(strlen(comment)+1))==NULL) {
  ERREXIT(tinfo->emethods, "read_freiburg: Error allocating comment memory\n");
 }
 strcpy(tinfo->comment, comment);

 if (local_arg->zero_idiotism_warned==FALSE && local_arg->zero_idiotism_encountered) {
  TRACEMS(tinfo->emethods, 0, "read_freiburg: All-zero data points have been encountered and omitted!\n");
  local_arg->zero_idiotism_warned=TRUE;
 }
 tinfo->z_label=NULL;
 tinfo->tsdata=myarray.start;
 tinfo->length_of_output_region=tinfo->nr_of_channels*tinfo->nr_of_points;
 tinfo->leaveright=0;
 tinfo->data_type=TIME_DATA;

 return tinfo->tsdata;
}