コード例 #1
0
ファイル: sdds3daverage.c プロジェクト: epicsdeb/sdds
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;
}
コード例 #2
0
ファイル: sddsvslopes.c プロジェクト: veprbl/epics-sdds
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);
}
コード例 #3
0
ファイル: ibsEmittance.c プロジェクト: epicsdeb/elegant
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);
}
コード例 #4
0
ファイル: sddssampledist.c プロジェクト: epicsdeb/sdds
int main(int argc, char **argv)
{
  int iArg;
  char *input, *output,*meanPar, *sigmaPar, *maxPar, *minPar;
  long i, j, mainInputOpened, haltonID=0, requireInput=0;
  unsigned long pipeFlags;
  SCANNED_ARG *scanned;
  SDDS_DATASET SDDSin, SDDSout, *SDDSptr;
  long randomNumberSeed = 0;
  SEQ_REQUEST *seqRequest;
  long samples, values, seqRequests, randomizationGroups=0;
  double *sample, *IVValue, *CDFValue;
  char msgBuffer[1000];
  RANDOMIZED_ORDER *randomizationData = NULL;
  long verbose, optimalHalton=0;
  
  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&scanned, argc, argv); 
  if (argc<2) {
    fprintf(stderr, "%s%s%s\n", USAGE1, USAGE2, USAGE3);
    return(1);
  }
  seqRequest = NULL;
  seqRequests = 0;
  output = input = NULL;
  pipeFlags = 0;
  samples = values = 0;
  sample = IVValue = CDFValue = NULL;
  verbose = 0;
  maxPar = minPar = meanPar = sigmaPar = NULL;
  
  for (iArg=1; iArg<argc; iArg++) {
    if (scanned[iArg].arg_type==OPTION) {
      /* process options here */
      switch (match_string(scanned[iArg].list[0], option, CLO_OPTIONS, 0)) {
      case CLO_COLUMNS:
        if (scanned[iArg].n_items<3)
          SDDS_Bomb("invalid -columns syntax");
        if (!(seqRequest = SDDS_Realloc(seqRequest, sizeof(*seqRequest)*(seqRequests+1))))
          SDDS_Bomb("memory allocation failure");
        scanned[iArg].n_items -= 1;
        memset(seqRequest+seqRequests, 0, sizeof(*seqRequest));
        /*remove following pointer initialization because memset already initialize them */
        seqRequest[seqRequests].randomizationGroup = -1;
        seqRequest[seqRequests].factor = 1;
        seqRequest[seqRequests].offset = 0;
        if (!scanItemList(&seqRequest[seqRequests].flags, 
                          scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                          "datafile", SDDS_STRING,
                          &seqRequest[seqRequests].dataFileName, 1, SEQ_DATAFILE,
                          "independentvariable", SDDS_STRING, 
                          &seqRequest[seqRequests].indepName, 1, SEQ_INDEPNAME,
                          "cdf", SDDS_STRING, 
                          &seqRequest[seqRequests].CDFName, 1, SEQ_CDFNAME,
                          "df", SDDS_STRING, 
                          &seqRequest[seqRequests].DFName, 1, SEQ_DFNAME,
                          "output", SDDS_STRING, 
                          &seqRequest[seqRequests].outputName, 1, SEQ_OUTPUTNAME,
                          "units", SDDS_STRING, 
                          &seqRequest[seqRequests].units, 1, SEQ_UNITSGIVEN,
                          "haltonradix", SDDS_LONG,
                          &seqRequest[seqRequests].haltonRadix, 1, SEQ_HALTONRADIX,
                          "haltonoffset", SDDS_LONG,
                          &seqRequest[seqRequests].haltonOffset, 1, SEQ_HALTONOFFSET,
                          "randomize", -1, NULL, 0, SEQ_RANDOMIZE,
                          "group", SDDS_LONG, 
                          &seqRequest[seqRequests].randomizationGroup, 1, SEQ_RANDOMGROUP,
                          "factor", SDDS_DOUBLE, 
                          &seqRequest[seqRequests].factor, 1, 0,
                          "offset", SDDS_DOUBLE, 
                          &seqRequest[seqRequests].offset, 1, 0,
                          NULL) ||
            bitsSet(seqRequest[seqRequests].flags&(SEQ_INDEPNAME+SEQ_CDFNAME+SEQ_DFNAME))!=2)
          SDDS_Bomb("invalid -columns syntax");
        if (seqRequest[seqRequests].flags&SEQ_RANDOMGROUP &&
            seqRequest[seqRequests].randomizationGroup<=0)
          SDDS_Bomb("use a positive integer for the randomization group ID");
        if (seqRequest[seqRequests].flags&SEQ_CDFNAME &&
            seqRequest[seqRequests].flags&SEQ_DFNAME) 
          SDDS_Bomb("give df or cdf for -columns, not both");
        if (seqRequest[seqRequests].flags&SEQ_HALTONRADIX &&
            !is_prime(seqRequest[seqRequests].haltonRadix))
          SDDS_Bomb("halton radix must be a prime number");
        seqRequests ++;
        scanned[iArg].n_items += 1;
        break;
      case CLO_GAUSSIAN:
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -gaussian syntax");
        if (!(seqRequest = SDDS_Realloc(seqRequest, sizeof(*seqRequest)*(seqRequests+1))))
          SDDS_Bomb("memory allocation failure");
        memset(seqRequest+seqRequests, 0, sizeof(*seqRequest)); 
        scanned[iArg].n_items -= 1;
        seqRequest[seqRequests].randomizationGroup = -1;
        seqRequest[seqRequests].mean = 0;
        seqRequest[seqRequests].sigma = 1;
        if (!scanItemList(&seqRequest[seqRequests].flags, 
                          scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                          "columnName", SDDS_STRING, &seqRequest[seqRequests].outputName, 1, SEQ_OUTPUTNAME,
                          "meanValue", SDDS_STRING,  &meanPar, 1, 0,
                          "sigmaValue", SDDS_STRING, &sigmaPar, 1, 0, 
                          "units", SDDS_STRING, &seqRequest[seqRequests].units, 1, SEQ_UNITSGIVEN,
                          NULL))
          SDDS_Bomb("invalid -gaussian syntax");
        seqRequest[seqRequests].flags |= SEQ_DIRECT_GAUSSIAN; 
        if (!(seqRequest[seqRequests].flags&SEQ_OUTPUTNAME) || !(seqRequest[seqRequests].outputName))
          SDDS_Bomb("columnName is not provided for gaussian distribution/");
        if (meanPar) {
          if (wild_match(meanPar, "@*"))
            SDDS_CopyString(&seqRequest[seqRequests].meanPar, meanPar+1);
          else if (!get_double(&seqRequest[seqRequests].mean, meanPar))  
            SDDS_Bomb("Invalid value given for mean value of -gaussian distribution.");
          free(meanPar);
          meanPar = NULL;
        }
        if (sigmaPar) {
          if (wild_match(sigmaPar, "@*"))
            SDDS_CopyString(&seqRequest[seqRequests].sigmaPar, sigmaPar+1);
          else if (!get_double(&seqRequest[seqRequests].sigma, sigmaPar)) 
            SDDS_Bomb("Invalid value given for sigma value of -gaussian distribution.");
          free(sigmaPar);
          sigmaPar = NULL;
        }
        seqRequests ++;
        scanned[iArg].n_items += 1;
        break;
      case CLO_UNIFORM:
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -uniform syntax");
        if (!(seqRequest = SDDS_Realloc(seqRequest, sizeof(*seqRequest)*(seqRequests+1))))
          SDDS_Bomb("memory allocation failure");
        memset(seqRequest+seqRequests, 0, sizeof(*seqRequest));
        scanned[iArg].n_items -= 1;
        memset(seqRequest+seqRequests, 0, sizeof(*seqRequest));
        seqRequest[seqRequests].randomizationGroup = -1;
        seqRequest[seqRequests].min = 0;
        seqRequest[seqRequests].max = 1;
        if (!scanItemList(&seqRequest[seqRequests].flags, 
                          scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                          "columnName", SDDS_STRING, &seqRequest[seqRequests].outputName, 1, SEQ_OUTPUTNAME,
                          "minimumValue", SDDS_STRING, &minPar, 1, 0,
                          "maximumValue", SDDS_STRING, &maxPar, 1, 0,
                          "units", SDDS_STRING, &seqRequest[seqRequests].units, 1, SEQ_UNITSGIVEN, 
                          NULL))
          SDDS_Bomb("invalid -uniform syntax");
        seqRequest[seqRequests].flags |= SEQ_DIRECT_UNIFORM; 
        if (!(seqRequest[seqRequests].flags&SEQ_OUTPUTNAME) || !(seqRequest[seqRequests].outputName))
          SDDS_Bomb("columnName is not provided for uniform distribution/");
        if (minPar) {
          if (wild_match(minPar, "@*"))
            SDDS_CopyString(&seqRequest[seqRequests].minPar, minPar+1);
          else if (!get_double(&seqRequest[seqRequests].min, minPar))  
            SDDS_Bomb("Invalid value given for minimum value of -uniform distribution.");
          free(minPar);
          minPar = NULL;
        }
        if (maxPar) {
          if (wild_match(maxPar, "@*"))
            SDDS_CopyString(&seqRequest[seqRequests].maxPar, maxPar+1);
          else if (!get_double(&seqRequest[seqRequests].max, maxPar))  
            SDDS_Bomb("Invalid value given for maximum value of -uniform distribution.");
          free(maxPar);
          maxPar = NULL;
        }
        seqRequests ++;
        scanned[iArg].n_items += 1;
        break;
      case CLO_POISSON:
        if (scanned[iArg].n_items<2)
          SDDS_Bomb("invalid -poisson syntax");
        if (!(seqRequest = SDDS_Realloc(seqRequest, sizeof(*seqRequest)*(seqRequests+1))))
          SDDS_Bomb("memory allocation failure");
        memset(seqRequest+seqRequests, 0, sizeof(*seqRequest));
        scanned[iArg].n_items -= 1;
        memset(seqRequest+seqRequests, 0, sizeof(*seqRequest));
        seqRequest[seqRequests].randomizationGroup = -1;
        seqRequest[seqRequests].mean = 1;
        if (!scanItemList(&seqRequest[seqRequests].flags, 
                          scanned[iArg].list+1, &scanned[iArg].n_items, 0,
                          "columnName", SDDS_STRING, &seqRequest[seqRequests].outputName, 1, SEQ_OUTPUTNAME,
                          "meanValue", SDDS_STRING, &meanPar, 1, 0,
                          "units", SDDS_STRING, &seqRequest[seqRequests].units, 1, SEQ_UNITSGIVEN, 
                          NULL))
          SDDS_Bomb("invalid -poisson syntax");
        seqRequest[seqRequests].flags |= SEQ_DIRECT_POISSON; 
        if (!(seqRequest[seqRequests].flags&SEQ_OUTPUTNAME) || !(seqRequest[seqRequests].outputName))
          SDDS_Bomb("columnName is not provided for uniform distribution/");
        if (meanPar) {
          if (wild_match(meanPar, "@*"))
            SDDS_CopyString(&seqRequest[seqRequests].meanPar, meanPar+1);
          else if (!get_double(&seqRequest[seqRequests].mean, meanPar))  
            SDDS_Bomb("Invalid value given for mean value of -poisson distribution.");
          free(meanPar);
          meanPar = NULL;
        } 
        seqRequests ++;
        scanned[iArg].n_items += 1;
        break;
      case CLO_SAMPLES:
        if (scanned[iArg].n_items!=2 ||
            sscanf(scanned[iArg].list[1], "%ld", &samples)!=1 || 
            samples<=0)
          SDDS_Bomb("invalid -samples syntax");
        break;
      case CLO_SEED:
        if (scanned[iArg].n_items!=2 ||
            sscanf(scanned[iArg].list[1], "%ld", &randomNumberSeed)!=1 || 
            randomNumberSeed<=0)
          SDDS_Bomb("invalid -seed syntax");
        break;
      case CLO_PIPE:
        if (!processPipeOption(scanned[iArg].list+1, scanned[iArg].n_items-1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      case CLO_VERBOSE:
        verbose = 1;
        break;
      case CLO_OPTIMAL_HALTON:
        optimalHalton = 1;
        break;
      default:
        fprintf(stderr, "error: unknown/ambiguous option: %s\n", 
                scanned[iArg].list[0]);
        exit(1);
        break;
      }
    }
    else {
      if (!input)
        input = scanned[iArg].list[0];
      else if (!output)
        output = scanned[iArg].list[0];
      else
        SDDS_Bomb("too many filenames seen");
    }
  }
  
  if (!seqRequests)
    SDDS_Bomb("give one or more -columns options");
  if (samples<1)
    SDDS_Bomb("-samples option not given");

  for (i=0; i<seqRequests; i++) {
    if (!(seqRequest[i].flags&
          (SEQ_DATAFILE|SEQ_DIRECT_GAUSSIAN|SEQ_DIRECT_UNIFORM|SEQ_DIRECT_POISSON)))
      break;
  }
  if (i==seqRequests) {
    /* all columns options have either their own input files or else use
     * one of the "direct" distributions.  Hence, we don't expect an input
     * file.
     */
    if (!input)
      pipeFlags |= USE_STDIN;   /* not really, but fakes out processFilenames */
    if (input && !output) {
      output = input;
      input = NULL;
      pipeFlags |= USE_STDIN;
      if (fexists(output)) {
        sprintf(msgBuffer, "%s exists already (sddssampledist)", output);
        SDDS_Bomb(msgBuffer);
      }
    }
  }
  
  processFilenames("sddssampledist", &input, &output, pipeFlags, 0, NULL);
  
  if (!SDDS_InitializeOutput(&SDDSout, SDDS_BINARY, 0, NULL, NULL, output))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (verbose)
    fprintf(stderr, "Initialized output file %s\n", output);
  
  /* open and check input files */
  for (i=mainInputOpened=0; i<seqRequests; i++) {
    if (seqRequest[i].flags&SEQ_DIRECT_GAUSSIAN) {
      if (seqRequest[i].meanPar || seqRequest[i].sigmaPar) {
        if (!mainInputOpened) {
          if (!SDDS_InitializeInput(&SDDSin, input) ||
              !SDDS_TransferAllParameterDefinitions(&SDDSout, &SDDSin, 0))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          mainInputOpened = 1;
        }
        requireInput = 1;
        SDDSptr = &SDDSin; 
        if ((seqRequest[i].meanPar &&
             SDDS_CheckParameter(SDDSptr, seqRequest[i].meanPar, NULL, SDDS_ANY_NUMERIC_TYPE, stderr)!=SDDS_CHECK_OK) ||
            (seqRequest[i].sigmaPar &&
             SDDS_CheckParameter(SDDSptr, seqRequest[i].sigmaPar, NULL, SDDS_ANY_NUMERIC_TYPE, stderr)!=SDDS_CHECK_OK)) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
      }
      if (!SDDS_DefineSimpleColumn(&SDDSout, seqRequest[i].outputName, NULL, SDDS_DOUBLE)) 
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
    } else if (seqRequest[i].flags&SEQ_DIRECT_UNIFORM) {
      if (seqRequest[i].minPar || seqRequest[i].maxPar) {
        if (!mainInputOpened) {
          if (!SDDS_InitializeInput(&SDDSin, input) ||
              !SDDS_TransferAllParameterDefinitions(&SDDSout, &SDDSin, 0))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          mainInputOpened = 1;
        }
        requireInput = 1;
        SDDSptr = &SDDSin;
        if ((seqRequest[i].minPar &&
             SDDS_CheckParameter(SDDSptr, seqRequest[i].minPar, NULL, SDDS_ANY_NUMERIC_TYPE, stderr)!=SDDS_CHECK_OK) ||
            (seqRequest[i].maxPar &&
             SDDS_CheckParameter(SDDSptr, seqRequest[i].maxPar, NULL, SDDS_ANY_NUMERIC_TYPE, stderr)!=SDDS_CHECK_OK)) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
      }
      if (!SDDS_DefineSimpleColumn(&SDDSout, seqRequest[i].outputName, NULL, SDDS_DOUBLE))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    } else if (seqRequest[i].flags&SEQ_DIRECT_POISSON) {
      if (seqRequest[i].meanPar) {
        if (!mainInputOpened) {
          if (!SDDS_InitializeInput(&SDDSin, input) ||
              !SDDS_TransferAllParameterDefinitions(&SDDSout, &SDDSin, 0))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          mainInputOpened = 1;
        }
        requireInput = 1;
        SDDSptr = &SDDSin;
        if ( SDDS_CheckParameter(SDDSptr, seqRequest[i].meanPar, NULL, SDDS_ANY_NUMERIC_TYPE, stderr)!=SDDS_CHECK_OK) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
      }
      if (!SDDS_DefineSimpleColumn(&SDDSout, seqRequest[i].outputName, NULL, SDDS_LONG))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    } else {     
      if (seqRequest[i].flags&SEQ_RANDOMIZE) {
        long newGroupID=0;
        /* define randomization groups */
        if (seqRequest[i].flags&SEQ_RANDOMGROUP) {
          newGroupID = seqRequest[i].randomizationGroup;
          for (j=0; j<randomizationGroups; j++)
            if (randomizationData[j].group==newGroupID) {
              newGroupID = 0;
              break;
            }
        } else {
          seqRequest[i].randomizationGroup = newGroupID = -(i+1);
        }
        if (newGroupID!=0) {
          if (!(randomizationData = 
                SDDS_Realloc(randomizationData,
                             sizeof(*randomizationData)*(randomizationGroups+1))))
            SDDS_Bomb("memory allocation failure");
          randomizationData[randomizationGroups].group = newGroupID;
          randomizationData[randomizationGroups].order = NULL;
          randomizationGroups ++;
        }
      }
      if (seqRequest[i].flags&SEQ_DATAFILE) {
        if (!SDDS_InitializeInput(&seqRequest[i].SDDSin, 
                                  seqRequest[i].dataFileName))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        SDDSptr = &seqRequest[i].SDDSin;
      } else {
        if (!mainInputOpened) {
          if (!SDDS_InitializeInput(&SDDSin, input) ||
              !SDDS_TransferAllParameterDefinitions(&SDDSout, &SDDSin, 0))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          mainInputOpened = 1;
        }
        requireInput = 1;
        SDDSptr = &SDDSin;
      }
      if (SDDS_CheckColumn(SDDSptr,
                           seqRequest[i].indepName, NULL, SDDS_ANY_NUMERIC_TYPE,
                           stderr)!=SDDS_CHECK_OK  ||
          ((seqRequest[i].flags&SEQ_CDFNAME) &&
           SDDS_CheckColumn(SDDSptr, seqRequest[i].CDFName, NULL, SDDS_ANY_NUMERIC_TYPE,
                            stderr)!=SDDS_CHECK_OK) ||
          ((seqRequest[i].flags&SEQ_DFNAME) &&
           SDDS_CheckColumn(SDDSptr, seqRequest[i].DFName, NULL, SDDS_ANY_NUMERIC_TYPE,
                            stderr)!=SDDS_CHECK_OK) ||
          !SDDS_TransferColumnDefinition(&SDDSout, SDDSptr,
                                         seqRequest[i].indepName,
                                         seqRequest[i].outputName)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
      } 
    }
    
    if (seqRequest[i].flags&SEQ_UNITSGIVEN &&
        !SDDS_ChangeColumnInformation(&SDDSout, "units", seqRequest[i].units,
                                      SDDS_SET_BY_NAME, 
                                      seqRequest[i].outputName))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  if (verbose)
    fprintf(stderr, "Initialized input files\n");

  if (!SDDS_WriteLayout(&SDDSout))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  if (randomNumberSeed==0) {
    randomNumberSeed = (long)time((time_t *) NULL);
    randomNumberSeed = 2*(randomNumberSeed/2) + 1;
#if defined(_WIN32)
    random_1(-labs(randomNumberSeed));
#else
    random_1(-FABS(randomNumberSeed));
#endif
  } else
    random_1(-randomNumberSeed);
  
  if (!((sample = calloc(sizeof(*sample), samples))))
    SDDS_Bomb("memory allocation failure");
  while (1) {
    if (verbose)
      fprintf(stderr, "Beginning page loop\n");
    if (input && SDDS_ReadPage(&SDDSin)<=0)
      break;
    for (i=0; i<seqRequests; i++) {
      if (seqRequest[i].flags&SEQ_DATAFILE &&
          SDDS_ReadPage(&seqRequest[i].SDDSin)<=0)
        break;
    }
    if (i!=seqRequests)
      break;
    if (!SDDS_StartPage(&SDDSout, samples)  ||
        (input && !SDDS_CopyParameters(&SDDSout, &SDDSin)))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (verbose)
      fprintf(stderr, "Defining randomization tables\n");
    /* define randomization tables */
    for (i=0; i<randomizationGroups; i++) {
      if (!(randomizationData[i].order=
            SDDS_Malloc(sizeof(*randomizationData[i].order)*samples)))
        SDDS_Bomb("memory allocation failure");
      for (j=0; j<samples; j++)
        randomizationData[i].order[j] = j;
      randomizeOrder((char*)randomizationData[i].order,
                     sizeof(*randomizationData[i].order), samples, 0,
                     random_1);
    }
    if (verbose)
      fprintf(stderr, "Beginning loop over sequence requests\n");
    for (i=0; i<seqRequests; i++) {
      if (verbose)
        fprintf(stderr, "Processing sequence request %ld\n", i);
      if (seqRequest[i].flags&SEQ_DIRECT_GAUSSIAN) {
        if ((seqRequest[i].meanPar && !SDDS_GetParameterAsDouble(&SDDSin, seqRequest[i].meanPar, &seqRequest[i].mean)) ||
            (seqRequest[i].sigmaPar && !SDDS_GetParameterAsDouble(&SDDSin, seqRequest[i].sigmaPar, &seqRequest[i].sigma)))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        for (j=0; j<samples; j++)
          sample[j] = gauss_rn_lim(seqRequest[i].mean, seqRequest[i].sigma, -1, random_1);
      } else if (seqRequest[i].flags&SEQ_DIRECT_UNIFORM) {
        if ((seqRequest[i].minPar && !SDDS_GetParameterAsDouble(&SDDSin, seqRequest[i].minPar, &seqRequest[i].min)) ||
            (seqRequest[i].maxPar && !SDDS_GetParameterAsDouble(&SDDSin, seqRequest[i].maxPar, &seqRequest[i].max)))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        for (j=0; j<samples; j++) 
          sample[j] = seqRequest[i].min + (seqRequest[i].max - seqRequest[i].min) * random_1(1);
      } else if (seqRequest[i].flags&SEQ_DIRECT_POISSON) {
        double *pos_x, *pos_cdf, CDF;
        long pos_points, code;
        pos_x = pos_cdf = NULL;
        if ((seqRequest[i].meanPar && !SDDS_GetParameterAsDouble(&SDDSin, seqRequest[i].meanPar, &seqRequest[i].mean)))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        pos_points = CreatePoissonDistributionTable(&pos_x, &pos_cdf, seqRequest[i].mean);
        
        for (j=0; j<samples; j++) {
          CDF = random_1(1);
          sample[j]= (int)(interp(pos_x, pos_cdf, pos_points, CDF, 0, 1, &code));
        /*  fprintf(stderr, "%d, cdf=%f, sample=%f\n", j, CDF, sample[j]);*/
          
        }
        free(pos_x);
        free(pos_cdf);
      } else {
        if (input && !(seqRequest[i].flags&SEQ_DATAFILE))
          SDDSptr = &SDDSin;
        else
          SDDSptr = &seqRequest[i].SDDSin;
        if ((values = SDDS_CountRowsOfInterest(SDDSptr))) {
          if (!(IVValue 
                = SDDS_GetColumnInDoubles(SDDSptr, seqRequest[i].indepName)) ||
              (seqRequest[i].flags&SEQ_CDFNAME &&
               !(CDFValue 
                 = SDDS_GetColumnInDoubles(SDDSptr, seqRequest[i].CDFName))) ||
            (seqRequest[i].flags&SEQ_DFNAME &&
             !(CDFValue 
               = SDDS_GetColumnInDoubles(SDDSptr, seqRequest[i].DFName))))
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        } else {
          sprintf(msgBuffer, "empty page for file %s\n",
                  seqRequest[i].flags&SEQ_DATAFILE?
                  seqRequest[i].dataFileName:input);
          SDDS_Bomb(msgBuffer);
        }
        if (verbose)
          fprintf(stderr, "Checking and converting CDF/DF values\n");
        /* check/convert CDF/DF values */
        for (j=1; j<values; j++) {
          if (IVValue[j-1]>IVValue[j]) {
            sprintf(msgBuffer, "random variate values not monotonically increasing for %s", 
                    seqRequest[i].flags&SEQ_DATAFILE?
                    seqRequest[i].dataFileName:input);
            SDDS_Bomb(msgBuffer);
          }
          if (seqRequest[i].flags&SEQ_DFNAME) 
            /* convert DF to CDF */
            CDFValue[j] += CDFValue[j-1];
          if (CDFValue[j] < CDFValue[j-1]) {
            sprintf(msgBuffer, "CDF values decreasing for %s", 
                    seqRequest[i].flags&SEQ_DATAFILE?
                    seqRequest[i].dataFileName:input);
            SDDS_Bomb(msgBuffer);
          }
        }
        if (verbose)
          fprintf(stderr, "Normalizing CDF\n");
        /* normalize the CDF */
        if (CDFValue[values-1]<=0) {
          sprintf(msgBuffer, "CDF not valid for %s\n", 
                  seqRequest[i].dataFileName);
          SDDS_Bomb(msgBuffer);
        }
        for (j=0; j<values; j++) 
          CDFValue[j] /= CDFValue[values-1];
        if (seqRequest[i].flags&SEQ_HALTONRADIX) {
          if (verbose)
            fprintf(stderr, "Starting halton sequence, offset=%" PRId32 "\n", seqRequest[i].haltonOffset);
          if (!optimalHalton)
            haltonID = startHaltonSequence(&seqRequest[i].haltonRadix, 0.5);
          else
            haltonID = startModHaltonSequence(&seqRequest[i].haltonRadix, 0);
          while (seqRequest[i].haltonOffset-- >0) {
            if (!optimalHalton)
              nextHaltonSequencePoint(haltonID);
            else
              nextModHaltonSequencePoint(haltonID);
          }
        }
        if (verbose)
          fprintf(stderr, "Generating samples\n");
        for (j=0; j<samples; j++) {
          double CDF;
          long code;
          while (1) {
            if (seqRequest[i].flags&SEQ_HALTONRADIX) {
              if (!optimalHalton)
                CDF = nextHaltonSequencePoint(haltonID);
              else
                CDF = nextModHaltonSequencePoint(haltonID);
            }
            else 
              CDF = random_1(1);
            if (CDF<=CDFValue[values-1] && CDF>=CDFValue[0])
              break;
          }
          sample[j] 
            = seqRequest[i].factor*interp(IVValue, CDFValue, values, CDF, 0, 1, &code) 
              + seqRequest[i].offset;
        }
        if (seqRequest[i].flags&SEQ_RANDOMIZE) {
          long k, l;
          double *sample1;
          if (verbose)
            fprintf(stderr, "Randomizing order of values\n");
          if (!(sample1 = malloc(sizeof(*sample1)*samples)))
            SDDS_Bomb("memory allocation failure");
          for (l=0; l<randomizationGroups; l++) 
            if (randomizationData[l].group==seqRequest[i].randomizationGroup)
              break;
        if (l==randomizationGroups)
          SDDS_Bomb("problem with construction of randomization groups!");
          for (k=0; k<samples; k++)
            sample1[k] = sample[randomizationData[l].order[k]];
          free(sample);
          sample = sample1;
        } 
        free(IVValue);
        free(CDFValue);
      }
      if (verbose)
        fprintf(stderr, "Setting SDDS column values\n");
      if (!SDDS_SetColumnFromDoubles(&SDDSout, SDDS_SET_BY_NAME, 
                                     sample, samples, 
                                     seqRequest[i].outputName?
                                     seqRequest[i].outputName:
                                     seqRequest[i].indepName))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
    }
    if (verbose)
      fprintf(stderr, "Writing data page\n");
    if (!SDDS_WritePage(&SDDSout))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!requireInput)
      break;
  }
  if (verbose)
    fprintf(stderr, "Exited read loop\n");
  free(sample);
  if ((input && !SDDS_Terminate(&SDDSin)) || !SDDS_Terminate(&SDDSout))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  for (i=0; i<seqRequests; i++) {
    if (seqRequest[i].dataFileName) free(seqRequest[i].dataFileName);
    if (seqRequest[i].indepName) free(seqRequest[i].indepName);
    if (seqRequest[i].outputName) free(seqRequest[i].outputName);
    if (seqRequest[i].DFName) free(seqRequest[i].DFName);
    if (seqRequest[i].CDFName) free(seqRequest[i].CDFName);
    if (seqRequest[i].units) free(seqRequest[i].units);
    if (seqRequest[i].meanPar) free(seqRequest[i].meanPar);
    if (seqRequest[i].sigmaPar) free(seqRequest[i].sigmaPar);
    if (seqRequest[i].minPar) free(seqRequest[i].minPar);
    if (seqRequest[i].maxPar) free(seqRequest[i].maxPar); 
    if (seqRequest[i].flags&SEQ_DATAFILE && !SDDS_Terminate(&(seqRequest[i].SDDSin)))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  free(seqRequest);
  for (i=0; i<randomizationGroups; i++)
    free(randomizationData[i].order);
  if (randomizationData) free(randomizationData);
  
  free_scanargs(&scanned, argc);
  
  return(0);
}
コード例 #5
0
ファイル: sddstranspose.c プロジェクト: veprbl/epics-sdds
int main(int argc, char **argv)
{
  SCANNED_ARG *s_arg;
  SDDS_DATASET inputPage, outputPage;
  
  char *inputfile, *outputfile;
  char **inputColumnName, **inputStringColumnName, **inputDoubleColumnName;
  char **outputStringColumnName, **outputDoubleColumnName, **matchColumn=NULL;
  long inputRows, inputDoubleColumns, inputStringColumns, indexColumn=0, matchColumns=0, noOldColumnNamesColumn=0;
  long outputRows, outputDoubleColumns, outputStringColumns;
  char **inputParameterName;
  int32_t inputParameters, inputColumns;
  char *inputDescription, *inputContents;
  char *outputDescription;
  long i, i_arg, col;
  char *buffer;
  char **columnOfStrings;
  long buffer_size;
#define BUFFER_SIZE_INCREMENT 16384
  MATRIX *R, *RInv;
  long OldStringColumnsDefined;
  char *inputStringRows, *outputStringRows;
  char **stringArray, *stringParameter;
  long token_length;
  long verbose;
  char format[32];
  long digits;
  char *Symbol, *Root;
  void *parameterPointer;
  long ascii;
  unsigned long pipeFlags, majorOrderFlag;
  long tmpfile_used, noWarnings;
  long ipage=0, columnType;
  char *oldColumnNames, *newColumnNamesColumn;
  short columnMajorOrder=-1;
  
  inputColumnName = outputStringColumnName = outputDoubleColumnName = inputParameterName = NULL;
  outputRows = outputDoubleColumns = outputStringColumns = OldStringColumnsDefined = 0;

  SDDS_RegisterProgramName(argv[0]);

  argc = scanargs(&s_arg, argc, argv);
  if (argc==1) 
    bomb(NULL,  USAGE);

  inputfile = outputfile = NULL;
  verbose = 0;
  Symbol = Root = NULL;
  ascii = 0;
  digits=3;
  pipeFlags = 0;
  tmpfile_used = 0;
  noWarnings = 0;
  oldColumnNames = NULL;
  newColumnNamesColumn = NULL;
  
  for (i_arg=1; i_arg<argc; i_arg++) {
    if (s_arg[i_arg].arg_type==OPTION) {
      switch(match_string(s_arg[i_arg].list[0], commandline_option, COMMANDLINE_OPTIONS, 
                          UNIQUE_MATCH)) {
      case CLO_MAJOR_ORDER:
        majorOrderFlag=0;
        s_arg[i_arg].n_items--;
        if (s_arg[i_arg].n_items>0 &&
            (!scanItemList(&majorOrderFlag, s_arg[i_arg].list+1, &s_arg[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 CLO_MATCH_COLUMN:
        matchColumns = s_arg[i_arg].n_items-1;
        matchColumn = s_arg[i_arg].list+1;
        break;
      case CLO_INDEX_COLUMN:
        indexColumn = 1;
        break;
      case CLO_NO_OLDCOLUMNNAMES:
        noOldColumnNamesColumn = 1;
        break;
      case CLO_VERBOSE:
        verbose=1;
        break;
      case CLO_ASCII:
        ascii=1;
        break;
      case CLO_DIGITS:
        if (!(get_long(&digits, s_arg[i_arg].list[1])))
          bomb("no string given for option -digits", USAGE);
        break;
      case CLO_COLUMNROOT:
        if (!(Root=s_arg[i_arg].list[1]))
          SDDS_Bomb("No root string given");
        break;
      case CLO_SYMBOL:
        if (!(Symbol=s_arg[i_arg].list[1]))
          SDDS_Bomb("No symbol string given");
        break;
      case CLO_PIPE:
        if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      case CLO_OLDCOLUMNNAMES:
        if (!(oldColumnNames=s_arg[i_arg].list[1]))
          SDDS_Bomb("No oldColumnNames string given");
        break;
      case CLO_NEWCOLUMNNAMES:
        if (s_arg[i_arg].n_items!=2 ||
            SDDS_StringIsBlank(newColumnNamesColumn = s_arg[i_arg].list[1]))
          SDDS_Bomb("Invalid -newColumnNames syntax/value");
        break;
      default:
        bomb("unrecognized option given", USAGE);
      }
    }
    else {
      if (!inputfile)
        inputfile = s_arg[i_arg].list[0];
      else if (!outputfile)
        outputfile = s_arg[i_arg].list[0];
      else
        bomb("too many filenames given", USAGE);
    }
  }

  processFilenames("sddstranpose", &inputfile, &outputfile, pipeFlags, noWarnings, &tmpfile_used);
  if (newColumnNamesColumn && Root) 
    SDDS_Bomb("-root and -newColumnNames are incompatible");
  
  if (!SDDS_InitializeInput(&inputPage, inputfile) ||
      !(inputParameterName=(char**)SDDS_GetParameterNames(&inputPage, &inputParameters)) ||
      !SDDS_GetDescription(&inputPage, &inputDescription, &inputContents))
    SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
  if (matchColumns) 
    inputColumnName = getMatchingSDDSNames(&inputPage, matchColumn, matchColumns, &inputColumns, SDDS_MATCH_COLUMN); 
  else {
    if (!(inputColumnName=(char**)SDDS_GetColumnNames(&inputPage, &inputColumns)))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
  }
  
  inputDoubleColumns=0;
  inputStringColumns=0;
  inputDoubleColumnName=(char**)malloc(inputColumns*sizeof(char*));
  inputStringColumnName=(char**)malloc(inputColumns*sizeof(char*));
  inputRows = 0;
  /***********                                  \
   * read data *
   \***********/
  while (0<SDDS_ReadTable(&inputPage)) {
    ipage ++;
#if defined(DEBUG)
    fprintf(stderr, "working on page %ld\n", ipage);
#endif
    if (ipage==1) {
      SDDS_DeferSavingLayout(1);
      if( !SDDS_SetColumnFlags(&inputPage, 0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
      /* count the string and numerical columns in the input file */
      for (i=0;i<inputColumns;i++) {
        if ( SDDS_NUMERIC_TYPE( columnType = SDDS_GetColumnType( &inputPage, i))) {
          inputDoubleColumnName[inputDoubleColumns]=inputColumnName[i];
          inputDoubleColumns++;
        }
      }
      for (i=0; i<inputPage.layout.n_columns; i++) {
        if (inputPage.layout.column_definition[i].type == SDDS_STRING ) {
          inputStringColumnName[inputStringColumns] = inputPage.layout.column_definition[i].name;
          inputStringColumns++;
        }
      }
      if( !(inputRows=SDDS_CountRowsOfInterest(&inputPage)))
        SDDS_Bomb("No rows in dataset.");
    }
    else {
      /* these statements are executed on the subsequent pages */
      if (inputRows != SDDS_CountRowsOfInterest(&inputPage)) {
        SDDS_Bomb("Datasets don't have the same number of rows.\nProcessing stopped before reaching the end of the input file.");
      }
    }
#if defined(DEBUG)
    fprintf(stderr, "row flags set\n");
#endif
    if (inputDoubleColumns == 0)
      SDDS_Bomb("No numerical columns in file.");
    if ((ipage==1) && verbose) {
      fprintf(stderr, "No. of double/float/integer columns: %ld.\n", inputDoubleColumns);
      fprintf(stderr, "No. of string columns: %ld.\n", inputStringColumns);
      fprintf(stderr, "No. of rows: %ld.\n", inputRows);
    }
    /****************\
     * transpose data *
     \****************/
    if (inputDoubleColumns) {
      if (ipage == 1) {
        m_alloc(&RInv, inputRows, inputDoubleColumns);
        m_alloc(&R, inputDoubleColumns, inputRows);
      }
      for (col=0;col<inputDoubleColumns;col++){
        if (!(R->a[col]=(double*)SDDS_GetColumnInDoubles(&inputPage, inputDoubleColumnName[col]))) {
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
      if (verbose) {
        m_show(R, "%9.6le ", "Transpose of input matrix:\n", stdout);
      }
      m_trans(RInv, R);
    }
    /***************************\
     * determine existence of    *
     * transposed string columns *
     \***************************/
    if (ipage == 1) {
      OldStringColumnsDefined=0;
      switch(SDDS_CheckParameter(&inputPage, OLD_STRING_COLUMN_NAMES, NULL, SDDS_STRING, NULL)){
      case SDDS_CHECK_OKAY:
        OldStringColumnsDefined=1;
        break;
      case SDDS_CHECK_NONEXISTENT:
        break;
      case SDDS_CHECK_WRONGTYPE:
      case SDDS_CHECK_WRONGUNITS:
        fprintf(stderr, "Something wrong with parameter OldStringColumns.\n"); 
        exit(1);
        break;
      }
      if (OldStringColumnsDefined){
        /* decompose OldStringColumns into names of string columns for the output file */
        if (!SDDS_GetParameter(&inputPage, OLD_STRING_COLUMN_NAMES, &inputStringRows))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        if (verbose) {
          fprintf(stderr, "Parameter OldStringColumns: %s.\n", inputStringRows);
        }
        outputStringColumnName=(char**)malloc(sizeof(char*));
        outputStringColumns=0;
        buffer_size=BUFFER_SIZE_INCREMENT;
        buffer=(char*)malloc(sizeof(char)*buffer_size);
        while ( 0 <= (token_length = SDDS_GetToken(inputStringRows, buffer, BUFFER_SIZE_INCREMENT))){
          if (!token_length)
            SDDS_Bomb("A null string was detected in parameter OldStringColumns.\n");
          if (!SDDS_CopyString(&outputStringColumnName[outputStringColumns], buffer))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          if (verbose) {
            fprintf(stderr, "Output string column: %s\n", outputStringColumnName[outputStringColumns]);
          }
          outputStringColumns++;
        }
      }
    }
    
    /*********************\
     * define output page *
     \*********************/
    if ( ipage == 1 ) {
      outputRows = inputDoubleColumns;
      outputDoubleColumns = inputRows;
      if (inputDescription){
        outputDescription = (char*) malloc( sizeof(char) * (strlen("Transpose of ") + strlen(inputDescription) + 1));
        strcat(strcpy(outputDescription, "Transpose of "), inputDescription);
        if (!SDDS_InitializeOutput(&outputPage, ascii?SDDS_ASCII:SDDS_BINARY, 1, outputDescription, inputContents, outputfile))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      else {
        if (!SDDS_InitializeOutput(&outputPage, ascii?SDDS_ASCII:SDDS_BINARY, 1, NULL, NULL, outputfile))
          SDDS_PrintErrors(stdout, 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;
      /***********************************\
       * define names for double columns *
       \***********************************/
      if (!Root && inputStringColumns ) {
        /* use specified string column, or first string column encountered */
        if (!newColumnNamesColumn)
          /* first string column encountered */
          outputDoubleColumnName = (char**) SDDS_GetColumn(&inputPage, inputStringColumnName[0]);
        else {
          /* use specified string column */
          if (SDDS_CheckColumn(&inputPage, newColumnNamesColumn, NULL, SDDS_STRING, stderr)!=SDDS_CHECK_OKAY)
            SDDS_Bomb("column named with -newColumnNames does not exist in input");
          outputDoubleColumnName = (char**)SDDS_GetColumn(&inputPage, newColumnNamesColumn);
        }
        for (i=1; i<inputRows; i++) {
          
          if (match_string(outputDoubleColumnName[i-1], outputDoubleColumnName+i, inputRows-i, EXACT_MATCH)>=0) {
            fprintf(stderr, "Error, duplicate %s found in input file string column %s, can not be used as output column names\n",  outputDoubleColumnName[i-1], newColumnNamesColumn ? newColumnNamesColumn : inputStringColumnName[0]);
            exit(1);
          }
        }
      }
      else {
        /* use command line options to produce column names in the output file */
        outputDoubleColumnName = (char**) malloc( outputDoubleColumns * sizeof(char*) );
        digits = MAX(digits, log10(inputRows) + 1);
        if (!Root){
          Root = (char*) malloc( sizeof(char) * (strlen("Column")+1) );
          strcpy(Root, "Column");
        }
        if (outputDoubleColumns!=1) {
          for ( i=0; i < outputDoubleColumns; i++){
            outputDoubleColumnName[i] = (char*) malloc( sizeof(char) * (strlen(Root)+digits+1));
            sprintf(format, "%s%%0%ldld", Root, digits);
            sprintf(outputDoubleColumnName[i], format, i);
          }
        }
        else {/* only one row to transpose */
          outputDoubleColumnName[0] = (char*) malloc( sizeof(char) * (strlen(Root)+1));
          strcpy( outputDoubleColumnName[0], Root);
        }
      }
      
      
      /*************************\
       * define string columns *
       \*************************/
      if (OldStringColumnsDefined) {
        if (!SDDS_DefineSimpleColumns(&outputPage, outputStringColumns, 
                                      outputStringColumnName, NULL, SDDS_STRING))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      else {
        /* by default there should be at least one string column, that of the old column names. */
        if (!noOldColumnNamesColumn) {
          outputStringColumns = 1;
          outputStringColumnName = (char**) malloc( sizeof(char*));
          if (oldColumnNames) {
            /* commanline option specification */
            outputStringColumnName[0] = oldColumnNames;
          }
          else {
            outputStringColumnName[0] = (char*) malloc( sizeof(char) * (strlen("OldColumnNames") + 1));
            strcpy(outputStringColumnName[0], "OldColumnNames");
          }
          if ( 0 > SDDS_DefineColumn(&outputPage, outputStringColumnName[0], NULL, NULL, NULL, NULL, SDDS_STRING, 0))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
      if (indexColumn && !SDDS_DefineSimpleColumn(&outputPage, "Index", NULL, SDDS_LONG))
        SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      /*************************\
       * define double columns *
       \*************************/
      for ( i=0; i < outputDoubleColumns; i++)
        if (Symbol){
          if (0>SDDS_DefineColumn(&outputPage, outputDoubleColumnName[i], Symbol, NULL, NULL, 
                                  NULL, SDDS_DOUBLE, 0))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
        else {
          if (0>SDDS_DefineColumn(&outputPage, outputDoubleColumnName[i], NULL, NULL, NULL, 
                                  NULL, SDDS_DOUBLE, 0))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      /********************************\
       * define string parameters       *
       * i.e. transposed string columns *
       \********************************/
      if ( inputStringColumns>1 ) {
        if (0>SDDS_DefineParameter(&outputPage, OLD_STRING_COLUMN_NAMES, 
                                   NULL, NULL, "Transposed string columns", NULL, SDDS_STRING, 
                                   NULL))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        for ( i=0; i < inputStringColumns; i++){
          if (0>SDDS_DefineParameter(&outputPage, inputStringColumnName[i], NULL, NULL, "Transposed string column data", NULL, 
                                     SDDS_STRING, NULL))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
      
      /*************************\
       * transfer parameters not *
       * associated with old     *
       * string columns          *
       \*************************/
      if (inputParameters) {
        for ( i=0; i < inputParameters; i++) {
          if ( (0 > match_string(inputParameterName[i], outputStringColumnName, outputStringColumns, 0) &&
                strcasecmp(inputParameterName[i], OLD_STRING_COLUMN_NAMES)))
            if ( 0 > SDDS_TransferParameterDefinition(&outputPage, &inputPage, inputParameterName[i], NULL))
              SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
      
      /***************\
       * write layout *
       \***************/
      SDDS_DeferSavingLayout(0);
      /* if InputFile is not already transfered ot the output file, then create it. */
      switch( SDDS_CheckParameter(&outputPage, "InputFile", NULL, SDDS_STRING, NULL) ) {
      case SDDS_CHECK_NONEXISTENT:
        if (0>SDDS_DefineParameter(&outputPage, "InputFile", NULL, NULL, "Original matrix file", NULL, SDDS_STRING, NULL))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        break;
      default:
        break;
      }
      if (!SDDS_WriteLayout(&outputPage) )
        SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
#if defined(DEBUG)
    fprintf(stderr, "table layout defined\n");
#endif

    if (!SDDS_StartTable(&outputPage, outputRows) )
      SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (ipage == 1) {
      if (!SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 
                              "InputFile", inputfile?inputfile:"pipe", NULL))
        SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    /***************************************\
     * assign string columns    from input *
     * to     string parameters in output  *
     \**************************************/
    if ( inputStringColumns > 1) {
      for ( i=0; i < inputStringColumns; i++){
        columnOfStrings = (char**) SDDS_GetColumn(&inputPage, inputStringColumnName[i]);
        stringParameter = JoinStrings(columnOfStrings, inputRows, BUFFER_SIZE_INCREMENT);
        if ( !SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 
                                 inputStringColumnName[i], stringParameter, NULL))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        free(columnOfStrings);
        free(stringParameter);
      }
      outputStringRows = JoinStrings(inputStringColumnName, inputStringColumns, BUFFER_SIZE_INCREMENT);
      if (!SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 
                              OLD_STRING_COLUMN_NAMES, outputStringRows, NULL))
        SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    
#if defined(DEBUG)
    fprintf(stderr, "string parameters assigned\n");
#endif
    
    if (inputParameters){
      for ( i=0; i < inputParameters; i++){
        if ( (0 > match_string(inputParameterName[i], outputStringColumnName, outputStringColumns, 0) &&
              strcasecmp(inputParameterName[i], OLD_STRING_COLUMN_NAMES))) {
          parameterPointer = (void*) SDDS_GetParameter(&inputPage, inputParameterName[i], NULL);
          if (!SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_REFERENCE, 
                                  inputParameterName[i], parameterPointer, NULL))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          free(parameterPointer);
        }
      }
    }
#if defined(DEBUG)
    fprintf(stderr, "input parameters assigned\n");
#endif
    
    /**********************************\
     * assign data to                   *
     * output table part of data set    *
     \**********************************/
    if (outputRows) {
      /***************************\
       * assign string column data *
       \***************************/
      if (OldStringColumnsDefined){
        for ( i=0 ; i < outputStringColumns; i++){
          if (!SDDS_GetParameter(&inputPage, outputStringColumnName[i], &stringParameter))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          stringArray=TokenizeString(stringParameter, outputRows);
          if (!SDDS_SetColumn(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_REFERENCE, 
                              stringArray, outputRows, outputStringColumnName[i]))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }
      else {
        if (!noOldColumnNamesColumn && !SDDS_SetColumn(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_REFERENCE, 
                            inputDoubleColumnName, outputRows, outputStringColumnName[0]))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
#if defined(DEBUG)
      fprintf(stderr, "string data columns assigned\n");
#endif
      /***************************\
       * assign double column data *
       \***************************/
      for ( i=0 ; i < outputDoubleColumns; i++) /* i is the row index */
        if (!SDDS_SetColumn(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_REFERENCE, 
                            RInv->a[i], outputRows, outputDoubleColumnName[i]))
          SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      if (indexColumn) {
        for (i=0; i<outputRows; i++)
          if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, i, "Index", i, NULL))
            SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
#if defined(DEBUG)
      fprintf(stderr, "double data columns assigned\n");
#endif
    }
    
#if defined(DEBUG)
    fprintf(stderr, "data assigned\n");
#endif
    if (!SDDS_WriteTable(&outputPage))
      SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
#if defined(DEBUG)
    fprintf(stderr, "data written out\n");
#endif
  }    
  if (inputDoubleColumns) {
    m_free(&RInv);
    m_free(&R);
  }
  if (inputColumnName) {
    SDDS_FreeStringArray(inputColumnName, inputColumns);
    free(inputColumnName);
  }
  if (inputStringColumns)
    free(inputStringColumnName);
  if (inputDescription)
    free(inputDescription);
  if (inputParameterName) {
    SDDS_FreeStringArray(inputParameterName, inputParameters);
    free(inputParameterName);
  }
  if (outputDoubleColumns) {
    SDDS_FreeStringArray(outputDoubleColumnName, outputDoubleColumns);
    free(outputDoubleColumnName);
  }
  
  if (!SDDS_Terminate(&inputPage) || !SDDS_Terminate(&outputPage))
    SDDS_PrintErrors(stdout, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  if (tmpfile_used && !replaceFileAndBackUp(inputfile, outputfile)) 
    exit(1);
  return(0);
}