void fputdata(FILE *fileptr, FILE *headerptr, float *outdata, int nt)
{    
    efread(&tr, 1, HDRBYTES, headerptr);
    erewind(headerptr);
    
    memcpy((void *)tr.data, (const void *) outdata, nt*FSIZE);

    fputtr(fileptr, &tr);
}
void fputdata3c(FILE *fileptr, FILE *headerptr, float **outdata3c, int nt)
{
    int i;
   
    for(i=1;i<=3;i++) {
        efread(&tr, 1, HDRBYTES, headerptr);
        
        memcpy((void *)tr.data, (const void *) outdata3c[i], nt*FSIZE);

        fputtr(fileptr, &tr);
    }
    erewind(headerptr);
}
Exemple #3
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());	
}
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());
}
Exemple #5
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());
}
Exemple #6
0
int main(int argc, char **argv)
{
  int verbose;
  time_t start,finish;
  double elapsed_time;
  int ix,nt,nx,nx_out;
  float dt,dh,hmin,hmax;
  float *h,*h_out;
  float **din,**dout,**din_tw,**dout_tw;
  int *ih,*ih_out;
  int padt,padx;
  int Ltw,Dtw;   
  int twstart;
  float taper;
  int itw,Itw,Ntw,niter;
  float fmin,fmax;

  /********/    
  fprintf(stderr,"*******SUALFT*********\n");
  /* Initialize */
  initargs(argc, argv);
  requestdoc(1);
  start=time(0);    
  /* Get parameters */
  if (!getparint("verbose", &verbose)) verbose = 0;
  if (!getparint("nx", &nx)) nx = 10000;
  if (!getparfloat("dh", &dh)) dh = 10;
  if (!gettr(&tr)) err("can't read first trace");
  if (!tr.dt) err("dt header field must be set");
  if (!tr.ns) err("ns header field must be set");
  if (!getparint("Ltw", &Ltw))  Ltw = 200; /* length of time window in samples */
  if (!getparint("Dtw", &Dtw))  Dtw = 10; /* overlap of time windows in samples	*/
  dt   = ((float) tr.dt)/1000000.0;
  nt = (int) tr.ns;
  if (!getparint("padt", &padt)) padt = 2; /* padding factor in time dimension*/
  if (!getparint("padx", &padx)) padx = 2; /* padding factor in spatial dimension*/
  if (!getparfloat("fmin",&fmin)) fmin = 0;
  if (!getparfloat("fmax",&fmax)) fmax = 0.5/dt;
  if (!getparint("niter", &niter)) niter = 100;
  fmax = MIN(fmax,0.5/dt);

  din   = ealloc2float(nt,nx);
  h        = ealloc1float(nx);
  ih       = ealloc1int(nx);
  /* ***********************************************************************
  input data
  *********************************************************************** */
  ix=0;
  do {
    h[ix]=(float)  tr.offset;
    memcpy((void *) din[ix],(const void *) tr.data,nt*sizeof(float));
    ix++;
    if (ix > nx) err("Number of traces > %d\n",nx); 
  } while (gettr(&tr));
  erewind(stdin);
  nx=ix;
  if (verbose) fprintf(stderr,"processing %d traces \n", nx);
  hmin = h[0];
  hmax = h[0];  
 
  for (ix=0;ix<nx;ix++){
  	if (hmin>h[ix]) hmin = h[ix]; 
  	if (hmax<h[ix]) hmax = h[ix]; 
  }
  for (ix=0;ix<nx;ix++){
  	ih[ix] = (int) truncf((h[ix]-hmin)/dh);
  }
  nx_out = 0;
  for (ix=0;ix<nx;ix++){
  	if (nx_out<ih[ix]) nx_out = ih[ix] + 1; 
  }
  nx_out = nx_out + 1;
  ih_out = ealloc1int(nx_out);
  h_out = ealloc1float(nx_out);

  for (ix=0;ix<nx_out;ix++){
  	ih_out[ix] = ix;
  	h_out[ix] = ix*dh + hmin;
  }

  dout  = ealloc2float(nt,nx_out);

  Ntw = 9999;	
  /* number of time windows (will be updated during first 
  iteration to be consistent with total number of time samples
  and the length of each window) */
  
  din_tw = ealloc2float(Ltw,nx);
  dout_tw = ealloc2float(Ltw,nx_out);

/***********************************************************************
process using sliding time windows
***********************************************************************/
 twstart = 0;
 taper = 0;
 for (Itw=0;Itw<Ntw;Itw++){	
   if (Itw == 0){
	 Ntw = (int) truncf(nt/(Ltw-Dtw));
	 if ( (float) nt/(Ltw-Dtw) - (float) Ntw > 0) Ntw++;
   }		
   twstart = (int) Itw * (int) (Ltw-Dtw);
   if ((twstart+Ltw-1 >nt) && (Ntw > 1)){
   	 twstart=nt-Ltw;
   }
   if (Itw*(Ltw-Dtw+1) > nt){
      Ltw = (int) Ltw + nt - Itw*(Ltw-Dtw+1);
   }
   for (ix=0;ix<nx;ix++){ 
     for (itw=0;itw<Ltw;itw++){
       din_tw[ix][itw] = din[ix][twstart+itw];
     }
   }
   fprintf(stderr,"processing time window %d of %d\n",Itw+1,Ntw);
   if (verbose) fprintf(stderr,"Ltw=%d\n",Ltw);
   if (verbose) fprintf(stderr,"Dtw=%d\n",Dtw);
   process_time_window(din_tw,dout_tw,h,h_out,hmin,hmax,dt,Ltw,nx,nx_out,fmin,fmax,niter,padt,padx,verbose); 
   if (Itw==0){ 
     for (ix=0;ix<nx_out;ix++){ 
       for (itw=0;itw<Ltw;itw++){   
	     dout[ix][twstart+itw] = dout_tw[ix][itw];
       }	 	 
     }
   }
   else{
     for (ix=0;ix<nx_out;ix++){ 
       for (itw=0;itw<Dtw;itw++){   /* taper the top of the time window */
	     taper = (float) ((Dtw-1) - itw)/(Dtw-1); 
	     dout[ix][twstart+itw] = dout[ix][twstart+itw]*(taper) + dout_tw[ix][itw]*(1-taper);
       }
       for (itw=Dtw;itw<Ltw;itw++){   
	     dout[ix][twstart+itw] = dout_tw[ix][itw];
       }
     }	 	 
   }
 }
 /***********************************************************************
 end of processing time windows
 ***********************************************************************/

  /* ***********************************************************************
  output data
  *********************************************************************** */
  rewind(stdin);
  for (ix=0;ix<nx_out;ix++){ 
    memcpy((void *) tr.data,(const void *) dout[ix],nt*sizeof(float));
    tr.offset=(int) h_out[ix];
    tr.ntr=nx_out;
    tr.ns=nt;
    tr.dt = NINT(dt*1000000.);
    tr.tracl = ix+1;
    tr.tracr = ix+1;    
    fputtr(stdout,&tr);
  }
  
  /******** End of output **********/
  finish=time(0);
  elapsed_time=difftime(finish,start);
  fprintf(stderr,"Total time required: %6.2fs\n", elapsed_time);
  
  free1float(h);
  free1float(h_out);
  free2float(din);
  free2float(dout);
  free1int(ih);
  free1int(ih_out);
  free2float(din_tw);
  free2float(dout_tw);
  
  return EXIT_SUCCESS;
}
Exemple #7
0
int
main(int argc, char **argv)
{
	int ix,it;		/* loop counters */
	int i,j,k;
	int ntr;		/* number of input traces */
	int nt;			/* number of time samples */
	int nx;			/* number of horizontal samples */
	float dt;               /* Time sample interval */
        float dx=1;               /* horizontal sample interval */
        float pminf;             /* Minimum slope for Tau-P transform */
        float pmaxf;             /* Maximum slope for Tau-P transform */
	float dpf;		/* slope sampling interval */
	int np;			/* number of slopes for slant stack */
	int nwin;		/* spatial window length */
	int npoints;		/* number of points for rho filter */
	float **twin;		/* array[nwin][nt] of window traces */	
	float **pwin;		/* array[np][nt] of sl traces */
	int ntrw;		/* number of traces in processing window */
				/* full multiple of nwin */	
	int ist;		/* start processing from this window */
	int ntfft;
	float **traces;
	int w;			/* flag to apply semblance weights */
	int s;			/* flag to apply smoothing weights */
	int sl1;		/* length of smoothing window */
	int sl2;		/* length of smoothing window */
	float *smb;		/* semblance weights */
	double pw;
	float smbwin;
	int sn;
	float *spw;		/* array of spatial weights */
	float **out_traces;	/* array[nx][nt] of output traces */	
	int verbose;		/* flag for echoing information */
	char *tmpdir;		/* directory path for tmp files */
	cwp_Bool istmpdir=cwp_false;/* true for user-given path */
	float fh1;		/* maximum frequency before taper */
	float fh2;		/* maximum frequency */
	float prw;		/* prewithening */
	
	
        /* hook up getpar to handle the parameters */
        initargs(argc,argv);
        requestdoc(1);

	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);

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

        /* Store traces 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));

        /* get general flags and parameters and set defaults */
        if (!getparint("np",&np))             	np = 25;
        if (!getparfloat("pminf",&pminf))	pminf = -0.01;
        if (!getparfloat("pmaxf",&pmaxf))	pmaxf = 0.01;
        if (!getparfloat("fh1",&fh1))		fh1 = 100;
        if (!getparfloat("fh2",&fh2))		fh2 = 120;
        if (!getparfloat("prw",&prw))		prw = 0.01;
	if (!getparfloat("dx",&dx))		dx = 1.0;
	if (!getparint("npoints",&npoints))	npoints = 71;
	if (!getparint("nwin",&nwin))		nwin= 5;
	if (!getparfloat("dt",&dt))		dt = dt;
	if (!getparfloat("smbwin",&smbwin))	smbwin = 0.05;
	if (!getpardouble("pw",&pw))		pw = 1.0;
	if (!getparint("w",&w))			w = 0;
	if (!getparint("s",&s))			s = 0;
	if (!getparint("sl1",&sl1))		sl1 = 2*nwin;
	if (!getparint("sl2",&sl2))		sl2 = nwin;
	
        nx = ntr;
	if (dt == 0.0)
		err("header field dt not set, must be getparred");

	/* allocate space */
	ntfft=npfar(nt);
	ntrw=nwin;
	while (ntrw < ntr) {
		ntrw+=nwin;
	}
	ist = ntrw-ntr/2;
	twin = alloc2float(nt, nwin);
	pwin = ealloc2float(ntfft,np);
        traces = alloc2float(nt, ntr);
        out_traces = alloc2float(nt, ntr);
	smb = ealloc1float(nt);
	
	/* Set up some constans*/
	dpf=(pmaxf-pminf)/(np-1);
	sn = (int)(smbwin/dt+0.5);
	if(sn%2==0) sn++;
	if(nwin%2==0) nwin++;
	
	/* spatial trace weigths */
	spw = ealloc1float(nwin);
	for(k=0,i=1;k<nwin/2+1;k++,i++) spw[k] = (float)i; 
	for(k=nwin/2+1,i=nwin/2;k<nwin;k++,i--) spw[k] = (float)i; 
/*	for(k=0,i=1;k<nwin;k++,i++) spw[k] =1.0; */
	
	
	
        /* load traces into an array and close temp file */
	erewind(headerfp);
        erewind(tracefp);
	
	memset( (void *) traces[0], (int) '\0', (nt*ntr)*FSIZE);
	memset( (void *) out_traces[0], (int) '\0', (nt*ntr)*FSIZE);
	
        for (ix=0; ix<ntr; ix++)
                fread (traces[ix], FSIZE, nt, tracefp);
        efclose (tracefp);
	if (istmpdir) eremove(tracefile);

	/* do requested operation */
	 
	for(i=0; i<ntr; i+=nwin/2) {
		memcpy( (void *) twin[0], (const void *) traces[i],
			nt*nwin*FSIZE);	

		/* compute forward slant stack */
/*		fwd_tx_sstack (dt, nt, nwin, -nwin/2*dx, dx, np, pminf, dpf,
	       		twin, pwin);
*/		forward_p_transform(nwin,nt,dt,pmaxf*1000.0,pminf*1000.0,dpf*1000.0,
                                    0.0,fh1,fh2,3.0,30.0,400,5,1,0,0,1,prw,
				    0.0,nwin*dx,1,dx,0.0,0.0,0.0,twin,pwin);
/*		fwd_FK_sstack (dt, nt, nwin, -nwin/2*dx, dx, np, pminf, dpf,0,
	       		twin, pwin);
*/		
		/* compute semplance */
		if(w==1) {
			semb(sn,pwin,np,nt,smb);
			/* apply weights */
			for(j=0;j<nt;j++)
				for(k=0;k<np;k++) pwin[k][j] *=smb[j];
		}
		if(s==1) {
			gaussian2d_smoothing (np,nt,sl2,sl1,pwin);
		}
		if(s==2) {
			dlsq_smoothing (nt,np,0,nt,0,np,sl1,sl2,0,pwin);
		}
		/* compute inverse slant stack */
/*		inv_tx_sstack (dt, nt, nwin, npoints,-nwin/2*dx, dx, np,pminf,dpf,
			pwin, twin);
*/		inverse_p_transform(nwin,nt,dt,pmaxf*1000.0,pminf*1000.0,dpf*1000.0,
                                    0.0,fh1,fh2,0.0,nwin*dx,1,dx,0.0,
				    pwin,twin);
/*		inv_FK_sstack (dt, nt, nwin,-nwin/2*dx, dx, np,pminf,dpf,0,
			pwin, twin);
*/			
		{ register int itr,it,spind;;
			for(itr=0;itr<nwin;itr++) {
				spind=i+itr;
				for(it=0;it<nt;it++) {
					if(spind>0 && spind<ntr) 
							out_traces[spind][it] += spw[itr]*twin[itr][it];
						/*	out_traces[spind][it] = twin[itr][it]; */
				}
			}
		}

/*		fprintf(stderr," Trace #= %5d\n",i); */	
        }
	/* write output traces */
        erewind(headerfp);
	{       register int itr;
		for (itr=0; itr<ntr; itr++) {
			efread(&tr, 1, HDRBYTES, headerfp);
			for (it=0; it<nt; it++) 
				tr.data[it]=out_traces[itr][it];
			puttr(&tr);
		}
	}
	efclose(headerfp);
	if (istmpdir) eremove(headerfile);

	/* free allocated space */
	free2float(out_traces);
	free1float(spw);

	return EXIT_SUCCESS;

}
Exemple #8
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());
}
Exemple #9
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());	
}
Exemple #10
0
/*
 * Main procedure.  Process arguments and then
 * transfer control to the main command processing loop
 * in the routine commands.  We are entered as either "ex", "edit", "vi"
 * or "view" and the distinction is made here.  Actually, we are "vi" if
 * there is a 'v' in our name, "view" is there is a 'w', and "edit" if
 * there is a 'd' in our name.  For edit we just diddle options;
 * for vi we actually force an early visual command.
 */
