예제 #1
0
파일: input.c 프로젝트: dmt4/ne
static void input_move_left(const bool do_refresh) {
	if (pos > 0) {

		const int x_delta = get_char_width(&input_buffer[pos = prev_pos(input_buffer, pos, encoding)], encoding);

		assert(pos >= 0);

		if (x == start_x) {
			offset = pos;

			if (char_ins_del_ok) {
				int i, j;
				for(i = start_x, j = offset; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));
				if (j < len) {
					move_cursor(ne_lines - 1, i);
					delete_chars(get_char_width(&input_buffer[j], encoding));
				}
				move_cursor(ne_lines - 1, start_x);
				insert_char(get_char(&input_buffer[pos], encoding), 0, encoding);
				move_cursor(ne_lines - 1, start_x);
			}
			else if (do_refresh) input_refresh();
		}
		else x -= x_delta;
	}
}
예제 #2
0
파일: test-util.c 프로젝트: banada/systemd
static void test_delete_chars(void) {
       char *r;
       char input[] = "   hello, waldo.   abc";

       r = delete_chars(input, WHITESPACE);
       assert_se(streq(r, "hello,waldo.abc"));
}
예제 #3
0
static void test_delete_chars(void) {
        char *s, input[] = "   hello, waldo.   abc";

        s = delete_chars(input, WHITESPACE);
        assert_se(streq(s, "hello,waldo.abc"));
        assert_se(s == input);
}
예제 #4
0
static void test_unhexmem_one(const char *s, size_t l, int retval) {
        _cleanup_free_ char *hex = NULL;
        _cleanup_free_ void *mem = NULL;
        size_t len;

        assert_se(unhexmem(s, l, &mem, &len) == retval);
        if (retval == 0) {
                char *answer;

                if (l == (size_t) -1)
                        l = strlen(s);

                assert_se(hex = hexmem(mem, len));
                answer = strndupa(strempty(s), l);
                assert_se(streq(delete_chars(answer, WHITESPACE), hex));
        }
}
예제 #5
0
파일: input.c 프로젝트: dmt4/ne
static void input_move_right(const bool do_refresh) {
	const int prev_pos = pos;

	if (pos < len) {
		const int x_delta = get_char_width(&input_buffer[pos], encoding);
		pos = next_pos(input_buffer, pos, encoding);

		assert(pos <= len);

		if ((x += x_delta) >= ne_columns) {
			const int shift = x - (ne_columns - 1);
			int width = 0;

			do {
				width += get_char_width(&input_buffer[offset], encoding);
				offset = next_pos(input_buffer, offset, encoding);
			} while(width < shift && offset < len);

			assert(offset < len);

			x -= width;

			if (char_ins_del_ok) {
				int i, j;
				move_cursor(ne_lines - 1, start_x);
				delete_chars(width);
				move_cursor(ne_lines - 1, x - x_delta);
				output_char(get_char(&input_buffer[prev_pos], encoding), 0, encoding);

				i = x;
				j = pos;
				while(j < len && i + (width = get_char_width(&input_buffer[j], encoding)) < ne_columns) {
					output_char(get_char(&input_buffer[j], encoding), 0, encoding);
					i += width;
					j = next_pos(input_buffer, j, encoding);
				}
			}
			else if (do_refresh) input_refresh();
		}
	}
}
예제 #6
0
void go_plot_contours(
    char *device, char *title, char *xvar, char *yvar, char *topline,
    double **data, double xmin, double xmax, double ymin, double ymax,
    double dx, double dy, long nx, long ny,
    double *contour_level, long n_contours, long contour_label_interval,
    long contour_label_offset, long layout[2], long ix, long iy,
    char *shapes, int *pen, long flags, long pause_interval,
    SHAPE_DATA *shape, long nshapes, unsigned long long tsetFlags, double xlableScale, double ylabelScale)
{
    double map[4], average, spread;
    double pmin, pmax, qmin, qmax;
    double wpmin, wpmax=0, wqmin, wqmax=0;
    long title_at_top=0;
    char newLabel[50];
    time_t timeValue;

    if (!(flags&DEVICE_DEFINED)) 
      change_term(device, strlen(device));
    if ((ix == 0) && (iy == 0))
      graphics_on();
    if (layout[0] && layout[1]) {
      wpmin = (1.0*ix+0)/layout[0];
      wpmax = (1.0*ix+1)/layout[0];
      wqmin = (layout[1]*1.0 - 1 - iy)/layout[1];
      wqmax = (layout[1]*1.0 - 0 - iy)/layout[1];
      set_wspace(wpmin, wpmax, wqmin, wqmax);
      pmin = (wpmax - wpmin) * .15 + wpmin;
      pmax = wpmax - (wpmax - wpmin) * .1;
      qmin = (wqmax - wqmin) * .17 + wqmin;
      qmax = wqmax - (wqmax - wqmin) * .08;
      set_pspace(pmin, pmax, qmin, qmax);
    }

    if (contour_label_interval<0) {
      get_pspace(&pmin, &pmax, &qmin, &qmax);
      set_pspace(pmin, 0.9 * wpmax, qmin, 0.85 * wqmax);
    }
    if (flags&TITLE_AT_TOP) {
      /* adjust pspace to make room at top for the title */
      get_pspace(&pmin, &pmax, &qmin, &qmax);
      spread = qmax-qmin;
      qmax -= 0.04*spread;
      qmin -= 0.04*spread;
      /*    qmax -= 0.04;
            qmin -= 0.04;*/
      set_pspace(pmin, pmax, qmin, qmax);
      title_at_top = 1;
    }
    set_clipping(1, 1, 1);


    if (flags&EQUAL_ASPECT1) 
        set_aspect(1.0L);
    else if (flags&EQUAL_ASPECT_1)
        set_aspect(-1.0L);

    set_linetype(pen[0]);
    get_mapping(map, map+1, map+2, map+3);
    if (map[0]==map[1]) {
        average  = (xmax+xmin)/2;
        spread   = (xmax-xmin)/2;
        map[0]   = average - spread*1.05;
        map[1]   = average + spread*1.05;
        }
    if (map[2]==map[3]) {
        average  = (ymax+ymin)/2;
        spread   = (ymax-ymin)/2;
        map[2]   = average - spread*1.05;
        map[3]   = average + spread*1.05;
        }
    set_mapping(map[0], map[1], map[2], map[3]);
    get_pspace(&pmin, &pmax, &qmin, &qmax);
    get_wspace(&wpmin, &wpmax, &wqmin, &wqmax);

    if (!(flags&NO_BORDER)) {
      border();
      if (!(flags&NO_SCALES)) {
        if (tsetFlags&TICKSET_XTIME) {
          timeValue = map[0];
          if (timeValue!=DBL_MAX)
            sprintf(newLabel, "Time starting %s", ctime(&timeValue));
          else
            sprintf(newLabel, "Undefined time values!");
          delete_chars(newLabel, "\n");
          makeTimeScales(0, 0.02, 0, map[2], map[2], newLabel, 
                         0, 0.67*(qmin-wqmin)*(map[3]-map[2])/(qmax-qmin), 
                         0, 1, 1);
        } else {
          make_scales_with_label(0, 0, 1, 0.0, 0.02, 0.0, 
                                 0.0, 1.0, 0, 0, 
                                 0, 0, 0, 0, xvar, 0, 0, xlableScale);
        }
	if (!(flags&NO_YSCALES)) {
          if (tsetFlags&TICKSET_YTIME) {
            timeValue = map[2];
            if (timeValue!=DBL_MAX)
              sprintf(newLabel, "Time starting %s", ctime(&timeValue));
            else
              sprintf(newLabel, "Undefined time values!");
            delete_chars(newLabel, "\n");
            makeTimeScales(1, 0.0125, 0, map[0], map[0], newLabel, 
                           0, (pmin-wpmin)*(map[1]-map[0])/(pmax-pmin), 
                           0, 1, 1);
          } else {
            make_scales_with_label(1, 0, 1, 0.0, 0.0125, 0.0, 
                                   0.0, 1.0, 0, 0, 
                                   0, 0, 0, 0, yvar, 0, 0, ylabelScale);
          }
	}
      }
    }
    if (!(flags&NO_LABELS)) {
      plotTitle(title, 1, title_at_top, 1.0, 0.0, 0, 0);
      if (contour_label_interval>=0)
	plotTitle(topline, 0, 0, 1.0, 0.0, 0, 0);
    }
    set_linetype(pen[1]);
    draw_contours(data, xmin, xmax, ymin, ymax, nx, ny, contour_level, n_contours);
    if (contour_label_interval!=0) {
        set_linetype(pen[2]);
        label_contours(data, nx, ny, contour_level, n_contours,
            contour_label_interval, contour_label_offset,
            xmin, (double)dx, ymin, (double)dy);
        }
    set_linetype(pen[0]);

    if (nshapes)
      PlotShapesData(shape, nshapes, xmin, xmax, ymin, ymax);

    if (flags&DATE_STAMP)
        time_date_stamp();

    }
