示例#1
0
int
main(int argc, char **argv)
{
	cwp_String key1,  key2;	/* x and y key header words	*/
	Value  val1,  val2;	/* ... their values		*/
	cwp_String type1, type2;/* ... their types		*/
	int index1, index2;	/* ... their indices in hdr.h	*/
	float x, y;		/* temps to hold current x & y 	*/
	cwp_String outpar;	/* name of par file		*/
	register int npairs;	/* number of pairs found	*/


	/* Hook up getpars */
	initargs(argc, argv);
	requestdoc(1);


	/* Prevent byte codes from spilling to screen */
	if (isatty(STDOUT)) err("must redirect or pipe binary output");


	/* Get parameters */
	if (!getparstring("key1", &key1))	key1 = "sx";
	if (!getparstring("key2", &key2))	key2 = "gx";

	type1 = hdtype(key1);
	type2 = hdtype(key2);

	index1 = getindex(key1);
	index2 = getindex(key2);


	/* Loop over traces */
	npairs = 0;
	while(gettr(&tr)) {

		gethval(&tr, index1, &val1);
		gethval(&tr, index2, &val2);

		x = vtof(type1, val1);
		y = vtof(type2, val2);

		efwrite(&x, FSIZE, 1, stdout);
		efwrite(&y, FSIZE, 1, stdout);

		++npairs;
	}


	/* Make parfile if needed */
	if (getparstring("outpar", &outpar))
		fprintf(efopen(outpar, "w"),
			"n=%d label1=%s label2=%s\n",
			npairs, key1, key2);

	return(CWP_Exit());
}
示例#2
0
int
main(int argc, char **argv)
{
	double sx, sy, gx, gy, factor;
	float mx, my;
        short unit;                                                           
	int degree;
	cwp_String outpar;
	register int npairs;


	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);

	if (!getparint("degree", &degree)) degree=0;

	npairs = 0;
	while (gettr(&tr)) {

		sx = tr.sx;
		sy = tr.sy;
		gx = tr.gx;
		gy = tr.gy;

                unit = tr.counit;
		
		/* If tr.scalco not set, use 1 as the value */
		factor = (!tr.scalco) ? 1 : tr.scalco;
		
                /* factor < 0 means divide; factor > 0 means to multiply */
                if (factor < 0) factor = -1/factor;

                /* if necessary, convert from seconds to degrees */
                if (unit == 2 && degree == 1) factor /= 3600;

                mx = (float) (0.5*(sx + gx) * factor);
                my = (float) (0.5*(sy + gy) * factor);

		efwrite(&mx, FSIZE, 1, stdout);
		efwrite(&my, FSIZE, 1, stdout);

		++npairs;
	}


	/* Make parfile if needed */
	if (getparstring("outpar", &outpar))
		fprintf(efopen(outpar, "w"), "n=%d\n", npairs);

	return(CWP_Exit());
}
示例#3
0
文件: fputtr.c 项目: 1014511134/src
static
int datawrite(struct outsegyinfo *iptr, segy *tp, cwp_Bool fixed_length)
{
	int nwritten;
	unsigned int nstobewritten = fixed_length?iptr->nsfirst:tp->ns;
	unsigned int databytes = iptr->bytesper*nstobewritten;
	
	/* write trace data */
	switch(tp->trid) {
	case CHARPACK:
	case SHORTPACK:
		nwritten = efwrite((char *) (&((tp->data)[0])),1,databytes,
				  iptr->outfp);
	break;
	default:
		if(FALSE == xdr_vector(iptr->segy_xdr,
				       (char *) (&((tp->data)[0])),
				       nstobewritten,sizeof(float),(xdrproc_t) xdr_float))
			nwritten = 0;
		else
			nwritten = databytes;
	}

	return(nwritten);
}
示例#4
0
void vavgout(FILE *datafp, float *ts, float *vs, float *work, int ns) {

	int it;

	vint2vavg(ts,vs,work,ns);
	bcopy(work,vs,ns*sizeof(float));
	for(it=0;it<ns;it++) {
		work[it*2] = ts[it];
		work[it*2+1] = vs[it];
	} 
	efwrite(work,sizeof(float),2*ns,datafp);
}
示例#5
0
main(int argc, char **argv)
{
	String output;
	bool asciiout = true;


	/* Initialize */
	initargs(argc, argv);
	askdoc(1);

	file2g(stdin);


	/* Argument count check */
	if (argc == 1)  err("must specify key(s) as command line arguments");


	/* Set and check output disposition (ascii or binary) */
	if (!getparstring("output", &output))   output = "ascii";
	if ((!STREQ(output, "ascii")) && (!STREQ(output, "binary")))
		err("output parameter=%s, must be ascii or binary", output);
	if (STREQ(output, "binary"))  asciiout = false;


	/* Loop over traces writing selected header field values */
	while (gettr(&tr)) {
		register int i;

		for (i = 1; i < argc; ++i) {
			String key = argv[i];
			Value val;

			/* discard command line parameter strings */
			if (STREQ(key, "output=ascii") ||
			    STREQ(key, "output=binary"))
				continue;

			gethdval(&tr, key, &val);
			if (asciiout) {  /* ascii output */
				printf("%6s=", key);
				printfval(hdtype(key), val);
				putchar('\t');
			} else {  /* binary output */
				float fval = vtof(hdtype(key), val);
				efwrite((char *) &fval, FSIZE, 1, stdout);
			}
		}

		if (asciiout)  printf("\n\n");
	}

	return EXIT_SUCCESS;
}
示例#6
0
void dump2xplot(float *d,int n1,int n2,int dtype, char *title) {
     	char cmd[1024] ;
    	FILE *cmpfp;
	/* set up xplot command */
	if ( dtype == 0 ) {
     		sprintf(cmd,"ximage n1=%d n2=%d title=\"%s\"",n1,n2,title) ; 
	} else {
     		sprintf(cmd,"xwigb n1=%d n2=%d title=\"%s\"",n1,n2,title) ; 
	}
	/* open pipe */
	cmpfp = epopen(cmd,"w");
	efwrite(d,sizeof(float),n1*n2,cmpfp);
	efclose(cmpfp);
}
示例#7
0
文件: fputtr.c 项目: 1014511134/src
static
void datawrite(segy *tp, struct outsegyinfo *iptr, cwp_Bool fixed_length)
{
	unsigned int nstobewritten = fixed_length?iptr->nsfirst:tp->ns;
	unsigned int databytes = iptr->bytesper * nstobewritten;
	int nwritten = (int) efwrite((char *) (&((tp->data)[0])), 1, databytes,
			       iptr->outfp);

	if (nwritten != databytes)
		suerr("%s: on trace #%ld, tried to write %d bytes, "
		    "wrote %d bytes",
		    __FILE__, (infoptr->itr)+1, databytes, nwritten);

	return;
}
示例#8
0
int main(int argc, char** argv) {
    long level = -1;
    bool read  = true;
    bool clear_before = false;
    bool clear_after = false;
    /* Parse command line options */
    OPTBEGIN {
    case 'C':
        clear_before = true;
        read = false;
        break;
    case 'c':
        clear_after = true;
        read = true;
        break;
    case 'n':
        level = estrtol(EOPTARG(usage()), 10);
        break;
    default:
        usage();
    } OPTEND;
    /* clear the before before  doing anything else */
    if (clear_before)
        eklogctl(SYSLOG_ACTION_CLEAR, NULL, 0);
    /* Set the log level */
    if (level >= 0)
        eklogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL, level);
    /* Read the raw log data and print it out */
    if (read) {
        int nbytes = eklogctl(SYSLOG_ACTION_SIZE_BUFFER, NULL, 0);
        char* buf  = (char*)emalloc(nbytes);
        eklogctl(SYSLOG_ACTION_READ_ALL, buf, nbytes);
        nbytes = efwrite(buf, 1, nbytes, stdout);
        if (buf[nbytes - 1] != '\n')
            fputc('\n', stdout);
        free(buf);
    }
    /* Clear the log after we've read it out */
    if (clear_after)
        eklogctl(SYSLOG_ACTION_CLEAR, NULL, 0);
    return 0;
}
示例#9
0
/* with axis labeling and grids */
void dump2xplotn(float *d,int n1,int n2,int dtype,char *title,
float f1, float f2, float d1, float d2, char *label1, char *label2,
char *grid1, char *grid2) {
     	char cmd[2048] ;
    	FILE *cmpfp;

	/* set up xplot command */
	if ( dtype == 0 ) {
     		sprintf(cmd,"ximage n1=%d n2=%d title=\"%s\" f1=%g f2=%g d1=%g d2=%g label1=\"%s\" label2=\"%s\" grid1=\"%s\" grid2=\"%s\" \n",
			n1,n2,title,f1,f2,d1,d2,label1,label2,grid1,grid2); 
	} else {
     		sprintf(cmd,"xwigb n1=%d n2=%d title=\"%s\" f1=%g f2=%g d1=%g d2=%g label1=\"%s\" label2=\"%s\" grid1=\"%s\" grid2=\"%s\"",
			n1,n2,title,f1,f2,d1,d2,label1,label2,grid1,grid2) ; 
	}

	/* open pipe */
	cmpfp = epopen(cmd,"w");
	efwrite(d,sizeof(float),n1*n2,cmpfp);
	efclose(cmpfp);
}
示例#10
0
int
main(int argc, char **argv)
{
	char *key=NULL;		/* header key word from segy.h		*/
	char *type=NULL;	/* ... its type				*/
	int index;		/* ... its index			*/
	Value val;		/* ... its value			*/
	float fval;		/* ... its value cast to float		*/

	float *xshift=NULL;	/* array of key shift curve values	*/
	float *tshift=NULL;	/* ...		shift curve time values */

	int nxshift;		/* number of key shift values		*/
	int ntshift;		/* ...		shift time values 	*/

	int nxtshift;		/* number of shift values 		*/

	int it;			/* sample counter			*/
	int itr;		/* trace counter			*/
	int nt;			/* number of time samples 		*/
	int ntr=0;		/* number of traces			*/
	int *inshift=NULL;	/* array of (integer) time shift values
				   used for positioning shifted trace in
				   data[][]				*/

	float dt;		/* time sampling interval		*/

	cwp_String xfile="";	/* file containing positions by key	*/
	FILE *xfilep=NULL;	/* ... its file pointer			*/
	cwp_String tfile="";	/* file containing times	 	*/
	FILE *tfilep=NULL;	/* ... its file pointer			*/

	int verbose;		/* flag for printing information	*/
	char *tmpdir=NULL;	/* directory path for tmp files		*/
	cwp_Bool istmpdir=cwp_false;/* true for user-given path		*/

	int median;		/* flag for median filter		*/
	int nmed;		/* no. of traces to median filter	*/
	int nmix;		/* number of traces to mix over		*/
	int imix;		/* mixing counter			*/
	float *mix=NULL;	/* array of mix values			*/
	int sign;		/* flag for up/down shift		*/
	int shiftmin=0;		/* minimum time shift (in samples)	*/
	int shiftmax=0;		/* maximum time shift (in samples)	*/
	int ntdshift;		/* nt + shiftmax			*/

	size_t mixbytes;	/* size of mixing array			*/
	size_t databytes;	/* size of data array			*/
	size_t shiftbytes;	/* size of data array			*/
	float *temp=NULL;	/* temporary array			*/
	float *dtemp=NULL;	/* temporary array			*/
	float *stemp=NULL;	/* rwh median sort array		*/
	float **data=NULL;	/* mixing array 			*/
	int subtract;		/* flag for subtracting shifted data	*/

	/* rwh extra pointers for median sort */
	int first;		/* start pointer in ring buffer */
	int middle;		/* middle pointer in ring buffer */
	int last;		/* last pointer in ring buffer */
	int halfwidth;		/* mid point */
	int trcount;		/* pointer to current start trace number */
	float tmp;		/* temp storage for bubble sort */
	int rindex;		/* wrap around index for ring buffer */
	int jmix;		/* internal pointer for bubble sort */
	

	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);

	/* Get parameters */
	if (!(getparstring("xfile",&xfile) && getparstring("tfile",&tfile))) {
		if (!(nxshift = countparval("xshift")))
			err("must give xshift= vector");
		if (!(ntshift = countparval("tshift")))
			err("must give tshift= vector");
		if (nxshift != ntshift)
			err("lengths of xshift, tshift must be the same");
		xshift = ealloc1float(nxshift);	getparfloat("xshift", xshift);
		tshift = ealloc1float(nxshift);	getparfloat("tshift", tshift);
	} else {
		MUSTGETPARINT("nshift",&nxtshift);
		nxshift = nxtshift;
		xshift = ealloc1float(nxtshift);
		tshift = ealloc1float(nxtshift);

		if((xfilep=fopen(xfile,"r"))==NULL)
			err("cannot open xfile=%s\n",xfile);
		if (fread(xshift,sizeof(float),nxtshift,xfilep)!=nxtshift)
			err("error reading xfile=%s\n",xfile);
		fclose(xfilep);

		if((tfilep=fopen(tfile,"r"))==NULL)
			err("cannot open tfile=%s\n",tfile);
		if (fread(tshift,sizeof(float),nxtshift,tfilep)!=nxtshift)
			err("error reading tfile=%s\n",tfile);
		fclose(tfilep);
	}
	if (!getparstring("key", &key))		key = "tracl";

	/* Get key type and index */
	type = hdtype(key);
	index = getindex(key);   

	/* Get mix weighting values values */
	if ((nmix = countparval("mix"))!=0) {
		mix = ealloc1float(nmix);
		getparfloat("mix",mix);
		/* rwh check nmix is odd */
		if (nmix%2==0) {
			err("number of mixing coefficients must be odd");
		}		
	} else {
		nmix = 5;
		mix = ealloc1float(nmix);
		mix[0] = VAL0;
		mix[1] = VAL1;
		mix[2] = VAL2;
		mix[3] = VAL3;
		mix[4] = VAL4;
	}
	
	/* Get remaning parameters */
	if (!getparint("median",&median))	median = 0;
	if (!getparint("nmed",&nmed) && median)	nmed = 5;
	if (!getparint("sign",&sign))		sign = -1;
	if (!getparint("subtract",&subtract))	subtract = 1;
	if (!getparint("verbose", &verbose))	verbose = 0;

	/* rwh check nmed is odd */
	if (median && nmed%2==0) {
		nmed=nmed+1;
		warn("increased nmed by 1 to ensure it is odd");
	}

	/* Look for user-supplied tmpdir */
	if (!getparstring("tmpdir",&tmpdir) &&
	    !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);

	/* rwh fix for median filter if median true set nmix=nmed */
	if (!median) {
		/* Divide mixing weights by number of traces to mix */
		for (imix = 0; imix < nmix; ++imix)
			mix[imix]=mix[imix]/((float) nmix);
	} else {
		nmix=nmed;
	}

	/* Get info from first trace */
	if (!gettr(&tr)) err("can't read first trace");
	if (!tr.dt) err("dt header field must be set");
	dt   = ((double) tr.dt)/1000000.0;
	nt = (int) tr.ns;
	databytes = FSIZE*nt;

	/* Tempfiles */
	if (STREQ(tmpdir,"")) {
		tracefp = etmpfile();
		headerfp = etmpfile();
		if (verbose) warn("using tmpfile() call");
	} else { /* user-supplied tmpdir */
		char directory[BUFSIZ];
		strcpy(directory, tmpdir);
		strcpy(tracefile, temporary_filename(directory));
		strcpy(headerfile, temporary_filename(directory));
		/* Trap signals so can remove temp files */
		signal(SIGINT,  (void (*) (int)) closefiles);
		signal(SIGQUIT, (void (*) (int)) closefiles);
		signal(SIGHUP,  (void (*) (int)) closefiles);
		signal(SIGTERM, (void (*) (int)) closefiles);
		tracefp = efopen(tracefile, "w+");
		headerfp = efopen(headerfile, "w+");
      		istmpdir=cwp_true;		
		if (verbose) warn("putting temporary files in %s", directory);
	}

	/* Read headers and data while getting a count */
	do {
		++ntr;
		efwrite(&tr, 1, HDRBYTES, headerfp);
		efwrite(tr.data, 1, databytes, tracefp);   

	} while (gettr(&tr));
	rewind(headerfp);
	rewind(tracefp);
	
	/* Allocate space for inshift vector */
	inshift = ealloc1int(ntr);

	/* Loop over headers */
 	for (itr=0; itr<ntr; ++itr) {
		float tmin=tr.delrt/1000.0;
		float t;

		/* Read header values */
		efread(&tr, 1, HDRBYTES, headerfp);

		/* Get value of key and convert to float */
		gethval(&tr, index, &val);
		fval = vtof(type,val);

		/* Linearly interpolate between (xshift,tshift) values */
		intlin(nxshift,xshift,tshift,tmin,tshift[nxshift-1],1,&fval,&t);
		
		/* allow for fractional shifts -> requires interpolation */ 
		inshift[itr] = NINT((t - tmin)/dt);
		
		/* Find minimum and maximum shifts */
		if (itr==0) {
			 shiftmax=inshift[0];
			 shiftmin=inshift[0];
		} else {
			shiftmax = MAX(inshift[itr],shiftmax);
			shiftmin = MIN(inshift[itr],shiftmin);
		}
	}
	rewind(headerfp);
	rewind(tracefp);

	if (verbose) {
		for (itr=0;itr<ntr;itr++)
			warn("inshift[%d]=%d",itr,inshift[itr]);
	}

	/* Compute databytes per trace and bytes in mixing panel */
	ntdshift = nt + shiftmax;
	shiftbytes = FSIZE*ntdshift;
	mixbytes = shiftbytes*nmix;
	if (verbose) {
		warn("nt=%d  shiftmax=%d  shiftmin=%d",nt,shiftmax,shiftmin);
		warn("ntdshift=%d  shiftbytes=%d  mixbytes=%d",
						ntdshift,shiftbytes,mixbytes);
	}
	
	/* Allocate space and zero  data array */
	data = ealloc2float(ntdshift,nmix);
	temp = ealloc1float(ntdshift);
	dtemp = ealloc1float(nt);
	memset( (void *) data[0], 0, mixbytes);

	/* rwh array for out of place bubble sort (so we do not corrupt order in ring buffer */ 
	stemp = ealloc1float(nmix);

	/* rwh first preload ring buffer symmetrically (now you know why nmix must be odd) */
	trcount=-1;
	halfwidth=(nmix-1)/2+1;
	first = 0;
	last  = nmix-1;
	middle = (nmix-1)/2;

	for (itr=0; itr<halfwidth; itr++) {
		efread(tr.data, 1, databytes, tracefp);
		trcount++;
		for(it=0; it<nt; ++it) {
			/* sign to account for positive or negative shift */
			/* tr.data needs to be interpolated for non-integer shifts */
			data[middle-itr][it + shiftmax + sign*inshift[itr]] = tr.data[it];
			data[middle+itr][it + shiftmax + sign*inshift[itr]] = tr.data[it];
		}
	}
	
	/* Loop over traces performing median filtering  */
 	for (itr=0; itr<ntr; ++itr) {

		/* paste header and data on output trace */
		efread(&tr, 1, HDRBYTES, headerfp);

		/* Zero out temp and dtemp */
		memset((void *) temp, 0, shiftbytes);
		memset((void *) dtemp, 0, databytes);

		/* Loop over time samples */
		for (it=0; it<nt; ++it) {

			/* Weighted moving average (mix) ? */
			if (!median) {
				for(imix=0; imix<nmix; ++imix) {
					temp[it] += data[imix][it] * mix[imix];
				}
			} else {
			
			/* inlcude median stack */
			/* rwh do bubble sort and choose median value */
				for(imix=0; imix<nmix; ++imix) {
					stemp[imix]=data[imix][it];
				}
				for (imix=0; imix<nmix-1; imix++) {
					for (jmix=0; jmix<nmix-1-imix; jmix++) {
						if (stemp[jmix+1] < stemp[jmix]) {
							tmp = stemp[jmix];
							stemp[jmix] = stemp[jmix+1];
							stemp[jmix+1] = tmp;
						}
					}
				}
				temp[it] = stemp[middle];
			}

			/* shift back mixed data and put into dtemp */
			if (subtract) {
				if ((it - shiftmax - sign*inshift[itr])>=0)
					dtemp[it - shiftmax - sign*inshift[itr]] = data[middle][it]-temp[it];
			} else {
				if ((it - shiftmax)>=0)
				dtemp[it - shiftmax - sign*inshift[itr]] = temp[it];
			}
		}
		memcpy((void *) tr.data,(const void *) dtemp,databytes);
			
		/* Bump rows of data[][] over by 1 to free first row for next tr.data */
		for (imix=nmix-1; 0<imix; --imix)
			memcpy((void *) data[imix],(const void *) data[imix-1],shiftbytes);
			/*for (it=0; it<nt; ++it)
				data[imix][it] = data[imix-1][it];*/

		/* Write output trace */
		tr.ns = nt;
		puttr(&tr);

		/* read next trace into buffer */
		if (trcount < ntr) {
			efread(tr.data, 1, databytes, tracefp);
			trcount++;

			/* read tr.data into first row of mixing array */
			/* WMH: changed ntdshift to nt */
			for(it=0; it<nt; ++it) {
				/* sign to account for positive or negative shift */
				/* tr.data needs to be interpolated for non-integer shifts */
				data[0][it + shiftmax + sign*inshift[trcount]] = tr.data[it];
			}
		} else {
			rindex=2*(trcount-ntr);
			memcpy((void *) data[0],(const void *) data[rindex],shiftbytes);
			trcount++;
		}

	}

	if (verbose && subtract)	warn("filtered data subtracted from input");

	/* Clean up */
	efclose(headerfp);
	if (istmpdir) eremove(headerfile);
	efclose(tracefp);
	if (istmpdir) eremove(tracefile);

	return(CWP_Exit());
}
示例#11
0
int
main(int argc, char **argv)
{
   char *tmpdir ;                 /* directory path for tmp files */
   cwp_Bool istmpdir=cwp_false ;  /* true for user given path */
   float *hedr ;                  /* the headers */
   float *data ;                  /* the data */

   int nt ;                       /* number of trace samples */
   float dt ;                     /* sample interval, sec */
   float delrt ;                  /* delay recording time, sec */
   cwp_String key[SU_NKEYS] ;     /* array of keywords */
   cwp_String type ;              /* key string type */
   int nkeys ;                    /* number of keywords */
   int ikey,ntr = 0 ;	          /* counters */
   int num ;                      /* number of traces to dump */
   int numtr = 4 ;                /* number of traces to dump */
   int hpf ;                      /* header print format */

   /* Initialize */
   initargs(argc, argv) ;
   requestdoc(1) ;

   /* Look for user-supplied tmpdir */
   if (!getparstring("tmpdir",&tmpdir) &&
       !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
   if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
       err("you can't write in %s (or it doesn't exist)", tmpdir);

   /* Get values from first trace */
   if (!gettr(&tr)) err("can't get first trace");
   nt = (int) tr.ns ;                  /* Get nt */
   dt = ((double) tr.dt)/1000000.0 ;   /* microsecs to secs */
   if (!dt) getparfloat("dt", &dt) ;
   if (!dt) MUSTGETPARFLOAT("dt", &dt) ;
   delrt = ((double) tr.delrt)/1000.0 ; /* millisecs to secs */

   /* Get parameters */
   if (getparint ("num", &num)) numtr = num ;
   if ((nkeys=countparval("key"))!=0) getparstringarray("key",key) ;
   hedr = ealloc1float(nkeys*numtr) ;  /* make space for headers */
   if (!getparint ("hpf", &hpf)) hpf = 0 ;

   /* Store traces, headers in tempfiles */
   if (STREQ(tmpdir,""))
   {
      tracefp = etmpfile();
      headerfp = etmpfile();

      do
      {
         ++ntr;
         efwrite(&tr, HDRBYTES, 1, headerfp);
         efwrite(tr.data, FSIZE, nt, tracefp);

         /* Get header values */
         for (ikey=0; ikey<nkeys; ++ikey)
         {
            Value val;
            float fval;

            gethdval(&tr, key[ikey], &val) ;
            type = hdtype(key[ikey]) ;
            fval = vtof(type,val) ;
            hedr[(ntr-1)*nkeys+ikey] = fval ;
         }

      }
      while (ntr<numtr  &&  gettr(&tr)) ;

   }
   else  /* user-supplied tmpdir */
   {
      char directory[BUFSIZ];
      strcpy(directory, tmpdir);
      strcpy(tracefile, temporary_filename(directory));
      strcpy(headerfile, temporary_filename(directory));
      /* Handle user interrupts */
      signal(SIGINT, (void (*) (int)) closefiles);
      signal(SIGQUIT, (void (*) (int)) closefiles);
      signal(SIGHUP,  (void (*) (int)) closefiles);
      signal(SIGTERM, (void (*) (int)) closefiles);
      tracefp = efopen(tracefile, "w+");
      headerfp = efopen(headerfile, "w+");
      istmpdir=cwp_true;      

      do
      {
         ++ntr;
         efwrite(&tr, HDRBYTES, 1, headerfp);
         efwrite(tr.data, FSIZE, nt, tracefp);

         /* Get header values */
         for (ikey=0; ikey<nkeys; ++ikey)
         {
            Value val;
            float fval;

            gethdval(&tr, key[ikey], &val) ;
            type = hdtype(key[ikey]) ;
            fval = vtof(type,val) ;
            hedr[(ntr-1)*nkeys+ikey] = fval ;
         }

      }
      while (ntr<numtr  &&  gettr(&tr)) ;

   }

   /* Rewind after read, allocate space */
   erewind(tracefp);
   erewind(headerfp);
   data = ealloc1float(nt*ntr);

   /* Load traces into data and close tmpfile */
   efread(data, FSIZE, nt*ntr, tracefp);
   efclose(tracefp);
   if (istmpdir) eremove(tracefile);

   rewind(headerfp);
   rewind(tracefp);

   /* Do trace work */
   dump(data, dt, hedr, key, delrt, nkeys, ntr, nt, hpf) ;

   /* close */
   efclose(headerfp);
   if (istmpdir) eremove(headerfile);

   free1(hedr) ;
   free1(data) ;

   return(CWP_Exit()) ;
}
示例#12
0
main(int argc, char **argv)
{
	FILE *fpr, *fpw;
	char msg[BUFSIZ];
	char erbuf[BUFSIZ], ewbuf[BUFSIZ], rbuf[BUFSIZ], wbuf[BUFSIZ];
	char pbuf[1], pfbuf[1];
	size_t mbytes, rbytes, wbytes;
	size_t ritems, witems;

	initargs(argc, argv);

	/* Exercise efread and efwrite */
  	fpw = efopen("junk.fwr", "w+");
 	strcpy(ewbuf, "   Writing with efwrite\n");
	witems = strlen(ewbuf);
	efwrite(ewbuf, 1, witems, fpw);
	erewind(fpw);

	fread(rbuf, 1, witems, fpw);
	erewind(fpw);
	strcpy(msg, "***efwrite from file to buffer ...");
	mbytes = strlen(msg);
	fwrite(msg, 1, mbytes, stdout);
	fwrite(rbuf, 1, witems, stdout);

  	fpr = fopen("junk.frd", "w+");
 	strcpy(wbuf, "   Reading with efread\n");
	ritems = strlen(wbuf);
	fwrite(wbuf, 1, ritems, fpr);
	erewind(fpr);
	strcpy(wbuf, "   efread saw zero bytes\n");
	witems = strlen(wbuf);

	strcpy(msg, "***efread from file to buffer ...");
	mbytes = strlen(msg);
	fwrite(msg, 1, mbytes, stdout);
	if (!efread(erbuf, 1, ritems, fpr)) {
		fwrite(wbuf, 1, witems, stdout);
	} else {
		fwrite(erbuf, 1, ritems, stdout);
	}
	erewind(fpr);

 	strcpy(wbuf, "   Reading byte by byte with efread\n");
	ritems = strlen(wbuf);
	fwrite(wbuf, 1, ritems, fpr);
	erewind(fpr);
	strcpy(wbuf, "   exit loop: efread returned zero\n");
	witems = strlen(wbuf);

	strcpy(msg, "***efread file byte by byte to buffer ...");
	mbytes = strlen(msg);
	fwrite(msg, 1, mbytes, stdout);
	while (efread(erbuf, 1, 1, fpr)) {
		fwrite(erbuf, 1, 1, stdout);
	}
	erewind(fpr);
	fwrite(wbuf, 1, witems, stdout);

 	strcpy(wbuf, "");
	ritems = strlen(wbuf);
	fwrite(wbuf, 1, ritems, fpr);
	erewind(fpr);
	strcpy(wbuf, "   efread saw zero bytes\n");
	witems = strlen(wbuf);

	strcpy(msg, "***efread from EMPTY file to buffer ...");
	mbytes = strlen(msg);
	fwrite(msg, 1, mbytes, stdout);
	efread(erbuf, 1, ritems, fpr);
	erewind(fpr);
	fwrite(wbuf, 1, witems, stdout);

	efclose(fpw);
	efclose(fpr);
	eremove("junk.frd");
	eremove("junk.fwr");

	return EXIT_SUCCESS;
}
示例#13
0
main(int argc, char **argv)
{
	char plotcmd[BUFSIZ];	/* build ximage command for popen 	*/
	float *trbuf;		/* trace buffer			 	*/
	FILE *datafp;		/* fp for trace data file		*/
	FILE *plotfp;		/* fp for plot data			*/
	int nt;			/* number of samples on trace		*/
	int ntr;		/* number of traces			*/
	float d1;		/* time/depth sample rate 		*/
	float d2;		/* trace/dx sample rate 		*/
	float f1;		/* tmin/zmin				*/
	float f2;		/* tracemin/xmin	 		*/
	bool seismic;		/* is this seismic data?		*/
	int panel;		/* panel to pick			*/
	int dtype;		/* type of display 			*/
	int ppos;		/* position of the panel		*/
	FILE *infp=stdin;
	int n3,n2,n1;
	


	/* Initialize */
	initargs(argc, argv);
	askdoc(1);
	

	/* Get info from headers and first trace */
      	fgethdr(infp,&ch,&bh);
	n1 = bh.hns;
	if(!getparint("ntpp",&n2)) {
		if (bh.tsort==2) {
	  		 n2 = bh.fold;
		} else {
	   		n2 = bh.ntrpr;
		} 
	}
	if (!fgettr(infp,&tr)) err("can't get first trace");
	nt = tr.ns;
	if ( n1!=nt ) 
	   warn("samples/trace in bhdr and trhdr different; trhdr used! \n");
	n1 = nt;
	fseek(infp,0L,2);
	n3=(ftell(infp)-EBCBYTES-BNYBYTES)/(n1*sizeof(float)+HDRBYTES)/n2;
        if(n3==0) {
	   n3=1;
	   n2=(ftell(infp)-EBCBYTES-BNYBYTES)/(n1*sizeof(float)+HDRBYTES);
	   warn("less traces were found in input! \n");
	}
	fseek(infp,0L,0);
 
	seismic =  (tr.trid == 0 || tr.trid == TREAL);

	if (!getparint("panel", &panel)) panel=1;
	if (!getparint("dtype", &dtype)) dtype=0;
	if (!getparfloat("d1", &d1)) {
		if (seismic) {
			/* sampling interval in ms or in m (ft) */
			if ( tr.dz!=0. ) { 
				d1 = tr.dz;	
			} else if (tr.dt) {
				d1 = (float) tr.dt / 1000.0;
				if (tr.dt<1000) d1 = tr.dt;
			} else {
				d1 = 0.004 * 1000.;
				warn("tr.dt not set, assuming dt=4");
			}
		} else { /* non-seismic data */
			if (tr.d1) {
				d1 = tr.d1;
			} else {
				d1 = 1.0;
				warn("tr.d1 not set, assuming d1=1.0");
			}
		}
	}

	if (!getparfloat("d2", &d2)) {
	   if(bh.tsort==2) {
	      d2 = tr.offset;
	   }
	   else {
	      d2 = tr.cdp;
	   }
	}

	if (!getparfloat("f1", &f1)) {
		if (seismic) {
			f1 = (tr.delrt) ? (float) tr.delrt/1000.0 : 0.0;
		        if(tr.delrt<1000) f1=tr.delrt;
			if(tr.dz!=0.) f1=tr.fz;
		} else {
			f1 = (tr.f1) ? tr.f1 : 0.0;
		}
	}

	if (!getparfloat("f2", &f2)) {
		if (bh.tsort==2) {
	           f2 = tr.offset;
		}
		else {
	           f2 = tr.cdp;
		}
	}


	/* Allocate trace buffer */
	trbuf = ealloc1float(nt);


	/* Create temporary "file" to hold data */
	datafp = etempfile(NULL);


	/* Loop over input traces & put them into the data file */
	ntr = 0;
     fseek(infp,EBCBYTES+BNYBYTES+(panel-1)*n2*(n1*sizeof(float)+HDRBYTES),0);


	for(ntr=0;ntr<n2;ntr++) {
	    	if(!fgettr(infp,&tr)) err("get trace error \n");
	    	efwrite(tr.data, FSIZE, nt, datafp);
	    	if(ntr==1) {
			if (bh.tsort==2) {
	       			if(!getparfloat("d2",&d2)) d2 = tr.offset-d2;
		  		if (!getparint("ppos", &ppos)) ppos = tr.cdp;
			} else {
	       			if(!getparfloat("d2",&d2)) d2 = tr.cdp-d2;
		  		if (!getparint("ppos", &ppos)) ppos = tr.offset;
			}
	    	}
	}



	/* Set up xipick or xwpick command line */
	if ( dtype == 0 ) {
	   sprintf(plotcmd,
"mipick n1=%d n2=%d d1=%f d2=%f f1=%f f2=%f ppos=%d",
		    n1, n2, d1, d2, f1, f2, ppos);
	} else {
	   sprintf(plotcmd,
"mwpick n1=%d n2=%d d1=%f d2=%f f1=%f f2=%f ppos=%d",
		    n1, n2, d1, d2, f1, f2, ppos);
	}

	for (--argc, ++argv; argc; --argc, ++argv) {
		if (strncmp(*argv, "d1=", 3) && /* skip those already set */
		    strncmp(*argv, "d2=", 3) &&
		    strncmp(*argv, "f1=", 3) &&
		    strncmp(*argv, "f2=", 3)) {
		    
			strcat(plotcmd, " ");   /* put a space between args */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
			strcat(plotcmd, *argv); /* add the arg */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
		}
	}


	/* Open pipe; read data to buf; write buf to plot program */
	plotfp = epopen(plotcmd, "w");
	rewind(datafp);
	{ register int itr;
		for (itr = 0; itr < ntr; ++itr) {
			efread (trbuf, FSIZE, nt, datafp);
			efwrite(trbuf, FSIZE, nt, plotfp);
		}
	}


	/* Clean up */
	epclose(plotfp);
	efclose(datafp);


	return EXIT_SUCCESS;
}
示例#14
0
int
main(int argc, char **argv)
{
	int nx1,nx2;		/* numbers of samples			*/
	int ix1, ix2;		/* sample indices			*/
	float a1,a2;		/* filter dimensions			*/

	float pi;		/* pi number				*/
	float vmax;		/* maximum value of the data		*/
	float vfmax;		/* scale factor after filtering		*/
	float c1,c2;
	float **v=NULL;		/* array of velocities			*/
	float *k1=NULL,*k2=NULL;	/* wavenumber arrays		*/
	float *kfilt1=NULL,*kfilt2=NULL;/* intermediate filter arrays   */
	float dk1,dk2;			/* wavenumber interval		*/
	float **kfilter=NULL;		/* array of filter values	*/

	int nx1fft,nx2fft;	/* dimensions after padding for FFT	*/
	int nK1,nK2;	  /* transform dimension			*/
	int ik1,ik2;	  /* wavenumber indices				*/

	register complex **ct=NULL;	/* complex FFT workspace	*/
	register float **rt=NULL;	/* float FFT workspace		*/
	FILE *tracefp=NULL;	/* temp file to hold traces		*/
	FILE *hfp=NULL;		/* temp file to hold trace headers	*/
	
	/* hook up getpar to handle the parameters */
	initargs(argc, argv);
	requestdoc(1);

	/* Get parameters from command line */
	if (!getparfloat("a1",&a1)) a1=0.;
	if (!getparfloat("a2",&a2)) a2=0.;

	/* Get info from first trace */
	if (!gettr(&tr))  err("can't get first trace");
	if (tr.trid != TRID_DEPTH)  warn("tr.trid=%d",tr.trid);
	nx1=tr.ns;

	/* Store traces in tmpfile while getting a count */
	tracefp=etmpfile();
	hfp=etmpfile();
	nx2=0;
	do {
		++nx2;
		efwrite(&tr,HDRBYTES, 1, hfp);
		efwrite(tr.data, FSIZE, nx1, tracefp);
	} while (gettr(&tr));
	
	/* Determine number of wavenumbers in K1 and K2 */
	nx1fft=npfaro(nx1, LOOKFAC*nx1);
	nx2fft=npfa(nx2);
	if (nx1fft >=SU_NFLTS || nx1fft >= PFA_MAX)
	  err("Padded nx1=%d--too big",nx1fft);
	if (nx2fft >= PFA_MAX)
	  err("Padded nx2=%d--too big",nx2fft);

	/* Determine number of wavenumbers in K1 and K2 */
	nK1=nx1fft/2 + 1;
	nK2=nx2fft/2 + 1;

	/* Allocate space */
	v=alloc2float(nx1,nx2);
	rt=alloc2float(nx1fft,nx2fft);
	ct=alloc2complex(nK1,nx2fft);
	kfilter=alloc2float(nx1fft,nx2fft);
	k1=alloc1float(nK1);
	k2=alloc1float(nK2);
	kfilt1= alloc1float(nK1);
	kfilt2= alloc1float(nK2);

	/* Zero all arrays */
	memset((void *) rt[0], 0, nx1fft*nx2fft*FSIZE);
	memset((void *) kfilter[0], 0, nx1fft*nx2fft*FSIZE);
	memset((void *) ct[0], 0, nK1*nx2fft*sizeof(complex));
	memset((void *) k1, 0, nK1*FSIZE);
	memset((void *) k2, 0, nK2*FSIZE);
	memset((void *) kfilt1, 0,  nK1*FSIZE);
	memset((void *) kfilt2, 0, nK2*FSIZE);

	/* Determine wavenumber arrays for the filter */
	pi=PI;
	dk1=2*pi / nx1fft;
	dk2=2*pi / nx2fft;
	for (ik1=0; ik1<nK1; ++ik1) {
	  c1=a1*ik1*dk1/ 2;
	  kfilt1[ik1]= exp(-pow(c1,2));
	}
	for (ik2=0; ik2<nK2; ++ik2) {
	  c2= a2*ik2*dk2/2;
	  kfilt2[ik2]= exp(-pow(c2,2));
	}
	
	/* Build Gaussian filter */
	/* positive k1, positive k2 */
	for (ik2=0; ik2<nK2; ++ik2) {
	  for (ik1=0; ik1<nK1; ++ik1) {
		kfilter[ik2][ik1]=kfilt2[ik2]*kfilt1[ik1];
	  }
	}
	/* positive k1, negative k2 */
	for (ik2=nK2; ik2<nx2fft; ++ik2) {
	  for (ik1=0; ik1<nK1; ++ik1) {
		kfilter[ik2][ik1]=kfilt2[nx2fft-ik2]*kfilt1[ik1];
	  }
	}

	/* Read velocities from temp file and determine maximum */
	rewind(tracefp);
	fread(v[0],sizeof(float),nx2*nx1,tracefp);
	vmax=v[0][0];
	for (ix2=0; ix2<nx2; ++ix2) {
	  for (ix1=0; ix1<nx1; ++ix1) {
		vmax=MAX(vmax,v[ix2][ix1]);
	  }
	}

	/* Load data into FFT arrays */
	rewind(tracefp);
	for (ix2=0; ix2<nx2; ++ix2) {
	  efread(rt[ix2], FSIZE, nx1, tracefp);
	}   
	
	/* Fourier transform dimension 1 */
	pfa2rc(-1,1,nx1fft,nx2,rt[0],ct[0]);
	
	/* Fourier transform dimension 2 */
	pfa2cc(-1,2,nK1,nx2fft,ct[0]);

	/* Apply filter to the data */
	for (ik2=0; ik2<nx2fft; ++ik2) {
	  	for (ik1=0; ik1<nK1;  ++ik1) {
			ct[ik2][ik1]=crmul(ct[ik2][ik1], kfilter[ik2][ik1]) ;
		}
	}

	/* Inverse Fourier transformation dimension 2 */
	pfa2cc(1,2,nK1,nx2fft,ct[0]);

	/* Inverse Fourier transformation dimension 1 */
	pfa2cr(1,1,nx1fft,nx2,ct[0],rt[0]);

	/* Find maximum of filtered data */
	vfmax=rt[0][0];
	for (ix2=0; ix2<nx2; ++ix2) {
		for (ix1=0; ix1<nx1; ++ix1) {
			vfmax=MAX(vfmax,rt[ix2][ix1]);
		}
	}

	/* Rescale and output filtered data */
	erewind(hfp);
	for (ix2=0; ix2<nx2; ++ix2) {
		efread(&tr, HDRBYTES, 1, hfp);
		for (ix1=0; ix1<nx1; ++ix1)
			tr.data[ix1]=(rt[ix2][ix1]) * vmax / vfmax;
	  puttr(&tr);
	}
	efclose(hfp);

	return(CWP_Exit());
}
示例#15
0
int
main(int argc, char **argv)
{
	int nt;		/* number of time samples			*/
	float dt;	/* time sampling interval			*/
	int ntr;	/* number of traces				*/
	float dx;	/* trace spacing (spatial sampling interval)	*/
	int nslopes;	/* number of slopes specified			*/
	float *slopes;	/* slopes at which amplitudes are specified	*/
	int namps;	/* number of amplitudes specified		*/
	float *amps;	/* amplitudes corresponding to slopes		*/
	float bias;	/* slope bias					*/
	int verbose;	/* flag for echoing info			*/
	char *tmpdir;	/* directory path for tmp files			*/
	cwp_Bool istmpdir=cwp_false;/* true for user-given path		*/


	/* Hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(1);


	/* Get info from first trace */ 
	if (!gettr(&tr))  err("can't get first trace");
	nt = tr.ns;


	/* Get parameters */
	if (!getparint("verbose", &verbose))	verbose = 0;

	/* Look for user-supplied tmpdir */
	if (!getparstring("tmpdir",&tmpdir) &&
	    !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);

	if (!getparfloat("dt", &dt))	dt = ((double) tr.dt)/1000000.0;
	if (!dt) err("dt field is zero and not getparred");
	if (!getparfloat("dx", &dx) && !getparfloat("d2", &dx))	dx = tr.d2;
	if (!dx) err("d2 field is zero and dx not getparred");

	nslopes = countparval("slopes");
	if (nslopes) {
		slopes = alloc1float(nslopes);
		getparfloat("slopes", slopes);
	} else {
		nslopes = 1;
		slopes = alloc1float(nslopes);
		slopes[0] = 0.0;
	}

	namps = countparval("amps");
	if (namps) {
		amps = alloc1float(namps);
		getparfloat("amps", amps);
	} else {
		namps = 1;
		amps = alloc1float(namps);
		amps[0] = 1.0;
		warn("no amps given--doing no-op");
	}

	if (!getparfloat("bias", &bias)) bias = 0.0;


	/* Check parameters */
	if (nslopes != namps)
		err("number of slopes (%d) must equal number of amps(%d)",
			nslopes, namps);
	{ register int i;
	  for (i=1; i<nslopes; ++i)
		if (slopes[i] <= slopes[i-1])
			err("slopes must be monotonically increasing");
	}


	/* Store traces and headers in tmpfile while getting a count */
	if (STREQ(tmpdir,"")) {
		tracefp = etmpfile();
		headerfp = etmpfile();
		if (verbose) warn("using tmpfile() call");
	} else { /* user-supplied tmpdir */
		char directory[BUFSIZ];
		strcpy(directory, tmpdir);
		strcpy(tracefile, temporary_filename(directory));
		strcpy(headerfile, temporary_filename(directory));
		/* Trap signals so can remove temp files */
		signal(SIGINT,  (void (*) (int)) closefiles);
		signal(SIGQUIT, (void (*) (int)) closefiles);
		signal(SIGHUP,  (void (*) (int)) closefiles);
		signal(SIGTERM, (void (*) (int)) closefiles);
		tracefp = efopen(tracefile, "w+");
		headerfp = efopen(headerfile, "w+");
      		istmpdir=cwp_true;		
		if (verbose) warn("putting temporary files in %s", directory);
	}

	ntr = 0;
	do { 
		++ntr;
		efwrite(&tr, 1, HDRBYTES, headerfp);
		efwrite(tr.data, FSIZE, nt, tracefp);
	} while (gettr(&tr));
	

	/* Apply slope filter */
	slopefilter(nslopes,slopes,amps,bias,nt,dt,ntr,dx,tracefp);


	/* Output filtered traces */
	erewind(headerfp);
	erewind(tracefp);
	{ register int itr;
	  for (itr = 0; itr < ntr; ++itr) {
		efread(&tr, 1, HDRBYTES, headerfp);
		efread(tr.data, FSIZE, nt, tracefp);
		puttr(&tr);
	  }
	}


	/* Clean up */
	efclose(headerfp);
	if (istmpdir) eremove(headerfile);
	efclose(tracefp);
	if (istmpdir) eremove(tracefile);
	free1float(slopes);
	free1float(amps);

	return(CWP_Exit());
}
示例#16
0
int
main(int argc, char **argv)
{
	int nx,nz,ix,iz,verbose;
	float tmp;
	float **c11,**c13,**c33,**c44,**vp,**vs,**rho,**eps, **delta;

	/* input files */
	char *c11_file, *c13_file, *c33_file, *c44_file;
	FILE *c11fp, *c13fp, *c33fp, *c44fp;

	/* output files */
	char *vp_file,*vs_file,*rho_file,*eps_file,*delta_file;
	FILE *vpfp,*vsfp,*rhofp,*epsfp,*deltafp;

	/* hook up getpar */
	initargs(argc, argv);
	requestdoc(1);

	/* get required parameters */
	MUSTGETPARINT("nx",  &nx );
	MUSTGETPARINT("nz",  &nz );

	/* get parameters */
	if (!getparstring("rho_file", &rho_file))       rho_file="rho.bin";
	if (!getparstring("c11_file", &c11_file))   	c11_file="c11.bin";
	if (!getparstring("c13_file", &c13_file))   	c13_file="c13.bin";
	if (!getparstring("c33_file", &c33_file))   	c33_file="c33.bin";
	if (!getparstring("c44_file", &c44_file))   	c44_file="c44.bin";
	if (!getparstring("vp_file", &vp_file))       	vp_file="vp.bin";
	if (!getparstring("vs_file", &vs_file))       	vs_file="vs.bin";
	if (!getparstring("eps_file", &eps_file))     	eps_file="eps.bin";
	if (!getparstring("delta_file", &delta_file)) 	delta_file="delta.bin";
	if (!getparint("verbose", &verbose))        	verbose = 1;
	

        checkpars();

	/* allocate space */
	rho	= alloc2float(nz,nx);
	c11	= alloc2float(nz,nx);
	c13	= alloc2float(nz,nx);
	c33	= alloc2float(nz,nx);
	c44	= alloc2float(nz,nx);
	vp	= alloc2float(nz,nx);
	vs	= alloc2float(nz,nx);
	eps	= alloc2float(nz,nx);
	delta   = alloc2float(nz,nx);



	/* read mandatory input files */
	rhofp = efopen(rho_file,"r");
	if (efread(*rho, sizeof(float), nz*nx, rhofp)!=nz*nx)
	  err("error reading rho_file=%s!\n",rho_file);

	c11fp = efopen(c11_file,"r");
	if (efread(*c11, sizeof(float), nz*nx, c11fp)!=nz*nx)
	  err("error reading c11_file=%s!\n",c11_file);

	c13fp = efopen(c13_file,"r");
	if (efread(*c13, sizeof(float), nz*nx, c13fp)!=nz*nx)
	  err("error reading c13_file=%s!\n",c13_file);

	c33fp = efopen(c33_file,"r");
	if (efread(*c33, sizeof(float), nz*nx, c33fp)!=nz*nx)
	  err("error reading c33_file=%s!\n",c33_file);

	c44fp = efopen(c44_file,"r");
	if (efread(*c44, sizeof(float), nz*nx, c44fp)!=nz*nx)
	  err("error reading c44_file=%s!\n",c44_file);

	fclose(rhofp);
	fclose(c11fp);
	fclose(c13fp);
	fclose(c33fp);
	fclose(c44fp);


	/* open output file: */
	vpfp = fopen(vp_file,"w");
	vsfp = fopen(vs_file,"w");
	epsfp = fopen(eps_file,"w");
	deltafp = fopen(delta_file,"w");


	/* loop over gridpoints and do calculations */
	for(ix=0; ix<nx; ++ix){
	      for(iz=0; iz<nz; ++iz){
		vp[ix][iz] = sqrt(c33[ix][iz]/rho[ix][iz]);
		vs[ix][iz] = sqrt(c44[ix][iz]/rho[ix][iz]);
		eps[ix][iz] = (c11[ix][iz]-c33[ix][iz])/(2*c33[ix][iz]);
		tmp = (c13[ix][iz]+c44[ix][iz])*(c13[ix][iz]+c44[ix][iz]);
		tmp = tmp - (c33[ix][iz]-c44[ix][iz])*(c33[ix][iz]-c44[ix][iz]);
		delta[ix][iz] = tmp/(2*c33[ix][iz]*(c33[ix][iz]-c44[ix][iz]));
	      }
	}

	/* write the output files to disk */
	efwrite(*vp,sizeof(float),nz*nx,vpfp);
	efwrite(*vs,sizeof(float),nz*nx,vsfp);
	efwrite(*eps,sizeof(float),nz*nx,epsfp);
	efwrite(*delta,sizeof(float),nz*nx,deltafp);
		if(verbose){
	  warn("Output file for vp : %s ",vp_file);
	  warn("Output file for vs : %s ",vs_file);
	  warn("Output file for epsilon : %s ",eps_file);
	  warn("Output file for delta : %s ",delta_file);
	}


	/* free workspace */
	free2float(vp);
	free2float(vs);
	free2float(rho);
	free2float(eps);
	free2float(delta);
	free2float(c11);
	free2float(c13);
	free2float(c33);
	free2float(c44);

	return(CWP_Exit());	
}
示例#17
0
int
main (int argc, char **argv)
{
	int nt;			/* number of time samples */
	int ntau;		/* number of migrated time samples */
	int nx;			/* number of midpoints 	*/
	int ik,ix,it,itau,itmig;/* loop counters 	*/
	int nxfft;		/* fft size		*/
	int nk;			/* number of wave numbers */	

	int ntmig,nvmig;	

	float dt;		/* time sampling interval 	*/
	float ft;		/* first time sample		*/
	float dtau;		/* migrated time sampling interval */
	float ftau;		/* first migrated time value 	*/
	float dk;		/* wave number sampling interval */
	float fk;		/* first wave number 		*/
	float Q, ceil;		/* quality factor, ceiling of amplitude */
	float t,k;		/* time,wave number		*/
	float *tmig, *vmig;	/* arrays of time, interval velocities */
	float dx;		/* spatial sampling interval	*/
	float *vt;		/* velocity v(t)		*/
	float **p,**q;		/* input, output data		*/

	complex **cp,**cq;	/* complex input,output		*/

	char *vfile="";		/* name of file containing velocities */
	int verbose=0;		/* flag for echoing info		*/
	char *tmpdir;		/* directory path for tmp files		*/
	cwp_Bool istmpdir=cwp_false;/* true for user-given path		*/

	/* hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(1);

	/* get info from first trace */
	if (!gettr(&tr))  err("can't get first trace");
	nt = tr.ns;

	/* let user give dt and/or dx from command line */
	if (!getparfloat("dt", &dt)) {
		if (tr.dt) { /* is dt field set? */
			dt = ((double) tr.dt)/1000000.0;
		} else { /* dt not set, assume 4 ms */
			dt = 0.004;
			warn("tr.dt not set, assuming dt=0.004");
		}
	}
	if (!getparfloat("dx",&dx)) {
		if (tr.d2) { /* is d2 field set? */
			dx = tr.d2;
		} else {
			dx = 1.0;
			warn("tr.d2 not set, assuming d2=1.0");
		}
	}


	/* get optional parameters */
	if (!getparfloat("ft",&ft)) ft = 0.0;
	if (!getparint("ntau",&ntau)) ntau = nt; CHECK_NT("ntau",ntau);
	if (!getparfloat("dtau",&dtau)) dtau = dt;
	if (!getparfloat("ftau",&ftau)) ftau = ft;
	if (!getparfloat("Q",&Q)) Q = 1.0e6;
	if (!getparfloat("ceil",&ceil)) ceil = 1.0e6; 
		if (verbose)warn("Q=%f ceil=%f",Q,ceil); 

	if (!getparint("verbose", &verbose)) verbose = 0;

	/* Look for user-supplied tmpdir */
	if (!getparstring("tmpdir",&tmpdir) &&
	    !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);


	/* store traces and headers in tempfiles while getting a count */
	if (STREQ(tmpdir,"")) {
		tracefp = etmpfile();
		headerfp = etmpfile();
		if (verbose) warn("using tmpfile() call");
	} else { /* user-supplied tmpdir */
		char directory[BUFSIZ];
		strcpy(directory, tmpdir);
		strcpy(tracefile, temporary_filename(directory));
		strcpy(headerfile, temporary_filename(directory));
		/* Trap signals so can remove temp files */
		signal(SIGINT,  (void (*) (int)) closefiles);
		signal(SIGQUIT, (void (*) (int)) closefiles);
		signal(SIGHUP,  (void (*) (int)) closefiles);
		signal(SIGTERM, (void (*) (int)) closefiles);
		tracefp = efopen(tracefile, "w+");
		headerfp = efopen(headerfile, "w+");
      		istmpdir=cwp_true;		
		if (verbose) warn("putting temporary files in %s", directory);
	}

	nx = 0;
	do {
		 ++nx;
		efwrite(&tr,HDRBYTES,1,headerfp);
		efwrite(tr.data, FSIZE, nt, tracefp);
	} while (gettr(&tr));
	erewind(tracefp);
	erewind(headerfp);
	
	/* determine wavenumber sampling (for real to complex FFT) */
	nxfft = npfar(nx);
	nk = nxfft/2+1;
	dk = 2.0*PI/(nxfft*dx);
	fk = 0.0;
	
	/* allocate space */
	p = alloc2float(nt,nxfft);
	q = alloc2float(ntau,nxfft);
	cp = alloc2complex(nt,nk);
	cq = alloc2complex(ntau,nk);

	/* load traces into the zero-offset array and close tmpfile */
	efread(*p, FSIZE, nt*nx, tracefp);
	efclose(tracefp);

	/* determine velocity function v(t) */
	vt = ealloc1float(ntau);
	if (!getparstring("vfile",&vfile)) {
		ntmig = countparval("tmig");
		if (ntmig==0) ntmig = 1;
		tmig = ealloc1float(ntmig);
		if (!getparfloat("tmig",tmig)) tmig[0] = 0.0;
		nvmig = countparval("vmig");
		if (nvmig==0) nvmig = 1;
		if (nvmig!=ntmig) err("number of tmig and vmig must be equal");
		vmig = ealloc1float(nvmig);
		if (!getparfloat("vmig",vmig)) vmig[0] = 1500.0;
		for (itmig=1; itmig<ntmig; ++itmig)
			if (tmig[itmig]<=tmig[itmig-1])
				err("tmig must increase monotonically");
		for (it=0,t=0.0; it<ntau; ++it,t+=dt)
			intlin(ntmig,tmig,vmig,vmig[0],vmig[ntmig-1],
				1,&t,&vt[it]);
	} else {
		if (fread(vt,sizeof(float),nt,fopen(vfile,"r"))!=nt)
			err("cannot read %d velocities from file %s",nt,vfile);
	}
	
        checkpars();

	/* pad with zeros and Fourier transform x to k */
	for (ix=nx; ix<nxfft; ix++)
		for (it=0; it<nt; it++)
			p[ix][it] = 0.0;
	pfa2rc(-1,2,nt,nxfft,p[0],cp[0]);
	
	/* migrate each wavenumber */
	for (ik=0,k=fk; ik<nk; ik++,k+=dk)
		gazdagvt(k,nt,dt,ft,ntau,dtau,ftau,vt,cp[ik],cq[ik], Q, ceil);
	
	/* Fourier transform k to x (including FFT scaling) */
	pfa2cr(1,2,ntau,nxfft,cq[0],q[0]);
	for (ix=0; ix<nx; ix++)
		for (itau=0; itau<ntau; itau++)
			q[ix][itau] /= nxfft;

	/* restore header fields and write output */
	for (ix=0; ix<nx; ++ix) {
		efread(&tr,HDRBYTES,1,headerfp);
		tr.ns = ntau ;
		tr.dt = dtau * 1000000.0 ;
		tr.delrt = ftau * 1000.0 ;
		memcpy( (void *) tr.data, (const void *) q[ix],ntau*FSIZE);
		puttr(&tr);
	}
	
	/* Clean up */
	efclose(headerfp);
	if (istmpdir) eremove(headerfile);
	if (istmpdir) eremove(tracefile);

	return(CWP_Exit());	
}
示例#18
0
int main(int argc, char **argv)
{
	usghed usghin, usghtop, usghbot, usghlayer;
	usghed usghvtop, usghvbot, usghglayer;
	FILE *infp,*outfp,*topfp,*botfp,*layerfp;
	FILE *vtopfp,*vbotfp,*glayerfp;
	char *infile,*outfile,*layertop, *layerbot;
	char *gtopgrid, *gbotgrid;
	char *layers, *glayers;
	int ibot, itop;
	int ierr;
	int nz, iz;
	float *dzrl, sm2top, sm2bot, sm3top, sm3bot;
	float gabovetop, gbelowbot;
	int igabovetop, igbelowbot;
	float g0, r0;
	int ginterp=0;

	int n1,n2,n3;
	int i1,i2,i3;
	float d1,o1,d2,d3;

	float *grid, *ztop, *zbot, gmin, gmax;
	float *vtop, *vbot;
	float top, bot;
	float tmp;
	int i1top, i1bot, itmp;
	int ivtop, ivbot;

	float *sm2s, *sm3s;
	float *work, *fsmx, *fsmy, *vs, *zs;
	float z, scale, zscale, vscale;
	int ismx, ismy;

	int nlayer, nglayer;


	/* hook up getpar */
	initargs(argc,argv);
	askdoc(0);

	/* get parameters */
	if(getparstring("infile",&infile)) {
		infp = efopen(infile,"r");
	} else {
		infp = stdin;
	}
	ierr = fgetusghdr(infp,&usghin);
    	if(ierr!=0) err(" input grid header error ");
	if(getparstring("outfile",&outfile)) {
		outfp = efopen(outfile,"w");
	} else {
		outfp = stdout;
	}
	file2g(infp);
	file2g(outfp);

	nlayer = 0;
	nglayer = 0;
        nlayer = countparname("layers");
	if(nlayer==1) err(" at least 2 layers are needed \n");
        nglayer = countparname("glayers");

	if(nlayer==0) {
		if (getparstring("layertop",&layertop)) {
			topfp = efopen(layertop,"r");
			ierr = fgetusghdr(topfp,&usghtop);
      			if(ierr!=0) err(" layertop grid header error ");
		} else {
			err(" layertop missing ");
		}
		if (getparstring("layerbot",&layerbot)) {
			botfp = efopen(layerbot,"r");
			ierr = fgetusghdr(botfp,&usghbot);
      			if(ierr!=0) err(" layerbot grid header error ");
		} else {
			err(" layerbot missing ");
		}
	} else {
		if(nlayer!=nglayer && nglayer>0 ) 
		   err(" %d layers not matching %d glayers \n",nlayer,nglayer);
	}

	ivtop = 0;
	if (getparstring("gtopgrid",&gtopgrid)) {
		vtopfp = efopen(gtopgrid,"r");
		ierr = fgetusghdr(vtopfp,&usghvtop);
      		if(ierr!=0) err(" gtopgrid header error ");
		ivtop = 1;
	}
	ivbot = 0;
	if(getparstring("gbotgrid",&gbotgrid) ) {
		vbotfp = efopen(gbotgrid,"r");
		ierr = fgetusghdr(vbotfp,&usghvbot);
      		if(ierr!=0) err(" gbotgrid header error ");
		ivbot = 1;
	}
	if(!getparint("ginterp",&ginterp)) ginterp=0;

	if(ivtop==0 || ivbot==0) {
		if ( getparfloat("g0",&g0) && getparfloat("r0",&r0) ) {
			ivtop = -1; ivbot = -1;
		}
	}

	if( !getparint("nz",&nz) ) nz=10;
	if(nlayer!=0) nz = nlayer - 1;
	dzrl = emalloc(nz*sizeof(float));
	sm2s = emalloc((nz+1)*sizeof(float));
	sm3s = emalloc((nz+1)*sizeof(float));

	if( countparval("dzrl")>0 && nz!=countparval("dzrl") ) {
		err( " number of dzrl elements must match nz=%d \n",nz);
	} else if( countparval("dzrl")==0 ) {
		for(iz=0;iz<nz;iz++) dzrl[iz] = 1.;
	} else if( countparval("dzrl")==nz) {
		getparfloat("dzrl",dzrl);
	}

	if( !getparfloat("sm2top",&sm2top) ) sm2top=0.;
	if( !getparfloat("sm3top",&sm3top) ) sm3top=0.;
	if( !getparfloat("sm2bot",&sm2bot) ) sm2bot=0.;
	if( !getparfloat("sm3bot",&sm3bot) ) sm3bot=0.;

	igabovetop = 1;
	if( !getparfloat("gabovetop",&gabovetop) ) igabovetop=0;
	igbelowbot = 1;
	if( !getparfloat("gbelowbot",&gbelowbot) ) igbelowbot=0;


	n1 = usghin.n1;
	n2 = usghin.n2;
	n3 = usghin.n3;
	o1 = usghin.o1;
	d1 = usghin.d1;
	d2 = usghin.d2;
	d3 = usghin.d3;
	gmin = usghin.gmin;
	gmax = usghin.gmax;

	/* memory allocations */
	ztop = (float*) emalloc(n2*n3*sizeof(float));
	zbot = (float*) emalloc(n2*n3*sizeof(float));
	vtop = (float*) emalloc(n2*n3*sizeof(float));
	vbot = (float*) emalloc(n2*n3*sizeof(float));
	zs = (float*) emalloc(n2*n3*(nz+1)*sizeof(float));
	vs = (float*) emalloc(n2*n3*(nz+1)*sizeof(float));
	work = (float*) emalloc(n2*n3*sizeof(float));
	grid = (float*) emalloc(n1*sizeof(float));
	
	if(nlayer==0) {
		if(usghin.n2!=usghtop.n1) err("check layertop header n1");
		if(usghin.n3!=usghtop.n2) err("check layertop header n2");
		if(usghin.o2!=usghtop.o1) err("check layertop header o1");
		if(usghin.o3!=usghtop.o2) err("check layertop header o2");
		if(usghin.d2!=usghtop.d1) err("check layertop header d1");
		if(usghin.d3!=usghtop.d2) err("check layertop header d2");
		efseek(topfp,0,0);
		efread(ztop,sizeof(float),n2*n3,topfp);

		if(usghin.n2!=usghbot.n1) err("check layerbot header n1");
		if(usghin.n3!=usghbot.n2) err("check layerbot header n2");
		if(usghin.o2!=usghbot.o1) err("check layerbot header o1");
		if(usghin.o3!=usghbot.o2) err("check layerbot header o2");
		if(usghin.d2!=usghbot.d1) err("check layerbot header d1");
		if(usghin.d3!=usghbot.d2) err("check layerbot header d2");
		efseek(botfp,0,0);
		efread(zbot,sizeof(float),n2*n3,botfp);

		if(ivtop==1) {
		if(usghin.n2!=usghvtop.n1) err("check gtopgrid header n1");
		if(usghin.n3!=usghvtop.n2) err("check gtopgrid header n2");
		if(usghin.o2!=usghvtop.o1) err("check gtopgrid header o1");
		if(usghin.o3!=usghvtop.o2) err("check gtopgrid header o2");
		if(usghin.d2!=usghvtop.d1) err("check gtopgrid header d1");
		if(usghin.d3!=usghvtop.d2) err("check gtopgrid header d2");
		efseek(vtopfp,0,0);
		efread(vtop,sizeof(float),n2*n3,vtopfp);
		} 

		if(ivbot==1) {
		if(usghin.n2!=usghvbot.n1) err("check gbotgrid header n1");
		if(usghin.n3!=usghvbot.n2) err("check gbotgrid header n2");
		if(usghin.o2!=usghvbot.o1) err("check gbotgrid header o1");
		if(usghin.o3!=usghvbot.o2) err("check gbotgrid header o2");
		if(usghin.d2!=usghvbot.d1) err("check gbotgrid header d1");
		if(usghin.d3!=usghvbot.d2) err("check gbotgrid header d2");
		efseek(vbotfp,0,0);
		efread(vbot,sizeof(float),n2*n3,vbotfp);
		}
	} else {
		for(iz=0;iz<nlayer;iz++) {
			getnparstring(iz+1,"layers",&layers);
			layerfp=efopen(layers,"r");
			ierr = fgetusghdr(layerfp,&usghlayer);
			if(ierr!=0) err(" error open layers=%s \n",layers);
			if(usghin.n2!=usghlayer.n1) err("check %s header n1",layers);
			if(usghin.n3!=usghlayer.n2) err("check %s header n2",layers);
			if(usghin.o2!=usghlayer.o1) err("check %s header o1",layers);
			if(usghin.o3!=usghlayer.o2) err("check %s header o2",layers);
			if(usghin.d2!=usghlayer.d1) err("check %s header d1",layers);
			if(usghin.d3!=usghlayer.d2) err("check %s header d2",layers);
			efseek(layerfp,0,0);
			efread(zs+iz*n2*n3,sizeof(float),n2*n3,layerfp);
			efclose(layerfp);
		}
		for(iz=0;iz<nglayer;iz++) {
			getnparstring(iz+1,"glayers",&glayers);
			glayerfp=efopen(glayers,"r");
			ierr = fgetusghdr(glayerfp,&usghglayer);
			if(ierr!=0) err(" error open layers=%s \n",layers);
			if(usghin.n2!=usghglayer.n1) err("check %s header n1",glayers);
			if(usghin.n3!=usghglayer.n2) err("check %s header n2",glayers);
			if(usghin.o2!=usghglayer.o1) err("check %s header o1",glayers);
			if(usghin.o3!=usghglayer.o2) err("check %s header o2",glayers);
			if(usghin.d2!=usghglayer.d1) err("check %s header d1",glayers);
			if(usghin.d3!=usghglayer.d2) err("check %s header d2",glayers);
			efseek(glayerfp,0,0);
			efread(vs+iz*n2*n3,sizeof(float),n2*n3,glayerfp);
			efclose(glayerfp);
		}
		nz = nlayer - 1;
	}

/* compute mini layer depth and grid values */
	if(nlayer==0) {
		for(i2=0;i2<n2*n3;i2++) {
			zs[i2] = ztop[i2];
			vs[i2] = vtop[i2];
		}
		tmp = 0.;
		for(iz=0;iz<nz;iz++) tmp = tmp + dzrl[iz];
		vscale = 0.;
		zscale = 0.;
		for(iz=1;iz<nz;iz++) {
			zscale += dzrl[iz-1]/tmp;
			if(ginterp==0) {
				vscale += dzrl[iz-1]/tmp;
			} else {
				vscale = (float)iz / nz;
			}

			for(i2=0;i2<n2*n3;i2++) {
				zs[i2+iz*n2*n3] = ztop[i2] +
					zscale*(zbot[i2]-ztop[i2]);
				vs[i2+iz*n2*n3] = vtop[i2] + 
					vscale*(vbot[i2]-vtop[i2]);
			}
		}
		for(i2=0;i2<n2*n3;i2++) {
			zs[i2+nz*n2*n3] = zbot[i2];
			vs[i2+nz*n2*n3] = vbot[i2];
		}
	}

/* compute smoothing window for mini layers */
	tmp = 0.;
	for(iz=0;iz<nz;iz++) tmp = tmp + dzrl[iz];
	scale = 0.;
	sm2s[0] = sm2top;
	sm3s[0] = sm3top;
	for(iz=1;iz<nz+1;iz++) {
		scale += dzrl[iz-1]/tmp;
		sm2s[iz] = sm2top + scale*(sm2bot-sm2top);
		sm3s[iz] = sm3top + scale*(sm3bot-sm3top);
	} 

/* compute grid values at the mini layers if not specified */
	fseek2g(infp,0,0);
	if( ( (ivtop==0 || ivbot==0) && nlayer==0 ) || (nglayer==0 && nlayer>0) ) {
		for(i3=0;i3<n3;i3++) {
			for(i2=0;i2<n2;i2++) {
				efread(grid,sizeof(float),n1,infp);
				for(iz=0;iz<nz+1;iz++) {
					tmp = (zs[i2+i3*n2+iz*n2*n3] - o1)/d1 + 0.5; 
					i1 = tmp;
					if(i1<0) {
						vs[i2+i3*n2+iz*n2*n3] = grid[0];
					} else if(i1>=n1-1) {
						vs[i2+i3*n2+iz*n2*n3] = grid[n1-1];
					} else {
						vs[i2+i3*n2+iz*n2*n3] = grid[i1]+
								(tmp-i1)*(grid[i1+1]-grid[i1]);
					}
				}
			}
		}
	} else if(ivtop==-1 && ivbot==-1) {
		for(i3=0;i3<n3;i3++) {
			for(i2=0;i2<n2;i2++) {
				for(iz=0;iz<nz+1;iz++) {
					tmp = (zs[i2+i3*n2+iz*n2*n3] - ztop[i3*n2+i2]);
					vs[i2+i3*n2+iz*n2*n3] = g0 + r0 * tmp;
				}	
			}
		}
	}
/* smooth mini layer grids */
	for(iz=0;iz<nz+1;iz++) {
		tmp = sm2s[iz]/d2;
		ismx = tmp + 1.5;
		tmp = sm3s[iz]/d3;
		ismy = tmp + 1.5;
		fsmx = (float*) emalloc(ismx*sizeof(float));
		fsmy = (float*) emalloc(ismy*sizeof(float));
		/* 2d smoothing */
		smth2d_(vs+iz*n2*n3,work,fsmx,fsmy,&n2,&n3,&ismx,&ismy);
		/*
		dump2xplot(vs+iz*n2*n3,n2,n3,0,"vsmoth");
		*/
		free(fsmx);
		free(fsmy);
	}


/* output grid */
	fseek2g(infp,0,0);
	for(i3=0;i3<n3;i3++) {
		for(i2=0;i2<n2;i2++) {

			efread(grid,sizeof(float),n1,infp);
			itmp = i2+i3*n2;
			if(nlayer==0) {
				top = ztop[itmp];
				bot = zbot[itmp];
			} else {
				top = zs[itmp];
				bot = zs[itmp+(nlayer-1)*n2*n3];
			}
			tmp = (top - o1)/d1 + 0.5; 
			i1top = tmp;
			tmp = (bot - o1)/d1 + 0.5; 
			i1bot = tmp;
			if(i1top<0) i1top = 0;
			if(i1bot>n1-1) i1bot = n1-1;
			for(i1=i1top;i1<=i1bot;i1++) {
				z = o1 + i1*d1;
                                if(z>=zs[itmp] && z<=zs[itmp+nz*n2*n3]) {
					for(iz=0;iz<nz;iz++) {
						if( z == zs[itmp+iz*n2*n3] && z == zs[itmp+(iz+1)*n2*n3] ){
							grid[i1] = vs[itmp+iz*n2*n3];

						}else if(z>=zs[itmp+iz*n2*n3] && z<zs[itmp+(iz+1)*n2*n3]) {
							tmp = (z-zs[itmp+iz*n2*n3]) /
					  			(zs[itmp+(iz+1)*n2*n3]-zs[itmp+iz*n2*n3]);
							grid[i1] = vs[itmp+iz*n2*n3] + 
								tmp*(vs[itmp+(iz+1)*n2*n3]-vs[itmp+iz*n2*n3]);
                                                	if( grid[i1] != grid[i1] ){
                                                   		fprintf( stderr ,"NaN at i3=%d " ,i3 );
                                                   		fprintf( stderr ,"i2=%d i1=%d\n" ,i2, i3);
                                                	}
							break;
						}
					}
				}
			}

			if(igabovetop==1) {
				for(i1=0;i1<i1top;i1++) {
					grid[i1] = gabovetop;
				}
			}
			if(igbelowbot==1) {
				for(i1=i1bot;i1<n1;i1++) {
					grid[i1] = gbelowbot;
				}
			}

			if(i2==0 && i3==0) {
				gmin = grid[0];
				gmax = grid[0];
			}
			for(i1=0;i1<n1;i1++) {
				if(gmin>grid[i1]) gmin = grid[i1];
				if(gmax<grid[i1]) gmax = grid[i1];
			}

                        if( grid[0] != grid[0] ){
                           fprintf( stderr ,"NaN\n" );
                        }
			efwrite(grid,sizeof(float),n1,outfp);

		}
	}

	usghin.gmin = gmin;
	usghin.gmax = gmax;

	ierr = fputusghdr(outfp,&usghin);
	
	free(ztop);
	free(zbot);
	free(vtop);
	free(vbot);
	free(zs);
	free(vs);
	free(work);
	free(grid);
	exit(0);
}
示例#19
0
int
main(int argc, char **argv)
{
	int nt;		/* number of time samples per trace */
	float dt;	/* time sampling interval */
	float ft;	/* time of first sample */
	int it;		/* time sample index */
	int cdpmin;	/* minimum cdp to process */
	int cdpmax;	/* maximum cdp to process */
	float dxcdp;	/* cdp sampling interval */
	int noffmix;	/* number of offsets to mix */
	float offmax;	/* maximum offset */
	float tmute;	/* mute time at far offset */
	float vrms;	/* rms velocity at mute time */
	int nsmax;	/* maximum number of time shifts per trace in DMO */
	int ns;		/* actual number of time shifts per trace in DMO */
	float *p;	/* input trace */
	float **q;	/* output DMO-corrected traces */
	float *temp;	/* temporary array */
	float *ts;	/* table of time shifts for DMO */
	float *as;	/* table of amplitudes for DMO */
	float offset=0.0;/* source-receiver offset of current trace */
	float oldoffset;/* offset of previous trace */
	int cdp=0;	/* cdp number of current trace */
	int ncdp;	/* number of cdps */
	int icdp;	/* cdp index */
	int jcdp;	/* cdp index */
	int jcdplo;	/* lower bound for jcdp */
	int jcdphi;	/* upper bound for jcdp */
	int ntrace;	/* number of traces processed in current mix */
	int itrace;	/* trace index */
	int noff;	/* number of offsets processed in current mix */
	int gottrace;	/* non-zero if an input trace was read */
	int done;	/* non-zero if done */
	float *ds;	/* shaping filter to complete DMO processing */
	int lds=125;	/* length of shaping filter */
	int ifds=-100;	/* time index of first sample in shaping filter */
	int verbose;	/* =1 for diagnostic print */
	char *tmpdir;	/* directory path for tmp files	*/
	cwp_Bool istmpdir=cwp_false;/* true for user given path */

	/* hook up getpar */
	initargs(argc, argv);
	requestdoc(1);

	/* get information from the first header */
	if (!gettr(&tr)) err("can't get first trace");
	nt = tr.ns;
	dt = ((double) tr.dt)/1000000.0;
	ft = tr.delrt/1000.0;

	/* get parameters */
	if (!getparint("cdpmin",&cdpmin)) err("must specify cdpmin");
	if (!getparint("cdpmax",&cdpmax)) err("must specify cdpmax");
	if (cdpmin>cdpmax) err("cdpmin must be less than cdpmax");
	if (!getparfloat("dxcdp",&dxcdp)) err("must specify dxcdp");
	if (!getparint("noffmix",&noffmix)) err("must specify noffmix");
	if (!getparfloat("offmax",&offmax)) offmax=3000.0;
	if (!getparfloat("tmute",&tmute)) tmute=2.0;
	if (!getparfloat("vrms",&vrms)) vrms=1500.0;
	if (!getparint("nsmax",&nsmax)) nsmax=400;
	if (!getparint("verbose",&verbose)) verbose=0;

	/* Look for user-supplied tmpdir */
	if (!getparstring("tmpdir",&tmpdir) &&
	    !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);
	
        checkpars();

	/* determine number of cdps */
	ncdp = cdpmax-cdpmin+1;

	/* allocate workspace */
	q = ealloc2float(nt,ncdp);
	p = ealloc1float(nt);
	temp = ealloc1float(nt);
	ts = ealloc1float(nsmax);
	as = ealloc1float(nsmax);
	ds = ealloc1float(lds);
	
	/* tabulate time shifts and amplitudes for dmo */
	maketa(dxcdp,dt,offmax,tmute,vrms,nsmax,&ns,ts,as);
	if (verbose) 
		fprintf(stderr,"\tDMO will be performed via %d time shifts\n",
			ns);
	
	/* compute shaping filter for dmo horizontal reflection response */
	makeds(ns,ts,as,lds,ifds,ds);
	
	/* open temporary file for headers */
	if (STREQ(tmpdir,"")) {
		headerfp = etmpfile();
		if (verbose) warn("using tmpfile() call");
	} else { /* user-supplied tmpdir */
		char directory[BUFSIZ];
		strcpy(directory, tmpdir);
		strcpy(headerfile, temporary_filename(directory));
		/* Trap signals so can remove temp files */
		signal(SIGINT,  (void (*) (int)) closefiles);
		signal(SIGQUIT, (void (*) (int)) closefiles);
		signal(SIGHUP,  (void (*) (int)) closefiles);
		signal(SIGTERM, (void (*) (int)) closefiles);
		headerfp = efopen(headerfile, "w+");
      		istmpdir=cwp_true;		
		if (verbose)
			warn("putting temporary header file in %s", directory);
	}
	
	/* initialize */
	oldoffset = tr.offset;
	gottrace = 1;
	done = 0;
	ntrace = 0;
	noff = 0;
	for (icdp=0; icdp<ncdp; ++icdp)
		for (it=0; it<nt; ++it)
			q[icdp][it] = 0.0;

	/* loop over traces */
	do {
		
		/* if got a trace */
		if (gottrace) {

			/* determine offset and cdp */
			offset = tr.offset;
			cdp = tr.cdp;
		
			/* update number of offsets mixed */
			if (offset!=oldoffset) noff++;

			/* get trace samples */
 			memcpy( (void *) p,
				  (const void *) tr.data, nt*sizeof(float));
		}
		
		/* if a mix of offsets is complete */
		if (noff==noffmix || !gottrace) {
			
			/* update number of offsets mixed */
			if (!gottrace) noff++; 
			
			/* apply shaping filter to complete dmo processing */
			for (icdp=0; icdp<ncdp; ++icdp) {
				convolve_cwp(lds,ifds,ds,nt,0,q[icdp],nt,0,temp);
				memcpy( (void *) q[icdp],
					(const void *) temp, nt*sizeof(float));
			}
			
			/* rewind trace header file */
			erewind(headerfp);
			
			/* loop over all output traces */
			for (itrace=0; itrace<ntrace; ++itrace) {
			
				/* read trace header and determine cdp index */
				efread(&tro,HDRBYTES,1,headerfp);
				icdp = tro.cdp-cdpmin;
				
				/* get dmo-corrected data */
				memcpy((void *) tro.data,
				      (const void *) q[icdp],nt*sizeof(float));
				
				/* write output trace */
				puttr(&tro);
			}
			
			/* report */
			if (verbose) 
				fprintf(stderr,"\tCompleted mix of "
					"%d offsets with %d traces\n",
					noff,ntrace);
			
			/* if no more traces, break */
			if (!gottrace) break;
			
			/* rewind trace header file */
			erewind(headerfp);
			
			/* reset number of offsets and traces */
			noff = 0;
			ntrace = 0;
			
			/* zero dmo accumulators */
			for (icdp=0; icdp<ncdp; ++icdp)
				for (it=0; it<nt; ++it)
					q[icdp][it] = 0.0;
		}
				
		/* if cdp is within range of cdps to process */
		if (cdp>=cdpmin && cdp<=cdpmax) {
		
			/* save trace header and update number of traces */
			efwrite(&tr,HDRBYTES,1,headerfp);
			ntrace++;
			
			/* determine output traces potentially modified
			   by input */
			icdp = cdp-cdpmin;
			jcdplo = MAX(0,icdp-0.5*ABS(offset/dxcdp));
			jcdphi = MIN(ncdp-1,icdp+0.5*ABS(offset/dxcdp));
			
			/* loop over potentially modified output traces */
			for (jcdp=jcdplo; jcdp<=jcdphi; ++jcdp) {
		
				/* do dmo for one output trace */
				dmotx(ns,ts,as,offset,(jcdp-icdp)*dxcdp,dxcdp,
				      0,nt,dt,ft,p,q[jcdp]);
			}

			/* remember offset */
			oldoffset = offset;
		}

		/* get next trace (if there is one) */
		if (!gettr(&tr)) gottrace = 0;
		
	} while (!done);

	/* clean up */
	efclose(headerfp);
	if (istmpdir) eremove(headerfile);
	return(CWP_Exit());
}
示例#20
0
int
main(int argc, char **argv)
{
	char plotcmd[BUFSIZ];	/* build psmovie command for popen 	*/
	float *trbuf;		/* trace buffer			 	*/
	FILE *plotfp;		/* fp for plot data			*/
	int nt;			/* number of samples on trace		*/
	int n2;			/* number of traces per frame		*/
	int n3;			/* number of frames in data		*/
	int ntr;		/* number of traces			*/
	int verbose;		/* verbose flag				*/
	float d1;		/* time/depth sample rate 		*/
	float d2;		/* trace/dx sample rate 		*/
	float f1;		/* tmin/zmin				*/
	float f2;		/* tracemin/xmin	 		*/
	cwp_Bool seismic;	/* is this seismic data?		*/
	cwp_Bool have_n2 = cwp_false;/* was n2 getparred?			*/
	cwp_Bool have_n3 = cwp_false;/* was n3 getparred?			*/
	cwp_Bool have_ntr = cwp_false;/* was ntr set in header?		*/
	char *tmpdir;		/* directory path for tmp files		*/
	cwp_Bool istmpdir=cwp_false;/* true for user given path		*/

	char *cwproot;		/* value of CWPROOT environment variable*/
	char *bindir;		/* directory path for tmp files		*/

	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);
	

	/* Get info from first trace */
	if (!gettr(&tr)) err("can't get first trace");
	seismic = ISSEISMIC(tr.trid); 
	nt = tr.ns;
	ntr = tr.ntr;
	if (ntr) have_ntr = cwp_true; 

	if (!getparint("verbose", &verbose))	verbose=0;

	if (!getparfloat("d1", &d1)) {
		if      (tr.d1)  d1 = tr.d1;
		else if (tr.dt)  d1 = ((double) tr.dt)/1000000.0;
		else {
			if (seismic) {
				d1 = 0.004;
				warn("tr.dt not set, assuming dt=0.004");
			} else { /* non-seismic data */
				d1 = 1.0;
				warn("tr.d1 not set, assuming d1=1.0");
			}
		}
	}

	if (!getparfloat("d2", &d2)) d2 = (tr.d2) ? tr.d2 : 1.0;

	if (!getparfloat("f1", &f1)) {
		if      (tr.f1)     f1 = tr.f1;
		else if (tr.delrt)  f1 = (float) tr.delrt/1000.0;
		else                f1 = 0.0;
	}

	if (!getparfloat("f2", &f2)) {
		if      (tr.f2)     f2 = tr.f2;
		else if (tr.tracr)  f2 = (float) tr.tracr;
		else if (tr.tracl)  f2 = (float) tr.tracl;
		else if (seismic)   f2 = 1.0;
		else 		    f2 = 0.0;
	}

	if (!getparfloat("f2", &f2)) f2 = 1.0;

	/* Look for user-supplied tmpdir */
	if (!getparstring("tmpdir",&tmpdir) &&
	    !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);

	/* See if CWPBIN environment variable is not set */
	if (!(bindir = getenv("CWPBIN"))) { /* construct bindir from CWPROOT */

		bindir = (char *) emalloc(BUFSIZ);

		/* Get value of CWPROOT environment variable */
		if (!(cwproot = getenv("CWPROOT"))) cwproot ="" ;
		if (STREQ(cwproot, "")) {
			warn("CWPROOT environment variable is not set! ");
			err("Set CWPROOT in shell environment as per instructions in CWP/SU Installation README files");
		}
		/* then bindir = $CWPROOT/bin */
		sprintf(bindir, "%s/bin", cwproot);
	}
	strcat(bindir,"/");   /* put / at the end of bindir */

	/* Allocate trace buffer */
	trbuf = ealloc1float(nt);

	/* Get or set n2 and n3 */
	if (getparint("n2", &n2)) have_n2 = cwp_true;
	if (getparint("n3", &n3)) have_n3 = cwp_true;
	if (have_n2 && have_n3) have_ntr = cwp_true;

	if (!have_ntr) { /* count traces */
		if (verbose) {
		   warn("n2 or n3 not getparred, or ntr header field not set");
		   warn("         ... counting traces");
		}

		/* Create temporary "file" to hold data */
		if (STREQ(tmpdir,"")) {
			tracefp = etmpfile();
			if (verbose) warn("using tmpfile() call");
		} else { /* user-supplied tmpdir */
			char directory[BUFSIZ];
			strcpy(directory, tmpdir);
			strcpy(tracefile, temporary_filename(directory));
			/* Handle user interrupts */
			signal(SIGINT, (void (*) (int)) closefiles);
			signal(SIGTERM, (void (*) (int)) closefiles);
			tracefp = efopen(tracefile, "w+");
			istmpdir=cwp_true;		
			if (verbose)
			      warn("putting temporary files in %s", directory);
		}

       
		/* Loop over input frames & put them into the data file */
		ntr = 0;
		do {
			++ntr;
			efwrite(tr.data, FSIZE, nt, tracefp);
		} while (gettr(&tr));

	} 

	/* Set dimensions of movie */
	if (!have_n2 && !have_n3) { n2 = ntr; n3=1; } 
	if (have_n2 && !have_n3) n3 = ntr/n2;
	if (!have_n2 && have_n3) n2 = ntr/n3;

	/* Set up psmovie command line */
	sprintf(plotcmd,
		"%spsmovie n1=%d n2=%d n3=%d d1=%f d2=%f f1=%f f2=%f", bindir,
			   nt, n2, n3, d1, d2, f1, f2);

	fprintf(stderr, "%s\n", plotcmd);

	for (--argc, ++argv; argc; --argc, ++argv) {
		if (strncmp(*argv, "d1=", 3) && /* skip those already set */
		    strncmp(*argv, "d2=", 3) &&
		    strncmp(*argv, "f1=", 3) &&
		    strncmp(*argv, "f2=", 3)) {
		    
			strcat(plotcmd, " ");   /* put a space between args */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
			strcat(plotcmd, *argv); /* add the arg */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
		}
	}


	/* Open pipe to psmovie and send the traces */
	plotfp = epopen(plotcmd, "w");
	
	if (!have_ntr){
			/* send out stored traces one by one */
		rewind(tracefp);
		{ register int itr;
			for (itr = 0; itr < ntr; ++itr) {
				efread (trbuf, FSIZE, nt, tracefp);
				efwrite(trbuf, FSIZE, nt, plotfp);
			}
		}
	} else { /* just pump out traces and let psmovie do the work */
		do {
			efwrite(tr.data, FSIZE, nt, plotfp);
		} while (gettr(&tr));
	}


	/* Clean up */
	epclose(plotfp);
	if (!have_ntr) {
		efclose(tracefp);
		if (istmpdir) eremove(tracefile);
	} 


	return EXIT_SUCCESS;
}
示例#21
0
main (int argc, char **argv)
{
	int n1,n2,n3,
		n1s,n2s,n3s,
		id1s,id2s,id3s,
		if1s,if2s,if3s,
		*ix1s,*ix2s,*ix3s,
		i1s,i2s,i3s,
		i1,i2,i3,
		offset;
	float *p,*ps;
	FILE *infp=stdin,*outfp=stdout;

	/* hook up getpar to handle the parameters */
	initargs(argc,argv);
	askdoc(0);

	/* get optional parameters */
	if (!getparint("n1",&n1)) {
		if (fseek(infp,0L,2)==-1)
			err("input file size unknown; specify n1\n");
		n1 = eftell(infp)/sizeof(float);
	}
	if (!getparint("n2",&n2)) {
		if (fseek(infp,0L,2)==-1)
			err("input file size unknown; specify n2\n");
		n2 = eftell(infp)/(n1*sizeof(float));
	}
	if (!getparint("n3",&n3)) {
		if (fseek(infp,0L,2)==-1)
			err("input file size unknown; specify n3\n");
		n3 = eftell(infp)/(n2*n1*sizeof(float));
	}
	ix1s = alloc1int(countparval("ix1s"));
	if ((n1s=getparint("ix1s",ix1s))==0) {
		free1int(ix1s);
		if (!getparint("id1s",&id1s)) id1s = 1;
		if (!getparint("if1s",&if1s)) if1s = 0;
		if (!getparint("n1s",&n1s)) n1s = 1+(n1-if1s-1)/id1s;
		ix1s = alloc1int(n1s);
		for (i1s=0,i1=if1s; i1s<n1s; i1s++,i1+=id1s)
			ix1s[i1s] = i1;
	}
	ix2s = alloc1int(countparval("ix2s"));
	if ((n2s=getparint("ix2s",ix2s))==0) {
		free1int(ix2s);
		if (!getparint("id2s",&id2s)) id2s = 1;
		if (!getparint("if2s",&if2s)) if2s = 0;
		if (!getparint("n2s",&n2s)) n2s = 1+(n2-if2s-1)/id2s;
		ix2s = alloc1int(n2s);
		for (i2s=0,i2=if2s; i2s<n2s; i2s++,i2+=id2s)
			ix2s[i2s] = i2;
	}
	ix3s = alloc1int(countparval("ix3s"));
	if ((n3s=getparint("ix3s",ix3s))==0) {
		free1int(ix3s);
		if (!getparint("id3s",&id3s)) id3s = 1;
		if (!getparint("if3s",&if3s)) if3s = 0;
		if (!getparint("n3s",&n3s)) n3s = 1+(n3-if3s-1)/id3s;
		ix3s = alloc1int(n3s);
		for (i3s=0,i3=if3s; i3s<n3s; i3s++,i3+=id3s)
			ix3s[i3s] = i3;
	}

	/* check parameters */
	for (i1s=0; i1s<n1s; i1s++)
		if (ix1s[i1s]<0 || ix1s[i1s]>n1-1)
			err("ix1s[%d]=%d is out of bounds!\n",i1s,ix1s[i1s]);
	for (i2s=0; i2s<n2s; i2s++)
		if (ix2s[i2s]<0 || ix2s[i2s]>n2-1)
			err("ix2s[%d]=%d is out of bounds!\n",i2s,ix2s[i2s]);
	for (i3s=0; i3s<n3s; i3s++)
		if (ix3s[i3s]<0 || ix3s[i3s]>n3-1)
			err("ix3s[%d]=%d is out of bounds!\n",i3s,ix3s[i3s]);

	/* allocate space for input and output arrays */
	p = ealloc1float(n1);
	ps = ealloc1float(n1s);

	/* loop over 3rd dimension */
	for (i3s=0; i3s<n3s; i3s++) {

		/* loop over 2nd dimension */
		for (i2s=0; i2s<n2s; i2s++) {

			/* find beginning of input array */
			offset = (ix2s[i2s]+ix3s[i3s]*n2)*n1*sizeof(float);
			efseek(infp,offset,0);

			/* read input array, if it exists */
			if (fread(p,sizeof(float),n1,infp)==n1) {

				/* loop over 1st dimension */
				for (i1s=0; i1s<n1s; i1s++) {
					ps[i1s] = p[ix1s[i1s]];
				}

			/* if input does not exist */
			} else {
				err("no input for ix2s[%d]=%d ix3s[%d]=%d!\n",
				i2s,ix2s[i2s],
				i3s,ix3s[i3s]);
			}

			/* write trace to output file */
			efwrite(ps,sizeof(float),n1s,outfp);
		}
	}
}
示例#22
0
文件: sgyin.c 项目: JOravetz/SeisUnix
main(int argc, char **argv)
{
    FILE     *ifp;     /* file pointer for input       */
    FILE     *hfp;     /* file pointer for popen write */
    int       bfd;     /* file descriptor for bfile    */

    string    tape;    /* name of raw tape device      */
    int       clean;   /* clean trace header           */
    int       verbose; /* echo every 20th trace        */
    int       over;    /* check format                 */
    int	      convert; /* convert ibm fpt to ieee fpt  */
    string    hfile;   /* name of ascii header file    */
    string    bfile;   /* name of binary header file   */
    int       trmin;   /* first trace to read	       */
    int       trmax;   /* last trace to read	       */
    int       nt;      /* number of data samples       */

    char      cmdbuf[BUFSIZ];	/* dd command buffer	              */
    char      ebcbuf[EBCBYTES];	/* ebcdic data buffer	              */
    int       itr = 0;	        /* current trace number		      */
    bool      nsflag = FALSE;	/* flag for error in tr.ns	      */
    char      hdr_buf[10];      /* 1st 10 bytes of header in ascii    */
    char      tmp_buf[3600];    /* temp. buffer to read in header     */
    unsigned  int nsamp;	/* number of samples per trace        */
    int       i;                /* loop counter to zero trace samples */
	int       *ibstart,*ibyte,*itype;
	int       *obstart,*obyte,*otype;
	int       nmap=0, imap;
	int       ibs,iby,ity,obs,oby,oty;
	short     itmp2;
	int       itmp4;
	float	  tmp;
	int		  ntg=0;
	int 	rmbadtrace, ibt, nbt;
    
    /* initialize */
    initargs(argc, argv);
    askdoc(1); 
    
    /* make sure stdout is a file or pipe */
    switch(filestat(STDOUT)) {
    case TTY:
	err("stdout can't be tty");
	break;
    case DIRECTORY:
	err("stdout must be a file, not a directory");
	break;
    case BADFILETYPE:
	err("stdout is illegal filetype");
	break;
    }
    
    /* set filenames */
    if (!getparstring("tape", &tape)) { 
	ifp = stdin;
	file2g(ifp);
    } else {
	/* open files - first the tape */
	ifp = efopen(tape, "r");
    }

    file2g(stdout); 

    /* set parameters */
    if (!getparint("clean", &clean))     clean   = 1;
    if (!getparint("verbose", &verbose)) verbose = 0;
    if (!getparint("over", &over))	 over    = 0;
    if (!getparint("convert", &convert)) convert    = 1;
    if (!getparint("trmin", &trmin))	 trmin   = 1;
    if (!getparint("trmax", &trmax))	 trmax   = LONG_MAX;
    if (!getparint("rmbadtrace",&rmbadtrace)) rmbadtrace=0;

	nmap = countparval("ibstart");
	if(nmap>0) {
		ibstart = (int*) malloc(nmap*sizeof(int));
		ibyte = (int*) malloc(nmap*sizeof(int));
		itype = (int*) malloc(nmap*sizeof(int));
		obstart = (int*) malloc(nmap*sizeof(int));
		obyte = (int*) malloc(nmap*sizeof(int));
		otype = (int*) malloc(nmap*sizeof(int));
		if(getparint("ibstart",ibstart)!=nmap) err(" check ibstart");
		if(getparint("ibyte",ibyte)!=nmap) err(" check ibyte");
		if(getparint("itype",itype)!=nmap) err(" check itype");
		if(getparint("obstart",obstart)!=nmap) err(" check obstart");
		if(getparint("obyte",obyte)!=nmap) err(" check obyte");
		if(getparint("otype",otype)!=nmap) err(" check otype");
	}
    
    /* read ebcdic and binary headers */
    efread(ebcbuf, 1, EBCBYTES, ifp);
    efread((char *)&bh, 1, BNYBYTES, ifp);
    
    if (bh.format != 1)
	(over) ? warn("ignore bh.format ... continue") :
	    err("format not IBM floating point");

    if (!convert) warn(
      "assuming data is IEEE floating point, no conversion will be done");
    
    /* set nt parameter */
    if (!getparint("nt", &nt)) {
		nt = bh.hns;
		ntg = 0;
	} else {
		ntg = 1;
	}
    
    /* if needed, save ebcbuf into hfile */
    if (getparstring("hfile", &hfile)) {
	/* Open pipe to use dd to convert ebcdic to ascii */
	sprintf(cmdbuf, 
		"dd ibs=3200 of=%s conv=ascii cbs=80 count=1", hfile);
	hfp = epopen(cmdbuf, "w");
	/* Write ascii stream from buffer into pipe */
	efwrite(ebcbuf, EBCBYTES, 1, hfp);
	epclose(hfp);
    }
    
    /* save the binary file, if needed */
    if (getparstring("bfile", &bfile)) {
	/* - the binary data file */
	bfd = eopen(bfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
	/* Write binary header from bhed structure to binary file */
	ewrite(bfd, (char *)&bh, BNYBYTES);
	eclose(bfd);
    }
    
    /* convert ebcdic to ascii for output data */	
    tascii_((unsigned char*)ebcbuf, (unsigned char*)&ch, EBCBYTES, 0);
    
    if (strncmp((char*)&ch, "C 1 CLIENT",10) != 0 ) {
		memcpy((char *)&ch, "C 1 CLIENT", 10);
    }
    
    /* test if number of samples set in binary header */
    if (!bh.hns) {
	warn("samples/trace not set in binary header \n");
	if (nt == 0) 
	    warn("samples/trace in 1st trace used \n"); 
	else 
	    warn("nt in input used for samples/trace \n"); 
    }
    
    if ((nt != bh.hns) && (nt != 0)) {
	warn("samples/trace reset in binary header =%d \n",nt);	
	bh.hns = nt;
    }
    
    /* output ascii and binary headers to stdout */
    puthdr(&ch, &bh);

    nbt = 0;
    
    /* convert the traces */
    while (efread((char *)&tr, 1, HDRBYTES, ifp) && (itr < trmax)) {
	
	/* check first 10 bytes to look for ebcdic header,
	   if found, this probably indicates a tape switch */
	/*
	tascii_((unsigned char*)&tr, &hdr_buf, 10, 0); 
	if ((strncmp(hdr_buf, "C 1 CLIENT", 10) == 0) 
	    || (strncmp(hdr_buf, "C CLIENT  ", 10) == 0)
	    || (strncmp(hdr_buf, "C 1 ", 4) == 0)) { 
		fprintf(stderr," %
	    efread(tmp_buf, 1, 3600 - HDRBYTES, ifp);
	} else {
	*/
	    /* read in the trace data */
		if(tr.ns==0) tr.ns = nt;
		if(ntg==0) { 
	    	nsamp = tr.ns * 4;
		} else {
	    	nsamp = nt * 4;
		}

	    efread((char *)&tr + HDRBYTES, 1, nsamp, ifp);
	    ibt = 0;

	    /* Check bh.hns with tr.ns */
	    if (bh.hns != tr.ns) {
		
		nsflag = true;
		ibt = 1;
		nbt = nbt + 1;
		/* print warning message */
		if(verbose==1 || nbt<1000) warn("discrepant tr.ns = %d with bh.hns = %d\n"
		     "\t... noted on trace %d", tr.ns, bh.hns, itr + 1);
		
		/* if user wants to leave things the way they are (nt=0) */
		/* otherwise, modify number of samples per trace */
		if (nt != 0) {
		    if (nt > tr.ns) {
			for (i = tr.ns; i < nt; i++)
			    tr.data[i] = 0.0;
		    }
		    nsamp = nt * 4;
		    tr.ns = nt;
		}
	    }
	    
	    /* convert and write desired traces */
	    if (++itr >= trmin) {
		/* Convert IBM floats to native floats */
		if (convert)
                   conv_float((char *)tr.data, (char *)tr.data, tr.ns, 1);
		

		/* write the trace to disk */
		if(nmap==0) {
			/* clean up trace header beyond 180 bytes */
			if (clean == 1) bzero((char *)&tr + 180, 60);
			if (ibt==0 || rmbadtrace==0) 
			efwrite((char *)&tr, 1, nsamp + HDRBYTES, stdout);
		} else {
			bcopy((char*)&tr,(char*)&tro,nsamp+HDRBYTES);
			for(imap=0;imap<nmap;imap++) {
				ibs = ibstart[imap];
				iby = ibyte[imap];
				ity = itype[imap];
				obs = obstart[imap];
				oby = obyte[imap];
				oty = otype[imap];

/*
			fprintf(stderr,"ibs=%d iby=%d ity=%d obs=%d oby=%d oty=%d \n",
							ibs,iby,ity,obs,oby,oty);
*/

				if(iby==oby && ity==oty && ity!=1 ) {
					bcopy((char*)&tr+ibs-1,(char*)&tro+obs-1,iby);
				} else {
					if(ity==1) {
						conv_float((char*)&tr+ibs-1,(char*)&tmp,1,1);
					} else {
						if(iby==2) {
							bcopy((char*)&tr+ibs-1,(char*)&itmp2,iby);
							tmp = itmp2;
						} else if(iby==4) {
							bcopy((char*)&tr+ibs-1,(char*)&itmp4,iby);
							tmp = itmp4;
						}
					}
					if(oty==1) {
						bcopy((char*)&tmp,(char*)&tro+obs-1,oby);
					} else {
						tmp = tmp + 0.5;
						if(oby==2) {
							itmp2 = (short) tmp;
							bcopy((char*)&itmp2,(char*)&tro+obs-1,oby);
						} else {
							itmp4 = (int) tmp;
							bcopy((char*)&itmp4,(char*)&tro+obs-1,oby);
						}
					}
				}
			}
			/* clean up trace header beyond 180 bytes */
			if (clean == 1) bzero((char *)&tro + 180, 60);
			if (ibt==0 || rmbadtrace==0)
			efwrite((char *)&tro, 1, nsamp + HDRBYTES, stdout);
		}
		
		/* echo under verbose option */
		if (verbose && itr % 20 == 0)
		    warn(" %d traces from tape", itr);
	    }
	/*
	} 
	*/
    } /* while loop */
    
    /* re-iterate error in case not seen during run */
    if ((nsflag) && (nt != 0))
	warn("discrepancy found in header and trace ns values\n"
	     "\theader value (%d) was used to extract traces", bh.hns);
    
    /* clean up */
    efclose(ifp);

	if(nmap>0) {
		free(ibstart);
		free(ibyte);
		free(itype);
		free(obstart);
		free(obyte);
		free(otype);
	}
    
    return EXIT_SUCCESS;
}
示例#23
0
int main(int argc, char **argv)
{
	char *plotcmd;		/* build pswigb command for popen	*/
	float *trbuf;		/* trace buffer				*/
	FILE *plotfp;		/* fp for plot data			*/
	int nt;			/* number of samples on trace	  	*/
	int ntr;		/* number of traces			*/
	int verbose;		/* verbose flag				*/
	float d1;		/* time/depth sample rate		*/
	float d2;		/* trace/dx sample rate			*/
	float f1;		/* tmin/zmin			   	*/
	float f2;		/* tracemin/xmin			*/
	cwp_Bool seismic;	/* is this seismic data?		*/
	cwp_Bool have_ntr=cwp_false;/* is ntr known from header or user?	*/
	char *tmpdir;		/* directory path for tmp files		*/
	cwp_Bool istmpdir=cwp_false;/* true for user given path		*/

	char *cwproot;		/* value of CWPROOT environment variable*/
	char *bindir;		/* directory path for tmp files		*/

	/* Support for irregularly spaced data */
	cwp_String key;		/* header key word with x2 information  */
	cwp_String type1=NULL;	/* ... its type				*/
	int index1=0;		/* ... its index			*/
	Value val;		/* value of key				*/
	Value scale;		/* Value of scaler			*/
	cwp_String type2=NULL;	/* ... its type				*/
	int index2=0;		/* ... its index			*/
	cwp_Bool isDepth=cwp_false;	/* Is this key a type of depth?		*/
	cwp_Bool isCoord=cwp_false;	/* Is this key a type of coordinate?	*/
	cwp_Bool irregular=cwp_false;  /* if true, reading x2 from header	*/ 
	cwp_String x2string;	/* string of x2 values			*/
	off_t x2len;		/* ... its length 			*/
	cwp_String style;	/* style parameter			*/


	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);
	
	/* Get info from first trace */
	if (!gettr(&tr)) err("can't get first trace");
	seismic = ISSEISMIC(tr.trid); 
	nt = tr.ns;
	ntr = tr.ntr;
	if (ntr) have_ntr = cwp_true; 

	if (!getparint("verbose", &verbose))    verbose=0;
	if (!getparfloat("d1", &d1)) {
		if      (tr.d1)  d1 = tr.d1;
		else if (tr.dt)  d1 = ((double) tr.dt)/1000000.0;
		else {
			if (seismic) {
				d1 = 0.004;
				warn("tr.dt not set, assuming dt=0.004");
			} else { /* non-seismic data */
				d1 = 1.0;
				warn("tr.d1 not set, assuming d1=1.0");
			}
		}
	}


	if (!getparfloat("f1", &f1)) {
		if      (tr.f1)     f1 = tr.f1;
		else if (tr.delrt)  f1 = (float) tr.delrt/1000.0;
		else		f1 = 0.0;
	}

	/* Get or set ntr */
	if (getparint("n2", &ntr) || getparint("ntr", &ntr)) have_ntr = cwp_true;
	if (!getparfloat("d2", &d2)) d2 = (tr.d2) ? tr.d2 : 1.0;


	if (!getparfloat("f2", &f2)) {
		if	(tr.f2)	f2 = tr.f2;
		else if (tr.tracr)  f2 = (float) tr.tracr;
		else if (tr.tracl)  f2 = (float) tr.tracl;
		else if (seismic)   f2 = 1.0;
		else		    f2 = 0.0;
	}

	if (!getparstring("style", &style)) style = "seismic";
	 	
	if (getparstring("key", &key)) {
		type1 = hdtype(key);
		if ( (index1 = getindex(key)) == -1 )
			err("%s: keyword not in segy.h: '%s'", __FILE__, key);
		irregular = cwp_true;
		isDepth = IS_DEPTH(key);
		isCoord = IS_COORD(key);
		if (isDepth) {
		   index2 = getindex("scalel");
		   type2 = hdtype("scalel");
		} else if (isCoord) {
		   index2 = getindex("scalco");
		   type2 = hdtype("scalco");
		}
	}


	/* Look for user-supplied tmpdir */
	if (!getparstring("tmpdir",&tmpdir) &&
	    !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
	if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
		err("you can't write in %s (or it doesn't exist)", tmpdir);

	/* See if CWPBIN environment variable is not set */
	if (!(bindir = getenv("CWPBIN"))) { /* construct bindir from CWPROOT */

		bindir = (char *) emalloc(BUFSIZ);

		/* Get value of CWPROOT environment variable */
		if (!(cwproot = getenv("CWPROOT"))) cwproot ="" ;
		if (STREQ(cwproot, "")) {
			warn("CWPROOT environment variable is not set! ");
			err("Set CWPROOT in shell environment as per instructions in CWP/SU Installation README files");
		}
		/* then bindir = $CWPROOT/bin */
		sprintf(bindir, "%s/bin", cwproot);
	}
	strcat(bindir,"/");   /* put / at the end of bindir */


	/* Allocate trace buffer */
	trbuf = ealloc1float(nt);


	if (!have_ntr || irregular ) { /* count traces */
		if (verbose) {
			if (irregular) {
				warn("trace spacing from header field %s",key);
				warn("... getting positions");

			} else {
				warn("n2 not getparred and "
				     "ntr header field not set");
				warn("....  counting traces");
			}
		}

		/* Create temporary "file" to hold data */
		if (STREQ(tmpdir,"")) {
			datafp = etmpfile();
			if (irregular) x2fp = etmpfile();
			if (verbose) warn("using tmpfile() call");
		} else { /* user-supplied tmpdir */
			char directory[BUFSIZ];
			strcpy(directory, tmpdir);
			strcpy(datafile, temporary_filename(directory));
			strcpy(x2file, temporary_filename(directory));
			/* Handle user interrupts */
			signal(SIGINT, (void (*) (int)) closefiles);
			signal(SIGQUIT, (void (*) (int)) closefiles);
			signal(SIGHUP,  (void (*) (int)) closefiles);
			signal(SIGTERM, (void (*) (int)) closefiles);
			datafp = efopen(datafile, "w+");
			if (irregular) x2fp = efopen(x2file, "w+");
			istmpdir=cwp_true;		
			if (verbose)
			      warn("putting temporary files in %s", directory);
		}

		/* Loop over input data and read to temporary file */
		ntr = 0;
		if(irregular ) {
		     float x,xmin=FLT_MAX,xmax=-FLT_MAX;

		     fprintf(x2fp,"x2=");
		     do {
			if(ntr) fprintf(x2fp,",");
			++ntr;
			gethval(&tr,index1,&val);
			if (isDepth || isCoord) {
			   gethval(&tr,index2,&scale);
			   x = (float) (vtod(type1,val) *
				 pow(10.0,vtod(type2,scale)));
			} else
			   x = vtof(type1,val);
			fprintf(x2fp,"%g",x);
			xmin = MIN(xmin,x);
			xmax = MAX(xmax,x);
			if (isDepth && STREQ(style,"vsp")) {
				int i;
				for (i = 0; i < nt; ++i) tr.data[i] *= -1.0;
			}
			efwrite(tr.data, FSIZE, nt, datafp);
		     } while (gettr(&tr));

		     /* Flip vertical axis if style = vsp */
		     if (isDepth && STREQ(style,"vsp")) {
			fprintf(x2fp," x2beg=%g x2end=%g",xmax,xmin);
			style = "normal";
		     }

		     if(xmin==xmax) {
			warn("values in header %s all equal,",key);
			warn("using f2=%f d2=%f",f2,d2);
			irregular=cwp_false;
			have_ntr=cwp_false;
			efclose(x2fp);
			if (istmpdir) eremove(x2file);
		     }

		} else {
			do {
				++ntr;
				efwrite(tr.data, FSIZE, nt, datafp);
			} while (gettr(&tr));
			/* Save naive user */
			if (STREQ(style,"vsp")) {
				style = "normal";
				warn("style=vsp requires key= to be set");
			}
		}


	}

	/* Set up pswigb command line */
	if (irregular ) {
		x2len = (off_t) eftell( x2fp );
		x2string = (char *) emalloc( ++x2len );
		rewind(x2fp);
		fread(x2string,sizeof(char),x2len,x2fp);
		plotcmd = (char *) emalloc(x2len+BUFSIZ);
		if (STREQ(style,"vsp")) {
			style = "normal";
		}
		sprintf(plotcmd, "%spswigb n1=%d d1=%f f1=%f %s style=%s", bindir,
			   nt, d1, f1, x2string, style);
		free(x2string);
	} else {
		if (STREQ(style,"vsp")) {
			style = "normal";
		}
		plotcmd = (char *) emalloc(BUFSIZ);
		sprintf(plotcmd,
			"%spswigb n1=%d n2=%d d1=%f d2=%f f1=%f f2=%f style=%s", bindir,
			   nt, ntr, d1, d2, f1, f2, style);
	}


	for (--argc, ++argv; argc; --argc, ++argv) {
		if (strncmp(*argv, "d1=", 3) && /* skip those already set */
		    strncmp(*argv, "d2=", 3) &&
		    strncmp(*argv, "f1=", 3) &&
		    strncmp(*argv, "f2=", 3) &&
		    strncmp(*argv, "style=", 6)){
		    
			strcat(plotcmd, " ");   /* put a space between args */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
			strcat(plotcmd, *argv); /* add the arg */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
		}
	}


	/* Open pipe to pswigb and send the traces */
	plotfp = epopen(plotcmd, "w");
	free(plotcmd);

	if (!have_ntr || irregular) { /* send out stored traces one by one */
		rewind(datafp);
		{ register int itr;
			for (itr = 0; itr < ntr; ++itr) {
				efread (trbuf, FSIZE, nt, datafp);
				efwrite(trbuf, FSIZE, nt, plotfp);
			}
		}
	} else { /* just pump out traces and let pswigb do the work */
		do {
			efwrite(tr.data, FSIZE, nt, plotfp);
		} while (gettr(&tr));
	}


	/* Clean up */
	epclose(plotfp);
	if (!have_ntr) {
		efclose(datafp);
		if (istmpdir) eremove(datafile);
	}
	if (irregular) {
		efclose(x2fp);
		if (istmpdir) eremove(x2file);
	}

	return EXIT_SUCCESS;
}
示例#24
0
文件: fputtr.c 项目: 1014511134/src
void fputtr_internal(FILE *fp, segy *tp, cwp_Bool fixed_length)
{
	/* search linked list for possible alternative */
	if(fp != lastfp)  searchlist(fp);

	if (infoptr == ((struct outsegyinfo *) NULL)) {
		/* initialize new segy output stream */

		/* allocate new segy output information table */
		*oldinfoptr = (struct outsegyinfo *)
			malloc(sizeof(struct outsegyinfo));
		infoptr = *oldinfoptr;
		infoptr->nextinfo = (struct outsegyinfo *) NULL;
		/* save FILE * ptr */
		infoptr->outfp = fp;
		infoptr->itr = 0;

		switch (infoptr->ftype = filestat(fileno(fp))) {
		case DIRECTORY:
			suerr("%s: segy output can't be a directory", __FILE__);
		case TTY:
			suerr("%s: segy output can't be tty", __FILE__);
		default:
			/* the rest are ok */
		break;
		}

		/* Sanity check the segy header */
		infoptr->nsfirst = tp->ns;
		if (infoptr->nsfirst > SU_NFLTS)
			suerr("%s: unable to handle %d > %d samples per trace",
			    __FILE__, infoptr->nsfirst, SU_NFLTS);
		switch(tp->trid) {
		case CHARPACK:
			infoptr->bytesper = sizeof(char); break;
		case SHORTPACK:
			infoptr->bytesper = 2*sizeof(char); break;
		default:
			infoptr->bytesper = sizeof(float); break;
		}

/*--------------------------------------------------------------------*\
   Write out a line header if it has been set as the default or has 
   requested on the caommandline.  Commandline takes precedence over
   the default in all cases.

   Reginald H. Beardsley                            [email protected]
\*--------------------------------------------------------------------*/
              
/* commented out 15.05.09 WWS 

                getparint( "lheader" ,&out_line_hdr );

                if( out_line_hdr ){

                   if( in_line_hdr ){
                     (void) efwrite(&(su_text_hdr[0]), 1 ,3200 
                                    ,infoptr->outfp);

                   }else{
                     memset( su_text_hdr ,0 ,sizeof(su_text_hdr) );
                     sprintf( hdr_str ,"%-80s" 
                            ,"C 1 CLIENT CWP/SU default text header " );
                     strncat( su_text_hdr ,hdr_str ,80 );
                     for( i=1; i<40; i++ ){
                        sprintf( hdr_str ,"%-80s" ,"C" );
                        strncat( su_text_hdr ,hdr_str ,80 );
                     }
                     (void) efwrite(&(su_text_hdr[0]), 1 ,3200 
                                    ,infoptr->outfp);


                   }

                   memset( &su_binary_hdr ,0 ,sizeof(su_binary_hdr) );
                   su_binary_hdr.format = 1;
                   su_binary_hdr.hns = tp->ns;
                   su_binary_hdr.hdt = tp->dt;
 
 
                  (void) efwrite(&su_binary_hdr, 1
                              ,sizeof(su_binary_hdr), infoptr->outfp);
                }
*/
		
	}

	if (tp->ns != infoptr->nsfirst && fixed_length)
		suerr("%s: on trace #%ld, number of samples in header (%d) "
		    "differs from number for first trace (%d)", 
		    __FILE__, (infoptr->itr)+1, tp->ns, infoptr->nsfirst);
	

	(void) efwrite(tp, 1,HDRBYTES, infoptr->outfp);
	datawrite(tp, infoptr, fixed_length);
	
	++infoptr->itr;
	lastfp = infoptr->outfp;
}
示例#25
0
int main(int argc, char **argv)      /*argc, argv - the arguments to the main() function*/
{ 
int nt;                              /*number of time samples*/
int nz;			             /*number of migrated depth samples*/
int nx;                              /*number of midpoints (traces)*/
int ix;
int iz;

float dt;                            /*time sampling interval*/                
float dx;                            /*spatial sampling interval*/
float dz;                            /*migrated depth sampling interval*/           
float **data;                        /*input seismic data*/
complex **image;                     /*migrated image*/      
float **rimage;                      /*migrated image*/ 
float **v;                           /*velocity model*/
FILE *vfp;

char *vfile="";                      /*name of velocity file*/
int verbose=1;
char *tmpdir;		             /* directory path for tmp files*/
cwp_Bool istmpdir=cwp_false;         /* true for user-given path*/

/******************************* Intialize *********************************************/
initargs(argc,argv);
requestdoc(1);

/********************************* Get parameters **************************************/
/*get info from first trace*/
if (!gettr(&tr))  err("can't get first trace");  /*fgettr: get a fixed-length segy trace from a file by file pointer*/
nt = tr.ns;                         /*nt*/       /*gettr: macro using fgettr to get a trace from stdin*/

if (!getparfloat("dt", &dt)) {      /*dt*/
if (tr.dt) { 
dt = ((double) tr.dt)/1000000.0;
} 
else {err("dt is not set");}
}

if (!getparfloat("dx", &dx)) {       /*dx*/
if (tr.d2) {
dx = tr.d2;
} 
else {
err("dx is not set");
}
}

/*get optional parameters*/
if (!getparint("nz",&nz)) err("nz must be specified"); 
if (!getparfloat("dz",&dz)) err("dz must be specified");
if (!getparstring("vfile", &vfile)) err("velocity file must be specified");
if (!getparint("verbose", &verbose)) verbose = 0;
/****************************************************************************************/

/* Look for user-supplied tmpdir */
if (!getparstring("tmpdir",&tmpdir) &&
 !(tmpdir = getenv("CWP_TMPDIR"))) tmpdir="";
if (!STREQ(tmpdir, "") && access(tmpdir, WRITE_OK))
err("you can't write in %s (or it doesn't exist)", tmpdir);
checkpars();

/**************************** Count trace number nx ******************************/
/* store traces and headers in tempfiles while getting a count */
	if (STREQ(tmpdir,"")) {
		tracefp = etmpfile();
		headerfp = etmpfile();
		if (verbose) warn("using tmpfile() call");
	} 
     else { /* user-supplied tmpdir */
		char directory[BUFSIZ];
		strcpy(directory, tmpdir);
		strcpy(tracefile, temporary_filename(directory));
		strcpy(headerfile, temporary_filename(directory));
		/* Trap signals so can remove temp files */
		signal(SIGINT,  (void (*) (int)) closefiles);
		signal(SIGQUIT, (void (*) (int)) closefiles);
		signal(SIGHUP,  (void (*) (int)) closefiles);
		signal(SIGTERM, (void (*) (int)) closefiles);
		tracefp = efopen(tracefile, "w+");
		headerfp = efopen(headerfile, "w+");
      		istmpdir=cwp_true;		
		if (verbose) warn("putting temporary files in %s", directory);
	}

	nx = 0;
	do {
		 ++nx;                                   /*get the number of traces nx*/
		efwrite(&tr,HDRBYTES,1,headerfp);
		efwrite(tr.data, FSIZE, nt, tracefp);
	} while (gettr(&tr));

	erewind(tracefp);                    /*Set position of stream to the beginning*/
	erewind(headerfp);

/******************************************************************************************/

/*allocate memory*/
data = alloc2float(nt,nx);                   /*2D array nx by nt*/
image = alloc2complex(nz,nx);                /*2D array nx by nz*/
rimage = alloc2float(nz,nx);                 /*2D array nx by nz*/
v= alloc2float(nz,nx);                       /*2D array, in Fortran the velocity model is nz by nx 2D array*/ 
                                             /*in binary, it is actually 1D*/

/* load traces into the zero-offset array and close tmpfile */
efread(*data, FSIZE, nt*nx, tracefp);        /*read traces to data*/
efclose(tracefp);                 

/*load velicoty file*/
vfp=efopen(vfile,"r");	
efread(v[0],FSIZE,nz*nx,vfp);                    /*load velocity*/
efclose(vfp);			

/***********************finish reading data*************************************************/
/* call pspi migration function*/
pspimig(data,image,v,nt,nx,nz,dt,dx,dz);

/*get real part of image*/
for (iz=0;iz<nz;iz++){
for (ix=0;ix<nx;ix++){
rimage[ix][iz] = image[ix][iz].r;
}
}

/* restore header fields and write output */
for (ix=0; ix<nx; ix++) {
efread(&tr,HDRBYTES,1,headerfp);
tr.ns = nz;
tr.d1 = dz;
memcpy( (void *) tr.data, (const void *) rimage[ix],nz*FSIZE);
puttr(&tr);
}
	
/* Clean up */
efclose(headerfp);
if (istmpdir) eremove(headerfile);
if (istmpdir) eremove(tracefile);
return(CWP_Exit());	
}
示例#26
0
main(int argc, char **argv)
{
	int nt,nx;		/* numbers of samples			*/
	float dt,dx;		/* sampling intervals			*/
	float d1,d2;		/* output intervals in F, K		*/
	float f1,f2;		/* output first samples in F, K		*/
	int it,ix;		/* sample indices			*/
	int ntfft,nxfft;	/* dimensions after padding for FFT	*/
	int nF,nK;		/* transform (output) dimensions	*/
	int iF,iK;		/* transform sample indices		*/
	register complex **ct;	/* complex FFT workspace		*/
	register float **rt;	/* float FFT workspace			*/
	FILE *tracefp;		/* temp file to hold traces		*/


	/* Hook up getpar to handle the parameters */
	initargs(argc,argv);
	askdoc(1);


	/* Get info from first trace */ 
	if (!gettr(&intrace))  err("can't get first trace");
	nt = intrace.ns;


	/* dt is used only to set output header value d1 */
	if (!getparfloat("dt", &dt)) {
		if (intrace.dt) { /* is dt field set? */
			dt = (float) intrace.dt / 1000000.0;
		} else { /* dt not set, assume 4 ms */
			dt = 0.004;
			warn("tr.dt not set, assuming dt=0.004");
		}
	}
	if (!getparfloat("dx",&dx)) {
		if (intrace.d2) { /* is d2 field set? */
			dx = intrace.d2;
		} else {
			dx = 1.0;
			warn("tr.d2 not set, assuming d2=1.0");
		}
	}


	/* Store traces in tmpfile while getting a count */
	/*tracefp = etmpfile();*/
	tracefp = etempfile(NULL);
	nx = 0;
	do { 
		++nx;
		efwrite(intrace.data, FSIZE, nt, tracefp);
	} while (gettr(&intrace));


	/* Determine lengths for prime-factor FFTs */
	ntfft = npfar(nt);
	nxfft = npfa(nx);
	if (ntfft >= MIN(SU_NFLTS, PFA_MAX)) err("Padded nt=%d--too big",ntfft);
	if (nxfft >= MIN(SU_NFLTS, PFA_MAX)) err("Padded nx=%d--too big",nxfft);


	/* Determine output header values */
	d1 = 1.0/(ntfft*dt);
	d2 = 1.0/(nxfft*dx);
	f1 = 0.0;
	f2 = -1.0/(2*dx);


	/* Determine complex transform sizes */
	nF = ntfft/2+1;
	nK = nxfft;


	/* Allocate space */
	ct = alloc2complex(nF, nK);
	rt = alloc2float(ntfft, nxfft);


	/* Load traces into fft arrays and close tmpfile */
	rewind(tracefp);
	for (ix=0; ix<nx; ++ix) {

		efread(rt[ix], FSIZE, nt, tracefp);

                /* if ix odd, negate to center transform of dimension 2 */
                if (ISODD(ix))
			for (it=0; it<nt; ++it)  rt[ix][it] = -rt[ix][it];

		/* pad dimension 1 with zeros */
		for (it=nt; it<ntfft; ++it)  rt[ix][it] = 0.0;
	}
	efclose(tracefp);


	/* Pad dimension 2 with zeros */
	for (ix=nx; ix<nxfft; ++ix)
		for (it=0; it<ntfft; ++it)  rt[ix][it] = 0.0;

	
	/* Fourier transform dimension 1 */
	pfa2rc(1,1,ntfft,nx,rt[0],ct[0]);
	

	/* Fourier transform dimension 2 */
	pfa2cc(-1,2,nF,nxfft,ct[0]);
	

	/* Compute and output amplitude spectrum */
	for (iK=0; iK<nK; ++iK) {
		for (iF=0; iF<nF; ++iF)  outtrace.data[iF] = fcabs(ct[iK][iF]);

		/* set header values */
		outtrace.tracl = iK + 1;
		outtrace.ns = nF;
		outtrace.dt = 0;  /* d1 is now the relevant step size */
		outtrace.trid = KOMEGA;
		outtrace.d1 = d1;
		outtrace.f1 = f1;
		outtrace.d2 = d2;
		outtrace.f2 = f2;

		puttr(&outtrace);
	}
}
示例#27
0
main(int argc, char **argv)
{
	string head;	/* name of file holding headers		*/
	FILE *headfp;	/* ... its file pointer			*/
	string outpar;	/* name of file holding output parfile	*/
	FILE *outparfp;	/* ... its file pointer			*/
	int ns;		/* number of data samples on the segys	*/
	int nsbytes;	/* ... in bytes				*/
	int ftn;	/* fortran flag				*/
	int ntr = 0;	/* number of traces written		*/
	FILE *infp=stdin, *outfp=stdout;


	/* Initialize */
	initargs(argc, argv);
	askdoc(1);


	switch(filestat(STDOUT)) {
	case BADFILETYPE:
		warn("stdout is illegal filetype");
		selfdoc();
	break;
	case TTY:
		warn("stdout can't be tty");
		selfdoc();
	break;
	}

	/* Get parameters */
	if (!getparstring("head"  , &head))	head   = "/dev/null";
	if (!getparstring("outpar", &outpar))	outpar = "/dev/tty" ;
	if (!getparint   ("ftn"   , &ftn))	ftn = 0;
	if (ftn != 0 && ftn != 1)  err("ftn=%d must be 0 or 1", ftn);


	/* Open files to save headers and parameters */
	headfp = efopen(head, "w");
	if( (outparfp = fopen(outpar,"w"))==NULL ) outparfp = stderr;

	/*
	outparfp = efopen(outpar, "w");
	*/

	fseek2g(infp,0,1);
        fseek2g(outfp,0,1);

	/* read id header and save in head */
	gethdr(&ch,&bh);
	fputhdr(headfp,&ch,&bh);

	/* Get info from first trace */
	if (!gettr(&tr)) err("can't get first trace");
	ns = tr.ns;
	nsbytes = ns * FSIZE;


	/* Write the data portion of the records--if the ftn	*/
	/* option is selected, write an int before and after	*/
	/* each trace giving the length of the trace in bytes	*/
	/* as per the Fortran unformatted record format.	*/
	do {

		if (ftn) efwrite(&nsbytes, ISIZE, 1, stdout);
		efwrite(tr.data, FSIZE, ns, stdout);
		if (ftn) efwrite(&nsbytes, ISIZE, 1, stdout);

		efwrite(&tr, 1, HDRBYTES, headfp);

		++ntr;

	} while (gettr(&tr));

	/* Make par file for headerless file */
	fprintf(outparfp, "n1=%d n2=%d d1=%f\n", tr.ns, ntr, 
		(float)tr.dt/1000000.0);


	return EXIT_SUCCESS;
}
示例#28
0
void slopefilter (int nslopes, float slopes[], float amps[], float bias,
	int nt, float dt, int nx, float dx, FILE *tracefp)
/******************************************************************************
apply slope filter in frequency-wavenumber domain
*******************************************************************************
Input:
nslopes		number of slopes (and amplitudes) specified
slopes		slopes at which amplitudes are specified (see notes below)
amps		amplitudes corresponding to slopes (see notes below)
bias		linear moveout slope before and after filtering
nt		number of time samples
dt		time sampling interval
nx		number of traces
dx		trace space (spatial sampling interval)
tracefp		file pointer to data to be filtered

Output:
tracefp		file pointer to filtered data
*******************************************************************************
Notes:
Linear interpolation and constant extrapolation are used to
determine amplitudes for slopes that are not specified.
******************************************************************************/
{
	int ntfft;		/* nt after padding for FFT */
	int nxfft;		/* nx after padding for FFT */
	float sfft;		/* scale factor for FFT */
	int nw;			/* number of frequencies */
	float dw;		/* frequency sampling interval */
	float fw;		/* first frequency */
	int nk;			/* number of wavenumbers */
	float dk;		/* wavenumber sampling interval */
	float w,k;		/* frequency and wavenumber */
	int it,ix,iw,ik;	/* sample indices */
	float slope,amp;	/* slope and amplitude for particular w,k */
	complex **cpfft;	/* complex FFT workspace */
	float **pfft;		/* float FFT workspace */
	float phase;		/* phase shift for bias */
	complex cshift;		/* complex phase shifter for bias */

	/* determine lengths and scale factors for prime-factor FFTs */
	ntfft = npfar(nt);
	nxfft = npfa(nx);
	sfft = 1.0/(ntfft*nxfft);
	
	/* determine frequency and wavenumber sampling */
	nw = ntfft/2+1;
	dw = 2.0*PI/(ntfft*dt);
	fw = 0.000001*dw; /* non-zero to avoid divide by zero w */
	nk = nxfft;
	dk = 2.0*PI/(nxfft*dx);

	/* allocate real and complex workspace for FFTs */
	cpfft = alloc2complex(nw,nk);
	pfft = alloc2float(ntfft,nxfft);

	/* copy data from input to FFT array and pad with zeros */
	rewind(tracefp);
	for (ix=0; ix<nx; ix++) {
		efread(pfft[ix], FSIZE, nt, tracefp);
		for (it=nt; it<ntfft; it++)
			pfft[ix][it] = 0.0;
	}
	for (ix=nx; ix<nxfft; ix++)
		for (it=0; it<ntfft; it++)
			pfft[ix][it] = 0.0;
	
	/* Fourier transform t to w */
	pfa2rc(1,1,ntfft,nx,pfft[0],cpfft[0]);
	
	/* do linear moveout bias via phase shift */
	for (ix=0; ix<nx; ix++) {
		for (iw=0,w=0.0; iw<nw; iw++,w+=dw) {
			phase = -ix*dx*w*bias;
			cshift = cmplx(cos(phase),sin(phase));
			cpfft[ix][iw] = cmul(cpfft[ix][iw],cshift);
		}
	}
	
	/* Fourier transform x to k */
	pfa2cc(-1,2,nw,nxfft,cpfft[0]);
	
	/* loop over wavenumbers */
	for (ik=0; ik<nk; ik++) {
	
		/* determine wavenumber */
		k = (ik<=nk/2) ? ik*dk : (ik-nk)*dk;
		
		/* loop over frequencies */
		for (iw=0,w=fw; iw<nw; iw++,w+=dw) {
		
			/* determine biased slope */
			slope = k/w+bias;
			
			/* linearly interpolate to find amplitude */
			intlin(nslopes,slopes,amps,amps[0],amps[nslopes-1],
				1,&slope,&amp);
			
			/* include fft scaling */
			amp *= sfft;
			
			/* filter real and imaginary parts */
			cpfft[ik][iw].r *= amp;
			cpfft[ik][iw].i *= amp;
		}
	}

	/* Fourier transform k to x */
	pfa2cc(1,2,nw,nxfft,cpfft[0]);

	/* undo linear moveout bias via phase shift */
	for (ix=0; ix<nx; ix++) {
		for (iw=0,w=0.0; iw<nw; iw++,w+=dw) {
			phase = ix*dx*w*bias;
			cshift = cmplx(cos(phase),sin(phase));
			cpfft[ix][iw] = cmul(cpfft[ix][iw],cshift);
		}
	}

	/* Fourier transform w to t */
	pfa2cr(-1,1,ntfft,nx,cpfft[0],pfft[0]);
	
	/* copy filtered data from FFT array to output */
	rewind(tracefp);
	for (ix=0; ix<nx; ix++)
		efwrite(pfft[ix], FSIZE, nt, tracefp);

	/* free workspace */
	free2complex(cpfft);
	free2float(pfft);
}
示例#29
0
int
main(int argc,char **argv)
{
 
	int  n1, n2, n3, depth, time, verbose, iter, slowness;
	float r1, r2, r3, d1, d2, d3, *wl, ***vel, mu, vminc, vmaxc;
 
	FILE *invp=stdin, *outvp=stdout;


	/* initialization */
	initargs(argc,argv) ;
	requestdoc(0);


	/*-----------get required parameters-----------*/
	if( !getparint("n1",&n1) ) n1 = 0 ;
	if( n1 <= 0 ) err("sample number of 1st dimension invalid" ) ;
	if( !getparint("n2",&n2) ) n2 = 0 ;
	if( n2 <= 0 ) err("sample number of 2nd dimension invalid" ) ;
	if( !getparint("n3",&n3) ) n3 = 0 ;
	if( n3 <= 0 ) err("sample number of 3rd dimension invalid" ) ;


	/*-----------get optional parameters-----------*/

	/* sample intervals */
	if( !getparfloat("d1",&d1) ) d1 = 1.0 ;
	if( !getparfloat("d2",&d2) ) d2 = 1.0 ;
	if( !getparfloat("d3",&d3) ) d3 = 1.0 ;

	/*   smoothing parameters    */
	if( !getparfloat("r1",&r1) || n1<4) r1 = 0. ;
	if( !getparfloat("r2",&r2) || n2<4) r2 = 0. ;
	if( !getparfloat("r3",&r3) || n3<4) r3 = 0. ;

/*	 scale smoothing parameters	*/
	r1 = (d1>0)?r1/d1:0;
	r2 = (d2>0)?r2/d2:0;
	r3 = (d3>0)?r3/d3:0;
	r1 = 0.5*r1*r1 ;
	r2 = 0.5*r2*r2 ;
	r3 = 0.5*r3*r3 ;
  
	/*   get iteration number for smoothing operator */
	if(!getparint("iter", &iter)) iter = 2;
	if(iter<=0 || iter>3) err("\t iter must be between 1 and 3!\n");

	/*   description for vertical dimension    */
	if(!getparint("time",&time )) time = 0;
	if(!getparint("depth",&depth) ) depth = 1;
	if(time) depth = time;

 
	/*   relative weight at bottom     */
	if(!getparfloat("mu",&mu) ) mu = 1.0;
	if(mu<1) err("mu must not be less than 1 \n");

	/*   smoothing on velocity or slowness     */
	if(!getparint("slowness",&slowness) ) slowness = 0;

	/*   clips of velocity before smoothing     */
	if(!getparfloat("vminc",&vminc) ) vminc = 0;
	if(!getparfloat("vmaxc",&vmaxc) ) vmaxc = 99999;

     /*   allocate input file    */
	vel  = alloc3float(n1,n2,n3) ;
	wl = alloc1float(4);

	/*   read input velocity file     */
	efread((char *)vel[0][0],sizeof(float),n1*n2*n3,invp);
 
	/*   perform smoothing operation    */
	vsm3d(vel,n3,n2,n1,iter,depth,r3,r2,r1,mu,slowness,vminc,vmaxc); 
 
	/*   write output velocity file     */
	efwrite((char *)vel[0][0],sizeof(float),n1*n2*n3,outvp);  


	if(!getparint("verbose",&verbose)) verbose = 0;
	if(verbose) {
		wavel(n1,n2,n3,d1,d2,d3,time,wl,vel);
 		fprintf(stderr,"minimum wavelengths of smoothed velocity:\n");
		fprintf(stderr,"\tlambda1 = %g,\n", wl[1]);
		fprintf(stderr,"\tlambda2 = %g,\n", wl[2]);
		fprintf(stderr,"\tlambda3 = %g,\n", wl[3]);
		fprintf(stderr,"\tlambda = %g,\n", wl[0]);
  	}
        checkpars();

	/*   close input and output files    */
	efclose(invp) ;
	efclose(outvp) ; 

	return(CWP_Exit());
}
示例#30
0
void JE_saveConfiguration( void )
{
#ifdef TARGET_UNIX
	if (getenv("HOME"))
	{
		char dir[1000];
		snprintf(dir, sizeof(dir), "%s/.opentyrian", getenv("HOME"));
		mkdir(dir, 0755);
	}
#endif /* HOME */
	
	FILE *f;
	JE_byte *p;
	int z;

	p = saveTemp;
	for (z = 0; z < SAVE_FILES_NUM; z++)
	{
		JE_SaveFileType tempSaveFile;
		memcpy(&tempSaveFile, &saveFiles[z], sizeof(tempSaveFile));
		
		tempSaveFile.encode = SDL_SwapLE16(tempSaveFile.encode);
		memcpy(p, &tempSaveFile.encode, sizeof(JE_word)); p += 2;
		
		tempSaveFile.level = SDL_SwapLE16(tempSaveFile.level);
		memcpy(p, &tempSaveFile.level, sizeof(JE_word)); p += 2;
		
		memcpy(p, &tempSaveFile.items, sizeof(JE_PItemsType)); p += sizeof(JE_PItemsType);
		
		tempSaveFile.score = SDL_SwapLE32(tempSaveFile.score);
		memcpy(p, &tempSaveFile.score, sizeof(JE_longint)); p += 4;
		
		tempSaveFile.score2 = SDL_SwapLE32(tempSaveFile.score2);
		memcpy(p, &tempSaveFile.score2, sizeof(JE_longint)); p += 4;
		
		/* SYN: Pascal strings are prefixed by a byte holding the length! */
		memset(p, 0, sizeof(tempSaveFile.levelName));
		*p = strlen(tempSaveFile.levelName);
		memcpy(&p[1], &tempSaveFile.levelName, *p);
		p += 10;
		
		/* This was a BYTE array, not a STRING, in the original. Go fig. */
		memcpy(p, &tempSaveFile.name, 14);
		p += 14;
		
		memcpy(p, &tempSaveFile.cubes, sizeof(JE_byte)); p++;
		memcpy(p, &tempSaveFile.power, sizeof(JE_byte) * 2); p += 2;
		memcpy(p, &tempSaveFile.episode, sizeof(JE_byte)); p++;
		memcpy(p, &tempSaveFile.lastItems, sizeof(JE_PItemsType)); p += sizeof(JE_PItemsType);
		memcpy(p, &tempSaveFile.difficulty, sizeof(JE_byte)); p++;
		memcpy(p, &tempSaveFile.secretHint, sizeof(JE_byte)); p++;
		memcpy(p, &tempSaveFile.input1, sizeof(JE_byte)); p++;
		memcpy(p, &tempSaveFile.input2, sizeof(JE_byte)); p++;
		
		/* booleans were 1 byte in pascal -- working around it */
		Uint8 temp = tempSaveFile.gameHasRepeated != false;
		memcpy(p, &temp, 1); p++;
		
		memcpy(p, &tempSaveFile.initialDifficulty, sizeof(JE_byte)); p++;
		
		tempSaveFile.highScore1 = SDL_SwapLE32(tempSaveFile.highScore1);
		memcpy(p, &tempSaveFile.highScore1, sizeof(JE_longint)); p += 4;
		
		tempSaveFile.highScore2 = SDL_SwapLE32(tempSaveFile.highScore2);
		memcpy(p, &tempSaveFile.highScore2, sizeof(JE_longint)); p += 4;
		
		memset(p, 0, sizeof(tempSaveFile.highScoreName));
		*p = strlen(tempSaveFile.highScoreName);
		memcpy(&p[1], &tempSaveFile.highScoreName, *p);
		p += 30;
		
		memcpy(p, &tempSaveFile.highScoreDiff, sizeof(JE_byte)); p++;
	}
	
	saveTemp[SIZEOF_SAVEGAMETEMP - 6] = editorLevel >> 8;
	saveTemp[SIZEOF_SAVEGAMETEMP - 5] = editorLevel;
	
	JE_encryptSaveTemp();
	
	f = dir_fopen_warn(get_user_directory(), "tyrian.sav", "wb");
	if (f)
	{
		efwrite(saveTemp, 1, sizeof(saveTemp), f);
		fclose(f);
#if (_BSD_SOURCE || _XOPEN_SOURCE >= 500)
		sync();
#endif
	}
	JE_decryptSaveTemp();
	
	f = dir_fopen_warn(get_user_directory(), "tyrian.cfg", "wb");
	if (f)
	{
		efwrite(&background2, 1, 1, f);
		efwrite(&gameSpeed, 1, 1, f);
		
		efwrite(&inputDevice_, 1, 1, f);
		efwrite(&jConfigure, 1, 1, f);
		
		efwrite(&versionNum, 1, 1, f);
		efwrite(&processorType, 1, 1, f);
		efwrite(&midiPort, 1, 1, f);
		efwrite(&soundEffects, 1, 1, f);
		efwrite(&gammaCorrection, 1, 1, f);
		efwrite(&difficultyLevel, 1, 1, f);
		efwrite(joyButtonAssign, 1, 4, f);
		
		efwrite(&tyrMusicVolume, 2, 1, f);
		efwrite(&fxVolume, 2, 1, f);
		
		efwrite(inputDevice, 1, 2, f);
		
		efwrite(keySettings, sizeof(*keySettings), COUNTOF(keySettings), f);
		
		fclose(f);
	}
	
	save_opentyrian_config();
	
#if (_BSD_SOURCE || _XOPEN_SOURCE >= 500)
	sync();
#endif
}