Пример #1
0
/* get a voxel from all files, voxel coordinates */
void get_voxel_from_files(char **filenames, int *num_files,
			  int *v1, int *v2, int *v3, double *voxel) {
  misize_t location[3];
  mihandle_t hvol;
  int result;
  int i;

  location[0] = *v1;
  location[1] = *v2;
  location[2] = *v3;

  for(i=0; i < *num_files; i++) {
    /* open the volume */
    result = miopen_volume(filenames[i],
			   MI2_OPEN_READ, &hvol);
    if (result != MI_NOERROR) {
      error("Error opening input file: %s.\n", filenames[i]);
    }

    result = miget_real_value(hvol, location, 3, &voxel[i]);

    if (result != MI_NOERROR) {
      error("Error getting voxel from: %s.\n", filenames[i]);
    }
    miclose_volume(hvol);
  }
}
Пример #2
0
SEXP get_minc_separations(SEXP filename) {
  int                result;
  mihandle_t         hvol;
  const char *filepath = CHAR(asChar(filename));
  midimhandle_t dimensions[3];
  double* voxel_separations = malloc(3 * sizeof(double));
  SEXP output = PROTECT(allocVector(REALSXP, 3));
  
  result = miopen_volume(filepath,
                         MI2_OPEN_READ, &hvol);
  
  if (result != MI_NOERROR) {
    miclose_volume(hvol);
    error("Error opening input file: %s.\n", filepath);
  }
  
  result =
    miget_volume_dimensions(hvol, MI_DIMCLASS_SPATIAL, MI_DIMATTR_ALL,
                            MI_DIMORDER_FILE, 3, dimensions);
  
  result =
    miget_dimension_separations(dimensions, MI_ORDER_FILE, 
                                3, voxel_separations);
    
  
  miclose_volume(hvol);
  for(int i = 0; i < 3; ++i) REAL(output)[i] = voxel_separations[i];
  UNPROTECT(1);
  
  return(output);
}
Пример #3
0
/* get a voxel from all files, world coordinates */
void get_world_voxel_from_files(char **filenames, int *num_files,
				double *v1, double *v2, double *v3, 
				double *voxel) {
  double location[3], voxel_coord_tmp[3];
  misize_t voxel_coord[3];
  mihandle_t hvol;
  int result;
  int i, j;

  location[0] = *v1;
  location[1] = *v2;
  location[2] = *v3;

  for(i=0; i < *num_files; i++) {
    /* open the volume */
    result = miopen_volume(filenames[i],
			   MI2_OPEN_READ, &hvol);
    if (result != MI_NOERROR) {
      error("Error opening input file: %s.\n", filenames[i]);
    }

    miconvert_world_to_voxel(hvol, location, voxel_coord_tmp);
    
    for (j=0; j < 3; j++) {
      voxel_coord[j] = (unsigned long) voxel_coord_tmp[j] + 0.5;
    }
    result = miget_real_value(hvol, voxel_coord, 3, &voxel[i]);

    if (result != MI_NOERROR) {
      error("Error getting voxel from: %s.\n", filenames[i]);
    }
    miclose_volume(hvol);
  }
}
Пример #4
0
/* open_minc_files: given a vector of filenames, open the volumes and
 * returns the dimhandles */
mihandle_t* open_minc_files(SEXP filenames, 
			       misize_t *sizes) {
  int num_files, i, result;
  midimhandle_t dimensions[3];
  mihandle_t *hvol;

  num_files = LENGTH(filenames);
  hvol = malloc(num_files * sizeof(mihandle_t));

  /* open all the files */
  for (i=0; i < num_files; i++) {
    result = miopen_volume(CHAR(STRING_ELT(filenames, i)),
			   MI2_OPEN_READ, &hvol[i]);
    if (result != MI_NOERROR) {
      error("Error opening input file: %s.\n", CHAR(STRING_ELT(filenames,i)));
    }
  }

  /* get dimension size - assume it's the same for all volumes */
  result = miget_volume_dimensions( hvol[0], MI_DIMCLASS_SPATIAL,
				    MI_DIMATTR_ALL, MI_DIMORDER_FILE,
				    3, dimensions );
  if (result == MI_ERROR) {
    error("Error getting dimensions\n");
  }
  result = miget_dimension_sizes(dimensions, 3, sizes);
  Rprintf("Sizes: %d %d %d\n", sizes[0], sizes[1], sizes[2]);
  if (result == MI_ERROR) {
    error("Error getting dimension sizes\n");
  }
  return(hvol);

}
Пример #5
0
void get_volume_sizes(char **filename, unsigned int *sizes) {
  int result;
  mihandle_t  hvol;
  misize_t tmp_sizes[3];
  midimhandle_t dimensions[3];
   /* open the existing volume */
  result = miopen_volume(filename[0],
			 MI2_OPEN_READ, &hvol);
  if (result != MI_NOERROR) {
    error("Error opening input file: %s.\n", filename[0]);
  }

    /* get the file dimensions and their sizes */
  miget_volume_dimensions( hvol, MI_DIMCLASS_SPATIAL,
			   MI_DIMATTR_ALL, MI_DIMORDER_FILE,
			   3, dimensions);
  result = miget_dimension_sizes( dimensions, 3, tmp_sizes ); 
  //Rprintf("Sizes: %i %i %i\n", tmp_sizes[0], tmp_sizes[1], tmp_sizes[2]);
  sizes[0] = (unsigned int) tmp_sizes[0];
  sizes[1] = (unsigned int) tmp_sizes[1];
  sizes[2] = (unsigned int) tmp_sizes[2];

   // Close the volume, to free handle
   result = miclose_volume(hvol); 
   if (result != MI_NOERROR) {
    error("Error closing file: %s.\n", filename[0]);
  }
  return;
}
Пример #6
0
/* get_mask: opens the mask volume and allocates memory for the 
 * mask buffer */