int
main(int ac, char **av)
{
#ifndef VMUNIX
	char *erpath = EXSTRINGS;
#endif
	register char *cp;
	register int c;
	bool recov = 0;
	bool ivis;
	bool itag = 0;
	bool fast = 0;
#ifdef TRACE
	register char *tracef;
#endif

	/*
	 * Immediately grab the tty modes so that we wont
	 * get messed up if an interrupt comes in quickly.
	 */
	gTTY(1);
#ifndef USG3TTY
	normf = tty.sg_flags;
#else
	normf = tty;
#endif
	ppid = getpid();
	/*
	 * Defend against d's, v's, w's, and a's in directories of
	 * path leading to our true name.
	 */
	av[0] = tailpath(av[0]);

	/*
	 * Figure out how we were invoked: ex, edit, vi, view.
	 */
	ivis = any('v', av[0]);	/* "vi" */
	if (any('w', av[0]))	/* "view" */
		value(READONLY) = 1;
	if (any('d', av[0])) {	/* "edit" */
		value(OPEN) = 0;
		value(REPORT) = 1;
		value(MAGIC) = 0;
	}

#ifndef VMUNIX
	/*
	 * For debugging take files out of . if name is a.out.
	 */
	if (av[0][0] == 'a')
		erpath = tailpath(erpath);
#endif
	/*
	 * Open the error message file.
	 */
	draino();
#ifndef VMUNIX
	erfile = open(erpath+4, O_RDONLY);
	if (erfile < 0) {
		erfile = open(erpath, O_RDONLY);
	}
#endif
	pstop();

	/*
	 * Initialize interrupt handling.
	 */
	oldhup = signal(SIGHUP, SIG_IGN);
	if (oldhup == SIG_DFL)
		signal(SIGHUP, onhup);
	oldquit = signal(SIGQUIT, SIG_IGN);
	ruptible = signal(SIGINT, SIG_IGN) == SIG_DFL;
	if (signal(SIGTERM, SIG_IGN) == SIG_DFL)
		signal(SIGTERM, onhup);
#ifdef SIGEMT
	if (signal(SIGEMT, SIG_IGN) == SIG_DFL)
		signal(SIGEMT, onemt);
#endif

	/*
	 * Initialize end of core pointers.
	 * Normally we avoid breaking back to fendcore after each
	 * file since this can be expensive (much core-core copying).
	 * If your system can scatter load processes you could do
	 * this as ed does, saving a little core, but it will probably
	 * not often make much difference.
	 */
#ifdef UNIX_SBRK
	fendcore = (line *) sbrk(0);
	endcore = fendcore - 2;
#else
# define LINELIMIT 0x8000
	fendcore = malloc(LINELIMIT * sizeof(line *));
	endcore = fendcore + LINELIMIT - 1;
#endif

	/*
	 * Process flag arguments.
	 */
	ac--, av++;
	while (ac && av[0][0] == '-') {
		c = av[0][1];
		if (c == 0) {
			hush = 1;
			value(AUTOPRINT) = 0;
			fast++;
		} else switch (c) {

		case 'R':
			value(READONLY) = 1;
			break;

#ifdef TRACE
		case 'T':
			if (av[0][2] == 0)
				tracef = "trace";
			else {
				tracef = tttrace;
				tracef[8] = av[0][2];
				if (tracef[8])
					tracef[9] = av[0][3];
				else
					tracef[9] = 0;
			}
			trace = fopen(tracef, "w");
			if (trace == NULL)
				ex_printf("Trace create error\n");
			setbuf(trace, tracbuf);
			break;

#endif

#ifdef LISPCODE
		case 'l':
			value(LISP) = 1;
			value(SHOWMATCH) = 1;
			break;
#endif

		case 'r':
			recov++;
			break;

		case 't':
			if (ac > 1 && av[1][0] != '-') {
				ac--, av++;
				itag = 1;
				/* BUG: should check for too long tag. */
				CP(lasttag, av[0]);
			}
			break;

		case 'v':
			ivis = 1;
			break;

		case 'w':
			defwind = 0;
			if (av[0][2] == 0) defwind = 3;
			else for (cp = &av[0][2]; isdigit((int)*cp); cp++)
				defwind = 10*defwind + *cp - '0';
			break;

#ifdef CRYPT
		case 'x':
			/* -x: encrypted mode */
			xflag = 1;
			break;
#endif

		default:
			smerror("Unknown option %s\n", av[0]);
			break;
		}
		ac--, av++;
	}

#ifdef SIGTSTP
	if (!hush && signal(SIGTSTP, SIG_IGN) == SIG_DFL)
		signal(SIGTSTP, onsusp), dosusp++;
#endif

	if (ac && av[0][0] == '+') {
		firstpat = &av[0][1];
		ac--, av++;
	}

#ifdef CRYPT
	if(xflag){
		key = getpass(KEYPROMPT);
		kflag = crinit(key, perm);
	}
#endif

	/*
	 * If we are doing a recover and no filename
	 * was given, then execute an exrecover command with
	 * the -r option to type out the list of saved file names.
	 * Otherwise set the remembered file name to the first argument
	 * file name so the "recover" initial command will find it.
	 */
	if (recov) {
		if (ac == 0) {
			ppid = 0;
			setrupt();
			execl(EXRECOVER, "exrecover", "-r", NULL);
			filioerr(EXRECOVER);
			ex_exit(1);
		}
		CP(savedfile, *av);
		av++, ac--;
	}

	/*
	 * Initialize the argument list.
	 */
	argv0 = av;
	argc0 = ac;
	args0 = av[0];
	erewind();

	/*
	 * Initialize a temporary file (buffer) and
	 * set up terminal environment.  Read user startup commands.
	 */
	if (setexit() == 0) {
		setrupt();
		intty = isatty(0);
		value(PROMPT) = intty;
		if ((cp = getenv("SHELL")))
			CP(shell, cp);
		if (fast || !intty)
			setterm("dumb");
		else {
			gettmode();
			if ((cp = getenv("TERM")) != 0 && *cp)
				setterm(cp);
		}
	}
	if (setexit() == 0 && !fast && intty) {
		if ((globp = getenv("EXINIT")) && *globp)
			commands(1,1);
		else {
			globp = 0;
			if ((cp = getenv("HOME")) != 0 && *cp)
				source(strcat(strcpy(genbuf, cp), "/.exrc"), 1);
		}
	}
	init();	/* moved after prev 2 chunks to fix directory option */

	/*
	 * Initial processing.  Handle tag, recover, and file argument
	 * implied next commands.  If going in as 'vi', then don't do
	 * anything, just set initev so we will do it later (from within
	 * visual).
	 */
	if (setexit() == 0) {
		if (recov)
			globp = "recover";
		else if (itag)
			globp = ivis ? "tag" : "tag|p";
		else if (argc)
			globp = "next";
		if (ivis)
			initev = globp;
		else if (globp) {
			inglobal = 1;
			commands(1, 1);
			inglobal = 0;
		}
	}

	/*
	 * Vi command... go into visual.
	 * Strange... everything in vi usually happens
	 * before we ever "start".
	 */
	if (ivis) {
		/*
		 * Don't have to be upward compatible with stupidity
		 * of starting editing at line $.
		 */
		if (dol > zero)
			dot = one;
		globp = "visual";
		if (setexit() == 0)
			commands(1, 1);
	}

	/*
	 * Clear out trash in state accumulated by startup,
	 * and then do the main command loop for a normal edit.
	 * If you quit out of a 'vi' command by doing Q or ^\,
	 * you also fall through to here.
	 */
	seenprompt = 1;
	ungetchar(0);
	globp = 0;
	initev = 0;
	setlastchar('\n');
	setexit();
	commands(0, 0);
	cleanup(1);
	return 0;
}
Exemple #11
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;
	size_t (*readptr) ();	/* pointer to efread() or pfread()	*/
	size_t efread();	/* must be declared to use ptr		*/
	size_t pfread();	/* must be declared to use ptr		*/

	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");


	/* Exercise pfread and efread */
	/* Set appropriate read function for input filetype */
	switch(filestat(STDIN)) {
	case TTY:
		err("input can't be tty");
	break;
	case DISK:
	case TAPE:
		readptr = efread;
		strcpy(ewbuf, "***Disk stdin: use efread ...   ");
		witems = strlen(ewbuf);
		efwrite(ewbuf, 1, witems, stdout);
	break;
	case PIPE:
		readptr = pfread;
		strcpy(ewbuf, "***Pipe stdin: use pfread ...   ");
		witems = strlen(ewbuf);
		efwrite(ewbuf, 1, witems, stdout);
	break;
	default:
		err("undefined input filetype %s", printstat(STDIN));
	break;
	}

	while ((*readptr)(pfbuf, 1, 1, stdin)) {
		efwrite(pfbuf, 1, 1, stdout);
	}

	return EXIT_SUCCESS;
}
Exemple #12
0
int main(int argc, char **argv)
{
    /* output file pointers */    
    FILE *rlfp=NULL, *taufp=NULL, *e21fp=NULL;
    FILE *e31fp=NULL, *e32fp=NULL, *plnfp=NULL;
    FILE *f1fp=NULL, *l1fp=NULL;
    FILE *thetafp=NULL, *phifp=NULL, *dirfp=NULL;
    FILE *erfp=NULL, *irfp=NULL, *qrfp=NULL;
    FILE *headerfp=NULL, *pfiltfp=NULL, *sfiltfp=NULL;
    FILE *nfiltfp=NULL, *efiltfp=NULL;
 //   FILE *pkur=NULL, *skur=NULL; 
        /* temporary file for trace headers */
			 /* (one 3C station only) */
        
    char *file=NULL;         /* base of output file name(s) */
    char *fname=NULL;        /* complete output file name */
    char *angle=NULL;        /* unit used for angles theta and phi */
    char *win=NULL;          /* shape of used time window */
    float fangle=0.0;   /* unit conversion factor applied to angles theta and phi */
    int iwin=0;           /* time window shape identifier */
        
    /* flags (see selfdoc) */
    int rl,theta,phi,tau,ellip,pln,f1,l1,dir,amp,verbose,all;
    
    int i,j,icomp;      /* indices for components (in loops) */
    int it;             /* index for time sample in main loop */
    int iwl;            /* correlation window length in samples */
    int nstat;          /* number of 3-component datasets */
    int nt;             /* number of time samples in one trace */
//    int kwl;            /* kurtosis window length in seconds */    


    float **data3c;     /* three-component data ([1..3][0..nt-1]) */
    float **a;          /* covariance matrix (a[1..3][1..3]) */
    float **v;          /* eigenvectors of covariance matrix (v[1..3][1..3]) */
    float *d;           /* the corresponding eigenvalues (d[1..3]) */
    float *w;           /* time window weights for correlation window */
    float dt;           /* sampling interval in seconds */
    float rlq;          /* contrast factor of rectilinearity */
    float wl;           /* correlation window length in seconds */
    

    float *data_e21=NULL;    /* main ellipticity */
    float *data_e31=NULL;    /* second ellipticity */
    float *data_e32=NULL;    /* transverse ellipticity */
    float *data_er=NULL;     /* eigenresultant */
    float *data_f1=NULL;     /* flatness coefficient */
    float *data_ir=NULL;     /* instantaneous resultant */
    float *data_l1=NULL;     /* linearity coefficient */
    float *data_phi=NULL;    /* horizontal azimuth phi */
    float *data_pln=NULL;    /* planarity */    
    float *data_qr=NULL;     /* quadratic resultant */
    float *data_rl=NULL;     /* rectilinearity factor */
    float *data_tau=NULL;    /* polarization parameter tau */
    float *data_theta=NULL;  /* inclination angle theta */
    float *data_pfilt=NULL;  /* P (vertical) polarization filter */
    float *data_sfilt=NULL;  /* S (horizontal) polarization filter */
    float *data_zfilt=NULL;  /* Z Filtered Trace */
    float *data_nfilt=NULL;  /* N Filtered Trace */
    float *data_efilt=NULL;  /* E Filtered Trace */
//    float *data_kwl=NULL;   /* Data for Kurtosis Window */
//    float *data_pkur=NULL;   /* Kurtosis detector for P */
//    float *data_skur=NULL;   /* Kurtosis detector for S */
    float **data3c_dir=NULL; /* 3 components of direction of polarization ([1..3][0..nt-1]) */
    
    /* initialize */
    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 (!getparstring("file", &file)) file="polar";
    if (!getparstring("angle", &angle)) angle="rad";
    if (!getparstring("win", &win)) win="boxcar";
    if (!getparfloat("wl", &wl)) wl = 0.1;
    if (!getparfloat("dt", &dt)) dt = ((double) tr.dt)/1000000.0;
    if (!getparfloat("rlq", &rlq)) rlq = 1.0;
    if (!getparint("verbose", &verbose)) verbose = 0;
//    if (!getparint("kwl", &kwl)) kwl = 5 * ((int) 1/dt);    

    /* ... and output flags */
    if (!getparint("all", &all))       all = 0;
    if (!getparint("rl", &rl))          rl = (all) ? all : 1;
    if (!getparint("dir", &dir))       dir = (all) ? 1 : 1;
    if (!getparint("theta", &theta)) theta = (all) ? all : 0;
    if (!getparint("phi", &phi))       phi = (all) ? all : 0;
    if (!getparint("tau", &tau))       tau = (all) ? 1 : 0;
    if (!getparint("ellip", &ellip)) ellip = (all) ? 1 : 0;
    if (!getparint("pln", &pln))       pln = (all) ? 1 : 0;
    if (!getparint("f1", &f1))          f1 = (all) ? 1 : 0;
    if (!getparint("l1", &l1))          l1 = (all) ? 1 : 0;
    if (!getparint("amp", &amp))       amp = (all) ? 1 : 0;

    checkpars();


    /* get time window shape */
    if      (STREQ(win, "boxcar"))   iwin=WBOXCAR;
    else if (STREQ(win, "bartlett")) iwin=WBARTLETT;
    else if (STREQ(win, "hanning"))  iwin=WHANNING;
    else if (STREQ(win, "welsh"))    iwin=WWELSH;
    else err("unknown win=%s", win);
    
    /* get unit conversion factor for angles */
    if      (STREQ(angle, "rad")) fangle=1.0;
    else if (STREQ(angle, "deg")) fangle=180.0/PI;
    else if (STREQ(angle, "gon")) fangle=200.0/PI;
    else err("unknown angle=%s", angle);

    /* convert seconds to samples */
    if (!dt) {
        dt = 0.004;
        warn("dt not set, assuming dt=0.004");
    }

    iwl = NINT(wl/dt);
        
    /* data validation */
    if (iwl<1) err("wl=%g must be positive", wl);
    if (iwl>nt) err("wl=%g too long for trace", wl);
    if (!strlen(file)) err("file= not set and default overridden");

    /* echo some information */
    if (verbose && (theta || phi)) warn("computing angles in %s", angle);
    if (verbose) warn("%s window length = %d samples\n", win, iwl);
    
    if (rl && theta) warn("computing filtered phase");

    /* open temporary file for trace headers */
    headerfp = etmpfile();
    
    /* set filenames and open files */
    fname = malloc( strlen(file)+7 );
    sprintf(fname, "%s.rl", file);    if (rl) rlfp = efopen(fname, "w");
    sprintf(fname, "%s.theta", file); if (theta) thetafp = efopen(fname, "w");
    sprintf(fname, "%s.phi", file);   if (phi) phifp = efopen(fname, "w");
    sprintf(fname, "%s.tau", file);   if (tau) taufp = efopen(fname, "w");
    sprintf(fname, "%s.e21", file);   if (ellip) e21fp = efopen(fname, "w");
    sprintf(fname, "%s.e31", file);   if (ellip) e31fp = efopen(fname, "w");
    sprintf(fname, "%s.e32", file);   if (ellip) e32fp = efopen(fname, "w");
    sprintf(fname, "%s.pln", file);   if (pln) plnfp = efopen(fname, "w");
    sprintf(fname, "%s.f1", file);    if (f1) f1fp = efopen(fname, "w");
    sprintf(fname, "%s.l1", file);    if (l1) l1fp = efopen(fname, "w");
    sprintf(fname, "%s.dir", file);   if (dir) dirfp = efopen(fname, "w");
    sprintf(fname, "%s.er", file);    if (amp) erfp = efopen(fname, "w");
    sprintf(fname, "%s.ir", file);    if (amp) irfp = efopen(fname, "w");
    sprintf(fname, "%s.qr", file);    if (amp) qrfp = efopen(fname, "w");
    sprintf(fname, "%s.pfilt", file); if (rl && theta) pfiltfp = efopen(fname, "w");
    sprintf(fname, "%s.sfilt", file); if (rl && theta) sfiltfp = efopen(fname, "w");
    sprintf(fname, "%s.nfilt", file); if (rl && theta) nfiltfp = efopen(fname, "w");
    sprintf(fname, "%s.efilt", file); if (rl && theta) efiltfp = efopen(fname, "w");
  //  sprintf(fname, "%s.pkur", file); if (rl && theta) pkur = efopen(fname, "w");
  //  sprintf(fname, "%s.skur", file); if (rl && theta) skur = efopen(fname, "w");
    free(fname);
    
    /* allocate space for input data and analysis matrices */
    /* index ranges used here: data3c[1..3][0..nt-1],      */
    /* a[1..3][1..3], v[1..3][1..3], d[1..3]               */
    data3c = ealloc2float(nt,3); data3c-=1;
    a = ealloc2float(3,3); a[0]-=1; a-=1;
    v = ealloc2float(3,3); v[0]-=1; v-=1;    
    d = ealloc1float(3); d-=1;

    /* calculate time window weights */
    w = ealloc1float(iwl);
    memset((void *) w, 0, iwl*FSIZE);
    calc_window(w, iwl, iwin);

    /* allocate and zero out space for output data */
    if (rl) { 
        data_rl = ealloc1float(nt); 
        memset((void *) data_rl, 0, nt*FSIZE);
    }
    if (theta) {
        data_theta = ealloc1float(nt);
        memset((void *) data_theta, 0, nt*FSIZE);
    }
    if (phi) {
        data_phi = ealloc1float(nt);
        memset((void *) data_phi, 0, nt*FSIZE);
    }    
    if (tau) {
        data_tau = ealloc1float(nt);
        memset((void *) data_tau, 0, nt*FSIZE);
    }
    if (ellip) {
        data_e21 = ealloc1float(nt);
        data_e31 = ealloc1float(nt);
        data_e32 = ealloc1float(nt);
        memset((void *) data_e21, 0, nt*FSIZE);
        memset((void *) data_e31, 0, nt*FSIZE);
        memset((void *) data_e32, 0, nt*FSIZE);
    }
    if (pln) {
        data_pln = ealloc1float(nt);
        memset((void *) data_pln, 0, nt*FSIZE);
    }
    if (f1) {
        data_f1 = ealloc1float(nt);
        memset((void *) data_f1, 0, nt*FSIZE);
    }
    if (l1) {
        data_l1 = ealloc1float(nt);
        memset((void *) data_l1, 0, nt*FSIZE);
    }
    if (amp) {
        data_er = ealloc1float(nt);
        data_ir = ealloc1float(nt);
        data_qr = ealloc1float(nt);
        memset((void *) data_er, 0, nt*FSIZE);
        memset((void *) data_ir, 0, nt*FSIZE);
        memset((void *) data_qr, 0, nt*FSIZE);
    }
    if (dir) {
        data3c_dir = ealloc2float(nt,3); data3c_dir-=1;
        for (i=1;i<=3;i++) memset((void *) data3c_dir[i], 0, nt*FSIZE);
    }
    if (rl && theta) {
        data_pfilt = ealloc1float(nt);
        memset((void *) data_pfilt, 0, nt*FSIZE);
        data_sfilt = ealloc1float(nt);
        memset((void *) data_pfilt, 0, nt*FSIZE);
/*        data_3Cfilt = ealloc2float(nt,3);
        for (i=1;i<=3;i++) memset((void *) data_3Cfilt[i], 0, nt*FSIZE); */
        data_zfilt = ealloc1float(nt);
        data_nfilt = ealloc1float(nt);
        data_efilt = ealloc1float(nt);
        memset((void *) data_zfilt, 0, nt*FSIZE);
        memset((void *) data_nfilt, 0, nt*FSIZE);
        memset((void *) data_efilt, 0, nt*FSIZE);

 //       data_pkur = ealloc1float(nt);
//        data_skur = ealloc1float(nt);
//        memset((void *) data_pkur, 0, nt*FSIZE);
//        memset((void *) data_skur, 0, nt*FSIZE);
        /* Allocate data for kurtosis window arrays */
//        data_kwl = ealloc1float(iwl);
//        memset((void *) data_kwl, 0, kwl*FSIZE);        
    }        


/* ************************ BEGIN CALCULATION ******************************* */    

    /* loop over traces */
    icomp=0;
    nstat=0;
    // Need to convert this do while loop into a for loop so as to be easier
    // to parallelize
    warn("Trace Start Time: %d %d %d %d %d", tr.year, tr.day, tr.hour, tr.minute, tr.sec);    
    do {
        /* store trace header in temporary file and read data */
        efwrite(&tr, HDRBYTES, 1, headerfp);
        icomp++;
        memcpy((void *)data3c[icomp], (const void *) tr.data, nt*FSIZE);
                
        /* process 3-component dataset */
        if (icomp==3) {
            erewind(headerfp);
            icomp = 0;
            nstat++;
            if (verbose) 
                fprintf(stderr,"%s: analyzing station %d \r",argv[0], nstat);

            /* start loop over samples */

            for (it=iwl/2;it<nt-iwl/2;it++) {
                //warn("Sample %d", it);
                /* covariance matrix */

                for (i=1;i<=3;i++) 
                {
                    for (j=i;j<=3;j++) 
                    {
                        a[i][j]=a[j][i]=covar(data3c[i], data3c[j], it-iwl/2, iwl, w);                    
                    }
                }
                    
                /* compute eigenvalues and vectors */
                eig_jacobi(a,d,v,3);
                sort_eigenvalues(d,v,3);
                
                /* polarization parameters */
                if (rl) data_rl[it]=calc_rl(d,rlq,rl);
                if (theta) data_theta[it]=calc_theta(v, theta) * fangle;
                if (phi) data_phi[it]=calc_phi(v, phi) * fangle;
                if (tau) data_tau[it]=calc_tau(d);
                if (ellip) {
                    data_e21[it]=calc_ellip(d,2,1);
                    data_e31[it]=calc_ellip(d,3,1);
                    data_e32[it]=calc_ellip(d,3,2);
                }
                if (pln) data_pln[it]=calc_plan(d);
                if (f1) data_f1[it]=calc_f1(d);
                if (l1) data_l1[it]=calc_l1(d);
                if (amp) data_er[it]=calc_er(d);
                if (dir) calc_dir(data3c_dir,v,it);
                if (rl && theta) 
                {
                    data_zfilt[it] = data3c[1][it] * calc_pfilt(rl, theta);
                    data_nfilt[it] = data3c[2][it] * calc_sfilt(rl, theta);
                    data_efilt[it] = data3c[3][it] * calc_sfilt(rl, theta);
                    data_pfilt[it] = data_zfilt[it];
                    data_sfilt[it] = (data_nfilt[it] + data_efilt[it]) / 2;                 
//                    data_pkur[it] = kurtosiswindow(data_pfilt,data_kwl,it - kwl/2,kwl,nt);     
//                    data_skur[it] = kurtosiswindow(data_sfilt,data_kwl,it - kwl/2,kwl,nt);
               }             

            } /* end loop over samples */

            /* compute amplitude parameters */
            if (amp) ampparams(data3c, data_ir, data_qr, nt, iwl);

/* *************************** END CALCULATION ****************************** */
/* ***************************** BEGIN WRITE ******************************** */

            /* write polarization attributes to files */
            if (rl) fputdata(rlfp, headerfp, data_rl, nt);
            if (theta) fputdata(thetafp, headerfp, data_theta, nt);
            if (phi) fputdata(phifp, headerfp, data_phi, nt);
            if (tau) fputdata(taufp, headerfp, data_tau, nt);
            if (ellip) {
                fputdata(e21fp, headerfp, data_e21, nt);
                fputdata(e31fp, headerfp, data_e31, nt);
                fputdata(e32fp, headerfp, data_e32, nt);
            }
            if (pln) fputdata(plnfp, headerfp, data_pln, nt);
            if (f1) fputdata(f1fp, headerfp, data_f1, nt);
            if (l1) fputdata(l1fp, headerfp, data_l1, nt);
            if (amp) {
                fputdata(erfp, headerfp, data_er, nt);
                fputdata(irfp, headerfp, data_ir, nt);
                fputdata(qrfp, headerfp, data_qr, nt);
            }
            if (dir) fputdata3c(dirfp, headerfp, data3c_dir, nt);
            if (rl && theta) 
            {
                fputdata(pfiltfp, headerfp, data_pfilt, nt);
                fputdata(sfiltfp, headerfp, data_sfilt, nt);
                fputdata(nfiltfp, headerfp, data_nfilt, nt);
                fputdata(efiltfp, headerfp, data_efilt, nt);
               // fputdata(pkur, headerfp, data_pkur, nt);
               // fputdata(skur, headerfp, data_skur, nt);
            }

/* ****************************** END WRITE ********************************* */
            
        } /* end of processing three-component dataset */
        
    } while (gettr(&tr)); /* end loop over traces */
    
    if (verbose) {
        fprintf(stderr,"\n");
        if (icomp) warn("last %d trace(s) skipped", icomp);
    }
    
    /* close files */
    efclose(headerfp);
    if (rl) efclose(rlfp);
    if (theta) efclose(thetafp);
    if (phi) efclose(phifp);
    if (tau) efclose(taufp);
    if (ellip) {
        efclose(e21fp);
        efclose(e31fp);
        efclose(e32fp);
    }
    if (pln) efclose(plnfp);
    if (f1) efclose(f1fp);
    if (l1) efclose(l1fp);
    if (amp) {
        efclose(erfp);
        efclose(irfp);
        efclose(qrfp);
    }
    if (dir) efclose(dirfp);
    if (rl && theta) {
        efclose(pfiltfp);
        efclose(sfiltfp);
//        efclose(pkur);
//        efclose(skur);
        }  
    return(CWP_Exit());
}
Exemple #13
0
int
main (int argc, char **argv)
{
	int nt;			/* number of time samples		*/
	int nz;			/* number of migrated depth samples	*/
	int nx;			/* number of horizontal samples       	*/
	int nxshot;		/* number of shots to be migrated	*/
	int iz,iw,ix,it,ik;	/* loop counters			*/
        int igx;                /* integerized gx value			*/
	int ntfft,nxfft;	/* fft size				*/
	int nw,truenw,nk;	/* number of wave numbers		*/
	int dip=65;		/* dip angle				*/
	int oldigx=0;		/* old value of integerized gx value	*/
	int oldisx=0;		/* old value of integerized sx value	*/

        float sx,gx;            /* x source and geophone location       */
        float gxmin=0.0,gxmax=0.0; /* x source and geophone location    */
        float min_sx_gx;        /* min(sx,gx)                           */
        float oldgx;            /* old gx position                      */
        float oldgxmin;         /* old gx position                      */
        float oldgxmax;         /* old gx position                      */
        float oldsx=0.0;        /* old sx position                      */

        int isx=0,nxo;          /* index for source and geophone        */
	int ix1,ix2,ix3,ixshot,il=0,ir=0; /* dummy index		*/
	int lpad,rpad; /* padding on both sides of the migrated section */

	float *wl=NULL,*wtmp=NULL;
	float fmax;
	float f1,f2,f3,f4;
	int nf1,nf2,nf3,nf4;
	int ntw;

	float dt=0.004,dz;	/* time and depth sampling interval 	*/
	float dw,dk;		/* wavenumber and frequency sampling interval */
	float fw,fk;		/* first wavenumber and frequency	*/
	float w,k;		/* wavenumber and frequency		*/
	float dx;		/* spatial sampling interval		*/
	float **p=NULL;
	float **cresult=NULL;	/* input, output data			*/
	float v1,vmin;

	double kz1,kz2;
	double phase1;
	float **v=NULL;
	float **vp=NULL;
	complex cshift1,cshift2;
	complex *wlsp=NULL;
	complex **cp=NULL;
	complex **cp1=NULL;
	complex **cq=NULL;
	complex **cq1=NULL;	/*complex input,output*/
	char *vfile="";		/* name of file containing velocities */
	FILE *vfp=NULL;

        int verbose;            /* verbose flag                         */
	

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

	/* get optional parameters */
	MUSTGETPARINT("nz",&nz);
	MUSTGETPARFLOAT("dz",&dz);
	MUSTGETPARSTRING("vfile", &vfile);
	MUSTGETPARINT("nxo",&nxo);
	MUSTGETPARINT("nxshot",&nxshot);

	if (!getparfloat("fmax",&fmax)) fmax = 25. ;  
	if (!getparfloat("f1",&f1)) f1 = 10.0;
	if (!getparfloat("f2",&f2)) f2 = 20.0;
	if (!getparfloat("f3",&f3)) f3 = 40.0;
	if (!getparfloat("f4",&f4)) f4 = 50.0;
	if (!getparint("lpad",&lpad)) lpad=9999;
	if (!getparint("rpad",&rpad)) rpad=9999;
	if (!getparint("dip",&dip)) dip=65;

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

	/* allocate space */
	cresult = alloc2float(nz,nxo);
	vp=alloc2float(nxo,nz);

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

        /* zero out cresult array */
        memset((void *) cresult[0], 0, nxo*nz*FSIZE);

	if (!gettr(&tr))  err("can't get first trace");
	nt = tr.ns;
        get_sx_gx(&sx,&gx);
        min_sx_gx = MIN(sx,gx);
        gxmin=gxmax=gx;
        erewind(stdin);
/*
        sx = sx - min_sx_gx;
        gx = gx - min_sx_gx;
*/

	/* 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");
		}
	}

        do {    /* begin loop over shots */

		/* determine frequency sampling interval*/
		ntfft = npfar(nt);
		nw = ntfft/2+1;
		dw = 2.0*PI/(ntfft*dt);

		/* compute the index of the frequency to be migrated */
		fw=2.0*PI*f1;
		nf1=fw/dw+0.5;
		 
		fw=2.0*PI*f2;
		nf2=fw/dw+0.5;

		fw=2.0*PI*f3;
		nf3=fw/dw+0.5;

		fw=2.0*PI*f4;
		nf4=fw/dw+0.5;  

		/* the number of frequencies to migrated */
		truenw=nf4-nf1+1;
		fw=0.0+nf1*dw;

		if (verbose)
		warn("nf1=%d nf2=%d nf3=%d nf4=%d nw=%d",nf1,nf2,nf3,nf4,truenw);

		/* allocate space */
		wl=alloc1float(ntfft);
		wlsp=alloc1complex(nw);

		/* generate the Ricker wavelet */
		wtmp=ricker(fmax,dt,&ntw);

                /* zero out wl[] array */
                memset((void *) wl, 0, ntfft*FSIZE);

	
		/* CHANGE BY CHRIS STOLK, Dec. 11, 2005 */
		/* The next two lines are the old code, */
		/* it is erroneous because the peak of  */
		/* the wavelet occurs at positive time 	*/
		/* instead of time zero.		*/
		for(it=0;it<ntw;it++)
	  			wl[it]=wtmp[it];
		/* New code: we put in the wavelet in a centered fashion */ 
		/*
		for(it=0;it<ntw;it++) {
	  		wl[(it-ntw/2+ntfft) % ntfft]=wtmp[it];
		}
		*/
	  	/*  warn("%12i    %12f    \n",(it-ntw/2+ntfft) % ntfft,wtmp[it]); */
		/* End of new code */
		free1float(wtmp);

                /* fourier transform wl array */
		pfarc(-1,ntfft,wl,wlsp);

		/* CS TEST: this was used to output the array wlsp
			   (the wavelet in the frequency domain) to the file CSinfo,
			   no longer needed and commented out */
			/*
			FILE *CSinfo;
			CSinfo=fopen("CSinfo","w");
			fprintf(CSinfo,"ntfft=%10i\n",ntfft);
			fprintf(CSinfo,"ntw=%10i\n",ntw);
			for(iw=0;iw<ntfft/2+1;iw++)
			  fprintf(CSinfo,"%12f   %12f   \n",wlsp[iw].r,wlsp[iw].i);
			fclose(CSinfo);
					*/
			/* conclusion from the analysis of this info:
			   the wavelet (whose fourier transform is in wlsp)
			   is not zero phase!!! 
			   so there is a timeshift error!!!
			   Conclusion obtained dec 11 2005 */
			/* CS */

		/* allocate space */
		p = alloc2float(ntfft,nxo);
		cq = alloc2complex(nw,nxo);
	
                /* zero out p[][] array */
                memset((void *) p[0], 0, ntfft*nxo*FSIZE);
		
                /* initialize a number of items before looping over traces */
                nx = 0;
                if (gx < 0 ) {
                    igx=gx/dx + nxo;
                } else {
                    igx=gx/dx ;
                }
                oldigx=igx;
                oldsx=sx;
                oldgx=gx;
                oldgxmax=gxmax;
                oldgxmin=gxmin;
                while(gettr(&tr)) { /* begin looping over traces within a shot gather */

                        /* get sx and gx */
                        get_sx_gx(&sx,&gx);
/*
warn("%d nx=%d", igx, nx);
                        sx = (sx - min_sx_gx);
                        gx = (gx - min_sx_gx);
*/
                        if (gx < 0 ) {
                            igx=gx/dx + nxo;
                        } else {
                            igx=gx/dx ;
                        }
			if (igx==oldigx) 
			   warn("repeated igx!!! check dx or scalco value!!!");
			oldigx = igx;
                        if(tr.sx!=oldsx){ efseeko(stdin,(off_t)(-240-nt*4),SEEK_CUR); break;}

                        if(gxmin>gx)gxmin=gx;
                        if(gxmax<gx)gxmax=gx;

                        if(verbose)
                                warn(" inside loop:  min_sx_gx %f isx %d igx %d gx %f sx %f",min_sx_gx,isx,igx,gx,sx);
                        /* sx, gx must increase monotonically */
                        if (!(oldsx <= sx) )
                         err("sx field must be monotonically increasing!");
                        if (!(oldgx <= gx) )
                         err("gx field must be monotonically increasing!");

			memcpy( (void *) p[igx], (const void *) tr.data,nt*FSIZE);

                        ++nx;
                } 

                isx=oldsx/dx;
		if (isx==oldisx) 
			warn("repeated isx!!! check dx or scalco value!!!");
		oldisx=isx;
                ixshot=isx;
                if(verbose) {
                        warn("sx %f, gx %f , gxmin %f  gxmax %f nx %d",sx,gx,gxmin,gxmax, nx);
                        warn("isx %d igx %d ixshot %d" ,isx,igx,ixshot);
                }

		/* transform the shot gather from time to frequency domain */
		pfa2rc(1,1,ntfft,nxo,p[0],cq[0]);

                /* compute the most left and right index for the migrated */
                /* section */
                ix1=oldsx/dx;
                ix2=gxmin/dx;
                ix3=gxmax/dx;

                if(ix1>=ix3)ix3=ix1;
                if(ix1<=ix2)ix2=ix1;
                il=ix2;
                ir=ix3;

                ix2-=lpad;
                ix3+=rpad;
                if(ix2<0)ix2=0;
                if(ix3>nxo-1)ix3=nxo-1;

                /* the total traces to be migrated */
                nx=ix3-ix2+1;
                nw=truenw;

		/* determine wavenumber sampling (for complex to complex FFT) */
		nxfft = npfa(nx);
		nk = nxfft;
		dk = 2.0*PI/(nxfft*dx);
		fk = -PI/dx;

		/* allocate space for velocity profile within the aperature */
		v=alloc2float(nx,nz);   
		for(iz=0;iz<nz;iz++)
			for(ix=0;ix<nx;ix++)
				v[iz][ix]=vp[iz][ix+ix2];

		/* allocate space */
		cp = alloc2complex(nx,nw);
		cp1 = alloc2complex(nx,nw);

                /* transpose the frequency domain data from     */
                /* data[ix][iw] to data[iw][ix] and apply a     */
                /* Hamming at the same time                     */
		for (ix=0; ix<nx; ix++) {
			for (iw=0; iw<nw; iw++){
				float tmpp=0.0,tmppp=0.0;

				if(iw>=(nf1-nf1)&&iw<=(nf2-nf1)){
					tmpp=PI/(nf2-nf1);
					tmppp=tmpp*(iw-nf1)-PI;
					tmpp=0.54+0.46*cos(tmppp);
					cp[iw][ix]=crmul(cq[ix+ix2][iw+nf1],tmpp);
				} else {
					if(iw>=(nf3-nf1)&&iw<=(nf4-nf1)){
						tmpp=PI/(nf4-nf3);
						tmppp=tmpp*(iw-nf3);
						tmpp=0.54+0.46*cos(tmppp);
						cp[iw][ix]=crmul(cq[ix+ix2][iw+nf1],tmpp);
					} else {
						cp[iw][ix]=cq[ix+ix2][iw+nf1];}
				}
				cp1[iw][ix]=cmplx(0.0,0.0);
			}
		}

		for(iw=0;iw<nw;iw++){
			cp1[iw][ixshot-ix2]=wlsp[iw+nf1];
		}

                if(verbose) {
                        warn("ixshot %d ix %d ix1 %d ix2 %d ix3 %d",ixshot,ix,ix1,ix2,ix3);
                        warn("oldsx %f ",oldsx);
                }
			
		free2float(p);
		free2complex(cq);
		free1float(wl);
		free1complex(wlsp);

		/* allocating space */
		cq=alloc2complex(nxfft,nw);
		cq1=alloc2complex(nxfft,nw);


		/* loops over depth */
		for(iz=0;iz<nz;++iz){

			/* the imaging condition */
			for(ix=0;ix<nx;ix++){
				for(iw=0,w=fw;iw<nw;w+=dw,iw++){   
					complex tmp;
					float ratio=10.0;
		
					if(fabs(ix+ix2-ixshot)*dx<ratio*iz*dz)
						tmp=cmul(cp[iw][ix],cp1[iw][ix]);
					else 
						tmp=cmplx(0.0,0.0);  

					cresult[ix+ix2][iz]+=tmp.r/ntfft;
				}
			}

			/* get the minimum velocity */
			vmin=0;
			for(ix=il-ix2;ix<=ir-ix2;ix++){
				vmin+=1.0/v[iz][ix]/(ir-il+1);
			}
			vmin=1.0/vmin;
		
			/* compute the shifted wavefield */
			for (ik=0;ik<nx;++ik) {
				for (iw=0; iw<nw; ++iw) {
					cq[iw][ik] = ik%2 ? cneg(cp[iw][ik]) : cp[iw][ik];
					cq1[iw][ik] = ik%2 ? cneg(cp1[iw][ik]) : cp1[iw][ik];
				}
			}
		 
			/* zero out cq[][] cq1[][] */
			for (ik=nx; ik<nk; ++ik) {
				for (iw=0; iw<nw; ++iw) {
					cq[iw][ik] = cmplx(0.0,0.0);
					cq1[iw][ik] = cmplx(0.0,0.0);
				}
			}

			/* FFT to W-K domain */
			pfa2cc(-1,1,nk,nw,cq[0]);
			pfa2cc(-1,1,nk,nw,cq1[0]);
	
			v1=vmin;
			for(ik=0,k=fk;ik<nk;++ik,k+=dk) {
				for(iw=0,w=fw;iw<nw;++iw,w+=dw){
					if(w==0.0)w=1.0e-10/dt; 
					kz1=1.0-pow(v1*k/w,2.0);
					if(kz1>0.15){
						phase1 = -w*sqrt(kz1)*dz/v1;
						cshift1 = cmplx(cos(phase1), sin(phase1));
						cq[iw][ik] = cmul(cq[iw][ik],cshift1);
						cq1[iw][ik] = cmul(cq1[iw][ik],cshift1);
					} else {
						cq[iw][ik] = cq1[iw][ik] = cmplx(0.0,0.0);
					}
				}
			}
	
			pfa2cc(1,1,nk,nw,cq[0]);
			pfa2cc(1,1,nk,nw,cq1[0]);

			for(ix=0;ix<nx;++ix) {
				for(iw=0,w=fw;iw<nw;w+=dw,++iw){
					float a=0.015,g=1.0;
					int I=10;
				
					if(ix<=I)g=exp(-a*(I-ix)*(I-ix));
					if(ix>=nx-I)g=exp(-a*(-nx+I+ix)*(-nx+I+ix));
				 
				
					cq[iw][ix] = crmul( cq[iw][ix],1.0/nxfft);
					cq[iw][ix] =ix%2 ? cneg(cq[iw][ix]) : cq[iw][ix];
					kz2=(1.0/v1-1.0/v[iz][ix])*w*dz;
					cshift2=cmplx(cos(kz2),sin(kz2));
					cp[iw][ix]=cmul(cq[iw][ix],cshift2);
		
					cq1[iw][ix] = crmul( cq1[iw][ix],1.0/nxfft);
					cq1[iw][ix] =ix%2 ? cneg(cq1[iw][ix]) : cq1[iw][ix];
					cp1[iw][ix]=cmul(cq1[iw][ix],cshift2);
		 
				}
			}
		}
		
		free2complex(cp);
		free2complex(cp1);
		free2complex(cq);
		free2complex(cq1);
		free2float(v);

		--nxshot;

	} while(nxshot);

        /* restore header fields and write output */
        for(ix=0; ix<nxo; ix++){
                tr.ns = nz;
                tr.d1 = dz;
                tr.d2 = dx;
                tr.offset = 0;
                tr.cdp = tr.tracl = ix;
                memcpy( (void *) tr.data, (const void *) cresult[ix],nz*FSIZE);
                puttr(&tr);
        }


	return(CWP_Exit());	

}
Exemple #14
0
/*
 * Main loop for command mode command decoding.
 * A few commands are executed here, but main function
 * is to strip command addresses, do a little address oriented
 * processing and call command routines to do the real work.
 */
