Exemple #1
0
static int
fixed_guess(int npts, int npars, double *p, int nvars,
	    double *x, double *y, double *resid, double *covar)
{
    int i;
    static int firsttime = TRUE;

    if (nbr_params < npars && default_pars_set < npars){
	if (firsttime){
	    firsttime = FALSE;
	    ib_errmsg("MATH: fit: Initial parameter values not found");
	}
	return FALSE;
    }
    /* Get as many values from command line as available */
    for (i=0; i<npars && i<nbr_params; i++){
	p[i] = in_params[i];
    }
    /* Get the rest from hard-coded defaults */
    for ( ; i<npars; i++){
	p[i] = default_par_values[i];
    }
    if (resid){
	*resid = 0;
    }
    if (covar){
	for (i=0; i < (npars*(npars+1)) / 2; i++){
	    covar[i] = 0;
	}
    }

    return TRUE;
}
Exemple #2
0
int mathfunc() {
  float Baseline, X; 
  int pixel, im;
  char msg[1024];

  if (nbr_infiles<1 || input_sizes_differ || !want_output(0)){
    return FALSE;
  }

  if (nbr_outfiles != in_vec_len[0]) {
    sprintf(msg,"%s: The number of output images (%d) must match number of input images (%d)\n",
      PGM,nbr_outfiles,in_vec_len[0]);
    ib_errmsg(msg);
    return FALSE;
  }
  
  create_output_files(nbr_infiles, in_object[0]);

  /* Loop through every pixel */
  for (pixel = 0; pixel < img_size; pixel++){

    if (nbr_image_vecs < 2)
      Baseline = in_data[0][pixel];
    else {
      Baseline = 0;
      for (im = vecindx[1]; im < vecindx[1]+in_vec_len[1]; im++)
        Baseline += in_data[im][pixel];
      Baseline /= in_vec_len[1];
    }

    /* Loop through all images in input vector */
    for (im = 0; im < nbr_infiles; im++){
      X = in_data[im][pixel];
    
      if (want_output(im)){
        out_data[im][pixel] = X - Baseline;
      }
    
    }  /* end of image loop */
  }  /* end pixel loop */
  return TRUE;
}
Exemple #3
0
/************************************************************************
*                                                                       *
*  Parse the expression "cmd", looking for strings (text enclosed in quotes).
*  Returns list.
*  The "cmd" string is MODIFIED by replacing all strings with ""
*  (STATIC)								*
*									*/
ParmList
Win_math::get_stringlist(char *name, char *cmd)
{
    int i;
    int j;
    //int n;
    char *pc;
    char *pcc;
    char *pccc;
    char *str;
    char msg[256];
    ParmList strings;

    pc = cmd;

    /* Count up number of quotes */
    /*for (n=0, pcc=pc; pcc=strchr(pcc,'"'); n++, pcc++);
    if (n%2){
	ib_errmsg("MATH WARNING: unmatched quotes (\") in expression:");
	sprintf(msg,"\t%.250s", cmd);
	ib_errmsg(msg);
    }
    n /= 2;			// Number of strings*/

    strings = allocParm(name, PL_STRING, 0);
    for (i=0, pcc=pc; /*i<n,*/ pcc=strchr(pcc,'"'); i++){
	pc = strchr(++pcc, '"'); // pc -> ending quote
	if (!pc){
	    ib_errmsg("MATH WARNING: unmatched quotes (\") in expression");
	    break;
	}
	//pc = pcc + j;		// pc -> ending quote
	*pc++ = '\0';		// Replace with NULL
	strings = appendStrParm(strings, pcc); // Copy string into the list
	*pcc++ = '"';		// Restore ending quote
	pccc = pcc;
	while (*pccc++ = *pc++); // Move down stuff after ending quote
    }

    return strings;
}
Exemple #4
0
int
mathfunc()
{
    int i;
    double val;
    double *xvars;		/* Values of the independent variable(s) */
    int nvars;			/* Nbr of independent variables */
    int np = 0;			/* Number of numerical parameters found */
    double threshold = 0;	/* Ignore pixels below this intensity */
    double sigLev = 1; // Significance level to set pixel's fit value (1=no significance)
    double chisq = 0; // Chi-square -- alternative to sigLev, if set
    double snThresh = 0; // min S/N to set value of parameter pixel
    int nparams = 0;		/* Nbr of parameters in fit */
    char *xname = "ti";
    char msg[256];
    char *str;

    int quick = FALSE;
    int noderiv = FALSE;
    int gotfun = FALSE;
    int fit_type = NONLINEAR;
    int use_prev_params = FALSE;
    int prev = FALSE;
    int noprev = FALSE;
    int pdone;

    void (*function)() = NULL;
    void (*jacobian)() = NULL;
    int (*guess)() = NULL;
    int (*parfix)() = NULL;
    int (*method)() = NULL;
    double *(*xvarfunc)() = set_xvars;

    int arg = 2;
    extern double d1mach_();

    if (in_vec_len[0]<1){
	ib_errmsg("MATH: fit: No input images");
	return FALSE;
    }
    if (input_sizes_differ){
	ib_errmsg("MATH: fit: Input image sizes differ");
	return FALSE;
    }
    if (!want_output(0)){
	ib_errmsg("MATH: fit: No frame for first output image");
	return FALSE;
    }

    /* Read numerical parameters (nothing to do with params of the fit!) */
    pdone = FALSE;
    for (i=0; i<nbr_params && !pdone; i++){
	val = in_params[i];
	switch (i){
	  case 0:
	    threshold = val;
	    pdone = TRUE;	/* Last parameter to read */
	    break;
	}
    }
    nbr_params -= i;
    in_params += i;

    /* Read string parameters */
    gotfun = FALSE;
    for (i=0; i<nbr_strings; i++){
	str = in_strings[i];
	if (!gotfun && getfunction(str, &nparams, &use_prev_params, &fit_type,
				   &function, &jacobian, &guess, &parfix))
	{
	    /* Got a functional form */
	    gotfun = TRUE;
	}else if (!quick && strcasecmp(str,"quick") == 0){
	    /* Use "quick" mode */
	    quick = TRUE;
	}else if (!noderiv && strcasecmp(str,"noderiv") == 0){
	    /* Do not use derivative, even if available */
	    noderiv = TRUE;
	}else if (!prev && strcasecmp(str,"prev") == 0){
	    /* Use previous parameter values for estimates */
	    prev = TRUE;
	}else if (!noprev && strcasecmp(str,"noprev") == 0){
	    /* Do not use previous parameter values for estimates */
	    noprev = TRUE;
	} else if (strncasecmp(str, "p=", 2) == 0) {
	    val = atof(str+2);
	    if (val != 0) {
	        val = val < 1e-20 ? 1e-20 : (val > 1 ? 1 : val);
	        sigLev = val;
	    }
        } else if (strncasecmp(str, "chisq=", 6) == 0) {
            val = atof(str+6);
            if (val != 0) {
                chisq = val;
            }
        } else if (strncasecmp(str, "snThresh=", 9) == 0) {
            val = atof(str+9);
            if (val != 0) {
                snThresh = val;
            }
	}else{
	    /* None of the above--assume independent variable name */
	    xname = str;
	}
    }

    /* Do not write to more output files than we can usefully use */
    if (nparams){
	int maxout;
	maxout = 2 * nparams + 1;
	if (maxout<nbr_outfiles) nbr_outfiles = maxout; /* Change global var */
    }
    create_output_files(nbr_outfiles, in_object[0]);

    /* Check the setup */
    if (!gotfun){
	ib_errmsg("MATH: fit: No known fit type specified");
	return FALSE;
    }

    if (noderiv){
	jacobian = NULL;
    }

    if (prev){
	use_prev_params = TRUE;
    }else if (noprev){
	use_prev_params = FALSE;
    }

    if (quick || !function){
	method = NULL;
    }else{
	method = marquardt;
    }

    /* Set the independent variable */
    xvars = (*xvarfunc)(in_object, in_vec_len[0], xname, &nvars);
    if (!xvars){
	sprintf(msg,"MATH: No values for independent variable \"%.200s\"",
                xname);
	ib_errmsg(msg);
	return FALSE;
    }

    if (chisq == 0) {
        chisq = chisqCompInv(sigLev, in_vec_len[0] - nparams + 1);
    }

    fit_images(in_object, in_vec_len[0], xvars, nvars,
	       threshold, chisq, snThresh, img_width, img_height, img_depth,
	       out_object, nbr_outfiles, want_output, fit_type,
	       nparams, use_prev_params,
	       function, jacobian, method, guess, parfix);

    write_output_files();

    return TRUE;
}
Exemple #5
0
int mathfunc() {
  double sum, sum_x2, mean, std, min, max, X, thr; 
  double av_mean,av_std, av_pp, max_std, min_std, max_pp, min_pp;
  float  fract;
  float  **tmp_data;
  int    pixel, im, N, Nfilter;
  int    r,c, r0, c0, r1, r2, c1, c2;
  int    rad, d, do_filter;
  int    n1, n2, n3, n4;
  char   msg[1024],pgm[1024];
  enum  {nstdp, npp, nmean, nstd};  /* output images 0,1,2,3 */
  
  FILE *fp;
    
  if (nbr_infiles<1 || input_sizes_differ || !want_output(0))
    return FALSE;

  create_output_files(4, in_object[0]);

  /*************************************/
  /* Get input parameters              */
  /*************************************/
  /* Comment */
  strcpy(pgm,"stats");
  if (nbr_strings > 0) {
    strcpy(pgm,in_strings[0]);
  }

  /* Filter size */
  if ((img_width < 128) || (img_height < 128))
    Nfilter = 5; /* for small matrices, default to a 5x5 filter */
  else
    Nfilter = 11;  /* else default to a 11x11 filter */
  do_filter = 1;
  if (nbr_params > 0)
    Nfilter = in_params[0];  /* filter kernel size */

  /* How much of the image should we use? */
  if (nbr_params > 1)
    fract = in_params[1]/100;
  else
    fract = 0.80; /* default to 80% */


  /* Zero center pixels in output images? */
  if (nbr_strings > 1) {
    if (!strcmp("nodc",in_strings[1])) {
      r1 = r2 = c1 = c2 = -1;
      n1 = n2 = n3 = n4 = -1; /* default to zero'ing center pixel */
    }
  }
  else {
    /* Four pixels in center of image - avoid DC artifact */
    r1 = img_height/2-1;
    r2 = r1 + 1;
    c1 = img_width/2-1;
    c2 = c1 + 1;

    n1 = (r1-1)*img_width + c1;
    n2 = (r1-1)*img_width + c2;
    n3 = (r2-1)*img_width + c1;
    n4 = (r2-1)*img_width + c2;

  }

  /* Get threshold for segmenting image */
  thr = threshold(in_data[0],img_height,img_width);
  /* Find object based on first image */
  find_object(in_data[0],thr,img_height,img_width,
      &r0,&c0,&r1,&c1,&r2,&c2,&rad);

  /* Optional filtering of input images */
  if (Nfilter > 0) { /* Filter all images */
    do_filter = 1;      
    if ((tmp_data = (float **) malloc(sizeof(float *)*nbr_infiles)) == NULL)
      ib_errmsg("MALLOC ERROR 1");      
    for (im = 0; im < nbr_infiles; im++)
      if ((tmp_data[im] = (float *) malloc(sizeof(float)*img_size)) == NULL)
        ib_errmsg("MALLOC ERROR 2");      

    for (im = 0; im < nbr_infiles; im++)
      filter(in_data[im],tmp_data[im],Nfilter,img_height,img_width,thr);
  }

  /* Initialize output image */
  for (r = 0; r < img_height; r++) {
    for (c = 0; c < img_width; c++) {
      pixel = r*img_width + c;

      if (want_output(nmean)) out_data[nmean][pixel] = 0;
      if (want_output(nstd))  out_data[nstd][pixel]  = 0;
      if (want_output(nstdp)) out_data[nstdp][pixel] = 0;
      if (want_output(npp))   out_data[npp][pixel]   = 0;
    }
  }


  /* Loop through every pixel */
  av_std = av_pp = 0;
  
  for (r = r1; r < r2; r++){
    for (c = c1; c < c2; c++){
      pixel = r*img_width + c;
      d = (int) sqrt((double) ((r-r0)*(r-r0) + (c-c0)*(c-c0)));  /* distance from center */

      sum = sum_x2  = 0.0;
      min = 1e6; 
      max = 0.0;
      mean = std = 0;
      N = 0;
      
      if ((pixel != n1) && (pixel != n2) && (pixel != n3) && (pixel != n4)) {  /* skip center pixels */
        if (in_data[0][pixel] > thr) {
          /* Loop through all images in input vector */
          for (im = 0; im < nbr_infiles; im++) {
            if (do_filter)
              X = tmp_data[im][pixel];
            else
              X = in_data[im][pixel];

            sum    += X;
            sum_x2 += (X*X);
      
            if (X < min) min = X;
            if (X > max) max = X;
            
            N++;
          }  /* end of image loop */
          mean = sum/N;
          std  = (double) sqrt((double)((sum_x2/N) - (mean*mean)));

        }  /* End check threshold */
      } /* End check center pixel */

/* DEBUG
if (((r == 37) && (c == 28)) || ((r == 32) && (c == 25))){
  printf("At (%d,%d), max, min, mean, pp, std is %f, %f, %f, %f, %f\n",
    c,r,max, min, mean, (max - min)/mean*100.0,std);
  printf("sum, sumsq, sumsq/N, mean^2, sqr = %f, %f, %f, %f, %f, N = %d\n",
    sum,sum_x2*1000,sum_x2/N*1000*1000, mean*mean*1000*1000,(sum_x2/N - mean*mean)*1000*1000,N);
}
/**/
      if (want_output(nmean)) out_data[nmean][pixel] = mean;
      if (want_output(nstd))  out_data[nstd][pixel]  = std;
      if (want_output(nstdp)) {
        if (mean != 0)
          out_data[nstdp][pixel] = std/mean*100;
        else
          out_data[nstdp][pixel] = 0;
      }
      if (want_output(npp)) {
        if (mean != 0)
          out_data[npp][pixel] = (max - min)/mean*100.0;     
        else
          out_data[npp][pixel] = 0;
      }
    } /* end columns loop */  
  }  /* end rows loop */


  /* Get average standard deviation and PP within image */
  av_std = av_pp = 0; 
  max_std = max_pp = 0;
  min_std = min_pp = 1e6;
  N = 0;
  for (r = 0; r < img_height; r++){
    for (c = 0; c < img_width; c++){
      pixel = r*img_width + c;
      d = (int) sqrt((double) ((r-r0)*(r-r0) + (c-c0)*(c-c0)));  /* distance from center */
      if ((pixel != n1) && (pixel != n2) && (pixel != n3) && (pixel != n4)) {  /* skip center pixels */
        if ((d < rad) && (in_data[0][pixel] > thr)) {
	  N++;
          X = out_data[nstdp][pixel];
          av_std += X;
          if (max_std < X) max_std = X;
          if (min_std > X) min_std = X;

          if (want_output(npp)) {
            X = out_data[npp][pixel];
            av_pp += X;
            if (max_pp < X) max_pp = X;
            if (min_pp > X) min_pp = X;
          }
        }
      }
    }
  }
	

  if (N > 0) {
    printf("=========== STATS: %s ===================\n",pgm);
    printf("Average standard deviation in %d pixels is %.2f%%\n",N,av_std/N);
    printf("Standard deviations range from %.2f%% to %.2f%%\n",min_std,max_std);
    if (want_output(npp)) {
      printf("Average peak-to-peak is %.2f%%\n",av_pp/N);
      printf("Peak-to-peak range from %.2f%% to %.2f%%\n",min_pp,max_pp);
    }


    if ((fp = fopen("STAB_measurements.txt","a")) == NULL) {
      sprintf(msg,"Can't open STAB_measurements.txt for printing results");
      ib_errmsg(msg);
      return FALSE;
    }
    fprintf(fp,"=========== STATS: %s ===================\n",pgm);
    fprintf(fp,"Average standard deviation in %d pixels is %.2f%%\n",N,av_std/N);
    fprintf(fp,"Standard deviations range from %.2f%% to %.2f%%\n",min_std,max_std);
    if (want_output(npp)) {
      fprintf(fp,"Average peak-to-peak is %.2f%%\n",av_pp/N);
      fprintf(fp,"Peak-to-peak range from %.2f%% to %.2f%%\n",min_pp,max_pp);
    }
    fclose(fp);

  }

  return TRUE;
}
Exemple #6
0
int mathfunc() {
  double meanS, noise, meanG, maxS, minS, sum2, stdS, thr, X, minmax;
  int   pixel, pixel2, im, n1, n2, r, c, r1, c1, rG, cG, rS1, rS2, cS1, cS2;
  int   im_r1, im_r2, im_c1, im_c2, r0, c0, rad, d,
        Nfilter, NF2, N, skip_pix, pixelG;
  double fract;
  char msg[1024],pgm[1024];
  FILE  *fp;

  if (nbr_infiles<1 || input_sizes_differ){
    return FALSE;
  }


  if (nbr_outfiles != in_vec_len[0]) {
    sprintf(msg,"Math: You must supply as many output images as input images\n");
    ib_errmsg(msg);
    return FALSE;
  }


  /**************************/
  /* Create output images ***/
  /**************************/
  if (want_output(1))
    create_output_files(nbr_infiles*2, in_object[0]);
  else
    create_output_files(nbr_infiles, in_object[0]);

  /* How large a (mean) filter do we apply to find the ghosting level */
  if ((img_width < 128) || (img_height < 128))
    Nfilter = 5; /* for small matrices, default to a 5x5 filter */
  else
    Nfilter = 11;  /* else default to a 11x11 filter */
  if (nbr_params > 0) Nfilter = (int) in_params[0];
  NF2 = (int) (Nfilter/2);

  fract = 0.8;
  if (nbr_params > 1)
    fract = in_params[1]/100;

  strcpy(pgm,"SNR");
  if (nbr_strings > 0)
    strcpy(pgm,in_strings[0]);

  /**************************/
  /* Calculations ***********/
  /**************************/
  /* Get threshold for segmenting image */
  thr = threshold(in_data[0],img_height,img_width);

  /* Find image boundaries (radius) *********/
  find_object(in_data[0],thr,img_height,img_width,
    &r0,&c0,&im_r1,&im_c1,&im_r2,&im_c2,&rad);
  /* rad is the smallest radius; im_r1/c1/r2/c2 gives maximum extent of object */

  /* Find noise standard deviation **************/
  noise = find_noise(in_data[0],im_r1-3, im_c1-3, im_r2+3, im_c2+3);


  for (im = 0; im < nbr_infiles; im++){

    /* Apply a NxN mean filter to the image */
    filter(in_data[im],out_data[im],Nfilter,img_height,img_width,thr);

    /***********************************************/
    /* Calculate signal intensity and uniformity ***/
    /***********************************************/
    meanS = sum2 = n2 = 0;
    maxS = 0; minS = 1e6;
    for (r = 0; r < img_height; r++) {
      for (c = 0; c < img_width; c++) {
        pixel = r*img_width + c;
        X = in_data[im][pixel];
        d = (int) sqrt((double) ((r-r0)*(r-r0) + (c-c0)*(c-c0)));  /* distance from center */
        if (d <= rad*fract) {
            meanS += X;
            sum2  += (X*X);
            n2++;

            minmax = out_data[im][pixel];
            /* Find max/min filtered signal intensity */
            if (maxS < minmax) {maxS = minmax; rS1=r; cS1 = c;}
            if (minS > minmax) {minS = minmax; rS2=r; cS2 = c;}

        }
      }
    }
    meanS /= n2;
    stdS  = (float) sqrt((double)((sum2/n2) - (meanS*meanS)));


    /******************************************/
    /* Calculate ghost intensity **************/
    /******************************************/
    /* Assume ghosting is in horizontal direction   */
    /* Search +/- Nfilter columns beyond maximum extent of object */
    meanG = 0;
    cG = rG = pixelG = 0;
    skip_pix = (Nfilter > 3 ? Nfilter : 3);
    for (r = im_r1-1; r <= im_r2; r++) {
      /* Check to the left of the image */
      for (c = skip_pix; c < im_c1-skip_pix; c++) {
        pixel = r*img_width + c;
        X = out_data[im][pixel];
        if (X > meanG) {
          meanG = X;
          rG = r; cG = c; pixelG = pixel;
        }
      }
      /* Check to the right of the image */
      for (c = im_c2+skip_pix; c < img_width-skip_pix; c++) {
        pixel = r*img_width + c;
        X = out_data[im][pixel];
        if (X > meanG) {
          meanG = X;
          rG = r; cG = c; pixelG = pixel;
        }
      }
    }

    for (r = 0; r < img_height; r++) {
      for (c = 0; c < img_width; c++) {
        pixel = r*img_width + c;
        X = in_data[im][pixel];
        d = (int) sqrt((double) ((r-r0)*(r-r0) + (c-c0)*(c-c0)));  /* distance from center */
        if (!(d <= rad*fract)) {
          out_data[im][pixel] = 0;
        }
      }
    }
    out_data[im][pixelG] = meanG;




    printf("=========== %s: image %d ===================\n",pgm,im+1);
    printf("Signal, Noise, Ghosting (x100): %.6f, %.6f, %.6f\n",maxS*100,noise*100, meanG*100);
    printf("SNR: %.f (NEMA standard: %.f)\n",maxS/noise, maxS/noise*1.253);
    printf("Ghosting: %.2f%% of max signal (in %dx%dROI)\n",(meanG-noise)/maxS*100,Nfilter,Nfilter);
    printf("Maximum ghosting is in pixel %d, %d\n",cG,rG);
    printf("Percent Image Uniformity is%.2f%%\n",(1-(maxS-minS)/(maxS+minS))*100);
    printf("minS, maxS = %f and %f at (%d,%d),(%d,%d)\n",minS*100,maxS*100,cS2,rS2,cS1,rS1);
/*    printf("Image variation is %.f%%\n",stdS/meanS*100); */

    if ((fp = fopen("SNR_measurements.txt","a")) == NULL) {
      sprintf(msg,"Can't open file SNR_measurements.txt for printing results");
      ib_errmsg(msg);
      return FALSE;
    }
    fprintf(fp,"=========== %s: image %d ===================\n",pgm,im+1);
    fprintf(fp,"Signal, Noise, Ghosting (x100): %.6f, %.6f, %.6f\n",maxS*100,noise*100, meanG*100);
    fprintf(fp,"SNR: %.f (NEMA standard: %.f)\n",maxS/noise, maxS/noise*1.253);
    fprintf(fp,"Ghosting: %.2f%% of max signal (in %dx%dROI)\n",(meanG-noise)/maxS*100,Nfilter,Nfilter);
    fprintf(fp,"Maximum ghosting is in pixel %d, %d\n",cG,rG);
    fprintf(fp,"Percent Image Uniformity is%.2f%%\n",(1-(maxS-minS)/(maxS+minS))*100);
    fprintf(fp,"minS, maxS = %f and %f at (%d,%d),(%d,%d)\n",minS*100,maxS*100,cS2,rS2,cS1,rS1);
    fclose(fp);

  }  /* end image loop */

  return TRUE;
}
int main (int argc, char *argv[])
{                               /* --- main function */
  int     i, k = 0;             /* loop variables */
  char    *s;                   /* to traverse the options */
  CCHAR   **optarg = NULL;      /* option argument */
  CCHAR   *fn_inp  = NULL;      /* name of input  file */
  CCHAR   *fn_out  = NULL;      /* name of output file */
  CCHAR   *fn_sel  = NULL;      /* name of item selection file */
  #ifdef ISR_PATSPEC            /* if to allow a pattern spectrum */
  CCHAR   *fn_psp  = NULL;      /* name of pattern spectrum file */
  #endif
  CCHAR   *recseps = NULL;      /* record  separators */
  CCHAR   *fldseps = NULL;      /* field   separators */
  CCHAR   *blanks  = NULL;      /* blank   characters */
  CCHAR   *comment = NULL;      /* comment characters */
  CCHAR   *hdr     = "";        /* record header  for output */
  CCHAR   *sep     = " ";       /* item separator for output */
  CCHAR   *dflt    = "  (%1S)"; /* default format for check */
  CCHAR   *format  = dflt;      /* format for information output */
  int     target   = 's';       /* target type (closed/maximal) */
  ITEM    min      =  1;        /* minimum size of an item set */
  ITEM    max      = 16;        /* maximum size of an item set */
  double  supp     = 10;        /* minimum support (in percent) */
  int     eval     = 'x';       /* additional evaluation measure */
  double  minval   = 10;        /* minimum evaluation measure value */
  int     sort     =  2;        /* flag for item sorting and recoding */
  int     dir      = +1;        /* item processing order */
  long    repeat   =  1;        /* number of repetitions */
  int     mtar     =  0;        /* mode for transaction reading */
  int     mrep     =  0;        /* mode for item set reporting */
  int     stats    =  0;        /* flag for item set statistics */
  ITEM    m;                    /* number of items */
  TID     n;                    /* number of transactions */
  SUPP    w;                    /* total transaction weight */
  clock_t t;                    /* timer for measurements */
  ISEVALFN *evalfn = (ISEVALFN*)0; /* evaluation function */

  #ifndef QUIET                 /* if not quiet version */
  prgname = argv[0];            /* get program name for error msgs. */

  /* --- print usage message --- */
  if (argc > 1) {               /* if arguments are given */
    fprintf(stderr, "%s - %s\n", argv[0], DESCRIPTION);
    fprintf(stderr, VERSION); } /* print a startup message */
  else {                        /* if no arguments given */
    printf("usage: %s [options] infile [outfile]\n", argv[0]);
    printf("%s\n", DESCRIPTION);
    printf("%s\n", VERSION);
    printf("-t#      target type                              "
                    "(default: %c)\n", target);
    printf("         (s: frequent, c: closed, m: maximal item sets, "
                     "g: generators)\n");
    printf("-m#      minimum number of items per item set     "
                    "(default: %"ITEM_FMT")\n", min);
    printf("-n#      maximum number of items per item set     "
                    "(default: %"ITEM_FMT")\n", max);
    printf("-s#      minimum support of an item set           "
                    "(default: %g%%)\n", supp);
    printf("         (positive: percentage, "
                     "negative: absolute number)\n");
    printf("-e#      additional evaluation measure            "
                    "(default: none)\n");
    printf("-d#      minimum value of add. evaluation measure "
                    "(default: %g%%)\n", minval);
    printf("-q#      sort items w.r.t. their frequency        "
                    "(default: %d)\n", sort);
    printf("         (1: ascending, -1: descending, 0: do not sort,\n"
           "          2: ascending, -2: descending w.r.t. "
                    "transaction size sum)\n");
    printf("-u#      item processing order/search direction   "
                    "(default: %d)\n", dir);
    printf("         (fixed to -1 for closed/maximal item sets\n"
           "          fixed to +1 for generators, free otherwise)\n");
    printf("-x#      number of repetitions (for benchmarking) "
                    "(default: 1)\n");
    printf("-R#      read an item selection from a file\n");
    #ifdef ISR_PATSPEC
    printf("-P#      write a pattern spectrum to a file\n");
    #endif
    printf("-Z       print item set statistics (counts per size)\n");
    printf("-g       write output in scanable form "
                    "(quote certain characters)\n");
    printf("-h#      record header  for output                "
                    "(default: \"%s\")\n", hdr);
    printf("-k#      item separator for output                "
                    "(default: \"%s\")\n", sep);
    printf("-v#      output format for item set information   "
                    "(default: \"%s\")\n", format);
    printf("-w       transaction weight in last field         "
                    "(default: only items)\n");
    printf("-r#      record/transaction separators            "
                    "(default: \"\\n\")\n");
    printf("-f#      field /item        separators            "
                    "(default: \" \\t,\")\n");
    printf("-b#      blank   characters                       "
                    "(default: \" \\t\\r\")\n");
    printf("-C#      comment characters                       "
                    "(default: \"#\")\n");
    printf("-!       print additional option information\n");
    printf("infile   file to read transactions from           "
                    "[required]\n");
    printf("outfile  file to write frequent item sets to      "
                    "[optional]\n");
    return 0;                   /* print a usage message */
  }                             /* and abort the program */
  #endif  /* #ifndef QUIET */
  /* free option characters: acilopy [A-Z]\[CT] */

  /* --- evaluate arguments --- */
  for (i = 1; i < argc; i++) {  /* traverse arguments */
    s = argv[i];                /* get option argument */
    if (optarg) { *optarg = s; optarg = NULL; continue; }
    if ((*s == '-') && *++s) {  /* -- if argument is an option */
      while (*s) {              /* traverse options */
        switch (*s++) {         /* evaluate switches */
          case '!': help();                          break;
          case 't': target = (*s) ? *s++ : 's';      break;
          case 'm': min    = (ITEM)strtol(s, &s, 0); break;
          case 'n': max    = (ITEM)strtol(s, &s, 0); break;
          case 's': supp   =       strtod(s, &s);    break;
          case 'e': eval   = (*s) ? *s++ : 0;        break;
          case 'd': minval =       strtod(s, &s);    break;
          case 'q': sort   = (int) strtol(s, &s, 0); break;
          case 'u': dir    = (int) strtol(s, &s, 0); break;
          case 'x': repeat =       strtol(s, &s, 0); break;
          case 'R': optarg = &fn_sel;                break;
          #ifdef ISR_PATSPEC
          case 'P': optarg = &fn_psp;                break;
          #endif
          case 'Z': stats  = 1;                      break;
          case 'g': mrep   = ISR_SCAN;               break;
          case 'h': optarg = &hdr;                   break;
          case 'k': optarg = &sep;                   break;
          case 'v': optarg = &format;                break;
          case 'w': mtar  |= TA_WEIGHT;              break;
          case 'r': optarg = &recseps;               break;
          case 'f': optarg = &fldseps;               break;
          case 'b': optarg = &blanks;                break;
          case 'C': optarg = &comment;               break;
          default : error(E_OPTION, *--s);           break;
        }                       /* set option variables */
        if (optarg && *s) { *optarg = s; optarg = NULL; break; }
      } }                       /* get option argument */
    else {                      /* -- if argument is no option */
      switch (k++) {            /* evaluate non-options */
        case  0: fn_inp = s;      break;
        case  1: fn_out = s;      break;
        default: error(E_ARGCNT); break;
      }                         /* note filenames */
    }
  }
  if (optarg)     error(E_OPTARG);      /* check (option) arguments */
  if (k    < 1)   error(E_ARGCNT);      /* and number of arguments */
  if (min  < 0)   error(E_SIZE, min);   /* check the size limits */
  if (max  < 0)   error(E_SIZE, max);   /* and the minimum support */
  if (max  > 16)  error(E_SIZE, max);   /* and the minimum support */
  if (supp > 100) error(E_SUPPORT, supp);
  if (repeat < 1) error(E_REPEAT, repeat);
  if ((!fn_inp || !*fn_inp) && (fn_sel && !*fn_sel))
    error(E_STDIN);             /* stdin must not be used twice */
  switch (target) {             /* check and translate target type */
    case 's': target = ISR_ALL;              break;
    case 'c': target = ISR_CLOSED;           break;
    case 'm': target = ISR_MAXIMAL;          break;
    case 'g': target = ISR_GENERA;           break;
    default : error(E_TARGET, (char)target); break;
  }                             /* (get target type code) */
  switch (eval) {               /* check and translate measure */
    case 'x': evalfn = (ISEVALFN*)0;         break;
    case 'b': evalfn = isr_logrto;           break;
    default : error(E_MEASURE, (char)eval);  break;
  }                             /* (get evaluation measure code) */
  if ((format == dflt) && (supp < 0))
    format = "  (%a)";          /* adapt the default info. format */
  MSG(stderr, "\n");            /* terminate the startup message */

  /* --- read item selection --- */
  ibase = ib_create(0, 0);      /* create an item base */
  if (!ibase) error(E_NOMEM);   /* to manage the items */
  tread = trd_create();         /* create a transaction reader */
  if (!tread) error(E_NOMEM);   /* and configure the characters */
  trd_allchs(tread, recseps, fldseps, blanks, "", comment);
  if (fn_sel) {                 /* if item appearances are given */
    t = clock();                /* start timer, open input file */
    if (trd_open(tread, NULL, fn_sel) != 0)
      error(E_FOPEN, trd_name(tread));
    MSG(stderr, "reading %s ... ", trd_name(tread));
    m = ib_readsel(ibase,tread);/* read the given item selection */
    if (m < 0) error((int)-m, ib_errmsg(ibase, NULL, 0));
    trd_close(tread);           /* close the input file */
    MSG(stderr, "[%"ITEM_FMT" item(s)]", m);
    MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));
  }                             /* print a log message */

  /* --- read transaction database --- */
  tabag = tbg_create(ibase);    /* create a transaction bag */
  if (!tabag) error(E_NOMEM);   /* to store the transactions */
  t = clock();                  /* start timer, open input file */
  if (trd_open(tread, NULL, fn_inp) != 0)
    error(E_FOPEN, trd_name(tread));
  MSG(stderr, "reading %s ... ", trd_name(tread));
  k = tbg_read(tabag, tread, mtar);
  if (k < 0)                    /* read the transaction database */
    error(-k, tbg_errmsg(tabag, NULL, 0));
  trd_delete(tread, 1);         /* close the input file and */
  tread = NULL;                 /* delete the table reader */
  m = ib_cnt(ibase);            /* get the number of items, */
  n = tbg_cnt(tabag);           /* the number of transactions, */
  w = tbg_wgt(tabag);           /* the total transaction weight */
  MSG(stderr, "[%"ITEM_FMT" item(s), %"TID_FMT, m, n);
  if (w != (SUPP)n) MSG(stderr, "/%"SUPP_FMT, w);
  MSG(stderr, " transaction(s)] done [%.2fs].", SEC_SINCE(t));
  if ((m <= 0) || (n <= 0))     /* check for at least one item */
    error(E_NOITEMS);           /* and at least one transaction */
  MSG(stderr, "\n");            /* compute absolute support value */
  supp = ceilsupp((supp >= 0) ? 0.01 *supp *(double)w : -supp);

  /* --- sort and recode items --- */
  t = clock();                  /* start timer, print log message */
  MSG(stderr, "filtering, sorting and recoding items ... ");
  m = tbg_recode(tabag, (SUPP)supp, -1, 16, -sort);
  if (m <  0) error(E_NOMEM);   /* recode items and transactions */
  if (m <= 0) error(E_NOITEMS); /* and check the number of items */
  MSG(stderr, "[%"ITEM_FMT" item(s)]", m);
  MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));

  /* --- sort and reduce transactions --- */
  t = clock();                  /* start timer, print log message */
  MSG(stderr, "sorting and reducing transactions ... ");
  tbg_filter(tabag,min,NULL,0); /* remove items of short transactions */
  tbg_itsort(tabag, +1, 1);     /* sort items in transactions and */
  tbg_sort  (tabag, +1, 1);     /* sort the trans. lexicographically */
  n = tbg_reduce(tabag, 0);     /* reduce transactions to unique ones */
  tbg_pack(tabag, 16);          /* pack items with codes < 16 */
  MSG(stderr, "[%"TID_FMT, n);  /* print number of transactions */
  if (w != (SUPP)n) MSG(stderr, "/%"SUPP_FMT, w);
  MSG(stderr, " transaction(s)] done [%.2fs].\n", SEC_SINCE(t));

  /* --- find frequent item sets --- */
  t = clock();                  /* start the timer */
  if (eval == 'b') mrep |= ISR_LOGS;
  report = isr_create(ibase, target|mrep, -1, hdr, sep, NULL);
  if (!report) error(E_NOMEM);  /* create an item set reporter */
  isr_setfmt (report, format);  /* and configure it: set flags, */
  isr_setsize(report, min, max);/* info. format and size range, */
  if (evalfn)                   /* and the evaluation function */
    isr_seteval(report, evalfn, NULL, +1, 0.01*minval);
  #ifdef ISR_PATSPEC            /* if to allow a pattern spectrum */
  if (fn_psp && (isr_addpsp(report, NULL) < 0))
    error(E_NOMEM);             /* add a pattern spectrum if req. */
  #endif
  if (isr_open(report, NULL, fn_out) != 0)
    error(E_FOPEN, isr_name(report));  /* open the output file */
  MSG(stderr, "writing %s ... ", isr_name(report));
  if      (target == ISR_GENERA)              dir = +1;
  else if (target & (ISR_CLOSED|ISR_MAXIMAL)) dir = -1;
  fim16 = m16_create(dir, (SUPP)supp, report);
  if (!fim16) error(E_NOMEM);   /* create a 16 items machine */
  for (i = 0; i < repeat; i++){ /* repeated mining loop */
    isr_reset(report);          /* (re)init. the output counters */
    m16_addtbg(fim16, tabag);   /* add trans. bag to 16 items machine */
    k = m16_mine(fim16);        /* find frequent item sets */
    if (k < 0) error(E_NOMEM);  /* with 16 items machine */
  }
  if (isr_report(report) < 0)   /* report the empty set (if needed) */
    error(E_NOMEM);
  if (isr_close(report) != 0)   /* close the output file */
    error(E_FWRITE, isr_name(report));
  MSG(stderr, "[%"SIZE_FMT" set(s)]", isr_repcnt(report));
  MSG(stderr, " done [%.2fs].\n", SEC_SINCE(t));
  if (stats) isr_prstats(report, stdout, 0);

  /* --- write pattern spectrum --- */
  #ifdef ISR_PATSPEC            /* if to allow a pattern spectrum */
  if (fn_psp) {                 /* if to write a pattern spectrum */
    psp    = isr_getpsp(report);/* get the pattern spectrum */
    twrite = twr_create();      /* create a table writer and */
    if (!twrite) error(E_NOMEM);/* open the output file */
    if (twr_open(twrite, NULL, fn_psp) != 0)
      error(E_FOPEN,  twr_name(twrite));
    if (psp_report(psp, twrite) != 0)
      error(E_FWRITE, twr_name(twrite));
    twr_delete(twrite, 1);      /* write the pattern spectrum, */
    twrite = NULL;              /* delete the table writer, and */
  }                             /* clear the writer variable */
  #endif

  /* --- clean up --- */
  CLEANUP;                      /* clean up memory and close files */
  SHOWMEM;                      /* show (final) memory usage */
  return 0;                     /* return 'ok' */
}  /* main() */
Exemple #8
0
int
mathexpr(ParmList inparms, ParmList *outparms)
{
    float x, y, z;		/* User variables */
    float r[100];		/* Many user variables */
    int ii, jj, kk;		/* Integer user variables */
    int n[100];			/* Many integer user variables */

    int i, j, k;		/* Pixel position in row, column, depth */
    int width, height, depth;	/* Size of all images */
    int indx;			/* Running pixel number */

    char msg[128];
    DDLSymbolTable *st;
    DDLSymbolTable *out;
    float **img;		/* Vector of pointers to input data */
    float *iout;		/* Pointer to output data */
    int nsrcs;			/* Number of input images */
    ParmList src_ddls;
    ParmList dst_ddls;

    /*fprintf(stderr,"mathexpr(0x%x, 0x%x)\n", inparms, outparms);/*CMP*/
    /*printParm(inparms);/*CMP*/
    /* Grab the input args */
    src_ddls = findParm(inparms, "src_ddls");
    if (!src_ddls){
	ib_errmsg("MATH: \"src_ddls\" not passed");
	return FALSE;
    }
    nsrcs = countParm(src_ddls);
    img = (float **)malloc(nsrcs * sizeof(float *));
    fdfhandle = (DDLSymbolTable **)malloc(nsrcs * sizeof(DDLSymbolTable *));
    if (!img || !fdfhandle){
	ib_errmsg("MATH: out of memory");
	return FALSE;
    }

    /* Check image sizes */
    width = height = depth = 0;
    for (indx=0; indx<nsrcs; indx++){
	getPtrParm(src_ddls, &st, indx);
	i = get_image_width(st);
	j = get_image_height(st);
	k = get_image_depth(st);
	if (!i || !j){
	    sprintf(msg,"MATH: image size is %dx%d\n", i, j);
	    ib_errmsg(msg);
	    return FALSE;
	}
	if ((width && i != width)
	    || (height && j != height)
	    || (depth && k != depth))
	{
	    ib_errmsg("MATH: images are different sizes\n");
	    return FALSE;
	}
	width = i;
	height = j;
	depth = k;

	/* Point the working source image pointers to the appropriate data */
	img[indx] = get_ddl_data(st);
	fdfhandle[indx] = st;
    }
    /*fprintf(stderr,"MATH: width=%d, height=%d, depth=%d\n",
	    width, height, depth);/*DBG*/

    /* Copy the first input object (for storing the output image) */
    getPtrParm(src_ddls, &st, 0);
    out = clone_ddl(st, 1);
    /*fprintf(stderr,"MATH: out width=%d, data=0x%x, *data=%g\n",
	    get_image_width(out),
	    get_ddl_data(out), *get_ddl_data(out));/*CMP*/
    /*fprintf(stderr,"indata=0x%x, *indata=%g\n", img[0], img[0][0]);/*CMP*/
    iout = get_ddl_data(out);

    /*
     * NOTE: IB_EXPRESSION will be expanded into something like
     *		img[0][indx]+img[1][indx]
     */
    interrupt_begin();
    for (indx=k=0; k<depth; k++){
	for (j=0; j<height; j++){
	    for (i=0; i<width && !interrupt(); i++, indx++){
		iout[indx] = IB_EXPRESSION;
	    }
	}
    }
    interrupt_end();
    /*fprintf(stderr,"MATH: out width=%d, data=0x%x, *data=%g\n",
	    get_image_width(out),
	    get_ddl_data(out), *get_ddl_data(out));/*CMP*/

    /* Pass back the output image */
    *outparms = allocParm("dst_ddls", PL_PTR, 1);
    setPtrParm(*outparms, out, 0);

    return TRUE;
}