void get_mask(SEXP filename, mihandle_t hmask, double *mask_buffer,
	      misize_t *sizes) {
  int result;
  
  result = miopen_volume(CHAR(STRING_ELT(filename, 0)),
			 MI2_OPEN_READ, &hmask);
  if (result != MI_NOERROR) {
    error("Error opening mask: %s.\n", CHAR(STRING_ELT(filename, 0)));
  }
  mask_buffer = malloc(sizes[1] * sizes[2] * sizeof(double));
}
Пример #7
0
/* convert voxel coordinates to a vector of world coords */
void convert_voxel_to_world(char **filenames, double *v1, double *v2,
			    double *v3, double *world_coords) {
  int result;
  mihandle_t hvol;
  double voxel_coords[3];

  /* open the volume */
  result = miopen_volume(filenames[0], MI2_OPEN_READ, &hvol);
  if (result != MI_NOERROR) {
    error("Error opening input file: %s.\n", filenames[0]);
  }

  voxel_coords[0] = *v1;
  voxel_coords[1] = *v2;
  voxel_coords[2] = *v3;

  miconvert_voxel_to_world(hvol, voxel_coords, world_coords);
  miclose_volume(hvol);
}
Пример #8
0
SEXP get_vector_from_files(SEXP filenames,  SEXP num_files,  SEXP vec_length,
			  SEXP v1, SEXP v2, SEXP v3) {
  misize_t location[4];
  mihandle_t hvol;
  int result;
  int i, j, vector_length, number_files; 
  SEXP output;
  double *xoutput;

  vector_length = *INTEGER(vec_length);
  number_files = *INTEGER(num_files);

  location[1] = *INTEGER(v1);
  location[2] = *INTEGER(v2);
  location[3] = *INTEGER(v3);

  Rprintf("NFILES: %d NVEC: %d\n", number_files, vector_length);
  PROTECT(output=allocMatrix(REALSXP, number_files, vector_length));
  xoutput = REAL(output);


  for(i=0; i < number_files; i++) {
    /* open the volume */
    result = miopen_volume(CHAR(STRING_ELT(filenames,i)),
			   MI2_OPEN_READ, &hvol);
    if (result != MI_NOERROR) {
      error("Error opening input file: %s.\n", CHAR(STRING_ELT(filenames, i)));
    }

    for(j=0; j < vector_length; j++) {
      location[0] = j;
      result = miget_real_value(hvol, location, 4, &xoutput[i + number_files*j]);

      if (result != MI_NOERROR) {
	error("Error getting voxel from: %s.\n", CHAR(STRING_ELT(filenames, i)));
      }
    }
    miclose_volume(hvol);
  }
  UNPROTECT(1);
  return(output);
}
Пример #9
0
SEXP minc_history_size(SEXP filename){
  size_t hist_size;
  mihandle_t hvol;
  int result;
  const char *filepath = CHAR(asChar(filename));
  
  result = miopen_volume(filepath,
                         MI2_OPEN_READ, &hvol);
  
  if (result != MI_NOERROR) {
    error("Error opening input file: %s.\n", filepath);
  }
  
  miget_attr_length(hvol, "", "history", &hist_size);

  miclose_volume(hvol);
  
  SEXP output = ScalarInteger((int) hist_size);
  return(output);
}
Пример #10
0
/* get a real value hyperslab from file */
SEXP get_hyperslab2( SEXP filename,  SEXP start,  SEXP count, SEXP slab) {
  int                result;
  mihandle_t         hvol;
  int                i;
  misize_t      tmp_start[3];
  misize_t      tmp_count[3];

  /*
  char **c_filename;
  int *c_start;
  int *c_count;
  double *c_slab;
  */
  /* open the volume */
  
  Rprintf("Crap %s\n", CHAR(STRING_ELT(filename, 0)));
  result = miopen_volume(CHAR(STRING_ELT(filename,0)),
			 MI2_OPEN_READ, &hvol);
  if (result != MI_NOERROR) {
    error("Error opening input file: %s.\n", CHAR(STRING_ELT(filename,0)));
  }

  for (i=0; i < 3; i++) {
    tmp_start[i] = (unsigned long) INTEGER(start)[i];
    tmp_count[i] = (unsigned long) INTEGER(count)[i];
  }

  /* get the hyperslab */
  Rprintf("Start: %i %i %i\n", INTEGER(start)[0], INTEGER(start)[1], INTEGER(start)[2]);
  Rprintf("Count: %i %i %i\n", INTEGER(count)[0], INTEGER(count)[1], INTEGER(count)[2]);
  if (miget_real_value_hyperslab(hvol, 
				 MI_TYPE_DOUBLE, 
				 tmp_start, 
				 tmp_count, 
				 REAL(slab))
      < 0) {
    error("Could not get hyperslab.\n");
  }
  return(slab);
}
Пример #11
0
int main ( int argc, char **argv )
{
  mihandle_t hvol;
  int r;
  misize_t coords[3];
  double min, max;
  int i;

  while ( --argc > 0 ) {
    const char *fname=*++argv;
    printf("Checking %s\n",fname);
    r = miopen_volume ( fname, MI2_OPEN_READ, &hvol );
    if ( r < 0 ) {
      fprintf ( stderr, "can't open %s, error %d\n", *argv, r );
      return 1;
    } else {
      for ( i = 0; i < CZ; i++ ) {
        coords[0] = i;         /*Z*/
        coords[1] = rand()%CX; /*X*/
        coords[2] = rand()%CY; /*Y*/

        r = miget_slice_min ( hvol, coords, 3, &min );
        if ( r < 0 ) {
          fprintf ( stderr, "error %d getting slice minimum at %d %d %d\n", r, (int)coords[0],(int)coords[1],(int)coords[2] );
          return 1;
        }

        r = miget_slice_max ( hvol, coords, 3, &max );
        if ( r < 0 ) {
          fprintf ( stderr, "error %d getting slice maximum at %d %d %d\n", r,(int)coords[0],(int)coords[1],(int)coords[2] );
          return 1;
        }
        /*printf ( "%d. min %f max %f\n", i, min, max );*/
        /*PASS*/
      }
      miclose_volume ( hvol );
    }
  }
  return ( 0 );
}
Пример #12
0
/* get a real value hyperslab from file */
void get_hyperslab(char **filename, int *start, int *count, double *slab) {
  int                result;
  mihandle_t         hvol;
  int                i;
  unsigned long      tmp_start[3];
  unsigned long      tmp_count[3];

  /* open the volume */
  result = miopen_volume(filename[0],
			 MI2_OPEN_READ, &hvol);
  if (result != MI_NOERROR) {
    error("Error opening input file: %s.\n", filename[0]);
  }

  for (i=0; i < 3; i++) {
    tmp_start[i] = (unsigned long) start[i];
    tmp_count[i] = (unsigned long) count[i];
  }

  /* get the hyperslab */
  //Rprintf("Start: %i %i %i\n", start[0], start[1], start[2]);
  //Rprintf("Count: %i %i %i\n", count[0], count[1], count[2]);
  if (miget_real_value_hyperslab(hvol, 
				 MI_TYPE_DOUBLE, 
				 (misize_t *) tmp_start, 
				 (misize_t *) tmp_count, 
				 slab)
      < 0) {
    error("Could not get hyperslab.\n");
  }
   // Close the volume, to free handle
   result = miclose_volume(hvol); 
   if (result != MI_NOERROR) {
    error("Error closing file: %s.\n", filename[0]);
  }

  return;
}
Пример #13
0
SEXP get_minc_history(SEXP filename) {
  int                result;
  mihandle_t         hvol;
  int int_size   =   asInteger(minc_history_size(filename));
  char  *history = malloc(int_size);  
  const char *filepath = CHAR(asChar(filename));

  result = miopen_volume(filepath,
                         MI2_OPEN_READ, &hvol);

  if (result != MI_NOERROR) {
    miclose_volume(hvol);
    error("Error opening input file: %s.\n", filepath);
  }
  
  miget_attr_values(hvol, MI_TYPE_STRING, "", "history", int_size, history);
  miclose_volume(hvol);
  
  SEXP output = PROTECT(mkString(history));
  free(history);
  UNPROTECT(1);
  
  return(output);
}
Пример #14
0
SEXP minc_overwrite_history(SEXP filename, SEXP history, SEXP hist_size){
  const char *history_line = CHAR(asChar(history));
  const char *filepath = CHAR(asChar(filename));
  int history_size = asInteger(hist_size);
  mihandle_t  hvol;
  int read_result;
  int hist_edit_result;
  
  read_result = miopen_volume(filepath,
                              MI2_OPEN_RDWR, &hvol);
  
  if (read_result != MI_NOERROR) {
    error("Error opening input file: %s.\n", filepath);
  }
  
  hist_edit_result = miadd_history_attr(hvol, history_size, history_line);
  if(hist_edit_result != MI_NOERROR){
    error("Error editing history for file: %s \n", filepath);
  }
  
  miclose_volume(hvol);
  
  return(R_NilValue);
}
Пример #15
0
void cautious_open_volume(char *filename, int mode, mihandle_t *volume, string error_message){
  int res = miopen_volume(filename, mode, volume);
  if(res != MI_NOERROR){
    stop(error_message);
  }
}
Пример #16
0
int main(int argc, char **argv)
{
  mihandle_t vol;
  mivolumeprops_t  props;
  int r;
  micompression_t compression_type;
  miboolean_t enable_flag;
  int zlib_level;
  int depth;
  int edge_lengths[MI2_MAX_VAR_DIMS];
  int edge_count;
  int i;

  r = minew_volume_props(&props);

  if (r < 0) {
    TESTRPT("failed", r);
  }
  
  r = miset_props_multi_resolution(props, 1 , 2);

  if (r < 0) {
    TESTRPT("failed", r);
   }

  r = miget_props_multi_resolution(props, &enable_flag, &depth);
  if (r < 0) {
    TESTRPT("failed", r);
  }
  else {
    printf("Multiresolution enabled: %d depth: %d \n", enable_flag, depth);
  }

  r = miset_props_compression_type(props, MI_COMPRESS_NONE);
  if (r < 0) {
    TESTRPT("failed", r);
  }
  else {
      printf("Set compression type to %d\n", MI_COMPRESS_NONE);
  }

  r = miget_props_compression_type(props,&compression_type);
  if (r < 0 || compression_type != MI_COMPRESS_NONE) {
    TESTRPT("failed", r);
  }
  else {
    printf("Got compression type %d \n", compression_type);
 }  

  r = miset_props_zlib_compression(props,4);
  if (r < 0) {
    TESTRPT("failed", r);
  }
  else {
    printf("Set zlib level to %d\n", 4);
  }

  r = miget_props_zlib_compression(props,&zlib_level);
  if (r < 0 || zlib_level != 4) {
    TESTRPT("failed", r);
  }
  else {
    printf("Got zlib level %d \n", zlib_level);
  }

  mifree_volume_props(props);

  while (--argc > 0) {
      r = miopen_volume(*++argv, MI2_OPEN_RDWR, &vol);
      if (r < 0) {
	  TESTRPT("failed", r);
      }
      r = miget_volume_props(vol, &props);
      if (r < 0) {
	  TESTRPT("failed", r);
      }
      r = miget_props_blocking(props, &edge_count, edge_lengths, 
			       MI2_MAX_VAR_DIMS);
      if (r < 0) {
	  TESTRPT("failed", r);
      }
      printf("edge_count %d\n", edge_count);
      for (i = 0; i < edge_count; i++) {
	  printf("  %d", edge_lengths[i]);
      }
      printf("\n");
      mifree_volume_props(props);
      miclose_volume(vol);
  }

 if (error_cnt != 0) {
    fprintf(stderr, "%d error%s reported\n", 
	    error_cnt, (error_cnt == 1) ? "" : "s");
  }
  else {
    fprintf(stderr, "No errors\n");
  }
  return (error_cnt);
}
Пример #17
0
t_vol		*init_get_volume_from_minc_file(char *path)
{
  t_vol		*volume;
  int		result;

  volume = malloc(sizeof(*volume));
  volume->path = path;
  volume->dim_nb = 3;
  if (volume->path == NULL)
    return (NULL);
  // open the minc file
  if ((result = miopen_volume(volume->path, MI2_OPEN_READ, &volume->minc_volume)) != MI_NOERROR)
    {
      ERROR("Error opening input file: %d.", result);
      return (NULL);
    }

  if ((result = miget_volume_dimension_count(volume->minc_volume, 0, 0, &volume->dim_nb)) != MI_NOERROR)
    {
      ERROR("Error getting number of dimensions: %d.", result);
      return (NULL);
    }

  volume->dimensions = malloc(volume->dim_nb * sizeof(*volume->dimensions));
  volume->starts = malloc(volume->dim_nb * sizeof(*volume->starts));
  volume->steps = malloc(volume->dim_nb * sizeof(*volume->steps));
  volume->size = malloc(volume->dim_nb * sizeof(*volume->size));
  volume->dim_name = malloc(volume->dim_nb * sizeof(*volume->dim_name));

  // get the volume dimensions
  if ((result = miget_volume_dimensions(volume->minc_volume, MI_DIMCLASS_SPATIAL, MI_DIMATTR_ALL,
					MI_DIMORDER_FILE, volume->dim_nb, volume->dimensions)) == MI_ERROR)
    {
      ERROR("Error getting dimensions: %d.", result);
      return (NULL);
    }
  // get the size of each dimensions
  if ((result = miget_dimension_sizes(volume->dimensions, volume->dim_nb, volume->size)) != MI_NOERROR)
    {
      ERROR("Error getting dimensions size: %d.", result);
      return (NULL);
    }
  if ((result = miget_dimension_starts(volume->dimensions, 0, volume->dim_nb, volume->starts)) != MI_NOERROR)
    {
      ERROR("Error getting dimensions start: %d.", result);
      return (NULL);
    }
  if ((result = miget_dimension_separations(volume->dimensions, 0, volume->dim_nb, volume->steps)) != MI_NOERROR)
    {
      ERROR("Error getting dimensions steps: %d.", result);
      return (NULL);
    }
  if (miget_dimension_name (volume->dimensions[0], &volume->dim_name[0]) != MI_NOERROR ||
      miget_dimension_name (volume->dimensions[1], &volume->dim_name[1]) != MI_NOERROR ||
      miget_dimension_name (volume->dimensions[2], &volume->dim_name[2]))
    {
      ERROR("Error getting dimensions name.");
      return (NULL);
    }
  // get slices_max
  volume->slices_max = get_slices_max(volume);
  volume->next = NULL;
  return (volume);
}
Пример #18
0
SEXP per_voxel_anova(SEXP filenames, SEXP Sx, SEXP asgn, 
		     SEXP have_mask, SEXP mask) {

  /* generic items for all slice_loop functions */
  misize_t sizes[3];
  double **full_buffer;
  double *mask_buffer;
  mihandle_t *hvol, hmask;
  double *use_mask;
  int v0, v1, v2;
  int num_files, i;
  misize_t buffer_index, output_index;

  /* anova specific items */
  int n,p, maxasgn;
  int *xasgn;
  double *coefficients, *residuals, *effects, *work, *qraux, *v, *diag,
    *se, *t, *comp, *ss;
  int *pivot, *df;
  SEXP Soutput, t_sexp, Sdata;
  double *output, *data;

  use_mask = REAL(have_mask);
  //Rprintf("Use mask: %f\n", use_mask[0]);
  
  num_files = LENGTH(filenames);
  //Rprintf("Before opening files\n");
  hvol = open_minc_files(filenames, sizes);
  //Rprintf("Before getting mask\n");
  if (use_mask[0] == 1) {
    Rprintf("Getting mask\n");
    //get_mask(mask, hmask, mask_buffer, sizes);
    miopen_volume(CHAR(STRING_ELT(mask, 0)),
		  MI2_OPEN_READ, &hmask);
    mask_buffer = malloc(sizes[1]*sizes[2]*sizeof(double));
  }
  
  //Rprintf("Before creating slice buffer\n");
  //full_buffer = malloc(num_files * sizeof(double));
  full_buffer = create_slice_buffer(filenames, sizes);
  //num_files = LENGTH(filenames);
  //full_buffer = malloc(num_files * sizeof(double));
  //for (i=0; i < num_files; i++) {
  //  full_buffer[i] = malloc(sizes[1] * sizes[2] * sizeof(double));
  //}
  /* ANOVA specific allocations */
  n = nrows(Sx);
  p = ncols(Sx);
  xasgn = INTEGER(asgn);
  
  maxasgn = 0;
  for (i=0; i < p; i++) {
    if (xasgn[i] > maxasgn) {
      maxasgn = (int) xasgn[i];
    }
  }
  maxasgn++;
  
  coefficients = malloc(sizeof(double) * p);
  residuals = malloc(sizeof(double) * n);
  effects = malloc(sizeof(double) * n);
  pivot = malloc(sizeof(int) * p);
  work = malloc(sizeof(double) * (2*p));
  qraux = malloc(sizeof(double) * p);
  v = malloc(sizeof(double) * p * p);
  diag = malloc(sizeof(double) * p);
  se = malloc(sizeof(double) * p);
  t = malloc(sizeof(double) * p);
  
  comp = malloc(sizeof(double) * p);
  ss = malloc(sizeof(double) * maxasgn);
  df = malloc(sizeof(int) * maxasgn);
  
  Rprintf("N: %d P: %d\n", n,p);
    
  PROTECT(t_sexp = allocVector(REALSXP, maxasgn-1));
  
  //Rprintf("Sizes: %d %d %d\n", sizes[0], sizes[1], sizes[2]);
  /* allocate the output buffer */
  PROTECT(Soutput=allocMatrix(REALSXP, (sizes[0] * sizes[1] * sizes[2]), 
			     maxasgn-1));
  output = REAL(Soutput);

  /* allocate the local buffer that will be passed to the function */
  PROTECT(Sdata = allocVector(REALSXP, LENGTH(filenames)));
  data = REAL(Sdata);
  
  /* enter slice loop */
  Rprintf("In slice \n");
  for (v0=0; v0 < sizes[0]; v0++) {
    //Rprintf("Before fill_slice_buffer\n");
    fill_slice_buffer(filenames, sizes, hvol, full_buffer, v0);
    //Rprintf("After fill_slice_buffer\n");
    if (use_mask[0] == 1) {
      get_mask_slice(hmask, sizes, mask_buffer, v0);
    }
    for (v1=0; v1 < sizes[1]; v1++) {
      for (v2=0; v2 < sizes[2]; v2++) {
	//Rprintf("Before get_indices\n");
	get_indices(v0,v1,v2, sizes, &output_index, &buffer_index);
	
	/* only perform operation if not masked */
	if (use_mask[0] == 0 ||
	    (use_mask[0] == 1 && mask_buffer[buffer_index] > 0.5)) {
	  /* fill data buffer */
	  for (i=0; i< num_files; i++) {
	    data[i] = full_buffer[i][buffer_index];
	  }

	  /* compute the linear model */
	  //Rprintf("Before voxel_anova\n");
	  t_sexp = voxel_anova(Sdata, Sx, asgn,
			       coefficients, residuals,
			       effects, work, qraux, v, pivot,
			       se, t, comp, ss, df);
	  //Rprintf("Before assigning of output\n");
	  for (i=0; i < maxasgn-1; i++) {
	    output[output_index + i * (sizes[0]*sizes[1]*sizes[2])] 
	      = REAL(t_sexp)[i];
	  }
	}
	else {
	  for (i=0; i < maxasgn-1; i++) {
	    output[output_index + i * (sizes[0]*sizes[1]*sizes[2])]
	      = 0.0;
	  }
	}
      }
    }
  }
  //Rprintf("freeing slice buffer\n");
  free_slice_buffer(filenames, sizes, full_buffer);
  //Rprintf("freeing volume handles\n");
  free_minc_files(filenames, hvol);
  //Rprintf("finished\n");

  free(coefficients);
  free(residuals);
  free(effects);
  free(pivot);
  free(work);
  free(qraux);
  free(v);
  free(diag);
  free(se);
  free(t);
  
  free(comp);
  free(ss);
  free(df);
  UNPROTECT(3);
  Rprintf("\nDone\n");
  return(Soutput);

}
Пример #19
0
/* writes a hyperslab to the output filename, creating the output voluem
   to be like the second filename passed in */