void
commands(bool noprompt, bool exitoneof)
{
	register line *addr;
	register int c;
	register int lchng;
	int given;
	int seensemi;
	int cnt;
	bool hadpr;

	resetflav();
	nochng();
	for (;;) {
		/*
		 * If dot at last command
		 * ended up at zero, advance to one if there is a such.
		 */
		if (dot <= zero) {
			dot = zero;
			if (dol > zero)
				dot = one;
		}
		shudclob = 0;

		/*
		 * If autoprint or trailing print flags,
		 * print the line at the specified offset
		 * before the next command.
		 */
		if (pflag ||
		    (lchng != chng && value(AUTOPRINT) && !inglobal && !inopen && endline)) {
			pflag = 0;
			nochng();
			if (dol != zero) {
				addr1 = addr2 = dot + poffset;
				if (addr1 < one || addr1 > dol)
error("Offset out-of-bounds|Offset after command too large");
				setdot1();
				goto print;
			}
		}
		nochng();

		/*
		 * Print prompt if appropriate.
		 * If not in global flush output first to prevent
		 * going into pfast mode unreasonably.
		 */
		if (inglobal == 0) {
			flush();
			if (!hush && value(PROMPT) && !globp && !noprompt && endline) {
				ex_putchar(':');
				hadpr = 1;
			}
			TSYNC();
		}

		/*
		 * Gobble up the address.
		 * Degenerate addresses yield ".".
		 */
		addr2 = 0;
		given = seensemi = 0;
		do {
			addr1 = addr2;
			addr = address(0);
			c = getcd();
			if (addr == 0) {
				if (c == ',')
					addr = dot;
				else if (addr1 != 0) {
					addr2 = dot;
					break;
				} else
					break;
			}
			addr2 = addr;
			given++;
			if (c == ';') {
				c = ',';
				dot = addr;
				seensemi = 1;
			}
		} while (c == ',');
		if (c == '%') {
			/* %: same as 1,$ */
			addr1 = one;
			addr2 = dol;
			given = 2;
			c = ex_getchar();
		}
		if (addr1 == 0)
			addr1 = addr2;
		if (c == ':')
			c = ex_getchar();

		/*
		 * Set command name for special character commands.
		 */
		tailspec(c);

		/*
		 * If called via : escape from open or visual, limit
		 * the set of available commands here to save work below.
		 */
		if (inopen) {
			if (c=='\n' || c=='\r' || c==CTRL('d') || c==EOF) {
				if (addr2)
					dot = addr2;
				if (c == EOF)
					return;
				continue;
			}
			if (any(c, "o"))
notinvis:
				tailprim(Command, 1, 1);
		}
		switch (c) {

		case 'a':

			switch(peekchar()) {
			case 'b':
/* abbreviate */
				tail("abbreviate");
				setnoaddr();
				mapcmd(0, 1);
				anyabbrs = 1;
				continue;
			case 'r':
/* args */
				tail("args");
				setnoaddr();
				eol();
				pargs();
				continue;
			}

/* append */
			if (inopen)
				goto notinvis;
			tail("append");
			setdot();
			aiflag = exclam();
			ex_newline();
			vmacchng(0);
			deletenone();
			setin(addr2);
			inappend = 1;
			ignore(append(gettty, addr2));
			inappend = 0;
			nochng();
			continue;

		case 'c':
			switch (peekchar()) {

/* copy */
			case 'o':
				tail("copy");
				vmacchng(0);
				move();
				continue;

#ifdef CHDIR
/* cd */
			case 'd':
				tail("cd");
				goto changdir;

/* chdir */
			case 'h':
				ignchar();
				if (peekchar() == 'd') {
					register char *p;
					tail2of("chdir");
changdir:
					if (savedfile[0] == '/' || !value(WARN))
						ignore(exclam());
					else
						ignore(quickly());
					if (skipend()) {
						p = getenv("HOME");
						if (p == NULL)
							error("Home directory unknown");
					} else
						getone(), p = file;
					eol();
					if (chdir(p) < 0)
						filioerr(p);
					if (savedfile[0] != '/')
						edited = 0;
					continue;
				}
				if (inopen)
					tailprim("change", 2, 1);
				tail2of("change");
				break;

#endif
			default:
				if (inopen)
					goto notinvis;
				tail("change");
				break;
			}
/* change */
			aiflag = exclam();
			setCNL();
			vmacchng(0);
			setin(addr1);
			delete(0);
			inappend = 1;
			ignore(append(gettty, addr1 - 1));
			inappend = 0;
			nochng();
			continue;

/* delete */
		case 'd':
			/*
			 * Caution: dp and dl have special meaning already.
			 */
			tail("delete");
			c = cmdreg();
			setCNL();
			vmacchng(0);
			if (c)
				YANKreg(c);
			delete(0);
			appendnone();
			continue;

/* edit */
/* ex */
		case 'e':
			tail(peekchar() == 'x' ? "ex" : "edit");
editcmd:
			if (!exclam() && chng)
				c = 'E';
			filename(c);
			if (c == 'E') {
				ungetchar(lastchar());
				ignore(quickly());
			}
			setnoaddr();
doecmd:
			init();
			addr2 = zero;
			laste++;
			ex_sync();
			rop(c);
			nochng();
			continue;

/* file */
		case 'f':
			tail("file");
			setnoaddr();
			filename(c);
			noonl();
/*
			synctmp();
*/
			continue;

/* global */
		case 'g':
			tail("global");
			global(!exclam());
			nochng();
			continue;

/* insert */
		case 'i':
			if (inopen)
				goto notinvis;
			tail("insert");
			setdot();
			nonzero();
			aiflag = exclam();
			ex_newline();
			vmacchng(0);
			deletenone();
			setin(addr2);
			inappend = 1;
			ignore(append(gettty, addr2 - 1));
			inappend = 0;
			if (dot == zero && dol > zero)
				dot = one;
			nochng();
			continue;

/* join */
		case 'j':
			tail("join");
			c = exclam();
			setcount();
			nonzero();
			ex_newline();
			vmacchng(0);
			if (given < 2 && addr2 != dol)
				addr2++;
			join(c);
			continue;

/* k */
		case 'k':
casek:
			pastwh();
			c = ex_getchar();
			if (endcmd(c))
				serror("Mark what?|%s requires following letter", Command);
			ex_newline();
			if (!islower(c))
				error("Bad mark|Mark must specify a letter");
			setdot();
			nonzero();
			names[c - 'a'] = *addr2 &~ 01;
			anymarks = 1;
			continue;

/* list */
		case 'l':
			tail("list");
			setCNL();
			ignorf(setlist(1));
			pflag = 0;
			goto print;

		case 'm':
			if (peekchar() == 'a') {
				ignchar();
				if (peekchar() == 'p') {
/* map */
					tail2of("map");
					setnoaddr();
					mapcmd(0, 0);
					continue;
				}
/* mark */
				tail2of("mark");
				goto casek;
			}
/* move */
			tail("move");
			vmacchng(0);
			move();
			continue;

		case 'n':
			if (peekchar() == 'u') {
				tail("number");
				goto numberit;
			}
/* next */
			tail("next");
			setnoaddr();
			ckaw();
			ignore(quickly());
			if (getargs())
				makargs();
			next();
			c = 'e';
			filename(c);
			goto doecmd;

/* open */
		case 'o':
			tail("open");
			oop();
			pflag = 0;
			nochng();
			continue;

		case 'p':
		case 'P':
			switch (peekchar()) {

/* put */
			case 'u':
				tail("put");
				setdot();
				c = cmdreg();
				eol();
				vmacchng(0);
				if (c)
					putreg(c);
				else
					put();
				continue;

			case 'r':
				ignchar();
				if (peekchar() == 'e') {
/* preserve */
					tail2of("preserve");
					eol();
					if (preserve() == 0)
						error("Preserve failed!");
					else
						error("File preserved.");
				}
				tail2of("print");
				break;

			default:
				tail("print");
				break;
			}
/* print */
			setCNL();
			pflag = 0;
print:
			nonzero();
			if (CL && span() > EX_LINES) {
				flush1();
				vclear();
			}
			plines(addr1, addr2, 1);
			continue;

/* quit */
		case 'q':
			tail("quit");
			setnoaddr();
			c = quickly();
			eol();
			if (!c)
quit:
				nomore();
			if (inopen) {
				vgoto(WECHO, 0);
				if (!ateopr())
					vnfl();
				else {
					tostop();
				}
				flush();
				setty(normf);
			}
			cleanup(1);
			ex_exit(0);

		case 'r':
			if (peekchar() == 'e') {
				ignchar();
				switch (peekchar()) {

/* rewind */
				case 'w':
					tail2of("rewind");
					setnoaddr();
					if (!exclam()) {
						ckaw();
						if (chng && dol > zero)
							error("No write@since last chage (:rewind! overrides)");
					}
					eol();
					erewind();
					next();
					c = 'e';
					ungetchar(lastchar());
					filename(c);
					goto doecmd;

/* recover */
				case 'c':
					tail2of("recover");
					setnoaddr();
					c = 'e';
					if (!exclam() && chng)
						c = 'E';
					filename(c);
					if (c == 'E') {
						ungetchar(lastchar());
						ignore(quickly());
					}
					init();
					addr2 = zero;
					laste++;
					ex_sync();
					recover();
					rop2();
					revocer();
					if (status == 0)
						rop3(c);
					if (dol != zero)
						change();
					nochng();
					continue;
				}
				tail2of("read");
			} else
				tail("read");
/* read */
			if (savedfile[0] == 0 && dol == zero)
				c = 'e';
			pastwh();
			vmacchng(0);
			if (peekchar() == '!') {
				setdot();
				ignchar();
				unix0(0);
				filter(0);
				continue;
			}
			filename(c);
			rop(c);
			nochng();
			if (inopen && endline && addr1 > zero && addr1 < dol)
				dot = addr1 + 1;
			continue;

		case 's':
			switch (peekchar()) {
			/*
			 * Caution: 2nd char cannot be c, g, or r
			 * because these have meaning to substitute.
			 */

/* set */
			case 'e':
				tail("set");
				setnoaddr();
				set();
				continue;

/* shell */
			case 'h':
				tail("shell");
				setNAEOL();
				vnfl();
				putpad(TE);
				flush();
				unixwt(1, unixex("-i", (char *) 0, 0, 0));
				vcontin(0);
				continue;

/* source */
			case 'o':
#ifdef notdef
				if (inopen)
					goto notinvis;
#endif
				tail("source");
				setnoaddr();
				getone();
				eol();
				source(file, 0);
				continue;
#ifdef SIGTSTP
/* stop, suspend */
			case 't':
				tail("stop");
				goto suspend;
			case 'u':
				tail("suspend");
suspend:
				if (!dosusp)
					error("Old tty driver|Not using new tty driver/shell");
				c = exclam();
				eol();
				if (!c)
					ckaw();
				onsusp(0);
				continue;
#endif

			}
			/* fall into ... */

/* & */
/* ~ */
/* substitute */
		case '&':
		case '~':
			Command = "substitute";
			if (c == 's')
				tail(Command);
			vmacchng(0);
			if (!substitute(c))
				pflag = 0;
			continue;

/* t */
		case 't':
			if (peekchar() == 'a') {
				tail("tag");
				tagfind(exclam());
				if (!inopen)
					lchng = chng - 1;
				else
					nochng();
				continue;
			}
			tail("t");
			vmacchng(0);
			move();
			continue;

		case 'u':
			if (peekchar() == 'n') {
				ignchar();
				switch(peekchar()) {
/* unmap */
				case 'm':
					tail2of("unmap");
					setnoaddr();
					mapcmd(1, 0);
					continue;
/* unabbreviate */
				case 'a':
					tail2of("unabbreviate");
					setnoaddr();
					mapcmd(1, 1);
					anyabbrs = 1;
					continue;
				}
/* undo */
				tail2of("undo");
			} else
				tail("undo");
			setnoaddr();
			markDOT();
			c = exclam();
			ex_newline();
			undo(c);
			continue;

		case 'v':
			switch (peekchar()) {

			case 'e':
/* version */
				tail("version");
				setNAEOL();
				ex_printf("@(#) Version 3.6, 11/3/80"
				    " (4.0BSD).  git "
				    "160803 14:24"
				    +5);
				noonl();
				continue;

/* visual */
			case 'i':
				tail("visual");
				if (inopen) {
					c = 'e';
					goto editcmd;
				}
				vop();
				pflag = 0;
				nochng();
				continue;
			}
/* v */
			tail("v");
			global(0);
			nochng();
			continue;

/* write */
		case 'w':
			c = peekchar();
			tail(c == 'q' ? "wq" : "write");
wq:
			if (skipwh() && peekchar() == '!') {
				pofix();
				ignchar();
				setall();
				unix0(0);
				filter(1);
			} else {
				setall();
				wop(1);
				nochng();
			}
			if (c == 'q')
				goto quit;
			continue;

/* xit */
		case 'x':
			tail("xit");
			if (!chng)
				goto quit;
			c = 'q';
			goto wq;

/* yank */
		case 'y':
			tail("yank");
			c = cmdreg();
			setcount();
			eol();
			vmacchng(0);
			if (c)
				YANKreg(c);
			else
				yank();
			continue;

/* z */
		case 'z':
			zop(0);
			pflag = 0;
			continue;

/* * */
/* @ */
		case '*':
		case '@':
			c = ex_getchar();
			if (c=='\n' || c=='\r')
				ungetchar(c);
			if (any(c, "@*\n\r"))
				c = lastmac;
			if (isupper(c))
				c = tolower(c);
			if (!islower(c))
				error("Bad register");
			ex_newline();
			setdot();
			cmdmac(c);
			continue;

/* | */
		case '|':
			endline = 0;
			goto caseline;

/* \n */
		case '\n':
			endline = 1;
caseline:
			notempty();
			if (addr2 == 0) {
				if (UP != NOSTR && c == '\n' && !inglobal)
					c = CTRL('k');
				if (inglobal)
					addr1 = addr2 = dot;
				else {
					if (dot == dol)
						error("At EOF|At end-of-file");
					addr1 = addr2 = dot + 1;
				}
			}
			setdot();
			nonzero();
			if (seensemi)
				addr1 = addr2;
			ex_getline(*addr1);
			if (c == CTRL('k')) {
				flush1();
				destline--;
				if (hadpr)
					shudclob = 1;
			}
			plines(addr1, addr2, 1);
			continue;

/* " */
		case '"':
			comment();
			continue;

/* # */
		case '#':
numberit:
			setCNL();
			ignorf(setnumb(1));
			pflag = 0;
			goto print;

/* = */
		case '=':
			ex_newline();
			setall();
			if (inglobal == 2)
				pofix();
			ex_printf("%d", lineno(addr2));
			noonl();
			continue;

/* ! */
		case '!':
			if (addr2 != 0) {
				vmacchng(0);
				unix0(0);
				setdot();
				filter(2);
			} else {
				unix0(1);
				pofix();
				putpad(TE);
				flush();
				unixwt(1, unixex("-c", uxb, 0, 0));
				vclrech(1);	/* vcontin(0); */
				nochng();
			}
			continue;

/* < */
/* > */
		case '<':
		case '>':
			for (cnt = 1; peekchar() == c; cnt++)
				ignchar();
			setCNL();
			vmacchng(0);
			shift(c, cnt);
			continue;

/* ^D */
/* EOF */
		case CTRL('d'):
		case EOF:
			if (exitoneof) {
				if (addr2 != 0)
					dot = addr2;
				return;
			}
			if (!isatty(0)) {
				if (intty)
					/*
					 * Chtty sys call at UCB may cause a
					 * input which was a tty to suddenly be
					 * turned into /dev/null.
					 */
					onhup(0);
				return;
			}
			if (addr2 != 0) {
				setlastchar('\n');
				putnl();
			}
			if (dol == zero) {
				if (addr2 == 0)
					putnl();
				notempty();
			}
			ungetchar(EOF);
			zop(hadpr);
			continue;

		default:
			if (!isalpha(c))
				break;
			ungetchar(c);
			tailprim("", 0, 0);
		}
		ierror("What?|Unknown command character '%c'", c);
	}
}
Exemple #15
0
int
main(int argc, char **argv)
{
	int nt,nx;		/* numbers of samples			*/
	float dt;		/* sampling intervals			*/
	int it,ix;		/* sample indices			*/
	int ntfft;		/* dimensions after padding for FFT	*/
	int nF;			/* transform (output) dimensions	*/
	int iF;			/* transform sample indices		*/

	register complex **ct=NULL;	/* complex FFT workspace	*/
	register float **rt=NULL;	/* float FFT workspace		*/

	int verbose;		/* flag for echoing information		*/

	char *tmpdir=NULL;	/* directory path for tmp files		*/
	cwp_Bool istmpdir=cwp_false;/* true for user-given path		*/

	float v,fv,dv;		/* phase velocity, first, step	 	*/
	float amp,oamp;		/* temp vars for amplitude spectrum	*/
	int nv,iv;		/* number of phase vels, counter	*/
	float x;		/* offset  				*/
	float omega;		/* circular frequency			*/
	float domega;		/* circular frequency spacing (from dt)	*/
	float onfft;		/* 1 / nfft				*/
	float phi;		/* omega/phase_velocity			*/
	complex *cDisp=NULL;	/* temp array for complex dispersion	*/
	float arg;		/* temp var for phase calculation	*/
	complex cExp;		/* temp vars for phase calculation	*/
	float *offs=NULL;	/* input data offsets			*/
	float fmax;		/* max freq to proc (Hz)    		*/

	int out;		/* output real or abs v(f) spectrum	*/
	int norm;		/* normalization flag			*/

	float xmax;		/* maximum abs(offset) of input		*/
	float twopi, f;		/* constant and frequency (Hz)		*/



	/* Hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(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 = ((double) intrace.dt)/ 1000000.0;
		} else { /* dt not set, exit */
			err("tr.dt not set, stop.");
		}
	}
	warn("dt=%f",dt);
	if (!getparfloat("fv",&fv))	fv   = 330;
	if (!getparfloat("dv",&dv))     dv   = 25;
	if (!getparint("nv",&nv))       nv   = 100;
	if (!getparint("out",&out))     out  = 0;
	if (!getparint("norm",&norm))   norm = 0;
	if (!getparfloat("fmax",&fmax)) fmax = 50;

	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();

	/* Set up tmpfile */
	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));
		/* 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+");
      		istmpdir=cwp_true;		
		if (verbose) warn("putting temporary files in %s", directory);
	}
	
	/* we have to allocate offs(nx) before we know nx */
	offs = alloc1float(MAX_OFFS);	

	ix = 0;
	nx = 0;
	xmax = 0.0;
	
	/* get nx and max abs(offset) */
	do { 
		++nx;
		efwrite(intrace.data, FSIZE, nt, tracefp);
		offs[ix] = intrace.offset;
		if ( abs(intrace.offset) > xmax ) xmax = abs(intrace.offset);
		++ix;
	} while (gettr(&intrace));
	
	/* confirm that offsets are set */
	if ( xmax == 0.0 ) err("tr.offset not set, stop.");


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

	/* Determine complex transform sizes */
	nF = ntfft/2+1;  /* must be this nF for fft */
        onfft = 1.0 / ntfft;
	twopi = 2.0 * PI;
	domega = twopi * onfft / dt;

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

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

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

		/* pad dimension 1 with zeros */
		for (it=nt; it<ntfft; ++it)  rt[ix][it] = 0.0;
	}
	efclose(tracefp);
	
	/* Fourier transform dimension 1 */
	pfa2rc(1,1,ntfft,nx,rt[0],ct[0]);

	/* set nF for processing */
	if (fmax == 0) { 	
		/* process to nyquist */
		nF = ntfft/2+1;
	} else {
		/* process to given fmax */
		nF = (int) (twopi * fmax / domega);
	}
	
	/* data now in (w,x) domain 
	   allocate arrays  */
	cDisp = alloc1complex(nF);	
	
	/* if requested, normalize by amplitude spectrum 
	    (normalizing by amplitude blows up aliasing and other artifacts) */			
	if (norm == 1) {
		for (iF=0; iF<nF; ++iF)  {
			/* calc this frequency */
			omega = iF * domega;
			f = omega / twopi;
			/* loop over traces */
			for (ix=0; ix<nx; ++ix) {
				/* calc amplitude at this (f,x) location */
				amp = rcabs(ct[ix][iF]);
				oamp = 1.0/amp;
				/* scale field by amp spectrum */
				ct[ix][iF] = crmul(ct[ix][iF],oamp);
			}
		}
	}
	
	/* set global output trace headers */
	outtrace.ns = 2 * nF;
	outtrace.dt = dt*1000000.;  
	outtrace.trid = FUNPACKNYQ;
	outtrace.d1 = 1.0 / (ntfft * dt); /* Hz */
	outtrace.f1 = 0;
	outtrace.d2 = dv;
	outtrace.f2 = fv;

	/* loop over phase velocities */
	for (iv=0; iv<nv; ++iv) {

		/* this velocity */
		v = fv + iv*dv;
	
		/* loop over frequencies */
		for (iF=0; iF<nF; ++iF)  {

			/* this frequency and phase */
			omega = iF * domega;
			f = omega / twopi;
			phi = omega / v;

			/* initialize */
			cDisp[iF] = cmplx(0.0,0.0);		

			/* sum over abs offset (this is ok for 3D, too) */
			for (ix=0; ix<nx; ++ix) {

				/* get this x */
				x = abs(offs[ix]);

				/* target phase */
				arg = - phi * x;
				cExp = cwp_cexp(crmul(cmplx(0.0,1.0), arg));
				
				/* phase vel profile for this frequency */				 
				cDisp[iF] = cadd(cDisp[iF],cmul(ct[ix][iF],cExp));
			}
			
		}
		
		/* set trace counter */
		outtrace.tracl = iv + 1;
			
		/* copy results to output trace 
		   interleaved format like sufft.c */
		for (iF = 0; iF < nF; ++iF) {
			outtrace.data[2*iF]   = cDisp[iF].r;
			outtrace.data[2*iF+1] = cDisp[iF].i;
		}
		
		/* output freqs at this vel */
		puttr(&outtrace);

	}  /* next frequency */
	
	
	/* Clean up */
	if (istmpdir) eremove(tracefile);
	return(CWP_Exit());
}
Exemple #16
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;
}
Exemple #17
0
int main( int argc, char *argv[] )
{
        int ntr=0;                /* number of traces                     */
        int ntrv=0;               /* number of traces                     */
	int ns=0;
	int nsv=0;
	float dt;
	float dtv;
	
	cwp_String fs;
	cwp_String fv;
	FILE *fps;
	FILE *fpv;
	FILE *headerfp;
		
	float *data;		/* data matrix of the migration volume */
	float *vel;		/* velocity matrix */
	float *velfi;		/* velocity function interpolated to ns values*/
	float *velf;		/* velocity function */
	float *vdt;
	float *ddt;
	float *ap;		/* array of apperture values in m */
	float apr;		/* array of apperture values in m */
	int *apt=NULL;		/* array of apperture time limits in mig. gath*/
	float   r;		/* maximum radius with a given apperture */
	float ir2;		/* r/d2 */
	float ir3;		/* r/d3 */
	float d2;		/* spatial sampling int. in dir 2. */
	float d3;		/* spatial sampling int. in dir 3. */
	float **mgd=NULL;	/* migration gather data */
	float *migt;		/* migrated data trace */
	int **mgdnz=NULL;		/* migration gather data non zero samples*/
	float dm;		/* migration gather spatial sample int. */
	int im;			/* number of traces in migration gather */
	int *mtnz;		/* migrated trace data non zero smaples */
	char **dummyi;		/* index array that the trace contains zeros only */
	float fac;		/* velocity scale factor */
	int sphr;		/* spherical divergence flag */
	int imt;		/* mute time sample of trace */
	float tmp;
	int imoff;
	int **igtr=NULL;
	int nigtr;
	int n2;
	int n3;

	int verbose;
	
	/* phase shift filter stuff */
        float power;            /* power of i omega applied to data     */
        float amp;              /* amplitude associated with the power  */
        float arg;              /* argument of power                    */
        float phasefac;         /* phase factor                         */
        float phase;            /* phase shift = phasefac*PI            */
        complex exparg;         /* cexp(I arg)                          */
        register float *rt;     /* real trace                           */
        register complex *ct;   /* complex transformed trace            */
        complex *filt;          /* complex power                        */
        float omega;            /* circular frequency                   */
        float domega;           /* circular frequency spacing (from dt) */
        float sign;             /* sign in front of i*omega default -1  */
        int nfft;               /* number of points in nfft             */
        int nf;                 /* number of frequencies (incl Nyq)     */
        float onfft;            /* 1 / nfft                             */
        size_t nzeros;          /* number of padded zeroes in bytes     */
	
	initargs(argc, argv);
   	requestdoc(1);
	
        MUSTGETPARSTRING("fs",&fs);
        MUSTGETPARSTRING("fv",&fv);
        MUSTGETPARINT("n2",&n2);
        MUSTGETPARINT("n3",&n3);
        MUSTGETPARFLOAT("d2",&d2);
        MUSTGETPARFLOAT("d3",&d3);
	
	if (!getparfloat("dm", &dm))	dm=(d2+d3)/2.0;
	
	/* open datafile */
        fps = efopen(fs,"r");
	fpv = efopen(fv,"r");
	
	/* Open tmpfile for headers */
	headerfp = etmpfile();

	/* get information from the first data trace */
	ntr = fgettra(fps,&tr,0);
	if(n2*n3!=ntr) err(" Number of traces in file %d not equal to n2*n3 %d \n",
			     ntr,n2*n3);
	ns=tr.ns;
	if (!getparfloat("dt", &dt))	dt = ((float) tr.dt)/1000000.0;
	if (!dt) {
		dt = .002;
		warn("dt not set, assumed to be .002");
	}

	/* get information from the first velocity trace */
	ntrv = fgettra(fpv,&trv,0);
	if(ntrv!=ntr) err(" Number of traces in velocity file %d differ from %d \n",
			     ntrv,ntr);
	nsv=trv.ns;
	if (!getparfloat("dtv", &dtv))	dtv = ((float) trv.dt)/1000000.0;
	if (!dtv) {
		dtv = .002;
		warn("dtv not set, assumed to be .002 for velocity");
	}
	
	if (!getparfloat("fac", &fac))	fac=2.0;
	if (!getparint("verbose", &verbose))	verbose=0;
	if (!getparint("sphr", &sphr))	sphr=0;
	
	if (!getparfloat("apr", &apr))	apr=75;
	apr*=3.141592653/180;

	/* allocate arrays */
	data = bmalloc(sizeof(float),ns,ntr);
	vel = bmalloc(sizeof(float),nsv,ntr);
	velf = ealloc1float(nsv); 
	velfi = ealloc1float(ns);
	migt = ealloc1float(ns);
	vdt = ealloc1float(nsv);
	ddt = ealloc1float(ns);
	ap = ealloc1float(ns);
	mtnz = ealloc1int(ns);
	dummyi = (char **) ealloc2(n2,n3,sizeof(char));
	
	/* Times to do interpolation of velocity from sparse sampling */
	/* to fine sampling of the data */
	{ register int it;
		for(it=0;it<nsv;it++) vdt[it]=it*dtv;
		for(it=0;it<ns;it++)  ddt[it]=it*dt;
	}
	
	/* Read traces into data */
        /* Store headers in tmpfile */
        ntr=0;
	erewind(fps);
	erewind(fpv);
		
	{ register int i2,i3;
	for(i3=0;i3<n3;i3++) 
		for(i2=0;i2<n2;i2++) {
			fgettr(fps,&tr);
			fgettr(fpv,&trv);
			if(tr.trid > 2) dummyi[i3][i2]=1;
			else dummyi[i3][i2]=0;	
			efwrite(&tr, 1, HDRBYTES, headerfp);
		 	bmwrite(data,1,0,i3*n2+i2,ns,tr.data);
		 	bmwrite(vel,1,0,i3*n2+i2,nsv,trv.data);
		}
	erewind(headerfp);

	/* set up the phase filter */
	power = 1.0;sign = 1.0;phasefac = 0.5;
	phase = phasefac * PI;
         
	/* Set up for fft */
        nfft = npfaro(ns, LOOKFAC * ns);
        if (nfft >= SU_NFLTS || nfft >= PFA_MAX)
                err("Padded nt=%d -- too big", nfft);

        nf = nfft/2 + 1;
        onfft = 1.0 / nfft;
        nzeros = (nfft - ns) * FSIZE;
        domega = TWOPI * onfft / dt;
        
	/* Allocate fft arrays */
        rt   = ealloc1float(nfft);
        ct   = ealloc1complex(nf);
        filt = ealloc1complex(nf);
        
	/* Set up args for complex power evaluation */
        arg = sign * PIBY2 * power + phase;
        exparg = cexp(crmul(I, arg));
        {       
		register int i;
                for (i = 0 ; i < nf; ++i) {

                        omega = i * domega;
		
		        /* kludge to handle omega=0 case for power < 0 */
                        if (power < 0 && i == 0) omega = FLT_MAX;

                        /* calculate filter */
                        amp = pow(omega, power) * onfft;
			filt[i] = crmul(exparg, amp);
                }
        }
	
	/* set up constants for migration */ 
	if(verbose) fprintf(stderr," Setting up constants....\n");
	r=0;
	for(i3=0;i3<n3;i3++) 
	    for(i2=0;i2<n2;i2++) {
		if(dummyi[i3][i2] < 1) {
			
			/* get the velocity function */
			bmread(vel,1,0,i3*n2+i2,nsv,velf);
			
			/* linear interpolation from nsv to ns values */  
			intlin(nsv,vdt,velf,velf[0],velf[nsv-1],ns,ddt,velfi);
			
			/* Apply scale factor to velocity */
			{ register int it;
				for(it=0;it<ns;it++) velfi[it] *=fac;
			}
			
			/* compute maximum radius from apperture and velocity */
			{ register int it;
				for(it=0;it<ns;it++) 
				ap[it] = ddt[it]*velfi[it]*tan(apr)/2.0;
			}
			tmp = ap[isamax(ns,ap,1)];
			if(tmp>r) r=tmp;
		}
	}
	r=MIN(r,sqrt(SQR((n2-1)*d2)+SQR((n3-1)*d3)));
	ir2 =  (int)(2*r/d2)+1;
	ir3 =  (int)(2*r/d3)+1;
	im = (int)(r/dm)+1;
		
	/*  allocate migration gather */
	mgd = ealloc2float(ns,im);
	mgdnz = ealloc2int(ns,im);
	apt = ealloc1int(im);
	/* set up the stencil for selecting traces */
	igtr = ealloc2int(ir2*ir3,2);
	stncl(r, d2, d3,igtr,&nigtr);
	
	if(verbose) {
		fprintf(stderr," Maximum radius %f\n",r);
		fprintf(stderr," Maximum offset %f\n",
			sqrt(SQR((n2-1)*d2)+SQR((n3-1)*d3)));
	}

	/* main processing loop */
	for(i3=0;i3<n3;i3++) 
	    for(i2=0;i2<n2;i2++) {
		memset( (void *) tr.data, (int) '\0',ns*FSIZE);
		if(dummyi[i3][i2] < 1) {
			memset( (void *) mgd[0], (int) '\0',ns*im*FSIZE);
			memset( (void *) mgdnz[0], (int) '\0',ns*im*ISIZE);
			/* get the velocity function */
			bmread(vel,1,0,i3*n2+i2,nsv,velf);
		
			/* linear interpolation from nsv to ns values */  
			intlin(nsv,vdt,velf,velf[0],velf[nsv-1],ns,ddt,velfi);
		
			/* Apply scale factor to velocity */
			{ register int it;
				for(it=0;it<ns;it++) velfi[it] *=fac;
			}

			/* create the migration gather */
			{ register int itr,ist2,ist3;
				for(itr=0;itr<nigtr;itr++) {
					ist2=i2+igtr[0][itr];
					ist3=i3+igtr[1][itr];
					if(ist2 >= 0 && ist2 <n2) 
						if(ist3 >= 0 && ist3 <n3) {
							if(dummyi[ist3][ist2] <1) {
								imoff = (int) ( 
								sqrt(SQR(igtr[0][itr]*d2)
							     	    +SQR(igtr[1][itr]*d3))/dm+0.5);
								bmread(data,1,0,ist3*n2+ist2,ns,tr.data);
								imoff=MIN(imoff,im-1);
								{ register int it;									
									/* get the mute time for this 
									  offset, apperture and velocity */
									xindex(ns,ap,imoff*dm,&imt);
									for(it=imt;it<ns;it++)
										if(tr.data[it]!=0) {
											mgd[imoff][it]+=tr.data[it];
											mgdnz[imoff][it]+=1;
									}	
								}
							}
						}
				}
			}

			/* normalize the gather */
				{ register int ix,it;
				for(ix=0;ix<im;ix++)
					for(it=0;it<ns;it++) 
						if(mgdnz[ix][it] > 1) mgd[ix][it] /=(float) mgdnz[ix][it];
			}
			memset( (void *) tr.data, (int) '\0',ns*FSIZE);
			memset( (void *) mtnz, (int) '\0',ns*ISIZE);
		
			/* do a knmo */
			{ register int ix,it;
				for(ix=0;ix<im;ix++) {
					/* get the mute time for this 
					offset, apperture and velocity */
					xindex(ns,ap,ix*dm,&imt);
					knmo(mgd[ix],migt,ns,velfi,0,ix*dm,dt,imt,sphr);
					/* stack the gather */
						for(it=0;it<ns;it++) { 
						if(migt[it]!=0.0) { 
								tr.data[it] += migt[it];
								mtnz[it]++;
						}
/*						tr.data[it] += mgd[ix][it]; */
					}
				}

			}
			{ register int it;
				for(it=0;it<ns;it++) 
					if(mtnz[it]>1) tr.data[it] /=(float)mtnz[it];
			}
		
			/*Do the phase filtering before the trace is released*/
                	/* Load trace into rt (zero-padded) */
               		memcpy( (void *) rt, (const void *) tr.data, ns*FSIZE);
               		memset((void *) (rt + ns), (int) '\0', nzeros);

         		pfarc(1, nfft, rt, ct);
        		{ register int i;
        			for (i = 0; i < nf; ++i)  ct[i] = cmul(ct[i], filt[i]);
        		}
         		pfacr(-1, nfft, ct, rt);
     			memcpy( (void *) tr.data, (const void *) rt, ns*FSIZE);
			
		} /* end of dummy if */
		/* spit out the gather */
		efread(&tr, 1, HDRBYTES, headerfp);
		puttr(&tr);
		if(verbose) fprintf(stderr," %d %d\n",i2,i3);
	    }   /* end of i2 loop */
	}	/* end of i3 loop */
	/* This should be the last thing */
	efclose(headerfp);
	/* Free memory */
	free2int(igtr);
	free2float(mgd);
	free2int(mgdnz);
	free1int(apt);
	bmfree(data);
	bmfree(vel);
	free1float(velfi);
	free1float(velf);
	free1float(ddt);
	free1float(vdt);
	free1float(ap);
	free1int(mtnz);
	free1float(migt);
	free1float(rt);
	free1complex(ct);
	free1complex(filt);
	free2((void **) dummyi);
	
	return EXIT_SUCCESS;
}
Exemple #18
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()) ;
}
Exemple #19
0
int
main(int argc, char **argv)
{
	FILE *headerfp=NULL;	/* temporary file for trace header	*/
				/*  ... (1st trace of ensemble);	*/
	char *key=NULL;		/* header key word from segy.h		*/
	char *type=NULL;	/* ... its type				*/
	int index;		/* ... its index			*/
	Value val;		/* ... its value			*/
	float fval = 0;		/* ... its value cast to float		*/
	float prevfval;		/* ... its value of the previous trace	*/

	complex *ct=NULL;	/* complex trace			*/
	complex *psct=NULL;	/* phase-stack data array		*/

	float *data=NULL;	/* input data array			*/
	float *hdata=NULL;	/* array of Hilbert transformed input data */
	float *stdata=NULL;	/* stacked data ("ordinary" stack)	*/
	float *psdata;	/* phase-stack data array (real weights for PWS)*/
	float a;	/* inst. amplitude				*/
	float dt;	/* time sample spacing in seconds		*/
	float pwr;	/* raise  phase stack to power pwr		*/
	float sl;	/* smoothing window length in seconds		*/

	int gottrace;	/* flag: set to 1, if trace is read from stdin	*/

	int i;		/* loop index					*/
	int isl;	/* smoothing window length in samples		*/
	int nt;		/* number of points on input trace		*/
	int ntr;	/* trace counter				*/
	int ps;		/* flag: output is PWS (0) or phase stack (1)	*/
	int verbose;	/* verbose flag					*/

	cwp_Bool pws_and_cdp=cwp_false;	/* are PWS and CDP set?		*/

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

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

	/* Get parameters */
	if (!getparstring("key", &key))			key="cdp";
	if (!getparfloat("pwr", &pwr))			pwr = 1.0;
	if (!getparfloat("dt", &dt)) dt = ((double) intr.dt)/1000000.0;
	if (!getparfloat("sl", &sl))			sl = 0.0;
	if (!getparint("ps", &ps))			ps = 0;
	if (!getparint("verbose", &verbose))		verbose = 0;

	if (STREQ(key, "cdp") &&  !(ps))
		pws_and_cdp = cwp_true;

	/* convert seconds to samples (necessary only for smoothing) */
	if (!dt) {
		dt = 0.004;
		warn("dt not set, assuming dt=0.004");
	}

	/* integerized smoothing window length */
	isl = NINT(fabs(sl)/dt);
	if (isl>nt)
		err("sl=%g too long for trace", fabs(sl));

	/* diagnostic print */
	if (verbose && isl)
		warn("smoothing window = %d samples", isl);

	/* initialize flag */
	gottrace = 1;

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

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

	/* remember previous value of key */
	prevfval = fval;

	/* allocate space for data, hilbert transformed data, */
	/* phase-stacked data and complex trace */
	data = ealloc1float(nt);
	hdata = ealloc1float(nt);
	stdata = ealloc1float(nt);
	psdata = ealloc1float(nt);
	psct = ealloc1complex(nt);
	ct = ealloc1complex(nt);


	/* zero out accumulators */
	memset( (void *) stdata, 0, nt*FSIZE);
	memset( (void *) psct, 0, nt*(sizeof(complex)));


	/* open temporary file for trace header   */
	headerfp = etmpfile();

	/* store trace header in temporary file and read data */
	efwrite(&intr, HDRBYTES, 1, headerfp);

	/* loop over input traces */
	ntr=0;
	while (gottrace|(~gottrace) ) { /* middle exit loop */

		/* if got a trace */
		if (gottrace) {
			/* get value of key */
			gethval(&intr, index, &val);
			fval = vtof(type,val);

			/* get data */
			memcpy((void *) data, (const void *) intr.data,
					nt*FSIZE);
		}

		/* construct quadrature trace with hilbert transform */
		hilbert(nt, data, hdata);

		/* build the complex trace and get rid of amplitude */
		for (i=0; i<nt; i++) {
			ct[i] = cmplx(data[i],hdata[i]);
			a = (rcabs(ct[i])) ? 1.0 / rcabs(ct[i]) : 0.0;
			ct[i] = crmul(ct[i], a);
		}

		/* stacking */
		if (fval==prevfval && gottrace) {
			++ntr;
			for (i=0; i<nt; ++i) {
				stdata[i] += data[i];
				psct[i] = cadd(psct[i],ct[i]);
			}
		}

		/* if key-value has changed or no more input traces */
		if (fval!=prevfval || !gottrace) {

			/* diagnostic print */
			if (verbose)
				warn("%s=%g, fold=%d\n", key, prevfval, ntr);

			/* convert complex phase stack to real weights */
			for (i=0; i<nt; ++i) {
				psdata[i] = rcabs(psct[i]) / (float) ntr;
				psdata[i] = pow(psdata[i], pwr);
			}

			/* smooth phase-stack (weights) */
			if (isl) do_smooth(psdata,nt,isl);

			/* apply weights to "ordinary" stack (do PWS) */
			if (!ps) {
				for (i=0; i<nt; ++i) {
					stdata[i] *= psdata[i] / (float) ntr;
				}
			}

			/* set header and write PS trace or */
			/* PWS trace to stdout */
			erewind(headerfp);
			efread(&outtr, 1, HDRBYTES, headerfp);
			outtr.nhs=ntr;
			if (ps) {
				memcpy((void *) outtr.data,
					(const void *) psdata, nt*FSIZE);
			} else {
				memcpy((void *) outtr.data,
					(const void *) stdata, nt*FSIZE);
			}

			/* zero offset field if a pws and cdp stack */
			if (pws_and_cdp) outtr.offset = 0;

			puttr(&outtr);

			/* if no more input traces, break input trace loop* */
			if (!gottrace) break;


			/* remember previous value of key */
			prevfval = fval;

			/* zero out accumulators */
			ntr=0;
			memset( (void *) stdata, 0, nt*FSIZE);
			memset( (void *) psct, 0, nt*(sizeof(complex)));

			/* stacking */
			if (gottrace) {
				++ntr;
				for (i=0; i<nt; ++i) {
					stdata[i] += data[i];
					psct[i] = cadd(psct[i],ct[i]);
				}
			}

			/* save trace header for output trace */
			erewind(headerfp);
			efwrite(&intr, HDRBYTES, 1, headerfp);
		}

		/* get next trace (if there is one) */
		if (!gettr(&intr)) gottrace = 0;

	} /* end loop over traces */

	return(CWP_Exit());
}
Exemple #20
0
/*
 * Main procedure.  Process arguments and then
 * transfer control to the main command processing loop
 * in the routine commands.  We are entered as either "ex", "edit" or "vi"
 * and the distinction is made here.  Actually, we are "vi" if
 * there is a 'v' in our name, and "edit" if there is a 'd' in our
 * name.  For edit we just diddle options; for vi we actually
 * force an early visual command, setting the external initev so
 * the q command in visual doesn't give command mode.
 */