예제 #7
0
파일: sddsslopes.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
  SCANNED_ARG *scanned;
  SDDS_TABLE inputPage, outputPage, residualPage;
  char *inputfile, *outputfile;
  char **column, **excludeColumn;
  int32_t columns;
  long excludeColumns;
  char *indColumnName;
  long verbose;
  long iArg, i, j, ipage;
  double *indVar, *indVarOrig;
  char *indVarUnits;
  char **intColumn, **slopeColumn, **slopeSigmaColumn, **interceptSigmaColumn;
  char *Units,*slopeUnits;
  double *depVar, *depVarOrig;
  long order;
  double *coef, *coefsigma, *weight, *diff, *diffOrig, chi;
  long iCol, iRow;
  long rows, rowsOrig;
  double rmsResidual;
  double slopeSigma, interceptSigma;
  char **sigmaColumn, **chiSquaredColumn;
  long *sigmaColumnExists;
  long doSlopeSigma, generateSigma, doPreliminaryFit;
  long validSigmas;
  double sigmaSum, averageSigma;
  long ascii;
  char *residualFile;
  unsigned long pipeFlags;
  long tmpfile_used, noWarnings;
  double xMin, xMax;

  indVar = indVarOrig = depVar = depVarOrig = coef = coefsigma = weight = diff = NULL;
  intColumn = slopeColumn = slopeSigmaColumn = interceptSigmaColumn = sigmaColumn = chiSquaredColumn = NULL;
  slopeUnits = NULL;
  sigmaColumnExists = NULL;

  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&scanned, argc, argv);
  if (argc == 1) 
    bomb(NULL, USAGE);

  inputfile = outputfile = NULL;
  columns = excludeColumns = 0;
  column = excludeColumn = NULL;
  indColumnName = NULL;
  verbose = 0;
  doSlopeSigma = 0;
  generateSigma = 0;
  doPreliminaryFit = 0;
  ascii = 0;
  pipeFlags = 0;
  tmpfile_used=0;
  noWarnings=0;
  residualFile = NULL;
  xMin = xMax = 0;

  for (iArg = 1;  iArg<argc;  iArg++) {
    if (scanned[iArg].arg_type == OPTION) {
      delete_chars(scanned[iArg].list[0], "_");
      switch (match_string(scanned[iArg].list[0], commandline_option, COMMANDLINE_OPTIONS, UNIQUE_MATCH)) {
      case CLO_INDEPENDENT_COLUMN:   
        if (!(indColumnName = scanned[iArg].list[1]))
          SDDS_Bomb("no string given for option -independentVariable");
        break;
      case CLO_COLUMNS:
        if (columns)
          SDDS_Bomb("only one -columns option may be given");
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -columns syntax");
        column = tmalloc(sizeof(*column)*(columns = scanned[iArg].n_items-1));
        for (i = 0;  i<columns;  i++)
          column[i] = scanned[iArg].list[i+1];
        break;
      case CLO_EXCLUDE:
        if (excludeColumns)
          SDDS_Bomb("only one -excludecolumns option may be given");
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -excludecolumns syntax");
        excludeColumn = tmalloc(sizeof(*excludeColumn)*(excludeColumns = scanned[iArg].n_items-1));
        for (i = 0;  i<excludeColumns;  i++)
          excludeColumn[i] = scanned[iArg].list[i+1];
        break;
      case CLO_VERBOSE:
        verbose = 1;
        break;
      case CLO_ASCII:
        ascii = 1;
        break;
      case CLO_PIPE:
        if (!processPipeOption(scanned[iArg].list+1, scanned[iArg].n_items-1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      case CLO_SIGMA:
        doSlopeSigma = 1;
        if (scanned[iArg].n_items > 1 ) {
          switch (match_string(scanned[iArg].list[1], sigma_option, SIGMA_OPTIONS, UNIQUE_MATCH)) {
          case SIGMA_GENERATE:
            generateSigma = 1;
            break;
          default:
            SDDS_Bomb("unrecognized sigma option given");
            break;
          }
        }
        break;
      case CLO_RESIDUAL:
        if (!(residualFile=scanned[iArg].list[1])){
          fprintf(stderr,"No file specified in -residual option.\n");
          exit(1);
        }
        break;
      case CLO_RANGE:
        if (scanned[iArg].n_items!=3 ||
            1!=sscanf(scanned[iArg].list[1], "%lf", &xMin) ||
            1!=sscanf(scanned[iArg].list[2], "%lf", &xMax) ||
            xMin>=xMax)
          SDDS_Bomb("incorrect -range syntax");
        break;
      default: 
        SDDS_Bomb("unrecognized option given");
        break;
      }
    }
    else {
      if (!inputfile)
        inputfile = scanned[iArg].list[0];
      else if (!outputfile)
        outputfile = scanned[iArg].list[0];
      else
        SDDS_Bomb("too many filenames given");
    }
  }

  if (residualFile && outputfile) {
    if (!strcmp( residualFile, outputfile)) {
      fprintf( stderr, "Residual file can't be the same as the output file.\n");
      exit(1);
    }
  }
  
  processFilenames("sddsslopes", &inputfile, &outputfile, pipeFlags, noWarnings, &tmpfile_used);

  if (!indColumnName) {
    fprintf( stderr, "independentVariable not given\n");
    exit(1);
  }
  
  if (!excludeColumns) {
    excludeColumn = defaultExcludedColumn;
    excludeColumns = DEFAULT_EXCLUDED_COLUMNS;
  }
  
  if (verbose)
    fprintf(stderr,"Reading file %s.\n",inputfile);
  if ( !SDDS_InitializeInput( &inputPage, inputfile) )
    SDDS_PrintErrors( stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
  while (0 < (ipage=SDDS_ReadTable( &inputPage))) {
    if (verbose) {
      fprintf(stderr, "working on page %ld\n", ipage);
    }
    rows = SDDS_CountRowsOfInterest(&inputPage);
    rowsOrig = rows;
    /*************************************\
     * make array of independent variable
     \*************************************/
    if (ipage==1) {
      indVar = (double*) malloc( sizeof(*indVar) * rows);
    }
    else {
      indVar = (double*) realloc( indVar, sizeof(*indVar) * rows);
    }
    if (ipage==1) {
      if (!SDDS_FindColumn(&inputPage, FIND_NUMERIC_TYPE, indColumnName, NULL)){
        fprintf(stderr,"Something wrong with column %s.\n", indColumnName);
        SDDS_CheckColumn(&inputPage, indColumnName, NULL, SDDS_ANY_NUMERIC_TYPE, stderr);
        exit(1);
      }
    }
    /* filter out the specified range in independent variable */
    if (xMin!=xMax) {
      if (!(indVarOrig = SDDS_GetColumnInDoubles( &inputPage, indColumnName))) 
        SDDS_PrintErrors( stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
      for (i=j=0; i<rowsOrig; i++) {
        if (indVarOrig[i]<=xMax && indVarOrig[i]>=xMin) {
          indVar[j] = indVarOrig[i];
          j++;
        }
      }
      rows = j;
    }
    else {
      if (!(indVar = SDDS_GetColumnInDoubles( &inputPage, indColumnName))) 
        SDDS_PrintErrors( stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    }
    if ( ipage == 1 ) {
      if (!SDDS_GetColumnInformation(&inputPage, "units", &indVarUnits, SDDS_GET_BY_NAME, indColumnName))
        SDDS_PrintErrors( stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      if (!indVarUnits) {
        indVarUnits = (char *) malloc(sizeof(*indVarUnits));
        indVarUnits[0] = 0;
      }
    }
    /************************************\
     * initialize residual file 
     \************************************/
    if (residualFile) {
      if ( ipage == 1 ) {
        if(!SDDS_InitializeOutput(&residualPage,ascii?SDDS_ASCII:SDDS_BINARY,1,
                                  "Residual of 2-term fit",NULL,outputfile) ||
           !SDDS_InitializeCopy(&residualPage, &inputPage, residualFile, "w") ||
           !SDDS_WriteLayout(&residualPage) )
          SDDS_PrintErrors(stderr,SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      if (!SDDS_CopyPage(&residualPage,&inputPage))
        SDDS_PrintErrors(stderr,SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  
    /************************************\
     * get columns of interest. use set_multicolumn_flags to simply
     * return new values for array column.
     \*************************************/
    if (!set_multicolumn_flags(&inputPage, &column, &columns, excludeColumn, excludeColumns)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
    /************************************\
     * make  column names for the output
     \*************************************/
    if (ipage==1) {
      intColumn = (char**) malloc((sizeof(char*)*columns));
      slopeColumn = (char**) malloc((sizeof(char*)*columns));
      if (doSlopeSigma) {
        slopeSigmaColumn = (char**) malloc((sizeof(char*)*columns));
        interceptSigmaColumn = (char**) malloc((sizeof(char*)*columns));
        chiSquaredColumn = (char**) malloc((sizeof(char*)*columns));
      }
      for (i=0; i<columns; i++) {
        intColumn[i] = (char*) malloc((sizeof(char)*(strlen(column[i])+strlen("Intercept")+1)));
        strcat(strcpy(intColumn[i], column[i]), "Intercept");
        slopeColumn[i] = (char*) malloc((sizeof(char)*(strlen(column[i])+strlen("Slope")+1)));
        strcat(strcpy(slopeColumn[i], column[i]), "Slope");
        if (doSlopeSigma) {
          slopeSigmaColumn[i] = (char*) malloc((sizeof(char)*(strlen(column[i])+strlen("SlopeSigma")+1)));
          strcat(strcpy(slopeSigmaColumn[i], column[i]), "SlopeSigma");
          interceptSigmaColumn[i] = (char*) malloc((sizeof(char)*(strlen(column[i])+strlen("InterceptSigma")+1)));
          strcat(strcpy(interceptSigmaColumn[i], column[i]), "InterceptSigma");
          chiSquaredColumn[i] = (char*) malloc((sizeof(char)*(strlen(column[i])+strlen("ChiSquared")+1)));
          strcat(strcpy(chiSquaredColumn[i], column[i]), "ChiSquared");
        }
      }
    }
    /************************************\
     * Write layout for output file
     \*************************************/
    if (ipage==1) {
      if (verbose)
        fprintf(stderr,"Opening file %s.\n",outputfile);
      if(!SDDS_InitializeOutput(&outputPage,ascii?SDDS_ASCII:SDDS_BINARY,1,
                                "2-term fit",NULL,outputfile) ||
         0>SDDS_DefineParameter(&outputPage, "InputFile", "InputFile", NULL,
                                "InputFile", NULL, SDDS_STRING, 0) ||
         0>SDDS_DefineColumn(&outputPage, "IndependentVariable", NULL, NULL, NULL, NULL, SDDS_STRING,0) )
        SDDS_PrintErrors(stderr,SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      for (iCol=0; iCol<columns; iCol++) {
        if (!SDDS_GetColumnInformation(&inputPage, "units", &Units, SDDS_GET_BY_NAME, column[iCol]))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if (!Units) {
          Units = (char*) malloc(sizeof(*Units));
          Units[0] = 0;
        }
        if (0>SDDS_DefineColumn(&outputPage, intColumn[iCol], NULL, Units, NULL, NULL, SDDS_DOUBLE,0))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        /* units for slopes columns */
        if (strlen(indVarUnits) && strlen(Units) ) {
          slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(Units)+strlen(indVarUnits)+2));
          strcat( strcat( strcpy(slopeUnits, Units), "/"), indVarUnits);
        }
        if (strlen(indVarUnits) && !strlen(Units) ) {
          slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(indVarUnits)+2));
          strcat( strcpy( slopeUnits, "1/"), indVarUnits);
        }
        if (!strlen(indVarUnits) && strlen(Units) ) {
          slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(Units)+2));
          strcpy( slopeUnits, indVarUnits);
        }
        if (!strlen(indVarUnits) && !strlen(Units) ) {
          slopeUnits = (char*)malloc(sizeof(*slopeUnits));
          strcpy( slopeUnits, "");
        }
        if (0>SDDS_DefineColumn(&outputPage, slopeColumn[iCol], NULL, slopeUnits, NULL, NULL, SDDS_DOUBLE,0))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if (doSlopeSigma) {
          if (0>SDDS_DefineColumn(&outputPage, interceptSigmaColumn[iCol], NULL, Units, 
                                  NULL, NULL, SDDS_DOUBLE,0) ||
              0>SDDS_DefineColumn(&outputPage, slopeSigmaColumn[iCol], NULL, slopeUnits, 
                                  NULL, NULL, SDDS_DOUBLE,0) ||
              0>SDDS_DefineColumn(&outputPage, chiSquaredColumn[iCol], NULL, NULL, 
                                  NULL, NULL, SDDS_DOUBLE,0))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
        free(slopeUnits);
      }
      if ( !SDDS_WriteLayout(&outputPage))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  
    if ( !SDDS_StartTable(&outputPage,1) ||
       !SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                           "InputFile",inputfile?inputfile:"pipe",NULL) ||
       !SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 0,
                          "IndependentVariable", indColumnName, NULL) )
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    
    /* determine which included columns has a Sigma column defined in the input file */
    if ( ipage == 1 ) {
      sigmaColumn = (char **) malloc( sizeof(*sigmaColumn)*columns);
      sigmaColumnExists = (long *) malloc(columns*sizeof(*sigmaColumnExists)); 
      for (iCol=0; iCol<columns; iCol++) {
        sigmaColumn[iCol] = (char *) malloc( sizeof(**sigmaColumn) * 
                                            (strlen(column[iCol]) + strlen("Sigma") + 1) );
        strcat( strcpy(sigmaColumn[iCol], column[iCol]), "Sigma");
        switch(SDDS_CheckColumn(&inputPage, sigmaColumn[iCol], NULL, SDDS_DOUBLE, NULL)) {
        case SDDS_CHECK_WRONGUNITS:
        case SDDS_CHECK_OKAY:
          sigmaColumnExists[iCol] = 1;
          break;
        default:
          /* try other possible spelling */
          strcat( strcpy(sigmaColumn[iCol] ,"Sigma"), column[iCol]);
          switch(SDDS_CheckColumn(&inputPage, sigmaColumn[iCol], NULL, SDDS_DOUBLE, NULL)) {
          case SDDS_CHECK_WRONGUNITS:
          case SDDS_CHECK_OKAY:
            sigmaColumnExists[iCol] = 1;
            break;
          default:
            sigmaColumnExists[iCol] = 0;
          }
          break;
        }
      }
    }
    
    if ( ipage == 1 ) {
      weight = (double*)malloc(sizeof(*weight)*rows);
      diff = (double*)malloc(sizeof(*diff)*rows);
      order=1;
      coef = (double*)malloc(sizeof(*coef)*(order+1));
      coefsigma = (double*)malloc(sizeof(*coefsigma)*(order+1));
    }
    else {
      weight = (double*)realloc( weight, sizeof(*weight)*rows);
      diff = (double*)realloc( diff, sizeof(*diff)*rows);
      order=1;
      coef = (double*)realloc( coef, sizeof(*coef)*(order+1));
      coefsigma = (double*)realloc( coefsigma, sizeof(*coefsigma)*(order+1));
    }
    
    if (ipage==1) {
      depVar = (double*) malloc( sizeof(*depVar) * rows);
    }
    else {
      depVar = (double*) realloc( depVar, sizeof(*depVar) * rows);
    }
    for (iCol=0; iCol<columns; iCol++) {
      if (verbose)
        fprintf(stderr,"Doing column %s.\n", column[iCol]);
      /* filter out the specified range in independent variable */
      if (xMin!=xMax) {
        if (!(depVarOrig = (double*) SDDS_GetColumnInDoubles(&inputPage, column[iCol])))
          SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        for (i=j=0; i<rowsOrig; i++) {
          if ( xMin <= indVarOrig[i] && indVarOrig[i] <= xMax ) {
            depVar[j] = depVarOrig[i];
            j++;
          }
        }
      }
      else {
        if (!(depVar=SDDS_GetColumnInDoubles(&inputPage, column[iCol])))
          SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
      }
      
      /*********************
        three possibilities:
        1) don't do or write slope errors. (doSlopeSigma=0)
        do one lsf call with all weights = 1
        2) calculated slope errors from sigma columns in the input file. 
        (doSlopeSigma=1 && generateSigma=0 && sigmaColumnExists[iCol]=1 )
        do one lsf call with weights from sigma columns
        3) calculate slope errors from generated sigma from a preliminary fit. 
        (doSlopeSigma=1 && (generateSigma=1 || sigmaColumnExists[iCol]=NULL)
        do preliminary fit to generate sigma
        *********************/

      for (iRow=0; iRow<rows; iRow++)
        weight[iRow] = 1;
      if (doSlopeSigma) {
        /*********************
          check validity of sigma column values 
          *********************/
        if( !generateSigma && sigmaColumnExists[iCol]) {
          if (verbose)
            fprintf(stderr,"\tUsing column %s for sigma.\n",sigmaColumn[iCol]);
          if(!(weight=SDDS_GetColumnInDoubles(&inputPage, sigmaColumn[iCol])))
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
          /* check for zero weight values which will give lsfn problems */
          validSigmas = rows;
          sigmaSum = 0;
          for (iRow=0; iRow<rows; iRow++) {
            sigmaSum += weight[iRow];
            if(!weight[iRow]) {
              validSigmas--;
              /* 
                fprintf(stderr,"Warning: %s of row number %ld is zero. Using average sigma.\n",sigmaColumn[iCol],iRow); */
            }
          }
          if (!validSigmas) {
            fprintf(stderr,"Warning: All sigmas are zero.\n");
            doPreliminaryFit = 1;
          }
          else if (validSigmas!=rows) {
            /* fix some sigmas */
            averageSigma = sigmaSum/ validSigmas;
            fprintf(stderr, "Warning: replacing %ld invalid sigmas with average (%e)\n",
                    rows-validSigmas, averageSigma);
            for (iRow=0; iRow<rows; iRow++) {
              if(!weight[iRow]) {
                weight[iRow] = averageSigma;
              }
            }
          }
        }
        else {
          doPreliminaryFit = 1;
        }
      }
      
      if (doPreliminaryFit) {
        if (verbose)
          fprintf(stderr,"\tGenerating sigmas from rms residual of a preliminary fit.\n");
        if (!(lsfn(indVar, depVar, weight, rows, order, coef, coefsigma, &chi, diff))){
          fprintf(stderr,"Problem with call to lsfn\n.");
          exit(1);
        }
        rmsResidual = 0;
        /* calculate rms residual */
        for (iRow=0; iRow<rows; iRow++) {
          rmsResidual += sqr(diff[iRow]);
        }
        rmsResidual = sqrt(rmsResidual/(rows));
        for (iRow=0; iRow<rows; iRow++) {
          weight[iRow] = rmsResidual;
        }
      }
      
      if (!(lsfn(indVar, depVar, weight, rows, order, coef, coefsigma, &chi, diff))) {
        fprintf(stderr,"Problem with call to lsfn\n.");
        exit(1);
      }
      if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 0,
                             intColumn[iCol], coef[0],
                             slopeColumn[iCol], coef[1], NULL))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      if (doSlopeSigma) {
        interceptSigma = coefsigma[0];
        slopeSigma = coefsigma[1];
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 0,
                               chiSquaredColumn[iCol], chi,
                               interceptSigmaColumn[iCol], interceptSigma,
                               slopeSigmaColumn[iCol], slopeSigma, NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      if (residualFile) {
        if (xMin!=xMax) {
          /* calculate the residuals for the whole column explicitly since there
             are points outside the range of which the lsf call did not calculate
             the difference. */
          diffOrig = (double*) malloc( rowsOrig * sizeof(double) );
          for (i=0; i<rowsOrig; i++) {
            diffOrig[i] = depVarOrig[i] - coef[0] - coef[1] * indVarOrig[i];
          }
          if( !SDDS_SetColumnFromDoubles(&residualPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_REFERENCE,
                                         diffOrig,rowsOrig,column[iCol]))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
        else {
          if( !SDDS_SetColumnFromDoubles(&residualPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_REFERENCE,
                                         diff,rows,column[iCol]))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
    }

    if (residualFile) {
      if (!SDDS_WriteTable(&residualPage)) 
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    
    if (!SDDS_WriteTable(&outputPage)) 
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  if (residualFile) {
    if (!SDDS_Terminate(&residualPage))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  if(!SDDS_Terminate(&inputPage) || !SDDS_Terminate(&outputPage))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  if (tmpfile_used && !replaceFileAndBackUp(inputfile, outputfile)) 
    exit(1);
  return(0);
}
예제 #8
0
int main(int argc, char **argv)
{
  SCANNED_ARG *scanned;
  SDDS_TABLE inputPage, *copiedPage, outputPage;
  long copiedPages;
  char *inputfile, *outputfile;
  char **column, **excludeColumn=NULL;
  int32_t columns;
  long excludeColumns;
  char *indParameterName;
  char **copyColumn;
  int32_t copyColumns;
  long verbose;
  long slopeErrors;
  long iArg,i;
  double *indVar;
  char *indVarUnits;
  char **intColumn,**slopeColumn,**slopeSigmaColumn;
  char *Units,*slopeUnits;
  double *depVar;
  long order;
  double *coef,*coefsigma,*weight,*diff,chi;
  long iCol,iRow,iPage;
  long rows;
  double *slope, slope2, slopeAve, slopeSigma;
  unsigned long pipeFlags, majorOrderFlag;
  long tmpfile_used, noWarnings;
  long generateIndex;
  short columnMajorOrder=-1;

  copiedPage = NULL;
  slopeSigmaColumn = NULL;
  slopeUnits = Units = indVarUnits = NULL;
  rows = 0;
  slope = NULL;
  slope2 = 0;
  coef = coefsigma = weight = diff = slope = NULL;
  
  argc = scanargs(&scanned, argc, argv);
  if (argc == 1) 
    bomb(NULL, USAGE);

  inputfile = outputfile = NULL;
  columns = excludeColumns = 0;
  column = excludeColumn = NULL;
  indParameterName = NULL;
  verbose = 0;
  slopeErrors = 0;
  pipeFlags = 0;
  tmpfile_used=0;
  noWarnings=0;
  for (iArg = 1;  iArg<argc;  iArg++) {
    if (scanned[iArg].arg_type == OPTION) {
      delete_chars(scanned[iArg].list[0], "_");
      switch (match_string(scanned[iArg].list[0], commandline_option, COMMANDLINE_OPTIONS, UNIQUE_MATCH)) {
      case CLO_MAJOR_ORDER:
        majorOrderFlag=0;
        scanned[iArg].n_items--;
        if (scanned[iArg].n_items>0 &&
            (!scanItemList(&majorOrderFlag, scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                           "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                           "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                           NULL)))
          SDDS_Bomb("invalid -majorOrder syntax/values");
        if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
          columnMajorOrder=1;
        else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
          columnMajorOrder=0;
        break;
      case CLO_INDEPENDENT_PARAMETER:   
        if (!(indParameterName = scanned[iArg].list[1]))
          SDDS_Bomb("no string given for option -independentVariable");
        break;
      case CLO_COLUMNS:
        if (columns)
          SDDS_Bomb("only one -columns option may be given");
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -columns syntax");
        column = tmalloc(sizeof(*column)*(columns = scanned[iArg].n_items-1));
        for (i = 0;  i<columns;  i++)
          column[i] = scanned[iArg].list[i+1];
        break;
      case CLO_EXCLUDE:
        if (excludeColumns)
          SDDS_Bomb("only one -excludecolumns option may be given");
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -excludecolumns syntax");
        excludeColumn = tmalloc(sizeof(*excludeColumn)*(excludeColumns = scanned[iArg].n_items-1));
        for (i = 0;  i<excludeColumns;  i++)
          excludeColumn[i] = scanned[iArg].list[i+1];
        break;
      case CLO_VERBOSE:
        verbose = 1;
        break;
      case CLO_PIPE:
        if (!processPipeOption(scanned[iArg].list+1, scanned[iArg].n_items-1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      case CLO_SLOPE_ERRORS:
        slopeErrors = 1;
        break;
      default: 
        SDDS_Bomb("unrecognized option given");
        break;
      }
    }
    else {
      if (!inputfile)
        inputfile = scanned[iArg].list[0];
      else if (!outputfile)
        outputfile = scanned[iArg].list[0];
      else
        SDDS_Bomb("too many filenames given");
    }
  }

  processFilenames("sddsvslopes", &inputfile, &outputfile, pipeFlags, noWarnings, &tmpfile_used);

  if (!indParameterName)
    SDDS_Bomb("independentVariable not given");

  if (!excludeColumns) {
    excludeColumn = defaultExcludedColumn;
    excludeColumns = DEFAULT_EXCLUDED_COLUMNS;
  }
  
  if (verbose)
    fprintf(stderr,"Reading file %s.\n",inputfile);
  SDDS_InitializeInput(&inputPage, inputfile);
  copiedPages = 0;
  while (SDDS_ReadTable(&inputPage)>0) {
    if (!copiedPages) {
      copiedPage = (SDDS_TABLE*)malloc(sizeof(SDDS_TABLE));
      rows = SDDS_CountRowsOfInterest(&inputPage);
    }
    else {
      copiedPage = (SDDS_TABLE*)realloc(copiedPage, (copiedPages+1)*sizeof(SDDS_TABLE));
    }
    if (!SDDS_InitializeCopy(&copiedPage[copiedPages], &inputPage, NULL, "m"))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    if (!SDDS_CopyTable(&copiedPage[copiedPages], &inputPage))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    copiedPages++;
  }
  if (copiedPages<2) {
    fprintf(stderr,"Insufficient data (i.e. number of data pages) to fit a straight line.\n");
    exit(1);
  }
  switch(SDDS_CheckColumn(&inputPage, "Rootname", NULL, SDDS_STRING, NULL)) {
  case SDDS_CHECK_WRONGUNITS:
  case SDDS_CHECK_OKAY:
    break;
  default:
    fprintf(stderr,"Something wrong with column %s.\n", "Rootname");
    exit(1);
  }
  switch(SDDS_CheckColumn(&inputPage, "Index", NULL, SDDS_LONG, NULL)) {
  case SDDS_CHECK_WRONGUNITS:
  case SDDS_CHECK_OKAY:
    generateIndex = 0;
    break;
  case SDDS_CHECK_NONEXISTENT:
    generateIndex = 1;
    break;
  default:
    fprintf(stderr,"Something wrong with column %s.\n", "Rootname");
    exit(1);
  }
  /****************\
   * make array of independent variable
   \**************/
  indVar = (double*)malloc(sizeof(*indVar)*copiedPages);
  switch(SDDS_CheckParameter(&inputPage, indParameterName, NULL, SDDS_DOUBLE, NULL)) {
  case SDDS_CHECK_WRONGUNITS:
  case SDDS_CHECK_OKAY:
    break;
  default:
    fprintf(stderr,"Something wrong with parameter %s.\n", indParameterName);
    exit(1);
  }
  for (iPage = 0; iPage<copiedPages; iPage++) {
    if (!SDDS_GetParameter(&copiedPage[iPage],indParameterName,&indVar[iPage])) 
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
  }
  if (!SDDS_GetParameterInformation(&inputPage, "units", &indVarUnits, SDDS_GET_BY_NAME, indParameterName))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (!indVarUnits) {
    indVarUnits = (char *) malloc(sizeof(*indVarUnits));
    indVarUnits[0] = 0;
  }
  /************************************\
   * get columns of interest. use set_multicolumn_flags to simply
   * return new values for array column.
   \*************************************/
  if (!set_multicolumn_flags(&inputPage, &column, &columns, excludeColumn, excludeColumns)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  /************************************\
   * make  column names for the output
   \*************************************/
  intColumn = (char**)malloc((sizeof(char*)*columns));
  slopeColumn = (char**)malloc((sizeof(char*)*columns)); 
  if (slopeErrors)
    slopeSigmaColumn = (char**)malloc((sizeof(char*)*columns));
  for (i=0; i<columns; i++) {
    intColumn[i] = (char*)malloc((sizeof(char)*(strlen(column[i])+strlen("Intercept")+1)));
    strcat(strcpy(intColumn[i], column[i]), "Intercept");
    slopeColumn[i] = (char*)malloc((sizeof(char)*(strlen(column[i])+strlen("Slope")+1)));
    strcat(strcpy(slopeColumn[i], column[i]), "Slope");
    if (slopeErrors) {
      slopeSigmaColumn[i] = (char*)malloc((sizeof(char)*(strlen(column[i])+strlen("SlopeSigma")+1)));
      strcat(strcpy(slopeSigmaColumn[i], column[i]), "SlopeSigma");
    }
  }
  /************************************\
   * Write layout for output file
   \*************************************/
  if (verbose)
    fprintf(stderr,"Opening file %s.\n",outputfile);
  if(!SDDS_InitializeOutput(&outputPage,SDDS_BINARY,1,
                            "lsf of sddsvexperiment",NULL,outputfile) ||
     0>SDDS_DefineParameter(&outputPage, "InputFile", "InputFile", NULL,
                            "InputFile", NULL, SDDS_STRING, 0) ||
     0>SDDS_DefineParameter(&outputPage, "IndependentVariable", "IndependentVariable", NULL,
                            "IndependentVariable", NULL, SDDS_STRING, 0) ||
     (0>SDDS_DefineColumn(&outputPage,"Index",NULL,NULL,"Rootname index",NULL,SDDS_LONG,0))||
     (0>SDDS_DefineColumn(&outputPage,"Rootname",NULL,NULL,NULL,NULL,SDDS_STRING,0)))
    SDDS_PrintErrors(stderr,SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
   if (columnMajorOrder!=-1)
     outputPage.layout.data_mode.column_major = columnMajorOrder;
   else
     outputPage.layout.data_mode.column_major = inputPage.layout.data_mode.column_major;
  for (iCol=0; iCol<columns; iCol++) {
    if (!SDDS_GetColumnInformation(&inputPage, "units", &Units, SDDS_GET_BY_NAME,column[iCol]))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!Units) {
      Units = (char*) malloc(sizeof(*Units));
      Units[0] = 0;
    }
    if (0>SDDS_DefineColumn(&outputPage, intColumn[iCol], NULL, Units, NULL, NULL, SDDS_DOUBLE,0))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    /* units for slopes columns */
    if (strlen(indVarUnits) && strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(Units)+strlen(indVarUnits)+2));
      strcat( strcat( strcpy(slopeUnits, Units), "/"), indVarUnits);
    }
    if (strlen(indVarUnits) && !strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(indVarUnits)+2));
      strcat( strcpy( slopeUnits, "1/"), indVarUnits);
    }
    if (!strlen(indVarUnits) && strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(Units)+2));
      strcpy( slopeUnits, indVarUnits);
    }
    if (!strlen(indVarUnits) && !strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits));
      strcpy( slopeUnits, "");
    }
    if (0>SDDS_DefineColumn(&outputPage, slopeColumn[iCol], NULL, slopeUnits, NULL, NULL, SDDS_DOUBLE,0))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (slopeErrors) {
      if (0>SDDS_DefineColumn(&outputPage, slopeSigmaColumn[iCol], NULL, slopeUnits, NULL, NULL, SDDS_DOUBLE,0))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    free(slopeUnits);
  }
  if(!SDDS_WriteLayout(&outputPage) || 
     !SDDS_StartTable(&outputPage,rows) ||
     !SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                         "InputFile",inputfile?inputfile:"pipe",NULL)  ||
     !SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 0,
                         "IndependentVariable", indParameterName, NULL) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  /************************************\
   * Copy columns to output file (usually columns Index and Rootname)
   \*************************************/
  copyColumns = DEFAULT_COPY_COLUMNS;
  copyColumn = defaultCopyColumn;
  if (!set_multicolumn_flags(&inputPage, &copyColumn, &copyColumns, NULL, 0)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    exit(1);
  }
  if(!SDDS_CopyColumns(&outputPage, &inputPage))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  depVar = (double*)malloc(sizeof(*depVar)*copiedPages);
  weight = (double*)malloc(sizeof(*weight)*copiedPages);
  diff = (double*)malloc(sizeof(*weight)*copiedPages);
  order=1;
  coef = (double*)malloc(sizeof(*coef)*(order+1));
  coefsigma = (double*)malloc(sizeof(*coefsigma)*(order+1));
  if(slopeErrors)
    slope = (double*)malloc(sizeof(*slope)*copiedPages);
  for (iCol=0; iCol<columns; iCol++) {
    for (iPage=0; iPage<copiedPages; iPage++) 
      weight[iPage]=1;
    if (verbose)
      fprintf(stderr,"Doing column %s.\n", column[iCol]);
    for (iRow=0; iRow<rows; iRow++) {
      for (iPage=0; iPage<copiedPages; iPage++) {
        if (!SDDS_GetValue(&copiedPage[iPage], column[iCol], iRow, &depVar[iPage]))                     
          SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
      }
      if (!(lsfn(indVar, depVar, weight, copiedPages, order, coef, coefsigma, &chi, diff))){
        fprintf(stderr,"Problem with call to lsfn\n.");
        exit(1);
      }
      if (generateIndex) {
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, iRow,
                               "Index",iRow,
                               intColumn[iCol], coef[0],
                               slopeColumn[iCol], coef[1], NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      else {
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, iRow,
                               intColumn[iCol], coef[0],
                               slopeColumn[iCol], coef[1], NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      if(slopeErrors){
        /* recalculate the slope with a subset of points  */
        slopeAve= slope2 = 0;
        for (iPage=0; iPage<copiedPages; iPage++) {
          weight[iPage] = 1e10;
          if(iPage)
            weight[iPage-1] = 1; 
          if (!(lsfn(indVar, depVar, weight, copiedPages, order, coef, coefsigma, &chi, diff))){
            fprintf(stderr,"Problem with call to lsfn\n.");
            exit(1);
          }
          slope[iPage] = coef[1];
          slopeAve += slope[iPage];
          slope2 += sqr(slope[iPage]);
        }
        slopeSigma = sqrt(slope2/copiedPages - sqr(slopeAve/copiedPages));
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, iRow,
                               slopeSigmaColumn[iCol], slopeSigma, NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
    }
  }
 
  if( !SDDS_WriteTable(&outputPage)|| SDDS_Terminate(&inputPage) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  for (iPage=0; iPage<copiedPages; iPage++) {
    if( !SDDS_Terminate(&copiedPage[iPage]) )
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  if( SDDS_Terminate(&outputPage) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (tmpfile_used && !replaceFileAndBackUp(inputfile, outputfile)) 
    exit(1);
  SDDS_FreeStringArray(column, columns);
  free(column);
  SDDS_FreeStringArray(intColumn, columns);
  SDDS_FreeStringArray(slopeColumn, columns); 
  free(intColumn);
  free(slopeColumn);
  if (slopeErrors) {
    SDDS_FreeStringArray(slopeSigmaColumn, columns);
    free(slopeSigmaColumn);
  }
  
  free(copiedPage);
  free(indVar);
  free(depVar);
  if (weight)
    free(weight);
  if (diff)
    free(diff);
  if (slope)
    free(slope);
  if (coef) free(coef);
  if (coefsigma) free(coefsigma);
  if (Units) free(Units);
  if (indVarUnits) free(indVarUnits);
  
  free_scanargs(&scanned, argc);
  
  return(0);
}
예제 #9
0
파일: citi2sdds.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, points;
    char *input, *output, *name, *indep_var, *var_list_format;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    char buffer[BUFSIZE], buffer0[BUFSIZE], buffer1[BUFSIZE];
    char *ptr, *ptr1, *ptr2;
    char **data_name, *package_name, *data_format;
    long data_names, data_sets_seen, data_sets_expected, realIndex, imagIndex;
    double **real_data, **imag_data, *var_list;

    argc = scanargs(&scanned, argc, argv);
    if (argc<3)
        bomb(NULL, USAGE);

    input = output = package_name = data_format = indep_var = var_list_format = ptr = NULL;
    mpl_title = mpl_topline = descrip_text = descrip_contents = NULL;
    data_names = realIndex = imagIndex = 0;
    data_name = NULL;
    real_data = imag_data = NULL;
    var_list = NULL;
    data_sets_expected = data_sets_seen = 0;
    points = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            delete_chars(scanned[i_arg].list[0], "_");
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_DESCRIPTION:
                if (scanned[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -description syntax");
                descrip_text = scanned[i_arg].list[1];
                descrip_contents = scanned[i_arg].list[2];
                break;
              case SET_MPL_LABELS:
                if (scanned[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -mpllabels syntax");
                mpl_title = scanned[i_arg].list[1];
                mpl_topline = scanned[i_arg].list[2];
                break;
              default:
                SDDS_Bomb("invalid option seen");
                break;
                }
            }
        else {
            if (!input)
                input = scanned[i_arg].list[0];
            else if (!output)
                output = scanned[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }
    if (!input)
        SDDS_Bomb("input file not seen");
    if (!output)
        SDDS_Bomb("output file not seen");

    fpi = fopen_e(input, "r", 0);
    if (!fgets(buffer, BUFSIZE, fpi) || strncmp(buffer, CITIFILE_TAG, strlen(CITIFILE_TAG))!=0 ||
        !(ptr=strchr(buffer, ' ')))
        SDDS_Bomb("valid CITIFILE version line not found");
    *ptr++ = 0;
    ptr[strlen(ptr)-1] = 0;
    if (strncmp(ptr, CITIFILE_VERSION, strlen(CITIFILE_VERSION))!=0)
        fprintf(stderr, "warning: the CITIFILE version is %s--this program is only designed for version %s\n",
                ptr, CITIFILE_VERSION);
    
    
    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, descrip_text, descrip_contents,
                               output))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if ((mpl_title &&
        SDDS_DefineParameter(&SDDS_table, "mplTitle", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_title)<0) ||
        (mpl_topline &&
         SDDS_DefineParameter(&SDDS_table, "mplTopline", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_topline)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    while (fgets(buffer, BUFSIZE, fpi)) {
#if DEBUG
        fputs(buffer, stderr);
#endif
        buffer[strlen(buffer)-1] = 0;
        strcpy(buffer0, buffer);
        ptr1 = NULL;
        if ((ptr1=strchr(buffer, ' '))) 
            *ptr1++ = 0;
        switch (match_string(buffer, citi_keyword, N_CITI_KEYWORDS, EXACT_MATCH)) {
          case CITI_NA_KEYWORD:
            name = buffer+1;
            if (!*ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains an apparently invalid #NA keyword:\n%s\n",
                        buffer0);
                exit(1);
                }
            *(ptr1-1) = '_';
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, name, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for #NA keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_NAME_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "NAME: %s\n", ptr1);
#endif
            cp_str(&package_name, ptr1);
            if (SDDS_DefineParameter(&SDDS_table, "CITIPackageName", NULL, NULL, NULL, NULL, SDDS_STRING,
                                      package_name)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for NAME keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_VAR_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "VAR: %s\n", ptr1);
#endif
            if (!(indep_var=get_token(ptr1)) || !(var_list_format=get_token(ptr1)) || !get_long(&points, ptr1) ||
                points<=0) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
            if (SDDS_DefineColumn(&SDDS_table, indep_var, NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_CONSTANT_KEYWORD:
            if (!ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "CONSTANT: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, ptr1, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for CONSTANT keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_COMMENT_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "COMMENT: %s\n", ptr1);
#endif
            break;
          case CITI_DATA_KEYWORD:
            if (!ptr1 || !(ptr2 = strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "DATA: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            cp_str(&data_format, ptr2);
            data_name = trealloc(data_name, sizeof(*data_name)*(data_names+1));
            cp_str(data_name+data_names, ptr1);
            alter_data_name(data_name[data_names]);
            real_data = trealloc(real_data, sizeof(*real_data)*(data_names+1));
            imag_data = trealloc(imag_data, sizeof(*imag_data)*(data_names+1));
	    sprintf(buffer, "%sReal", data_name[data_names]);
	    sprintf(buffer1, "%sImag", data_name[data_names]);
            if ((realIndex=SDDS_DefineColumn(&SDDS_table, buffer, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ||
                (imagIndex=SDDS_DefineColumn(&SDDS_table, buffer1, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            data_names++;
            break;
          case CITI_VAR_LIST_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "VAR_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("VAR_LIST_BEGIN statement seen without prior VAR statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_var_list(fpi, var_list, points))
                SDDS_Bomb("unable to read VAR_LIST");
            break;
          case CITI_BEGIN_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("BEGIN statement seen without prior VAR statement");
            real_data[data_sets_seen] = tmalloc(sizeof(**real_data)*points);
            imag_data[data_sets_seen] = tmalloc(sizeof(**imag_data)*points);
            if (!read_CITI_data(fpi, real_data[data_sets_seen], imag_data[data_sets_seen], points))
                SDDS_Bomb("problem reading data section");
            data_sets_seen++;
            break;
          case CITI_SEG_LIST_BEGIN:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "SEG_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("SEG_LIST_BEGIN statement seen without prior SEG statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_seg_list(fpi, var_list, points))
                SDDS_Bomb("unable to read SEG_LIST");
            break;
          default:
            fprintf(stderr, "unidentifiable line in file--not CITI format:\n\"%s\"\n",
                    buffer0);
            exit(1);
            break;
            }
        }
    if (!points)
        SDDS_Bomb("no data in file");
    if (data_sets_seen!=(data_sets_expected=data_names))
        SDDS_Bomb("fewer data sets than expected were actually present");
    if (!var_list) {
        fprintf(stderr, "warning: no independent variable data---supplying index\n");
        var_list = tmalloc(sizeof(*var_list)*points);
        for (i=0; i<points; i++)
            var_list[i] = i;
        }
    if (!SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, (void*)var_list, points, indep_var))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    for (i=0; i<data_sets_expected; i++) {
         if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)real_data[i], points, 
                             realIndex) ||
             !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)imag_data[i], points, 
                             imagIndex)) {
             fprintf(stderr, "problem setting data for column(s) %s\n", data_name[i]);
             SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
             }
         }
    if (!SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
예제 #10
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, index, points, lsb_first, bytes_per_number;
    char *input, *output, buffer[BUFSIZE];
    char *signal_name, *ptr, *parameter_name;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    long code, binary;
    double xIncrement, xZero, yMultiplier, yZero;
    char *xUnits, *yUnits;
    double *time, *data;
    short columnMajorOrder=0;
    unsigned long majorOrderFlag;
    
    xUnits = yUnits = NULL;

    argc = scanargs(&scanned, argc, argv);
    if (argc<3)
        bomb(NULL, USAGE);

    input = output = signal_name = NULL;
    mpl_title = mpl_topline = descrip_text = descrip_contents = NULL;
    binary = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            delete_chars(scanned[i_arg].list[0], "_");
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_MAJOR_ORDER:
              majorOrderFlag=0;
              scanned[i_arg].n_items--;
              if (scanned[i_arg].n_items>0 &&
                  (!scanItemList(&majorOrderFlag, scanned[i_arg].list+1, &scanned[i_arg].n_items, 0,
                                 "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                                 "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                                 NULL)))
                SDDS_Bomb("invalid -majorOrder syntax/values");
              if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
                columnMajorOrder=1;
              else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
                columnMajorOrder=0;
              break;
            case SET_SIGNAL_NAME:
              if (scanned[i_arg].n_items!=2)
                bomb("invalid -signal_name syntax", USAGE);
              signal_name = scanned[i_arg].list[1];
                break;
            case SET_DESCRIPTION:
              if (scanned[i_arg].n_items!=3)
                bomb("invalid -description syntax", USAGE);
              descrip_text = scanned[i_arg].list[1];
              descrip_contents = scanned[i_arg].list[2];
              break;
            case SET_MPL_LABELS:
              if (scanned[i_arg].n_items!=3)
                bomb("invalid -mpl_labels syntax", USAGE);
              mpl_title = scanned[i_arg].list[1];
              mpl_topline = scanned[i_arg].list[2];
              break;
            default:
              bomb("invalid option seen", USAGE);
              break;
            }
        }
        else {
          if (!input)
            input = scanned[i_arg].list[0];
          else if (!output)
            output = scanned[i_arg].list[0];
          else
            bomb("too many filenames", USAGE);
            }
    }
    if (!input)
      SDDS_Bomb("input file not seen");
    if (!output)
      SDDS_Bomb("output file not seen");
    if (!signal_name)
      signal_name = "V";
    
    fpi = fopen_e(input, "r", 0);
    if (fread(buffer, 1, strlen(TEK_PreambleString), fpi)!=strlen(TEK_PreambleString) ||
        strncmp(TEK_PreambleString, buffer, strlen(TEK_PreambleString))!=0)
        SDDS_Bomb("file does not appear to be in Tektronix format");

    parameter_name = buffer;
    while ((code=GetNextItem(buffer, BUFSIZE, fpi))<3) {
        if (!(ptr=strchr(buffer, ':')))
            SDDS_Bomb("error parsing input file--missing colon on parameter tag");
        *ptr++ = 0;
        if (strcmp(TEK_DataMarker, parameter_name)==0)
            break;
        index = 0;
        while (TEK_parameter[index].TEK_name) {
            if (strcmp(TEK_parameter[index].TEK_name, parameter_name)==0)
                break;
            index++;
            }
        if (!TEK_parameter[index].TEK_name) {
            fprintf(stderr, "warning: parameter %s is not recognized\n",
                    parameter_name);
            continue;
            }
        if (TEK_parameter[index].value_string) {
            fprintf(stderr, "error: duplicate entries for parameter %s\n",
                    parameter_name);
            exit(1);
            }
        SDDS_RemovePadding(ptr);
        SDDS_CopyString(&TEK_parameter[index].value_string, ptr);
        if (code==2 || code==3)
            break;
        }
    if (code!=2)
        SDDS_Bomb("unexpected end of file");

    if (fread(buffer, 1, strlen(TEK_DataMarker), fpi)!=strlen(TEK_DataMarker) ||
        strncmp(TEK_DataMarker, buffer, strlen(TEK_DataMarker))!=0)
        SDDS_Bomb("CURVE item missing or not in right place");

    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, descrip_text, descrip_contents,
                               output))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_table.layout.data_mode.column_major = columnMajorOrder;
    
    index = 0;
    while (TEK_parameter[index].TEK_name) {
        if (!TEK_parameter[index].value_string) {
            index++;
            continue;
            }
        if (strcmp(TEK_parameter[index].TEK_name, TEK_XIncrementName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &xIncrement)!=1)
                SDDS_Bomb("unable to scan value for x increment");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_XZeroName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &xZero)!=1)
                SDDS_Bomb("unable to scan value for x zero");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YZeroName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &yZero)!=1)
                SDDS_Bomb("unable to scan value for y zero");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YMultiplierName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &yMultiplier)!=1)
                SDDS_Bomb("unable to scan value for y multiplier");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_XUnitsName)==0) {
            xUnits = TEK_parameter[index].value_string;
            str_tolower(xUnits);
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YUnitsName)==0) {
            yUnits = TEK_parameter[index].value_string;
            str_tolower(yUnits);
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_PointsName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%ld", &points)!=1)
                SDDS_Bomb("unable to scan value for number of points");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_EncodingName)==0) {
            if (strcmp(TEK_parameter[index].value_string, "ASCII")==0) 
                binary = 0;
            else if (strcmp(TEK_parameter[index].value_string, "BINARY")==0)
                binary = 1;
            else
                SDDS_Bomb("data encoding is neither ASCII nor BINARY");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_BytesPerNumberName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%ld", &bytes_per_number)!=1)
                SDDS_Bomb("unable to scan value bytes per number");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_ByteOrderName)==0) {
            lsb_first = 1;
            if (strcmp(TEK_parameter[index].value_string, "LSB")!=0)
                lsb_first = 0;
            }
        if (SDDS_DefineParameter(&SDDS_table, TEK_parameter[index].SDDS_name,
                                  NULL, NULL, TEK_parameter[index].TEK_name,
                                  NULL, TEK_parameter[index].type, 
                                  TEK_parameter[index].value_string)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        index++;
        }

    if (mpl_title &&
        (SDDS_DefineParameter(&SDDS_table, "mplTitle", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_title)<0 ||
         SDDS_DefineParameter(&SDDS_table, "mplTopline", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_topline)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (SDDS_DefineColumn(&SDDS_table, "t", NULL, xUnits, NULL, NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&SDDS_table, signal_name, NULL, yUnits, NULL, NULL, SDDS_DOUBLE, 0)<0 ||
        !SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    data = tmalloc(sizeof(*data)*points);
    time = tmalloc(sizeof(*time)*points);
    if (!binary) {
        for (i=0; i<points; i++) {

            if (!(code=GetNextItem(buffer, BUFSIZE, fpi)))
                SDDS_Bomb("insufficient data in input file");
            if (code==4) {
                points = i;
                break;
                }
            time[i] = xZero + i*xIncrement;
            if (sscanf(buffer, "%lf", data+i)!=1)
                SDDS_Bomb("invalid data in input file");
            data[i] = yZero + data[i]*yMultiplier;
            }
        }
    else {
        short sdata;
        fread(buffer, sizeof(char), 4, fpi);
        for (i=0; i<points; i++) {
            if (fread(&sdata, sizeof(sdata), 1, fpi)!=1) {
                fprintf(stderr, "file ends unexpectedly\n");
                points = i;
                break;
                }
            time[i] = xZero + i*xIncrement;
            data[i] = sdata;
            data[i] = yZero + data[i]*yMultiplier;
            }
        }

    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, time, points, "t") ||
        !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, data, points, signal_name) ||
        !SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
예제 #11
0
int main( int argc, char **argv)
{
  SCANNED_ARG *scanned;
  char *inputfile, *outputfile;
  SDDS_DATASET twissPage, resultsPage;
  double particles, charge, length;
  long verbosity, noWarning, i, elements, superperiods, growthRatesOnly, force;
  double pCentral0, I1, I2, I3, I4, I5, taux, tauy, taudelta;
  double EMeV;
  double emitx0, emitx, emitxInput, emityInput, emity, coupling, sigmaz0, sigmaz;
  double sigmaDelta0, sigmaDelta, sigmaDeltaInput, xGrowthRate, yGrowthRate, zGrowthRate;
  double xGrowthRateInitial, yGrowthRateInitial, zGrowthRateInitial;
  double emitxOld, sigmaDeltaOld;
  long method, converged;
/* used in simplex minimization */
  double yReturn, *xGuess, *dxGuess, *xLowerLimit, *xUpperLimit;
  short *disable;
  long dimensions = 15, maxEvaluations = 500, maxPasses = 2;
  double target = 1e-6;
  int32_t integrationTurns, integrationStepSize;
  long integrationPoints = 0;
  double *exInteg=NULL, *eyInteg=NULL, *elInteg=NULL, *xRateInteg=NULL, *yRateInteg=NULL, *zRateInteg=NULL;
  double *SdeltaInteg=NULL, *SzInteg=NULL;
  int32_t *passInteg=NULL;
  unsigned long dummyFlags;
  double rfVoltage, rfHarmonic;
  double alphac, U0, circumference, energy;
  double *xRateVsS, *yRateVsS, *zRateVsS;
  
  SDDS_RegisterProgramName(argv[0]);
  argc  =  scanargs(&scanned, argc, argv);
  if (argc == 1)
    bomb(NULL, USAGE);

  xRateVsS = yRateVsS = zRateVsS = NULL;
  inputfile  =  NULL;
  outputfile  =  NULL;
  energy = 0;
  verbosity = 0;
  isRing = 1;
  particles = 0;
  charge = 0;
  coupling = emityInput = 0;
  force = 1;
  length = 0;
  superperiods=1;
  method = 0;
  emitxInput = 0;
  sigmaDeltaInput = 0;
  growthRatesOnly = 0;
  integrationTurns = 0;
  rfVoltage = rfHarmonic = 0;
  noWarning = 0;
  for (i = 1; i<argc; i++) {
    if (scanned[i].arg_type == OPTION) {
      delete_chars(scanned[i].list[0], "_");
      switch(match_string(scanned[i].list[0], option, N_OPTIONS, UNIQUE_MATCH)) {
      case VERBOSE:
        if(scanned[i].n_items > 1 ) {
          get_long(&verbosity, scanned[i].list[1]);
        } else {
          verbosity=1;
        }
        break;
      case ISRING:
        if(scanned[i].n_items > 1 ) {
          get_long(&isRing, scanned[i].list[1]);
        } else {
          isRing=1;
        }
        break;
      case CHARGE:
        get_double(&charge, scanned[i].list[1]);
        break;
      case EMITXINPUT:
        /* This is really the emitx+emity, not emitx */
        get_double(&emitxInput, scanned[i].list[1]);
        break;
      case EMITINPUT:
        get_double(&emitxInput, scanned[i].list[1]);
        break;
      case DELTAINPUT:
        get_double(&sigmaDeltaInput, scanned[i].list[1]);
        break;
      case LENGTH:
        get_double(&length, scanned[i].list[1]);
        length /= 1000; /* convert input length from mm to m */
        break;
      case COUPLING:
        get_double(&coupling, scanned[i].list[1]);
        break;
      case EMITYINPUT:
        get_double(&emityInput, scanned[i].list[1]);
        break;
      case FORCECOUPLING:
        get_long(&force, scanned[i].list[1]);
        break;
      case PARTICLES:
        get_double(&particles, scanned[i].list[1]);
        break;
      case SUPERPERIOD:
        get_long(&superperiods, scanned[i].list[1]);
        break;
      case METHOD:
        get_long(&method, scanned[i].list[1]);
        break;
      case GROWTHRATESONLY:
        growthRatesOnly = 1;
        break;
      case SET_TARGET:
        if (scanned[i].n_items!=2 ||
            !get_double(&target, scanned[i].list[1]) ||
            target<0)
          bomb("invalid -target syntax", NULL);
        break;
      case RF:
        if (scanned[i].n_items<2)
          bomb("invalid -rf syntax", NULL);
        scanned[i].n_items--;
        rfVoltage = rfHarmonic = 0;
        if (!scanItemList(&dummyFlags, scanned[i].list+1, &scanned[i].n_items, 0,
                          "voltage", SDDS_DOUBLE, &rfVoltage, 1, 0,
                          "harmonic", SDDS_DOUBLE, &rfHarmonic, 1, 0,
                          NULL) ||
            rfVoltage<=0 || rfHarmonic<=0)
          bomb("invalid -rf syntax/values", "-rf=voltage=MV,harmonic=<value>");
        break;
      case SET_ENERGY:
        if (scanned[i].n_items!=2)
          bomb("invalid -energy syntax", NULL);
        if (!sscanf(scanned[i].list[1], "%lf", &energy) || energy<=0)
          bomb("invalid -energy syntax/values", "-energy=<MeV>");
        break;
      case SET_INTEGRATE:
        if (scanned[i].n_items<2)
          bomb("invalid -integrate syntax", NULL);
        integrationTurns = 0;
        integrationStepSize = 1;
        scanned[i].n_items--;
        if (!scanItemList(&dummyFlags, scanned[i].list+1, &scanned[i].n_items, 0,
                          "turns", SDDS_LONG, &integrationTurns, 1, 0,
                          "stepsize", SDDS_LONG, &integrationStepSize, 1, 0,
                          NULL) ||
            integrationTurns<=0 || integrationStepSize<1) 
          bomb("invalid -integrate syntax", NULL);
        break;
      case NO_WARNING:
        noWarning = 1;
        break;
      default:
        fprintf(stderr, "Unknown option %s given", scanned[i].list[0]);
        exit(1);
        break;
      }
    }
    else {
      if (!inputfile)
        inputfile  =  scanned[i].list[0];
      else if (!outputfile) 
        outputfile =  scanned[i].list[0];
      else
        bomb("too many filenames given", NULL);
    }
  }
  if (charge && particles) {
    bomb("Options charge and particles cannot be both specified.",NULL);
  }
  if (!charge) 
    charge = particles * e_mks;
  if (!particles) {
    /* command line input value is in units of nC */
    charge /= 1e9; 
    particles = charge/ e_mks;
  }
  if ((!coupling && !emityInput) || (coupling && emityInput))
    bomb("Give -coupling or -emityInput (but not both)", NULL);
  if (!length && !rfVoltage) 
    bomb("Specify either the bunch length or the rf voltage.", NULL);

  if (growthRatesOnly && integrationTurns) {
    growthRatesOnly = 0;
    if (!noWarning)
      fprintf( stdout, "*Warning* -growthRatesOnly option is incompatiable with -integrate option. The -growthRatesOnly will be disabled.\n");
  }
  
  if (!growthRatesOnly && !integrationTurns && !noWarning)  
    fprintf( stdout, "*Warning* The growth rate contribution columns in the results file will be those calculated from the equilibrium (or final) condition.\n");
  if (integrationTurns && !isRing) {
    integrationTurns = 0;
    fprintf( stdout, "*Warning* -isRing=0 is incompatiable with -integrate option. The -integrate will be disabled.\n");
  }
  if (energy && !isRing) {
    energy = 0;
    fprintf( stdout, "*Warning* you can not scale energy for linac beam. Scaling will be disabled.\n");
  }

  /***************************************************\
   * get parameter information from first input file  *
   \***************************************************/
  if (verbosity)
    fprintf( stdout, "Opening \"%s\" for checking presence of parameters.\n", inputfile);
  if (!SDDS_InitializeInput(&twissPage, inputfile))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  /* read first page of input file to get parameters 
     I1 I2 I3 I4 I5.
     Check presence of first radiation integral.
     */
  SDDS_ReadPage(&twissPage);
  /* parameter Type */
  switch(SDDS_CheckParameter(&twissPage, "I1", NULL, SDDS_DOUBLE, verbosity?stdout:NULL)) {
  case SDDS_CHECK_NONEXISTENT:
    if (verbosity)
      fprintf( stdout, "\tParameter I1 not found in input file.\n");
    break;
  case SDDS_CHECK_WRONGTYPE:
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    exitElegant(1);
    break;
  case SDDS_CHECK_OKAY:
    break;
  default:
    fprintf( stdout, "Unexpected result from SDDS_CheckParameter routine while checking parameter Type.\n");
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    exitElegant(1);
    break;
  }
  if (verbosity)
    fprintf( stdout, "Opening \"%s\" for writing...\n", outputfile);
  if (!SDDS_InitializeOutput(&resultsPage, SDDS_BINARY, 1, "Intra-beam scattering rates",
                             "Intra-beam scattering rates", outputfile))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (!SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "I1", NULL) ||
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "I2", NULL) ||
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "I3", NULL) ||
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "I4", NULL) ||             
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "I5", NULL) ||             
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "pCentral", NULL) ||
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "taux", NULL) ||
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "tauy", NULL) ||
      !SDDS_TransferParameterDefinition(&resultsPage, &twissPage, "taudelta", NULL) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  if (0>SDDS_DefineParameter(&resultsPage, "Superperiods", NULL, NULL, "Superperiods", NULL, SDDS_LONG, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "Energy", "E", "MeV", "Total Energy", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "Particles", NULL, NULL, "Particles", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "Charge", NULL, "nC", "Charge", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "PeakCurrent", "I$bp$n", "A", "Peak Current", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "RfVoltage", NULL, "MV", "Rf Voltage", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "xGrowthRateInitial", "g$bIBS,x$n", "1/s", "Initial IBS emittance growth rate in the horizontal plane", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "yGrowthRateInitial", "g$bIBS,y$n", "1/s", "Initial IBS emittance growth rate in the vertical plane", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "zGrowthRateInitial", "g$bIBS,z$n", "1/s", "Initial IBS emittance growth rate in the longitudinal plane", NULL, SDDS_DOUBLE, NULL))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  if (0>SDDS_DefineParameter(&resultsPage, "Convergence", NULL, NULL, "Convergence state of emittance calculations", NULL, SDDS_STRING, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "emitx0", "$ge$r$bx,0$n", "$gp$rm", "Equilibrium horizontal emittance with no coupling and no IBS", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "emitxInput", "$ge$r$bx,Input$n", "$gp$rm", "Initial horizontal emittance with coupling", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "emityInput", "$ge$r$by,Input$n", "$gp$rm", "Initial vertical emittance with coupling", NULL, SDDS_DOUBLE, NULL))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  /* requested equilibrium emittances or integrate emittances turn-by-turn*/
  if (!growthRatesOnly) {
    if (0>SDDS_DefineParameter(&resultsPage, "xGrowthRate", "g$bIBS,x$n", "1/s", "IBS emittance growth rate in the horizontal plane", NULL, SDDS_DOUBLE, NULL) ||
        0>SDDS_DefineParameter(&resultsPage, "yGrowthRate", "g$bIBS,y$n", "1/s", "IBS emittance growth rate in the vertical plane", NULL, SDDS_DOUBLE, NULL) ||
        0>SDDS_DefineParameter(&resultsPage, "zGrowthRate", "g$bIBS,z$n", "1/s", "IBS emittance growth rate in the longitudinal plane", NULL, SDDS_DOUBLE, NULL) ||
0>SDDS_DefineParameter(&resultsPage, "emitx", "$ge$r$bx$n", "$gp$rm", "Horizontal emittance with coupling and with IBS", NULL, SDDS_DOUBLE, NULL) ||
        0>SDDS_DefineParameter(&resultsPage, "emity", "$ge$r$by$n", "$gp$rm", "Vertical emittance with coupling and with IBS", NULL, SDDS_DOUBLE, NULL) ||
        0>SDDS_DefineParameter(&resultsPage, "sigmaDelta", "$gs$r$bd$n", NULL, "Relative momentum spread with IBS", NULL, SDDS_DOUBLE, NULL) || 
        0>SDDS_DefineParameter(&resultsPage, "sigmaz", "$gs$r$bz$n", "m", "Bunch length with IBS", NULL, SDDS_DOUBLE, NULL))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  
  if (0>SDDS_DefineParameter(&resultsPage, "sigmaDelta0", "$gs$r$bd,0$n", NULL, "Equilibrium relative momentum spread without IBS", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "sigmaDeltaInput", "$gs$r$bd,0$n", NULL, "Initial relative momentum spread", NULL, SDDS_DOUBLE, NULL) ||
      0>SDDS_DefineParameter(&resultsPage, "sigmaz0", "$gs$r$bz,0$n", "m", "Bunch length without IBS", NULL, SDDS_DOUBLE, NULL))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  if (verbosity)
    fprintf( stdout, "Opening for reading \"%s\"\n", inputfile);
  if (!SDDS_InitializeInput(&twissPage, inputfile))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  if (integrationTurns) {
    if (SDDS_DefineColumn(&resultsPage, "ex", "$ge$r$bx$n", "$gp$rm", "Horizontal Emittance", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "ey", "$ge$r$by$n", "$gp$rm", "Vertical Emittance", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "el", "$ge$r$bl$n", "s", "Longitudinal Emittance", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "Sdelta", "$gs$bd$n$r", "", "Fractional RMS Energy Spread", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "Sz", "$gs$r$bz$n", "m", "RMS Bunch Length", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "IBSRatex", NULL, "1/s", "Horizontal IBS Emittance Growth Rate", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "IBSRatey", NULL, "1/s", "Vertical IBS Emittance Growth Rate", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "IBSRatel", NULL, "1/s", "Longitudinal IBS Emittance Growth Rate", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "Pass", NULL, NULL, NULL, NULL, SDDS_LONG, 0)<0)
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    integrationPoints = integrationTurns/integrationStepSize+1;
    if (!(exInteg = SDDS_Malloc(sizeof(*exInteg)*integrationPoints)) ||
        !(eyInteg = SDDS_Malloc(sizeof(*eyInteg)*integrationPoints)) ||
        !(elInteg = SDDS_Malloc(sizeof(*elInteg)*integrationPoints)) ||
        !(SdeltaInteg = SDDS_Malloc(sizeof(*SdeltaInteg)*integrationPoints)) ||
        !(SzInteg = SDDS_Malloc(sizeof(*SzInteg)*integrationPoints)) ||
        !(xRateInteg = SDDS_Malloc(sizeof(*xRateInteg)*integrationPoints)) ||
        !(yRateInteg = SDDS_Malloc(sizeof(*yRateInteg)*integrationPoints)) ||
        !(zRateInteg = SDDS_Malloc(sizeof(*zRateInteg)*integrationPoints)) ||
        !(passInteg = SDDS_Malloc(sizeof(*passInteg)*integrationPoints)))
      bomb("memory allocation failure (integration arrays)", NULL);
  } else {
    if (SDDS_DefineColumn(&resultsPage, "s", NULL, "m", "Position", NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "dIBSRatex", NULL, "1/s", "Local Horizontal IBS Emittance Growth Rate",  NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "dIBSRatey", NULL, "1/s", "Local Vertical IBS Emittance Growth Rate",  NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&resultsPage, "dIBSRatel", NULL, "1/s", "Local Longitudinal IBS Emittance Growth Rate",  NULL, SDDS_DOUBLE, 0)<0)
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }

  if (!SDDS_WriteLayout(&resultsPage) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  while(SDDS_ReadPage(&twissPage)>0) {
    if (!SDDS_GetParameters(&twissPage,
                            "pCentral", &pCentral0,
                            "I1", &I1,
                            "I2", &I2,
                            "I3", &I3,
                            "I4", &I4,
                            "I5", &I5,
                            "taux", &taux,
			    "tauy", &tauy,
                            "taudelta", &taudelta,
                            "alphac", &alphac,
                            "U0", &U0,
                            NULL) )
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    EMeV = sqrt(sqr(pCentral0) + 1) * me_mev;
    elements = SDDS_CountRowsOfInterest(&twissPage);
    s = SDDS_GetColumnInDoubles(&twissPage, "s");
    pCentral = SDDS_GetColumnInDoubles(&twissPage, "pCentral0");
    circumference = s[elements-1]*superperiods;
    U0 *= superperiods;
    if (energy!=0) {
      /* scale to new energy */
      pCentral0 = sqrt(sqr(energy/me_mev)-1);
      taux /= ipow(energy/EMeV, 3);
      tauy /= ipow(energy/EMeV, 3);
      taudelta /= ipow(energy/EMeV, 3);
      U0 *= ipow(energy/EMeV, 4);
      for (i=0; i<elements; i++) pCentral[i] = pCentral0;
      EMeV = energy;
    }
    
    if (!length && U0>rfVoltage)
      bomb("energy loss per turn is greater than rf voltage", NULL);
    betax = SDDS_GetColumnInDoubles(&twissPage, "betax");
    betay = SDDS_GetColumnInDoubles(&twissPage, "betay");
    alphax = SDDS_GetColumnInDoubles(&twissPage, "alphax");
    alphay = SDDS_GetColumnInDoubles(&twissPage, "alphay");
    etax = SDDS_GetColumnInDoubles(&twissPage, "etax");
    etaxp = SDDS_GetColumnInDoubles(&twissPage, "etaxp");
    etay = SDDS_GetColumnInDoubles(&twissPage, "etay");
    etayp = SDDS_GetColumnInDoubles(&twissPage, "etayp");

    /* emitx0 and sigmaDelta0 are unperturbed quantities 
       (i.e. no coupling and no IBS) that
       zibs requires to internally calculate the quantum excitation.
       (zibs doesn't use the radiation integrals but should!) 
       */
    emitx0 = 55.0/ (32.*sqrt(3.)) * hbar_mks * sqr(pCentral0)/ (me_mks * c_mks)
      * I5 / (I2 - I4);
    sigmaDelta0 = sqrt(55.0/ (32.*sqrt(3.)) * hbar_mks * sqr(pCentral0)/ (me_mks * c_mks)
      * I3 / (2 * I2 + I4));
    /* use unperturbed quantities in no input supplied. */
    if (!sigmaDeltaInput)
      sigmaDeltaInput = sigmaDelta0;
    if (!emitxInput)
      emitxInput = emitx0/ ( 1 + coupling);
    else 
      /* The emitxInput value is really emit=emitx+emity */
      emitxInput = emitxInput/ ( 1 + coupling);
    if (!emityInput)
      emityInput = emitxInput * coupling;
    else
      coupling = emityInput/emityInput;
    sigmaDelta = sigmaDeltaInput;
    if (length)
      sigmaz0 = length;
    else {
      /* compute length in m from rf voltage, energy spread, etc */
      sigmaz0 = 
        circumference*sigmaDelta*
          sqrt(alphac*EMeV/(PIx2*rfHarmonic*sqrt(sqr(rfVoltage)-sqr(U0))));
    }
    sigmaz = sigmaz0;
    emity = emityInput;
    emitx = emitxInput;

    if (integrationPoints) {
      IBSIntegrate(exInteg, eyInteg, elInteg, passInteg,
                   SdeltaInteg, SzInteg,
                   xRateInteg, yRateInteg, zRateInteg,
                   integrationTurns, integrationStepSize, 
                   pCentral0, emitx, emity, sigmaDelta, sigmaz, particles,
                   emitx0, sigmaDelta0, 2./taux, 2./tauy, 2./taudelta, coupling,
                   s, pCentral, betax, alphax, betay, alphay, etax, etaxp, etay, etayp, elements,
                   superperiods, verbosity, isRing, force);
    } else {
      if (!(xRateVsS = SDDS_Realloc(xRateVsS, sizeof(*xRateVsS)*elements)) ||
          !(yRateVsS = SDDS_Realloc(yRateVsS, sizeof(*yRateVsS)*elements)) ||
          !(zRateVsS = SDDS_Realloc(zRateVsS, sizeof(*zRateVsS)*elements)) )
        bomb("memory allocation failure", NULL);
    }

    /* This call is to get the initial growth rates for writing to results file.
       This applies for any running option selected in the commandline */
    IBSRate(particles, elements, superperiods, verbosity, isRing,
             emitx, emity, sigmaDelta, sigmaz, 
             s, pCentral, betax, alphax, betay, alphay, etax, etaxp, etay, etayp,
             NULL, NULL, NULL, 
            &xGrowthRateInitial, &yGrowthRateInitial, &zGrowthRateInitial, 0);

    /* iterating for equilibrium emittances and final growth rates */
    if (!integrationTurns && !growthRatesOnly && isRing) {
      if (verbosity > 1) {
        fprintf (stdout, "Starting values:\nemitx: %10.5g sigmaDelta %10.5g.\n", emitx, sigmaDelta);
      }
      emitxOld = emitx;
      sigmaDeltaOld = sigmaDelta;
      xGuess = (double*) malloc(sizeof(double)*dimensions);
      dxGuess = (double*) malloc(sizeof(double)*dimensions);
      xLowerLimit = (double*) malloc(sizeof(double)*dimensions);
      xUpperLimit = (double*) malloc(sizeof(double)*dimensions);
      disable = (short*) malloc(sizeof(short)*dimensions);
      xGuess[0] = MAX(emitx, emitx0/ (1 + coupling));
      xGuess[1] = MAX(sigmaDelta, sigmaDelta0);
      dxGuess[0] = emitx * 0.1;
      dxGuess[1] = sigmaDelta * 0.1;
      xLowerLimit[0] = emitx0/ (1 + coupling);
      xLowerLimit[1] = sigmaDelta0;
      xUpperLimit[0] = emitx0/ (1 + coupling) * 200;
      xUpperLimit[1] = MIN(sigmaDelta0 * 100, 1.0);
      /* assign other variables to array which are not supoosed
         to be varied by simplex minimization
         */
      xGuess[2] = pCentral0;
      xGuess[3] = emity;
      xGuess[4] = sigmaz0;
      xGuess[5] = particles;
      xGuess[6] = emitx0;
      xGuess[7] = sigmaDelta0;
      xGuess[8] = taux;
      xGuess[9] = tauy;
      xGuess[10] = taudelta;
      xGuess[11] = coupling;
      xGuess[12] = elements;
      xGuess[13] = superperiods;
      xGuess[14] = verbosity;
      xLowerLimit[2] = pCentral0;
      xLowerLimit[3] = emity;
      xLowerLimit[4] = sigmaz0;
      xLowerLimit[5] = particles;
      xLowerLimit[6] = emitx0;
      xLowerLimit[7] = sigmaDelta0;
      xLowerLimit[8] = taux;
      xLowerLimit[9] = tauy;
      xLowerLimit[10] = taudelta;
      xLowerLimit[11] = coupling;
      xLowerLimit[12] = elements;
      xLowerLimit[13] = superperiods;
      xLowerLimit[14] = verbosity;
      xUpperLimit[2] = pCentral0;
      xUpperLimit[3] = emity;
      xUpperLimit[4] = sigmaz0;
      xUpperLimit[5] = particles;
      xUpperLimit[6] = emitx0;
      xUpperLimit[7] = sigmaDelta0;
      xUpperLimit[8] = taux;
      xUpperLimit[9] = tauy;
      xUpperLimit[10] = taudelta;
      xUpperLimit[11] = coupling;
      xUpperLimit[12] = elements;
      xUpperLimit[13] = superperiods;
      xUpperLimit[14] = verbosity;
      disable[0] = 0;
      disable[1] = 0;
      for (i=2 ; i<dimensions ; i++) {
        dxGuess[i] = 0.0;
        disable[i] = 1;
      }
      if (verbosity) {
        fprintf( stdout, "Doing simplex minimization...\n");
      }
      simplexMin( &yReturn, xGuess, dxGuess, xLowerLimit, xUpperLimit, disable, dimensions,
                 target, target/100.0, IBSequations, verbosity?IBSsimplexReport:NULL, 
                 maxEvaluations, maxPasses, 12, 3.0, 1.0, 0);
      /* final answers */
      emitx = xGuess[0];
      sigmaDelta = xGuess[1];
      emity = emitx * coupling;
      sigmaz = sigmaz0 * (sigmaDelta/ sigmaDelta0);
    }

    /* calculate growth rates contributions at equilibrium or
     just one time (-growthRateOnly option) */
     if (!integrationPoints) {
       IBSRate(particles, elements, superperiods, verbosity, isRing, 
                emitx, emity, sigmaDelta, sigmaz, 
                s, pCentral, betax, alphax, betay, alphay, etax, etaxp, etay, etayp,
                xRateVsS, yRateVsS, zRateVsS, 
               &xGrowthRate, &yGrowthRate, &zGrowthRate, 0);
     } else {
       /* final growth rates and emittances after integration */
       xGrowthRate = xRateInteg[integrationPoints - 1] ;
       yGrowthRate = yRateInteg[integrationPoints - 1] ;
       zGrowthRate = zRateInteg[integrationPoints - 1] ;
       emitx = exInteg[integrationPoints - 1] ;
       emity = eyInteg[integrationPoints - 1] ;
       sigmaDelta = SdeltaInteg[integrationPoints - 1] ;
       sigmaz = SzInteg[integrationPoints - 1] ;
     }
    
    
    
    converged = 1;

    if (0>SDDS_StartPage(&resultsPage, integrationPoints?integrationPoints:elements) ||
        !SDDS_SetParameters(&resultsPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                            "Convergence", converged?"Emittance converged":"Emittance did not converge",
                            "pCentral", pCentral0, "RfVoltage", rfVoltage,
                            "I1", I1,
                            "I2", I2,
                            "I3", I3,
                            "I4", I4,
                            "I5", I5,
                            "taux", taux,
                            "tauy", tauy,
                            "taudelta", taudelta,
                            "Energy", EMeV,
                            "Particles", particles,
                            "Charge", (1e9 * charge),
                            "PeakCurrent", (charge*c_mks/(sqrt(2*PI)*sigmaz)),
                            "Superperiods", superperiods,
                            "emitx0", emitx0,
                            "emitxInput", emitxInput,
                            "emityInput", emityInput,
                            "xGrowthRateInitial", xGrowthRateInitial,
                            "yGrowthRateInitial", yGrowthRateInitial,
                            "zGrowthRateInitial", zGrowthRateInitial,
                            "sigmaDeltaInput", sigmaDeltaInput,
                            "sigmaDelta0", sigmaDelta0,
                            "sigmaz0", sigmaz0, NULL) ||
        (!growthRatesOnly && 
         !SDDS_SetParameters(&resultsPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                             "xGrowthRate", xGrowthRate,
                             "yGrowthRate", yGrowthRate,
                             "zGrowthRate", zGrowthRate,
                             "emitx", emitx,
                             "emity", emity,
                             "sigmaDelta", sigmaDelta,
                             "sigmaz", sigmaz, NULL)) ||
         (integrationPoints && 
          (!SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, exInteg, integrationPoints, "ex") ||
           !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, eyInteg, integrationPoints, "ey") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, elInteg, integrationPoints, "el") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, SdeltaInteg, integrationPoints, "Sdelta") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, SzInteg, integrationPoints, "Sz") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, xRateInteg, integrationPoints, "IBSRatex") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, yRateInteg, integrationPoints, "IBSRatey") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, zRateInteg, integrationPoints, "IBSRatel") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, passInteg, integrationPoints, "Pass"))) ||
        (!integrationPoints && 
         (!SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, s, elements, "s") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, xRateVsS, elements, "dIBSRatex") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, yRateVsS, elements, "dIBSRatey") ||
          !SDDS_SetColumn(&resultsPage, SDDS_SET_BY_NAME, zRateVsS, elements, "dIBSRatel"))) ||
        !SDDS_WritePage(&resultsPage))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  if (!SDDS_Terminate(&twissPage) || !SDDS_Terminate(&resultsPage))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  return(0);
}
예제 #12
0
파일: sddsendian.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
  SDDS_DATASET SDDSin, SDDSout;
  long i_arg, tmpfileUsed;
  SCANNED_ARG *s_arg;
  char *input, *output, *description_text, *description_contents;
  unsigned long pipeFlags;
  long pageNumber, nonNative = 0;
  char *outputEndianess = NULL;
  char buffer[40];
  
  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&s_arg, argc, argv);
  if (argc<2) 
    bomb(NULL, USAGE);

  input = output = description_text = description_contents = NULL;
  pipeFlags = 0;
  for (i_arg=1; i_arg<argc; i_arg++) {
    if (s_arg[i_arg].arg_type==OPTION) {
      delete_chars(s_arg[i_arg].list[0], "_");
      switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
      case SET_PIPE:
        if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      case NONNATIVE:
	nonNative = 1;
        break;
      default:
        fprintf(stderr, "Error (%s): unknown switch: %s\n", argv[0], s_arg[i_arg].list[0]);
        exit(1);
        break;
      }
    }
    else {
      if (input==NULL)
        input = s_arg[i_arg].list[0];
      else if (output==NULL)
        output = s_arg[i_arg].list[0];
      else
        SDDS_Bomb("too many filenames");
    }
  }

  processFilenames("sddsendian", &input, &output, pipeFlags, 0, &tmpfileUsed);

  outputEndianess = getenv("SDDS_OUTPUT_ENDIANESS");

  if (outputEndianess) {
    putenv("SDDS_OUTPUT_ENDIANESS=");
  }

  if (!SDDS_InitializeInput(&SDDSin, input)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  if (!description_text)
    SDDS_GetDescription(&SDDSin, &description_text, &description_contents);
  if (!SDDS_InitializeCopy(&SDDSout, &SDDSin, output, "w") || 
      !SDDS_SetDataMode(&SDDSout, nonNative?SDDS_BINARY:-SDDS_BINARY) ||
      !SDDS_WriteLayout(&SDDSout)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  
  if (nonNative) {
    while ((pageNumber=SDDS_ReadNonNativePage(&SDDSin))>=0) {
      if (!SDDS_CopyPage(&SDDSout, &SDDSin) ||
          !SDDS_WritePage(&SDDSout)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
      }
    }
  } else {
    while ((pageNumber=SDDS_ReadPage(&SDDSin))>=0) {
      if (!SDDS_CopyPage(&SDDSout, &SDDSin) ||
          !SDDS_WriteNonNativeBinaryPage(&SDDSout)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
      }
    }
  }

  if (!SDDS_Terminate(&SDDSin) || !SDDS_Terminate(&SDDSout)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  
  if (tmpfileUsed && !replaceFileAndBackUp(input, output))
    exit(1);

  if (outputEndianess) {
    sprintf(buffer, "SDDS_OUTPUT_ENDIANESS=%s", outputEndianess);
    putenv(buffer);
  }

  return(0);
}
예제 #13
0
파일: sddsselect.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
    SDDS_DATASET SDDS_1, SDDS_2, SDDS_output;
    long i, j, i_arg, rows1, rows2, reuse, reusePage, i1, i2;
    SCANNED_ARG *s_arg;
    char s[200], *ptr;
    char **match_column, **equate_column;
    long match_columns, equate_columns;
    char *input1, *input2, *output;
    long tmpfile_used, retval1, retval2;
    long warnings, invert;
    unsigned long pipeFlags;
    KEYED_EQUIVALENT **keyGroup=NULL;
    long keyGroups=0;
    
    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&s_arg, argc, argv);
    if (argc<3) 
        bomb(NULL, USAGE);

    input1 = input2 = output = NULL;
    match_column  = equate_column  = NULL;
    match_columns = equate_columns = reuse = reusePage = 0;
    tmpfile_used = invert = 0;
    warnings = 1;
    pipeFlags = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            delete_chars(s_arg[i_arg].list[0], "_");
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_MATCH_COLUMN:
                if (s_arg[i_arg].n_items!=2)
                    SDDS_Bomb("invalid -match syntax");
                if (match_columns!=0)
                    SDDS_Bomb("only one -match option may be given");
		match_column = tmalloc(sizeof(*match_column)*2);
                if ((ptr=strchr(s_arg[i_arg].list[1], '=')))
                    *ptr++ = 0;
                else 
                    ptr = s_arg[i_arg].list[1];
                match_column[0] = s_arg[i_arg].list[1];
                match_column[1] = ptr;
		match_columns = 1;
                break;
              case SET_EQUATE_COLUMN:
                if (s_arg[i_arg].n_items!=2)
                    SDDS_Bomb("invalid -equate syntax");
                if (equate_columns!=0)
                    SDDS_Bomb("only one -equate option may be given");
		equate_column = tmalloc(sizeof(*equate_column)*2);
                if ((ptr=strchr(s_arg[i_arg].list[1], '=')))
                    *ptr++ = 0;
                else 
                    ptr = s_arg[i_arg].list[1];
                equate_column[0] = s_arg[i_arg].list[1];
                equate_column[1] = ptr;
		equate_columns = 1;
                break;
              case SET_REUSE:
                if (s_arg[i_arg].n_items==1)
                    reuse = 1;
                else {
                    char *reuseOptions[2] = {"rows", "page"};
                    for (i=1; i<s_arg[i_arg].n_items; i++) {
                        switch (match_string(s_arg[i_arg].list[i], reuseOptions, 2, 0)) {
                          case 0:
                            reuse = 1;
                            break;
                          case 1:
                            reusePage = 1;
                            break;
                          default:
                            SDDS_Bomb("unknown reuse keyword");
                            break;
                            }
                        }
                    }
                break;
              case SET_INVERT:
                invert = 1;
                break;
              case SET_NOWARNINGS:
                warnings = 0;
                break;
              case SET_PIPE:
                if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
                    SDDS_Bomb("invalid -pipe syntax");
                break;
              default:
                fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]);
                SDDS_Bomb(NULL);
                break;
                }
            }
        else {
            if (input1==NULL)
                input1 = s_arg[i_arg].list[0];
            else if (input2==NULL)
                input2 = s_arg[i_arg].list[0];
            else if (output==NULL)
                output = s_arg[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }

    if (pipeFlags&USE_STDIN && input1) {
        if (output)
            SDDS_Bomb("too many filenames (sddsxref)");
        output = input2;
        input2 = input1;
        input1 = NULL;
        }
    processFilenames("sddsselect", &input1, &output, pipeFlags, !warnings, &tmpfile_used);
    if (!input2)
        SDDS_Bomb("second input file not specified (sddsxref)");

    if (equate_columns && match_columns)
        SDDS_Bomb("only one of -equate or -match may be given");
    if (!equate_columns && !match_columns)
        SDDS_Bomb("one of -equate or -match must be given");

    if (!SDDS_InitializeInput(&SDDS_1, input1)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
        }
    if (!SDDS_InitializeInput(&SDDS_2, input2)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
        }

    if (match_columns) {
        if ((j=SDDS_GetColumnIndex(&SDDS_1, match_column[0]))<0 || SDDS_GetColumnType(&SDDS_1, j)!=SDDS_STRING) {
            sprintf(s, "error: column %s not found or not string type in file %s", match_column[0], input1?input1:"stdin");
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if ((j=SDDS_GetColumnIndex(&SDDS_2, match_column[1]))<0 || SDDS_GetColumnType(&SDDS_2, j)!=SDDS_STRING) {
            sprintf(s, "error: column %s not found or not string type in file %s", match_column[1], input2);
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }
    if (equate_columns) {
        if ((j=SDDS_GetColumnIndex(&SDDS_1, equate_column[0]))<0 || !SDDS_NUMERIC_TYPE(SDDS_GetColumnType(&SDDS_1, j))) {
            sprintf(s, "error: column %s not found or not numeric type in file %s", equate_column[0], input1?input1:"stdin");
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if ((j=SDDS_GetColumnIndex(&SDDS_2, equate_column[1]))<0 || !SDDS_NUMERIC_TYPE(SDDS_GetColumnType(&SDDS_2, j))) {
            sprintf(s, "error: column %s not found or not numeric type in file %s", equate_column[1], input2);
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }

    if (output && pipeFlags&USE_STDOUT)
        SDDS_Bomb("too many filenames with -pipe option");
    if (!output && !(pipeFlags&USE_STDOUT)) {
        if (warnings)
            fprintf(stderr, "warning: existing file %s will be replaced (sddsselect)\n", input1?input1:"stdin");
        tmpfile_used = 1;
        cp_str(&output, tmpname(NULL));
        }
    if (!SDDS_InitializeCopy(&SDDS_output, &SDDS_1, output, "w")) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
        }

    if (!SDDS_WriteLayout(&SDDS_output)) 
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
   
    while ((retval1=SDDS_ReadPage(&SDDS_1))>0) {
        if (!reusePage) {
            if ((retval2=SDDS_ReadPage(&SDDS_2))<=0) {
                if (warnings)
                    fprintf(stderr, "warning: <input2> ends before <input1>\n");
                if (invert) {
                    /* nothing to match, so everything would normally be thrown out */
                    if (!SDDS_CopyPage(&SDDS_output, &SDDS_1) || !SDDS_WritePage(&SDDS_output))
                        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    continue;
                    }
                else 
                    /* nothing to match, so everything thrown out */
                    break;
                }
            }
        else {
            if (retval1==1 && (retval2=SDDS_ReadPage(&SDDS_2))<=0)
                SDDS_Bomb("<input2> has no data");
            SDDS_SetRowFlags(&SDDS_2, 1);
            }
        rows1 = SDDS_CountRowsOfInterest(&SDDS_1);
        rows2 = SDDS_CountRowsOfInterest(&SDDS_2);
        
        if (!SDDS_StartPage(&SDDS_output, rows1)) {
            SDDS_SetError("Problem starting output page");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!SDDS_CopyParameters(&SDDS_output, &SDDS_2) || !SDDS_CopyArrays(&SDDS_output, &SDDS_2)) {
            SDDS_SetError("Problem copying parameter or array data from second input file");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!SDDS_CopyParameters(&SDDS_output, &SDDS_1) || !SDDS_CopyArrays(&SDDS_output, &SDDS_1)) {
            SDDS_SetError("Problem copying parameter or array data from first input file");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (match_columns) {
          char **string1, **string2;
          long matched;
          string2 = NULL;
          if (!(string1 = SDDS_GetColumn(&SDDS_1, match_column[0]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    match_column[0], input1?input1:"stdin");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2 && !(string2 = SDDS_GetColumn(&SDDS_2, match_column[1]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    match_column[1], input2);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2)
            keyGroup = MakeSortedKeyGroups(&keyGroups, SDDS_STRING, string2, rows2);
          for (i1=0; i1<rows1; i1++) {
            if (!SDDS_CopyRowDirect(&SDDS_output, i1, &SDDS_1, i1)) {
              sprintf(s, "Problem copying row %ld of first data set", i1);
              SDDS_SetError(s);
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            matched = 0;
            if (rows2 &&(i2 = FindMatchingKeyGroup(keyGroup, keyGroups, SDDS_STRING, string1+i1, reuse))>=0) {
              matched = 1;
            }
            if ((!matched && !invert) || (matched && invert)) {
              if (!SDDS_AssertRowFlags(&SDDS_output, SDDS_INDEX_LIMITS, i1, i1, 0)) 
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (string1) {
            for (i=0;i<rows1;i++) 
              free(string1[i]);
            free(string1);
            string1 = NULL;
          }
          if (string2) {
            for (i=0;i<rows2;i++) 
              free(string2[i]);
            free(string2);
            string2 = NULL;
          }
          for (i=0;i<keyGroups;i++) {
	    if (keyGroup[i]) {
	      if (keyGroup[i]->equivalent)
		free(keyGroup[i]->equivalent);
	      free(keyGroup[i]);
	      keyGroup[i] = NULL;
	    }
          }
          if (keyGroups) {
            free(keyGroup);
	    keyGroup = NULL;
	    keyGroups = 0;
	  }
        }
        else if (equate_columns) {
          double *value1, *value2;
          long equated;
          value2 = NULL;
          if (!(value1 = SDDS_GetColumnInDoubles(&SDDS_1, equate_column[0]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    equate_column[0], input1?input1:"stdin");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2 && !(value2 = SDDS_GetColumnInDoubles(&SDDS_2, equate_column[1]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    equate_column[1], input2);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2)
            keyGroup = MakeSortedKeyGroups(&keyGroups, SDDS_DOUBLE, value2, rows2);
          for (i1=0; i1<rows1; i1++) {
            if (!SDDS_CopyRowDirect(&SDDS_output, i1, &SDDS_1, i1)) {
              sprintf(s, "Problem copying row %ld of first data set", i1);
              SDDS_SetError(s);
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            equated = 0;
            if (rows2 && (i2 = FindMatchingKeyGroup(keyGroup, keyGroups, SDDS_DOUBLE, value1+i1, reuse))>=0) {
              equated = 1;
            }
            if ((!equated && !invert) || (equated && invert)) {
              if (!SDDS_AssertRowFlags(&SDDS_output, SDDS_INDEX_LIMITS, i1, i1, 0)) 
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (value1)
            free(value1);
          value1 = NULL;
          if (rows2 && value2)
            free(value2);
          value2 = NULL;
          for (i=0;i<keyGroups;i++) {
	    if (keyGroup[i]) {
	      if (keyGroup[i]->equivalent)
		free(keyGroup[i]->equivalent);
	      free(keyGroup[i]);
	      keyGroup[i] = NULL;
	    }
          }
          if (keyGroups) {
            free(keyGroup);
	    keyGroup = NULL;
	    keyGroups = 0;
	  }
        }
        if (!SDDS_WritePage(&SDDS_output)) {
          SDDS_SetError("Problem writing data to output file");
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }

    if (!SDDS_Terminate(&SDDS_1) || !SDDS_Terminate(&SDDS_2) || !SDDS_Terminate(&SDDS_output)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
    if (tmpfile_used && !replaceFileAndBackUp(input1, output))
        exit(1);
    free_scanargs(&s_arg,argc);
    if (match_columns) 
      free(match_column);
    return(0);
}
예제 #14
0
파일: sddscongen.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
    double x_lo, x_hi, y_lo, y_hi, dx, dy, x, y;
    double **z_data, z_min, z_max, z_val;
    long ix, iy, nx, ny;
    long x_rpn_var, y_rpn_var;
    char *z_equation = NULL;
    char *rpn_defns_file;
    char *rpn_init_command;
    char *z_udf = "Z.UDF";
    char *input, *output, *label[4];
    long i_arg;
    SCANNED_ARG *s_arg;
    FILE *fp;
    unsigned long pipeFlags;
    char pfix[IFPF_BUF_SIZE], *ptr;
    char * rpn_defns;
#if defined(LINUX)
    struct stat sts;
#endif

    if (argc<2 || argc>(2+N_OPTIONS)) 
        bomb(NULL, USAGE);

    output = NULL;
    nx = ny = 0;
    rpn_defns_file = NULL;
    rpn_init_command = NULL;
    pipeFlags = 0;

    for (ix=0; ix<4; ix++)
        label[ix] = " ";
    scanargs(&s_arg, argc, argv);
    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            delete_chars(s_arg[i_arg].list[0], "_");
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
                case SET_RPN_DEFNS_FILE:
                    if (s_arg[i_arg].n_items!=2 ||
                            !(rpn_defns_file=s_arg[i_arg].list[1]))
                        bomb("incorrect -rpndefnsfile syntax", NULL);
                    break;
                case SET_RPN_INIT_COMMAND:
		  /*
                    if (s_arg[i_arg].n_items!=2 ||
                            !(rpn_init_command = s_arg[i_arg].list[1]))
                        bomb("incorrect -rpncommand syntax", NULL);
		  */
		  if ((s_arg[i_arg].n_items<2) || (s_arg[i_arg].n_items>3))
		    SDDS_Bomb("incorrect -rpncommand syntax");
		  if (s_arg[i_arg].n_items==2) {
		    if (!strlen(rpn_init_command=s_arg[i_arg].list[1])) {
		      SDDS_Bomb("incorrect -rpncommand syntax");
		    }
		  } else if (s_arg[i_arg].n_items==3) {
		    if (strncmp(s_arg[i_arg].list[2], "algebraic", strlen(s_arg[i_arg].list[2]))==0) {
		      ptr = addOuterParentheses(s_arg[i_arg].list[1]);
		      if2pf(pfix, ptr, sizeof pfix);
		      free(ptr);
		      if (!SDDS_CopyString(&rpn_init_command, pfix)) {
			fprintf(stderr, "error: problem copying argument string\n");
			return(1);
		      }
		    } else {
		      SDDS_Bomb("incorrect -rpncommand syntax");
		    }
		  }
		  break;
                case SET_Z_EQUATION:
		  /*
                    if (s_arg[i_arg].n_items!=2 ||
			!(z_equation=s_arg[i_arg].list[1]))
                        bomb("incorrect -zequation syntax", NULL);
		  */
		  if ((s_arg[i_arg].n_items<2) || (s_arg[i_arg].n_items>3))
		    SDDS_Bomb("incorrect -zequation syntax");
		  if (s_arg[i_arg].n_items==2) {
		    if (!strlen(z_equation=s_arg[i_arg].list[1])) {
		      SDDS_Bomb("incorrect -zequation syntax");
		    }
		  } else if (s_arg[i_arg].n_items==3) {
		    if (strncmp(s_arg[i_arg].list[2], "algebraic", strlen(s_arg[i_arg].list[2]))==0) {
		      if2pf(pfix, s_arg[i_arg].list[1], sizeof pfix);
		      if (!SDDS_CopyString(&z_equation, pfix)) {
			fprintf(stderr, "error: problem copying argument string\n");
			return(1);
		      }
		    } else {
		      SDDS_Bomb("incorrect -zequation syntax");
		    }
		  }
		  break;
                case SET_X_RANGE:
                    if (s_arg[i_arg].n_items!=4 ||
                            1!=sscanf(s_arg[i_arg].list[1], "%le", &x_lo) ||
                            1!=sscanf(s_arg[i_arg].list[2], "%le", &x_hi) ||
                            x_lo>=x_hi || 
                            1!=sscanf(s_arg[i_arg].list[3], "%ld", &nx) ||
                            nx<=1) 
                        bomb("incorrect -xrange syntax", NULL);
                    break;
                case SET_Y_RANGE:
                    if (s_arg[i_arg].n_items!=4 ||
                            1!=sscanf(s_arg[i_arg].list[1], "%le", &y_lo) ||
                            1!=sscanf(s_arg[i_arg].list[2], "%le", &y_hi) ||
                            y_lo>=y_hi || 
                            1!=sscanf(s_arg[i_arg].list[3], "%ld", &ny) ||
                            ny<=1) 
                        bomb("incorrect -yrange syntax", NULL);
                    break;
                  case SET_PIPE:
                    if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
                        bomb("invalid -pipe syntax", NULL);
                    break;
                  default:
                    fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]);
                    bomb(NULL, NULL);
                    break;
                }
            }
        else {
            if (output==NULL) 
                output = s_arg[i_arg].list[0];
            else
                bomb("too many filenames (sddscongen)", NULL);
            }
        }

    pipeFlags |= DEFAULT_STDIN;
    input = NULL;
    processFilenames("sddscongen", &input, &output, pipeFlags, 0, NULL);

    if (nx==0)
        bomb("-xrange must be supplied", NULL);    
    if (ny==0)
        bomb("-yrange must be supplied", NULL);    
    
    if (z_equation==NULL)
        bomb("-zequation must be supplied", NULL);

    if(!rpn_defns_file) {
	rpn_defns_file=getenv("RPN_DEFNS");
	/*if failed, check where default setting exists for a linux system, G. Shen, Dec 31, 2009 */
	if(!rpn_defns_file) {
#if defined(LINUX)
	    if (!(stat(rpn_default, &sts) == -1 && errno == ENOENT)) { /* check whether default file exists */
		rpn_defns = rpn_default;
	    }
#endif
	}
    }
    rpn(rpn_defns_file);
    /* rpn(rpn_defns_file?rpn_defns_file:getenv("RPN_DEFNS")); */
    if (rpn_init_command)
        rpn(rpn_init_command);
    x_rpn_var = rpn_create_mem("x", 0);
    y_rpn_var = rpn_create_mem("y", 0);
    create_udf(z_udf, z_equation);

    z_data = (double**)array_2d(sizeof(double), 0, nx-1, 0, ny-1);
    dx = (x_hi-x_lo)/(nx-1);
    dy = (y_hi-y_lo)/(ny-1);
    z_min =  FLT_MAX;
    z_max = -FLT_MAX;
    
    for (ix=0,x=x_lo; ix<nx; ix++,x+=dx) {
        for (iy=0,y=y_lo; iy<ny; iy++,y+=dy) {
            rpn_store(x, NULL, x_rpn_var);
            rpn_store(y, NULL, y_rpn_var);
            if ((z_val = z_data[ix][iy] = rpn(z_udf))>z_max)
                z_max = z_val;
            if (z_val<z_min)
                z_min = z_val;
            rpn_clear();
            }
        }

    if (output)
        fp = fopen_e(output, "w", 0);
    else
        fp = stdout;
    fprintf(fp, "SDDS1\n&parameter name=Variable1Name, type=string, fixed_value=x &end\n");
    fprintf(fp, "&parameter name=Variable2Name, type=string, fixed_value=y &end\n");
    fprintf(fp, "&parameter name=xInterval, type=double, fixed_value=%e &end\n", dx);
    fprintf(fp, "&parameter name=xMinimum, type=double, fixed_value=%e &end\n", x_lo);
    fprintf(fp, "&parameter name=xDimension, type=long, fixed_value=%ld &end\n", nx);
    fprintf(fp, "&parameter name=yInterval, type=double, fixed_value=%e &end\n", dy);
    fprintf(fp, "&parameter name=yMinimum, type=double, fixed_value=%e &end\n", y_lo);
    fprintf(fp, "&parameter name=yDimension, type=long, fixed_value=%ld &end\n", ny);
    fprintf(fp, "&column name=z, type=double, description=\"%s\" &end\n", z_equation);
    fprintf(fp, "&data mode=ascii, no_row_counts=1 &end\n");
    for (ix=0; ix<nx; ix++)
         for (iy=0; iy<ny; iy++)
             fprintf(fp, "%e\n", z_data[ix][iy]);
    return(0);
}
예제 #15
0
int main(int argc, char **argv)
{
    SDDS_DATASET SDDS_orig, SDDS_out;
    int32_t i, j, k, i_arg, rows, xfilter_provided, yfilter_provided, zfilter_provided, row;
    long power=1;
    SCANNED_ARG *s_arg;
    char *inputFile, *outputRoot, output[1024], tmpcol[256];
    double xmin, xmax, ymin, ymax, zmin, zmax, xinterval, yinterval, zinterval;
    int32_t xdim, ydim, zdim, columnNames, outputColumns, page=0;
    char **columnName, **outputColumn;
    double ***Rho, ***Jz, rhoSum, rhoSum1, yRho, zRho, jzRho;
    double x_min, x_max, y_min, y_max, z_min, z_max, x, y, z;
    unsigned long dummyFlags = 0;

    x_min = x_max = y_min = y_max = z_min = z_max = 0;
    xfilter_provided = yfilter_provided = zfilter_provided = 0;

    inputFile = outputRoot = NULL;
    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&s_arg, argc, argv);
    if (argc<2)
        bomb(NULL, USAGE);

    columnNames = outputColumns = 0;
    columnName = outputColumn = NULL;
    Rho = Jz = NULL;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            delete_chars(s_arg[i_arg].list[0], "_");
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_POWER:
                if (s_arg[i_arg].n_items!=2)
                    SDDS_Bomb("Invalid -power syntax.");
                if (!get_long(&power, s_arg[i_arg].list[1]))
                    SDDS_Bomb("Invalid -power value provided.");
                break;
            case SET_XFILTER:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("Invalid -xfilter syntax.");
                s_arg[i_arg].n_items--;
                if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                  "minimum", SDDS_DOUBLE, &x_min, 1, 0,
                                  "maximum", SDDS_DOUBLE, &x_max, 1, 0,
                                  NULL))
                    SDDS_Bomb("Invalid -xfilter syntax");
                s_arg[i_arg].n_items++;
                if (x_max<=x_min) {
                    fprintf(stderr, "Invalid -xfilter provided, x_max <= x_min\n");
                    exit(1);
                }
                xfilter_provided =1;
                break;
            case SET_YFILTER:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("Invalid -yfilter syntax.");
                s_arg[i_arg].n_items--;
                if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                  "minimum", SDDS_DOUBLE, &y_min, 1, 0,
                                  "maximum", SDDS_DOUBLE, &y_max, 1, 0,
                                  NULL))
                    SDDS_Bomb("Invalid -yfilter syntax");
                s_arg[i_arg].n_items++;
                if (y_max<=y_min) {
                    fprintf(stderr, "Invalid -yfilter provided, y_max <= y_min\n");
                    exit(1);
                }
                yfilter_provided =1;
                break;
            case SET_ZFILTER:
                if (s_arg[i_arg].n_items<2)
                    SDDS_Bomb("Invalid -zfilter syntax.");
                s_arg[i_arg].n_items--;
                if (!scanItemList(&dummyFlags, s_arg[i_arg].list+1, &s_arg[i_arg].n_items, 0,
                                  "minimum", SDDS_DOUBLE, &z_min, 1, 0,
                                  "maximum", SDDS_DOUBLE, &z_max, 1, 0,
                                  NULL))
                    SDDS_Bomb("Invalid -zfilter syntax");
                s_arg[i_arg].n_items++;
                if (z_max<=z_min) {
                    fprintf(stderr, "Invalid -yfilter provided, z_max <= z_min\n");
                    exit(1);
                }
                zfilter_provided =1;
                break;
            default:
                fprintf(stderr, "Unknown option - %s provided.\n", s_arg[i_arg].list[0]);
                exit(1);
            }
        } else {
            if (!inputFile)
                inputFile = s_arg[i_arg].list[0];
            else if (!outputRoot)
                outputRoot = s_arg[i_arg].list[0];
            else
                SDDS_Bomb("Too many file names provided.");
        }
    }
    if (!outputRoot)
        outputRoot = inputFile;
    sprintf(output, "%s.ave", outputRoot);

    if (!SDDS_InitializeInput(&SDDS_orig, inputFile)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
    }

    xdim = ydim = zdim = 1;
    zmin = zmax = zinterval = 0;
    while (SDDS_ReadPage(&SDDS_orig)>0) {
        if (page==0) {
            if (!SDDS_GetParameterAsDouble(&SDDS_orig, "origin1", &xmin) || !SDDS_GetParameterAsDouble(&SDDS_orig, "max_ext1", &xmax) ||
                    !SDDS_GetParameterAsDouble(&SDDS_orig, "delta1", &xinterval) || !SDDS_GetParameterAsLong(&SDDS_orig, "numPhysCells1", &xdim) ||
                    !SDDS_GetParameterAsDouble(&SDDS_orig, "origin2", &ymin) || !SDDS_GetParameterAsDouble(&SDDS_orig, "max_ext2", &ymax) ||
                    !SDDS_GetParameterAsDouble(&SDDS_orig, "delta2", &yinterval) || !SDDS_GetParameterAsLong(&SDDS_orig, "numPhysCells2", &ydim)) {
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
                exit(1);
            }
            if (SDDS_CheckParameter(&SDDS_orig, "origin3", NULL, SDDS_ANY_NUMERIC_TYPE, NULL)==SDDS_CHECK_OK) {
                if (!SDDS_GetParameterAsDouble(&SDDS_orig, "origin3", &zmin) ||
                        !SDDS_GetParameterAsDouble(&SDDS_orig, "max_ext3", &zmax) ||
                        !SDDS_GetParameterAsDouble(&SDDS_orig, "delta3", &zinterval) ||
                        !SDDS_GetParameterAsLong(&SDDS_orig, "numPhysCells3", &zdim)) {
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
                    exit(1);
                }
            }
            if (xfilter_provided) {
                if (x_min>xmax || x_max<xmin) {
                    fprintf(stderr, "Invalid xfilter provided, it should be between %le and %le\n", xmin, xmax);
                    if (!SDDS_Terminate(&SDDS_orig))
                        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    exit(1);
                }
            } else {
                x_min = xmin;
                x_max = xmax;
            }
            if (yfilter_provided) {
                if (y_min>ymax || y_max<ymin) {
                    fprintf(stderr, "Invalid yfilter provided, it should be between %le and %le\n", ymin, ymax);
                    if (!SDDS_Terminate(&SDDS_orig))
                        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    exit(1);
                }
            } else {
                y_min = ymin;
                y_max = ymax;
            }
            if (zfilter_provided && zmin!=0 && zmax!=0) {
                if (z_min>zmax || z_max<zmin) {
                    fprintf(stderr, "Invalid zfilter provided, it should be between %le and %le\n", zmin, zmax);
                    if (!SDDS_Terminate(&SDDS_orig))
                        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    exit(1);
                }
            } else {
                z_min = zmin;
                z_max = zmax;
            }
            Rho = malloc(sizeof(*Rho)*zdim);
            Jz = malloc(sizeof(*Rho)*zdim);
            for (i=0; i<zdim; i++) {
                Rho[i] = malloc(sizeof(**Rho)*ydim);
                Jz[i] = malloc(sizeof(**Jz)*ydim);
            }
            SetupOutputFile(&SDDS_out, output, zdim);
        }
        rows = SDDS_CountRowsOfInterest(&SDDS_orig);
        if (rows!=xdim) {
            fprintf(stderr, "Row number does not equal xdim size.\n");
            exit(1);
        }
        for (j=1; j<=ydim; j++) {
            sprintf(tmpcol, "Rho_%d",j);
            Rho[page][j-1] = NULL;
            if (!(Rho[page][j-1]=SDDS_GetColumnInDoubles(&SDDS_orig, tmpcol)))
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            sprintf(tmpcol, "Jz_%d",j);
            Jz[page][j-1] = NULL;
            if (!(Jz[page][j-1]=SDDS_GetColumnInDoubles(&SDDS_orig, tmpcol)))
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
        page ++;
    }
    if (!SDDS_Terminate(&SDDS_orig)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
    }
    if (page!=zdim) {
        free_data_memory(Rho, zdim, ydim);
        free_data_memory(Jz, zdim, ydim);
        fprintf(stderr, "Error, the page number does not equal to zdim size.\n");
        exit(1);
    }

    if (!SDDS_StartPage(&SDDS_out, xdim) ||
            !SDDS_SetParameters(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                "origin1", xmin, "origin2", ymin, "origin3", zmin, "max_ext1", xmax, "max_ext2", ymax,
                                "delta1", xinterval, "delta2", yinterval,   "numPhysCells1", xdim,
                                "numPhysCells2", ydim, "xstart", x_min, "xend", x_max, "ystart", y_min, "yend", y_max, NULL))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (zdim>1) {
        if (!SDDS_SetParameters(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                "origin3", zmin,  "max_ext3", zmax,
                                "delta3", zinterval,   "numPhysCells3", zdim,
                                "zstart", z_min, "zend", z_max, NULL))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    row = 0;
    x = y = z = 0;
    for (i=0; i<xdim; i++) {
        rhoSum = rhoSum1 = 0;
        yRho = zRho = jzRho = 0;
        x = i * xinterval + xmin;
        if (xfilter_provided && (x<x_min || x>x_max))
            continue;
        for (j=0; j<ydim; j++) {
            y = j * yinterval + ymin;
            if (yfilter_provided && (y<y_min || y>y_max))
                continue;
            for (k=0; k<zdim; k++) {
                z = k * zinterval + zmin;
                if (zfilter_provided && zdim>1 && (z<z_min || z>z_max))
                    continue;
                if (power==1) {
                    yRho += fabs(Rho[k][j][i]) * y;
                    zRho += fabs(Rho[k][j][i]) * z;
                    jzRho += Rho[k][j][i] * Jz[k][j][i];
                    rhoSum += fabs(Rho[k][j][i]);
                    rhoSum1 += Rho[k][j][i];
                } else {
                    yRho += pow(fabs(Rho[k][j][i]), power) * y;
                    zRho += pow(fabs(Rho[k][j][i]), power) * z;
                    jzRho += pow(Rho[k][j][i] * Jz[k][j][i], power);
                    rhoSum += pow(fabs(Rho[k][j][i]), power);
                    rhoSum1 += pow(Rho[k][j][i], power);
                }
            }
        }
        /*set row values */
        if (!SDDS_SetRowValues(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, row,
                               "x", x, "YAve", yRho/(rhoSum+1.0e-20), "JzAve", jzRho/(rhoSum1 + 1.0e-20), NULL))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if (zdim>1 && !SDDS_SetRowValues(&SDDS_out, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, row,
                                         "ZAve",zRho/(rhoSum+1.0e-20), NULL))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        row++;
    }
    if (!SDDS_WritePage(&SDDS_out) || !SDDS_Terminate(&SDDS_out))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

    free_data_memory(Rho, zdim, ydim);
    free_data_memory(Jz, zdim, ydim);
    return 0;
}
예제 #16
0
파일: input.c 프로젝트: dmt4/ne
char *request(const char *prompt, const char * const default_string, const bool alpha_allowed, const int completion_type, const bool prefer_utf8) {

	set_attr(0);

	input_buffer[pos = len = offset = 0] = 0;
	encoding = ENC_ASCII;
	x = start_x = print_prompt(prompt);

	init_history();

	if (default_string) {
		strncpy(input_buffer, default_string, MAX_INPUT_LINE_LEN);
		len = strlen(input_buffer);
		encoding = detect_encoding(input_buffer, len);
		input_refresh();
	}

	bool first_char_typed = true, last_char_completion = false, selection = false;

	while(true) {

		assert(input_buffer[len] == 0);

		move_cursor(ne_lines - 1, x);

		int c;
		input_class ic;
		do c = get_key_code(); while((ic = CHAR_CLASS(c)) == IGNORE);

		/* ISO 10646 characters *above 256* can be added only to UTF-8 lines, or ASCII lines (making them, of course, UTF-8). */
		if (ic == ALPHA && c > 0xFF && encoding != ENC_ASCII && encoding != ENC_UTF8) ic = INVALID;

		if (ic != TAB) last_char_completion = false;
		if (ic == TAB && !completion_type) ic = ALPHA;

		switch(ic) {

		case INVALID:
			alert();
			break;

		case ALPHA:

			if (first_char_typed) {
				input_buffer[len = 0] = 0;
				clear_to_eol();
			}

			if (encoding == ENC_ASCII && c > 0x7F) encoding = prefer_utf8 || c > 0xFF ? ENC_UTF8 : ENC_8_BIT;
			int c_len = encoding == ENC_UTF8 ? utf8seqlen(c) : 1;
			int c_width = output_width(c);
			assert(c_len > 0);

			if (len <= MAX_INPUT_LINE_LEN - c_len && (alpha_allowed || (c < 0x100 && isxdigit(c)) || c=='X' || c=='x')) {

				memmove(&input_buffer[pos + c_len], &input_buffer[pos], len - pos + 1);

				if (c_len == 1) input_buffer[pos] = c;
				else utf8str(c, &input_buffer[pos]);

				len += c_len;

				move_cursor(ne_lines - 1, x);

				if (x < ne_columns - c_width) {
					if (pos == len - c_len) output_char(c, 0, encoding);
					else if (char_ins_del_ok) insert_char(c, 0, encoding);
					else input_refresh();
				}

				input_move_right(true);
			}
			break;

		case RETURN:
			selection = true;
			break;

		case TAB:
			if (completion_type == COMPLETE_FILE || completion_type == COMPLETE_SYNTAX) {
				bool quoted = false;
				char *prefix, *completion, *p;
				if (len && input_buffer[len - 1] == '"') {
					input_buffer[len - 1] = 0;
					if (prefix = strrchr(input_buffer, '"')) {
						quoted = true;
						prefix++;
					}
					else input_buffer[len - 1] = '"';
				}

				if (!quoted) {
					prefix = strrchr(input_buffer, ' ');
					if (prefix) prefix++;
					else prefix = input_buffer;
				}

				if (last_char_completion || completion_type == COMPLETE_SYNTAX) {
					if (completion_type == COMPLETE_FILE )
						completion = p = request_files(prefix, true);
					else
						completion = p = request_syntax(prefix, true);
					reset_window();
					if (completion) {
						if (*completion) selection = true;
						else completion++;
					}
				}
				else {
					if (completion_type == COMPLETE_FILE )
						completion = p = complete_filename(prefix);
					else
						completion = p = request_syntax(prefix, true);
					last_char_completion = true;
					if (!completion) alert();
				}

				if (completion && (prefix - input_buffer) + strlen(completion) + 1 < MAX_INPUT_LINE_LEN) {
					const encoding_type completion_encoding = detect_encoding(completion, strlen(completion));
					if (encoding == ENC_ASCII || completion_encoding == ENC_ASCII || encoding == completion_encoding) {
						strcpy(prefix, completion);
						if (quoted) strcat(prefix, "\"");
						len = strlen(input_buffer);
						pos = offset = 0;
						x = start_x;
						if (encoding == ENC_ASCII) encoding = completion_encoding;
						input_move_to_eol();
						if (quoted) input_move_left(false);
						input_refresh();
					}
					else alert();
				}
				else if (quoted) strcat(prefix, "\"");

				free(p);
			}
			break;

		case COMMAND:
			if (c < 0) c = -c - 1;
			const int a = parse_command_line(key_binding[c], NULL, NULL, false);
			if (a >= 0) {
				switch(a) {

				case LINEUP_A:
				case LINEDOWN_A:
				case MOVESOF_A:
				case MOVEEOF_A:
				case PAGEUP_A:
				case PAGEDOWN_A:
				case NEXTPAGE_A:
				case PREVPAGE_A:
					if (history_buff) {
						switch(a) {
						case LINEUP_A: line_up(history_buff); break;
						case LINEDOWN_A: line_down(history_buff); break;
						case MOVESOF_A: move_to_sof(history_buff); break;
						case MOVEEOF_A: move_to_bof(history_buff); break;
						case PAGEUP_A:
						case PREVPAGE_A: prev_page(history_buff); break;
						case PAGEDOWN_A:
						case NEXTPAGE_A: next_page(history_buff); break;
						}

						/* In some cases, the default displayed on the command line will be the same as the 
							first history item. In that case we skip it. */

						if (first_char_typed == true 
							 && a == LINEUP_A 
							 && history_buff->cur_line_desc->line 
							 && !strncmp(history_buff->cur_line_desc->line, input_buffer, history_buff->cur_line_desc->line_len))
							line_up(history_buff);

						if (history_buff->cur_line_desc->line) {
							strncpy(input_buffer,
									  history_buff->cur_line_desc->line,
									  min(history_buff->cur_line_desc->line_len,MAX_INPUT_LINE_LEN));
							input_buffer[min(history_buff->cur_line_desc->line_len,MAX_INPUT_LINE_LEN)] = 0;
							len	 = strlen(input_buffer);
							encoding = detect_encoding(input_buffer, len);
						}
						else {
							input_buffer[len = 0] = 0;
							encoding = ENC_ASCII;
						}

						x		= start_x;
						pos	= 0;
						offset = 0;
						input_refresh();
					}
					break;

				case MOVELEFT_A:
					input_move_left(true);
					break;

				case MOVERIGHT_A:
					input_move_right(true);
					break;

				case BACKSPACE_A:
					if (pos == 0) break;
					input_move_left(true);

				case DELETECHAR_A:
					if (len > 0 && pos < len) {
						int c_len = encoding == ENC_UTF8 ? utf8len(input_buffer[pos]) : 1;
						int c_width = get_char_width(&input_buffer[pos], encoding);
						memmove(&input_buffer[pos], &input_buffer[pos + c_len], len - pos - c_len + 1);
						len -= c_len;
						if (input_buffer_is_ascii()) encoding = ENC_ASCII;

						if (char_ins_del_ok) {
							int i, j;

							move_cursor(ne_lines - 1, x);
							delete_chars(c_width);

							for(i = x, j = pos; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns - c_width; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));

							if (j < len) {
								move_cursor(ne_lines - 1, i);
								while(j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns) {
									output_char(get_char(&input_buffer[j], encoding), 0, encoding);
									i += get_char_width(&input_buffer[j], encoding);
									j = next_pos(input_buffer, j, encoding);
								}
							}
						}
						else input_refresh();
					}
					break;

				case DELETELINE_A:
					move_cursor(ne_lines - 1, start_x);
					clear_to_eol();
					input_buffer[len = pos = offset = 0] = 0;
					encoding = ENC_ASCII;
					x = start_x;
					break;

				case DELETEEOL_A:
					input_buffer[len = pos] = 0;
					clear_to_eol();
					if (input_buffer_is_ascii()) encoding = ENC_ASCII;
					break;

				case MOVEINCUP_A:
					if (x != start_x) {
						pos = offset;
						x = start_x;
						break;
					}

				case MOVESOL_A:
					input_move_to_sol();
					break;

				case MOVEINCDOWN_A: {
					int i, j;
					for(i = x, j = pos; j < len && i + get_char_width(&input_buffer[j], encoding) < ne_columns; i += get_char_width(&input_buffer[j], encoding), j = next_pos(input_buffer, j, encoding));
					if (j != pos && j < len) {
						pos = j;
						x = i;
						break;
					}
				}

				case MOVEEOL_A:
					input_move_to_eol();
					break;

				case TOGGLESEOL_A:
				case TOGGLESEOF_A:
					if (pos != 0) input_move_to_sol();
					else input_move_to_eol();
					break;

				case PREVWORD_A:
					input_prev_word();
					break;

				case NEXTWORD_A:
					input_next_word();
					break;

				case REFRESH_A:
					input_refresh();
					break;

				case PASTE_A:
					input_paste();
					break;

				case AUTOCOMPLETE_A:
					input_autocomplete();
					break;

				case ESCAPE_A:
					return NULL;

				default:
					break;
				}
			}
			break;

		default:
			break;
		}

		if (selection) {
			const line_desc * const last = (line_desc *)history_buff->line_desc_list.tail_pred->prev;
			assert(input_buffer[len] == 0);
			if (history_buff->num_lines == 0 || len != last->line_len || strncmp(input_buffer, last->line, last->line_len)) add_to_history(input_buffer);
			return input_buffer;
		}

		first_char_typed = false;
	}
}
예제 #17
0
void determine_panel_labels(PLOT_SPEC *plspec, long panel_index)
{
  long i, request, file, first, datasets;
  long j, plane, scaleCount, group, set, index, ig;
  static char buffer[SDDS_MAXLINE], s[SDDS_MAXLINE];
  PLOT_DATA **dataset;
  time_t timeValue;
  static unsigned long ticksetTime[2] = {TICKSET_XTIME, TICKSET_YTIME}, flags;
  char *newLabel, *editCommand;
  
  /* Construct labels for each scale for each plane */
  first = 1;
  dataset = plspec->panel[panel_index].dataset;
  datasets = plspec->panel[panel_index].datasets;
#if defined(DEBUG)
  fprintf(stderr, "panel label determination: %ld datasets for panel %ld\n", 
          datasets, panel_index);
#endif
  newLabel = NULL;
  for (plane=0; plane<2; plane++) {
    scaleCount = 0;
    for (ig=0; ig<plspec->panel[panel_index].scalesUsed[plane]; ig++) {
      group = plspec->panel[panel_index].scalesGroupIndex[plane][ig];
      /* each scales group has a separate label */
      if (plspec->scaleLabelInfo[plane][group].flags!=SCALE_LABEL_USED)
          continue;
      plspec->scaleLabelInfo[plane][group].flags = 0;
      plspec->scaleLabelInfo[plane][group].scaleNumber = -1;
      plspec->scaleLabelInfo[plane][group].label = newLabel = editCommand = NULL;
      for (set=0; set<datasets; set++) {
        /* scan for datasets that belong to this group */
        if (dataset[set]->scalesGroupIndex[plane]!=group)
          continue;
        request = dataset[set]->request_index;
	if (plspec->plot_request[request].overlay.flags)
	  continue;
        /* If we get to this point, then a scale will be made for
         * this group.
         */
        if (plspec->scaleLabelInfo[plane][group].scaleNumber==-1)
          plspec->scaleLabelInfo[plane][group].scaleNumber = ++scaleCount;
        /* For each scales group, the label may have been specified by 
         * a -label option for one request.
         */
        if ((index=plspec->scalesGroupData[plane][group].labelSpecRequestIndex)>=0 &&
            index==request &&
            (flags=plspec->plot_request[index].label[plane].flags)) {
          if (flags&(LABEL_STRING_GIVEN+LABEL_PARAMETER_GIVEN+
                     LABEL_USE_NAME+LABEL_USE_SYMBOL+LABEL_USE_DESCRIPTION)) {
            if (newLabel)
              free(newLabel);
            if (!SDDS_CopyString(&newLabel, dataset[set]->label[plane]))
              SDDS_Bomb("Memory allocation failure (determine_panel_labels)");
          }
          if (flags&LABEL_EDITCOMMAND_GIVEN)
            editCommand = plspec->plot_request[index].label[plane].edit_command;
          if (flags&LABEL_SCALE_GIVEN) {
            plspec->scaleLabelInfo[plane][group].flags |= SCALE_LABEL_SCALEGIVEN;
            plspec->scaleLabelInfo[plane][group].scale = plspec->plot_request[index].label[plane].scale;
          }
          if (flags&LABEL_OFFSET_GIVEN) {
            plspec->scaleLabelInfo[plane][group].flags |= SCALE_LABEL_OFFSETGIVEN;
            plspec->scaleLabelInfo[plane][group].offset = plspec->plot_request[index].label[plane].offset;
          }
          if (flags&LABEL_THICKNESS_GIVEN) {
            plspec->scaleLabelInfo[plane][group].flags |= SCALE_LABEL_THICKNESSGIVEN;
            plspec->scaleLabelInfo[plane][group].thickness = plspec->plot_request[index].label[plane].thickness;
          }
          if (flags&LABEL_LINETYPE_GIVEN) {
            plspec->scaleLabelInfo[plane][group].flags |= SCALE_LABEL_LINETYPEGIVEN;
            plspec->scaleLabelInfo[plane][group].linetype = plspec->plot_request[index].label[plane].linetype;
          }
          break;
        }
      }
      if (plspec->scaleLabelInfo[plane][group].scaleNumber==-1)
        continue;

      if (!newLabel) {
        /* No explicit label was given or generated */
        if ((index=plspec->scalesGroupData[plane][group].tickSettingsRequestIndex)>=0 &&
            plspec->plot_request[index].tick_settings.flags&ticksetTime[plane]) {
          /* Use calendar time scales, per user request. */
          timeValue = plspec->scalesGroupData[plane][group].limit[0];
          if (!(newLabel = SDDS_Malloc(sizeof(*newLabel)*50)))
            SDDS_Bomb("Memory allocation failure (determine_panel_labels)");
          if (timeValue!=DBL_MAX)
            sprintf(newLabel, "Time starting %s", ctime(&timeValue));
          else
            sprintf(newLabel, "Undefined time values!");
          delete_chars(newLabel, "\n");
        } 
        else {
          /* Make a label using the names of the columns.  This is the default
           * if no commandline options are given. */
          if (!(newLabel=makeNameUnitsLabel(plspec, panel_index, plane, group))) 
            SDDS_Bomb("Unable to make label (determine_panel_labels)");
        }
      }
      if (editCommand) {
        /* Edit the label per user request. */
        strcpy_ss(buffer, newLabel);
        free(newLabel);
        edit_string(buffer, editCommand);
        if (plspec->scaleLabelInfo[plane][group].label)
          free(plspec->scaleLabelInfo[plane][group].label);
        if (!SDDS_CopyString(&plspec->scaleLabelInfo[plane][group].label, buffer))
          SDDS_Bomb("String copy problem (determine_panel_labels)");
      }
      else {
        /* Store the label for latter placement on plot. */
        if (plspec->scaleLabelInfo[plane][group].label)
          free(plspec->scaleLabelInfo[plane][group].label);
        plspec->scaleLabelInfo[plane][group].label = newLabel;
        newLabel = NULL;
      }
    }
  }
  

  /* This section creates labels for the title (0) and topline (1) */
  for (j=0; j<2; j++) {
    if (plspec->panel[panel_index].titleSpec[j].label)
      SDDS_CopyString(plspec->panel[panel_index].title+j, plspec->panel[panel_index].titleSpec[j].label);
    else {
      /* Stuff in some default labels... */
      if (j==0 &&
          plspec->plot_request[dataset[0]->request_index].description_text[dataset[0]->file_index]) 
        /* title from description text of first dataset, if there is any */
        SDDS_CopyString(plspec->panel[panel_index].title+j, 
                        plspec->plot_request[dataset[0]->request_index].
                        description_text[dataset[0]->file_index]);
      else
        SDDS_CopyString(plspec->panel[panel_index].title+j, "");
    }
    if ((editCommand=plspec->panel[panel_index].titleSpec[j].edit_command)) {
      strcpy_ss(buffer, plspec->panel[panel_index].title[j]);
      edit_string(buffer, editCommand);
      free(plspec->panel[panel_index].title[j]);
      SDDS_CopyString(plspec->panel[panel_index].title+j, buffer);
    }
  }

  if (plspec->panel[panel_index].flags&PLREQ_FNONTOPLINE) {
    /* User requested filenames on topline */
    char **filename;
    char buffer[1024];
    filename = tmalloc(sizeof(*filename)*plspec->panel[panel_index].datasets);
    for (i=0; i<plspec->panel[panel_index].datasets; i++) {
      request = plspec->panel[panel_index].dataset[i]->request_index;
      file = plspec->panel[panel_index].dataset[i]->file_index;
      filename[i] = plspec->plot_request[request].filename[file];
      if (plspec->plot_request[request].filenamesOnToplineEditCmd) {
        strcpy_ss(buffer, filename[i]);
        edit_string(buffer, plspec->plot_request[request].filenamesOnToplineEditCmd);
        SDDS_CopyString(&filename[i], buffer);
      }
    }
    qsort(filename, plspec->panel[panel_index].datasets, sizeof(*filename),
          string_cmpasc);
    i = unique(filename, plspec->panel[panel_index].datasets, sizeof(*filename),
               string_cmpasc, string_copy);
    if (plspec->panel[panel_index].title[1][0])
      sprintf(s, "%s  ", plspec->panel[panel_index].title[1]);
    else
      s[0] = 0;
    for (j=0; j<i; j++) {
      if ((strlen(s)+strlen(filename[j])+3)>1024)
        break;
      if (j)
        strcat(s, ", ");
      strcat(s, filename[j]);
    }
    SDDS_CopyString(plspec->panel[panel_index].title+1, s);
  }

  if (plspec->panel[panel_index].flags&PLREQ_YLONTOPLINE) {
    /* This is probably impossible with the multiple scales... */
  }
}
예제 #18
0
int32_t SDDS_ReadIntoMplTable(TABLE *mpl_data, char *file, int32_t sample_interval,
                           int32_t mpl_flags, char *SDDS_tags)
{
  SDDS_DATASET SDDS_dataset;
  int32_t i, first, new_points, n_rows;
  SDDS_LAYOUT *layout;
  char *xname, *yname, *sxname, *syname, *option_string, *ptr;
  COLUMN_DEFINITION *xdef, *ydef, *sxdef, *sydef;
  PARAMETER_DEFINITION *xpdef, *ypdef, *sxpdef, *sypdef;
  PARAMETER_DEFINITION *titledef, *toplinedef, *pardef;
  static char s[SDDS_MAXLINE];
  double *data;
  MATCH_TERM *column_match, *parameter_match;
  int32_t accept = 1;
 
  xname = yname = sxname = syname = NULL;
  xdef = ydef = sxdef = sydef = NULL;
  xpdef = ypdef = sxpdef = sypdef = titledef = toplinedef = NULL;
  n_rows = 0;

  if (!SDDS_InitializeInput(&SDDS_dataset, file)) {
    SDDS_PrintErrors(stderr, 1);
    return(0);
  }
  layout = &SDDS_dataset.layout;
  if (SDDS_dataset.layout.n_columns<1 && SDDS_dataset.layout.n_parameters<1)
    return(0);

  first = 1;
  while (SDDS_ReadPage(&SDDS_dataset)>0) {
    if (first) {
      first = 0;
#if 0
      if ((pardef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplTitle")) && pardef->type==SDDS_STRING)
        mpl_data->title = SDDS_GetParameter(&SDDS_dataset, "mplTitle", NULL);
      else
        SDDS_CopyString(&mpl_data->title, "");
      if ((pardef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplTopline")) && pardef->type==SDDS_STRING)
        mpl_data->topline = SDDS_GetParameter(&SDDS_dataset, "mplTopline", NULL);
      else
        SDDS_CopyString(&mpl_data->topline, "");
#endif

      xname = yname = sxname = syname = option_string = NULL;
      xdef = ydef = sxdef = sydef = NULL;
      xpdef = ypdef = sxpdef = sypdef = NULL;
      if (SDDS_tags) {
        /* expect columns-of-interest to be specified in this string as
         * <xname>+<yname>[+<syname>][,<options>] or
         * <xname>+<yname>[+<sxname>+<syname>][,<options>]
         */
        xname = SDDS_tags;
        if ((yname=strchr(xname, '+'))) {
          ptr = yname;
          while ((option_string = strchr(ptr, ','))) {
            if (option_string!=ptr && *(option_string-1)=='\\')
              ptr = option_string+1;
            else {
              *option_string++ = 0;
              break;
            }
          }
          *yname++ = 0;
          if ((sxname=strchr(yname, '+'))) {
            *sxname++ = 0;
            if ((syname=strchr(sxname, '+'))) {
              *syname++ = 0;
            }
            else {
              syname = sxname;
              sxname = NULL;
            }
          }
        }
        delete_bounding_characters(xname, "\"'");
        delete_bounding_characters(yname, "\"'"); 
        if (sxname)
          delete_bounding_characters(sxname, "\"'");
        if (syname)
          delete_bounding_characters(syname, "\"'");
      }

      if (!xname || !yname) {
        xname = yname = NULL;
        /* No columns-of-interest found in SDDS_tags.  Check for parameters mplxName and mplyName */
        if ((pardef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplxName")) && pardef->type==SDDS_STRING &&
            (pardef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplyName")) && pardef->type==SDDS_STRING) {
          xname = SDDS_GetParameter(&SDDS_dataset, "mplxName", NULL);
          yname = SDDS_GetParameter(&SDDS_dataset, "mplyName", NULL);
          if (xname && yname) {
            /* check for mplSigmaxName and mplSigmayName */
            if ((pardef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplSigmayName")) && pardef->type==SDDS_STRING)
              syname = SDDS_GetParameter(&SDDS_dataset, "mplSigmayName", NULL);
            if ((pardef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplSigmaxName")) && pardef->type==SDDS_STRING)
              sxname = SDDS_GetParameter(&SDDS_dataset, "mplSigmaxName", NULL);
          }
        }
      }
      
      if (!xname || !yname) {
        /* No columns-of-interest found in SDDS_tags or parameters. Just take the first two numeric
         * column definitions in order 
         */
        for (i=0; i<layout->n_columns; i++) {
          if (SDDS_NUMERIC_TYPE(layout->column_definition[i].type)) {
            if (!xname)
              xname = layout->column_definition[i].name;
            else if (!yname)
              yname = layout->column_definition[i].name;
            else
              break;
          }
        }
        if (sxname && !syname) {
          syname = sxname;
          sxname = NULL;
        }
      }
      
      if (!xname || !yname) 
        return(0);

      if (!((xdef=SDDS_GetColumnDefinition(&SDDS_dataset, xname)) && SDDS_NUMERIC_TYPE(xdef->type)) &&
          !((xpdef=SDDS_GetParameterDefinition(&SDDS_dataset, xname)) && SDDS_NUMERIC_TYPE(xpdef->type))) {
        fprintf(stderr, "error: column (or parameter) %s does not exist or is non-numeric\n", xname);
        SDDS_PrintListOfColumns(&SDDS_dataset, "Valid columns are:\n", stderr);
        SDDS_PrintListOfParameters(&SDDS_dataset, "Valid parameters are:\n", stderr);
        return(0);
      }
      if (xdef) {
        if (!((ydef=SDDS_GetColumnDefinition(&SDDS_dataset, yname)) && SDDS_NUMERIC_TYPE(ydef->type))) {
          fprintf(stderr, "error: column %s does not exist or is non-numeric\n", yname);
          SDDS_PrintListOfColumns(&SDDS_dataset, "Valid columns are:\n", stderr);
          return(0);
        }
        if (sxname && !((sxdef=SDDS_GetColumnDefinition(&SDDS_dataset, sxname)) && SDDS_NUMERIC_TYPE(sxdef->type))) {
          fprintf(stderr, "error: column %s does not exist or is non-numeric\n", sxname);
          SDDS_PrintListOfColumns(&SDDS_dataset, "Valid columns are:\n", stderr);
          return(0);
        }
        if (syname && !((sydef=SDDS_GetColumnDefinition(&SDDS_dataset, syname)) && SDDS_NUMERIC_TYPE(sydef->type))) {
          fprintf(stderr, "error: column %s does not exist or is non-numeric\n", syname);
          SDDS_PrintListOfColumns(&SDDS_dataset, "Valid columns are:\n", stderr);
          return(0);
        }
        if (xdef->symbol && !(mpl_flags&SDDS_NOCOMPRESS_NAMES))
          delete_chars(xdef->symbol, " ");
        if (ydef->symbol && !(mpl_flags&SDDS_NOCOMPRESS_NAMES))
          delete_chars(ydef->symbol, " ");
        if (sxdef && sxdef->symbol && !(mpl_flags&SDDS_NOCOMPRESS_NAMES))
          delete_chars(sxdef->symbol, " ");
        if (sydef && sydef->symbol && !(mpl_flags&SDDS_NOCOMPRESS_NAMES))
          delete_chars(sydef->symbol, " ");

        if (xdef->units && !SDDS_StringIsBlank(xdef->units))
          sprintf(s, "%s (%s)", xdef->symbol?xdef->symbol:xdef->name, xdef->units);
        else
          sprintf(s, "%s", xdef->symbol?xdef->symbol:xdef->name);
        SDDS_CopyString(&mpl_data->xlab, s);
        if (ydef->units && !SDDS_StringIsBlank(ydef->units))
          sprintf(s, "%s (%s)", ydef->symbol?ydef->symbol:ydef->name, ydef->units);
        else
          sprintf(s, "%s", ydef->symbol?ydef->symbol:ydef->name);
        SDDS_CopyString(&mpl_data->ylab, s);
        toplinedef = titledef = NULL;
        if ((toplinedef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplTopline")) && 
            (toplinedef->type!=SDDS_STRING || 
             !SDDS_GetParameter(&SDDS_dataset, toplinedef->name, &mpl_data->topline))) {
          SDDS_FreeParameterDefinition(toplinedef);
          toplinedef = NULL;
        }
        if (!toplinedef) {
          if (layout->description)
            SDDS_CopyString(&mpl_data->topline, layout->description);
          else
            SDDS_CopyString(&mpl_data->topline, "");
        }
        if ((titledef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplTitle"))) {
          if (titledef->type!=SDDS_STRING || !SDDS_GetParameter(&SDDS_dataset, titledef->name, &mpl_data->title))
            titledef = NULL;
        }
        if (!titledef) {
          if (!option_string)
            sprintf(s, "%s vs %s", 
                    ydef->description?ydef->description:(ydef->symbol?ydef->symbol:yname),
                    xdef->description?xdef->description:(xdef->symbol?xdef->symbol:xname));
          else
            sprintf(s, "%s vs %s : %s", 
                    ydef->description?ydef->description:(ydef->symbol?ydef->symbol:yname),
                    xdef->description?xdef->description:(xdef->symbol?xdef->symbol:xname),
                    option_string);
          SDDS_CopyString(&mpl_data->title, s);
        }
      }
      else {
        if (!((ypdef=SDDS_GetParameterDefinition(&SDDS_dataset, yname)) && SDDS_NUMERIC_TYPE(ypdef->type))) {
          fprintf(stderr, "error: parameter %s does not exist or is non-numeric\n", yname);
          SDDS_PrintListOfParameters(&SDDS_dataset, "Valid parameters are:\n", stderr);
          return(0);
        }
        if (sxname && !((sxpdef=SDDS_GetParameterDefinition(&SDDS_dataset, sxname)) && SDDS_NUMERIC_TYPE(sxpdef->type))) {
          fprintf(stderr, "error: parameter %s does not exist or is non-numeric\n", sxname);
          SDDS_PrintListOfParameters(&SDDS_dataset, "Valid parameters are:\n", stderr);
          return(0);
        }
        if (syname && !((sypdef=SDDS_GetParameterDefinition(&SDDS_dataset, syname)) && SDDS_NUMERIC_TYPE(sypdef->type))) {
          fprintf(stderr, "error: parameter %s does not exist or is non-numeric\n", syname);
          SDDS_PrintListOfParameters(&SDDS_dataset, "Valid parameters are:\n", stderr);
          return(0);
        }
        
        if (xpdef->units && !SDDS_StringIsBlank(xpdef->units))
          sprintf(s, "%s (%s)", xpdef->symbol?delete_chars(xpdef->symbol, " "):xpdef->name, xpdef->units);
        else
          sprintf(s, "%s", xpdef->symbol?delete_chars(xpdef->symbol, " "):xpdef->name);
        SDDS_CopyString(&mpl_data->xlab, s);
        if (ypdef->units && !SDDS_StringIsBlank(ypdef->units))
          sprintf(s, "%s (%s)", ypdef->symbol?delete_chars(ypdef->symbol, " "):ypdef->name, ypdef->units);
        else
          sprintf(s, "%s", ypdef->symbol?delete_chars(ypdef->symbol, " "):ypdef->name);
        SDDS_CopyString(&mpl_data->ylab, s);
        toplinedef = titledef = NULL;
        if ((toplinedef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplTopline")) && 
            (toplinedef->type!=SDDS_STRING || 
             !SDDS_GetParameter(&SDDS_dataset, toplinedef->name, &mpl_data->topline))) {
          SDDS_FreeParameterDefinition(toplinedef);
          toplinedef = NULL;
        }
        if (!toplinedef) {
          if (layout->description)
            SDDS_CopyString(&mpl_data->topline, layout->description);
          else
            SDDS_CopyString(&mpl_data->topline, "");
        }
        if ((titledef=SDDS_GetParameterDefinition(&SDDS_dataset, "mplTitle"))) {
          if (titledef->type!=SDDS_STRING || !SDDS_GetParameter(&SDDS_dataset, titledef->name, &mpl_data->title))
            titledef = NULL;
        }
        if (!titledef) {
          if (!option_string)
            sprintf(s, "%s vs %s", 
                    ypdef->description?ypdef->description:(ypdef->symbol?ypdef->symbol:yname),
                    xpdef->description?xpdef->description:(xpdef->symbol?xpdef->symbol:xname));
          else
            sprintf(s, "%s vs %s : %s", 
                    ypdef->description?ypdef->description:(ypdef->symbol?ypdef->symbol:yname),
                    xpdef->description?xpdef->description:(xpdef->symbol?xpdef->symbol:xname),
                    option_string);
          SDDS_CopyString(&mpl_data->title, s);
        }
      }

      mpl_data->c1 = mpl_data->c2 = mpl_data->s1 = mpl_data->s2 = NULL;
      mpl_data->n_data = 0;
      mpl_data->flags = (sxname?SIGMA_X_PRESENT:0)+(syname?SIGMA_Y_PRESENT:0);

      column_match = parameter_match = NULL;
      if (option_string && !process_match_requests(&column_match, &parameter_match, option_string))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }  /* end of block for first page */
    if (!SDDS_dataset.n_rows && xdef)
      continue;

    accept = 1;
    if (parameter_match) {
      i = -1;
      do {
        i++;
        if (!(pardef=SDDS_GetParameterDefinition(&SDDS_dataset, parameter_match[i].name)) ||
            !(pardef->type==SDDS_STRING || pardef->type==SDDS_CHARACTER)) {
          fprintf(stderr, "error: unknown or numeric parameter %s given for match\n",
                  parameter_match[i].name);
          exit(1);
        }
        if (pardef->type==SDDS_STRING) {
          char **ppc;
          ppc = SDDS_GetParameter(&SDDS_dataset, parameter_match[i].name, NULL);
          strcpy(s, *ppc);
        }
        else {
          char *pc;
          pc = SDDS_GetParameter(&SDDS_dataset, parameter_match[i].name, NULL);
          sprintf(s, "%c", *pc);
        }
        accept = SDDS_Logic(accept, wild_match(s, parameter_match[i].string), parameter_match[i].logic);
      } while (!parameter_match[i].last);
    }
    if (!accept)
      continue;

    if (xdef) {
      if (!SDDS_SetColumnFlags(&SDDS_dataset, 1) ||
          (sxname && syname && 
           !SDDS_SetColumnsOfInterest(&SDDS_dataset, SDDS_NAME_STRINGS, xname, yname, sxname, syname, NULL)) ||
          (syname && !sxname &&
           !SDDS_SetColumnsOfInterest(&SDDS_dataset, SDDS_NAME_STRINGS, xname, yname, syname, NULL)) ||
          !SDDS_SetColumnsOfInterest(&SDDS_dataset, SDDS_NAME_STRINGS, xname, yname, NULL)) 
        return(0);

      if (column_match) {
        i = -1;
        do {
          i++;
          if (SDDS_MatchRowsOfInterest(&SDDS_dataset, column_match[i].name, 
                                       column_match[i].string, column_match[i].logic)<0) {
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
            exit(1);
          }
        } while (!column_match[i].last);
      }
      
      if ((n_rows = SDDS_CountRowsOfInterest(&SDDS_dataset))<=0)
        continue;
      
      if (!(new_points = ceil((1.0*n_rows)/sample_interval)))
        new_points = 1;
    }
    else
      new_points = 1;

    /* allocate all four arrays, since that is the expected behavior from get_table() */
    mpl_data->c1 = SDDS_Realloc(mpl_data->c1, sizeof(*mpl_data->c1)*(mpl_data->n_data+new_points));
    mpl_data->c2 = SDDS_Realloc(mpl_data->c2, sizeof(*mpl_data->c2)*(mpl_data->n_data+new_points));
    mpl_data->s1 = SDDS_Realloc(mpl_data->s1, sizeof(*mpl_data->s1)*(mpl_data->n_data+new_points));
    mpl_data->s2 = SDDS_Realloc(mpl_data->s2, sizeof(*mpl_data->s2)*(mpl_data->n_data+new_points));
    for (i=0; i<new_points; i++)
      mpl_data->c1[i+mpl_data->n_data] = 
        mpl_data->c2[i+mpl_data->n_data] = 
          mpl_data->s1[i+mpl_data->n_data] = 
            mpl_data->s2[i+mpl_data->n_data] = 0;

    if (SDDS_NumberOfErrors()) {
      SDDS_SetError("Allocation failure creating mpl-compatible structure");
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }

    if (xdef) {
      if (!(data=SDDS_GetColumnInDoubles(&SDDS_dataset, xdef->name)) ||
          (i=copy_doubles_with_sampling((mpl_flags&SWAP?mpl_data->c2:mpl_data->c1)+mpl_data->n_data, 
                                        data, n_rows, sample_interval))!=new_points) {
        sprintf(s,"Sampling problem: %" PRId32 " rows created, %" PRId32 " expected",i,new_points);
        SDDS_SetError(s);
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        return(0);
      }
      free(data);
      if (!(data=SDDS_GetColumnInDoubles(&SDDS_dataset, ydef->name)) ||
          (i=copy_doubles_with_sampling((mpl_flags&SWAP?mpl_data->c1:mpl_data->c2)+mpl_data->n_data, 
                                        data, n_rows, sample_interval))!=new_points) {
        sprintf(s,"Sampling problem: %" PRId32 " rows created, %" PRId32 " expected",i,new_points);
        SDDS_SetError(s);
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        return(0);
      }
      free(data);
      if (sxdef) {
        if (!(data=SDDS_GetColumnInDoubles(&SDDS_dataset, sxdef->name)) ||
            (i=copy_doubles_with_sampling((mpl_flags&SWAP?mpl_data->s2:mpl_data->s1)+mpl_data->n_data, 
                                          data, n_rows, sample_interval))!=new_points) {
          sprintf(s,"Sampling problem: %" PRId32 " rows created, %" PRId32 " expected",i,new_points);
          SDDS_SetError(s);
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          return(0);
        }
        free(data);
      }
      if (sydef) {
        if (!(data=SDDS_GetColumnInDoubles(&SDDS_dataset, sydef->name)) ||
            (i=copy_doubles_with_sampling((mpl_flags&SWAP?mpl_data->s1:mpl_data->s2)+mpl_data->n_data, 
                                          data, n_rows, sample_interval))!=new_points) {
          sprintf(s,"Sampling problem: %" PRId32 " rows created, %" PRId32 " expected",i,new_points);
          SDDS_SetError(s);
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          return(0);
        }
        free(data);
      }
    }
    else {
      static int32_t buffer[16];
      SDDS_GetParameter(&SDDS_dataset, xpdef->name, buffer);
      mpl_data->c1[mpl_data->n_data] = SDDS_ConvertToDouble(xpdef->type, buffer, 0);
      SDDS_GetParameter(&SDDS_dataset, ypdef->name, buffer);
      mpl_data->c2[mpl_data->n_data] = SDDS_ConvertToDouble(ypdef->type, buffer, 0);
      if (sxpdef) {
        SDDS_GetParameter(&SDDS_dataset, sxpdef->name, buffer);
        mpl_data->s1[mpl_data->n_data] = SDDS_ConvertToDouble(sxpdef->type, buffer, 0);
      }
      if (sypdef) {
        SDDS_GetParameter(&SDDS_dataset, sypdef->name, buffer);
        mpl_data->s2[mpl_data->n_data] = SDDS_ConvertToDouble(sypdef->type, buffer, 0);
      }
      if (SDDS_NumberOfErrors()) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        return(0);
      }
    }
    mpl_data->n_data += new_points;
  }
  if (xdef)  SDDS_FreeColumnDefinition(xdef);
  if (ydef)  SDDS_FreeColumnDefinition(ydef);
  if (sxdef)  SDDS_FreeColumnDefinition(sxdef);
  if (sydef)  SDDS_FreeColumnDefinition(sydef);
  if (titledef) SDDS_FreeParameterDefinition(titledef);
  if (toplinedef) SDDS_FreeParameterDefinition(toplinedef);
  if (first || !SDDS_Terminate(&SDDS_dataset)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    return(0);
  }
  return(1);
}