void write_minc2_volume(char **output, char **like_filename,
			int *start, int *count, double *max_range,
			double *min_range, double *slab) {
  mihandle_t hvol_like, hvol_new;
  midimhandle_t *dimensions_like, *dimensions_new;
  unsigned long tmp_count[3];
  unsigned long tmp_start[3];
  int i;

  /* allocate the dimension handles */
  dimensions_like = malloc(sizeof(midimhandle_t) * 3);
  dimensions_new = malloc(sizeof(midimhandle_t) * 3);

  /* read the like volume */
  if (miopen_volume(like_filename[0], MI2_OPEN_READ, &hvol_like) < 0 ) {
    error("Error opening volume: %s\n", like_filename[0]);
  }
  
  /* get dimensions */
  if (miget_volume_dimensions( hvol_like, MI_DIMCLASS_SPATIAL, MI_DIMATTR_ALL,
			       MI_DIMORDER_FILE, 3, dimensions_like ) < 0 ) {
    error("Error getting volume dimensions\n");
  }

  /* copy the dimensions to the new file */
  for (i=0; i < 3; i++) {
    if (micopy_dimension(dimensions_like[i], &dimensions_new[i]) < 0) {
      error ("Error copying dimension %d\n", i);
    }
  }

  /* create the new volume */
  if ( micreate_volume(output[0], 3, dimensions_new, MI_TYPE_USHORT,
		       MI_CLASS_REAL, NULL, &hvol_new) < 0 ) {
    error("Error creating volume %s\n", output[0]);
  }
  if (micreate_volume_image(hvol_new) < 0) {
    error("Error creating volume image\n");
  }
  
  /* set valid and real range */
  miset_volume_valid_range(hvol_new, 65535, 0);
  miset_volume_range(hvol_new, max_range[0], min_range[0]);

  Rprintf("Range: %f %f\n", max_range[0], min_range[0]);

  /* write the buffer */
  for (i=0; i < 3; i++) {
    tmp_start[i] = (unsigned long) start[i];
    tmp_count[i] = (unsigned long) count[i];
  }
  if (miset_real_value_hyperslab(hvol_new, MI_TYPE_DOUBLE, 
				 (misize_t *) tmp_start, 
				 (misize_t *) tmp_count,
				 slab) < 0) {
    error("Error writing buffer to volume\n");
  }
  if (miclose_volume(hvol_like) < 0) {
    error("Error closing like volume\n");
  }
  if (miclose_volume(hvol_new) < 0) {
    error("Error closing new volume\n");
  }

  free(dimensions_new);
  free(dimensions_like);
  return;
}
Пример #20
0
int main ( void )
{
  mihandle_t vol;
  int r = 0;
  midimhandle_t dim[NDIMS];
  misize_t lengths[NDIMS];
  midimhandle_t copy_dim[NDIMS];
  misize_t coords[NDIMS];
  misize_t count[NDIMS];
  int i, j;
  unsigned char * Atmp;
  midimclass_t dimension_class;
  int ndims;
  Atmp = ( unsigned char * ) malloc ( CX * CY * CZ * sizeof ( unsigned char ) );

  create_test_file();

  printf ( " \n" );
  printf ( "Opening vector-dimension file!\n" );
  printf ( " \n" );

  r = miopen_volume ( "example_vector2.mnc", MI2_OPEN_READ, &vol );

  if ( r < 0 ) {
    TESTRPT ( "failed to open vector_dimension volume", r );
  }

  r = miget_volume_dimension_count ( vol, MI_DIMCLASS_ANY, MI_DIMATTR_REGULARLY_SAMPLED, &ndims );
  if ( r < 0 ) {
    TESTRPT ( "failed to get number of dimensions", r );

  }

  printf ( "Total number of dimensions : %d \n", ndims );

  r = miget_volume_dimensions ( vol, MI_DIMCLASS_ANY, MI_DIMATTR_REGULARLY_SAMPLED, MI_DIMORDER_FILE, NDIMS, dim );

  if ( r < 0 ) {
    TESTRPT ( "Could not get dimension handles from volume", r );

  }

  r = miget_dimension_sizes ( dim, NDIMS, lengths );
  if ( r < 0 ) {
    TESTRPT ( " more trouble", r );

  }
  printf ( "Dimension Size in file order : " );
  for ( i = 0; i < NDIMS; i++ ) {
    printf ( " %lld ", lengths[i] );
  }
  printf ( " \n" );

  for ( i = 0; i < NDIMS; i++ ) {
    r = miget_dimension_class ( dim[i], &dimension_class );
    if ( r < 0 ) {
      TESTRPT ( "failed to get dimension class", r );
    }
    if ( dimension_class == MI_DIMCLASS_RECORD ) {
      printf ( "Dim class RECORD present check dim name for *vector_dimension*\n" );
    }
  }

  printf ( "Let's get the first 10 data values of each vector component (file order) \n" );

  coords[0] = coords[1] = coords[2] = 0;

  count[0] = CZ;
  count[1] = CY;
  count[2] = CX;
  count[3] = 1;
  printf ( " FILE ORDER --> zspace, yspace, xspace, vector_dimension \n" );
  for ( i = 0; i < 3; i++ ) {
    printf ( "Vector Componenet %d \n", i + 1 );
    coords[3] = i;
    r = miget_voxel_value_hyperslab ( vol, MI_TYPE_UBYTE, coords, count, Atmp );
    if ( r < 0 ) {
      TESTRPT ( "Failed to operate hyperslab function", r );
    }

    for ( j = 0; j < 10; j++ ) {
      printf ( " %u ", Atmp[j] );
    }
    printf ( " \n" );
  }
  printf ( "APPARENT ORDER --> vector_dimension, zspace, yspace, xspace\n" );

  // Set the apparent dimension order

  copy_dim[0] = dim[3];
  copy_dim[1] = dim[0];
  copy_dim[2] = dim[1];
  copy_dim[3] = dim[2];

  r = miset_apparent_dimension_order ( vol, NDIMS, copy_dim );
  if ( r < 0 ) {
    TESTRPT ( "failed to set apparent order", r );
  }

  coords[1] = coords[2] = coords[3] = 0;

  count[0] = 1; //must always be one
  count[1] = CZ;
  count[2] = CY;
  count[3] = CZ;

  printf ( "APPARENT ORDER SET \n" );
  for ( i = 0; i < 3; i++ ) {
    printf ( "Vector Componenet %d \n", i + 1 );
    coords[0] = i;
    r = miget_voxel_value_hyperslab ( vol, MI_TYPE_UBYTE, coords, count, Atmp );
    if ( r < 0 ) {
      TESTRPT ( "Failed to operate hyperslab function", r );
    }

    for ( j = 0; j < 10; j++ ) {
      printf ( " %u ", Atmp[j] );
    }
    printf ( " \n" );
  }

  if ( error_cnt != 0 ) {
    fprintf ( stderr, "%d error%s reported\n",
              error_cnt, ( error_cnt == 1 ) ? "" : "s" );
  } else {
    fprintf ( stderr, "No errors\n" );
  }

  return ( error_cnt );
}
Пример #21
0
/*
   Given a minc filename, return a list containing:
   (1) the dimension names
   (2) the dimension sizes
   (3) and much, much more
   */
