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

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

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

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

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

  if (!excludeColumns) {
    excludeColumn = defaultExcludedColumn;
    excludeColumns = DEFAULT_EXCLUDED_COLUMNS;
  }
  
  if (verbose)
    fprintf(stderr,"Reading file %s.\n",inputfile);
  SDDS_InitializeInput(&inputPage, inputfile);
  copiedPages = 0;
  while (SDDS_ReadTable(&inputPage)>0) {
    if (!copiedPages) {
      copiedPage = (SDDS_TABLE*)malloc(sizeof(SDDS_TABLE));
      rows = SDDS_CountRowsOfInterest(&inputPage);
    }
    else {
      copiedPage = (SDDS_TABLE*)realloc(copiedPage, (copiedPages+1)*sizeof(SDDS_TABLE));
    }
    if (!SDDS_InitializeCopy(&copiedPage[copiedPages], &inputPage, NULL, "m"))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    if (!SDDS_CopyTable(&copiedPage[copiedPages], &inputPage))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    copiedPages++;
  }
  if (copiedPages<2) {
    fprintf(stderr,"Insufficient data (i.e. number of data pages) to fit a straight line.\n");
    exit(1);
  }
  switch(SDDS_CheckColumn(&inputPage, "Rootname", NULL, SDDS_STRING, NULL)) {
  case SDDS_CHECK_WRONGUNITS:
  case SDDS_CHECK_OKAY:
    break;
  default:
    fprintf(stderr,"Something wrong with column %s.\n", "Rootname");
    exit(1);
  }
  switch(SDDS_CheckColumn(&inputPage, "Index", NULL, SDDS_LONG, NULL)) {
  case SDDS_CHECK_WRONGUNITS:
  case SDDS_CHECK_OKAY:
    generateIndex = 0;
    break;
  case SDDS_CHECK_NONEXISTENT:
    generateIndex = 1;
    break;
  default:
    fprintf(stderr,"Something wrong with column %s.\n", "Rootname");
    exit(1);
  }
  /****************\
   * make array of independent variable
   \**************/
  indVar = (double*)malloc(sizeof(*indVar)*copiedPages);
  switch(SDDS_CheckParameter(&inputPage, indParameterName, NULL, SDDS_DOUBLE, NULL)) {
  case SDDS_CHECK_WRONGUNITS:
  case SDDS_CHECK_OKAY:
    break;
  default:
    fprintf(stderr,"Something wrong with parameter %s.\n", indParameterName);
    exit(1);
  }
  for (iPage = 0; iPage<copiedPages; iPage++) {
    if (!SDDS_GetParameter(&copiedPage[iPage],indParameterName,&indVar[iPage])) 
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
  }
  if (!SDDS_GetParameterInformation(&inputPage, "units", &indVarUnits, SDDS_GET_BY_NAME, indParameterName))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (!indVarUnits) {
    indVarUnits = (char *) malloc(sizeof(*indVarUnits));
    indVarUnits[0] = 0;
  }
  /************************************\
   * get columns of interest. use set_multicolumn_flags to simply
   * return new values for array column.
   \*************************************/
  if (!set_multicolumn_flags(&inputPage, &column, &columns, excludeColumn, excludeColumns)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }
  /************************************\
   * make  column names for the output
   \*************************************/
  intColumn = (char**)malloc((sizeof(char*)*columns));
  slopeColumn = (char**)malloc((sizeof(char*)*columns)); 
  if (slopeErrors)
    slopeSigmaColumn = (char**)malloc((sizeof(char*)*columns));
  for (i=0; i<columns; i++) {
    intColumn[i] = (char*)malloc((sizeof(char)*(strlen(column[i])+strlen("Intercept")+1)));
    strcat(strcpy(intColumn[i], column[i]), "Intercept");
    slopeColumn[i] = (char*)malloc((sizeof(char)*(strlen(column[i])+strlen("Slope")+1)));
    strcat(strcpy(slopeColumn[i], column[i]), "Slope");
    if (slopeErrors) {
      slopeSigmaColumn[i] = (char*)malloc((sizeof(char)*(strlen(column[i])+strlen("SlopeSigma")+1)));
      strcat(strcpy(slopeSigmaColumn[i], column[i]), "SlopeSigma");
    }
  }
  /************************************\
   * Write layout for output file
   \*************************************/
  if (verbose)
    fprintf(stderr,"Opening file %s.\n",outputfile);
  if(!SDDS_InitializeOutput(&outputPage,SDDS_BINARY,1,
                            "lsf of sddsvexperiment",NULL,outputfile) ||
     0>SDDS_DefineParameter(&outputPage, "InputFile", "InputFile", NULL,
                            "InputFile", NULL, SDDS_STRING, 0) ||
     0>SDDS_DefineParameter(&outputPage, "IndependentVariable", "IndependentVariable", NULL,
                            "IndependentVariable", NULL, SDDS_STRING, 0) ||
     (0>SDDS_DefineColumn(&outputPage,"Index",NULL,NULL,"Rootname index",NULL,SDDS_LONG,0))||
     (0>SDDS_DefineColumn(&outputPage,"Rootname",NULL,NULL,NULL,NULL,SDDS_STRING,0)))
    SDDS_PrintErrors(stderr,SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
   if (columnMajorOrder!=-1)
     outputPage.layout.data_mode.column_major = columnMajorOrder;
   else
     outputPage.layout.data_mode.column_major = inputPage.layout.data_mode.column_major;
  for (iCol=0; iCol<columns; iCol++) {
    if (!SDDS_GetColumnInformation(&inputPage, "units", &Units, SDDS_GET_BY_NAME,column[iCol]))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!Units) {
      Units = (char*) malloc(sizeof(*Units));
      Units[0] = 0;
    }
    if (0>SDDS_DefineColumn(&outputPage, intColumn[iCol], NULL, Units, NULL, NULL, SDDS_DOUBLE,0))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    /* units for slopes columns */
    if (strlen(indVarUnits) && strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(Units)+strlen(indVarUnits)+2));
      strcat( strcat( strcpy(slopeUnits, Units), "/"), indVarUnits);
    }
    if (strlen(indVarUnits) && !strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(indVarUnits)+2));
      strcat( strcpy( slopeUnits, "1/"), indVarUnits);
    }
    if (!strlen(indVarUnits) && strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits)*(strlen(Units)+2));
      strcpy( slopeUnits, indVarUnits);
    }
    if (!strlen(indVarUnits) && !strlen(Units) ) {
      slopeUnits = (char*)malloc(sizeof(*slopeUnits));
      strcpy( slopeUnits, "");
    }
    if (0>SDDS_DefineColumn(&outputPage, slopeColumn[iCol], NULL, slopeUnits, NULL, NULL, SDDS_DOUBLE,0))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (slopeErrors) {
      if (0>SDDS_DefineColumn(&outputPage, slopeSigmaColumn[iCol], NULL, slopeUnits, NULL, NULL, SDDS_DOUBLE,0))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    free(slopeUnits);
  }
  if(!SDDS_WriteLayout(&outputPage) || 
     !SDDS_StartTable(&outputPage,rows) ||
     !SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                         "InputFile",inputfile?inputfile:"pipe",NULL)  ||
     !SDDS_SetParameters(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, 0,
                         "IndependentVariable", indParameterName, NULL) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  /************************************\
   * Copy columns to output file (usually columns Index and Rootname)
   \*************************************/
  copyColumns = DEFAULT_COPY_COLUMNS;
  copyColumn = defaultCopyColumn;
  if (!set_multicolumn_flags(&inputPage, &copyColumn, &copyColumns, NULL, 0)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    exit(1);
  }
  if(!SDDS_CopyColumns(&outputPage, &inputPage))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  depVar = (double*)malloc(sizeof(*depVar)*copiedPages);
  weight = (double*)malloc(sizeof(*weight)*copiedPages);
  diff = (double*)malloc(sizeof(*weight)*copiedPages);
  order=1;
  coef = (double*)malloc(sizeof(*coef)*(order+1));
  coefsigma = (double*)malloc(sizeof(*coefsigma)*(order+1));
  if(slopeErrors)
    slope = (double*)malloc(sizeof(*slope)*copiedPages);
  for (iCol=0; iCol<columns; iCol++) {
    for (iPage=0; iPage<copiedPages; iPage++) 
      weight[iPage]=1;
    if (verbose)
      fprintf(stderr,"Doing column %s.\n", column[iCol]);
    for (iRow=0; iRow<rows; iRow++) {
      for (iPage=0; iPage<copiedPages; iPage++) {
        if (!SDDS_GetValue(&copiedPage[iPage], column[iCol], iRow, &depVar[iPage]))                     
          SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
      }
      if (!(lsfn(indVar, depVar, weight, copiedPages, order, coef, coefsigma, &chi, diff))){
        fprintf(stderr,"Problem with call to lsfn\n.");
        exit(1);
      }
      if (generateIndex) {
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, iRow,
                               "Index",iRow,
                               intColumn[iCol], coef[0],
                               slopeColumn[iCol], coef[1], NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      else {
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, iRow,
                               intColumn[iCol], coef[0],
                               slopeColumn[iCol], coef[1], NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      if(slopeErrors){
        /* recalculate the slope with a subset of points  */
        slopeAve= slope2 = 0;
        for (iPage=0; iPage<copiedPages; iPage++) {
          weight[iPage] = 1e10;
          if(iPage)
            weight[iPage-1] = 1; 
          if (!(lsfn(indVar, depVar, weight, copiedPages, order, coef, coefsigma, &chi, diff))){
            fprintf(stderr,"Problem with call to lsfn\n.");
            exit(1);
          }
          slope[iPage] = coef[1];
          slopeAve += slope[iPage];
          slope2 += sqr(slope[iPage]);
        }
        slopeSigma = sqrt(slope2/copiedPages - sqr(slopeAve/copiedPages));
        if (!SDDS_SetRowValues(&outputPage, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, iRow,
                               slopeSigmaColumn[iCol], slopeSigma, NULL))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
    }
  }
 
  if( !SDDS_WriteTable(&outputPage)|| SDDS_Terminate(&inputPage) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  for (iPage=0; iPage<copiedPages; iPage++) {
    if( !SDDS_Terminate(&copiedPage[iPage]) )
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  if( SDDS_Terminate(&outputPage) )
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  if (tmpfile_used && !replaceFileAndBackUp(inputfile, outputfile)) 
    exit(1);
  SDDS_FreeStringArray(column, columns);
  free(column);
  SDDS_FreeStringArray(intColumn, columns);
  SDDS_FreeStringArray(slopeColumn, columns); 
  free(intColumn);
  free(slopeColumn);
  if (slopeErrors) {
    SDDS_FreeStringArray(slopeSigmaColumn, columns);
    free(slopeSigmaColumn);
  }
  
  free(copiedPage);
  free(indVar);
  free(depVar);
  if (weight)
    free(weight);
  if (diff)
    free(diff);
  if (slope)
    free(slope);
  if (coef) free(coef);
  if (coefsigma) free(coefsigma);
  if (Units) free(Units);
  if (indVarUnits) free(indVarUnits);
  
  free_scanargs(&scanned, argc);
  
  return(0);
}
예제 #2
0
파일: sddsslopes.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
  SCANNED_ARG *scanned;
  SDDS_TABLE inputPage, outputPage, residualPage;
  char *inputfile, *outputfile;
  char **column, **excludeColumn;
  int32_t columns;
  long excludeColumns;
  char *indColumnName;
  long verbose;
  long iArg, i, j, ipage;
  double *indVar, *indVarOrig;
  char *indVarUnits;
  char **intColumn, **slopeColumn, **slopeSigmaColumn, **interceptSigmaColumn;
  char *Units,*slopeUnits;
  double *depVar, *depVarOrig;
  long order;
  double *coef, *coefsigma, *weight, *diff, *diffOrig, chi;
  long iCol, iRow;
  long rows, rowsOrig;
  double rmsResidual;
  double slopeSigma, interceptSigma;
  char **sigmaColumn, **chiSquaredColumn;
  long *sigmaColumnExists;
  long doSlopeSigma, generateSigma, doPreliminaryFit;
  long validSigmas;
  double sigmaSum, averageSigma;
  long ascii;
  char *residualFile;
  unsigned long pipeFlags;
  long tmpfile_used, noWarnings;
  double xMin, xMax;

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

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

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

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

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

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

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

    if (residualFile) {
      if (!SDDS_WriteTable(&residualPage)) 
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    
    if (!SDDS_WriteTable(&outputPage)) 
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  if (residualFile) {
    if (!SDDS_Terminate(&residualPage))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  if(!SDDS_Terminate(&inputPage) || !SDDS_Terminate(&outputPage))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  
  if (tmpfile_used && !replaceFileAndBackUp(inputfile, outputfile)) 
    exit(1);
  return(0);
}
예제 #3
0
void track_through_ztransverse(double **part, long np, ZTRANSVERSE *ztransverse, double Po,
                               RUN *run, long i_pass, CHARGE *charge
                               )
{
  static double *posItime[2] = {NULL, NULL};     /* array for particle density times x, y*/
  static double *posIfreq;                       /* array for FFT of particle density times x or y*/
  static double *Vtime = NULL;           /* array for voltage acting on each bin */
  static long max_n_bins = 0;
  static long *pbin = NULL;              /* array to record which bin each particle is in */
  static double *time = NULL;            /* array to record arrival time of each particle */
  static double *pz = NULL;
  static long max_np = 0;
  double *Vfreq, *iZ;
#if USE_MPI
  long i;
#endif
  long ib, nb, n_binned, nfreq, iReal, iImag, plane, first;
  double factor, tmin, tmax, tmean, dt, userFactor[2], rampFactor=1;
  static long not_first_call = -1;
  long ip, ip1, ip2, bunches, bunch, npb, i_pass0;
  long bucketEnd[MAX_BUCKETS];
#if USE_MPI
  float *buffer_send, *buffer_recv;
#endif
#if defined(DEBUG)
  FILE *fp;
#endif
  i_pass0 = i_pass;
  if ((i_pass -= ztransverse->startOnPass)<0)
    return;
  
  if (i_pass>=(ztransverse->rampPasses-1))
    rampFactor = 1;
  else
    rampFactor = (i_pass+1.0)/ztransverse->rampPasses;
  
  not_first_call += 1;

#if (!USE_MPI)
  if (np>max_np) {
    pbin = trealloc(pbin, sizeof(*pbin)*(max_np=np));
    time = trealloc(time, sizeof(*time)*max_np);
    pz = trealloc(pz, sizeof(*pz)*max_np);
  }
#else
    if (USE_MPI) {
      long np_total;
      if (isSlave) {
	MPI_Allreduce(&np, &np_total, 1, MPI_LONG, MPI_SUM, workers);
	if (np_total>max_np) { 
	  /* if the total number of particles is increased, we do reallocation for every CPU */
	  pbin = trealloc(pbin, sizeof(*pbin)*(max_np=np));
	  time = trealloc(time, sizeof(*time)*max_np);
	  pz = trealloc(pz, sizeof(*pz)*max_np);
	  max_np = np_total; /* max_np should be the sum across all the processors */
	}
      }
    } 
#endif
  
  if ((part[0][6]-floor(part[0][6]))!=0) {
    /* This is a kludgey way to determine that particles have been assigned to buckets */
    printf("Bunched beam detected\n"); fflush(stdout);
#if USE_MPI
    if (n_processors!=1) {
      printf("Error (ZTRANSVERSE): must have bunch_frequency=0 for parallel mode.\n");
      MPI_Barrier(MPI_COMM_WORLD); /* Make sure the information can be printed before aborting */
      MPI_Abort(MPI_COMM_WORLD, 2);
    }
#endif
    /* Start by sorting in bucket order */
    qsort(part[0], np, COORDINATES_PER_PARTICLE*sizeof(double), comp_BucketNumbers);
    /* Find the end of the buckets in the particle list */
    bunches = 0;
    for (ip=1; ip<np; ip++) {
      if ((part[ip-1][6]-floor(part[ip-1][6]))!=(part[ip][6]-floor(part[ip][6]))) {
        /* printf("Bucket %ld ends with ip=%ld\n", bunches, ip-1); fflush(stdout); */
        bucketEnd[bunches++] = ip-1;
        if (bunches>=MAX_BUCKETS) {
            bombElegant("Error (wake): maximum number of buckets was exceeded", NULL);
          }
      }
    }
    bucketEnd[bunches++] = np-1;
  } else {
    bunches = 1;
    bucketEnd[0] = np-1;
  }
  /* printf("Bucket %ld ends with ip=%ld\n", bunches, bucketEnd[bunches-1]); fflush(stdout); */

  ip2 = -1;
  for (bunch=0; bunch<bunches; bunch++) {
    ip1 = ip2+1;
    ip2 = bucketEnd[bunch];
    npb = ip2-ip1+1;
    /* printf("Processing bunch %ld with %ld particles\n", bunch, npb); fflush(stdout); */
    /* Compute time coordinate of each particle */
    tmean = computeTimeCoordinates(time+ip1, Po, part+ip1, npb);
    find_min_max(&tmin, &tmax, time+ip1, npb);
#if USE_MPI
    find_global_min_max(&tmin, &tmax, np, workers);      
#endif
    if (bunch==0) {
      /* use np here since we need to compute the macroparticle charge */
      set_up_ztransverse(ztransverse, run, i_pass, np, charge, tmax-tmin);
    }
    nb = ztransverse->n_bins;
    dt = ztransverse->bin_size;
    tmin -= dt;
    tmax -= dt;
    if ((tmax-tmin)*2>nb*dt) {
      TRACKING_CONTEXT tcontext;
      getTrackingContext(&tcontext);
      fprintf(stderr, "%s %s: Time span of bunch (%le s) is more than half the total time span (%le s).\n",
              entity_name[tcontext.elementType],
              tcontext.elementName,
              tmax-tmin, nb*dt);
      fprintf(stderr, "If using broad-band impedance, you should increase the number of bins and rerun.\n");
      fprintf(stderr, "If using file-based impedance, you should increase the number of data points or decrease the frequency resolution.\n");
      exitElegant(1);
    }

    if (nb>max_n_bins) {
      posItime[0] = trealloc(posItime[0], 2*sizeof(**posItime)*(max_n_bins=nb));
      posItime[1] = trealloc(posItime[1], 2*sizeof(**posItime)*(max_n_bins=nb));
      posIfreq = trealloc(posIfreq, 2*sizeof(*posIfreq)*(max_n_bins=nb));
      Vtime = trealloc(Vtime, 2*sizeof(*Vtime)*(max_n_bins+1));
    }

    for (ib=0; ib<nb; ib++)
      posItime[0][2*ib] = posItime[0][2*ib+1] = 
        posItime[1][2*ib] = posItime[1][2*ib+1] = 0;

    /* make arrays of I(t)*x and I(t)*y */
    n_binned = binTransverseTimeDistribution(posItime, pz, pbin, tmin, dt, nb, 
                                             time+ip1, part+ip1, Po, npb,
                                             ztransverse->dx, ztransverse->dy,
                                             ztransverse->xDriveExponent, ztransverse->yDriveExponent);
#if (!USE_MPI)
    if (n_binned!=npb) {
      fprintf(stdout, "Warning: only %ld of %ld particles were binned (ZTRANSVERSE)!\n", n_binned, npb);
      if (!not_first_call) {
        fprintf(stdout, "*** This may produce unphysical results.  Your wake needs smaller frequency\n");
        fprintf(stdout, "    spacing to cover a longer time span.\n");
      }
      fflush(stdout);
    }  
#else
    if (USE_MPI) {
      int all_binned, result = 1;
      if (isSlave)
        result = ((n_binned==np) ? 1 : 0);
      
      MPI_Allreduce(&result, &all_binned, 1, MPI_INT, MPI_LAND, workers);
      if (!all_binned) {
	if (myid==1) {  
	  /* This warning will be given only if the flag MPI_DEBUG is defined for the Pelegant */ 
	  fprintf(stdout, "warning: Not all of %ld particles were binned (WAKE)\n", np);
	  fprintf(stdout, "consider setting n_bins=0 in WAKE definition to invoke autoscaling\n");
	  fflush(stdout); 
	}
      }
    }
#endif

    userFactor[0] = ztransverse->factor*ztransverse->xfactor*rampFactor;
    userFactor[1] = ztransverse->factor*ztransverse->yfactor*rampFactor;

    first = 1;
    for (plane=0; plane<2; plane++) {
#if USE_MPI
      /* This could be good for some advanced network structures */
      /*
        if (isSlave) {
        double buffer[nb];
        MPI_Allreduce(posItime[plane], buffer, nb, MPI_DOUBLE, MPI_SUM, workers);
        memcpy(posItime[plane], buffer, sizeof(double)*nb);
        }
        */
      if (isSlave) {
        buffer_send = malloc(sizeof(float) * nb);
        buffer_recv = malloc(sizeof(float) * nb);
        for (i=0; i<nb; i++)
          buffer_send[i] = posItime[plane][i];
        MPI_Reduce(buffer_send, buffer_recv, nb, MPI_FLOAT, MPI_SUM, 1, workers);
        MPI_Bcast(buffer_recv, nb, MPI_FLOAT, 1, workers);
        for (i=0; i<nb; i++)
          posItime[plane][i] = buffer_recv[i];
        free(buffer_send);
        free(buffer_recv);
      }

#endif
      if (userFactor[plane]==0) {
        for (ib=0; ib<nb; ib++)
          Vtime[ib] = 0;
      } else {
        if (ztransverse->smoothing)
          SavitzyGolaySmooth(posItime[plane], nb, ztransverse->SGOrder,
                             ztransverse->SGHalfWidth, ztransverse->SGHalfWidth, 0);
        
        /* Take the FFT of (x*I)(t) to get (x*I)(f) */
        memcpy(posIfreq, posItime[plane], 2*nb*sizeof(*posIfreq));
        realFFT(posIfreq, nb, 0);
        
        /* Compute V(f) = i*Z(f)*(x*I)(f), putting in a factor 
         * to normalize the current waveform
         */
        Vfreq = Vtime;
        factor = ztransverse->macroParticleCharge*particleRelSign/dt*userFactor[plane];
        iZ = ztransverse->iZ[plane];
        Vfreq[0] = posIfreq[0]*iZ[0]*factor;
        nfreq = nb/2 + 1;
        if (nb%2==0)
          /* Nyquist term */
          Vfreq[nb-1] = posIfreq[nb-1]*iZ[nb-1]*factor;
        for (ib=1; ib<nfreq-1; ib++) {
          iImag = (iReal = 2*ib-1)+1;
          /* The signs are chosen here to get agreement with TRFMODE.
             In particular, test particles following closely behind the 
             drive particle get defocused.
             */
          Vfreq[iReal] =  (posIfreq[iReal]*iZ[iImag] + posIfreq[iImag]*iZ[iReal])*factor; 
          Vfreq[iImag] = -(posIfreq[iReal]*iZ[iReal] - posIfreq[iImag]*iZ[iImag])*factor;
        }
        
        /* Compute inverse FFT of V(f) to get V(t) */
        realFFT(Vfreq, nb, INVERSE_FFT);
        Vtime = Vfreq;
        
        /* change particle transverse momenta to reflect voltage in relevant bin */
        applyTransverseWakeKicks(part+ip1, time+ip1, pz, pbin, npb, 
                                 Po, plane, 
                                 Vtime, nb, tmin, dt, ztransverse->interpolate,
                                 plane==0?ztransverse->xProbeExponent:ztransverse->yProbeExponent);
      }

      if (ztransverse->SDDS_wake_initialized && ztransverse->wakes) {
        /* wake potential output */
        factor = ztransverse->macroParticleCharge*particleRelSign/dt;
        if ((ztransverse->wake_interval<=0 || ((i_pass0-ztransverse->wake_start)%ztransverse->wake_interval)==0) &&
            i_pass0>=ztransverse->wake_start && i_pass0<=ztransverse->wake_end) {
          if (first && !SDDS_StartTable(&ztransverse->SDDS_wake, nb)) {
            SDDS_SetError("Problem starting SDDS table for wake output (track_through_ztransverse)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          for (ib=0; ib<nb; ib++) {
            if (!SDDS_SetRowValues(&ztransverse->SDDS_wake, SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE, ib,
                                   0, ib*dt, 
                                   1+plane*2, posItime[plane][ib]*factor,  
                                   2+plane*2, Vtime[ib], -1)) {
              SDDS_SetError("Problem setting rows of SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (!SDDS_SetParameters(&ztransverse->SDDS_wake, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                  "Pass", i_pass0, "q", ztransverse->macroParticleCharge*particleRelSign*np, NULL)) {
            SDDS_SetError("Problem setting parameters of SDDS table for wake output (track_through_ztransverse)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (ztransverse->broad_band) {
            if (!SDDS_SetParameters(&ztransverse->SDDS_wake, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE,
                                    "Rs", ztransverse->Rs, "fo", ztransverse->freq, 
                                    "Deltaf", ztransverse->bin_size, NULL)) {
              SDDS_SetError("Problem setting parameters of SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (!first) {
            if (!SDDS_WriteTable(&ztransverse->SDDS_wake)) {
              SDDS_SetError("Problem writing SDDS table for wake output (track_through_ztransverse)");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            if (!inhibitFileSync)
              SDDS_DoFSync(&ztransverse->SDDS_wake);
          }
        }
      }
      first = 0;
    }
  }
  
#if defined(MIMIMIZE_MEMORY)
  free(posItime[0]);
  free(posItime[1]);
  free(posIfreq);
  free(Vtime);
  free(pbin);
  free(time);
  free(pz);
  posItime[0] = posItime[1] = Vtime = time = pz = posIfreq = NULL;
  pbin = NULL;
  max_n_bins = max_np = 0 ;
#endif

}
예제 #4
0
파일: citi2sdds.c 프로젝트: epicsdeb/sdds
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, points;
    char *input, *output, *name, *indep_var, *var_list_format;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    char buffer[BUFSIZE], buffer0[BUFSIZE], buffer1[BUFSIZE];
    char *ptr, *ptr1, *ptr2;
    char **data_name, *package_name, *data_format;
    long data_names, data_sets_seen, data_sets_expected, realIndex, imagIndex;
    double **real_data, **imag_data, *var_list;

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

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

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

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

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

    while (fgets(buffer, BUFSIZE, fpi)) {
#if DEBUG
        fputs(buffer, stderr);
#endif
        buffer[strlen(buffer)-1] = 0;
        strcpy(buffer0, buffer);
        ptr1 = NULL;
        if ((ptr1=strchr(buffer, ' '))) 
            *ptr1++ = 0;
        switch (match_string(buffer, citi_keyword, N_CITI_KEYWORDS, EXACT_MATCH)) {
          case CITI_NA_KEYWORD:
            name = buffer+1;
            if (!*ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains an apparently invalid #NA keyword:\n%s\n",
                        buffer0);
                exit(1);
                }
            *(ptr1-1) = '_';
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, name, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for #NA keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_NAME_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "NAME: %s\n", ptr1);
#endif
            cp_str(&package_name, ptr1);
            if (SDDS_DefineParameter(&SDDS_table, "CITIPackageName", NULL, NULL, NULL, NULL, SDDS_STRING,
                                      package_name)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for NAME keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_VAR_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "VAR: %s\n", ptr1);
#endif
            if (!(indep_var=get_token(ptr1)) || !(var_list_format=get_token(ptr1)) || !get_long(&points, ptr1) ||
                points<=0) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
            if (SDDS_DefineColumn(&SDDS_table, indep_var, NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_CONSTANT_KEYWORD:
            if (!ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "CONSTANT: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, ptr1, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for CONSTANT keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_COMMENT_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "COMMENT: %s\n", ptr1);
#endif
            break;
          case CITI_DATA_KEYWORD:
            if (!ptr1 || !(ptr2 = strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "DATA: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            cp_str(&data_format, ptr2);
            data_name = trealloc(data_name, sizeof(*data_name)*(data_names+1));
            cp_str(data_name+data_names, ptr1);
            alter_data_name(data_name[data_names]);
            real_data = trealloc(real_data, sizeof(*real_data)*(data_names+1));
            imag_data = trealloc(imag_data, sizeof(*imag_data)*(data_names+1));
	    sprintf(buffer, "%sReal", data_name[data_names]);
	    sprintf(buffer1, "%sImag", data_name[data_names]);
            if ((realIndex=SDDS_DefineColumn(&SDDS_table, buffer, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ||
                (imagIndex=SDDS_DefineColumn(&SDDS_table, buffer1, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            data_names++;
            break;
          case CITI_VAR_LIST_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "VAR_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("VAR_LIST_BEGIN statement seen without prior VAR statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_var_list(fpi, var_list, points))
                SDDS_Bomb("unable to read VAR_LIST");
            break;
          case CITI_BEGIN_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("BEGIN statement seen without prior VAR statement");
            real_data[data_sets_seen] = tmalloc(sizeof(**real_data)*points);
            imag_data[data_sets_seen] = tmalloc(sizeof(**imag_data)*points);
            if (!read_CITI_data(fpi, real_data[data_sets_seen], imag_data[data_sets_seen], points))
                SDDS_Bomb("problem reading data section");
            data_sets_seen++;
            break;
          case CITI_SEG_LIST_BEGIN:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "SEG_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("SEG_LIST_BEGIN statement seen without prior SEG statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_seg_list(fpi, var_list, points))
                SDDS_Bomb("unable to read SEG_LIST");
            break;
          default:
            fprintf(stderr, "unidentifiable line in file--not CITI format:\n\"%s\"\n",
                    buffer0);
            exit(1);
            break;
            }
        }
    if (!points)
        SDDS_Bomb("no data in file");
    if (data_sets_seen!=(data_sets_expected=data_names))
        SDDS_Bomb("fewer data sets than expected were actually present");
    if (!var_list) {
        fprintf(stderr, "warning: no independent variable data---supplying index\n");
        var_list = tmalloc(sizeof(*var_list)*points);
        for (i=0; i<points; i++)
            var_list[i] = i;
        }
    if (!SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, (void*)var_list, points, indep_var))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    for (i=0; i<data_sets_expected; i++) {
         if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)real_data[i], points, 
                             realIndex) ||
             !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)imag_data[i], points, 
                             imagIndex)) {
             fprintf(stderr, "problem setting data for column(s) %s\n", data_name[i]);
             SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
             }
         }
    if (!SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
예제 #5
0
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);
}
예제 #6
0
void dump_IBScatter(SDDS_TABLE *SDDS_table, IBSCATTER *IBS, long pass)
{
  long i, islice;
  double gamma;

  log_entry("dump_IBScatter");

  if (!IBS->elements)
    return;

  gamma = sqrt(ipow(IBS->pCentral[IBS->elements-1], 2)+1.);
  for (islice=0; islice<IBS->nslice; islice++) {
    if (!SDDS_StartTable(SDDS_table, IBS->elements)) {
      SDDS_SetError("Problem starting SDDS table (dump_IBScatter)");
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }

    for (i=0; i<IBS->elements; i++) {
      if (!SDDS_SetRowValues(SDDS_table, SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE, i,
                             0, IBS->name[i], 1, IBS->s[i], 
                             2, IBS->xRateVsS[islice][i], 3, IBS->yRateVsS[islice][i], 4, IBS->zRateVsS[islice][i], 
                             5, IBS->betax[islice][i], 6, IBS->alphax[islice][i], 7, IBS->etax[i], 8, IBS->etaxp[i], 
                             9, IBS->betay[islice][i], 10, IBS->alphay[islice][i], 11, IBS->etay[i], 12, IBS->etayp[i], -1)) {
        SDDS_SetError("Problem setting SDDS row values (dump_IBScatter)");
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
    }
    if ((!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "Particles", fabs(IBS->icharge[islice]/particleCharge), NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "Charge", IBS->icharge[islice]*1e9, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "TotalSlice", IBS->nslice, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "NSlice", islice+1, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "s", IBS->s[IBS->elements-1], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "Pass", pass, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "StartPoint", IBS->offset, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "Elements", IBS->elements, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "ds", IBS->revolutionLength, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "dt", IBS->dT, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "xGrowthRate", IBS->xGrowthRate[islice], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "yGrowthRate", IBS->yGrowthRate[islice], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "zGrowthRate", IBS->zGrowthRate[islice], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "enx0", IBS->emitx0[islice]*gamma, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "eny0", IBS->emity0[islice]*gamma, NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "emitx0", IBS->emitx0[islice], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "emity0", IBS->emity0[islice], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "sigmaDelta0", IBS->sigmaDelta0[islice], NULL))||
        (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "sigmaz0", IBS->sigmaz0[islice], NULL))){
      SDDS_SetError("Problem setting SDDS parameters (dump_IBScatter)");
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }

    if (!IBS->isRing) {
      if ((!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "emitx", IBS->emitx[islice], NULL))||
          (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "emity", IBS->emity[islice], NULL))||
          (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "enx", IBS->emitx[islice]*gamma, NULL))||
          (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "eny", IBS->emity[islice]*gamma, NULL))||
          (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "sigmaDelta", IBS->sigmaDelta[islice], NULL))||
          (!SDDS_SetParameters(SDDS_table, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, "sigmaz", IBS->sigmaz[islice], NULL))){
        SDDS_SetError("Problem setting SDDS parameters (dump_IBScatter)");
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
    }

    if (!SDDS_WriteTable(SDDS_table)) {
      SDDS_SetError("Problem writing SDDS table (dump_IBScatter)");
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    } 
    
    SDDS_UpdatePage(SDDS_table, 0);
    if (!inhibitFileSync)
      SDDS_DoFSync(SDDS_table);
  }
  log_exit("dump_IBScatter");    
}
예제 #7
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    unsigned long majorOrderFlag;
    long i_arg;
    char *input, *output, *definition;
    long hsize, vsize;
    char *data, *data_name;
    char ts1[100], ts2[100];
    FILE *fpi;
    short columnMajorOrder=0;

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

    input = output = data_name = NULL;
    hsize = DEFAULT_HSIZE;
    vsize = DEFAULT_VSIZE;
    definition = NULL;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_MAJOR_ORDER:
              majorOrderFlag=0;
              scanned[i_arg].n_items--;
              if (scanned[i_arg].n_items>0 &&
                  (!scanItemList(&majorOrderFlag, scanned[i_arg].list+1, &scanned[i_arg].n_items, 0,
                                 "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                                 "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                                   NULL)))
                SDDS_Bomb("invalid -majorOrder syntax/values");
              if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
                columnMajorOrder=1;
              else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
                columnMajorOrder=0;
              break;
              case SET_DEFINITION:
                data_name = scanned[i_arg].list[1];
                definition = process_column_definition(scanned[i_arg].list+1, 
                                                       scanned[i_arg].n_items-1);
                if (!strstr(definition, "type=character"))
                  SDDS_Bomb("data type must be character for now");
                break;
              case SET_SIZE:
                if (scanned[i_arg].n_items!=3 ||
                    sscanf(scanned[i_arg].list[1], "%ld", &hsize)!=1 || hsize<=0 ||
                    sscanf(scanned[i_arg].list[2], "%ld", &vsize)!=1 || vsize<=0)
                    bomb("invalid -size syntax", USAGE);
                break;
            default:
              bomb("invalid option seen", USAGE);
              break;
            }
        }
        else {
          if (!input)
            input = scanned[i_arg].list[0];
          else if (!output)
            output = scanned[i_arg].list[0];
            else
              bomb("too many filenames", USAGE);
        }
    }
    if (!input)
        SDDS_Bomb("input file not seen");
    if (!output)
        SDDS_Bomb("output file not seen");
    if (!definition)
        SDDS_Bomb("definition not seen");

    sprintf(ts1, "%ld", hsize);
    sprintf(ts2, "%ld", vsize);
    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, 
                               "screen image from raw file", "screen image",
                               output) ||
        SDDS_ProcessColumnString(&SDDS_table, definition, 0)<0 || 
        SDDS_DefineParameter(&SDDS_table, "NumberOfRows", NULL, NULL, "number of rows",
                              NULL, SDDS_LONG, ts1)<0 ||
        !SDDS_DefineParameter(&SDDS_table, "NumberOfColumns", NULL, NULL, 
                              "number of columns", NULL, SDDS_LONG, ts2)<0)
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_table.layout.data_mode.column_major = columnMajorOrder;
    if (!SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, hsize*vsize))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    data = tmalloc(sizeof(*data)*hsize*vsize);
    fpi = fopen_e(input, "r", 0);
    if (fread(data, sizeof(*data), hsize*vsize, fpi)!=hsize*vsize)
        SDDS_Bomb("unable to read (all) data from input file");
    fclose(fpi);
    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, data, hsize*vsize, 
                        data_name) ||
        !SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
