Пример #1
0
void keep_alloc_record(char *filename)
{
    char s[100];
    
    if (fp_tmalloc)
        free(fp_tmalloc);
    if (fp_trealloc)
        free(fp_trealloc);
    if (fp_tfree)
        free(fp_tfree);
    sprintf(s, "%s.tmalloc", filename);
    fp_tmalloc = fopen_e(s, "w", 0);
    sprintf(s, "%s.trealloc", filename);
    fp_trealloc = fopen_e(s, "w", 0);
    sprintf(s, "%s.tfree", filename);
    fp_tfree = fopen_e(s, "w", 0);
    }
Пример #2
0
main(int argc, char **argv)
{
    FILE *fp;
    char s[100];

    fp = fopen_e("x11test.out", "w", 0);
    while (fgets(s, 100, stdin))
        fputs(s, fp);
    }
Пример #3
0
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);
}
Пример #4
0
int main(int argc,char **argv)
{
	try
	{
		dolog = (!!scanparm(argc,argv,"-v"));
		double xfactor = 1;
		if (int xpos = scanparm(argc,argv,"-xf"))
			if ((xfactor = strtod(grabparm(argc,argv,xpos + 1),0)) == 0)
			{
				throw exception::root("Invalid value after -xf");
			}
		double yfactor = 1;
		if (int ypos = scanparm(argc,argv,"-yf"))
			if ((yfactor = strtod(grabparm(argc,argv,ypos + 1),0)) == 0)
			{
				throw exception::root("Invalid value after -yf");
			}
		double zfactor = 1;
		if (int zpos = scanparm(argc,argv,"-zf"))
			if ((zfactor = strtod(grabparm(argc,argv,zpos + 1),0)) == 0)
			{
				throw exception::root("Invalid value after -zf");
			}
		char *tm_fname;
		if (scanparm(argc,argv,"-h"))
		{
			showhelp(argc,argv);
			return 0;
		}
		FILE *THINGS = 0;
		FILE *LINEDEFS = 0;
		FILE *SIDEDEFS = 0;
		FILE *VERTEXES = 0;
		FILE *SECTORS = 0;
		if (int wpos = scanparm(argc,argv,"-w"))
		{
			grabparm(argc,argv,wpos + 3);
			FILE *wad;
			log("Opening wad file...");
			wad = fopen_e(grabparm(argc,argv,wpos + 1),"rb");
			log("Reading wad header...");
			int dirofs;
			int lumpcount;
			long filesize;
			fseek(wad,0,SEEK_END);
			filesize = ftell(wad);
			if (filesize < 12)
			{
				throw exception::root("Wad is less than 12 bytes large (invalid wad)");
			}
			fseek(wad,0,SEEK_SET);
			char type[5];
			for (int i = 0;i < 4;i++)
			{
				type[i] = fgetc(wad);
			}
			type[4] = 0;
			std::cout << "WAD Type: " << type << std::endl;
			lumpcount = fgetc(wad);
			lumpcount |= (fgetc(wad) << (8 * 1));
			lumpcount |= (fgetc(wad) << (8 * 2));
			lumpcount |= (fgetc(wad) << (8 * 3));
			if (lumpcount <= 0)
			{
				throw exception::root("Wad lump count less than 1 (empty wad)");
			}
			dirofs = fgetc(wad);
			dirofs |= (fgetc(wad) << (8 * 1));
			dirofs |= (fgetc(wad) << (8 * 2));
			dirofs |= (fgetc(wad) << (8 * 3));
			if ((dirofs < 0) || ((dirofs + (16 * lumpcount)) > filesize))
			{
				throw exception::root("Lump directory outside of WAD file (invalid wad)");
			}
			fseek(wad,dirofs,SEEK_SET);
			log("Searching for map lump...");
			char lumpname[9];
			lumpname[8] = 0;
			strtoupper(grabparm(argc,argv,wpos + 2));
			for (int i = 0;i < lumpcount;i++)
			{
				fseek(wad,8,SEEK_CUR);
				for (int j = 0;j < 8;j++)
					lumpname[j] = fgetc(wad);
				if (!strcmp(lumpname,grabparm(argc,argv,wpos + 2)))
					break;
				if (i == lumpcount - 1)
				{
					throw exception::root("Map lump not found");
				}
			}
			log("Extracting lumps...");
			THINGS = extractlump(wad,filesize);
			LINEDEFS = extractlump(wad,filesize);
			SIDEDEFS = extractlump(wad,filesize);
			VERTEXES = extractlump(wad,filesize);
			fseek(wad,16 * 3,SEEK_CUR);
			SECTORS = extractlump(wad,filesize);
			log("Closing wad file...");
			fclose(wad);
			tm_fname = grabparm(argc,argv,wpos + 3);
		}
		else
		{
			log("Opening THINGS...");
			THINGS = fopen_e(shiftparm(argc,argv),"rb");
			log("Opening LINEDEFS...");
			LINEDEFS = fopen_e(shiftparm(argc,argv),"rb");
			log("Opening SIDEDEFS...");
			SIDEDEFS = fopen_e(shiftparm(argc,argv),"rb");
			log("Opening VERTEXES...");
			VERTEXES = fopen_e(shiftparm(argc,argv),"rb");
			log("Opening SECTORS...");
			SECTORS = fopen_e(shiftparm(argc,argv),"rb");
			tm_fname = shiftparm(argc,argv);
		}
		log("Checking if TEXTMAP already exists...");
		if (!scanparm(argc,argv,"-f") && fopen(tm_fname,"rb"))
		{
			char verify[10];
			std::cout << tm_fname << " already exists. Overwrite? (Y/N)";
			std::cin.getline(verify,10);
			if (strcmp("Y",strtoupper(verify)))
			{
				std::cout << "Aborting...";
				std::cout << std::endl;
				return 2;
			}
		}
		log("Opening TEXTMAP...");
		FILE *textmap_check;
		textmap_check = fopen(tm_fname,"w");	//Ugly, but I see no other way
		if (textmap_check == 0)
		{
			throw exception::file_error(tm_fname);
		}
		fclose(textmap_check);
		std::ofstream TEXTMAP(tm_fname);
		log("Writing Namespace...");
		int pos;
		pos = scanparm(argc,argv,"-n");
		TEXTMAP << "Namespace = \"" << (pos ? grabparm(argc,argv,pos + 1) : format_namespace) << "\";\n\n";
		log("Converting things...");
		eofloop(udmf::writeblock("thing",convert(format::getthing(THINGS),xfactor,yfactor),TEXTMAP));
		log("Converting linedefs...");
		eofloop(udmf::writeblock("linedef",convert(format::getlinedef(LINEDEFS)),TEXTMAP));
		log("Converting sidedefs...");
		eofloop(udmf::writeblock("sidedef",convert(format::getsidedef(SIDEDEFS)),TEXTMAP));
		log("Converting vertexes...");
		eofloop(udmf::writeblock("vertex",convert(format::getvertex(VERTEXES),xfactor,yfactor),TEXTMAP));
		log("Converting sectors...");
		eofloop(udmf::writeblock("sector",convert(format::getsector(SECTORS),zfactor),TEXTMAP));
		log("Closing files...");
		std::cout << "Conversion complete!" << std::endl;
		return 0;
	}
	catch (exception::missing_args problem)
	{
		std::cerr << "Missing arguments. Run with -h for help." << std::endl;
		return 0;
	}
	catch (exception::root problem)
	{
		std::cerr << problem.what() << std::endl;
		return 0;
	}
	catch (std::exception problem)
	{
		std::cerr << "Error: \"" << problem.what() << "\"!" << std::endl;
		return 255;
	}
}
Пример #5
0
void set_up_ztransverse(ZTRANSVERSE *ztransverse, RUN *run, long pass, long particles, CHARGE *charge,
                        double timeSpan)
{
  long i, nfreq;
  double df;

  if (charge) {
    ztransverse->macroParticleCharge = charge->macroParticleCharge;
  } else if (pass==0) {
    ztransverse->macroParticleCharge = 0;
    if (ztransverse->charge<0)
      bombElegant("ZTRANSVERSE charge parameter should be non-negative. Use change_particle to set particle charge state.", NULL);
#if (!USE_MPI)
    if (particles)
      ztransverse->macroParticleCharge = ztransverse->charge/particles;
#else
      if (USE_MPI) {
	long particles_total;

	MPI_Allreduce(&particles, &particles_total, 1, MPI_LONG, MPI_SUM, workers);
	if (particles_total)
	  ztransverse->macroParticleCharge = ztransverse->charge/particles_total;  
      } 
#endif
  }

  if (ztransverse->initialized)
    return;

  ztransverse->SDDS_wake_initialized = 0;

  if (ztransverse->broad_band) {
    /* Use impedance Z = -i*wr/w*Rs/(1 + i*Q(w/wr-wr/w))
       */
    double term;
    if (ztransverse->bin_size<=0)
      bombElegant("bin_size must be positive for ZTRANSVERSE element", NULL);
    if (ztransverse->n_bins%2!=0)
      bombElegant("ZTRANSVERSE element must have n_bins divisible by 2", NULL);
    if (ztransverse->ZxReal || ztransverse->ZxImag ||
        ztransverse->ZyReal || ztransverse->ZyImag )
      bombElegant("can't specify both broad_band impedance and Z(f) files for ZTRANSVERSE element", NULL);

    optimizeBinSettingsForImpedance(timeSpan, ztransverse->freq, ztransverse->Q,
                                    &(ztransverse->bin_size), &(ztransverse->n_bins),
                                    ztransverse->max_n_bins);
    
    nfreq = ztransverse->n_bins/2 + 1;
    ztransverse->iZ[0] = tmalloc(sizeof(**(ztransverse->iZ))*ztransverse->n_bins);
    ztransverse->iZ[1] = tmalloc(sizeof(**(ztransverse->iZ))*ztransverse->n_bins);
    /* df is the frequency spacing normalized to the resonant frequency */
    df = 1/(ztransverse->n_bins*ztransverse->bin_size)/(ztransverse->freq);
    /* DC term of iZ is 0  */
    ztransverse->iZ[0][0] = ztransverse->iZ[1][0] = 0;
    for (i=1; i<nfreq-1; i++) {
      term = ztransverse->Q*(i*df-1.0/(i*df));
      /* real part of i*Z */
      ztransverse->iZ[0][2*i-1] =  
        ztransverse->iZ[1][2*i-1] =  
	ztransverse->Rs/(i*df)/(1+term*term);
      /* imaginary part of i*Z is -Real[i*Z]*term */
      ztransverse->iZ[0][2*i] = 
        ztransverse->iZ[1][2*i] = 
	-term*ztransverse->iZ[0][2*i-1];
    }
    /* Nyquist term--real part of iZ only */
    term = ztransverse->Q*(1.0/(nfreq*df)-nfreq*df);
    ztransverse->iZ[0][ztransverse->n_bins-1] = 
      ztransverse->iZ[1][ztransverse->n_bins-1] = 
      ztransverse->Rs/(nfreq*df)/(1+term*term);
    df *= ztransverse->freq;
  } else {
    double *ZReal[2], *ZImag[2], *freqData;
    double df_spect;
    long n_spect;
    SDDS_DATASET SDDSin;
    if (!ztransverse->freqColumn || !ztransverse->inputFile)
      bombElegant("you must give an inputFile and freqColumn, or use a broad band model (ZTRANSVERSE)", NULL);
    if (!ztransverse->ZxReal && !ztransverse->ZxImag &&
        !ztransverse->ZyReal && !ztransverse->ZxImag)
      bombElegant("you must either give broad_band=1, or Z[xy]Real and/or Z[xy]Imag (ZTRANSVERSE)", NULL);
    if (!SDDS_InitializeInputFromSearchPath(&SDDSin, ztransverse->inputFile) || !SDDS_ReadPage(&SDDSin)) {
      fprintf(stdout, "unable to read file %s\n", ztransverse->inputFile);
      fflush(stdout);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors); 
      exitElegant(1);
    }
    if ((n_spect=SDDS_RowCount(&SDDSin))<4) {
      fprintf(stdout, "too little data in %s\n", ztransverse->inputFile);
      fflush(stdout);
      exitElegant(1);
    }
    if (!power_of_2(n_spect-1))
      bombElegant("number of spectrum points must be 2^n+1, n>1 (ZTRANSVERSE)", NULL);
    ZReal[0] = getTransverseImpedance(&SDDSin, ztransverse->ZxReal);
    ZImag[0] = getTransverseImpedance(&SDDSin, ztransverse->ZxImag);
    ZReal[1] = getTransverseImpedance(&SDDSin, ztransverse->ZyReal);
    ZImag[1] = getTransverseImpedance(&SDDSin, ztransverse->ZyImag);
    if (!(freqData=SDDS_GetColumnInDoubles(&SDDSin, ztransverse->freqColumn))) {
      fprintf(stdout, "Unable to read column %s (ZTRANSVERSE)\n", ztransverse->freqColumn);
      fflush(stdout);
      exitElegant(1);
    }
    if (!checkPointSpacing(freqData, n_spect, 1e-6)) {
      fprintf(stdout, "Frequency values are not equispaced (ZTRANSVERSE)\n");
      fflush(stdout);
      exitElegant(1);
    }
    if ((df_spect = (freqData[n_spect-1]-freqData[0])/(n_spect-1))<=0) {
      fprintf(stdout, "Zero or negative frequency spacing in %s (ZTRANSVERSE)\n",
              ztransverse->inputFile);
      fflush(stdout);
      exitElegant(1);
    }
    df = df_spect;
    nfreq = n_spect;
    ztransverse->n_bins = 2*(n_spect-1);
    ztransverse->bin_size = 1.0/(ztransverse->n_bins*df_spect);
    if (!SDDS_Terminate(&SDDSin)) {
      fprintf(stdout, "Error closing data set %s\n",
              ztransverse->inputFile);
      fflush(stdout);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exitElegant(1);
    }
    if (!(ztransverse->iZ[0] =
          calloc(sizeof(*ztransverse->iZ[0]), n_spect*2)) ||
        !(ztransverse->iZ[1] =
          calloc(sizeof(*ztransverse->iZ[1]), n_spect*2)))
      bombElegant("memory allocation failure (ZTRANSVERSE)", NULL);
    for (i=0; i<n_spect; i++) {
      if (i==0) {
        /* DC term */
        ztransverse->iZ[0][i] = -ZImag[0][i];
        ztransverse->iZ[1][i] = -ZImag[1][i];
      } else if (i==n_spect-1 && ztransverse->n_bins%2==0) {
        /* Nyquist term */
        ztransverse->iZ[0][2*i-1] = -ZImag[0][i];
        ztransverse->iZ[1][2*i-1] = -ZImag[1][i];
      } else {
        /* real part of iZ */
        ztransverse->iZ[0][2*i-1] = -ZImag[0][i];
        ztransverse->iZ[1][2*i-1] = -ZImag[1][i];
        /* imaginary part of iZ */
        ztransverse->iZ[0][2*i  ] = ZReal[0][i];
        ztransverse->iZ[1][2*i  ] = ZReal[1][i];
      }
    }
    free(ZReal[0]);
    free(ZReal[1]);
    free(ZImag[0]);
    free(ZImag[1]);
  }