int
main(int ac, char **av)
{
#if 0
	char *erpath = EXSTRINGS;
#endif
	register char *cp;
	register int c;
	bool recov = 0;
	bool ivis = any('v', av[0]);
	bool itag = 0;
	bool fast = 0;
#ifdef TRACE
	register char *tracef;
#endif

	/*
	 * Immediately grab the tty modes so that we wont
	 * get messed up if an interrupt comes in quickly.
	 */
	gTTY(1);
	normf = tty;

#if 0
	/*
	 * For debugging take files out of . if name is a.out.
	 * If a 'd' in our name, then set options for edit.
	 */
	if (av[0][0] == 'a')
		erpath += 9;
#endif
	if (ivis) {
		options[MAGIC].odefault = value(MAGIC) = 0;
		options[BEAUTIFY].odefault = value(BEAUTIFY) = 1;
	} else if (any('d', av[0])) {
		value(OPEN) = 0;
		value(REPORT) = 1;
		value(MAGIC) = 0;
	}

	/*
	 * Open the error message file.
	 */
	draino();
#if 0
	erfile = open(erpath, 0);
	if (erfile < 0) {
		flush();
		exit(1);
	}
#endif
	pstop();

	/*
	 * Initialize interrupt handling.
	 */
	oldhup = signal(SIGHUP, SIG_IGN);
	if (oldhup == SIG_DFL)
		signal(SIGHUP, onhup);
	oldquit = signal(SIGQUIT, SIG_IGN);
	ruptible = signal(SIGINT, SIG_IGN) == SIG_DFL;
	if (signal(SIGTERM, SIG_IGN) == SIG_DFL)
		signal(SIGTERM, onhup);

	/*
	 * Initialize end of core pointers.
	 * Normally we avoid breaking back to fendcore after each
	 * file since this can be expensive (much core-core copying).
	 * If your system can scatter load processes you could do
	 * this as ed does, saving a little core, but it will probably
	 * not often make much difference.
	 */
#ifdef UNIX_SBRK
	fendcore = (line *) sbrk(0);
	endcore = fendcore - 2;
#else
# define LINELIMIT 0x8000
	fendcore = malloc(LINELIMIT * sizeof(line *));
	endcore = fendcore + LINELIMIT - 1;
#endif

	/*
	 * Process flag arguments.
	 */
	ac--, av++;
	while (ac && av[0][0] == '-') {
		c = av[0][1];
		if (c == 0) {
			hush = 1;
			value(AUTOPRINT) = 0;
			fast++;
		} else switch (c) {

#ifdef TRACE
		case 'T':
			if (av[0][2] == 0)
				tracef = "trace";
			else {
				tracef = tttrace;
				tracef[8] = av[0][2];
				if (tracef[8])
					tracef[9] = av[0][3];
				else
					tracef[9] = 0;
			}
			trace = fopen(tracef, "w");
			if (trace == NULL)
				ex_printf("Trace create error\n");
			setbuf(trace, tracbuf);
			break;

#endif

#ifdef LISP
		case 'l':
			value(LISP) = 1;
			value(SHOWMATCH) = 1;
			break;
#endif

		case 'r':
			recov++;
			break;

		case 't':
			if (ac > 1 && av[1][0] != '-') {
				ac--, av++;
				itag = 1;
				/* BUG: should check for too long tag. */
				CP(lasttag, av[0]);
			}
			break;

		case 'v':
			globp = "";
			ivis = 1;
			break;

		default:
			smerror("Unknown option %s\n", av[0]);
			break;
		}
		ac--, av++;
	}
	if (ac && av[0][0] == '+') {
		firstln = getn(av[0] + 1);
		if (firstln == 0)
			firstln = 20000;
		ac--, av++;
	}

	/*
	 * If we are doing a recover and no filename
	 * was given, then execute an exrecover command with
	 * the -r option to type out the list of saved file names.
	 * Otherwise set the remembered file name to the first argument
	 * file name so the "recover" initial command will find it.
	 */
	if (recov) {
		if (ac == 0) {
			die++;
			setrupt();
			execl(EXRECOVER, "exrecover", "-r", NULL);
			filioerr(EXRECOVER);
			exit(1);
		}
		CP(savedfile, *av);
		av++, ac--;
	}

	/*
	 * Initialize the argument list.
	 */
	argv0 = av;
	argc0 = ac;
	args0 = av[0];
	erewind();

	/*
	 * Initialize a temporary file (buffer) and
	 * set up terminal environment.  Read user startup commands.
	 */
	init();
	if (setexit() == 0) {
		setrupt();
		intty = isatty(0);
		if (fast || !intty)
			setterm("dumb");
		else {
			gettmode();
			if ((cp = getenv("TERM")) != 0)
				setterm(cp);
			if ((cp = getenv("HOME")) != 0)
				source(strcat(strcpy(genbuf, cp), "/.exrc"), 1);
		}
	}

	/*
	 * Initial processing.  Handle tag, recover, and file argument
	 * implied next commands.  If going in as 'vi', then don't do
	 * anything, just set initev so we will do it later (from within
	 * visual).
	 */
	if (setexit() == 0) {
		if (recov)
			globp = "recover";
		else if (itag)
			globp = ivis ? "tag" : "tag|p";
		else if (argc)
			globp = "next";
		if (ivis)
			initev = globp;
		else if (globp) {
			inglobal = 1;
			commands(1, 1);
			inglobal = 0;
		}
	}

	/*
	 * Vi command... go into visual.
	 * Strange... everything in vi usually happens
	 * before we ever "start".
	 */
	if (ivis) {
		/*
		 * Don't have to be upward compatible with stupidity
		 * of starting editing at line $.
		 */
		if (dol > zero)
			dot = one;
		globp = "visual";
		if (setexit() == 0)
			commands(1, 1);
	}

	/*
	 * Clear out trash in state accumulated by startup,
	 * and then do the main command loop for a normal edit.
	 * If you quit out of a 'vi' command by doing Q or ^\,
	 * you also fall through to here.
	 */
	ungetchar(0);
	globp = 0;
	initev = 0;
	setlastchar('\n');
	setexit();
	commands(0, 0);
	cleanup(1);
	return 0;
}
Exemple #21
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 dx;	/* cdp sampling interval */
	int nx;		/* number of cdps to process */
	int nxfft;	/* number of cdps after zero padding for fft */
	int nxpad;	/* minimum number of cdps for zero padding */
	int ix;		/* cdp index, starting with ix=0 */
	int noffmix;	/* number of offsets to mix */
	float *tdmo;	/* times at which rms velocities are specified */
	float *vdmo;	/* rms velocities at times specified in tdmo */
	float sdmo;	/* DMO stretch factor */
	int ntdmo;	/* number tnmo values specified */
	int itdmo;	/* index into tnmo array */
	int nvdmo;	/* number vnmo values specified */
	float fmax;	/* maximum frequency */
	float *vrms;	/* uniformly sampled vrms(t) */
	float **p;	/* traces for one offset - common-offset gather */
	float **q;	/* DMO-corrected and mixed traces to be output */
	float offset;	/* source-receiver offset of current trace */
	float oldoffset;/* offset of previous trace */
	int noff;	/* number of offsets processed in current mix */
	int ntrace;	/* number of traces processed in current mix */
	int itrace;	/* trace index */
	int gottrace;	/* non-zero if an input trace was read */
	int done;	/* non-zero if done */
	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;
	offset = tr.offset;

	/* get parameters */
	if (!getparint("cdpmin",&cdpmin)) err("must specify cdpmin");
	if (!getparint("cdpmax",&cdpmax)) err("must specify cdpmax");
	if (cdpmin>cdpmax) err("cdpmin must not be greater than cdpmax");
	if (!getparfloat("dxcdp",&dx)) err("must specify dxcdp");
	if (!getparint("noffmix",&noffmix)) err("must specify noffmix");
	ntdmo = countparval("tdmo");
	if (ntdmo==0) ntdmo = 1;
	tdmo = ealloc1float(ntdmo);
	if (!getparfloat("tdmo",tdmo)) tdmo[0] = 0.0;
	nvdmo = countparval("vdmo");
	if (nvdmo==0) nvdmo = 1;
	if (nvdmo!=ntdmo) err("number of tdmo and vdmo must be equal");
	vdmo = ealloc1float(nvdmo);
	if (!getparfloat("vdmo",vdmo)) vdmo[0] = 1500.0;
	for (itdmo=1; itdmo<ntdmo; ++itdmo)
		if (tdmo[itdmo]<=tdmo[itdmo-1])
			err("tdmo must increase monotonically");
	if (!getparfloat("sdmo",&sdmo)) sdmo = 1.0;
	if (!getparfloat("fmax",&fmax)) fmax = 0.5/dt;
	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);
	
	/* make uniformly sampled rms velocity function of time */
	vrms = ealloc1float(nt);
	mkvrms(ntdmo,tdmo,vdmo,nt,dt,ft,vrms);
	
	/* determine number of cdps to process */
	nx = cdpmax-cdpmin+1;
	
	/* allocate and zero common-offset gather p(t,x) */
	nxpad = 0.5*ABS(offset/dx);
	nxfft = npfar(nx+nxpad);
	p = ealloc2float(nt,nxfft+2);
	for (ix=0; ix<nxfft; ++ix)
		for (it=0; it<nt; ++it)
			p[ix][it] = 0.0;

	/* allocate and zero offset mix accumulator q(t,x) */
	q = ealloc2float(nt,nx);
	for (ix=0; ix<nx; ++ix)
		for (it=0; it<nt; ++it)
			q[ix][it] = 0.0;
		
	/* 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 = offset;
	gottrace = 1;
	done = 0;
	ntrace = 0;
	noff = 0;

	/* loop over traces */
	do {
		/* if got a trace, determine offset */
		if (gottrace) offset = tr.offset;
		
		/* if an offset is complete */
		if ((gottrace && offset!=oldoffset) || !gottrace) {
		
			/* do dmo for old common-offset gather */
			dmooff(oldoffset,fmax,sdmo,nx,dx,nt,dt,ft,vrms,p);
			
			/* add dmo-corrected traces to mix */
			for (ix=0; ix<nx; ++ix)
				for (it=0; it<nt; ++it)
					q[ix][it] += p[ix][it];
			
			/* count offsets in mix */
			noff++;
							
			/* free space for old common-offset gather */
			free2float(p);
			
			/* if beginning a new offset */
			if (offset!=oldoffset) {
				
				/* allocate space for new offset */
				nxpad = 0.5*ABS(offset/dx);
				nxfft = npfar(nx+nxpad);
				p = ealloc2float(nt,nxfft+2);
				for (ix=0; ix<nxfft; ++ix)
					for (it=0; it<nt; ++it)
						p[ix][it] = 0.0;
			}
		}
		
		/* if a mix of offsets is complete */
		if (noff==noffmix || !gottrace) {
			
			/* 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);
				
				/* get dmo-corrected data */
				memcpy( (void *) tro.data,
					(const void *)	q[tro.cdp-cdpmin],
					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 in mix */
			noff = 0;
			ntrace = 0;
			
			/* zero offset mix accumulator */
			for (ix=0; ix<nx; ++ix)
				for (it=0; it<nt; ++it)
					q[ix][it] = 0.0;
		}
			
		/* if cdp is within range to process */
		if (tr.cdp>=cdpmin && tr.cdp<=cdpmax) {
	
			/* save trace header and update number of traces */
			efwrite(&tr,HDRBYTES,1,headerfp);
			ntrace++;

			/* remember offset */
			oldoffset = offset;

			/* get trace samples */
			memcpy( (void *) p[tr.cdp-cdpmin],
				   (const void *) tr.data, nt*sizeof(float));
		}

		/* 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());
}