예제 #8
0
void dump_cormon_stats(long verbose, long plane, double **kick, long n_kicks, 
    double **position, long n_positions, double *Cdp, long n_iterations, long cycle,
    long final_cycle, long sim_step, long textOnly)
{
    long i, j;
    static double **data = NULL;
    static char **stage = NULL;
    static long n_iter = 0;

    if (!verbose && !SDDS_cormon_initialized)
        return;

    log_entry("dump_cormon_stats");

    if (!data || n_iterations>n_iter) {
        if (data)
            free_czarray_2d((void**)data, n_iter+1, N_COLUMNS);
        if (stage)
            free(stage);
        data = (double**)czarray_2d(sizeof(**data), n_iterations+1, N_COLUMNS);    
        stage = tmalloc(sizeof(*stage)*(n_iterations+1));
        n_iter = n_iterations;
        }

    for (j=0; j<=n_iterations; j++) {
        if (j==0)
            stage[j] = "uncorrected";
        else if (j==n_iterations)
            stage[j] = "corrected";
        else
            stage[j] = "intermediate";
        data[j][IC_ITERATION] = j;
        data[j][IC_CYCLE] = cycle;
        data[j][IC_KRMS] = data[j][IC_KMAX] = data[j][IC_PRMS] = 
            data[j][IC_PMAX] = 0;
        for (i=0; i<n_kicks; i++) {
            if (FABS(kick[j][i]) > data[j][IC_KMAX])
                data[j][IC_KMAX] = FABS(kick[j][i]);
            data[j][IC_KRMS] += sqr(kick[j][i]);
            }
        if (n_kicks) 
            data[j][IC_KRMS] = sqrt(data[j][IC_KRMS]/n_kicks);
        for (i=0; i<n_positions; i++) {
            if (FABS(position[j][i]) > data[j][IC_PMAX])
                data[j][IC_PMAX] = FABS(position[j][i]);
            data[j][IC_PRMS] += sqr(position[j][i]);
            }
        if (n_positions)
            data[j][IC_PRMS] = sqrt(data[j][IC_PRMS]/n_positions);
        data[j][IC_CDP] = (Cdp?Cdp[j]:0);
        }

    if (SDDS_cormon_initialized && !textOnly) {
        if (!SDDS_StartTable(&SDDS_cormon, n_iterations+1)) {
            SDDS_SetError("Unable to start SDDS table (dump_cormon_stats)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!SDDS_SetParameters(&SDDS_cormon, SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE, 
                                IP_STEP, sim_step, IP_PLANE, plane?"vertical":"horizontal", 
                                IP_FINAL, final_cycle?'y':'n', -1)) {
            SDDS_SetError("Unable to set SDDS parameter values (dump_cormon_stats)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        for (j=0; j<=n_iterations; j++) {
            if (!SDDS_SetRowValues(&SDDS_cormon, SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE, j,
                                   IC_ITERATION, j,
                                   IC_CYCLE, cycle,
                                   IC_KRMS, data[j][IC_KRMS],
                                   IC_PRMS, data[j][IC_PRMS],
                                   IC_KMAX, data[j][IC_KMAX],
                                   IC_PMAX, data[j][IC_PMAX],
                                   IC_CDP, data[j][IC_CDP],
                                   IC_STAGE, stage[j], -1)) {
                fprintf(stdout, "Unable to set row %ld values (dump_cormon_stats)\n", j);
                fflush(stdout);
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
                exitElegant(1);
                }
            }
        if (!SDDS_WriteTable(&SDDS_cormon)) {
            SDDS_SetError("Unable to write corrector data (dump_cormon_stats)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!inhibitFileSync)
          SDDS_DoFSync(&SDDS_cormon);
        if (!SDDS_EraseData(&SDDS_cormon)) {
            SDDS_SetError("Unable to erase corrector data (dump_cormon_stats)");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }

    if (verbose) {
        for (j=0; j<=n_iterations; j++) 
          if (Cdp) {
                fprintf(stdout, "   %c     %4ld     %8.3f    %8.3f     %8.3f     %8.3f   %8.3f %s\n",
                    'x'+(plane?1:0), j,
                    1e3*data[j][IC_KRMS], 1e3*data[j][IC_PRMS],
                    1e3*data[j][IC_KMAX], 1e3*data[j][IC_PMAX],
                    1e2*data[j][IC_CDP],
                    (j==n_iterations?"**":"") );
                fflush(stdout);
              }
          else {
                fprintf(stdout, "   %c     %4ld     %8.3f    %8.3f     %8.3f     %8.3f %s\n",
                    'x'+(plane?1:0), j,
                    1e3*data[j][IC_KRMS], 1e3*data[j][IC_PRMS],
                    1e3*data[j][IC_KMAX], 1e3*data[j][IC_PMAX],
                    (j==n_iterations?"**":"") );
                fflush(stdout);
              }
        }

    log_exit("dump_cormon_stats");    
    }
예제 #9
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, index, points, lsb_first, bytes_per_number;
    char *input, *output, buffer[BUFSIZE];
    char *signal_name, *ptr, *parameter_name;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    long code, binary;
    double xIncrement, xZero, yMultiplier, yZero;
    char *xUnits, *yUnits;
    double *time, *data;
    short columnMajorOrder=0;
    unsigned long majorOrderFlag;
    
    xUnits = yUnits = NULL;

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

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

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

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

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

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

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

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

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

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

    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, time, points, "t") ||
        !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, data, points, signal_name) ||
        !SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}