#if (!USE_MPI)
  /* Only the serial version will dump this part of output */
  if (ztransverse->wakes) {
    ztransverse->wakes = compose_filename(ztransverse->wakes, run->rootname);
    if (ztransverse->broad_band) 
      SDDS_ElegantOutputSetup(&ztransverse->SDDS_wake, ztransverse->wakes, SDDS_BINARY, 
			      1, "transverse wake",
			      run->runfile, run->lattice, wake_parameter, BB_WAKE_PARAMETERS,
			      wake_column, WAKE_COLUMNS, "set_up_ztransverse", 
			      SDDS_EOS_NEWFILE|SDDS_EOS_COMPLETE);
    else {
      SDDS_ElegantOutputSetup(&ztransverse->SDDS_wake, ztransverse->wakes, SDDS_BINARY, 
			      1, "transverse wake",
			      run->runfile, run->lattice, wake_parameter, NBB_WAKE_PARAMETERS,
			      wake_column, WAKE_COLUMNS, "set_up_ztransverse", 
			      SDDS_EOS_NEWFILE|SDDS_EOS_COMPLETE);
    }
    ztransverse->SDDS_wake_initialized = 1;
  }
#endif

  if (ztransverse->highFrequencyCutoff0>0) {
    applyLowPassFilterToImpedance(ztransverse->iZ[0], nfreq,
                                  ztransverse->highFrequencyCutoff0, 
                                  ztransverse->highFrequencyCutoff1);
    applyLowPassFilterToImpedance(ztransverse->iZ[1], nfreq,
                                  ztransverse->highFrequencyCutoff0, 
                                  ztransverse->highFrequencyCutoff1);
  }

#if 0
  if (!ztransverse->initialized) {
    FILE *fp;
    fp = fopen_e("ztransverse.sdds", "w", 0);
    fprintf(fp, "SDDS1\n&column name=f units=Hz type=double &end\n");
    fprintf(fp, "&column name=ZReal type=double &end\n");
    fprintf(fp, "&column name=ZImag type=double &end\n");
    fprintf(fp, "&data mode=ascii no_row_counts=1 &end\n");
    for (i=0; i<nfreq; i++) 
      fprintf(fp, "%21.15e %21.15e %21.15e\n",
              i*df, ztransverse->iZ[0][2*i], i>0?-ztransverse->iZ[0][2*i-1]:0);
    fclose(fp);
  }
