コード例 #1
0
ファイル: vdeform.C プロジェクト: Rollmops/lipsia
void ReadImages (VString Name, VAttrList& Images, VAttrList& history_list)
{
   FILE*         file;    /* input file       */
   VAttrList     list, list1;    /* attribute list   */
   VAttrListPosn pos;     /* position in list */
   VImage        image;   /* image in list    */


   /* initialize results */
   Images  = NULL;

   /* open file */
   file = fopen (Name, "r");
   if (!file)
   {
      VError ("Failed to open input file '%s'", Name);
      return;
   }

   /* read file */
   list = VReadFile (file, NULL);
   if (!list)
   {
      VError ("Failed to read input file '%s'", Name);
      fclose (file);
      return;
   }

   /* Read History */
   list1 = VReadHistory(&list);
   if (list1==NULL) list1=VCreateAttrList();
   history_list = VCopyAttrList(list1);

   /* extract images */
   for (VFirstAttr (list, &pos); VAttrExists (&pos); VNextAttr (&pos))
   {
      if (VGetAttrRepn (&pos) != VImageRepn) continue;
      if (!Images) Images = VCreateAttrList ();
      VGetAttrValue (&pos, NULL, VImageRepn, &image);
      VSetAttrValue (&pos, NULL, VImageRepn, NULL);
      VAppendAttr (Images, "image", NULL, VImageRepn, image);
   }
   if (!Images) VError ("Input file '%s' does not contain an image", Name);

   /* clean-up*/
   VDestroyAttrList (list);
   fclose (file);

} /* ReadImages */
コード例 #2
0
ファイル: graph.c プロジェクト: Frederik-D-Weber/spisop
VGraph VCreateGraph (int size, int nfields, VRepnKind repn, int useW)
{
  VGraph graph;

  /* Check parameters: */
  if (size < 1  || nfields < 1)
    VWarning ("VCreateGraph: Invalid number of nodes or fields.");

  /* Allocate memory for the VGraph, and the node table: */
  graph = VMalloc (sizeof (VGraphRec));
  if (graph == NULL) return NULL;

  graph->table = VCalloc(size, sizeof(VNode));
  if (graph->table == NULL) {
    VFree(graph);
    return NULL;
  };

  /* Initialize the VGraph: */
  graph->nnodes = 0;
  graph->nfields = nfields;
  graph->node_repn = repn;
  graph->attributes = VCreateAttrList ();
  graph->lastUsed = 0;
  graph->size = size;
  graph->useWeights = useW;
  graph->iter = 0;

  return graph;
}
コード例 #3
0
ファイル: FIL_Vista_File.c プロジェクト: KoraST/ft_BIU-1
VBoolean VWriteObjects (FILE *file, VRepnKind repn, VAttrList attributes,
			int nobjects, VPointer objects[])
{
    VAttrList list;
    VAttrListPosn posn;
    int i;
    VBoolean result;

    /* Create an attribute list if none was supplied: */
    list = attributes ? attributes : VCreateAttrList ();

    /* Prepend to the attribute list an attribute for each object: */
    for (i = nobjects - 1; i >= 0; i--)
	VPrependAttr (list, VRepnName (repn), NULL, repn, objects[i]);

    /* Write the attribute list: */
    result = VWriteFile (file, list);

    /* Remove the attributes just prepended: */
    VFirstAttr (list, & posn);
    for (i = 0; i < nobjects; i++)
	VDeleteAttr (& posn);
    if (list != attributes)
	VDestroyAttrList (list);

    return result;
}
コード例 #4
0
ファイル: plaintov.c プロジェクト: Rollmops/via
int main (int argc, char **argv)
{
    FILE *in_file, *out_file;
    VImage image;
    VAttrList list = VCreateAttrList ();
    char prg[50];	
    sprintf(prg,"plaintov V%s", getVersion());
    fprintf (stderr, "%s\n", prg);


    VParseFilterCmd (VNumber (options), options, argc, argv,
		     & in_file, & out_file);
    
    if (! (image = VReadPlain (in_file)))
	exit (EXIT_FAILURE);

    VHistory(VNumber(options),options,prg,&list,&list);
    VAppendAttr (list, object_name, NULL, VImageRepn, image);
    if (! VWriteFile (out_file, list))
	exit (EXIT_FAILURE);

    fprintf (stderr, "%s: Converted 1 file from Vista plain format"
	     " to Vista format.\n", argv[0]);

    return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: vcovariates.c プロジェクト: Rollmops/lipsia
int
main(int argc, char *argv[]) {
    static VString cfile = "";
    static VFloat tr = 2;
    static VBoolean normalize = FALSE;
    static VOptionDescRec  options[] = {
        {"in", VStringRepn, 1, (VPointer) &cfile, VRequiredOpt, NULL, "file"},
        {"tr", VFloatRepn, 1, (VPointer) &tr, VRequiredOpt, NULL, "TR in seconds"},
        {"normalize", VBooleanRepn, 1, (VPointer) &normalize, VOptionalOpt, NULL, "Whether to normalize"}
    };
    FILE *out_file = NULL;
    VAttrList list = NULL;
    VImage dest = NULL;
	char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vcovariates V%s", ver);
	fprintf(stderr, "%s\n", prg_name);
    VParseFilterCmd(VNumber(options), options, argc, argv, NULL, &out_file);
    if(tr > 500)
        VError(" tr must be given in seconds, not milliseconds");
    dest = VCovariates(cfile, tr, normalize);
    list = VCreateAttrList();
    VAppendAttr(list, "image", NULL, VImageRepn, dest);
    /* Output: */
    if(! VWriteFile(out_file, list))
        exit(1);
    fprintf(stderr, " %s: done.\n", argv[0]);
    return 0;
}
コード例 #6
0
ファイル: vsimmat.c プロジェクト: Rollmops/lipsia
int
main(int argc, char *argv[]) {
    static VString filename = "";
    static VBoolean fisher = FALSE;
    static VShort  minval = 0;
    static VOptionDescRec  options[] = {
        {"mask", VStringRepn, 1, (VPointer) &filename, VRequiredOpt, NULL, "mask"},
        {"fisher", VBooleanRepn, 1, (VPointer) &fisher, VOptionalOpt, NULL, "Whether to do fisher transform"},
        {"minval", VShortRepn, 1, (VPointer) &minval, VOptionalOpt, NULL, "signal threshold"}
    };
    FILE *in_file, *out_file, *fp;
    VAttrList list = NULL, list1 = NULL, list2 = NULL;
    VAttrListPosn posn;
    VImage dest = NULL, mask = NULL;
	char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vsimmat V%s", ver);
	fprintf(stderr, "%s\n", prg_name);
    VParseFilterCmd(VNumber(options), options, argc, argv, &in_file, &out_file);
    /*
    ** read mask
    */
    fp = VOpenInputFile(filename, TRUE);
    list1 = VReadFile(fp, NULL);
    if(! list1)
        VError("Error reading mask file");
    fclose(fp);
    for(VFirstAttr(list1, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & mask);
        if(VPixelRepn(mask) != VBitRepn) {
            mask = NULL;
            continue;
        }
    }
    if(mask == NULL)
        VError(" no mask found");
    /*
    ** read functional data
    */
    if(!(list = VReadFile(in_file, NULL)))
        exit(1);
    fclose(in_file);
    /*
    ** process
    */
    dest = SimilarityMatrix(list, mask, minval, fisher);
    list2 = VCreateAttrList();
    VAppendAttr(list2, "matrix", NULL, VImageRepn, dest);
    VHistory(VNumber(options), options, prg_name, &list, &list2);
    if(! VWriteFile(out_file, list2))
        exit(1);
    fprintf(stderr, "%s: done.\n", argv[0]);
    return 0;
}
コード例 #7
0
ファイル: graph.c プロジェクト: Frederik-D-Weber/spisop
static VAttrList VGraphEncodeAttrMethod (VPointer value, size_t *lengthp)
{
  VGraph graph = value;
  VAttrList list;
  size_t len, nadj;
  int i, slong, sfloat, spriv, nnodes;
  VNode n;
  VAdjacency adj;

  /* Compute the file space needed for the Graph's binary data: */
  len = 0;
  slong = VRepnPrecision (VLongRepn) / 8;
  sfloat = VRepnPrecision (VFloatRepn) / 8;
  spriv = graph->nfields * VRepnPrecision (graph->node_repn) / 8;

  nnodes = 0;
  for (i = 1; i <= graph->size; i++) {
    n = VGraphGetNode(graph, i); if (n == 0) continue;
    ++nnodes;
    /* Count the number of adjacencies : */
    for (adj = n->base.head, nadj = 0; adj; adj = adj->next) nadj++;

    /* each node contains:
     * an index and the number of adjacencies
     * the private data area
     * the list of adjacencies
     * optionally reserve space for weights
     */
    len += 2 * slong + nadj * slong + spriv;
    if (graph->useWeights) len += (nadj+1) * sfloat;
  };
  *lengthp = len;
  assert(nnodes == graph->nnodes);	 /* for debugging */
  graph->nnodes = nnodes;		 /* just to be safe for now... */

  /* Temporarily prepend several attributes to the graph's list: */
  if ((list = VGraphAttrList (graph)) == NULL)
    list = VGraphAttrList (graph) = VCreateAttrList ();
  VPrependAttr (list, VRepnAttr, VNumericRepnDict,
		VLongRepn, (VLong) graph->node_repn);
  VPrependAttr (list, VNNodeFieldsAttr, NULL, VLongRepn,
		(VLong) graph->nfields);
  VPrependAttr (list, VNGraphSizeAttr, NULL, VLongRepn,
		(VLong) graph->size);
  VPrependAttr (list, VNNodeWeightsAttr, NULL, VLongRepn,
		(VLong) graph->useWeights);

  return list;
}
コード例 #8
0
ファイル: vdeform.C プロジェクト: Rollmops/lipsia
VBoolean WriteImages (VString Name, VAttrList Images, VAttrList& history_list)
{
   FILE*         file;      /* output file      */
   VAttrList     list;      /* attribute list   */
   VAttrListPosn pos;       /* position in list */
   VImage        image;     /* image in list    */
   VBoolean      success;   /* success flag     */
   char history[]="history";

   /* open file */
   file = fopen (Name, "w");
   if (!file)
   {
      VError ("Failed to open output file '%s'", Name);
      return FALSE;
   }

   /* create list */
   list = VCreateAttrList();
 
   /* insert images */
   for (VFirstAttr (Images, &pos); VAttrExists (&pos); VNextAttr (&pos))
   {
      VGetAttrValue (&pos, NULL, VImageRepn, &image);
      VAppendAttr (list, VGetAttrName (&pos), NULL, VImageRepn, image);
   }

   /* Prepend history */
   VPrependAttr(list, history ,NULL,VAttrListRepn,history_list);
   
   /* write file */
   success = VWriteFile (file, list);
   if (!success) VError ("Failed to write output file '%s'", Name);

   /* remove images */
   for (VFirstAttr (list, &pos); VAttrExists (&pos); VNextAttr (&pos))
      if (VGetAttrRepn (&pos) == VImageRepn)
         VSetAttrValue (&pos, NULL, VImageRepn, NULL);

   /* clean-up*/
   VDestroyAttrList (list);
   fclose (file);

   return success;

} /* WriteImages */
コード例 #9
0
ファイル: FIL_Vista_Image.c プロジェクト: KoraST/ft_BIU-1
VImage VCopyImageAttrs (VImage src, VImage dest)
{
  VAttrList list;

  if (src == dest)
    return dest;
  if (! dest) {
    dest = VCreateImage (VImageNBands (src), VImageNRows (src),
			 VImageNColumns (src), VPixelRepn (src));
    if (! dest)
      return NULL;
  }

  /* Clone the source image's attribute list if it isn't empty: */
  if (! VAttrListEmpty (VImageAttrList (src))) {
    list = VImageAttrList (dest);
    VImageAttrList (dest) = VCopyAttrList (VImageAttrList (src));
  } else if (! VAttrListEmpty (VImageAttrList (dest))) {
    list = VImageAttrList (dest);
    VImageAttrList (dest) = VCreateAttrList ();
  } else list = NULL;
  if (list)
    VDestroyAttrList (list);

  /* Preserve band interpretation attributes only if the source and
     destination images have the same number of bands: */
  if (VImageNBands (src) > 1 && VImageNBands (dest) == VImageNBands (src)) {
    VImageNFrames (dest) = VImageNFrames (src);
    VImageNViewpoints (dest) = VImageNViewpoints (src);
    VImageNColors (dest) = VImageNColors (src);
    VImageNComponents (dest) = VImageNComponents (src);
  } else {
    VExtractAttr (VImageAttrList (dest), VFrameInterpAttr, NULL,
		  VBitRepn, NULL, FALSE);
    VExtractAttr (VImageAttrList (dest), VViewpointInterpAttr, NULL,
		  VBitRepn, NULL, FALSE);
    VExtractAttr (VImageAttrList (dest), VColorInterpAttr, NULL,
		  VBitRepn, NULL, FALSE);
    VExtractAttr (VImageAttrList (dest), VComponentInterpAttr, NULL,
		  VBitRepn, NULL, FALSE);
    VImageNComponents (dest) = VImageNColors (dest) = 
      VImageNViewpoints (dest) = 1;
    VImageNFrames (dest) = VImageNBands (dest);
  }
  return dest;
}
コード例 #10
0
ファイル: Edges.c プロジェクト: Rollmops/via
VEdges VCreateEdges (int nrows, int ncolumns,
		     int nedge_fields, int npoint_fields)
{
    VEdges edges;

    /* Check parameters: */
    if (nrows < 1  ||  ncolumns < 1)
	VWarning ("VCreateEdges: Invalid number of rows or columns.");

    /* Allocate memory for the VEdges, its indices, and pixel values: */
    edges = VMalloc (sizeof (VEdgesRec));

    /* Initialize the VEdges: */
    edges->nrows = nrows;
    edges->ncolumns = ncolumns;
    edges->attributes = VCreateAttrList ();
    edges->nedge_fields = nedge_fields;
    edges->npoint_fields = npoint_fields;
    edges->nedges = edges->npoints = 0;
    edges->first = edges->last = NULL;
    edges->free = NULL;

    return edges;
}
コード例 #11
0
ファイル: FIL_Vista_Image.c プロジェクト: KoraST/ft_BIU-1
static VAttrList VImageEncodeAttrMethod (VPointer value, size_t *lengthp)
{
  VImage image = value;
  VAttrList list;
  size_t length;

#define OptionallyPrepend(value, name)				\
	if (value != 1)							\
	    VPrependAttr (list, name, NULL, VLongRepn, (VLong) value)

  /* Temporarily prepend several attributes to the image's attribute list: */
  if ((list = VImageAttrList (image)) == NULL)
    list = VImageAttrList (image) = VCreateAttrList ();
  VPrependAttr (list, VRepnAttr, VNumericRepnDict,
		VLongRepn, (VLong) VPixelRepn (image));
  VPrependAttr (list, VNColumnsAttr, NULL,
		VLongRepn, (VLong) VImageNColumns (image));
  VPrependAttr (list, VNRowsAttr, NULL,
		VLongRepn, (VLong) VImageNRows (image));
  OptionallyPrepend (VImageNComponents (image), VNComponentsAttr);
  OptionallyPrepend (VImageNColors (image), VNColorsAttr);
  OptionallyPrepend (VImageNViewpoints (image), VNViewpointsAttr);
  OptionallyPrepend (VImageNFrames (image), VNFramesAttr);
  OptionallyPrepend (VImageNBands (image), VNBandsAttr);

  /* Compute the file space needed for the image's binary data: */
  length = VImageNPixels (image);
  if (VPixelRepn (image) == VBitRepn)
    length = (length + 7) / 8;
  else length *= VPixelPrecision (image) / 8;
  *lengthp = length;

  return list;

#undef OptionallyPrepend
}
コード例 #12
0
ファイル: vpaired_ttest.c プロジェクト: Rollmops/lipsia
int main(int argc, char *argv[]) {
    static VArgVector in_files1;
    static VArgVector in_files2;
    static VString out_filename;
    static VShort type = 1;
    static VBoolean gauss = FALSE;
    static VOptionDescRec options[] = {
        {"in1", VStringRepn, 0, & in_files1, VRequiredOpt, NULL, "Input files 1" },
        {"in2", VStringRepn, 0, & in_files2, VRequiredOpt, NULL, "Input files 2" },
        {"type", VShortRepn, 1, (VPointer) &type, VOptionalOpt, TypeDict, "output type"},
        {"gaussianize", VBooleanRepn, 1, (VPointer) &gauss, VOptionalOpt, NULL, "Whether to Gaussianize"},
        {"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL, "Output file" }
    };
    FILE *fp = NULL;
    VStringConst in_filename, buf1, buf2;
    VAttrList list1, list2, out_list;
    VAttrListPosn posn;
    VString str;
    VImage src, *src1, *src2, dest = NULL;
    int i, nimages, npix = 0;
	char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vpaired_ttest V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /*
    ** parse command line
    */
    if(! VParseCommand(VNumber(options), options, & argc, argv)) {
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    if(argc > 1) {
        VReportBadArgs(argc, argv);
        exit(EXIT_FAILURE);
    }
    if(type < 0 || type > 1)
        VError(" illegal type");
    /* ini */
    nimages = in_files1.number;
    if(in_files2.number != nimages)
        VError(" inconsistent number of files %d %d", nimages, in_files2.number);
    for(i = 0; i < nimages; i++) {
        buf1 = ((VStringConst *) in_files1.vector)[i];
        buf2 = ((VStringConst *) in_files2.vector)[i];
        fprintf(stderr, "%3d:  %s  %s\n", i, buf1, buf2);
    }
    fprintf(stderr, "\n");
    /* images 1 */
    src1 = (VImage *) VCalloc(nimages, sizeof(VImage));
    for(i = 0; i < nimages; i++) {
        src1[i] = NULL;
        in_filename = ((VStringConst *) in_files1.vector)[i];
        fp = VOpenInputFile(in_filename, TRUE);
        list1 = VReadFile(fp, NULL);
        if(! list1)
            VError("Error reading image");
        fclose(fp);
        for(VFirstAttr(list1, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VPixelRepn(src) != VFloatRepn)
                continue;
            if(VGetAttr(VImageAttrList(src), "modality", NULL, VStringRepn, &str) == VAttrFound) {
                if(strcmp(str, "conimg") != 0)
                    continue;
            }
            if(i == 0)
                npix = VImageNPixels(src);
            else if(npix != VImageNPixels(src))
                VError(" inconsistent image dimensions");
            src1[i] = src;
            break;
        }
        if(src1[i] == NULL)
            VError(" no contrast image found in %s", in_filename);
    }
    /* images 2 */
    src2 = (VImage *) VCalloc(nimages, sizeof(VImage));
    for(i = 0; i < nimages; i++) {
        src2[i] = NULL;
        in_filename = ((VStringConst *) in_files2.vector)[i];
        fp = VOpenInputFile(in_filename, TRUE);
        list2 = VReadFile(fp, NULL);
        if(! list2)
            VError("Error reading image");
        fclose(fp);
        for(VFirstAttr(list2, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VPixelRepn(src) != VFloatRepn)
                continue;
            if(VGetAttr(VImageAttrList(src), "modality", NULL, VStringRepn, &str) == VAttrFound) {
                if(strcmp(str, "conimg") != 0)
                    continue;
            }
            if(npix != VImageNPixels(src))
                VError(" inconsistent image dimensions");
            src2[i] = src;
            break;
        }
        if(src2[i] == NULL)
            VError(" no contrast image found in %s", in_filename);
    }
    /* make normally distributed */
    if(gauss) {
        VGaussianize(src1, nimages);
        VGaussianize(src2, nimages);
    }
    /* paired t-test */
    dest = PairedTest(src1, src2, dest, nimages, type);
    /*
    ** output
    */
    out_list = VCreateAttrList();
    VHistory(VNumber(options), options, prg_name, &list1, &out_list);
    VAppendAttr(out_list, "image", NULL, VImageRepn, dest);
    fp = VOpenOutputFile(out_filename, TRUE);
    if(! VWriteFile(fp, out_list))
        exit(1);
    fclose(fp);
    fprintf(stderr, "%s: done.\n", argv[0]);
    exit(0);
}
コード例 #13
0
ファイル: vcolorglm.c プロジェクト: karda/lipsia
int
main(int argc, char *argv[]) {
    static VArgVector in_files;
    static VString out_filename;
    static VString filename;
    static VShort minval = 0;
    static VFloat fwhm = 4.0;
    static VOptionDescRec  options[] = {
        {"in", VStringRepn, 0, & in_files, VRequiredOpt, NULL, "Input files" },
        {"out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL, "Output file" },
        {"design", VStringRepn, 1, (VPointer) &filename, VRequiredOpt, NULL, "Design file"},
        {
            "fwhm", VFloatRepn, 1, (VPointer) &fwhm, VOptionalOpt, NULL,
            "FWHM of temporal Gaussian filter in seconds"
        },
        {"minval", VShortRepn, 1, (VPointer) &minval, VOptionalOpt, NULL, "Signal threshold"}
    };
    FILE *fp = NULL, *f = NULL;
    VStringConst in_filename;
    VString ifilename;
    VAttrList list = NULL, list1 = NULL;
    VAttrList out_list = NULL, history_list = NULL;
    VAttrListPosn posn;
    VImage design = NULL;
    ListInfo *linfo;
    VLong itr = 0;
    VFloat sigma = 0, tr = 0;
    int  i, n, nimages;
   char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vcolorglm V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /*
    ** parse command line
    */
    if(! VParseCommand(VNumber(options), options, & argc, argv)) {
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    if(argc > 1) {
        VReportBadArgs(argc, argv);
        exit(EXIT_FAILURE);
    }
    /*
    ** read design matrix
    */
    fp = VOpenInputFile(filename, TRUE);
    list1 = VReadFile(fp, NULL);
    if(! list1)
        VError("Error reading design file");
    fclose(fp);
    n = 0;
    for(VFirstAttr(list1, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & design);
        if(VPixelRepn(design) != VFloatRepn /* && VPixelRepn(design) != VDoubleRepn */)
            continue;
        n++;
        break;
    }
    if(n == 0)
        VError(" design matrix not found ");
    /*
    ** get pre-coloring info
    */
    if(VGetAttr(VImageAttrList(design), "repetition_time", NULL, VLongRepn, &itr) != VAttrFound)
        VError(" TR info missing in header");
    tr = (float) itr / 1000.0;
    sigma = 0;
    if(tr > 0.001 && fwhm > 0.001) {
        fprintf(stderr, " TR: %.3f seconds\n", tr);
        sigma = fwhm / 2.35482;
        sigma /= tr;
        if(sigma < 0.1) {
            VWarning(" 'fwhm/sigma' too small (%.3f / %.3f), will be set to zero", fwhm, sigma);
            sigma = 0;
        }
    }
    /*
    ** Read each input file
    */
    nimages = in_files.number;
    linfo = (ListInfo *) VMalloc(sizeof(ListInfo) * nimages);
    for(i = 0; i < nimages; i++) {
        in_filename = ((VStringConst *) in_files.vector)[i];
        ifilename = VNewString(in_filename);
        fprintf(stderr, " file:  %s\n", ifilename);
        list = GetListInfo(ifilename, &linfo[i]);
        /* Create history */
        if(i == 0) {
            history_list = VReadHistory(&list);
            if(history_list == NULL)
                history_list = VCreateAttrList();
            VPrependHistory(VNumber(options), options, prg_name, &history_list);
        }
    }

    /*
    ** GLM
    */
    out_list = VRegression(linfo, nimages, minval, design, sigma, itr);


    /*
    **  Output:
    */
    VPrependAttr(out_list, "history", NULL, VAttrListRepn, history_list);
    f = VOpenOutputFile(out_filename, TRUE);
    if(!f)
        VError(" error opening outout file %s", out_filename);
    if(! VWriteFile(f, out_list))
        exit(1);
    fprintf(stderr, "%s: done.\n", argv[0]);
    return 0;
}
コード例 #14
0
ファイル: vcolorglm.c プロジェクト: karda/lipsia
/*
** general linear regression
*/
VAttrList
VRegression(ListInfo *linfo, int nlists, VShort minval, VImage design, VFloat sigma, VLong itr) {
    VAttrList out_list;
    VImageInfo *xinfo;
    int nbands = 0, nslices = 0, nrows = 0, ncols = 0, slice, row, col, nr, nc;
    VImage src[NSLICES], res_image = NULL;
    VImage beta_image[MBETA], BCOV = NULL, KX_image = NULL;
    VImage res_map[ETMP];
    float  smooth_fwhm = 0, vx = 0, vy = 0, vz = 0;
    VFloat *float_pp, df;
    VRepnKind repn;
    float d, err;
    int   i, k, l, n, m = 0, nt, fd = 0, npix = 0;
    int   i0 = 0, i1 = 0;
    double u, sig, trace = 0, trace2 = 0, var = 0, sum = 0, nx = 0, mean = 0, sum2;
    float *ptr1, *ptr2;
    double x;
    gsl_matrix_float *X = NULL, *XInv = NULL, *SX = NULL;
    gsl_vector_float *y, *z, *beta, *ys;
    gsl_vector *kernel;
    gsl_matrix_float *S = NULL, *Vc = NULL, *F = NULL, *P = NULL, *Q = NULL;
    gsl_matrix_float *R = NULL, *RV = NULL;
    VBoolean smooth = TRUE;  /* no smoothness estimation */
    gsl_set_error_handler_off();
    /*
    ** read input data
    */
    nslices = nbands = nrows = ncols = 0;
    for(k = 0; k < nlists; k++) {
        n  = linfo[k].nslices;
        nr = linfo[k].nrows;
        nc = linfo[k].ncols;
        nt = linfo[k].ntimesteps;
        nbands += nt;
        if(nslices == 0)
            nslices = n;
        else if(nslices != n)
            VError(" inconsistent image dimensions, slices: %d %d", n, nslices);
        if(nrows == 0)
            nrows = nr;
        else if(nrows != nr)
            VError(" inconsistent image dimensions, rows: %d %d", nr, nrows);
        if(ncols == 0)
            ncols = nc;
        else if(ncols != nc)
            VError(" inconsistent image dimensions, cols: %d %d", nc, ncols);
    }
    fprintf(stderr, " num images: %d,  image dimensions: %d x %d x %d\n",
            nlists, nslices, nrows, ncols);
    /*
    ** get design dimensions
    */
    m = VImageNRows(design);      /* number of timesteps   */
    n = VImageNColumns(design);   /* number of covariates */
    fprintf(stderr, " ntimesteps=%d,   num covariates=%d\n", m, n);
    if(n >= MBETA)
        VError(" too many covariates (%d), max is %d", n, MBETA);
    if(m != nbands)
        VError(" design dimension inconsistency: %d %d", m, nbands);
    fprintf(stderr, " working...\n");
    /*
    ** read design matrix
    */
    X = gsl_matrix_float_alloc(m, n);
    for(k = 0; k < m; k++) {
        for(l = 0; l < n; l++) {
            x = VGetPixel(design, 0, k, l);
            fmset(X, k, l, (float)x);
        }
    }
    /*
    ** pre-coloring, set up K-matrix, S=K, V = K*K^T with K=S
    */
    S  = gsl_matrix_float_alloc(m, m);
    GaussMatrix((double)sigma, S);
    Vc = fmat_x_matT(S, S, NULL);
    /*
    ** compute pseudoinverse
    */
    SX = fmat_x_mat(S, X, NULL);
    XInv = fmat_PseudoInv(SX, NULL);
    /*
    ** get variance estimate
    */
    Q = fmat_x_mat(XInv, Vc, Q);
    F = fmat_x_matT(Q, XInv, F);
    BCOV = VCreateImage(1, n, n, VFloatRepn);
    float_pp = VImageData(BCOV);
    ptr1 = F->data;
    for(i = 0; i < n * n; i++)
        *float_pp++ = *ptr1++;
    gsl_matrix_float_free(Q);
    gsl_matrix_float_free(F);
    /*
    ** get effective degrees of freedom
    */
    R  = gsl_matrix_float_alloc(m, m);
    P = fmat_x_mat(SX, XInv, P);
    gsl_matrix_float_set_identity(R);
    gsl_matrix_float_sub(R, P);
    RV = fmat_x_mat(R, Vc, NULL);
    trace = 0;
    for(i = 0; i < m; i++)
        trace += fmget(RV, i, i);
    P = fmat_x_mat(RV, RV, P);
    trace2 = 0;
    for(i = 0; i < m; i++)
        trace2 += fmget(P, i, i);
    df = (trace * trace) / trace2;
    fprintf(stderr, " df= %.3f\n", df);
    /*
    ** create output images
    */
    xinfo = linfo[0].info;
    out_list = VCreateAttrList();
    res_image = VCreateImage(nslices, nrows, ncols, VFloatRepn);
    VFillImage(res_image, VAllBands, 0);
    VSetAttr(VImageAttrList(res_image), "name", NULL, VStringRepn, "RES/trRV");
    VSetAttr(VImageAttrList(res_image), "modality", NULL, VStringRepn, "RES/trRV");
    VSetAttr(VImageAttrList(res_image), "df", NULL, VFloatRepn, df);
    VSetAttr(VImageAttrList(res_image), "patient", NULL, VStringRepn, xinfo->patient);
    VSetAttr(VImageAttrList(res_image), "voxel", NULL, VStringRepn, xinfo->voxel);
    VSetAttr(VImageAttrList(res_image), "repetition_time", NULL, VLongRepn, itr);
    VSetAttr(VImageAttrList(res_image), "talairach", NULL, VStringRepn, xinfo->talairach);

    /* neu */
    VSetAttr(VImageAttrList(res_image),"indexOrigin",NULL,VStringRepn,xinfo->indexOrigin);
    VSetAttr(VImageAttrList(res_image),"columnVec",NULL,VStringRepn,xinfo->columnVec);
    VSetAttr(VImageAttrList(res_image),"rowVec",NULL,VStringRepn,xinfo->rowVec);
    VSetAttr(VImageAttrList(res_image),"sliceVec",NULL,VStringRepn,xinfo->sliceVec);
    VSetAttr(VImageAttrList(res_image),"FOV",NULL,VStringRepn,xinfo->FOV);
    /*--------*/

    if(xinfo->fixpoint[0] != 'N')
        VSetAttr(VImageAttrList(res_image), "fixpoint", NULL, VStringRepn, xinfo->fixpoint);
    if(xinfo->ca[0] != 'N') {
        VSetAttr(VImageAttrList(res_image), "ca", NULL, VStringRepn, xinfo->ca);
        VSetAttr(VImageAttrList(res_image), "cp", NULL, VStringRepn, xinfo->cp);
        VSetAttr(VImageAttrList(res_image), "extent", NULL, VStringRepn, xinfo->extent);
    }
    VAppendAttr(out_list, "image", NULL, VImageRepn, res_image);
    for(i = 0; i < n; i++) {
        beta_image[i] = VCreateImage(nslices, nrows, ncols, VFloatRepn);
        VFillImage(beta_image[i], VAllBands, 0);
        VSetAttr(VImageAttrList(beta_image[i]), "patient", NULL, VStringRepn, xinfo->patient);
        VSetAttr(VImageAttrList(beta_image[i]), "voxel", NULL, VStringRepn, xinfo->voxel);
        VSetAttr(VImageAttrList(beta_image[i]), "repetition_time", NULL, VLongRepn, itr);
        VSetAttr(VImageAttrList(beta_image[i]), "talairach", NULL, VStringRepn, xinfo->talairach);

	/* neu */
	VSetAttr(VImageAttrList(beta_image[i]),"indexOrigin",NULL,VStringRepn,xinfo->indexOrigin);
	VSetAttr(VImageAttrList(beta_image[i]),"columnVec",NULL,VStringRepn,xinfo->columnVec);
	VSetAttr(VImageAttrList(beta_image[i]),"rowVec",NULL,VStringRepn,xinfo->rowVec);
	VSetAttr(VImageAttrList(beta_image[i]),"sliceVec",NULL,VStringRepn,xinfo->sliceVec);
	VSetAttr(VImageAttrList(beta_image[i]),"FOV",NULL,VStringRepn,xinfo->FOV);
	/*--------*/


        if(xinfo->fixpoint[0] != 'N')
            VSetAttr(VImageAttrList(beta_image[i]), "fixpoint", NULL, VStringRepn, xinfo->fixpoint);
        if(xinfo->ca[0] != 'N') {
            VSetAttr(VImageAttrList(beta_image[i]), "ca", NULL, VStringRepn, xinfo->ca);
            VSetAttr(VImageAttrList(beta_image[i]), "cp", NULL, VStringRepn, xinfo->cp);
            VSetAttr(VImageAttrList(beta_image[i]), "extent", NULL, VStringRepn, xinfo->extent);
        }
        VSetAttr(VImageAttrList(beta_image[i]), "name", NULL, VStringRepn, "BETA");
        VSetAttr(VImageAttrList(beta_image[i]), "modality", NULL, VStringRepn, "BETA");
        VSetAttr(VImageAttrList(beta_image[i]), "beta", NULL, VShortRepn, i + 1);
        VSetAttr(VImageAttrList(beta_image[i]), "df", NULL, VFloatRepn, df);
        VAppendAttr(out_list, "image", NULL, VImageRepn, beta_image[i]);
    }
    VSetAttr(VImageAttrList(design), "name", NULL, VStringRepn, "X");
    VSetAttr(VImageAttrList(design), "modality", NULL, VStringRepn, "X");
    VAppendAttr(out_list, "image", NULL, VImageRepn, design);
    KX_image = Mat2Vista(SX);
    VSetAttr(VImageAttrList(KX_image), "name", NULL, VStringRepn, "KX");
    VSetAttr(VImageAttrList(KX_image), "modality", NULL, VStringRepn, "KX");
    VAppendAttr(out_list, "image", NULL, VImageRepn, KX_image);
    VSetAttr(VImageAttrList(BCOV), "name", NULL, VStringRepn, "BCOV");
    VSetAttr(VImageAttrList(BCOV), "modality", NULL, VStringRepn, "BCOV");
    VAppendAttr(out_list, "image", NULL, VImageRepn, BCOV);
    /*
    ** create temporary images for smoothness estimation
    */
    /* smoothness estim only for 3D images, i.e. CA/CP known */
/*    if(xinfo->ca[0] == 'N')
        smooth = FALSE;*/
    if(smooth) {
        i0 = 20;
        i1 = i0 + 30;
        if(i1 > m)
            i1 = m;
        for(i = i0; i < i1; i++) {
            if(i - i0 >= ETMP)
                VError(" too many tmp images");
            res_map[i - i0] = VCreateImage(nslices, nrows, ncols, VFloatRepn);
            VFillImage(res_map[i - i0], VAllBands, 0);
        }
    }
    /*
    ** process
    */
    ys   = gsl_vector_float_alloc(m);
    y    = gsl_vector_float_alloc(m);
    z    = gsl_vector_float_alloc(m);
    beta = gsl_vector_float_alloc(n);
    kernel = GaussKernel((double)sigma);
    for(k = 0; k < nlists; k++) {
        src[k] = VCreateImage(linfo[k].ntimesteps, nrows, ncols, linfo[k].repn);
        VFillImage(src[k], VAllBands, 0);
    }
    npix = 0;
    for(slice = 0; slice < nslices; slice++) {
        if(slice % 5 == 0)
            fprintf(stderr, " slice: %3d\r", slice);
        for(k = 0; k < nlists; k++) {
            if(linfo[k].zero[slice] == 0)
                goto next1;
            fd = open(linfo[k].filename, O_RDONLY);
            if(fd == -1)
                VError("could not open file %s", linfo[k].filename);
            nt = linfo[k].ntimesteps;
            if(! VReadBandDataFD(fd, &linfo[k].info[slice], 0, nt, &src[k]))
                VError(" error reading data");
            close(fd);
        }
        repn = linfo[0].repn;
        for(row = 0; row < nrows; row++) {
            for(col = 0; col < ncols; col++) {
                for(k = 0; k < nlists; k++)
                    if(VPixel(src[k], 0, row, col, VShort) < minval + 1)
                        goto next;
                npix++;
                /* read time series data */
                sum = sum2 = nx = 0;
                ptr1 = y->data;
                for(k = 0; k < nlists; k++) {
                    nt  = VImageNBands(src[k]);
                    for(i = 0; i < nt; i++) {
                        u = VPixel(src[k], i, row, col, VShort);
                        (*ptr1++) = u;
                        sum  += u;
                        sum2 += u * u;
                        nx++;
                    }
                }
                mean = sum / nx;
                sig = sqrt((double)((sum2 - nx * mean * mean) / (nx - 1.0)));
                if(sig < 0.001)
                    continue;
                /* centering and scaling, Seber, p.330 */
                ptr1 = y->data;
                for(i = 0; i < m; i++) {
                    u = ((*ptr1) - mean) / sig;
                    (*ptr1++) = u + 100.0;
                }
                /* S x y */
                ys = VectorConvolve(y, ys, kernel);
                /* compute beta's */
                fmat_x_vector(XInv, ys, beta);
                /* residuals */
                fmat_x_vector(SX, beta, z);
                err = 0;
                ptr1 = ys->data;
                ptr2 = z->data;
                for(i = 0; i < m; i++) {
                    d = ((*ptr1++) - (*ptr2++));
                    err += d * d;
                }
                /* sigma^2 */
                var = err / trace;
                /* write residuals output */
                VPixel(res_image, slice, row, col, VFloat) = (VFloat)var;
                /* save residuals of several timesteps for smoothness estimation */
                if(smooth) {
                    ptr1 = ys->data;
                    ptr2 = z->data;
                    err = 0;
                    for(i = i0; i < i1; i++) {
                        d = ((*ptr1++) - (*ptr2++));
                        err += d * d;
                        VPixel(res_map[i - i0], slice, row, col, VFloat) = d;
                    }
                    if (err > 0) err = sqrt(err); 
                    for(i = i0; i < i1; i++) {
                        d = VPixel(res_map[i - i0], slice, row, col, VFloat);
						if (err > 1.0e-6) d /= err;
						else d = 0; 
                        VPixel(res_map[i - i0], slice, row, col, VFloat) = d / err;
                    }
                }
                /* write beta output */
                ptr1 = beta->data;
                for(i = 0; i < n; i++)
                    VPixel(beta_image[i], slice, row, col, VFloat) = (VFloat)(*ptr1++);
next:
                ;
            }
        }
next1:
        ;
    }
    /*
    ** Smoothness estimation based on residual images
    */
    if(smooth) {
        smooth_fwhm = VSmoothnessEstim(res_map, i1 - i0);
        sscanf(xinfo->voxel, "%f %f %f", &vx, &vy, &vz);
        vx = (vx + vy + vz) / 3.0;    /* voxels should be isotropic */
        smooth_fwhm *= vx;
        fprintf(stderr, " smoothness: %f\n", smooth_fwhm);
        VSetAttr(VImageAttrList(res_image), "smoothness", NULL, VFloatRepn, smooth_fwhm);
        for(i = 0; i < n; i++) {
            VSetAttr(VImageAttrList(beta_image[i]), "smoothness", NULL, VFloatRepn, smooth_fwhm);
        }
        for(i = 0; i < i1 - i0; i++)
            VDestroyImage(res_map[i]);
    }
ende:
    if(npix == 0)
        VError(" no voxels above threshold %d found", minval);
    return out_list;
}
コード例 #15
0
ファイル: FIL_Vista_Image.c プロジェクト: KoraST/ft_BIU-1
VImage VCreateImage (int nbands, int nrows, int ncolumns, VRepnKind pixel_repn)
{
  size_t row_size = ncolumns * VRepnSize (pixel_repn);
  size_t data_size = nbands * nrows * row_size;
  size_t row_index_size = nbands * nrows * sizeof (char *);
  size_t band_index_size = nbands * sizeof (char **);
  size_t pixel_size;
  char *p;
  VImage image;
  int band, row;

#define AlignUp(v, b) ((((v) + (b) - 1) / (b)) * (b))

  /* Check parameters: */
  if (nbands < 1) {
    VWarning ("VCreateImage: Invalid number of bands: %d", (int) nbands);
    return NULL;
  }
  if (nrows < 1) {
    VWarning ("VCreateImage: Invalid number of rows: %d", (int) nrows);
    return NULL;
  }
  if (ncolumns < 1) {
    VWarning ("VCreateImage: Invalid number of columns: %d",
	      (int) ncolumns);
    return NULL;
  }
  if (pixel_repn != VBitRepn && pixel_repn != VUByteRepn &&
      pixel_repn != VSByteRepn && pixel_repn != VShortRepn &&
      pixel_repn != VLongRepn && pixel_repn != VFloatRepn &&
      pixel_repn != VDoubleRepn) {
    VWarning ("VCreateImage: Invalid pixel representation: %d",
	      (int) pixel_repn);
    return NULL;
  }

  /* Allocate memory for the VImage, its indices, and pixel values, while
     padding enough to ensure pixel values are appropriately aligned: */
  pixel_size = VRepnSize (pixel_repn);
  p = VMalloc (AlignUp (sizeof (VImageRec) + row_index_size +
			band_index_size, pixel_size) + data_size);

  /* Initialize the VImage: */
  image = (VImage) p;
  image->nbands = nbands;
  image->nrows = nrows;
  image->ncolumns = ncolumns;
  image->flags = VImageSingleAlloc;
  image->pixel_repn = pixel_repn;
  image->attributes = VCreateAttrList ();
  image->band_index = (VPointer **) (p += sizeof (VImageRec));
  image->row_index = (VPointer *) (p += band_index_size);
  image->data = (VPointer) AlignUp ((long) p + row_index_size, pixel_size);
  image->nframes = nbands;
  image->nviewpoints = image->ncolors = image->ncomponents = 1;

  /* Initialize the indices: */
  for (band = 0; band < nbands; band++)
    image->band_index[band] = image->row_index + band * nrows;
  for (row = 0, p = image->data; row < nbands * nrows; row++, p += row_size)
    image->row_index[row] = p;

  return image;

#undef AlignUp
}
コード例 #16
0
ファイル: FIL_Vista_File.c プロジェクト: KoraST/ft_BIU-1
static VAttrList ReadAttrList (FILE *f)
{
    VAttrList sublist, list = VCreateAttrList ();
    VAttrRec *a;
    int ch = 0;
    size_t name_size;
    VBundle b;
    char buf[2], *str, name_buf[VMaxAttrNameLength + 1];

    /* Swallow a { marking the start of the attribute list: */
    if (fscanf (f, " %1s", buf) != 1 || buf[0] != '{') {
	VWarning ("VReadFile: Missing {");
	goto Fail;
    }

    /* For each attribute up to the next "}": */
    while (fscanf (f, " %[^}: \t\n]", name_buf) == 1) {
	name_size = strlen (name_buf);

	/* Read a : and the first character of the attribute's value: */
	if (fscanf (f, " %1s", buf) != 1 || buf[0] != ':' ||
	    fscanf (f, " %1s", buf) != 1) {
	    VWarning ("VReadFile: Invalid %s attribute", name_buf);
	    goto Fail;
	}

	/* The first character of the value tells us whether its an attribute
	   list, quoted string, or unquoted string: */
	if (buf[0] == '{') {

	    /* The attribute value is another list of attributes: */
	    ungetc ('{', f);
	    if (! (sublist = ReadAttrList (f)))
		goto Fail;
	    a = VMalloc (sizeof (VAttrRec) + name_size);
	    a->value = sublist;
	    a->repn = VAttrListRepn;

	} else {

	    /* The value doesn't start with '{' -- parse a word or string: */
	    if (! (str = ReadString (f, buf[0], name_buf)))
		goto Fail;
	    while ((ch = fgetc (f)) && (ch == ' ' || ch == '\t')) ;
	    ungetc (ch, f);

	    /* If the word is followed by an '{'... */
	    if (ch == '{') {

		/* ...then it's a typed value -- the word is it's type name
		   and the { is the start of it's attribute list value. */
		b = VCreateBundle (str, NULL, 0, NULL);
		if (! (sublist = ReadAttrList (f))) {
		    VFree (b);
		    goto Fail;
		}
		b->list = sublist;
		a = VMalloc (sizeof (VAttrRec) + name_size);
		a->repn = VBundleRepn;
		a->value = b;

	    } else {

		/* ...otherwise store it as a simple string value: */
		a = VMalloc (sizeof (VAttrRec) + name_size + strlen (str) + 1);
		a->repn = VStringRepn;
		a->value = a->name + name_size + 1;
		strcpy (a->value, str);
	    }
	    VFree(str);
	}

	/* Copy the attribute's name into the newly allocated node: */
	strcpy (a->name, name_buf);

	/* Place the new node on the end of the growing attribute list: */
	a->next = NULL;
	a->prev = list->prev;
	if (a->prev) a->prev->next = a;
	else list->next = a;
	list->prev = a;
    }

    /* Swallow the terminating "}": */
    if (fscanf (f, " %1s", buf) != 1 || buf[0] != '}') {
	VWarning ("VReadFile: Missing }");
Fail:	VDestroyAttrList (list);
	return NULL;
    }
    return list;
}
コード例 #17
0
ファイル: vbayes.c プロジェクト: Rollmops/lipsia
VAttrList
VBayes(VImage cbeta_images[], VImage sd_images[], int nimages, VBoolean level, VBoolean zscore) {
    VAttrList out_list = NULL;
    VImage dest = NULL, sigma_image = NULL;
    int    i, j, k, npixels;
    VFloat *dest_pp, *beta_pp[N], *sd_pp[N], *sigma_pp = NULL;
    VFloat pmin, pmax;
    double mean = 0, sigma = 0;
    float  rx, wsum, msum, w0, wx, s, msumold;
    float  result = 0;
    float  gmean[N], gvar[N];
    float  tiny = 1.0e-12;
    /*
    ** create output image
    */
    dest = VCopyImage(cbeta_images[0], NULL, VAllBands);
    if(!dest)
        return NULL;
    VFillImage(dest, VAllBands, 0);
    VSetAttr(VImageAttrList(dest), "num_images", NULL, VShortRepn, (VShort)nimages);
    VSetAttr(VImageAttrList(dest), "modality", NULL, VStringRepn, "bayes_map");
    VSetAttr(VImageAttrList(dest), "name", NULL, VStringRepn, "bayes");
    if(level == TRUE) {
        VSetAttr(VImageAttrList(dest), "modality", NULL, VStringRepn, "mean");
        VSetAttr(VImageAttrList(dest), "name", NULL, VStringRepn, "mean");
        sigma_image = VCopyImage(dest, NULL, VAllBands);
        if(!sigma_image)
            return NULL;
        VFillImage(sigma_image, VAllBands, 0);
        VSetAttr(VImageAttrList(sigma_image), "num_images", NULL, VShortRepn, (VShort)nimages);
        VSetAttr(VImageAttrList(sigma_image), "modality", NULL, VStringRepn, "std_dev");
        VSetAttr(VImageAttrList(sigma_image), "name", NULL, VStringRepn, "std_dev");
    }
    /*
    ** for each voxel
    */
    pmax = VRepnMinValue(VFloatRepn);
    pmin = VRepnMaxValue(VFloatRepn);
    npixels = VImageNPixels(cbeta_images[0]);
    for(i = 0; i < nimages; i++) {
        beta_pp[i] = (VFloat *) VImageData(cbeta_images[i]);
        sd_pp[i]   = (VFloat *) VImageData(sd_images[i]);
    }
    dest_pp = (VFloat *) VImageData(dest);
    if(level == TRUE)
        sigma_pp = (VFloat *) VImageData(sigma_image);
    for(j = 0; j < npixels; j++) {
        if(j % 10000 == 0)
            fprintf(stderr, "...%.2f%%\r", (float)100 * j / (float)npixels);
        result = mean = sigma = 0;
        /*
        ** read data from input images
        */
        for(k = 0; k < nimages; k++) {
            gmean[k] = *beta_pp[k]++;  /* mean c*beta */
            rx       = *sd_pp[k]++;    /* standard deviation of c*beta*/
            gvar[k]  = rx * rx;        /* variation of c*beta*/
        }
        /* see Box,Tiao, pp.17-18     calculate probability distribution */
        wsum = 0;
        msum = 0;
        w0 = 0;
        for(k = 0; k < nimages; k++) {    /* for each image */
            s = gvar[k];
            if(s < tiny)
                goto next;
            s = sqrt((double)s);
            if(s < tiny)
                goto next;
            wx = 1.0 / (s * s);
            wsum = w0 + wx;
            msumold = msum;
            msum = (w0 * msum  +  wx * gmean[k]) / wsum;
            w0 = wsum;
            sigma = 1.0 / sqrt(wsum);
        }
        if(wsum < tiny)
            goto next;
        /* resulting mean and std dev */
        mean = msum;
        sigma = 1.0 / sqrt(wsum);
        if(level == TRUE) {
            result = mean;
            goto next;
        }
        /* calculate probability under distribution */
        result = CumulativeNormal(mean, sigma);
        /* output */
        if(zscore) {
            /* CHECK HERE IF "1.0-" is correct */
            result = (float)p2z((double)(1.0 - result));
            if(mean < 0)
                result = -result;
            if(result >  20)
                result =  20;
            if(result < -20)
                result = -20;
        } else {
            result *= 100.0;
            if(result >  100)
                result =  100;
            if(mean < 0)
                result = -result;
        }
        if(result < pmin)
            pmin = result;
        if(result > pmax)
            pmax = result;
next:
        *dest_pp++ = result;
        if(level)
            *sigma_pp++ = sigma;
    }
    out_list = VCreateAttrList();
    fprintf(stderr, "...100.00%%\n");
    if(level == FALSE) {
        fprintf(stderr, "\n min: %.3f, max: %.3f\n", pmin, pmax);
        VAppendAttr(out_list, "zmap", NULL, VImageRepn, dest);
        return out_list;
    } else {
        VAppendAttr(out_list, "mean", NULL, VImageRepn, dest);
        VAppendAttr(out_list, "std_dev", NULL, VImageRepn, sigma_image);
        return out_list;
    }
    return NULL;
}
コード例 #18
0
ファイル: vpaired_ccm.c プロジェクト: hahtse/Lipsia
int
main (int argc,char *argv[])
{
  static VString  filename = "";
  static VString  filename1 = "";
  static VString  filename2 = "";
  static VShort   first  = 2;
  static VShort   length = 0;
  static VShort   type = 0;
  static VShort   minval = 0;
  static VShort   nproc = 4;
  static VOptionDescRec  options[] = {
    {"in1",VStringRepn,1,(VPointer) &filename1,VRequiredOpt,NULL,"first input file"},
    {"in2",VStringRepn,1,(VPointer) &filename2,VRequiredOpt,NULL,"second input file"},
    {"mask",VStringRepn,1,(VPointer) &filename,VRequiredOpt,NULL,"mask"},
    {"type",VShortRepn,1,(VPointer) &type,VOptionalOpt,TYPDict,"type of concordance measure"},
    {"minval",VShortRepn,1,(VPointer) &minval,VOptionalOpt,NULL,"signal threshold"},
    {"first",VShortRepn,1,(VPointer) &first,VOptionalOpt,NULL,"first timestep to use"},
    {"length",VShortRepn,1,(VPointer) &length,VOptionalOpt,NULL,
     "length of time series to use, '0' to use full length"},
    {"j",VShortRepn,1,(VPointer) &nproc,VOptionalOpt,NULL,"number of processors to use, '0' to use all"}
  };
  FILE *out_file,*fp;
  VAttrList list=NULL,list1=NULL,list2=NULL,out_list=NULL;
  VAttrListPosn posn;
  VImage mask=NULL,map=NULL,dest=NULL,disc=NULL;
  float *A1=NULL,*A2=NULL,u=0,tiny=1.0e-6;
  int b,r,c;
  char *prg = "vccm2";

  VParseFilterCmd (VNumber (options),options,argc,argv,NULL,&out_file);
  if (type > 3) VError("illegal type");


  /*
  ** read mask
  */
  fp = VOpenInputFile (filename, TRUE);
  list = VReadFile (fp, NULL);
  if (! list) VError("Error reading mask file");
  fclose(fp);

  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
    if (VGetAttrRepn (& posn) != VImageRepn) continue;
    VGetAttrValue (& posn, NULL,VImageRepn, & mask);
    if (VPixelRepn(mask) == VFloatRepn || VPixelRepn(mask) == VDoubleRepn) {
      mask = NULL;
      continue;
    }
  }
  if (mask == NULL) VError(" no mask found");


  /* read files */
  fp = VOpenInputFile (filename1, TRUE);
  list1 = VReadFile (fp, NULL);
  if (! list1) VError("Error reading 1st input file");
  fclose(fp);

  fp = VOpenInputFile (filename2, TRUE);
  list2 = VReadFile (fp, NULL);
  if (! list2) VError("Error reading 2nd input file");
  fclose(fp);


  /* get voxel map */
  map = GetMap(list1,list2,mask,minval);


 /* omp-stuff */
#ifdef _OPENMP
  int num_procs=omp_get_num_procs();
  if (nproc > 0 && nproc < num_procs) num_procs = nproc;
  printf("using %d cores\n",(int)num_procs);
  omp_set_num_threads(num_procs);
#endif /* _OPENMP */


  /* compute corr matrices */
  A1 = VCorrMatrix(list1,map,first,length);
  A2 = VCorrMatrix(list2,map,first,length);


  /* get concordance between two corr matrices */
  dest = VCCM2(A1,A2,map,(int)type);


  /* invert to get discordant map */
  disc = VCreateImageLike(dest);
  VFillImage(disc,VAllBands,0);

  if (type < 2) {
    for (b=0; b<VImageNBands(dest); b++) {
      for (r=0; r<VImageNRows(dest); r++) {
	for (c=0; c<VImageNColumns(dest); c++) {
	  if (VGetPixel(mask,b,r,c) < 1) continue;
	  u = VPixel(dest,b,r,c,VFloat);
	  if (u < tiny) continue;
	  VPixel(disc,b,r,c,VFloat) = 1-u;
	} 
      }
    }
  }


  /* output */
  out_list = VCreateAttrList();
  VHistory(VNumber(options),options,prg,&list,&out_list);
  VAppendAttr(out_list,"concordant",NULL,VImageRepn,dest);
  if (type < 2) VAppendAttr(out_list,"discordant",NULL,VImageRepn,disc);
  if (! VWriteFile (out_file, out_list)) exit (1);
  fprintf (stderr, "%s: done.\n", argv[0]);
  return 0;
}
コード例 #19
0
ファイル: vncm.c プロジェクト: Rollmops/lipsia
VAttrList
VNCM(VAttrList list,VImage mask,VShort minval,VShort first,VShort length,VFloat threshold)
{
  VAttrList out_list=NULL;
  VAttrListPosn posn;
  VImage src[NSLICES],map=NULL;
  VImage dest=NULL;
  size_t b,r,c,i,j,i1,n,m,nt,last,ntimesteps,nrows,ncols,nslices;
  gsl_matrix_float *mat=NULL;
  float *A=NULL,*ev=NULL;


  /*
  ** get image dimensions
  */
  i = ntimesteps = nrows = ncols = 0;
  for (VFirstAttr (list, & posn); VAttrExists (& posn); VNextAttr (& posn)) {
    if (VGetAttrRepn (& posn) != VImageRepn) continue;
    VGetAttrValue (& posn, NULL,VImageRepn, & src[i]);
    if (VPixelRepn(src[i]) != VShortRepn) continue;

    if (VImageNBands(src[i]) > ntimesteps) ntimesteps = VImageNBands(src[i]);
    if (VImageNRows(src[i])  > nrows)  nrows = VImageNRows(src[i]);
    if (VImageNColumns(src[i]) > ncols) ncols = VImageNColumns(src[i]);
    i++;
    if (i >= NSLICES) VError(" too many slices");
  }
  nslices = i;


  /* get time steps to include */
  if (length < 1) length = ntimesteps-2;
  last = first + length -1;
  if (last >= ntimesteps) last = ntimesteps-1;
  if (first < 0) first = 1;

  nt = last - first + 1;
  i1 = first+1;
  if (nt < 2) VError(" not enough timesteps, nt= %d",nt);
  fprintf(stderr,"# ntimesteps: %d, first= %d, last= %d, nt= %d\n",
	  (int)ntimesteps,(int)first,(int)last,(int)nt);


  /* count number of voxels */
  n = 0;
  for (b=0; b<nslices; b++) {
    if (VImageNRows(src[b]) < 2) continue;
    for (r=0; r<nrows; r++) {
      for (c=0; c<ncols; c++) {
	if (VPixel(src[b],i1,r,c,VShort) < minval) continue;
	if (VGetPixel(mask,b,r,c) < 0.5) continue;
	n++;
      }
    }
  }
  fprintf(stderr," nvoxels: %ld\n",(long)n);



  /*
  ** voxel addresses
  */
  map = VCreateImage(1,5,n,VFloatRepn);
  if (map == NULL) VError(" error allocating addr map");
  VFillImage(map,VAllBands,0);
  VPixel(map,0,3,0,VFloat) = nslices;
  VPixel(map,0,3,1,VFloat) = nrows;
  VPixel(map,0,3,2,VFloat) = ncols;

  i = 0;
  for (b=0; b<nslices; b++) {
    if (VImageNRows(src[b]) < 2) continue;
    for (r=0; r<nrows; r++) {
      for (c=0; c<ncols; c++) {
	if (VPixel(src[b],i1,r,c,VShort) < minval) continue;
	if (VGetPixel(mask,b,r,c) < 0.5) continue;

	VPixel(map,0,0,i,VFloat) = b;
	VPixel(map,0,1,i,VFloat) = r;
	VPixel(map,0,2,i,VFloat) = c;
	i++;
      }
    }
  }


  /*
  ** avoid casting to float, copy data to matrix
  */
  mat = gsl_matrix_float_calloc(n,nt);
  for (i=0; i<n; i++) {

    b = VPixel(map,0,0,i,VFloat);
    r = VPixel(map,0,1,i,VFloat);
    c = VPixel(map,0,2,i,VFloat);

    float *ptr = gsl_matrix_float_ptr(mat,i,0);
    int k;
    j = 0;
    for (k=first; k<=last; k++) {
      if (j >= mat->size2) VError(" j= %d %d",j,mat->size2);
      if (k >= VImageNBands(src[b])) VError(" k= %d %d",k, VImageNBands(src[b]));
      *ptr++ = (float) VPixel(src[b],k,r,c,VShort);
      j++;
    }
  }


  /*
  ** compute similarity matrix
  */
  m = (n*(n+1))/2;
  fprintf(stderr," matrix computation, n= %ld...\n",(long)n);
  A = (float *) calloc(m,sizeof(float));
  if (!A) VError(" err allocating correlation matrix");
  memset(A,0,m*sizeof(float));
  size_t progress=0;

#pragma omp parallel for shared(progress) private(j) schedule(guided) firstprivate(mat,A)
  for (i=0; i<n; i++) {
    if (i%100 == 0) fprintf(stderr," %d00\r",(int)(++progress));

    const float *arr1 = gsl_matrix_float_const_ptr(mat,i,0);
    for (j=0; j<i; j++) {

      const float *arr2 = gsl_matrix_float_const_ptr(mat,j,0);
      const double v = Correlation(arr1,arr2,nt);
      const size_t k=j+i*(i+1)/2;
      if (k >= m) VError(" illegal addr k= %d, m= %d",k,m);
      A[k] = (float)v;
    }
  }
  fprintf(stderr," matrix done.\n");
  gsl_matrix_float_free(mat);
 

  /*
  ** eigenvector centrality
  */
  ev = (float *) VCalloc(n,sizeof(float));
  DegreeCentrality(A,ev,n,threshold);
  dest = WriteOutput(src[0],map,nslices,nrows,ncols,ev,n);
  VSetAttr(VImageAttrList(dest),"name",NULL,VStringRepn,"DegreeCM");

  out_list = VCreateAttrList();
  VAppendAttr(out_list,"image",NULL,VImageRepn,dest);
  return out_list;
}
コード例 #20
0
ファイル: vgetcontrast.c プロジェクト: Rollmops/lipsia
VAttrList
VGetContrast(VAttrList list, gsl_vector_float *con, VShort type) {
    VAttrList out_list;
    int nbands = 0, nrows = 0, ncols = 0, band, row, col;
    VImage src = NULL, dest = NULL, std_image = NULL;
    VImage beta_images[MBETA], res_image = NULL, bcov_image = NULL;
    VString buf = NULL;
    VAttrListPosn posn;
    VString str;
    int    i, nbeta;
    float  t = 0, s = 0, tsigma = 0, z = 0, zmax = 0, zmin = 0;
    float  sigma, var, sum, df;
    float  *ptr1, *ptr2;
    char *constring = NULL;
    gsl_vector_float *beta = NULL, *tmp = NULL;
    gsl_matrix_float *bcov = NULL;
    i = 0;
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & src);
        if(VPixelRepn(src) != VFloatRepn)
            continue;
        VGetAttr(VImageAttrList(src), "modality", NULL, VStringRepn, &str);
        if(strcmp(str, "BETA") == 0) {
            beta_images[i++] = VCopyImage(src, NULL, VAllBands);
        } else if(strcmp(str, "RES/trRV") == 0) {
            res_image = VCopyImage(src, NULL, VAllBands);
        } else if(strcmp(str, "BCOV") == 0) {
            bcov_image = VCopyImage(src, NULL, VAllBands);
        }
    }
    nbeta  = VImageNRows(bcov_image);
    nbands = VImageNBands(beta_images[0]);
    nrows  = VImageNRows(beta_images[0]);
    ncols  = VImageNColumns(beta_images[0]);
    if(VGetAttr(VImageAttrList(beta_images[0]), "df", NULL, VFloatRepn, &df) != VAttrFound)
        VError(" attribute 'df' not found");
    if(nbeta > MBETA) {
        fprintf(stderr, " number of betas: %d,  maximum number of betas: %d\n", nbeta, MBETA);
        VError(" maximum number of betas is exceeded");
    }
    /*
    ** read contrast vector
    */
    if(nbeta != con->size)
        VError("contrast vector has bad length (%d), correct length is %d", con->size, nbeta);
    fprintf(stderr, " contrast vector:\n");
    char str1[10];
    constring = (char *)VMalloc(sizeof(char) * 10 * nbeta);
    constring[0] = '\0';
    for(i = 0; i < nbeta; i++) {
        fprintf(stderr, "  %.2f", fvget(con, i));
        sprintf(str1, "%1.2f ", fvget(con, i));
        strcat((char *)constring, (const char *)str1);
    }
    fprintf(stderr, "\n");
    /* get variance estimation */
    bcov = gsl_matrix_float_alloc(nbeta, nbeta);
    ptr1 = VImageData(bcov_image);
    ptr2 = bcov->data;
    for(i = 0; i < nbeta * nbeta; i++)
        *ptr2++ = *ptr1++;
    gsl_matrix_float_transpose(bcov);
    tmp   = fmat_x_vector(bcov, con, tmp);
    var   = fskalarproduct(tmp, con);
    sigma = sqrt(var);
    /*
    ** create output data structs
    */
    out_list = VCreateAttrList();
    dest = VCreateImage(nbands, nrows, ncols, VFloatRepn);
    VFillImage(dest, VAllBands, 0);
    VCopyImageAttrs(beta_images[0], dest);
    switch(type) {
    case 0:    /* conimg  */
        buf = VNewString("conimg");
        break;
    case 1:    /* t-image */
        buf = VNewString("tmap");
        break;
    case 2:    /* zmap    */
        buf = VNewString("zmap");
        break;
    default:
        VError(" illegal type");
    }
    fprintf(stderr, " output type: %s\n", buf);
    VSetAttr(VImageAttrList(dest), "modality", NULL, VStringRepn, buf);
    VSetAttr(VImageAttrList(dest), "name", NULL, VStringRepn, buf);
    VSetAttr(VImageAttrList(dest), "contrast", NULL, VStringRepn, constring);
    VAppendAttr(out_list, "image", NULL, VImageRepn, dest);
    if(type == 0) {
        std_image = VCreateImage(nbands, nrows, ncols, VFloatRepn);
        VFillImage(std_image, VAllBands, 0);
        VCopyImageAttrs(beta_images[0], std_image);
        VSetAttr(VImageAttrList(std_image), "modality", NULL, VStringRepn, "std_dev");
        VSetAttr(VImageAttrList(std_image), "name", NULL, VStringRepn, "std_dev");
        VAppendAttr(out_list, "image", NULL, VImageRepn, std_image);
    }
    /*
    ** loop thru image
    */
    zmax = zmin = 0;
    beta = gsl_vector_float_alloc(nbeta);
    for(band = 0; band < nbands; band++) {
        for(row = 0; row < nrows; row++) {
            for(col = 0; col < ncols; col++) {
                t = z = sum = 0;
                ptr1 = beta->data;
                for(i = 0; i < nbeta; i++) {
                    *ptr1++ = VPixel(beta_images[i], band, row, col, VFloat);
                }
                sum  = fskalarproduct(beta, con);
                if(ABS(sum) < 1.0e-10)
                    continue;
                s = VPixel(res_image, band, row, col, VFloat);
                tsigma = sqrt(s) * sigma;
                if(tsigma > 0.00001)
                    t = sum / tsigma;
                else
                    t = 0;
                if(isnan(t) || isinf(t))
                    t = 0;
                switch(type) {
                case 0:    /* conimg  */
                    z = sum;
                    break;
                case 1:    /* t-image */
                    z = t;
                    break;
                case 2:    /* zmap    */
                    z = t2z_approx(t, df);
                    if(z > 30)
                        z = 30;
                    if(sum < 0)
                        z = -z;
                    break;
                default:
                    ;
                }
                if(isnan(z) || isinf(z))
                    z = 0;
                if(z > zmax)
                    zmax = z;
                if(z < zmin)
                    zmin = z;
                VPixel(dest, band, row, col, VFloat) = z;
                if(type == 0)
                    VPixel(std_image, band, row, col, VFloat) = tsigma;
            }
        }
    }
    fprintf(stderr, " min= %.3f,  max= %.3f\n", zmin, zmax);
    return out_list;
}
コード例 #21
0
ファイル: vdelcereb.c プロジェクト: tibu-mpg/Lipsia
int main(int argc, char *argv[]) {
    VAttrList list, out_list;
    VImage src;
    VImage dest = NULL;
    VAttrListPosn posn;
    VString str;
    int nimages;
    char historystr[] = "history";
    char prg_name[100];
    char ver[100];
    getLipsiaVersion(ver, sizeof(ver));
    sprintf(prg_name, "vdelcereb V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /* Parse command line arguments: */
    if(!VParseCommand(VNumber(options), options, &argc, argv) ||
            ! VIdentifyFiles(VNumber(options), options, "in", & argc, argv, 0) ||
            ! VIdentifyFiles(VNumber(options), options, "out", & argc, argv, -1))
        goto Usage;
    if(argc > 1) {
        VReportBadArgs(argc, argv);
Usage:
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    /* Read source image(s): */
    if(strcmp(in_filename, "-") == 0)
        in_file = stdin;
    else {
        in_file = fopen(in_filename, "r");
        if(! in_file)
            VError("Failed to open input file %s", in_filename);
    }
    if(!(list = VReadFile(in_file, NULL)))
        exit(EXIT_FAILURE);
    fclose(in_file);
    /* Process image */
    nimages = 0;
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & src);
        dest = VCerebellum(src);
        VSetAttrValue(& posn, NULL, VImageRepn, dest);
        VDestroyImage(src);
        nimages++;
        break;
    }
    /* Create outlist */
    out_list = VCreateAttrList();
    /* Make History */
    VHistory(VNumber(options), options, prg_name, &list, &out_list);
    /*  Alle Attribute (ausser history:) in die neue Liste schreiben: */
    for(VFirstAttr(list, &posn); VAttrExists(&posn); VNextAttr(&posn)) {
        if(strncmp(VGetAttrName(&posn), historystr, strlen(historystr)) == 0)
            continue;
        switch(VGetAttrRepn(&posn)) {
        case VImageRepn:
            VGetAttrValue(&posn, NULL, VImageRepn, &src);
            VAppendAttr(out_list, VGetAttrName(&posn), NULL, VImageRepn, src);
            break;
        case VStringRepn:
            VGetAttrValue(&posn, NULL, VStringRepn, &str);
            VAppendAttr(out_list, VGetAttrName(&posn), NULL, VImageRepn, str);
            break;
        default:
            break;
        }
    }
    /* Write the results to the output file: */
    if(strcmp(out_filename, "-") == 0)
        out_file = stdout;
    else {
        out_file = fopen(out_filename, "w");
        if(! out_file)
            VError("Failed to open output file %s", out_filename);
    }
    if(VWriteFile(out_file, out_list)) {
        if(verbose >= 1)
            fprintf(stderr, "%s: processed %d image%s.\n",
                    argv[0], nimages, nimages == 1 ? "" : "s");
        fprintf(stderr, "%s: done.\n", argv[0]);
    }
    return 0;
}
コード例 #22
0
ファイル: vcatdesign.c プロジェクト: Rollmops/lipsia
int
main(int argc, char *argv[]) {
    static VArgVector in_files;
    static VString out_filename;
    static VBoolean in_found, out_found;
    static VOptionDescRec  options[] = {
        {"in", VStringRepn, 0, & in_files, & in_found, NULL, "Input files" },
        {"out", VStringRepn, 1, & out_filename, & out_found, NULL, "Output file" }
    };
    FILE *fp = NULL;
    VStringConst in_filename;
    VAttrList list = NULL, out_list = NULL;
    VImage *design = NULL, tmp = NULL, dest = NULL;
    VAttrListPosn posn;
    int  i, nimages;
    char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vcatdesign V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /* Parse command line arguments: */
    if(! VParseCommand(VNumber(options), options, & argc, argv) ||
            ! VIdentifyFiles(VNumber(options), options, "in", & argc, argv, 0) ||
            ! VIdentifyFiles(VNumber(options), options, "out", & argc, argv, -1))
        goto Usage;
    if(argc > 1) {
        VReportBadArgs(argc, argv);
Usage:
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    /* Read each input file */
    nimages = in_files.number;
    design = (VImage *) VMalloc(sizeof(VImage) * nimages);
    for(i = 0; i < nimages; i++) {
        in_filename = ((VStringConst *) in_files.vector)[i];
        fprintf(stderr, " reading:  %s\n", in_filename);
        fp = VOpenInputFile(in_filename, TRUE);
        list = VReadFile(fp, NULL);
        if(! list)
            VError("Error reading file %s", in_filename);
        fclose(fp);
        for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & tmp);
            if(VPixelRepn(tmp) == VFloatRepn || VPixelRepn(tmp) == VDoubleRepn) {
                design[i] = tmp;
                break;
            }
        }
    }
    /* process */
    dest = ConcatDesigns(design, nimages);
    out_list = VCreateAttrList();
    VAppendAttr(out_list, "image", NULL, VImageRepn, dest);
    /* Output: */
    VHistory(VNumber(options), options, prg_name, &list, &out_list);
    fp = VOpenOutputFile(out_filename, TRUE);
    if(!fp)
        VError(" error opening outout file %s", out_filename);
    if(! VWriteFile(fp, out_list))
        exit(1);
    fprintf(stderr, "%s: done.\n", argv[0]);
    return 0;
}
コード例 #23
0
ファイル: Attr.c プロジェクト: Rollmops/via
VAttrList VCopyAttrList (VAttrList list)
{
    VAttrList new_list = VCreateAttrList ();
    size_t name_size, value_size;
    VAttrRec *old_a, *new_a;
    VBundle old_b, new_b;
    VTypeMethods *methods;

    /* For each node of the old list: */
    for (old_a = list->next; old_a; old_a = old_a->next) {

	/* Compute the amount of storage needed for a copy of the node: */
	name_size = strlen (old_a->name);
	value_size = (old_a->repn == VStringRepn) ?
	    strlen ((VStringConst) old_a->value) + 1 : 0;

	/* Allocate that size and fill in the node's value: */
	new_a = VMalloc (sizeof (VAttrRec) + name_size + value_size);
	strcpy (new_a->name, old_a->name);
	switch (new_a->repn = old_a->repn) {

	case VAttrListRepn:
	    new_a->value = VCopyAttrList (old_a->value);
	    break;

	case VBundleRepn:
	    old_b = old_a->value;
	    new_b = VCreateBundle (old_b->type_name,
				   VCopyAttrList (old_b->list),
				   old_b->length, NULL);
	    if (old_b->length > 0) {
		new_b->data = VMalloc (old_b->length);
		memcpy (new_b->data, old_b->data, old_b->length);
	    }
	    new_a->value = new_b;
	    break;

	case VPointerRepn:
	    new_a->value = old_a->value;
	    break;

	case VStringRepn:
	    new_a->value = (VPointer) (new_a->name + name_size + 1);
	    strcpy (new_a->value, old_a->value);
	    break;

	default:
	    if (methods = VRepnMethods (new_a->repn))
		new_a->value = (methods->copy) (old_a->value);
	    else VError ("VCopyAttrList: %s attribute has invalid repn %d",
			 old_a->name, old_a->repn);
	}

	/* Append it to the new list: */
	new_a->next = NULL;
	if (new_a->prev = new_list->prev)
	    new_a->prev->next = new_a;
	if (! new_list->next)
	    new_list->next = new_a;
	new_list->prev = new_a;
    }
    return new_list;
}
コード例 #24
0
ファイル: vpaired_wilcoxtest.c プロジェクト: Rollmops/lipsia
int main(int argc, char *argv[]) {
    static VArgVector in_files1;
    static VArgVector in_files2;
    static VString out_filename;
    static VOptionDescRec options[] = {
        { "in1", VStringRepn, 0, & in_files1, VRequiredOpt, NULL, "Input files 1" },
        { "in2", VStringRepn, 0, & in_files2, VRequiredOpt, NULL, "Input files 2" },
        { "out", VStringRepn, 1, & out_filename, VRequiredOpt, NULL, "Output file" }
    };
    FILE *fp = NULL;
    VStringConst in_filename, buf1, buf2;
    VAttrList list1, list2, out_list;
    VAttrListPosn posn;
    VImage src, *src1, *src2, dest = NULL;
    int i, nimages, npix = 0;
    char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vpaired_wilcoxtest V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /*
    ** parse command line
    */
    if(! VParseCommand(VNumber(options), options, & argc, argv)) {
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    if(argc > 1) {
        VReportBadArgs(argc, argv);
        exit(EXIT_FAILURE);
    }
    /* number of images */
    nimages = in_files1.number;
    if(in_files2.number != nimages)
        VError(" inconsistent number of files ");
    for(i = 0; i < nimages; i++) {
        buf1 = ((VStringConst *) in_files1.vector)[i];
        buf2 = ((VStringConst *) in_files2.vector)[i];
        fprintf(stderr, "%3d:  %s  %s\n", i, buf1, buf2);
    }
    fprintf(stderr, "\n");
    /*
    ** read images 1
    */
    src1 = (VImage *) VCalloc(nimages, sizeof(VImage));
    for(i = 0; i < nimages; i++) {
        src1[i] = NULL;
        in_filename = ((VStringConst *) in_files1.vector)[i];
        fp = VOpenInputFile(in_filename, TRUE);
        list1 = VReadFile(fp, NULL);
        if(! list1)
            VError("Error reading image");
        fclose(fp);
        for(VFirstAttr(list1, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VPixelRepn(src) != VFloatRepn)
                continue;
            src1[i] = src;
            break;
        }
        if(i == 0)
            npix = VImageNPixels(src1[i]);
        else if(npix != VImageNPixels(src1[i]))
            VError(" inconsistent image dimensions");
        if(src1[i] == NULL)
            VError(" no image found in %s", in_filename);
    }
    /*
    ** read images 2
    */
    src2 = (VImage *) VCalloc(nimages, sizeof(VImage));
    for(i = 0; i < nimages; i++) {
        src2[i] = NULL;
        in_filename = ((VStringConst *) in_files2.vector)[i];
        fp = VOpenInputFile(in_filename, TRUE);
        list2 = VReadFile(fp, NULL);
        if(! list2)
            VError("Error reading image");
        fclose(fp);
        for(VFirstAttr(list2, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
            if(VGetAttrRepn(& posn) != VImageRepn)
                continue;
            VGetAttrValue(& posn, NULL, VImageRepn, & src);
            if(VPixelRepn(src) != VFloatRepn)
                continue;
            src2[i] = src;
            break;
        }
        if(npix != VImageNPixels(src2[i]))
            VError(" inconsistent image dimensions");
        if(src2[i] == NULL)
            VError(" no image found in %s", in_filename);
    }
    /*
    ** paired wilcoxon test
    */
    dest = PairedWilcoxTest(src1, src2, dest, nimages);
    /*
    ** output
    */
    out_list = VCreateAttrList();
    VHistory(VNumber(options), options, prg_name, &list1, &out_list);
    VAppendAttr(out_list, "image", NULL, VImageRepn, dest);
    fp = VOpenOutputFile(out_filename, TRUE);
    if(! VWriteFile(fp, out_list))
        exit(1);
    fclose(fp);
    fprintf(stderr, "%s: done.\n", argv[0]);
    exit(0);
}
コード例 #25
0
ファイル: vfunctrans.c プロジェクト: Rollmops/lipsia
int main(int argc, char *argv[]) {
    /* command line arguments */
    static VString out_filename;
    static VArgVector in_files;
    static VString trans_filename = "";
    static VBoolean in_found, out_found;
    static VShort minval = 0;
    static VBoolean compress = TRUE;
    static VFloat resolution = 3;
    static VOptionDescRec options[] = {
        { "in", VStringRepn, 0, & in_files, & in_found, NULL, "Input file" },
        { "out", VStringRepn, 1, & out_filename, & out_found, NULL, "Output file" },
        {
            "trans", VStringRepn, 1, &trans_filename, VRequiredOpt, NULL,
            "File containing transformation matrix"
        },
        {
            "resolution", VFloatRepn, 1, &resolution, VOptionalOpt, NULL,
            "Output voxel resolution in mm"
        },
        {
            "minval", VShortRepn, 1, &minval, VOptionalOpt, NULL,
            "Signal threshold"
        },
        {
            "compress", VBooleanRepn, 1, &compress, VOptionalOpt, NULL,
            "Whether to compress empty slices"
        }
    };
    VStringConst in_filename;
    FILE *in_file, *out_file, *fp;
    VAttrList list, list1, out_list;
    VAttrListPosn posn;
    VImage trans = NULL;
    VImage *dst_image;
    VImageInfo *imageInfo;
    int nobject = 0, ntimesteps = 0, nbands = 0, nrows = 0, ncols = 0;
    VString ca, cp, extent, str;
    int found = 0;
    int j, dest_nbands;
    char prg_name[100];
	char ver[100];
	getLipsiaVersion(ver, sizeof(ver));
	sprintf(prg_name, "vfunctrans V%s", ver);
    fprintf(stderr, "%s\n", prg_name);
    /* Parse command line arguments: */
    if(! VParseCommand(VNumber(options), options, & argc, argv) ||
            ! VIdentifyFiles(VNumber(options), options, "in", & argc, argv, 0) ||
            ! VIdentifyFiles(VNumber(options), options, "out", & argc, argv, -1))
        goto Usage;
    if(argc > 1) {
        VReportBadArgs(argc, argv);
Usage:
        VReportUsage(argv[0], VNumber(options), options, NULL);
        exit(EXIT_FAILURE);
    }
    if(resolution <= 0)
        VError(" 'resolution' must be an integer > 0");
    /*
    ** Read the transformation matrix:
    */
    fp = VOpenInputFile(trans_filename, TRUE);
    list1 = VReadFile(fp, NULL);
    if(! list1)
        VError("Error reading image");
    fclose(fp);
    for(VFirstAttr(list1, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        if(VGetAttrRepn(& posn) != VImageRepn)
            continue;
        if(strncmp(VGetAttrName(&posn), "transform", 9) != 0)
            continue;
        VGetAttrValue(& posn, NULL, VImageRepn, & trans);
        break;
    }
    if(trans == NULL)
        VError("transformation matrix not found");
    /*
    ** check attributes
    */
    if(VGetAttr(VImageAttrList(trans), "ca", NULL,
                VStringRepn, (VPointer) & ca) != VAttrFound)
        VError(" attribute 'ca' missing in transformation matrix ");
    if(VGetAttr(VImageAttrList(trans), "cp", NULL,
                VStringRepn, (VPointer) & cp) != VAttrFound)
        VError(" attribute 'cp' missing in transformation matrix ");
    if(VGetAttr(VImageAttrList(trans), "extent", NULL,
                VStringRepn, (VPointer) & extent) != VAttrFound)
        VError(" attribute 'extent' missing in transformation matrix ");
    /*
    ** open in-file
    */
    if(in_files.number < 1 || in_files.number > 1)
        VError(" incorrect number of input files: %d", in_files.number);
    in_filename = ((VStringConst *) in_files.vector)[0];
    if(strcmp(in_filename, "-") == 0)
        in_file = stdin;
    else {
        in_file = fopen((char *)in_filename, "r");
        if(! in_file)
            VError("Failed to open input file %s", in_filename);
    }
    /*
    ** read file info
    */
    if(! ReadHeader(in_file))
        VError("error reading header");
    if(!(list = ReadAttrList(in_file)))
        VError("error reading attr list");
    j = 0;
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        j++;
    }
    imageInfo = (VImageInfo *) VMalloc(sizeof(VImageInfo) * (j + 1));
    nobject = nbands = found = 0;
    for(VFirstAttr(list, & posn); VAttrExists(& posn); VNextAttr(& posn)) {
        str = VGetAttrName(&posn);
        if(strncmp(str, "history", 7) == 0) {
            nobject++;
            continue;
        }
        VImageInfoIni(&imageInfo[nbands]);
        if(! VGetImageInfo(in_file, list, nobject, &imageInfo[nbands]))
            VError(" error reading image info");
        if(imageInfo[nbands].repn == VShortRepn) {
            found = 1;
            nrows = imageInfo[nbands].nrows;
            ncols = imageInfo[nbands].ncolumns;
            ntimesteps = imageInfo[nbands].nbands;
            nbands++;
        }
        nobject++;
    }
    fclose(in_file);
    if(!found)
        VError(" couldn't find functional data");
    /*
    ** process each time step
    */
    dst_image = VFunctrans(in_filename, imageInfo, nbands, trans, resolution,
                           ntimesteps, minval, compress, &dest_nbands);
    /*
    ** output
    */
    out_list = VCreateAttrList();
    VHistory(VNumber(options), options, prg_name, &list, &out_list);
    for(j = 0; j < dest_nbands; j++) {
        VAppendAttr(out_list, "image", NULL, VImageRepn, dst_image[j]);
    }
    /* Open and write the output file: */
    if(strcmp(out_filename, "-") == 0)
        out_file = stdout;
    else {
        out_file = fopen(out_filename, "w");
        if(! out_file)
            VError("Failed to open output file %s", out_filename);
    }
    if(!VWriteFile(out_file, out_list) || fclose(out_file))
        VSystemError("error writing output file");
    fprintf(stderr, "\n%s: done.\n", argv[0]);
    return (EXIT_SUCCESS);
}