SEXP get_volume_info(SEXP filename) {

    mihandle_t          minc_volume;
	midimhandle_t		*dimensions;
	miclass_t			volume_class;
	mitype_t			volume_type;
	
	int					result, i;
	int					n_dimensions;
	misize_t    n_dimensions_misize_t;
	int					n_protects, list_index;
	int					n_frames;
	
// variables to hold dim-related info
	misize_t		dim_sizes[MI2_MAX_VAR_DIMS];
	double				dim_starts[MI2_MAX_VAR_DIMS];
	double				dim_steps[MI2_MAX_VAR_DIMS];
	double				time_offsets[MAX_FRAMES];
	double				time_widths[MAX_FRAMES];
	char 				*dim_name;
	char 				*dim_units;
	char 				*space_type;
	Rboolean			time_dim_exists;
	static char *dimorder3d[] = { "zspace","yspace","xspace" };
	static char *dimorder4d[] = { "time", "zspace","yspace","xspace" };
	

	/* declare R datatypes  */
	SEXP rtnList, listNames;
	SEXP xDimSizes, xDimNames, xDimUnits, xDimStarts, xDimSteps, xTimeWidths, xTimeOffsets;



	// start ...
	if ( R_DEBUG_mincIO ) Rprintf("get_volume_info: start ...\n");


	/* do some initialization */
	for (i=0; i < MI2_MAX_VAR_DIMS; ++i){					// set dim info to zeros
		dim_sizes[i] = 0;
		dim_starts[i] = 0;
		dim_steps[i] = 0;
	}

	// frame-related init
	time_dim_exists = FALSE;
	for (i=0; i < MAX_FRAMES; ++i) {
		time_offsets[i]=999.9;
		time_widths[i]=999.9;
	}
	n_frames = 0;

	n_protects = 0;								// counter of protected R variables



	/* init the return list (include list names) */
	PROTECT(rtnList=allocVector(VECSXP, R_RTN_LIST_LEN));
	PROTECT(listNames=allocVector(STRSXP, R_RTN_LIST_LEN));
	n_protects = n_protects +2;


	/* open the existing volume */
	result = miopen_volume(CHAR(STRING_ELT(filename,0)), MI2_OPEN_READ, &minc_volume);
	/* error on open? */
	if (result != MI_NOERROR) {
		error("Error opening input file: %s.\n", CHAR(STRING_ELT(filename,0)));
	}

	/* set the apparent order to something conventional */
	//	... first need to get the number of dimensions
	if ( miget_volume_dimension_count(minc_volume, MI_DIMCLASS_ANY, MI_DIMATTR_ALL, &n_dimensions) != MI_NOERROR ){
		error("Error returned from miget_volume_dimension_count.\n");
	}
	n_dimensions_misize_t = (misize_t) n_dimensions;
	// ... now set the order
	if ( R_DEBUG_mincIO ) Rprintf("Setting the apparent order for %d dimensions ... ", n_dimensions);
	if ( n_dimensions == 3 ) {
		result = miset_apparent_dimension_order_by_name(minc_volume, 3, dimorder3d);
	} else if ( n_dimensions == 4 ) {
		result = miset_apparent_dimension_order_by_name(minc_volume, 4, dimorder4d);
	} else {
		error("Error file %s has %d dimensions and we can only deal with 3 or 4.\n", CHAR(STRING_ELT(filename,0)), n_dimensions);
	}
	if ( result != MI_NOERROR ) { 
		error("Error returned from miset_apparent_dimension_order_by_name while setting apparent order for %d dimensions.\n", n_dimensions); 
	}
	if ( R_DEBUG_mincIO ) Rprintf("Done.\n");

	/* get the volume data class (the intended "real" values) */ 
	if ( miget_data_class(minc_volume, &volume_class) != MI_NOERROR ){
		error("Error returned from miget_data_class.\n");
	}
	/* append to return list ... */
	list_index = 0;
	SET_VECTOR_ELT(rtnList, list_index, ScalarInteger(volume_class));
	SET_STRING_ELT(listNames, list_index, mkChar("volumeDataClass"));


	/* print the volume data type (as it is actually stored in the volume) */
	if ( miget_data_type(minc_volume, &volume_type) != MI_NOERROR ){
		error("Error returned from miget_data_type.\n");
	}
	/* append to return list ... */
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, ScalarInteger(volume_type));
	SET_STRING_ELT(listNames, list_index, mkChar("volumeDataType"));


	/* retrieve the volume space type (talairach, native, etc) */
	result = miget_space_name(minc_volume, &space_type);
	if ( result == MI_NOERROR ) { error("Error returned from miget_space_name.\n"); }
	/* append to return list ... */
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, mkString(space_type));
	SET_STRING_ELT(listNames, list_index, mkChar("spaceType"));


	/* retrieve the total number of dimensions in this volume */
	if ( miget_volume_dimension_count(minc_volume, MI_DIMCLASS_ANY, MI_DIMATTR_ALL, &n_dimensions) != MI_NOERROR ){
		error("Error returned from miget_volume_dimension_count.\n");
	}
	/* append to return list ... */
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, ScalarInteger(n_dimensions));
	SET_STRING_ELT(listNames, list_index, mkChar("nDimensions"));


	/* load up dimension-related information */
	//
	/* first allocate the R variables */
	PROTECT( xDimSizes=allocVector(INTSXP,n_dimensions) );
	PROTECT( xDimNames=allocVector(STRSXP,n_dimensions) );
	PROTECT( xDimUnits=allocVector(STRSXP,n_dimensions) );
	PROTECT( xDimStarts=allocVector(REALSXP,n_dimensions) );
	PROTECT( xDimSteps=allocVector(REALSXP,n_dimensions) );
	n_protects = n_protects +5;

	/* next, load up the midimension struct for all dimensions*/
	dimensions = (midimhandle_t *) malloc( sizeof( midimhandle_t ) * n_dimensions );
	result = miget_volume_dimensions(minc_volume, MI_DIMCLASS_ANY, MI_DIMATTR_ALL, MI_DIMORDER_APPARENT, n_dimensions, dimensions);
	// need to check against MI_ERROR, as "result" will contain nDimensions if OK
	if ( result == MI_ERROR ) { error("Error code(%d) returned from miget_volume_dimensions.\n", result); }


	/* get the dimension sizes for all dimensions */
	result = miget_dimension_sizes(dimensions, n_dimensions_misize_t, dim_sizes);
	if ( result != MI_NOERROR ) { error("Error returned from miget_dimension_sizes.\n"); }
	/* add to R vector ... */
	for (i=0; i<n_dimensions; ++i){
		INTEGER(xDimSizes)[i] = dim_sizes[i];
	}
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, xDimSizes);
	SET_STRING_ELT(listNames, list_index, mkChar("dimSizes"));


	/* get the dimension START values for all dimensions */
	result = miget_dimension_starts(dimensions, MI_ORDER_FILE, n_dimensions, dim_starts);
	if ( result == MI_ERROR ) { error("Error returned from miget_dimension_starts.\n"); }
	/* add to R vector ... */
	for (i=0; i<n_dimensions; ++i){
		REAL(xDimStarts)[i] = dim_starts[i];
	}
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, xDimStarts);
	SET_STRING_ELT(listNames, list_index, mkChar("dimStarts"));


	/* get the dimension STEP values for all dimensions */
	result = miget_dimension_separations(dimensions, MI_ORDER_FILE, n_dimensions, dim_steps);
	if ( result == MI_ERROR ) { error("Error returned from miget_dimension_separations.\n"); }
	/* add to R vector ... */
	for (i=0; i<n_dimensions; ++i){
		REAL(xDimSteps)[i] = dim_steps[i];
	}
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, xDimSteps);
	SET_STRING_ELT(listNames, list_index, mkChar("dimSteps"));


	/* Loop over the dimensions to grab the remaining info ... */
	for( i=0; i < n_dimensions; ++i ){
	//
	/* get (and print) the dimension names for all dimensions*
	... remember that since miget_dimension_name calls strdup which, in turn,
	... calls malloc to get memory for the new string -- we need to call "mifree" on
	... our pointer to release that memory.  */
		result = miget_dimension_name(dimensions[i], &dim_name);
		
		// do we have a time dimension?
		if ( !strcmp(dim_name, "time") ) { 
			time_dim_exists = TRUE;
			n_frames = ( time_dim_exists ) ? dim_sizes[0] : 0;
		}
		
		// store the dimension name and units
		SET_STRING_ELT(xDimNames, i, mkChar(dim_name));
		mifree_name(dim_name);
		
		result = miget_dimension_units(dimensions[i], &dim_units);
		SET_STRING_ELT(xDimUnits, i, mkChar(dim_units));
		mifree_name(dim_units);
		
	}
	/* add number of frames to return list */
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, ScalarInteger(n_frames));
	SET_STRING_ELT(listNames, list_index, mkChar("nFrames"));
	
	// add dim names to return list
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, xDimNames);
	SET_STRING_ELT(listNames, list_index, mkChar("dimNames"));
	// add dim units
	list_index++;
	SET_VECTOR_ELT(rtnList, list_index, xDimUnits);
	SET_STRING_ELT(listNames, list_index, mkChar("dimUnits"));


	/* get the dimension OFFSETS values for the TIME dimension */
	if ( time_dim_exists ) {

		PROTECT( xTimeOffsets=allocVector(REALSXP,n_frames) );
		n_protects++;
		result = miget_dimension_offsets(dimensions[0], n_frames, 0, time_offsets);
		if ( result == MI_ERROR ) { error("Error returned from miget_dimension_offsets.\n"); }
		/* add to R vector ... */
		for (i=0; i < n_frames; ++i) {
			REAL(xTimeOffsets)[i] = time_offsets[i];
//			if (R_DEBUG_mincIO) Rprintf("Time offset[%d] =  %g\n", i, time_offsets[i]);
		}
		list_index++;
		SET_VECTOR_ELT(rtnList, list_index, xTimeOffsets);
		SET_STRING_ELT(listNames, list_index, mkChar("timeOffsets"));

		/* get the dimension WIDTH values for the TIME dimension */
		PROTECT( xTimeWidths=allocVector(REALSXP,n_frames) );
		n_protects++;
	
		result = miget_dimension_widths(dimensions[0], MI_ORDER_FILE, n_frames, 0, time_widths);
		if ( result == MI_ERROR ) { error("Error returned from miget_dimension_widths.\n"); }
		/* add to R vector ... */
		for (i=0; i<n_frames; ++i) {
			REAL(xTimeWidths)[i] = time_widths[i];
//			if (R_DEBUG_mincIO) Rprintf("Time width[%d] =  %g\n", i, time_widths[i]);
		}
		list_index++;
		SET_VECTOR_ELT(rtnList, list_index, xTimeWidths);
		SET_STRING_ELT(listNames, list_index, mkChar("timeWidths"));
	}



	// free heap memory
	free(dimensions);


	/* close volume */
	miclose_volume(minc_volume);


	/* attach the list component names to the list */
	setAttrib(rtnList, R_NamesSymbol, listNames);


	/* remove gc collection protection */
	UNPROTECT(n_protects);

   /* return */
	if ( R_DEBUG_mincIO ) Rprintf("get_volume_info: returning ...\n");
   return(rtnList);
}
Пример #22
0
int main(void)
{
    mihandle_t vol;
    int r;
    midimhandle_t dim[NDIMS];
    int n;
    misize_t coords[NDIMS];
    misize_t count[NDIMS];
    int i,j,k;
    double offset;
    unsigned int voxel;

    /* Write data one voxel at a time. */
    for (i = 0; i < NDIMS; i++) {
        count[i] = 1;
    }

    r = micreate_dimension("time", MI_DIMCLASS_TIME,
                           MI_DIMATTR_NOT_REGULARLY_SAMPLED, CT, &dim[0]);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    for (i = 0; i < CT; i++) {
        offset = (i * i) + 100.0;
        r = miset_dimension_offsets(dim[0], 1, i, &offset);
        if (r < 0) {
            TESTRPT("failed", r);
        }
    }

    r = micreate_dimension("xspace",MI_DIMCLASS_SPATIAL,
                           MI_DIMATTR_REGULARLY_SAMPLED, CX, &dim[1]);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miset_dimension_start(dim[1], XSTART);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miset_dimension_separation(dim[1], XSTEP);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = micreate_dimension("yspace",MI_DIMCLASS_SPATIAL,
                           MI_DIMATTR_REGULARLY_SAMPLED, CY, &dim[2]);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miset_dimension_start(dim[2], YSTART);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miset_dimension_separation(dim[2], YSTEP);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = micreate_dimension("zspace",MI_DIMCLASS_SPATIAL,
                           MI_DIMATTR_REGULARLY_SAMPLED, CZ, &dim[3]);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miset_dimension_start(dim[3], ZSTART);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miset_dimension_separation(dim[3], ZSTEP);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = micreate_volume("tst-dim.mnc", NDIMS, dim, MI_TYPE_UINT,
                        MI_CLASS_REAL, NULL, &vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = micreate_volume_image(vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    check_dims(vol, dim);

    for (i = 0; i < CX; i++) {
        for (j = 0; j < CY; j++) {
            for (k = 0; k < CZ; k++) {
                coords[0] = 0;
                coords[1] = i;
                coords[2] = j;
                coords[3] = k;

                voxel = (i*10000)+(j*100)+k;
                r = miset_voxel_value_hyperslab(vol, 
                                                MI_TYPE_UINT,
                                                coords,
                                                count, 
                                                &voxel);
                if (r < 0) {
                    TESTRPT("Error writing voxel", r);
                }
            }
        }
    }


    r = miclose_volume(vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    /***** 03-Aug-2004: Added two tests for bugs reported by Leila */

    r = miopen_volume("tst-dim.mnc", MI2_OPEN_RDWR, &vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miget_volume_dimension_count(vol, MI_DIMCLASS_ANY,
                                     MI_DIMATTR_REGULARLY_SAMPLED, &n);
    if (r < 0) {
        TESTRPT("failed", r);
    }
    if (n != NDIMS - 1) {
        TESTRPT("wrong result", n);
    }

    r = miget_volume_dimension_count(vol, MI_DIMCLASS_ANY,
                                     MI_DIMATTR_NOT_REGULARLY_SAMPLED, &n);
    if (r < 0) {
        TESTRPT("failed", r);
    }
    if (n != 1) {
        TESTRPT("wrong result", n);
    }

    r = miclose_volume(vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    /* Test #2 - verify that we don't print anything scary if a user
     * closes a volume prematurely.
     */
    r = micreate_dimension("xspace",MI_DIMCLASS_SPATIAL,
                           MI_DIMATTR_REGULARLY_SAMPLED, CX, &dim[0]);
    if (r < 0) {
        TESTRPT("failed", r);
    }
    r = micreate_dimension("yspace",MI_DIMCLASS_SPATIAL,
                           MI_DIMATTR_REGULARLY_SAMPLED, CY, &dim[1]);
    if (r < 0) {
        TESTRPT("failed", r);
    }
    r = micreate_dimension("zspace",MI_DIMCLASS_SPATIAL,
                           MI_DIMATTR_REGULARLY_SAMPLED, CZ, &dim[2]);
    if (r < 0) {
        TESTRPT("failed", r);
    }
    r = micreate_volume("tst-vol.mnc", 3, dim, MI_TYPE_SHORT,
                        MI_CLASS_LABEL, NULL, &vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }

    r = miclose_volume(vol);
    if (r < 0) {
        TESTRPT("failed", r);
    }
    /** End of tests added 03-Aug-2004 **/

    if (error_cnt != 0) {
        fprintf(stderr, "%d error%s reported\n", 
                error_cnt, (error_cnt == 1) ? "" : "s");
    }
    else {
        fprintf(stderr, "No errors\n");
    }
    return (error_cnt);
}
Пример #23
0
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
 *  Purpose:
 *
 *    Convert world coordinates to a vector of voxel coords
 *
 * NOTE: 
 *    (1) 0-relative voxel coordinates are being returned
 *    (2) output voxel coordinates are in volume order, which we are forcing to be (t)zyx
 *    (3) input world coordinates are in xyz order
 *    (4) if the volume has 4D, then 4 voxel coords are returned, else 3 of 'em
 *
 * * * * * * * * * * * * * */
SEXP convert_world_to_voxel_mincIO(SEXP filename, SEXP worldCoords) {

	int			result, ndx;
	int			n_dimensions;
	mihandle_t	minc_volume;
	double		voxel_coords[MI2_MAX_VAR_DIMS];
	double		world_coords[MI2_3D];
	static char *dimorder3d[] = { "zspace","yspace","xspace" };
	static char *dimorder4d[] = { "time", "zspace","yspace","xspace" };
	
	SEXP		output;



	// start ...
	if ( R_DEBUG_mincIO ) Rprintf("convert_world_to_voxel: start ...\n");

	// init the world coordinates
	for ( ndx=0; ndx < MI2_3D; ++ndx ) {
		world_coords[ndx] = REAL(worldCoords)[ndx];
	}

	/* open the volume */
	result = miopen_volume(CHAR(STRING_ELT(filename,0)), MI2_OPEN_READ, &minc_volume);
	//
	if (result != MI_NOERROR) {
		error("Error opening input file: %s.\n", CHAR(STRING_ELT(filename, 0)));
	}


	/* set the apparent order to something conventional */
	//	... first need to get the number of dimensions
	if ( miget_volume_dimension_count(minc_volume, MI_DIMCLASS_ANY, MI_DIMATTR_ALL, &n_dimensions) != MI_NOERROR ){
		error("Error returned from miget_volume_dimension_count.\n");
	}
	/* ... now set the order */
	if ( R_DEBUG_mincIO ) Rprintf("convert_world_to_voxel: Setting the apparent order for %d dimensions ... ", n_dimensions);
	if ( n_dimensions == 3 ) {
		result = miset_apparent_dimension_order_by_name(minc_volume, 3, dimorder3d);
	} else if ( n_dimensions == 4 ) {
		result = miset_apparent_dimension_order_by_name(minc_volume, 4, dimorder4d);
	} else {
		error("Error file %s has %d dimensions and we can only deal with 3 or 4.\n", CHAR(STRING_ELT(filename,0)), n_dimensions);
	}
	
	if ( result != MI_NOERROR ) { 
		error("Error returned from miset_apparent_dimension_order_by_name while setting apparent order for %d dimensions.\n", n_dimensions); 
	}
	if ( R_DEBUG_mincIO ) Rprintf("Done.\n");


	// do the call
	miconvert_world_to_voxel(minc_volume,  world_coords, voxel_coords);

	// allocate output vector and then copy the results into it
	PROTECT(output=allocVector(REALSXP, n_dimensions));
	for ( ndx=0; ndx < n_dimensions; ++ndx ) {
		REAL(output)[ndx] = voxel_coords[ndx];
	}

	// remove protection and return vector
	UNPROTECT(1);
	if ( R_DEBUG_mincIO ) Rprintf("convert_world_to_voxel: returning ...\n");
	return(output);
}
Пример #24
0
SEXP minc2_apply(SEXP filenames, SEXP fn, SEXP have_mask, 
		 SEXP mask, SEXP mask_value, SEXP rho) {
  int                result;
  mihandle_t         *hvol, hmask;
  int                i, v0, v1, v2, output_index, buffer_index;
  unsigned long     start[3], count[3];
  //unsigned long      location[3];
  int                num_files;
  double             *xbuffer, *xoutput, **full_buffer;
  double             *xhave_mask, *xmask_value;
  double             *mask_buffer;
  midimhandle_t      dimensions[3];
  misize_t            sizes[3];
  SEXP               output, buffer;
  //SEXP               R_fcall;
  

  /* allocate memory for volume handles */
  num_files = LENGTH(filenames);
  hvol = malloc(num_files * sizeof(mihandle_t));

  Rprintf("Number of volumes: %i\n", num_files);

  /* open the mask - if so desired */
  xhave_mask = REAL(have_mask);
  if (xhave_mask[0] == 1) {
    result = miopen_volume(CHAR(STRING_ELT(mask, 0)),
			   MI2_OPEN_READ, &hmask);
    if (result != MI_NOERROR) {
      error("Error opening mask: %s.\n", CHAR(STRING_ELT(mask, 0)));
    }
  }
  
  /* get the value inside that mask */
  xmask_value = REAL(mask_value);

  /* open each volume */
  for(i=0; i < num_files; i++) {
    result = miopen_volume(CHAR(STRING_ELT(filenames, i)),
      MI2_OPEN_READ, &hvol[i]);
    if (result != MI_NOERROR) {
      error("Error opening input file: %s.\n", CHAR(STRING_ELT(filenames,i)));
    }
  }

  /* get the file dimensions and their sizes - assume they are the same*/
  miget_volume_dimensions( hvol[0], MI_DIMCLASS_SPATIAL,
			   MI_DIMATTR_ALL, MI_DIMORDER_FILE,
			   3, dimensions);
  result = miget_dimension_sizes( dimensions, 3, sizes );
  Rprintf("Volume sizes: %i %i %i\n", sizes[0], sizes[1], sizes[2]);

  /* allocate the output buffer */
  PROTECT(output=allocVector(REALSXP, (sizes[0] * sizes[1] * sizes[2])));
  xoutput = REAL(output);

  /* allocate the local buffer that will be passed to the function */
  PROTECT(buffer=allocVector(REALSXP, num_files));
  xbuffer = REAL(buffer); 

  //PROTECT(R_fcall = lang2(fn, R_NilValue));


  /* allocate first dimension of the buffer */
  full_buffer = malloc(num_files * sizeof(double));

  /* allocate second dimension of the buffer 
     - big enough to hold one slice per subject at a time */
  for (i=0; i < num_files; i++) {
    full_buffer[i] = malloc(sizes[1] * sizes[2] * sizeof(double));
  }
  
  /* allocate buffer for mask - if necessary */
  if (xhave_mask[0] == 1) {
    mask_buffer = malloc(sizes[1] * sizes[2] * sizeof(double));
  }
	
  /* set start and count. start[0] will change during the loop */
  start[0] = 0; start[1] = 0; start[2] = 0;
  count[0] = 1; count[1] = sizes[1]; count[2] = sizes[2];

  /* loop across all files and voxels */
  Rprintf("In slice \n");
  for (v0=0; v0 < sizes[0]; v0++) {
    start[0] = v0;
    for (i=0; i < num_files; i++) {
      if (miget_real_value_hyperslab(hvol[i], 
				     MI_TYPE_DOUBLE, 
				     (misize_t *) start, 
				     (misize_t *) count, 
				     full_buffer[i]) )
	error("Error opening buffer.\n");
    }
    /* get mask - if desired */
    if (xhave_mask[0] == 1) {
      if (miget_real_value_hyperslab(hmask, 
				     MI_TYPE_DOUBLE, 
				     (misize_t *) start, 
				     (misize_t *) count, 
				     mask_buffer) )
	error("Error opening mask buffer.\n");
    }

    Rprintf(" %d ", v0);
    for (v1=0; v1 < sizes[1]; v1++) {
      for (v2=0; v2 < sizes[2]; v2++) {
	output_index = v0*sizes[1]*sizes[2]+v1*sizes[2]+v2;
	buffer_index = sizes[2] * v1 + v2;

	/* only perform operation if not masked */
	if(xhave_mask[0] == 0 
	   || (xhave_mask[0] == 1 && 
	       mask_buffer[buffer_index] > xmask_value[0] -0.5 &&
	       mask_buffer[buffer_index] < xmask_value[0] + 0.5)) {
	
	  for (i=0; i < num_files; i++) {
// 	    location[0] = v0;
// 	    location[1] = v1;
// 	    location[2] = v2;
	    //SET_VECTOR_ELT(buffer, i, full_buffer[i][index]);
	    //result = miget_real_value(hvol[i], location, 3, &xbuffer[i]);
	    xbuffer[i] = full_buffer[i][buffer_index];
	    
	    //Rprintf("V%i: %f\n", i, full_buffer[i][index]);

	  }
	  /* install the variable "x" into environment */
	  defineVar(install("x"), buffer, rho);
	  //SETCADDR(R_fcall, buffer);
	  //SET_VECTOR_ELT(output, index, eval(R_fcall, rho));
	  //SET_VECTOR_ELT(output, index, test);
	  /* evaluate the function */
	  xoutput[output_index] = REAL(eval(fn, rho))[0]; 
	}
	else {
	  xoutput[output_index] = 0;
	}
      }
    }
  }
  Rprintf("\nDone\n");

  /* free memory */
  for (i=0; i<num_files; i++) {
    miclose_volume(hvol[i]);
    free(full_buffer[i]);
  }
  free(full_buffer);
  UNPROTECT(2);

  /* return the results */
  return(output);
}
Пример #25
0
int main(int argc, char **argv)
{
    mihandle_t vol;

    midimhandle_t dim[NDIMS];

    unsigned int sizes[NDIMS];
    unsigned long start[NDIMS];
    unsigned long count[NDIMS];
    unsigned long howfar[NDIMS];
    unsigned long location[NDIMS];
    double *buffer,value;
    int r = 0;

    static char *dimorder[] = {"xspace", "yspace", "zspace"};

    printf("Creating image with slice scaling!! \n");
    create_test_file();
    printf("Opening hyperslab-test2.mnc! \n");

    r = miopen_volume("hyperslab-test2.mnc", MI2_OPEN_READ, &vol);

    if (r < 0) {
        TESTRPT("failed to open image", r);
    }

#ifdef APPARENTORDER
    /* set the apparent dimension order to be xyz */
    r  = miset_apparent_dimension_order_by_name(vol, 3, dimorder);

    /* get the apparent dimensions and their sizes */
    r  = miget_volume_dimensions( vol, MI_DIMCLASS_SPATIAL,
                                  MI_DIMATTR_ALL, MI_DIMORDER_APPARENT,
                                  3, dim);
    r = miget_dimension_sizes( dim, 3, sizes );
#else
    /* get the apparent dimensions and their sizes */
    r = miget_volume_dimensions( vol, MI_DIMCLASS_SPATIAL,
                                 MI_DIMATTR_ALL, MI_DIMORDER_FILE,
                                 3, dim);
    r = miget_dimension_sizes( dim, 3, sizes );
#endif
    if (r == MI_NOERROR) {
        printf("Sizes: %d, %d, %d\n", sizes[0], sizes[1], sizes[2]);
    }
    else {
        fprintf(stderr, "Error getting dimension sizes\n");
    }
    /* try to play with hyperslab functions!! */
    start[0] = 4;
    start[1] = 3;
    start[2] = 5;

    howfar[0] = 120;
    howfar[1] = 180;
    howfar[2] = 110;

    count[0] = howfar[0] - start[0];
    count[1] = howfar[1] - start[1];
    count[2] = howfar[2] - start[2];

    /* Alocate memory for the hyperslab*/
    buffer = (double *)malloc(count[0] * count[1] * count[2] * sizeof(double));
    if (buffer == NULL) {
        fprintf(stderr, "Error allocation memory.\n");
        exit(-1);
    }

    /* Get real value hyperslab*/
    printf("\n");
    printf("Getting a real value hyperslab \n");
    printf("Starting at %d, %d, %d \n", start[0], start[1], start[2]);
    printf("Extending to %d, %d, %d \n", howfar[0], howfar[1], howfar[2]);
    printf("\n");
    if (miget_real_value_hyperslab(vol,MI_TYPE_DOUBLE, start, count, buffer)
            < 0) {
        fprintf(stderr, "Could not get hyperslab.\n");
        exit(-1);
    }
    /* set an arbitrary location to print values from */
    location[0] = 70;
    location[1] = 100;
    location[2] = 104;
    printf("Test arbitrary location %d, %d, %d \n",
           location[0], location[1], location[2]);
    miget_real_value(vol, location, 3, &value);
    printf("Test from hyperslab: %f \n",
           *( buffer + (location[0] - start[0])*count[1]*count[2] +
              (location[1]- start[1]) * count[2] + (location[2]- start[2])));
    printf("Test from voxel scaled: %f\n", value);
    miget_voxel_value(vol, location, 3, &value);
    printf("Test voxel value itself: %f\n", value);
    printf("\n");
    printf("HMMMMMMMMMM! let's try something else \n");
    printf("\n");
    /* set another arbitrary location to print values from */
    location[0] = 104;
    location[1] = 100;
    location[2] = 70;
    printf("Test arbitrary location %d, %d, %d \n",
           location[0], location[1], location[2]);
    miget_real_value(vol, location, 3, &value);
    printf("Test from hyperslab: %f \n",
           *( buffer + (location[0] - start[0])*count[1]*count[2] +
              (location[1]- start[1]) * count[2] + (location[2]- start[2])));
    printf("Test from voxel scaled: %f\n", value);
    miget_voxel_value(vol, location, 3, &value);
    printf("Test voxel value itself: %f\n", value);

    /* close volume*/
    miclose_volume(vol);

    if (error_cnt != 0) {
        fprintf(stderr, "%d error%s reported\n",
                error_cnt, (error_cnt == 1) ? "" : "s");
    }
    else {
        fprintf(stderr, "\n No errors\n");
    }

    return (error_cnt);
}
Пример #26
0
void MINCResource::Load() {
    if (loaded) return;

    int result = miopen_volume(file.c_str(), MI2_OPEN_READ, &handle); 
    if (result != MI_NOERROR) {
        logger.warning << "Error opening the MINC input file: " << file << logger.end;
        return;
    }

    // char** names = new char*[3];
    // names[0] = "x_space";
    // names[1] = "y_space";
    // names[2] = "z_space";
    
    // miset_apparent_dimension_order_by_name(handle, 3, names);



    
    int count;
    miget_volume_voxel_count(handle, &count);
    logger.info << "voxel count: " << count << logger.end;

    // atomic type of the resulting texture (float, int)
    miclass_t klass;
    miget_data_class(handle, &klass);
    logger.info << "data class: " << klass << logger.end;

    // data type of a voxel (float, uchar, ...)
    // convert this type into class type by scaling.
    mitype_t type;
    miget_data_type(handle, &type);
    logger.info << "voxel type: " << type << logger.end;

    misize_t vsize;
    miget_data_type_size(handle, &vsize);
    logger.info << "voxel size in bytes: " << vsize << logger.end;

    midimhandle_t dims[3];
    result = miget_volume_dimensions(handle, MI_DIMCLASS_SPATIAL, 
                                     MI_DIMATTR_ALL, MI_DIMORDER_FILE, 
                                     3, dims);

    if (result != 3) {
        logger.warning << "Only three spatial dimensions supported. Volume has " << result << logger.end;
        return;
    }

    w = h = d = 0;
    // hack: in our files dimensions are given in z,y,x order, so we reverse it.
    miget_dimension_size(dims[0], &w);
    miget_dimension_size(dims[1], &h);
    miget_dimension_size(dims[2], &d);

    // midimhandle_t* dims_app = new midimhandle_t[3];
    // dims_app[0] = dims[2];
    // dims_app[1] = dims[1];
    // dims_app[2] = dims[0];

    // miset_apparent_dimension_order (handle, 3, dims_app);
    logger.info << "dimensions: " << w << " x " << h << " x " << d << logger.end;

    
    // count records
    int recs = 0;
    miget_record_length(handle, &recs);
    logger.info << "record length: " << recs << logger.end;

    // count labels
    int lbls = 0;
    miget_number_of_defined_labels(handle, &lbls);
    logger.info << "# of labels: " << lbls << logger.end;

    // count attributes
    milisthandle_t lhandle;
    milist_start(handle, "", 0, &lhandle);
    char* path = new char[255];
    char* name = new char[255];
    while (milist_attr_next(handle, lhandle, path, 255, name, 255) == MI_NOERROR) {
        logger.info << "path: " << string(path) << " name: " << string(name) << logger.end;
    }
    milist_finish(lhandle);
    delete path;
    delete name;

    // char* nm;
    // miget_dimension_name(dims[2], &nm);
    // string hest(nm);
    // mifree_name(nm);
    // logger.info << "dimension name: " << hest << logger.end;

    char* space_name;
    miget_space_name(handle, &space_name);
    logger.info << "space name: " << string(space_name) << logger.end;
    mifree_name(space_name);

    loaded = true;
}