#endif
  
  ztransverse->initialized = 1;
}
Пример #6
0
void error_setup(ERRORVAL *errcon, NAMELIST_TEXT *nltext, RUN *run_cond, LINE_LIST *beamline)
{
    long i;

    log_entry("error_setup");

    /* reset namelist variables to defaults */
/*
    clear_error_settings = 1;
    summarize_error_settings = 0;
    error_log = NULL;
 */

    /* process namelist text */
    set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
    set_print_namelist_flags(0);
    if (processNamelist(&error_control, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    if (echoNamelists) print_namelist(stdout, &error_control);

    if (summarize_error_settings) {
        fprintf(stdout, "summary of random error settings: \n");
        fflush(stdout);
        if (errcon->no_errors_first_step)
          fprintf(stdout, "No errors will be generated for the first step.\n");
          fflush(stdout);
        for (i=0; i<errcon->n_items; i++) {
            switch (errcon->error_type[i]) {
                case UNIFORM_ERRORS:
                case GAUSSIAN_ERRORS:
                    fprintf(stdout, "%8s:  %sadditive %s errors with amplitude %e %s and cutoff %e %s\n",
                        errcon->quan_name[i], (errcon->flags[i]&NONADDITIVE_ERRORS?"non-":""),
                        known_error_type[errcon->error_type[i]], 
                        (errcon->flags[i]&FRACTIONAL_ERRORS?100:1)*errcon->error_level[i],
                        errcon->flags[i]&FRACTIONAL_ERRORS?"%":errcon->quan_unit[i], 
                        errcon->error_cutoff[i], (errcon->flags[i]&POST_CORRECTION?"(post-correction)":""));
                    fflush(stdout);
                    break;
                case PLUS_OR_MINUS_ERRORS:
                    fprintf(stdout, "%8s:  %sadditive %s errors with amplitude %e\n", 
                        errcon->quan_name[i], 
                        (errcon->flags[i]&NONADDITIVE_ERRORS?"non-":""),
                        known_error_type[errcon->error_type[i]],
                        errcon->error_level[i]);
                    fflush(stdout);
                    break;
	    }
	}
        log_exit("error_setup");
        return;
    }

    errcon->no_errors_first_step = no_errors_for_first_step;

    compute_end_positions(beamline);
    
    if (errcon->fp_log)
        fclose(errcon->fp_log);
#if USE_MPI
    if (isSlave)
      error_log = NULL;
#endif
    if (error_log) {
        errcon->fp_log = fopen_e(compose_filename(error_log, run_cond->rootname), "w", 0);
        fprintf(errcon->fp_log, "SDDS1\n");
        fprintf(errcon->fp_log, 
                "&description text=\"Error log--input: %s  lattice: %s\", contents=\"error log, elegant output\" &end\n",
                run_cond->runfile, run_cond->lattice);
        fprintf(errcon->fp_log, "&associate filename=\"%s\", path=\"%s\", contents=\"elegant input, parent\" &end\n",
                run_cond->runfile, getenv("PWD"));
        fprintf(errcon->fp_log, "&associate filename=\"%s\", path=\"%s\", contents=\"elegant lattice, parent\" &end\n",
                run_cond->lattice, getenv("PWD"));
        fprintf(errcon->fp_log, "&parameter name=Step, type=long, description=\"simulation step\" &end\n");

        fprintf(errcon->fp_log, "&parameter name=When, type=string, description=\"phase of simulation when errors were asserted\" &end\n");
        fprintf(errcon->fp_log, "&column name=ParameterValue, type=double, description=\"Perturbed value\" &end\n");
        fprintf(errcon->fp_log, "&column name=ParameterError, type=double, description=\"Perturbation value\" &end\n");
        fprintf(errcon->fp_log, "&column name=ElementParameter, type=string, description=\"Parameter name\" &end\n");
        fprintf(errcon->fp_log, "&column name=ElementName, type=string, description=\"Element name\" &end\n");
        fprintf(errcon->fp_log, "&column name=ElementOccurence, type=long, description=\"Element occurence\" &end\n");
        fprintf(errcon->fp_log, "&column name=ElementType, type=string, description=\"Element type\" &end\n");
        fprintf(errcon->fp_log, "&data mode=ascii, lines_per_row=1, no_row_counts=1 &end\n");
        fflush(errcon->fp_log);
        }
    else
        errcon->fp_log = NULL;

    if (clear_error_settings) {
        /* indicate that no error data has been asserted */
        errcon->new_data_read = 0;
        /* clean up the error control structure and flags on elements */
        if (errcon->n_items)
            set_element_flags(beamline, errcon->name, NULL, NULL, NULL, errcon->n_items, PARAMETERS_ARE_STATIC, 0, 1, 0);
        errcon->n_items = 0;
        }
    fprintf(stdout, "\n*** Cleared error settings\n");
    fflush(stdout);
    log_exit("error_setup");
    }
Пример #7
0
long get_mc_table(MC_TABLE *table, char *file, long flags)
{
    FILE *fpi;
    long i, j, i_col;
    char *ptr;

    if (!(fpi = fopen_e(file, "r", 1)))
        return(0);

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("unable to read first line of table file", NULL);
    if (!(get_long(&table->n_cols, buffer)))
        bomb("unable to scan number of columns in table file", NULL);
    if (table->n_cols<=0)
        bomb("number of columns is invalid in table file", NULL);
    table->n_lines_per_row = 1;
    table->n_auxiliaries = 0;
    if (get_long(&table->n_lines_per_row, buffer)) {
        if (table->n_lines_per_row<=0)
            bomb("number of lines per row is invalid in table file", NULL);
        if (get_long(&table->n_auxiliaries, buffer) &&
                table->n_auxiliaries<0)
            bomb("number of auxiliary quantities is invalid in table file", NULL);
        }

#if DEBUG
    printf("file %s\nn_cols = %ld  n_lines_per_row = %ld  n_auxiliaries = %ld\n",
        file, table->n_cols, table->n_lines_per_row, table->n_auxiliaries);
#endif

    table->name = tmalloc(sizeof(char*)*table->n_cols);
    table->unit = tmalloc(sizeof(char*)*table->n_cols);
    table->description
                = tmalloc(sizeof(char*)*table->n_cols);
    table->format
                = tmalloc(sizeof(char*)*table->n_cols);
    
    for (i=0; i<table->n_cols; i++) {
        if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
            bomb("missing quantity name and units line in table file", NULL);
        get_name_unit_descrip_format(table->name+i, table->unit+i,
                table->description+i, table->format+i, buffer);
        if (table->format[i] && !strchr(table->format[i], '%'))
            table->format[i] = NULL;
        }

#if DEBUG
    for (i=0; i<table->n_cols; i++)
        printf("column %ld:  %s in %s--%s in format %s\n", 
                i, table->name[i], table->unit[i], table->description[i], 
                (table->format[i]?table->format[i]:"{null}") );
#endif

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("missing title string in table file", NULL);
    cp_str(&table->title, buffer);

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("missing label string in table file", NULL);
    cp_str(&table->label, buffer);

#if DEBUG
    printf("title: %s\nlabel: %s\n", table->title, table->label);
#endif

    if (table->n_auxiliaries) {
#if DEBUG
        printf("%ld auxuliary quantities are expected\n", table->n_auxiliaries);
#endif
        /* get auxiliary quantity names\units... */
        table->aux_name        = tmalloc(sizeof(char*)*table->n_auxiliaries);
        table->aux_unit        = tmalloc(sizeof(char*)*table->n_auxiliaries);
        table->aux_description = tmalloc(sizeof(char*)*table->n_auxiliaries);
        table->aux_value       = tmalloc(sizeof(*(table->aux_value))*table->n_auxiliaries);
        for (i=0; i<table->n_auxiliaries; i++) {
            if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
                bomb("missing quantity name and units line in table file", NULL);
            get_name_unit_descrip_format(table->aux_name+i, table->aux_unit+i,
                    table->aux_description+i, &ptr, buffer);
            if ((!ptr || 1!=sscanf(ptr, "%lf", table->aux_value+i)) && flags&GMCT_WARN_MISSING_AUXVAL)
                printf("warning: missing value for auxiliary quantity %s---zero assumed\n", table->aux_name[i]);
            }
        }
        
#if DEBUG
    for (i=0; i<table->n_auxiliaries; i++) {
        printf("auxiliary %ld:  %s = %le %s---%s\n", 
            i, table->aux_name[i], table->aux_value[i], table->aux_unit[i],
            table->aux_description[i]);
        }
#endif

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("missing number of data rows in table file", NULL);
    if (!get_long(&table->n_rows, buffer) || table->n_rows<0)
        bomb("invalid number of data rows specified in table file", NULL);
    if (table->n_rows==0)
        return(1);    

#if DEBUG
    printf("n_rows = %ld\n", table->n_rows);
#endif
    
    table->value = (double**)zarray_2d(sizeof(double), table->n_cols, table->n_rows);
    table->row_label = (char**)tmalloc(sizeof(char*)*table->n_rows);

    for (i=0; i<table->n_rows; i++) {
        i_col = 0;
        table->row_label[i] = NULL;
        for (j=0; j<table->n_lines_per_row && i_col<table->n_cols; j++) {
            if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
                break;
            strcpy(buffer1, buffer);
#if DEBUG
            printf("row %ld, line %ld:\n%s\n", i, j, buffer);
#endif
            while (i_col<table->n_cols && get_double(table->value[i_col]+i, buffer))
                i_col++;
            }

        if (!is_blank(buffer)) {
            cp_str(table->row_label+i, buffer);
            while (isspace(*table->row_label[i]))
                table->row_label[i]++;
            }
        else
            cp_str(table->row_label+i, "");

        if (i_col==0) {
            if (flags&GMCT_WARN_WRONG_COUNT)
                printf("warning: fewer data rows than expected in file %s\n", file);
            break;
            }
        else if (i_col!=table->n_cols) {
            if (flags&GMCT_WARN_INCOMPLETE_ROW) {
                printf("warning: incomplete data row in file %s\n", file);
                printf("line in question is:\n%s\n", buffer1);
                printf("skipping to next line\n");
                }
            i--;
            continue;
            }
#if DEBUG
        printf("%ld: ", i);
        for (i_col=0; i_col<table->n_cols; i_col++)
            printf("%.4le  ", table->value[i_col][i]);
        putchar('\n');
#endif
        }
    if (i==table->n_rows && fgets_mc_skip(buffer, 1024, fpi, '!') && flags&GMCT_WARN_EXTRA_ROWS)
        printf("warning: file %s contains extra rows, which are ignored\n",
                file);
    table->n_rows = i;
    return(1);
    }
Пример #8
0
void output_magnets(char *filename, char *line_name, LINE_LIST *beamline)
{
    ELEMENT_LIST *eptr;
    QUAD  *qptr;
    BEND  *bptr;
    KQUSE *kqsptr;
    KQUAD *kqptr;
    KSBEND *kbptr;
    CSBEND *cbptr;
    CSRCSBEND *csrbptr;
    long iPhase;
    double start, end, total_length, dz, value;
    FILE *fpm;

    log_entry("output_magnets");

    total_length = 0;
    eptr = &(beamline->elem);

    fpm = fopen_e(filename, "w", 0);

    start = end = 0;
    fprintf(fpm, "SDDS1\n&description text=\"magnet layout for beamline %s\" &end\n", line_name);
    fprintf(fpm, "&column name=ElementName, type=string &end\n");
    fprintf(fpm, "&column name=ElementType, type=string &end\n");
    fprintf(fpm, "&column name=s, units=m, type=double &end\n&column name=Profile, type=double &end\n");
    fprintf(fpm, "&data mode=ascii, no_row_counts=1 &end\n");

    eptr = &(beamline->elem);
    fprintf(fpm, "_BEGIN_ MARK 0 0\n");
    while (eptr) {
        switch (eptr->type) {
        case T_QUAD:
            qptr = (QUAD*)eptr->p_elem;
            fprintf(fpm, "%s %s %e  %d\n", eptr->name, entity_name[eptr->type], start, SIGN(qptr->k1));
            end = start+qptr->length;
            fprintf(fpm, "%s %s %e  %d\n%s %s %e  0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], end, SIGN(qptr->k1),
                    eptr->name, entity_name[eptr->type], end,
                    eptr->name, entity_name[eptr->type], start,
                    eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_KQUAD:
            kqptr = (KQUAD*)eptr->p_elem;
            if (kqptr->bore)
                value = kqptr->B;
            else
                value = kqptr->k1;
            fprintf(fpm, "%s %s %e  %d\n", eptr->name, entity_name[eptr->type], start, SIGN(value));
            end = start+kqptr->length;
            fprintf(fpm, "%s %s %e  %d\n%s %s %e  0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], end, SIGN(kqptr->k1),
                    eptr->name, entity_name[eptr->type], end,
                    eptr->name, entity_name[eptr->type], start,
                    eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_KQUSE:
            kqsptr = (KQUSE*)eptr->p_elem;
            value = kqsptr->k1;
            fprintf(fpm, "%s %s %e  %d\n", eptr->name, entity_name[eptr->type], start, SIGN(value));
            end = start+kqsptr->length;
            fprintf(fpm, "%s %s %e  %d\n%s %s %e  0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], end, SIGN(value),
                    eptr->name, entity_name[eptr->type], end,
                    eptr->name, entity_name[eptr->type], start,
                    eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_RBEN:
        case T_SBEN:
            bptr = (BEND*)eptr->p_elem;
            end  = start+bptr->length;
            if (bptr->angle>0)
                fprintf(fpm,
                        "%s %s %e .33333333\n%s %s %e .33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], start,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            else if (bptr->angle<0)
                fprintf(fpm,
                        "%s %s %e -.33333333\n%s %s %e -.33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], start,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_KSBEND:
            kbptr = (KSBEND*)eptr->p_elem;
            end  = start+kbptr->length;
            if (kbptr->angle>0)
                fprintf(fpm,
                        "%s %s %e .33333333\n%s %s %e .33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], start,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            else if (kbptr->angle<0)
                fprintf(fpm,
                        "%s %s %e -.33333333\n%s %s %e -.33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], start,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_SEXT:
            end = start+((SEXT*)eptr->p_elem)->length;
            fprintf(fpm, "%s %s %e  .5\n%s %s %e .5\n%s %s %e 0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], start,
                    eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_KSEXT:
            end = start+((KSEXT*)eptr->p_elem)->length;
            fprintf(fpm, "%s %s %e  .5\n%s %s %e .5\n%s %s %e 0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], start,
                    eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_HCOR:
            end    = start+((HCOR*)eptr->p_elem)->length;
            fprintf(fpm, "%s %s %e .25\n%s %s %e .25\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_VCOR:
            end    = start+((VCOR*)eptr->p_elem)->length;
            fprintf(fpm, "%s %s %e -.25\n%s %s %e -.25\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_HVCOR:
            end    = start+((HVCOR*)eptr->p_elem)->length;
            fprintf(fpm, "%s %s %e .25\n%s %s %e -.25\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_DRIF:
            start = (end = start+((DRIFT*)eptr->p_elem)->length);
            fprintf(fpm, "%s %s %e  0\n", eptr->name, entity_name[eptr->type], end);
            break;
        case T_HMON:
            dz = ((HMON*)eptr->p_elem)->length/2;
            fprintf(fpm, "%s %s %e 0.125\n%s %s %e 0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start+2*dz,
                    eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start+2*dz);
            start += 2*dz;
            break;
        case T_VMON:
            dz = ((VMON*)eptr->p_elem)->length/2;
            fprintf(fpm, "%s %s %e -0.125\n%s %s %e 0\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start+2*dz,
                    eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start+2*dz);
            start += 2*dz;
            break;
        case T_MONI:
            dz = ((MONI*)eptr->p_elem)->length/2;
            fprintf(fpm, "%s %s %e 0.125\n%s %s %e 0\n%s %s %e -0.125\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start+2*dz, eptr->name, entity_name[eptr->type], start+dz,
                    eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], start+2*dz);
            start += 2*dz;
            break;
        case T_MULT:
            dz = ((MULT*)eptr->p_elem)->length/3;
            fprintf(fpm, "%s %s %e 0.6666\n%s %s %e 0.6666\n%s %s %e 0\n%s %s %e -0.6666\n%s %s %e -0.6666\n%s %s %e 0\n%s %s %e 0\n",
                    eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start+2*dz, eptr->name, entity_name[eptr->type], start+3*dz,
                    eptr->name, entity_name[eptr->type], start+2*dz, eptr->name, entity_name[eptr->type], start+dz, eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], start+3*dz);
            start += 3*dz;
            break;
        case T_MARK:    /* zero-length drift */
            break;
        case T_CSBEND:
            cbptr = (CSBEND*)eptr->p_elem;
            end  = start+cbptr->length;
            if (cbptr->angle>0)
                fprintf(fpm,
                        "%s %s %e .33333333\n%s %s %e .33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            else if (cbptr->angle<0)
                fprintf(fpm,
                        "%s %s %e -.33333333\n%s %s %e -.33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_CSRCSBEND:
            csrbptr = (CSRCSBEND*)eptr->p_elem;
            end  = start+csrbptr->length;
            if (csrbptr->angle>0)
                fprintf(fpm,
                        "%s %s %e .33333333\n%s %s %e .33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            else if (csrbptr->angle<0)
                fprintf(fpm,
                        "%s %s %e -.33333333\n%s %s %e -.33333333\n%s %s %e  0\n%s %s %e  0\n%s %s %e  0\n%s %s %e 0\n",
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end, eptr->name, entity_name[eptr->type], end,
                        eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], start, eptr->name, entity_name[eptr->type], end);
            start = end;
            break;
        case T_RFCA:
        case T_TWLA:
        case T_RAMPRF:
        case T_RFCW:
        case T_MODRF:
            dz = ((DRIFT*)eptr->p_elem)->length;
            dz /= 8;
            for (iPhase=0; iPhase<9; iPhase++) {
                fprintf(fpm, "%s %s %e %e\n",
                        eptr->name, entity_name[eptr->type], start+dz*iPhase,
                        0.5*sin((iPhase/8.0)*PIx2));
            }
            start += dz*8;
            break;
        case T_MATR:
            dz = ((MATR*)eptr->p_elem)->length;
            fprintf(fpm, "%s %s %e %e\n", eptr->name, entity_name[eptr->type], start, 0.5);
            fprintf(fpm, "%s %s %e %e\n", eptr->name, entity_name[eptr->type], start+dz, -0.5);
            fprintf(fpm, "%s %s %e %e\n", eptr->name, entity_name[eptr->type], start+dz, 0.5);
            fprintf(fpm, "%s %s %e %e\n", eptr->name, entity_name[eptr->type], start, -0.5);
            fprintf(fpm, "%s %s %e %e\n", eptr->name, entity_name[eptr->type], start, 0.0);
            fprintf(fpm, "%s %s %e %e\n", eptr->name, entity_name[eptr->type], start+dz, 0.0);
            start += dz;
            break;
        default:
            if (entity_description[eptr->type].flags&HAS_LENGTH) {
                dz = ((DRIFT*)eptr->p_elem)->length;
                fprintf(fpm, "%s %s %e 0\n", eptr->name, entity_name[eptr->type], start+=dz);
            }
            break;
        }
        eptr = eptr->succ;
    }
    log_exit("output_magnets");
    fclose(fpm);
}
Пример #9
0
int main(int argc,char **argv)
{
    char reserved[100]; /* buffer to skip reserved bytes */
    short f_type; /* MCS file type */
    char trigger; /* Trigger Flag */
    char dwell_flag; /* External Dwell Flag */
    char dwell_units; /* 0=us, 1=ms, 2=sec, 3=ns */
    char acq_mode; /* Acquisition mode flag 0=replace, 1=sum */
    unsigned long dwell_913; /* Dwell time in old 913 format */
    unsigned short pass_length; /* pass length in channels */
    unsigned long pass_count;
    unsigned long pass_count_preset;
    char acq_time[9]; /* buffer for acquisition time */
    char acq_date[9]; /* buffer for acquisition date */
    unsigned short mark_chan; /* first marker channel */
    char mcs_num; /* 1-8 are valid */
    char cal_flag; /* 0=no calibration */
    char cal_units[4]; /* calibration units */
    float cal_zero; /* calibration zero intercept */
    float cal_slope; /* calibration slope */
    char id_byte; /* always 0xaa */
    char detector_len; /* Detector description length */
    char detector[65]; /* detector description */
    char sample_len; /* Sample description length */
    char sample[65]; /* Sample description */
    char disc_sel; /* 0=SCA otherwise Disc */
    char disc_edge; /* 0=falling else rising */
    float disc; /* disc setting in volts */
    float sca_uld; /* sca upper-level in volts */
    float sca_lld; /* sca lower-level in volts */
    float dwell; /* dwell time in dwell_units */
    char consistent; /* settings consistent flag */
    char mcs_id[9]; /* MCS ID string "0914-001" */
    
    FILE *fpi;
    char *input, *output;
    SDDS_DATASET SDDS_dataset;
    SCANNED_ARG *scanned;
    long i, i_arg;
    char ts1[256], ts2[256], ts3[256], ts4[256];
    unsigned long *ucount;
    long *count, *channel;
    long ascii;

    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&scanned, argc, argv);
    if (argc<3) 
        bomb(NULL, USAGE);
    input = output = NULL;
    ascii = 0;
    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_ASCII:
                ascii = 1;
                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");
    fpi = fopen_e(input, "r", 0);

    /***************************************************************************/
    /*    Header Data     */
    /* Read header info from MCS file */
    /***************************************************************************/
    /* Read filetype -4 (MCS) */
    fread(&f_type,sizeof(short),1,fpi);
    swapshort(&f_type);
    if (f_type != MCS) {
        fprintf(stderr, "Not a valid file: f_type = %hx\n", f_type);
        exit(1);
        }
    fread(&trigger,sizeof(char),1,fpi); /* Read Trigger Flag */
    fread(&dwell_flag,sizeof(char),1,fpi); /* Read dwell flag */
    fread(&dwell_units,sizeof(char),1,fpi);/* Read dwell units */
    fread(&acq_mode,sizeof(char),1,fpi);
    fread(&dwell_913,sizeof(long),1,fpi);
    swapulong(&dwell_913);
    fread(&pass_length,sizeof(short),1,fpi);
    swapushort(&pass_length);
    fread(&pass_count,sizeof(long),1,fpi);
    swapulong(&pass_count);
    fread(&pass_count_preset,sizeof(long),1,fpi);
    swapulong(&pass_count_preset);
    fread(acq_time,sizeof(char),8,fpi);
    fread(acq_date,sizeof(char),8,fpi);
    fread(&mark_chan,sizeof(short),1,fpi);
    swapushort(&mark_chan);
    fread(&mcs_num,sizeof(char),1,fpi);
    fread(&cal_flag,sizeof(char),1,fpi);
    fread(cal_units,sizeof(char),4,fpi);
    fread(&cal_zero,sizeof(float),1,fpi);
    swapfloat(&cal_zero);
    fread(&cal_slope,sizeof(float),1,fpi);
    swapfloat(&cal_slope);
    fread(reserved,sizeof(char),10,fpi);
    fread(&id_byte,sizeof(char),1,fpi);
    fread(reserved,sizeof(char),1,fpi);
    fread(&detector_len,sizeof(char),1,fpi);
    fread(detector,sizeof(char),63,fpi);
    fread(&sample_len,sizeof(char),1,fpi);
    fread(sample,sizeof(char),63,fpi);
    fread(reserved,sizeof(char),16,fpi); /* skip view info & reserved */
    fread(&disc_sel,sizeof(char),1,fpi);
    fread(&disc_edge,sizeof(char),1,fpi);
    fread(&disc,sizeof(float),1,fpi);
    swapfloat(&disc);
    fread(&sca_uld,sizeof(float),1,fpi);
    swapfloat(&sca_uld);
    fread(&sca_lld,sizeof(float),1,fpi);
    swapfloat(&sca_lld);
    fread(&dwell,sizeof(float),1,fpi);
    swapfloat(&dwell);
    fread(&consistent,sizeof(char),1,fpi);
    fread(reserved,sizeof(char),21,fpi);
    fread(mcs_id,sizeof(char),8,fpi);
    mcs_id[8]=0;

    sprintf(ts1, "%hd", mcs_num+1);
    sprintf(ts2, "%hd", pass_length);
    sprintf(ts3, "%ld", pass_count);
    sprintf(ts4, "%ld", pass_count_preset);
    
    if (!SDDS_InitializeOutput(&SDDS_dataset, ascii?SDDS_ASCII:SDDS_BINARY, 1, "Turbo MCS data", "Turbo MCS data", output) ||
        SDDS_DefineParameter(&SDDS_dataset, "MCSNumber", NULL, NULL, "MCS number", NULL, SDDS_SHORT, 
                             ts1)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "MCSID", NULL, NULL, "MCS ID", NULL, SDDS_STRING, mcs_id)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "PassLength", NULL, NULL, "Pass length", NULL, SDDS_SHORT,
                             ts2)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "PassCount", NULL, NULL, "Pass count", NULL, SDDS_LONG,
                             ts3)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "PassCountPreset", NULL, NULL, "Pass count preset", NULL, SDDS_LONG,
                             ts4)<0)
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (dwell_flag == 0) {
        if (dwell_units==0)
            dwell *= 1e-6;
        else if (dwell_units==1) 
            dwell *= 1e-3;
        else if (dwell_units==3) 
            dwell *= 1e-9;
        } 
    else 
        dwell = -1;
    sprintf(ts1, "%15.8e", dwell);
    sprintf(ts2, "%8s %8s", acq_time,acq_date);
    if (SDDS_DefineParameter(&SDDS_dataset, "DwellTime", NULL, "s", "Dwell time", NULL, SDDS_DOUBLE, 
                             ts1)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "TriggerMode", NULL, NULL, "Trigger mode", NULL, SDDS_STRING,
                             trigger?"external":"internal")<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "AcquisitionMode", NULL, NULL, "Acquisition mode", NULL, SDDS_STRING,
                             acq_mode?"sum":"replace")<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "TimeStamp", NULL, NULL, "Time at which data collection started", NULL, SDDS_STRING,
                             ts2)<0)
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        
    sprintf(ts1, "%15.8e", cal_slope);
    sprintf(ts2, "%15.8e", cal_zero);
    if (cal_flag && 
        (SDDS_DefineParameter(&SDDS_dataset, "CalibrationSlope", NULL, cal_units, "Spectrum calibration slope", NULL, SDDS_DOUBLE, ts1)<0 ||
         SDDS_DefineParameter(&SDDS_dataset, "CalibrationOffset", NULL, cal_units, "Spectrum calibration slope", NULL, SDDS_DOUBLE, ts2)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (detector_len) {
        detector[(unsigned)detector_len] = 0;
        if (SDDS_DefineParameter(&SDDS_dataset, "HardwareDescription", NULL, NULL, 
                                  NULL, NULL, SDDS_DOUBLE, detector)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        }
    
    if (sample_len) {
        sample[(unsigned)sample_len] = 0;
        if (SDDS_DefineParameter(&SDDS_dataset, "DataDescription", NULL, NULL, 
                                 NULL, NULL, SDDS_STRING, sample)<0 ||
            SDDS_DefineParameter(&SDDS_dataset, "mplTitle", NULL, NULL, 
                                 NULL, NULL, SDDS_STRING, sample)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        }
    
    if (disc_sel == 0) {
        sprintf(ts1, "%15.8e", sca_lld);
        sprintf(ts2, "%15.8e", sca_uld);
        if (SDDS_DefineParameter(&SDDS_dataset, "SCA-LLD", NULL, "V", "SCA Lower-Level Discriminator Setting",
                                  NULL, SDDS_DOUBLE, ts1)<0 ||
            SDDS_DefineParameter(&SDDS_dataset, "SCA-ULD", NULL, "V", "SCA Upper-Level Discriminator Setting",
                                 NULL, SDDS_DOUBLE, ts2)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        } 
    else {
        sprintf(ts1, "%15.8e", disc);
        if (SDDS_DefineParameter(&SDDS_dataset, "DiscrimLevel", NULL, "V", "Discriminator Level",
				 NULL, SDDS_DOUBLE, ts1)<0 ||
            SDDS_DefineParameter(&SDDS_dataset, "DiscrimSlope", NULL, NULL, "Discriminator Slope",
                                 NULL, SDDS_LONG, disc_edge?"+1":"-1")<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        }

    if (consistent==0) {
        if (SDDS_DefineParameter(&SDDS_dataset, "Inconsistent", NULL, NULL, 
                                  "Flag indicating whether data and settings are inconsistent",
                                  NULL, SDDS_LONG, "1")<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        fprintf(stderr, "WARNING: Settings are not consistent with data\n");
        }
    
    if (SDDS_DefineColumn(&SDDS_dataset, "ChannelNumber", NULL, NULL, "Channel number", NULL, SDDS_LONG, 0)<0 ||
        SDDS_DefineColumn(&SDDS_dataset, "EventCount", NULL, NULL, "Number of events", NULL, SDDS_LONG, 0)<0 ||
        !SDDS_WriteLayout(&SDDS_dataset) || !SDDS_StartPage(&SDDS_dataset, (long)pass_length))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        
    /***************************************************************************/
    /*    Channel Data     */
    /* Output channel data from MCS file */
    /***************************************************************************/
    channel = tmalloc(sizeof(*channel)*pass_length);
    count   = tmalloc(sizeof(*count)*pass_length);
    ucount   = tmalloc(sizeof(*ucount)*pass_length);
    if (fread(ucount, sizeof(*ucount), pass_length, fpi)!=pass_length)
        SDDS_Bomb("unable to read channel data");
    for (i=0; i<(long)pass_length; i++) {
        swapulong(ucount+i);
        count[i] = (long)ucount[i];
        channel[i] = i;
        }
    if (!SDDS_SetColumn(&SDDS_dataset, SDDS_SET_BY_NAME, channel, (long)pass_length, "ChannelNumber") ||
        !SDDS_SetColumn(&SDDS_dataset, SDDS_SET_BY_NAME, count, (long)pass_length, "EventCount") ||
        !SDDS_WritePage(&SDDS_dataset) || !SDDS_Terminate(&SDDS_dataset))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    fclose(fpi);
    return(0);
}
Пример #10
0
int main(int argc, char **argv)
{
    double x_lo, x_hi, y_lo, y_hi, dx, dy, x, y;
    double **z_data, z_min, z_max, z_val;
    long ix, iy, nx, ny;
    long x_rpn_var, y_rpn_var;
    char *z_equation = NULL;
    char *rpn_defns_file;
    char *rpn_init_command;
    char *z_udf = "Z.UDF";
    char *input, *output, *label[4];
    long i_arg;
    SCANNED_ARG *s_arg;
    FILE *fp;
    unsigned long pipeFlags;
    char pfix[IFPF_BUF_SIZE], *ptr;
    char * rpn_defns;
#if defined(LINUX)
    struct stat sts;
#endif

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

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

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

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

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

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

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

    if (output)
        fp = fopen_e(output, "w", 0);
    else
        fp = stdout;
    fprintf(fp, "SDDS1\n&parameter name=Variable1Name, type=string, fixed_value=x &end\n");
    fprintf(fp, "&parameter name=Variable2Name, type=string, fixed_value=y &end\n");
    fprintf(fp, "&parameter name=xInterval, type=double, fixed_value=%e &end\n", dx);
    fprintf(fp, "&parameter name=xMinimum, type=double, fixed_value=%e &end\n", x_lo);
    fprintf(fp, "&parameter name=xDimension, type=long, fixed_value=%ld &end\n", nx);
    fprintf(fp, "&parameter name=yInterval, type=double, fixed_value=%e &end\n", dy);
    fprintf(fp, "&parameter name=yMinimum, type=double, fixed_value=%e &end\n", y_lo);
    fprintf(fp, "&parameter name=yDimension, type=long, fixed_value=%ld &end\n", ny);
    fprintf(fp, "&column name=z, type=double, description=\"%s\" &end\n", z_equation);
    fprintf(fp, "&data mode=ascii, no_row_counts=1 &end\n");
    for (ix=0; ix<nx; ix++)
         for (iy=0; iy<ny; iy++)
             fprintf(fp, "%e\n", z_data[ix][iy]);
    return(0);
}
Пример #11
0
int main(int argc, char **argv)
{
    long i, return_code;
    char *ptr;
    static char *input;
    static char *rpn_defns;
#if defined(LINUX)
    struct stat sts;
#endif

#ifdef VAX_VMS
    /* initialize collection of computer usage statistics--required by
     * user-callable function 'rs'
     */
    init_stats();
#endif

    puts("Welcome to rpn version 6, by Michael Borland and Robert Soliday (June 1999).");

    /* sort the command table for faster access */
    /*qsort(func, NFUNCS, sizeof(struct FUNCTION), func_compare); */
    qsort(funcRPN, sizeof(funcRPN)/sizeof(funcRPN[0]), sizeof(struct FUNCTION), func_compare);
    /* initialize stack pointers--empty stacks */
    stackptr = 0;
    sstackptr = 0;
    lstackptr = 0;
    astackptr = 0;
    dstackptr = 0;
    astack = NULL;
    udf_stackptr = 0;
    max_udf_stackptr = 0;
    udf_stack = NULL;
    udf_cond_stackptr = 0;
    max_udf_cond_stackptr = 0;
    udf_cond_stack = NULL;
    udf_id = NULL;	
    udf_unknown = NULL;

    /* The first item on the command input stack is the standard input.
     * Input from this source is echoed to the screen. */
    istackptr = 1;
    input_stack[0].fp = stdin;
    input_stack[0].filemode = ECHO;

    /* Initialize variables use in keeping track of what 'code' is being
     * executed.  code_ptr is a global pointer to the currently used
     * code structure.  The code is kept track of in a linked list of
     * code structures.
     */
    code_ptr = &code;
    input = code_ptr->text = tmalloc(sizeof(*(code_ptr->text))*CODE_LEN);
    code_ptr->position = 0;
    code_ptr->token = NULL;
    code_ptr->storage_mode = STATIC;
    code_ptr->buffer = tmalloc(sizeof(*(code_ptr->buffer))*LBUFFER);
    code_ptr->pred = code_ptr->succ = NULL;
    code_lev = 1;

    /* Initialize array of IO file structures.  Element 0 is for terminal
     * input, while element 1 is for terminal output.
     */
    for (i=0; i<FILESTACKSIZE; i++)
        io_file[i].fp = NULL;
    io_file[0].fp = stdin;
    cp_str(&(io_file[0].name), "stdin");
    io_file[0].mode = INPUT;
    io_file[1].fp = stdout;
    cp_str(&(io_file[1].name), "stdout");
    io_file[1].mode = OUTPUT;

    /* initialize variables for UDF storage */
    udf_changed = num_udfs = max_udfs = 0;
    udf_list = NULL;

    /* Initialize flags for user memories */
    n_memories = memory_added = 0;

    /* If there are arguments push them onto the input stack
     * so that it will be run to set up the program.
     */
    while (argc-- >= 2) {
        input_stack[istackptr].fp = fopen_e(argv[argc], "r", 0);
        input_stack[istackptr++].filemode = NO_ECHO;
        }

    /*add default setting for a linux system, G. Shen, Dec 31, 2009 */
    rpn_defns=getenv("RPN_DEFNS");
    if(!rpn_defns) {
#if defined(LINUX)
	if (!(stat(rpn_default, &sts) == -1 && errno == ENOENT)) { /* check whether default file exists */
	    rpn_defns = rpn_default;
	}
#endif
    }
    if (rpn_defns && (long)strlen(rpn_defns)>0 ) {
        /* push rpn definitions file onto top of the stack */
        input_stack[istackptr].fp = fopen_e(rpn_defns, "r", 0);
        input_stack[istackptr++].filemode = NO_ECHO;
        }

    /* This is the main loop. Code is read in and executed here. */
    while (istackptr!=0) {
        /* istackptr-1 gives index of most recently pushed input file. */
        /* This loop implements the command input file stacking. */
#ifdef DEBUG
        fprintf(stderr, "istackptr = %ld\n", istackptr);
#endif
        while (prompt("rpn> ", !(istackptr-1)),
                ptr=fgets((code_ptr->text=input), CODE_LEN,
                input_stack[istackptr-1].fp)) {
            /* Loop while there's still data in the (istackptr-1)th file. *
             * The data is put in the code list.                          */
#ifdef DEBUG
            fprintf(stderr, "input string: >%s<\n", ptr);
#endif
            /* If we are at the terminal input level and a UDF has been changed
             * or a memory added, relink the udfs to get any references to the
             * new udf or memory translated into 'pcode'.
             */
            if ((udf_changed) || memory_added) {
#ifdef DEBUG
                fputs("re-linking udfs", stderr);
#endif
                link_udfs();
                udf_changed = memory_added = 0;
                }
            code_ptr->position = 0;

            /* Get rid of new-lines in data from files, and echo data to  *
             * screen if appropriate.                                     */
            if (istackptr!=1 && ptr!=NULL) {
#ifdef DEBUG
                fputs("truncating input line", stderr);
#endif
                chop_nl(ptr);
                if (input_stack[istackptr-1].filemode==ECHO)
                    puts(ptr);
                }

            /* Check for and ignore comment lines. */
#ifdef DEBUG
            fputs("checking for comment line", stderr);
#endif
            if (strncmp(ptr, "/*", 2)==0)
                continue;

            /* Finally, push input line onto the code stack & execute it.   */
#ifdef DEBUG
            fputs("pushing onto stack and executing", stderr);
#endif
            return_code = execute_code();
	    cycle_counter = 0;

            if (code_lev!=1) {
                fputs("error: code level on return from execute_code is not 1\n", stderr);
                exit(1);
                }
            /* Reset pointers in the current code structure to indicate that the
             * stuff has been executed.
             */
#ifdef DEBUG
            fputs("reseting pointers", stderr);
#endif
            *(code_ptr->text) = 0;
            code_ptr->position = 0;

            /* If it's appropriate to print the top of the numeric or logical *
             * stacks, do so here.                                            */
            if (stackptr>=1 && return_code==NUMERIC_FUNC )
                printf(choose_format(format_flag, stack[stackptr-1]),
                                    ' ', stack[stackptr-1], '\n');
            if (lstackptr>=1 && return_code==LOGICAL_FUNC)
                printf("%s\n", (logicstack[lstackptr-1])?"true":"false");
            }

        /* Close the current input file and go to the one below it on the *
         * stack.  This constitutes popping the command input stack.      *
         */
#ifdef DEBUG
        fputs("closing input file", stderr);
#endif
        fclose(input_stack[--istackptr].fp);
        }
    return(0);
    }
Пример #12
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);
}
Пример #13
0
int main(int argc, char **argv)
{
    SDDS_DATASET SDDS_dataset;
    SCANNED_ARG *scanned;
    long i_arg;
    char *input, *output, *definition;
    long hsize, vsize;
    char *data, *data_name;
    char header[200];
    char ts1[100], ts2[100];
    FILE *fpi;
    unsigned long pipeFlags, majorOrderFlag;
    short columnMajorOrder = 0;

    SDDS_RegisterProgramName(argv[0]);

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

    input = output = data_name = NULL;
    definition = NULL;
    pipeFlags = 0;
    hsize = vsize = 0;
    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_PIPE:
              if (!processPipeOption(scanned[i_arg].list+1, scanned[i_arg].n_items-1, &pipeFlags))
                SDDS_Bomb("invalid -pipe syntax");
              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);
        }
    }
    
    processFilenames("lba2sdds", &input, &output, pipeFlags, 0, NULL);

    if (!definition)
        SDDS_Bomb("definition not seen");

    if (input)
        fpi = fopen_e(input, "r", 0);
    else
        fpi = stdin;

    if (fread(header, sizeof(*header), 200, fpi)!=200) 
        SDDS_Bomb("unable to read LBA file header");
    switch (header[0]) {
      case 'A':
        hsize = vsize = 120;
        break;
      case 'B':
        vsize = 256;
        hsize = 240;
        break;
      case 'C':
        vsize = 512;
        hsize = 480;
        break;
      default:
        SDDS_Bomb("data does not appear to be in LBA format--invalid frame type");
        break;
        }

    sprintf(ts1, "%ld", hsize);
    sprintf(ts2, "%ld", vsize);
    if (!SDDS_InitializeOutput(&SDDS_dataset, SDDS_BINARY, 0, 
                               "screen image from LBA file", "screen image",
                               output) ||
        SDDS_ProcessColumnString(&SDDS_dataset, definition, 0)<0 || 
        SDDS_DefineParameter(&SDDS_dataset, "NumberOfRows", NULL, NULL, "number of rows",
                             NULL, SDDS_LONG, ts1)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "NumberOfColumns", NULL, NULL, 
                             "number of columns", NULL, SDDS_LONG,
                             ts2)<0) 
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_dataset.layout.data_mode.column_major = columnMajorOrder;
    if (!SDDS_WriteLayout(&SDDS_dataset))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    
    data = tmalloc(sizeof(*data)*hsize*vsize);
    do {
        if (fread(data, sizeof(*data), hsize*vsize, fpi)!=hsize*vsize)
            SDDS_Bomb("unable to read (all) data from input file");
        if (!SDDS_StartPage(&SDDS_dataset, hsize*vsize) ||
            !SDDS_SetColumn(&SDDS_dataset, SDDS_SET_BY_NAME, data, hsize*vsize, 
                            data_name) ||
            !SDDS_WritePage(&SDDS_dataset))
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        } while (fread(header, sizeof(*header), 200, fpi)==200) ;
    fclose(fpi);
    if (!SDDS_Terminate(&SDDS_dataset))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
Пример #14
0
void setup_chromaticity_correction(NAMELIST_TEXT *nltext, RUN *run, LINE_LIST *beamline, CHROM_CORRECTION *chrom)
{
    VMATRIX *M;
    ELEMENT_LIST *eptr, *elast;
#include "chrom.h"
    unsigned long unstable;
    
    log_entry("setup_chromaticity_correction");

    cp_str(&sextupoles, "sf sd");

    /* process namelist input */
    set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
    set_print_namelist_flags(0);
    if (processNamelist(&chromaticity, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    str_toupper(sextupoles);
    if (echoNamelists) print_namelist(stdout, &chromaticity);

    if (run->default_order<2)
        bombElegant("default order must be >= 2 for chromaticity correction", NULL);

    if (chrom->name)
        tfree(chrom->name);
    chrom->name = tmalloc(sizeof(*chrom->name)*(chrom->n_families=1));
    while ((chrom->name[chrom->n_families-1]=get_token(sextupoles)))
        chrom->name = trealloc(chrom->name, sizeof(*chrom->name)*(chrom->n_families+=1));
    if ((--chrom->n_families)<1)
        bombElegant("too few sextupoles given for chromaticity correction", NULL);
    chrom->chromx = dnux_dp;
    chrom->chromy = dnuy_dp;
    chrom->n_iterations = n_iterations;
    chrom->correction_fraction = correction_fraction;
    alter_defined_values = change_defined_values;
    chrom->strengthLimit = strength_limit;
    chrom->use_perturbed_matrix = use_perturbed_matrix;
    chrom->sextupole_tweek = sextupole_tweek;
    chrom->tolerance = tolerance;
    verbosityLevel = verbosity;
    chrom->exit_on_failure = exit_on_failure;
    
    if (!use_perturbed_matrix) {
      if (!beamline->twiss0 || !beamline->matrix) {
        double beta_x, alpha_x, eta_x, etap_x;
        double beta_y, alpha_y, eta_y, etap_y;

        fprintf(stdout, "Computing periodic Twiss parameters.\n");
        fflush(stdout);

        if (!beamline->twiss0)
          beamline->twiss0 = tmalloc(sizeof(*beamline->twiss0));

        eptr = beamline->elem_twiss = &(beamline->elem);
        elast = eptr;
        while (eptr) {
          if (eptr->type==T_RECIRC)
            beamline->elem_twiss = beamline->elem_recirc = eptr;
          elast = eptr;
          eptr = eptr->succ;
        }
        if (beamline->links) {
          /* rebaseline_element_links(beamline->links, run, beamline); */
          if (assert_element_links(beamline->links, run, beamline, STATIC_LINK+DYNAMIC_LINK)) {
            beamline->flags &= ~BEAMLINE_CONCAT_CURRENT;
            beamline->flags &= ~BEAMLINE_TWISS_CURRENT;
            beamline->flags &= ~BEAMLINE_RADINT_CURRENT;
          }
        }
        
        M = beamline->matrix = compute_periodic_twiss(&beta_x, &alpha_x, &eta_x, &etap_x, beamline->tune,
                                                      &beta_y, &alpha_y, &eta_y, &etap_y, beamline->tune+1, 
                                                      beamline->elem_twiss, NULL, run, 
                                                      &unstable, NULL, NULL);
        beamline->twiss0->betax  = beta_x;
        beamline->twiss0->alphax = alpha_x;
        beamline->twiss0->phix   = 0;
        beamline->twiss0->etax   = eta_x;
        beamline->twiss0->etapx  = etap_x;
        beamline->twiss0->betay  = beta_y;
        beamline->twiss0->alphay = alpha_y;
        beamline->twiss0->phiy   = 0;
        beamline->twiss0->etay   = eta_y;
        beamline->twiss0->etapy  = etap_y;
        
        propagate_twiss_parameters(beamline->twiss0, beamline->tune, beamline->waists,
                                   NULL, beamline->elem_twiss, run, NULL,
				   beamline->couplingFactor);
      }

      if (!(M=beamline->matrix) || !M->C || !M->R || !M->T)
        bombElegant("something wrong with transfer map for beamline (setup_chromaticity_correction)", NULL);

      computeChromCorrectionMatrix(run, beamline, chrom);
    }
    
#if USE_MPI
    if (!writePermitted)
       strength_log = NULL;
#endif
    if (strength_log) {
        strength_log = compose_filename(strength_log, run->rootname);
        fp_sl = fopen_e(strength_log, "w", 0);
        fprintf(fp_sl, "SDDS1\n&column name=Step, type=long, description=\"Simulation step\" &end\n");
        fprintf(fp_sl, "&column name=K2, type=double, units=\"1/m$a2$n\" &end\n");
        fprintf(fp_sl, "&column name=SextupoleName, type=string  &end\n");
        fprintf(fp_sl, "&data mode=ascii, no_row_counts=1 &end\n");
        fflush(fp_sl);
        }

    log_exit("setup_chromaticity_correction");
    
}
Пример #15
0
double rpn(char *expression)
{
    static long i, return_code;
    static char *ptr;
    static char *input, *rpn_defns;
    static long initial_call = 1;
#if defined(LINUX)
    struct stat sts;
#endif

    if (initial_call) {
        initial_call = 0;

#ifdef VAX_VMS
        /* initialize collection of computer usage statistics--required by
         * user-callable function 'rs'
         */
        init_stats();
#endif

        /* sort the command table for faster access */
        qsort(funcRPN, NFUNCS, sizeof(struct FUNCTION), func_compare);

        /* initialize stack pointers--empty stacks */
        stackptr = 0;
        dstackptr = 0;
        sstackptr = 0;
        lstackptr = 0;
        astackptr = 0;
	udf_stackptr = 0;
	max_udf_stackptr = 0;
        astack = NULL;
	udf_stack = NULL;
	udf_id = NULL;
	udf_unknown = NULL;

        /* The first item on the command input stack is the standard input.
         * Input from this source is echoed to the screen. */
        istackptr = 1;
        input_stack[0].fp = stdin;
        input_stack[0].filemode = ECHO;


       /* Initialize variables use in keeping track of what 'code' is being
         * executed.  code_ptr is a global pointer to the currently used
         * code structure.  The code is kept track of in a linked list of
         * code structures.
         */
        code_ptr = &code;
        input = code_ptr->text = tmalloc(sizeof(*(code_ptr->text))*CODE_LEN);
        code_ptr->position = 0;
        code_ptr->token = NULL;
        code_ptr->storage_mode = STATIC;
        code_ptr->buffer = tmalloc(sizeof(*(code_ptr->buffer))*LBUFFER);
        code_ptr->pred = code_ptr->succ = NULL;
        code_lev = 1;

        /* Initialize array of IO file structures.  Element 0 is for terminal
         * input, while element 1 is for terminal output.
         */
        for (i=0; i<FILESTACKSIZE; i++)
            io_file[i].fp = NULL;
        io_file[0].fp = stdin;
        cp_str(&(io_file[0].name), "stdin");
        io_file[0].mode = INPUT;
        io_file[1].fp = stdout;
        cp_str(&(io_file[1].name), "stdout");
        io_file[1].mode = OUTPUT;

        /* initialize variables for UDF storage */
        udf_changed = num_udfs = max_udfs = 0;
        udf_list = NULL;

        /* Initialize flags for user memories */
        n_memories = memory_added = 0;

        /* If there was an argument (filename), push it onto the input stack
         * so that it will be run to set up the program.
         */
        if (expression) {
          if ((input_stack[istackptr].fp = fopen_e(expression, "r", 1))==NULL) {
            fprintf(stderr, "ensure the RPN_DEFNS environment variable is set\n");
            exit(1);
          }
          input_stack[istackptr++].filemode = NO_ECHO;
        }
        else { /*add default setting for a linux system, G. Shen, Dec 31, 2009 */
	    rpn_defns=getenv("RPN_DEFNS");
	    if(!rpn_defns) {
#if defined(LINUX)
		if (!(stat(rpn_default, &sts) == -1 && errno == ENOENT)) { /* check whether default file exists */
		    rpn_defns = rpn_default;
		}
#endif
	    }
	    if (rpn_defns) {
            /* check environment variable RPN_DEFNS for setup file */
		/*cp_str(&rpn_defns, getenv("RPN_DEFNS"));*/
		if (strlen(rpn_defns)) {
		    input_stack[istackptr].fp = fopen_e(rpn_defns, "r", 0);
		    input_stack[istackptr++].filemode = NO_ECHO;
                }
            }
	}
        expression = NULL;

        /* end of initialization section */
        }
    else
        istackptr = 1;

    /* check the stacks for overflows */

    if (stackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: numeric stack size overflow (rpn).\n");
        abort();
        }
/*
    if (astackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: array stack size overflow (rpn).\n");
        abort();
        }
*/
    if (sstackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: string stack size overflow (rpn).\n");
        abort();
        }
    if (lstackptr>=LOGICSTACKSIZE-1) {
        fprintf(stderr, "error: logic stack size overflow (rpn).\n");
        abort();
        }


    /* This is the main loop. Code is read in and executed here. */
    while (istackptr!=0) {
        /* istackptr-1 gives index of most recently pushed input file. */
        /* This loop implements the command input file stacking. */
        while (istackptr>0 &&
               (ptr=((istackptr-1)?fgets((code_ptr->text=input), CODE_LEN,
                                     input_stack[istackptr-1].fp)
                                 :(expression?strcpy(code_ptr->text,expression):NULL) )) ) {
            /* Loop while there's still data in the (istackptr-1)th file. *
             * istackptr=1 corresponds to the expression passed.          *
             * The data is put in the code list.                          */

            /* If we are at the terminal input level and a UDF has been changed
             * or a memory added, relink the udfs to get any references to the
             * new udf or memory translated into 'pcode'.
             */
            if ((istackptr==1 && udf_changed) || memory_added) {
                link_udfs();
                udf_changed = memory_added = 0;
                }
            code_ptr->position = 0;

            /* Get rid of new-lines in data from files */
            if (istackptr!=1 && ptr!=NULL) {
                chop_nl(ptr);
                }

            /* Check for and ignore comment lines. */
            if (strncmp(ptr, "/*", 2)==0)
                continue;

            /* Finally, push input line onto the code stack & execute it.   */
            return_code = execute_code();
            if (code_lev!=1) {
                fputs("error: code level on return from execute_code is not 1\n\n", stderr);
                exit(1);
                }
            /* Reset pointers in the current code structure to indicate that the
             * stuff has been executed.
             */
            *(code_ptr->text) = 0;
            code_ptr->position = 0;

            expression = NULL;
            }

        /* Close the current input file and go to the one below it on the *
         * stack.  This constitutes popping the command input stack.      *
         */
        if (istackptr>1)
            fclose(input_stack[--istackptr].fp);
        else
            istackptr--;
        }

    /* check the stacks for overflows */
    if (stackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: numeric stack size overflow (rpn).\n");
        abort();
        }
/*
    if (astackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: array stack size overflow (rpn).\n");
        abort();
        }
*/
    if (sstackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: string stack size overflow (rpn).\n");
        abort();
        }
    if (lstackptr>=LOGICSTACKSIZE-1) {
        fprintf(stderr, "error: logic stack size overflow (rpn).\n");
        abort();
        }

    if (stackptr>0)
        return(stack[stackptr-1]);
    return(0.0);
    }
Пример #16
0
void convert_to_EmmaMatlab(char *outputfile, LINE_LIST *beamline, char *header_file, char *ender_file)
{
    ELEMENT_LIST *eptr;
    QUAD  *quad;
    SEXT  *sext;
    BEND  *bend;
    HCOR  *hcor;
    VCOR  *vcor;
    DRIFT *drift;
    CSBEND *csbend;
    CSRCSBEND *csrbend;
    CSRDRIFT *csrdrift;
    FILE *fpi, *fp;
    double length, angle, k1, E1, E2;
    long slices;
    char s[256];
    

    fp = fopen_e(outputfile, "w", 0);

    if (header_file) {
        fpi = fopen_e(header_file, "r", 1);
        while (fgets(s, 256, fpi))
            fputs(s, fp);
        fclose(fpi);
        }

    eptr = &(beamline->elem);
    
    while (eptr) {
      length = angle = k1 = E1 = E2 = slices = 0;
      switch (eptr->type) {
      case T_QUAD:
        quad = (QUAD*)eptr->p_elem;
        k1 = quad->k1;
        length = quad->length;
        break;
      case T_SBEN:
        bend = (BEND*)eptr->p_elem;
        angle = bend->angle;
        E1 = bend->e1;
        E2 = bend->e2;
        length = bend->length;
        k1 = bend->k1;
        break;
      case T_CSBEND:
        csbend = (CSBEND*)eptr->p_elem;
        angle = csbend->angle;
        E1 = csbend->e1;
        E2 = csbend->e2;
        length = csbend->length;
        k1 = csbend->k1;
        slices = csbend->n_kicks;
        break;
      case T_CSRCSBEND:
        csrbend = (CSRCSBEND*)eptr->p_elem;
        angle = csrbend->angle;
        E1 = csrbend->e1;
        E2 = csrbend->e2;
        length = csrbend->length;
        k1 = csrbend->k1;
        slices = csrbend->n_kicks;
        break;
      case T_DRIF:
        drift = (DRIFT*)eptr->p_elem;
        length = drift->length;
        break;
      case T_CSRDRIFT:
        csrdrift = (CSRDRIFT*)eptr->p_elem;
        length = csrdrift->length;
        break;
      case T_SEXT:
        sext = (SEXT*)eptr->p_elem;
        length = sext->length;
        break;
      case T_HCOR:
        hcor = (HCOR*)eptr->p_elem;
        length = hcor->length;
        break;
      case T_VCOR:
        vcor = (VCOR*)eptr->p_elem;
        length = vcor->length;
        break;
      default:
        fprintf(stderr, "warning: entity type %s not implemented\n",
               entity_name[eptr->type]);
        break;
      }
      fprintf(fp, "%21.15g %21.15g %21.15g %21.15g %21.15g %ld 0\n",
              length, angle, k1, E1, E2, slices);
      eptr = eptr->succ;
    }

    if (ender_file) {
        fpi = fopen_e(ender_file, "r", 1);
        while (fgets(s, 256, fpi))
            fputs(s, fp);
        fclose(fpi);
        }
    }
Пример #17
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);
}