Esempio n. 1
0
int
main(int argc, char **argv)
{
	FILE *fp;
	int fd,j=0,verbose;

	initargs(argc,argv);
	requestdoc(1);

	if(!getparint("fd",&fd)) fd=-1;
	if(!getparint("verbose",&verbose)) verbose=0; 
	warn("File descriptor passed to suget = %d",fd);
	if( (fp = (FILE *) fdopen(fd,"r"))==NULL) err("Bad file descriptor");
	warn("About to read first trace");
	if(!fgettr(fp,&tr)) err("Can't get first trace");

	do{
		if(verbose>0){
			warn("read trace %d",j);
			j++;
		}

		puttr(&tr);

	} while(fgettr(fp,&tr));

	return(CWP_Exit());
}
Esempio n. 2
0
int fgettra(FILE *fp, segy *tp, int itr)
{
	int nread;
	if(lastfp != fp)  searchlist(fp);  /* search for match */
		
	
	if(infoptr == (struct insegyinfo *) NULL) {
		/* get first trace */
		if(0 >= fgettr(fp, tp)) return(0); /* error return */

		switch(infoptr->ftype) {
		case TTY:
			warn("stdin not redirected");
		break;
		case DISK:	/* correct */
		break;
		default:
			err("%s: input must be disk file",__FILE__);
		}
	


		efseeko(fp,(off_t) 0LL,SEEK_END);
		if( in_line_hdr ){
			infoptr->ntr = (off_t)((eftello(fp)-3600)/infoptr->nsegy);
			efseeko(fp, (off_t) 3600+infoptr->nsegy,SEEK_SET);
		}else{
			infoptr->ntr = (off_t)(eftello(fp)/infoptr->nsegy);
			efseeko(fp, (off_t) infoptr->nsegy,SEEK_SET);
		}
	} /* end first entry initialization */
	
	/* Check on requested trace number */
	if(itr >= infoptr->ntr)
		err("%s: trying to read off end of file",__FILE__);
	
	/* Position file pointer at start of requested trace */
	if( in_line_hdr ){
		efseeko(fp, (off_t) 3600+itr*infoptr->nsegy,SEEK_SET);
	}else{
		efseeko(fp, (off_t) itr*infoptr->nsegy,SEEK_SET);
	}
	
	nread=fgettr(fp, tp); /* let fgettr do the work */
	if(nread != infoptr->nsegy)
		err("%s: read %d bytes in trace of %d bytes",
		    __FILE__,nread,infoptr->nsegy);
	
	if(tp->ns != infoptr->nsfirst)
		warn("%s: header ns field = %d differs from first trace = %d",
		     __FILE__,tp->ns,infoptr->nsfirst);
	
	return(infoptr->ntr);
}
Esempio n. 3
0
void readhead(FILE *infp, segytrace tr1, int ixx, int iyy,
	int nx, int ny, int nsegy) {
	long ltmp;
	ltmp  = (iyy*nx+ixx)*nsegy+3600;
	fseek2g(infp,ltmp,0);
	fgettr(infp,&tr1);
}
Esempio n. 4
0
main(int argc, char **argv)
{

	segytrace tr;

	FILE *infp=stdin, *outfp=stdout;
	int it, nt;
	float *im, tmp1, tmp2, i0;


    	/* get parameters */
    	initargs(argc,argv);
    	askdoc(1);

	if(!getparfloat("i0",&i0)) err("must specify i0");

	/* large file(s) */
	file2g(infp);
	file2g(outfp);
	
        if (!fgettr(infp,&tr))  err("can't get first trace");
	nt = tr.ns;

	im = (float*) emalloc(nt*sizeof(float));

	do {
		im[0] = i0;
		for(it=1;it<nt;it++) {
			tmp1 = 1. - tr.data[it-1];
			tmp2 = 1. + tr.data[it-1];
			if(tmp1==0.) {
				im[it] = im[it-1];
			} else {
				im[it] = tmp2/tmp1*im[it-1];
			}
		}
		for(it=0;it<nt;it++) tr.data[it] = im[it];
		fputtr(outfp,&tr);
	} while(fgettr(infp,&tr));

	return 0;

}
Esempio n. 5
0
void readdata(FILE *infp, float *data, segytrace tr1, 
	int *jy, int iy, int ny, int nt, int nx, int hy, int nycore) {

	
	long ltmp;
	int i3, i2, i1, iyy, iread, i11;

	iyy = *jy; 
	iread = 0;
	if(*jy==-1) {
		iyy = iy - hy;
		if(iyy<0) iyy = 0;
		iread = 1;
	} else if( (*jy>(iy-hy) && iy>=hy)  
		|| (*jy+nycore)<(iy+hy) && (iy+hy)<ny ) {
		iyy = iy - hy; 
		if(iyy<0) iyy = 0;
		iread = 1;
	}
	*jy = iyy;
	if(iread==1) {
		ltmp = iyy*nx*(nt*4+240);
		ltmp = ltmp + 3600;
		fseek2g(infp,ltmp,0);
		for(i3=0;i3<nycore;i3++) {
			for(i2=0;i2<nx;i2++) {
				i11 = (i3*nx+i2)*nt;
				fgettr(infp,&tr1);
				for(i1=0;i1<nt;i1++) {
					data[i1+i11] = tr1.data[i1];
				}
			}
		}
		iread = 0;
	}
	
}
Esempio n. 6
0
/*                                              September 1995  */
#include "stratInv.h"
segy tr;		        /* reading data */
void inputData(char* dataFile)
{
   /* declaration of variables */
   int iS, iR, iF, iF1, iF2;    /* generic counters */
   int ns;			/* # of samples */
   int wL;                      /* window length */
   float *buffer = NULL;	/* to input data */
   float window;                /* windowing purposes */
   complex *bufferC = NULL;	/* to Fourier transform the input data */
   FILE *fp;			/* input file */

   /* memory for bufferC */
   bufferC = alloc1complex(info->nSamples / 2 + 1);
   
   fp = fopen(dataFile,"r");
   if (fp == NULL)
      err("Can't open input data file!\n");

   for (iR = 0; iR < info->nR; iR++)
   {
      fgettr(fp, &tr);
      ns = tr.ns;
      /* DD 
      fprintf(stderr, "ns %d\n", ns);*/

      /* allocating memory */
      if (iR == 0) buffer = alloc1float(MAX(ns, info->nSamples));

      /* reseting */
      for (iS = 0; iS < MAX(ns, info->nSamples); iS++) buffer[iS] = 0;
      memcpy(buffer, tr.data, ns * FSIZE);
      
      /* buffer -> dataObs and compensating for complex frequency */
      for (iS = 0; iS < info->nSamples; iS++)
      {
	 buffer[iS] *= exp(-info->tau * iS * dt);
	 /* DD 
	 fprintf(stderr, "buffer[%d] : %f\n", iS, buffer[iS]);*/
      }

      /* going to the Fourier domain */
      pfarc(-1, info->nSamples, buffer, bufferC);
      
      /* windowing (PERC_WINDOW) spectrum */
      iF1 = NINT(info->f1 / info->dF);
      iF2 = NINT(info->f2 / info->dF);
      wL = info->nF * PERC_WINDOW / 2;
      wL = 2 * wL + 1;
      for (iS = 0, iF = 0; iF < info->nSamples / 2 + 1; iF++)
      {
	 window = 0;
	 if (iF < iF1 || iF >= iF2)
	 {
	    bufferC[iF] = cmplx(0, 0);
	 }
	 else if (iF - iF1 < (wL - 1) / 2)
	 {
	    window =
	       .42 - .5 * cos(2 * PI * (float) iS / ((float) (wL - 1))) +
		  .08 * cos(4 * PI * (float) iS / ((float) (wL - 1)));
	    bufferC[iF].r *= window; bufferC[iF].i *= window;
	    iS++;
	 }
	 else if (iF - iF1 >= info->nF - (wL - 1) / 2)
	 {
	    iS++;
	    window =
	       .42 - .5 * cos(2 * PI * (float) iS / ((float) (wL - 1))) +
		  .08 * cos(4 * PI * (float) iS / ((float) (wL - 1)));
	    bufferC[iF].r *= window; bufferC[iF].i *= window;
	 }
      }

      /* going back to time domain */
      pfacr(1, info->nSamples, bufferC, buffer);

      /* copying to dataObs within target window and scaling */
      for (iF = 0, iS = NINT(t1 / dt); iS <= NINT(t2 / dt); iS++, iF++)
      {
	 dataObs[iR][iF] = (scaleData * buffer[iS]) / (float) info->nSamples;
	 /* DD 
	 fprintf(stderr, "%d %d %f %f %f %f\n", iR, iF, dataObs[iR][iF], 
		 info->f1, info->f2, scaleData);*/
      }
   }
   /* DD 
   fprintf(stderr, "energy %f\n", auxm1 / (nDM * info->nR));
   fwrite(&dataObs[0][0], sizeof(float), nDM * info->nR, stdout);
   exit(-1);*/
   
   /* freeing memory */
   free1float(buffer);
   free1complex(bufferC);

   fclose(fp); 
}
Esempio n. 7
0
int
main(int argc, char **argv)
{
	int nt;			/* number of points on trace		*/
	float dt;		/* time sample interval (sec)		*/
	float *shaper;		/* shaping filter coefficients		*/
	float *spiker;		/* spiking decon filter (not used)	*/
	float *w;		/* input wavelet			*/
	int nw;			/* length of input wavelet in samples	*/
	float *d;		/* desired output wavelet		*/
	int nd;			/* length of desired wavelet in samples	*/
	int nshape;		/* length of shaping filter in samples	*/
	float pnoise;		/* pef additive noise level		*/
	float *crosscorr;	/* right hand side of Wiener eqs	*/
	float *autocorr;	/* vector of autocorrelations		*/
	int showshaper;		/* flag to display shaping filter	*/
        float f_zero=0.0;       /* zero valued item for comparison      */

	cwp_String wfile="";	/* input wavelet file name		*/
	cwp_String dfile="";	/* desired output wavelet file name	*/
	FILE *wfp;		/* input wavelet file pointer 		*/
	FILE *dfp;		/* desired wavelet file pointer		*/


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


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


	/* Get parameters */
	if (!getparint("showshaper",  &showshaper))	showshaper = 0;
	if (!getparint("nshape",  &nshape))		nshape = nt;
	if (!getparfloat("pnoise",  &pnoise))		pnoise = PNOISE;

	/* Open dfile and wfile if they have been getparred */
	getparstring("dfile",&dfile);	
	getparstring("wfile",&wfile);	

	if ((*dfile=='\0')) { /* if no dfile, then get from command line */
		if (!(nd = countparval("d")))
			err("must specify d= desired wavelet");
		d = ealloc1float(nd);	getparfloat("d", d);

	} else { /* read from dfile  */

                if((dfp=fopen(dfile,"r"))==NULL)
                        err("cannot open dfile=%s\n",dfile);

        	if (!fgettr(dfp,&dtr))  err("can't get input wavelet");
        		nd = (int) dtr.ns;
		d = ealloc1float(nd);
		memcpy((void *) d, (const void *) dtr.data, nd*FSIZE);
	}
		
	if ((*wfile=='\0')) { /* then get w from command line */
		if (!(nw = countparval("w")))
			err("must specify w= desired wavelet");
		w = ealloc1float(nw);	getparfloat("w", w);

	} else { /* read from wfile  */

                if((wfp=fopen(wfile,"r"))==NULL)
                        err("cannot open wfile=%s\n",wfile);

        	if (!fgettr(wfp,&wtr))  err("can't get desired output wavelet");
        		nw = (int) wtr.ns;
		w = ealloc1float(nw);
		memcpy((void *) w, (const void *) wtr.data, nw*FSIZE);
	}


	/* Get shaping filter by Wiener-Levinson */
	shaper	  = ealloc1float(nshape);
	spiker 	  = ealloc1float(nshape);	/* not used */
	crosscorr = ealloc1float(nshape);
	autocorr  = ealloc1float(nshape);
	xcor(nw, 0, w, nw, 0, w, nshape, 0, autocorr);  /* for matrix */
	xcor(nw, 0, w, nd, 0, d, nshape, 0, crosscorr); /* right hand side */
        if (CLOSETO(autocorr[0],f_zero))  err("can't shape with zero wavelet");
	autocorr[0] *= (1.0 + pnoise);			/* whiten */
	stoepf(nshape, autocorr, crosscorr, shaper, spiker);
		

	/* Show shaper on request */
	if (showshaper) {
		register int i;
		warn("Shaping filter:");
		for (i = 0; i < nshape; ++i)
			fprintf(stderr, "%10g%c", shaper[i],
				(i%6==5 || i==nshape-1) ? '\n' : ' ');
	}



	/* Main loop over traces */
	do {
		/* Center and convolve shaping filter with trace */
		conv(nshape, (nw-nd)/2, shaper,
		     nt, 0, intrace.data, 
                     nt, 0, outtrace.data);        


		/* Output filtered trace */
		memcpy( (void *) &outtrace, (const void *) &intrace, HDRBYTES);
		puttr(&outtrace);

	} while (gettr(&intrace));


	return(CWP_Exit());
}
Esempio n. 8
0
int kirmigs(char *datain, char *dataout, int lseekin, int lseekout, 
	    char *timefile, char *ampfile, int iamp,
	    int nt, int nx, int nz, int lt, 
	    float itmin, float iix0, float iz0, 
	    float idt, float idx, float idz,
	    float ismint, float ixmint, float izmint, 
	    float idst, float idxt, float idzt,
	    int nst, int nxt, int nzt,
	    float iofimin, float iofimax,
	    float iofomin, float idofo, int nofo,
	    int *mtrace, int i2p5,
	    int intps, int intpx, int intpz,int intype, float idcdp,
	    int amptype,int mlimit, int lagc, float itpow,
            float iaper, float iapanl, float iapanr, float iv0, 
	    int cdpx0, int dcdpx, char *dipfile, float idxdip, float idxtol) {

/* subroutine kmigs */

	int ix, iz, it, i;
	float tminl;
	float *trace, *trt, *migs, *fold, *tr, *ts, *ar, *as, *sigxt, *sigzt;
	int *inxt, *inzt;
	short *ttbl, *atbl;
	float ascale, tscale;
	long sx, gx;
	int ntrace, iofo;
	int ix0, iof, latbl;
	float xs, xr, tmp, *trz, *trr,dldt,dl,offout,dlm;
	float *twk1,*twk2,*awk1,*awk2,*trwk;
	FILE *tfp, *afp;
	FILE *infp, *outfp;
	int mute;
	int chkcdp;
	long sy, gy, icdp1;
	float offset;
	char *afile, *tfile;
	int lttbl,llimit;
	int lmem ;
	int lwin, mt, notrace, itmp;
	float rmso, zw;
	float *dips;
	int idip;
	int isize;

        /* convert double to float */
	float tmin = itmin , x0 = iix0 , z0 = iz0 ; 
	float dt = idt , dx = idx , dz =idz ;
	float smint = ismint , xmint = ixmint , zmint = izmint ;
	float dst = idst , dxt = idxt , dzt = idzt ;
	float ofimin = iofimin , ofimax = iofimax ;
	float ofomin = iofomin , dofo = idofo ;
	float dcdp = idcdp;
	float tpow = itpow; 
	float v0 = iv0;
	float aper = iaper;
	float apanl = iapanl;
	float apanr = iapanr;
	float dxdip  = idxdip;
	float dxtol = idxtol;

        char chost[MAXHOSTNAMELEN] ;
	int nxdip;

        gethostname(chost,MAXHOSTNAMELEN) ;
	fprintf(stderr,"starting migration at %s for\t%f < offsets <= %f \n",
			chost, ofomin-dofo*.5,ofomin+(nofo-.5)*dofo);
	
	tmp = nx * dx/dxdip;
	nxdip = (int)tmp;
	if(nxdip<1) nxdip = 1;
	if(nxdip>nx) nxdip = nx;
	dxdip = dx * nx/nxdip;
	 
	lwin = lagc/(int)(dt*1000.);

	/* in case the dp starts the migration again, do not remigrate */ 
	isize = 0;
	if((outfp = fopen(dataout,"r"))!=NULL) {
                 fseek(outfp,0L,SEEK_END);
                 isize= (int) ftell(outfp);
                 fclose(outfp);
        }
	if( isize==(nz*sizeof(float)+HDRBYTES)*nx*nofo ) {
	   fprintf(stderr,"output %s already migrated \n",dataout);
           return 0 ;
	}

	/* set mtrace to be -1 in case of error return to kirmig */
	*mtrace = -1;
	
        infp = fopen(datain,"r");
        if( infp == NULL ) {
	   fprintf(stderr,"kirmigs datain=%s not found\n",datain);
           return 1 ;
        }

        outfp = fopen(dataout,"w");
        if( outfp == NULL ) {
	   fprintf(stderr,"kirmigs dataout=%s not found\n",dataout);
           return 1 ;
        }

	/* check to see if there is any input data */
	efseek(infp,0L,2);
	notrace = 0;
        if((eftell(infp)-lseekin)<=0) {
		warn("no trace in input %s \n",datain); 
		notrace = 1;
		*mtrace = 0;
	}

	if (notrace==1) goto skipmig; 

        /* turn off buffering for outfp */
	/* setbuf(outfp,NULL); */

	/*
	fprintf(stderr,"within kirmigs mlimit=%d \n",mlimit);
	fprintf(stderr,"x0=%f z0=%f nx=%d nz=%d \n",x0,z0,nx,nz);
	fprintf(stderr,"dx=%f dz=%f \n",dx,dz);
	fprintf(stderr,"timefile=%s \n",timefile);
	fprintf(stderr,"ampfile=%s \n",ampfile);
	fprintf(stderr,"nt=%d dt=%f tmin=%f \n",nt,dt,tmin);
	fprintf(stderr,"ofomin=%f dofo=%f nofo=%d \n",ofomin,dofo,nofo);
	fprintf(stderr,"xmint=%f zmint=%f smint=%f \n",xmint,zmint,smint);
	fprintf(stderr,"dxt=%f dzt=%f dst=%f \n",dxt,dzt,dst);
	fprintf(stderr,"nxt=%d nzt=%d nst=%d \n",nxt,nzt,nst);
	fprintf(stderr,"lt=%d \n",lt);
	fprintf(stderr,"dcdp=%f dxtol=%f \n",dcdp,dxtol);
	fprintf(stderr,"lseekin=%d lseekout=%d \n",lseekin,lseekout);
	*/

	idip = 1;
	if(dipfile[0]=='N' && dipfile[1]=='U',
		dipfile[2]=='L' && dipfile[3]=='L') idip=0;

	/* memory allocations */
	lmem = (2*nzt*nxt + nofo*nx*nz + nofo + 4*nx*nz + nx + 2*nz 
		+ nzt + 2*lt + nt)*sizeof(float) 
	      +(nx + nz) * sizeof(int) + idip*2*nxdip*nz*sizeof(float);

	llimit = mlimit * 1024 * 1024;	
	if ( lmem > llimit ) {
	   fprintf(stderr,"Need at least memory size mlimit=%d (Bytes)\n",
	 	   lmem);
	   return 1;
	} 

        twk1 = (float*) malloc(nzt*nxt*sizeof(float));
	if( twk1 == 0 ) return 1 ;
        twk2 = (float*) malloc(nzt*nxt*sizeof(float));
	if( twk2 == 0 ) return 1 ;
	migs = (float*) malloc(nofo*nx*nz*sizeof(float));
	if( migs == 0 ) return 1 ;
	fold = (float*) malloc(nofo*sizeof(float));
	if( fold == 0 ) return 1 ;
	ts = (float*) malloc(nx*nz*sizeof(float));
	if( ts == 0 ) return 1 ;
	tr = (float*) malloc(nx*nz*sizeof(float));
	if( tr == 0 ) return 1 ;
	as = (float*) malloc(nx*nz*sizeof(float));
	if( as == 0 ) return 1 ;
	ar = (float*) malloc(nx*nz*sizeof(float));
	if( ar == 0 ) return 1 ;
	sigxt = (float*) malloc(nx*sizeof(float));
	if( sigxt == 0 ) return 1 ;
	sigzt = (float*) malloc(nz*sizeof(float));
	if( sigzt == 0 ) return 1 ;
	inxt = (int*) malloc(nx*sizeof(int));
	if( inxt == 0 ) return 1 ;
	inzt = (int*) malloc(nz*sizeof(int));
	if( inzt == 0 ) return 1 ;

	trt = (float*) malloc(nzt*sizeof(float));
	if( trt == 0 ) return 1 ;
	trz = (float*) malloc(nz*sizeof(float));
	if( trz == 0 ) return 1 ;
	trace = (float*) malloc(lt*sizeof(float));
	if( trace == 0 ) return 1 ;
        trwk = (float*) malloc(lt*sizeof(float));
	if( trwk == 0 ) return 1 ;
	trr = (float*) malloc(nt*sizeof(float));
	if( trr == 0 ) return 1 ;
	dips = (float*) malloc(idip*2*nxdip*nz*sizeof(float));
	if( dips == 0 ) return 1 ;


	lttbl = nst*nxt*nzt*sizeof(short);
	if ( lmem + lttbl > llimit ) {  
	   lttbl = 1 * sizeof(short);
	   tfile = (char*) malloc(strlen(timefile)+1);
	   sprintf(tfile,"%s\0",timefile);
	}
	else {
	   tfile = "null";
	}
	lmem +=lttbl;
	ttbl = (short*) malloc(lttbl);
	if( ttbl == 0 ) return 1 ;
        if ( iamp == 1 ) {
           latbl = nst*nxt*nzt*sizeof(short);
	   if ( lmem + latbl > llimit ) {  
	      latbl = 1 * sizeof(short);
	      afile = (char*) malloc(strlen(ampfile)+1);
	      sprintf(afile,"%s\0",ampfile);
	   }
	   else {
	      afile = "null";
	   }
           awk2 = (float*) malloc(nzt*nxt*sizeof(float));
	   lmem += nzt*nxt*sizeof(float); 
	   if( awk2 == 0 ) return 1 ;
           awk1 = (float*) malloc(nzt*sizeof(float));
	   lmem += nzt*sizeof(float); 
	   if( awk1 == 0 ) return 1 ;
        } else {
           latbl = 1 * sizeof(short);
	   afile = "null";
           awk2 = (float*) malloc(latbl);
	   lmem += latbl; 
	   if( awk2 == 0 ) return 1 ;
           awk1 = (float*) malloc(latbl);
	   lmem += latbl; 
	   if( awk1 == 0 ) return 1 ;
        }
	atbl = (short*) malloc(latbl);
	lmem += latbl; 
	if( atbl == 0 ) return 1 ;
	fprintf(stderr,"total memory used (Byte) =%d \n",lmem); 
	if(lttbl==1) fprintf(stderr,"travel time table disk i/o used \n"); 
	if(iamp==1 && latbl==1) 
	   fprintf(stderr,"amplitude table disk i/o used \n");

	/* read in travel time table and amplitude table */
	tfp = fopen(timefile,"r");
        if( tfp == NULL ) {
	   fprintf(stderr,"kirmigs: timefile=%s not found\n",timefile);
           return 1 ;
        }

	if ( iamp == 1 && latbl > 1 ) { 
	   afp = fopen(ampfile,"r");
           if( afp == NULL ) {
	       fprintf(stderr,"kirmigs: ampfile=%s not found\n",ampfile);
               return 1 ;
           }
	   /* find scale to scale amplitudes */
	   ascale = 0.;
           for(ix=0;ix<nxt*nst;ix++) {
              fread((char *)trt,sizeof(float),nzt,afp);
	      for(iz=0;iz<nzt;iz++) {
	         if(fabs(trt[iz]) > ascale) ascale=fabs(trt[iz]); 
	      }
	   }
	   /* read in amplitudes, scale and store in short *atbl */ 
	   fseek(afp,0,0);
	   if(ascale>0.) ascale = 32000./ascale;
           for(ix=0;ix<nxt*nst;ix++) {
              fread((char *)trt,sizeof(float),nzt,afp);
	      ix0 = ix*nzt;
	      for(iz=0;iz<nzt;iz++) {
	      tmp = trt[iz]*ascale; 
	      atbl[ix0+iz] = (short)tmp;
	      }
	   }
	}
	else {
	   ascale = 1.;
	}
	
	if(lttbl > 1 ) {
	   /* read in times, scale and store in short *ttbl */ 
           /* times in ms */
	   if (dt>=1.) {
              tscale = 32000./(nt*dt);
           }
           else {
              tscale = 1000. * 32000. / (nt*dt*1000.);
           }
           for(ix=0;ix<nxt*nst;ix++) {
              fread((char *)trt,sizeof(float),nzt,tfp);
	      ix0 = ix*nzt;
	      for(iz=0;iz<nzt;iz++) {
	         tmp = trt[iz]*tscale;
	         if ( tmp < 32000 ) {
	            ttbl[ix0+iz] = (short)tmp;
	         }
	         else {
	            ttbl[ix0+iz] = 32500;
	         }
	      }
	   }   

           if (dt>=1.) {
              tmin = tmin * 1000.;
              dl = dt * nt / lt;
	      dlm = dl;
           } else {
              tscale = tscale/1000.;
              dt = dt * 1000.;
              tmin = tmin * 1000.;
              dl = dt * nt / lt;
	      dlm = dl;
           }
	} else {
	   dl = dt*nt/lt;
	   dlm = dl * 1000.;
	   tscale = 1.;
	}
	
	

	/* Main loop over traces */
	ix = 0;
	dldt = dl/dt;
	tminl = tmin / dt; 
	ntrace =0;

/* skip lseekin bytes in infp */
	fseek(infp,lseekin,0);

/* see if cdp and offset are used in migration, instead of sx and gx */
/* read first trace */
	fgettr(infp,&tra);
	sy = tra.sy;
	gy = tra.gy;
	if ( sy == gy && dcdp==0. ) {
	   chkcdp = 0;
	} else {
	   chkcdp = 1;
	   if( dcdp == 0. ) {
		fprintf(stderr,"dcdp must be specified ! \n");
		return 1;
	   }
	   icdp1 = cdpx0;
	}
	
	/* read in dips grid */
	
	if(idip==1) {

		tmp = dcdpx*nx/nxdip;
		itmp = (int) tmp;	
		dipsgrid_cpp(dipfile,dips,dips+nz*nxdip,z0,dz,nz,
			cdpx0,itmp,nxdip);
		for(iz=0;iz<nxdip*nz*2;iz++) {
			tmp=dips[iz];
			if(tmp>=90.) {
		 		tmp = 89.9;
			} else if (tmp<=-90.) {
				tmp = -89.9;
			} 
			dips[iz]=tan(tmp*3.141592654/180.);
		}
	}

	/* initialize mtrace */
	*mtrace = 0;

	do {

                int nonzerotrace ;
		/* Load trace into trace (zero-padded) */
		memcpy(trr, tra.data, nt*sizeof(float));

	        /* check if this is a zero trace */
		nonzerotrace = 0 ;	
		for(it=0;it<nt;it++) {
		  if(trr[it] != 0.0) { nonzerotrace = 1; break ; } 
		} 
		if( nonzerotrace == 0 ) tra.trid = 0;
		if( tra.trid != 0 ) {

/* apply 2.5-D filter */
	            if(i2p5==1) f2p5_(trr,&nt);
/* apply agc */
		    if(lwin>0) {
                        mute = (tra.mute-tra.delrt)/tra.dt;
                        if(mute<0) mute=0;
                        if(mute>nt) mute=nt;
                        mt = nt - mute;
                        rmso = 2000.;
                        agc_(trr+mute,&mt,&lwin,trwk,&rmso);
                    }
/* apply tpow */
                    if(fabs(tpow)>0.0001) tp_(trr,&nt,&tpow,&tmin,&dt);


/* linearly interpolate input trace */
	            for(it=0;it<lt;it++) {
		       tmp = tminl+it*dldt; 
	               i = (int)tmp;
	               tmp = tmp - i;
	               if(i>=0 && i<nt-1) {
		          trace[it] = (1.-tmp)*trr[i]+tmp*trr[i+1];
		       }
		       else {
		          trace[it] = 0.;
		       }	
		    }
	

	            /* obtain source and receiver x's from trace hader */
		    if ( chkcdp == 0 ) {
		       sx = tra.sx;
		       gx = tra.gx;	
		       xs = sx;
		       xr = gx;
		       if(tra.scalco>1) {
				xs = xs*tra.scalco;
				xr = xr*tra.scalco;
		       } else if (tra.scalco<0) {
				xs = xs/(-tra.scalco);
				xr = xr/(-tra.scalco);
		       }		
		    }
		    else {
		       xs = (tra.cdp-icdp1)*dcdp + x0 - tra.offset/2.;
		       xr = (tra.cdp-icdp1)*dcdp + x0 + tra.offset/2.;

		    }
	            tmp = (tra.mute-tra.delrt)/dlm + 1.;
	            mute = (int)tmp ; 
		    tmp = tra.mute * 0.5 * v0 * 0.001;
                    tmp = tmp*tmp - 0.25 * fabs(xs-xr) * fabs(xs-xr);
                    if ( tmp > 0. ) {
                        zw = sqrt(tmp);
                    } else {
			zw = 0.;
		    }
		    ix = ix+ 1;

		    /* migration */
		    tmp = fabs(xs-xr);
		    offset = (tmp-ofomin)/dofo+1.5 ;   
		    iofo = (int)offset;
		    if ( (iofo<1 || iofo>nofo) && intype==1 ) break; 

/*
 fprintf(stderr,"xr=%f xs=%f at cdp=%d dcdp=%f icdp1=%d x0=%f offset=%d\n",
	xr,xs,tra.cdp,dcdp,icdp1,x0,tra.offset);	
*/

		}
		ntrace = ntrace + 1;
		if ( ntrace%1000 == 0 )
   	fprintf(stderr,"input %d traces processed at %s \n",ntrace,chost);

	        if(tmp>=ofimin && tmp<=ofimax && tra.trid==1 && mute<lt) {

		   	kirmig_(trace,&xs,&xr,&tmin,&lt,&dl,
                           	migs,&x0,&z0,&dx,&dz,&nx,&nz,
                           	&nofo,&ofomin,&dofo,fold,
                           	ttbl,atbl,&xmint,&zmint,&dxt,&dzt,&nxt,&nzt,
                           	&nst,&smint,&dst,ts,tr,as,ar,&dxtol,
                           	sigxt,sigzt,inxt,inzt,&iamp,mtrace,
                           	twk1,twk2,awk1,awk2,&tscale,trwk,
                           	&intps,&intpx,&intpz,&mute,
			   	&ascale,&amptype,
			   	tfile,afile,&aper,&apanl,&apanr,&zw,
				dips,&idip,&nxdip,&dxdip);
		}

	} while (fgettr(infp,&tra));


   fprintf(stderr,"input %d traces processed at %s \n",ntrace,chost);
	
        /* free spaces */
	free((char *)trt);
	free((char *)trr);
	free((char *)ttbl);
	free((char *)atbl);
	free((char *)twk1);
	free((char *)twk2);
	free((char *)awk1);
	free((char *)awk2);
	free((char *)trwk);
	free((char *)tr);
	free((char *)ts);
	free((char *)ar);
	free((char *)as);
	free((char *)sigxt);
	free((char *)sigzt);
	free((char *)inxt);
	free((char *)inzt);
	free((char *)trace);
	free((char*)dips);

	if(fabs(tpow)>0.0001) {
                trace = (float *) malloc(nz*sizeof(float));
                for(i=0;i<nz;i++) {
                        tmp = (z0+i*dz)/(z0+nz*0.5*dz);
                        tmp = fabs(tmp);
                        if(tmp==0.) {
                                trace[i] = 0.;
                        } else {
                                trace[i] = pow(tmp,-tpow);
                        }
                }
        }

	ascale=1./ascale;
	if ( amptype == 0 ) {
	   ascale = ascale/2.;
	}
	else {
	   ascale=ascale*ascale;
	}
	if ( iamp == 0 ) ascale = 1.;
	
	skipmig:

/* output traces */

	/* skip lseekout bytes in outfp */
	fseek(outfp,lseekout,0);
	
	/* if no input trace, zero output */
	if(notrace==1) {
		bzero((char*)&tra,(240+nz*sizeof(float)));
	}

	/* update trace headers */
	tra.ns = nz;
	tra.trid = 1;

	if ( dz < 30. ) {
	   tmp = dz * 1000.;
           tra.dt = (unsigned short) tmp;
	   tmp = z0 * 1000.;
	   tra.delrt = (unsigned short) tmp;
	} else if (dz <300.) {
	   tmp = dz * 100.;
           tra.dt = (unsigned short) tmp;
	   tmp = z0 * 100.;
	   tra.delrt = (unsigned short) tmp;
	} else {
           tra.dt = (unsigned short) dz;
	   tra.delrt = (unsigned short) z0;
	}
	tra.sy = 0;
	tra.gy = 0;
	/* scale x coordinate if needed */  
	itmp = (int) dx;
	tmp = dx - itmp;
	if(fabs(tmp)>0.01) {
		tra.scalco = -100;
	} else {
		tra.scalco = 1;
	} 

	for(iof=0;iof<nofo;iof++) {
	   offout = ofomin + iof*dofo;
	   if(notrace==0) {
	   	if(fold[iof]>1.) {
	      		tmp = ascale / fold[iof];
	   	}
	   	else {
	      		tmp = ascale;
	   	}
	   }
	   for(ix=0;ix<nx;ix++) {
/* update trace headers */
	      tra.offset = offout;
              tra.cdp = ix+1 ;
              tra.tracf = ix+1 ;
              xs = x0 + ix*dx - offout/2;  
              xr = x0 + ix*dx + offout/2;  
	      if (tra.scalco==-100) {
              	xs = xs * 100.;
              	xr = xr * 100.;
	      }
	      tra.sx = xs;
	      tra.gx = xr;
	      tra.ep = tra.sx;	
	      tra.fldr = tra.sx;	

	      if(notrace==0) {
	      	ix0 = ix*nz+iof*nx*nz;
	      	for (i=0;i<nz;i++) {
	         	trz[i] = migs[ix0+i]*tmp;
	      	}
	      	if(fabs(tpow)>0.0001)
                        for(i=0;i<nz;i++) trz[i] = trz[i]*trace[i];
	      	memcpy(tra.data, trz, nz*sizeof(float));
	      }
	      fputtr(outfp,&tra);
	      /* fflush(outfp); */
	   }
	} 

	if(notrace==0) {
		free((char *)migs);
		free((char *)fold);
		free((char *)trz);
		if(fabs(tpow)>0.0001) free((char *)trace);
	}

	fclose(infp);
	fclose(outfp);

   fprintf(stderr,
	"kirmig done at %s for\t%f < offsets <= %f  for %d live traces\n",
		  chost,ofomin-0.5*dofo,ofomin+(nofo-0.5)*dofo,*mtrace);

	return 0;
}
Esempio n. 9
0
int
main(int argc, char **argv)
{
	cwp_String key;	/* header key word from segy.h		*/
	cwp_String type;/* ... its type				*/
	int index;	/* ... its index			*/
	int nsegy;	/* number of bytes in the segy		*/
	Value val;	/* value of key in current gather	*/
	Value valnew;	/* value of key in trace being treated	*/
	int verbose;	/* verbose flag				*/
	int val_i;	/* key value as an integer		*/

	int ntr=0;	/* count of number of traces in an ensemble */
	int numlength;	/* length of numerical part of filenames */
	
	FILE *tmpfp=NULL;		/* file pointer			*/
	FILE *outfp=NULL;	/* file pointer			*/
	cwp_String dir;		/* directory name		*/
	cwp_String suffix;	/* suffix of output files	*/

	char directory[BUFSIZ];		/* storage for directory name	*/
 	char tempfilename[BUFSIZ];	/* 	...temporary filename	*/
	char middle[BUFSIZ];		/*      ...middle of final filename */
	char stem[BUFSIZ];		/*      ...stem of final filename */
 	char format[BUFSIZ];		/* 	...format of numeric part */
	char outfile[BUFSIZ];		/*      ...final filename	*/

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


	/* Get parameters */
	MUSTGETPARSTRING("dir", &dir);
	if (!getparint   ("verbose", &verbose))	 	verbose = 0;
	if (!getparstring("key", &key))		 	key = "ep";
	if (!getparstring("suffix", &suffix))		suffix = ".hsu";
	if (!getparint("numlength", &numlength)) 	numlength=7;

	/* Initialize */
	/* tempfilename = ealloc1(strlen(tmplt)+3,sizeof(char)); */
	type = hdtype(key);
	index = getindex(key);

	/* Set up for first trace (must compare new key field each time) */
	nsegy = gettr(&intrace);
	
	/* Create temporary filename for the first gather */
	strcpy(directory, dir);
	strcpy(tempfilename, temporary_filename(directory));
	if((tmpfp = fopen(tempfilename,"w+")) == NULL)
		err("Cannot open file %s\n",tempfilename);

	if (verbose) warn(" temporary filename = %s", tempfilename);

	/* get key header value */
	gethval(&intrace, index, &val);
	
	ntr=0;
	do {

		++ntr;
		/* Get header value */				 
		gethval(&intrace, index, &valnew);

		/* compare past header value to current value */
		if (valcmp(type, val, valnew) || !nsegy) {
		 /* Either val and valnew differ, indicating a  */
		 /* new gather or nsegy is zero, indicating the */
		 /* end of the traces.			  */
			
			/* capture key field value */
			/* and build output filename */
			val_i=vtoi(type,val);

			/* zero out name parts */
			strcpy(outfile,"");
			strcpy(middle,"");
			strcpy(stem,"");

			/* build output name parts */
			strcat(middle,directory);
			strcat(middle,"/");
			strcat(stem,key);
			strcat(stem,"=");

			/* format for numeric part */
			(void)sprintf(format, "%%s%%s%%0%dd%%s",numlength);
		
			/* build name of output file */
			(void)sprintf(outfile, format,middle,stem,
					val_i, suffix);

			if (verbose) warn(" outfile = %s", outfile);

			/* rewind file */
			rewind(tmpfp);

			/* open the new file */
			if((outfp = fopen(outfile,"w+")) == NULL)
				err("Cannot open file %s\n",outfile);
			/* loop over traces setting ntr field */
			/*  and write to finalfile */	
			while(fgettr(tmpfp,&tmptr))  {
				tmptr.ntr = ntr;
				fputtr(outfp,&tmptr);
			}
			/* Close files */
			fclose(tmpfp);
			fclose(outfp);
			remove(tempfilename);

			if (verbose) warn("val= %i", val_i);

			/* Set up for next gather */
			/* create new tempfname first */
			strcpy(tempfilename, temporary_filename(directory));
			
			/* open filename */
			if((tmpfp = fopen(tempfilename,"w+")) == NULL)
				err("Cannot open file %s\n",tempfilename);
			val = valnew;
			ntr=0;
		}
		fputtr(tmpfp,&intrace);
	} while(gettr(&intrace));
	
	/* Close file */
	rewind(tmpfp);
	val_i=vtoi(type,val);
	
	/* Move last gather into new location */
	/* capture key field value */
	/* and build output filename */

	/* null out name parts */
	strcpy(outfile,"");
	strcpy(middle,"");
	strcpy(stem,"");

	/* build name parts */
	strcat(middle,directory);
	strcat(middle,"/");
	strcat(stem,key);
	strcat(stem,"=");
	
	/* write format of numeric part of output filename */
	(void)sprintf(format, "%%s%%s%%0%dd%%s",numlength);

	/* write output filename */
	(void)sprintf(outfile, format,middle,stem,
				val_i, suffix);

	/* open the output file */
	if((outfp = fopen(outfile,"w+")) == NULL)
			err("Cannot open file %s\n",outfile);
	/* loop over traces setting ntr field */
	while(fgettr(tmpfp,&tmptr))  {
		tmptr.ntr = ntr;
		fputtr(outfp,&tmptr);
	}
	/* Close file */
	fclose(tmpfp);
	fclose(outfp);
	remove(tempfilename);

	if (verbose) warn(" outfile = %s", outfile);
	if (verbose) warn("val= %i",val_i);

	return(CWP_Exit());

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


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

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

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

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

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

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


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


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


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


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



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

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


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


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


	return EXIT_SUCCESS;
}
Esempio n. 11
0
/* main program */
main(int argc, char **argv)
{
	
	
	float min, max; 		/* scale */
	double dtmp, tmp, dmin, dmax;
	int nt;			/* number of samples per trace */
	int it;			/* time index */
	FILE *infp=stdin, *outfp=stdout;	
	int itrace;
	int nbad, ibad, report_good, action;
	char *printout;
	FILE *printfp;
	float fmax, fmin;
	int *count, itmp, i; 
	float *plots;
	double rms, rmssum;
	float rmsout, scale;
	int imute, ntrace;
	int itmin, itmax, its;
	
/* initialize */
	initargs(argc, argv);	/* initialize parameter reading */ 
	askdoc(1);		/* on-line self documentation */

/* parameters fetching */

	if (!getparfloat("min",&min)) min=0.0;
	if (!getparfloat("max",&max)) max=1.0e+6;
	if (!getparint("report",&report_good)) report_good=0;
	if (!getparint("action",&action)) action=0;
	if (!getparstring("printout",&printout)) {
		printfp = stderr;
	} else {
		printfp = fopen(printout,"w");
	}

	if (action==3) {
		if(!getparfloat("rmsout",&rmsout)) 
			err(" rmsout missing ");
	}

/* processing */ 

	file2g(infp);
	if (!fgettr(infp,&trin))  err("can't get first trace");
				/* read in the first trace, exit if fail */

	nt = trin.ns;		/* obtain number of samples per trace */

	if(action!=0) file2g(outfp);



	if (!getparint("itmin",&itmin)) itmin = 0;
	if (!getparint("itmax",&itmax)) itmax = nt;

	dmin = min;
	dmax = max;
	nbad = 0;
	itrace=1;
	fmax = 0.;
	fmin = 1.e+38;
	count = (int*) malloc(40*sizeof(int));
	plots = (float*) malloc(160*sizeof(float));
	bzero(count,40*sizeof(int));
	bzero(plots,160*sizeof(float));
	rmssum = 0.;
	ntrace = 0;

	/* Main loop over traces */
	do {

		ibad = 0;
		rms = 0.;
		if(itmin==0) {
			imute = (trin.mute - trin.delrt)*1000/(int)trin.dt;
			if(imute<0) imute=0;
			its = imute;
		} else {
			its = itmin;
		}
		for(it=its;it<nt;it++) {
		        if( !ieeefinite(&trin.data[it]) ) {
				ibad += 1;
				if(action==1) trin.data[it] = 0.;
				count[39] += 1;
			} else {
				rms = rms + trin.data[it]*trin.data[it]; 
				dtmp = trin.data[it];
				tmp = fabs(dtmp);
				if(tmp<dmin || tmp>dmax) {
					ibad += 1;
					if(action==1) trin.data[it] = 0.;
				}
				if(tmp>fmax) {
					 fmax = tmp;
				} else if (tmp<fmin) {
					 fmin = tmp;
				} 
				if(dtmp>0.) {
					dtmp = log10(tmp);
					itmp = dtmp;
				} else {
					itmp = 0;
				}
				if(itmp<0) {
					itmp = 0;
				} else if(itmp>38) {
					itmp = 39;
				} 
				count[itmp] += 1;
			}
		}
		if(nt>its) {
			rms = sqrt(rms/(nt-its));
		}
		
		if(ibad>0 && action==2) bzero((char*)trin.data,nt*4);

		if( (ibad>0 || rms>rmsout) && action==3) {
			if(rms==0) {
				bzero((char*)trin.data,nt*4);
			} else {
				scale = rmsout/rms;
				for(it=0;it<nt;it++) trin.data[it] *=scale;
			}
		}
		if(ibad>0) nbad += 1;

		/* report */
		if(ibad>0) {
		    fprintf(printfp, 
	    "BAD amplitude at trace %d with trace number=%d rms=%g \n",
			itrace,trin.tracl,rms);
		} else if(report_good == 1) {
		    fprintf(printfp, 
		    "GOOD amplitude at trace %d with trace number=%d rms=%g\n",
			itrace,trin.tracl,rms);
		} else if(action==3 && rms>rmsout) {
		    fprintf(printfp, 
	    "BAD rms amplitude at trace %d with trace number=%d rms=%g \n",
			itrace,trin.tracl,rms);
		}
		fflush(printfp);
		itrace +=1;
		if(action!=0) fputtr(outfp,&trin);
		rmssum += rms;
		ntrace += 1; 
 
	} while (fgettr(infp,&trin));		/* reading traces */

	if( ntrace>1) rmssum = rmssum / ntrace;

	fprintf(printfp, 
	"===> Total Number of Bad Traces in Input = %d \n",nbad);
	fprintf(printfp, 
	"===> Maximum Absolute Amplitude in Input = %g \n",fmax);
	fprintf(printfp, 
	"===> Minimum Absolute Amplitude in Input = %g \n",fmin);
	fprintf(printfp, 
	"===> average trace rms amplitude in Input = %g \n",rmssum);
	itmp = 0;
	for(i=0;i<40;i++) itmp += count[i]; 

	
	for(i=0;i<40;i++) {
		plots[i*4] = i;
		plots[i*4+1] = (float)count[i]/(float)itmp*100.;
		plots[i*4+2] = i+1;
		plots[i*4+3] = (float)count[i]/(float)itmp*100.;
	}
		
	for(i=0;i<39;i++) {
		if(count[i]>0) {
			if(i==0) {
				tmp = 0.;
			} else {
				tmp = pow(10.,(float)i);
			}
	fprintf(printfp,
	"===> Percentage of Amplitudes from %g to %g =%-5.2f \n",
	tmp, pow(10.,(float)(i+1)),
	(float)count[i]/(float)itmp*100.);
		}
	}
	if(count[39]>0) fprintf(printfp,
	"===> Percentage of Infinity/NaN Amplitudes =%-5.2f \n",
	(float)count[39]/(float)itmp*100.);
	
	itmp = 80;
	dump2xgraph(plots,&itmp,1,"Input Amplitude Distribution","power of 10",
			"percentage","normal");

	free(count);
	free(plots);

	return 0;
}
Esempio n. 12
0
main(int argc, char **argv)
{
	int nt;		/* number of time samples per trace */
	int it;		/* time sample index */
	char *datain, *dataout;
	int cdppre,cdpnow;
	FILE *infp,*outfp;
	float scale;
	int maxfold, ix, nfold; 
	float *data;
	char *header;
	int op;
	int nofo;
	float *fold, *ofo, oofo, dofo;
	int itmp, iofoin;
	int *iofo, one, io;
	float ofol, ofor, tmp;
	int signof;
	
	
	/* hook up getpar */
	initargs(argc, argv);
	askdoc(1);

	/* get required parameters */

	if (!getparstring("datain",&datain)) {
		infp = stdin;
	} else {
		infp = efopen(datain,"r");
	} 
	file2g(infp);

	if (!getparstring("dataout",&dataout)) {
		outfp = stdout;
	} else {
		if(strcmp(dataout,datain)) { 
			outfp = efopen(dataout,"w");
		} else {
			outfp = efopen(dataout,"r+w");
		}
	} 
	file2g(outfp);

	/* get information from the first header */
	if (!fgettr(infp,&tri)) err("can't get first trace");
	nt = tri.ns;
	
	/* get other optional parameters */
	if (!getparint("maxfold",&maxfold)) maxfold = 120;
	if (!getparint("op",&op)) op = 1;
	if (!getparint("nofo",&nofo)) nofo = 1;
	if (!getparfloat("oofo",&oofo)) oofo = 0.;
	if (!getparfloat("dofo",&dofo)) dofo = 999999.;
	if (!getparint("signof",&signof)) signof = 1;
        itmp = countparname("ofo");
        if(itmp>0 && itmp!=nofo) err("number of ofo not match with nofo");
        ofo = (float*) emalloc(nofo*sizeof(float));
        if(itmp>0) {
                getparfloat("ofo",ofo);
                if(nofo>1) {
                        ofol = ofo[0] - 0.5*(ofo[1]-ofo[0]);
                        ofor = ofo[nofo-1] + 0.5*(ofo[nofo-1]-ofo[nofo-2]);
                } else {
                        ofol = ofo[0] - 0.5*dofo;
                        ofor = ofo[nofo-1] + 0.5*dofo;
	                oofo = ofo[0];
                }
        } else {
                for(io=0;io<nofo;io++) ofo[io] = oofo + io*dofo;
        }
        iofoin = itmp;


	data = (float*) malloc(nt*maxfold*sizeof(float));
	header = (char*) malloc(HDRBYTES*maxfold*sizeof(char));
	fold = (float*) malloc(nofo*sizeof(float));
	iofo = (int*) malloc(maxfold*sizeof(int));

	cdppre = tri.cdp;
	bzero(fold,nofo*sizeof(float));

	/* loop over traces */
	do {

		cdpnow = tri.cdp;
		if (cdpnow==cdppre) {
			tmp  = tri.offset;
			if(signof==1 && tmp<0. ) tmp = -tmp;
                	if(iofoin==0 || nofo==1 ) {
                        	tmp = (tmp-oofo)/dofo+.5;
                        	io = tmp;
                	} else {
                        	if(tmp<ofol) {
                                	io = -1;
                        	} else if(tmp>ofor) {
                                	io = nofo;
                        	} else {
                                	bisear_(&nofo,&one,ofo,&tmp,&io);
                                	io = io - 1;
                                	if(io<nofo-1) {
                                        	if(abs(tmp-ofo[io])	
							>abs(tmp-ofo[io+1]))
                                                	io = io + 1;
                                	}
                        	}
                	}
			if(io>=0 && io<nofo) { 
				bcopy((char*)&tri,header+nfold*HDRBYTES,
					HDRBYTES);
				bcopy((char*)tri.data,data+nfold*nt,nt*4);
				fold[io] += 1.0; 
				iofo[nfold] = io;
				nfold = nfold + 1;
			}
		} else {
			for(ix=0;ix<nfold;ix++) {
				if(op==1) {
					scale = 1./fold[iofo[ix]];
				} else {
					scale = fold[iofo[ix]];
				}
				for(it=0;it<nt;it++) 
					tro.data[it] = data[it+ix*nt]*scale; 
				bcopy(header+ix*HDRBYTES,(char*)&tro,
					HDRBYTES);
				fputtr(outfp,&tro);
			}
			nfold = 0;
			bzero(fold,nofo*sizeof(float));
			tmp  = tri.offset;
			if(signof==1 && tmp<0. ) tmp = -tmp;
                        if(iofoin==0 || nofo==1 ) {
                                tmp = (tmp-oofo)/dofo+.5;
                                io = tmp;
                        } else {
                                if(tmp<ofol) {
                                        io = -1;
                                } else if(tmp>ofor) {
                                        io = nofo;
                                } else {
                                        bisear_(&nofo,&one,ofo,&tmp,&io);
                                        io = io - 1;
                                        if(io<nofo-1) {
                                                if(abs(tmp-ofo[io])
                                                        >abs(tmp-ofo[io+1]))
                                                        io = io + 1;
                                        }
                                }
                        }
                        if(io>=0 && io<nofo) {
                                bcopy((char*)&tri,header+nfold*HDRBYTES,
                                        HDRBYTES);
                                bcopy((char*)tri.data,data+nfold*nt,nt*4);
				fold[io] += 1.0; 
				iofo[nfold] = io;
				nfold = nfold + 1;
			}
			cdppre = cdpnow;
		}
		
	} while (fgettr(infp,&tri));

	/* output last gather */
	if(nfold>0) {
		for(ix=0;ix<nfold;ix++) {
			if(op==1) {
				scale = 1./fold[iofo[ix]];
			} else {
				scale = fold[iofo[ix]];
			}
			for(it=0;it<nt;it++) 
				tro.data[it] = data[it+ix*nt]*scale; 
			bcopy(header+ix*HDRBYTES,(char*)&tro,HDRBYTES);
			fputtr(outfp,&tro);
		}
	}
	
	return EXIT_SUCCESS;
}
Esempio n. 13
0
main(int argc, char **argv)
{
	int nt;			/* number of points on trace		*/
	int databytes;		/* ... in bytes 			*/
	int ntr;		/* number of traces			*/
	string stype;		/* noise type (gauss, flat) as string	*/
	int itype;		/* ... as integer (for use in switch)	*/
	float sn;		/* signal to noise ratio		*/
	unsigned int seed;	/* random number seed			*/
	FILE *hdrfp;		/* fp for header storage file		*/
	FILE *sigfp;		/* fp for data ("signal")		*/
	int nfloats;		/* number of floats in "signal"		*/
	float *noise;		/* noise vector				*/
	float noiscale;		/* scale for noise			*/
	float absmaxsig;	/* absolute maximum in signal		*/
	float noipow;		/* a measure of noise power		*/
	float f1;		/* left lower corner frequency		*/
	float f2;		/* left upper corner frequency		*/
	float f4;		/* right lower corner frequency		*/
	float f3;		/* right upper corner frequency		*/
        char * scrdir;          /* scratch dir to put temporary data set */

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


	/* Get noise type */
	if (!getparstring("noise", &stype))	stype = "gauss";

	if      (STREQ(stype, "gauss")) itype = GAUSS;
	else if (STREQ(stype, "flat"))  itype = FLAT;
	else     err("noise=\"%s\", must be gauss or flat", stype);


	/* Get signal to noise ratio */
	if (!getparfloat("sn", &sn))	sn = SN;
	if (sn <= 0) err("sn=%d must be positive", sn);


	/* Set seed */
	if (!getparuint("seed", &seed)) { /* if not supplied, use clock */
		if (-1 == (seed = (uint) time((time_t *) NULL))) {
			err("time() failed to set seed");
		}
	}
	(itype == GAUSS) ? srannor(seed) : sranuni(seed);

        if( !getparstring("scrdir",&scrdir) ) {
            scrdir = getenv("SU_SCRATCHDIR") ;
        }


	/* Prepare temporary files to hold headers and data */
	/*
	hdrfp = etmpfile();
	sigfp = etmpfile();
	*/
	hdrfp = etempfile(NULL);
	sigfp = etempfile(NULL);


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


	/* Loop over input traces & write headers and data to tmp files */
	ntr = 0;
	do {
		++ntr;
		efwrite(&tr, 1, HDRBYTES, hdrfp);
		efwrite(tr.data, 1, databytes, sigfp);
	} while (gettr(&tr));
	nfloats = ntr * nt;


	/* Compute absmax of signal over entire data set */
	rewind(sigfp);
	absmaxsig = 0.0;
	{ register int i;
	  for (i = 0; i < nfloats; ++i) {
		float sigval;
		efread(&sigval, FSIZE, 1, sigfp);
		absmaxsig = MAX(absmaxsig, ABS(sigval));
	  }
	}


	/* Compute noise vector elements in [-1, 1] */
	noise = ealloc1float(nfloats);
	switch (itype) {
		register int i;
	case GAUSS: /* frannor gives elements in N(0,1)--ie. pos & negs */
		for (i = 0; i < nfloats; ++i)  noise[i] = frannor();
	break;
	case FLAT: /* franuni gives elements in [0, 1] */
		for (i = 0; i < nfloats; ++i)  noise[i] = 2.0*franuni() - 1.0;
	break;
	default:	/* defensive programming */
		err("%d: mysterious itype = %d", __LINE__, itype);
	}


	/* Band limit noise traces if user getpars any of the f's */
	if (getparfloat("f1", &f1) || getparfloat("f2", &f2) ||
	    getparfloat("f3", &f3) || getparfloat("f4", &f4) ) {

		/* Set up call to suband */
		char cmdbuf[BUFSIZ];	    /* build suband command	*/
		FILE *bandinfp;		    /* fp for input file	*/
		FILE *fp;                   /* fp for pipe to suband	*/
		int nsegy = HDRBYTES + databytes;
		char *segybuf = ealloc1(nsegy, 1);


		/* Trap signals so can remove tmpnam file */
		signal(SIGINT,  (void *) trapsig);
		signal(SIGQUIT, (void *) trapsig);
		signal(SIGHUP,  (void *) trapsig);
		signal(SIGTERM, (void *) trapsig);

		/* Prepare temporary files to hold traces */
		/*bandinfp  = etmpfile();*/
		bandinfp  = etempfile(NULL);
		/*bandoutfp = efopen(etmpnam(bandoutfile), "w+");*/
		bandoutfile = etempnam(scrdir,NULL) ;
		bandoutfp = efopen(bandoutfile, "w+");

		/* Paste headers on noise traces and put in tmpfile */
		rewind(hdrfp);
		{ register int itr;
		  for (itr = 0; itr < ntr; ++itr) {
			efread(&tr, 1, HDRBYTES, hdrfp);
			memcpy(tr.data, noise + itr*nt, databytes); 
			fputtr(bandinfp, &tr);
		  }
		}

		/* Pipe to suband - suband handles the getpars */
		sprintf(cmdbuf, "suband >%s", bandoutfile);
		fp = epopen(cmdbuf, "w");
		rewind (bandinfp);
		{ register int itr;
		  for (itr = 0; itr < ntr; ++itr) {
			efread(segybuf, 1, nsegy, bandinfp);
			efwrite(segybuf, 1, nsegy, fp);
		  }
		}
		efclose(bandinfp);
		epclose(fp);

		/* Load bandlimited traces back into noise vector */
		rewind(bandoutfp);
		{ register int itr;
		  for (itr = 0; itr < ntr; ++itr) {
			fgettr(bandoutfp, &tr);
			memcpy(noise + itr*nt, tr.data, databytes); 
		  }
		}
		efclose(bandoutfp);
		eremove(bandoutfile);

	} /* End optional bandlimiting */
		


	/* Compute noise power */
	noipow = 0.0;
	{ register int i;
	  for (i = 0; i < nfloats; ++i) {
		register float noiseval = noise[i];
		noipow += noiseval * noiseval;
	  }
	}


	/* Compute noise scale for desired noise/signal ratio */
	absmaxsig /= sqrt(2.0);  /* make it look like a rmsq value   */
	noipow /= nfloats;	 /* make it the square of rmsq value */
	noiscale = absmaxsig / (sn * sqrt(noipow));


	/* Add scaled noise to trace and output sum */
	rewind(hdrfp);
	rewind(sigfp);
	{ register int itr;
	  for (itr = 0; itr < ntr; ++itr) {
		register int trshift = itr*nt;
		register int i;

		efread(&tr, 1, HDRBYTES, hdrfp);
		efread(tr.data, 1, databytes, sigfp);
		for (i = 0; i < nt; ++i)
			tr.data[i] += noiscale * noise[trshift + i];

		puttr(&tr);
	  }
	}


	return EXIT_SUCCESS;
}
Esempio n. 14
0
main(int argc, char **argv)
{
        float **filter;         /* filter arrays                        */
        float *tf;              /* times at which filters are centered  */
        int *itf;               /* ... as integers                      */
	int jmin;		/* index of first filter itf value	*/
	int jmax;		/* index of last filter itf value	*/
        int nfft;     	        /* fft sizes in each time gate          */
        int nfreq;     	        /* number of frequencies  	        */
        float **ftrace;         /* filtered sub-traces                  */
        int nfilter;            /* number of filters specified          */
      	float dt;               /* sample spacing                       */
        float tmin;             /* first time on traces                 */
        int nt;                 /* number of points on input trace      */
	float *data;
	FILE *infp=stdin, *outfp=stdout;
        
        /* Initialize */
        initargs(argc, argv);
        requestdoc(1);


        /* Get info from first trace */ 
	file2g(infp);
	file2g(outfp);
        if (!fgettr(infp,&tr))  err("can't get first trace");
        if (tr.trid && tr.trid != TREAL)
                err("input is not seismic data, trid=%d", tr.trid);
        nt = tr.ns;
        if (!getparfloat("dt", &dt))    dt = (float)tr.dt/1000000.0;
        if (!dt) err("dt field is zero and not getparred");
	tmin = tr.delrt/1000.0;


        /* Get number of filters and center times */
        if (!(nfilter = countparval("tf")))  MUSTGETPARFLOAT("tf", tf);
	if (countparname("f") != nfilter)
		err("must give one f 4-tuple for each"
		    " (%d) tf value", nfilter);
		
	/* Leave room for possibly missing filters at endpoints */
	tf = ealloc1float(nfilter+4);  /* never use ist2 or last 2 */
	itf = ealloc1int(nfilter+4);
        getparfloat("tf", tf+2); jmin = 2; jmax = nfilter + 1;
	{ register int j;
          for (j = jmin; j <= jmax; ++j)  itf[j] = NINT((tf[j] - tmin)/dt);
        }

	

        /* Make filters with scale for inverse transform */
	nfft = npfaro(nt, LOOKFAC * nt);
	if (nfft >= MIN(SU_NFLTS, PFA_MAX))
		err("Padded nt=%d -- too big", nfft);
	nfreq = nfft/2 + 1;
	filter = ealloc2float(nfreq, nfilter+4); /* never use 1st & last */
        { register int j;
          for (j = jmin; j <= jmax; ++j) {
                float *f = ealloc1float(4);

                if (getnparfloat(j-jmin+1, "f", f) != 4)
                        err("must give 4 corner frequencies in f=");
        	if (f[0] < 0.0 || f[0] > f[1] ||
				  f[1] >= f[2] || f[2] > f[3])
               		err("Filter #%d has bad frequencies", j - jmin + 1);
                makefilter(f, nfft, nfreq, dt, filter[j]);
          }
        }
	


	/* User may not have given a filter for tmin and/or tmax--	*/
	/* Extend array so can always assume these filters are present.	*/
	/* Note don't really use any of the extra storage in **filter!	*/
	if (itf[jmin] > 0) {
		filter[jmin-1] = filter[jmin]; 
		itf[jmin-1] = 0;
		--jmin;
	}
	if (itf[jmax] < nt - 1) {
		filter[jmax+1] = filter[jmax];
		itf[jmax+1] = nt - 1;
		++jmax;
	}
	
	
	/* Extend array so can always consider time points to be interior */
	itf[jmin-1] = 0;      /* now jmin - 1 is a valid index */
	itf[jmax+1] = nt - 1; /* now jmax + 1 is a valid index */


        /* Main loop over traces */
        ftrace = ealloc2float(nt, nfilter+4); /* never use 1st & last */
	data = ealloc1float(nt);
        do {
                register int i, j;
		
		/* Construct filtered sub-traces */
		for (j = jmin; j <= jmax; ++j) {			
			bzero(data, nt*FSIZE);
			for (i = itf[j-1]; i <= itf[j+1]; ++i)
				data[i] = tr.data[i];
                        bandpass(data,nt,nfft,nfreq,filter[j],ftrace[j]);
                }

               /* Compose filtered trace from sub-traces */
               for (j = jmin; j < jmax; ++j) {
	       		float fitfj;
                        for (fitfj = i = itf[j]; i <= itf[j+1]; ++i) {
                                float a = (i - fitfj)/(itf[j+1] - fitfj);
                                tr.data[i] = (1-a)*ftrace[j][i] +
                                                 a*ftrace[j+1][i];
			}
                }
                
                fputtr(outfp,&tr);
        } while (fgettr(infp,&tr));

        return EXIT_SUCCESS;
}
Esempio n. 15
0
main(int argc, char* argv[] ){

   segytrace in;   /* input volume */
   segytrace out;

   FILE* infp  = stdin;
   FILE* outfp = stdout;

   int i;
   int j;
   int k;
   int w;

   int len;

   int a;
   int b;

   float sum[SU_NFLTS];
   float tmp[SU_NFLTS];

   initargs(argc, argv);
   askdoc(1);

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

   getparint( "len" ,&len );

   /*------------------------*/
   /* loop over input traces */
   /*------------------------*/

   memset( &in ,0 ,sizeof(in) );

   if( !fgettr( infp ,&in ) ){
      err( "Unable to read first trace!" );
   }

   /*---------------------*/
   /* check filter length */
   /*---------------------*/

   if( in.ns < len ){
      fprintf( stderr ,"filter too long for input\n" );
      exit(-1);

   }else{
      w = len / 2;
   }

   do {

      memset( tmp  ,0 ,sizeof(tmp) );
      memset( sum  ,0 ,sizeof(sum) );

      memset( &out ,0 ,sizeof(out) );
      memcpy( &out ,&in ,240 );

      /*--------------*/
      /* remove trend */
      /*--------------*/

      for( i=0; i<in.ns; i++ ){
         tmp[i] = in.data[i] 
                - (in.data[0] + i*(in.data[in.ns-1]-in.data[0])/in.ns);
      }

      /*---------------------*/
      /* forward integration */
      /*---------------------*/

      sum[0] = tmp[0];
 
      for( i=1; i<in.ns; i++ ){
         sum[i] = sum[i-1] + tmp[i];
      }

      /*----------------------*/
      /* backward integration */
      /*----------------------*/

      for( i=in.ns-2; i>=0; i-- ){
         sum[i] += sum[i+1];
      }

      /*-----------------*/
      /* leading segment */
      /*-----------------*/

      k = (w*w + w)/2;
      j = w;

      for( i=0; i<w; i++ ){

         k -= j;
         j--;

         out.data[i] = 2*sum[i] - sum[i+w] - sum[0];
         out.data[i] /= w*w - k;
         out.data[i] += (in.data[0] + i*(in.data[in.ns-1]-in.data[0])/in.ns);

      }

      /*-----------------*/
      /* central segment */
      /*-----------------*/

      for( i=w; i<in.ns-w; i++ ){

         out.data[i] = 2*sum[i] - sum[i-w] - sum[i+w];
         out.data[i] /= w*w;
         out.data[i] += (in.data[0] + i*(in.data[in.ns-1]-in.data[0])/in.ns);

      }

      /*------------------*/
      /* trailing segment */
      /*------------------*/

      k = 0;
      j = 0;

      for( i=in.ns-w; i<in.ns; i++ ){

         k += j;

         out.data[i] = 2*sum[i] - sum[i-w] + j*sum[in.ns-1];
         out.data[i] /= w*w - k;
         out.data[i] += (in.data[0] + i*(in.data[in.ns-1]-in.data[0])/in.ns);
         j++;

      }

      /*----------------*/
      /* output results */
      /*----------------*/

      if( outfp ){
         fputtr(outfp, &out);
      }

   } while (fgettr(infp, &in));

   return 0;

}
Esempio n. 16
0
main(int argc, char **argv)
{
    	int nt,nxi,nxo,ntfft,it,ix,nf,i,extrap;
	int nxipre;
    	float dt,fmin,fmax;
    	float *xi, *xo, *xipre;
    	float *yi, *yo;
    	char *hdrs;
    	float tol;
    	int niter, np;
    	string datain, dataout;
	complex *ccexp, *ccexpo;
	int iccexp=1, iccexpo=1;
	int nxip, ifmin, lftwk, npp, nph;
	float tmp, tmp2;
	float df; 

    	FILE *infp,*outfp;

	segytrace tr;

	String pkey="tracl", ptype, skey="tracr", stype;
     	Value pval, sval;
       	int indxp, indxs;

	int ofill=0, dfill=1, nfill=1;
	int iof=1, inf=1;
	int nsmax, ns; 
	int is, ip, ipre;


	float *sort;
	int *sortindex;
	char *hdrsort;



    	/* get parameters */
    	initargs(argc,argv);
    	askdoc(1);

	getparstring("pkey",&pkey);
	getparstring("skey",&skey);
	if(!getparint("ofill",&ofill)) iof = 0 ;
        if(!getparint("dfill",&dfill)) dfill = 1;
       	if(!getparint("nfill",&nfill))inf = 0;
     	if (!getparint("nsmax",&nsmax)) nsmax = 2000;

	/* open input/output */
    	if (!getparstring("datain",&datain)) {
		infp = stdin;
	} else {
		infp = fopen(datain,"r");
	}
    	if (!getparstring("dataout",&dataout)) {
		outfp = stdout;
	} else {
		outfp = fopen(dataout,"w");
	}
	/* make file size to be able to exceed 2 G on convex */
	file2g(infp);
	file2g(outfp);

	/* read in first trace for nt and dt */
        if (!fgettr(infp,&tr))  err("can't get first trace");
	nt = tr.ns; 
	dt = (float)tr.dt/1000000.;

	/* optional parameters */
    	if (!getparint("ntfft",&ntfft)) ntfft=(nt*3/2)/2*2;
    	if (ntfft < nt) ntfft = nt;
	nf = ntfft;
	radix_(&nf,&ntfft);
    	if (!getparfloat("fmin",&fmin)) fmin = 0.;
    	if (!getparfloat("fmax",&fmax)) fmax = .5 / dt * 2. / 3.;
    	if (!getparint("niter",&niter)) niter = 10; 
    	if (!getparfloat("tol",&tol)) tol = 0.000001;
    	if (!getparint("extrap",&extrap)) extrap = 1; 


        ptype  = hdtype(pkey);
	indxp = getindex(pkey);
	stype  = hdtype(skey);
	indxs = getindex(skey);
	gethval(&tr, indxp, &pval);
	ipre = vtoi(ptype,pval);
	gethval(&tr, indxs, &sval);
	is = vtoi(stype,sval);

	nxo = nfill;
	if(inf==0) nxo = nsmax;

    	xi = (float*)malloc(nsmax*sizeof(float));
    	xipre = (float*)malloc(nsmax*sizeof(float));
    	yi = (float*)malloc(nt*nsmax*sizeof(float));
    	xo = (float*)malloc(nxo*sizeof(float));
    	yo = (float*)malloc(nt*nxo*sizeof(float));
	hdrs = (char*) malloc(nsmax*HDRBYTES*sizeof(char));

	sort = (float*)malloc(nsmax*nt*sizeof(float));
	hdrsort = (char*)malloc(nsmax*HDRBYTES);
	sortindex = (int*)malloc(nsmax*sizeof(int));

	iccexp = 1;
	nxip = nsmax + 10;
    	initpf_(&ntfft,&dt,&fmin,&fmax,&nxip,&ifmin,&df,
		&nf,&lftwk,&npp,&nph);
	tmp = (nph*2+1)*nf*nxip;
	tmp = tmp*sizeof(complex);

	if( tmp > 1600000000. ) {
		fprintf(stderr," --- forward t-p coefficients --- " );
		fprintf(stderr," need memory %f MB \n",tmp/1000000.);
		fprintf(stderr," memory limit exceeded \n");
		fprintf(stderr," no pre-computation of coefficients \n");
		iccexp = -1; 
		ccexp = (complex*) malloc(sizeof(complex));
		tmp = 0.;
	} else {
		ccexp = (complex*) malloc((nph*2+1)*nf*nxip*sizeof(complex));
	}

	iccexpo = 1;
	tmp2 = (nph*2+1)*nf*nxo;
	tmp2 = tmp2*sizeof(complex);
	tmp = tmp + tmp2;
	if( tmp > 1600000000. ) {
		fprintf(stderr," --- inverse t-p coefficients --- " );
		fprintf(stderr," need memory %f MB \n",tmp/1000000.);
		fprintf(stderr," memory limit exceeded \n");
		fprintf(stderr," no pre-computation of coefficients \n");
		iccexpo = -1; 
		ccexpo = (complex*) malloc(sizeof(complex));
	} else {
		ccexpo = (complex*) malloc((nph*2+1)*nf*nxo*sizeof(complex));
	}

   	for(ix=0;ix<nxo;ix++) xo[ix] = ofill + ix*dfill;

	/* loop over input traces */
	ns = 0;
	nxipre = 0;

	do {

	
                gethval(&tr, indxp, &pval);
		ip = vtoi(ptype,pval);
		gethval(&tr, indxs, &sval);
		is = vtoi(stype,sval);

		if(ns>nsmax) 
			err("maximum number traces %d exceed %d \n",ns,nsmax);

		if(ip==ipre) {

			for(it=0;it<nt;it++) yi[it+ns*nt] = tr.data[it];
			xi[ns] = is;
			bcopy((char*)&tr,hdrs+ns*HDRBYTES,HDRBYTES);
			ns = ns + 1;

		} else if(ip!=ipre && ns>0) {

			nxi = ns;
			/* sort xi into ascending order */
			for(i=0;i<nxi;i++) sortindex[i] = i;
			qkisort(nxi,xi,sortindex);
			bcopy(yi,sort,nxi*nt*sizeof(float));

			for(i=0;i<nxi;i++) {
               			bcopy(sort+sortindex[i]*nt,yi+i*nt,
					nt*sizeof(float));
			}

			bcopy(xi,sort,nxi*sizeof(float));
			for(i=0;i<nxi;i++) {
               			xi[i] = sort[sortindex[i]];
			}

			bcopy(hdrs,hdrsort,nxi*HDRBYTES);
			for(i=0;i<nxi;i++) {
			    bcopy(hdrsort+sortindex[i]*HDRBYTES,
				hdrs+i*HDRBYTES,HDRBYTES);
			}

			np = nxi;

			if(inf==0) nxo = nxi;
			if(iof==0) {
				for(ix=0;ix<nxo;ix++) xo[ix] = xi[ix];
			}

			/* tau-p interpolation */
			intps(xi,yi,xo,yo,nxi,nxo,
				nt,dt,np,fmin,fmax,ntfft, 
				niter,tol,xipre,nxipre,ccexp,iccexp,
				ccexpo,iccexpo);
			for(ix=0;ix<nxi;ix++) {
				xipre[ix] = xi[ix];
			}
			nxipre = nxi;


			/* output gather */
			intout(xi,xo,yo,hdrs,nxi,nxo,nt,
				outfp,extrap,stype,indxs);

			fprintf(stderr,
" interpolation done from input %d live traces to output %d traces at %s=%d \n",nxi, nxo, pkey, ipre);

			ns = 0;
			for(it=0;it<nt;it++) yi[it+ns*nt] = tr.data[it];
			xi[ns] = is;
			bcopy((char*)&tr,hdrs+ns*HDRBYTES,HDRBYTES);

			ipre = ip;
			ns = ns + 1;
		}
			
	} while(fgettr(infp,&tr)); 
			

	if (ns>0) {

		nxi = ns;

		for(i=0;i<nxi;i++) sortindex[i] = i;
		qkisort(nxi,xi,sortindex);
		bcopy(yi,sort,nxi*nt*sizeof(float));

		for(i=0;i<nxi;i++) {
       			bcopy(sort+sortindex[i]*nt,yi+i*nt,
			nt*sizeof(float));
		}
		bcopy(xi,sort,nxi*sizeof(float));
		for(i=0;i<nxi;i++) {
               		xi[i] = sort[sortindex[i]];
		}
		bcopy(hdrs,hdrsort,nxi*HDRBYTES);
		for(i=0;i<nxi;i++) {
		    bcopy(hdrsort+sortindex[i]*HDRBYTES,
			hdrs+i*HDRBYTES,HDRBYTES);
		}

		np = nxi;

		if(inf==0) nxo = nxi;
		if(iof==0) {
			for(ix=0;ix<nxo;ix++) xo[ix] = xi[ix];
		}

		/* interpolation */
                intps(xi,yi,xo,yo,nxi,nxo,nt,dt,np,fmin,fmax,ntfft,niter,tol,
			xipre,nxipre,ccexp,iccexp,
			ccexpo,iccexpo);
		/* output gather */
		intout(xi,xo,yo,hdrs,nxi,nxo,nt,outfp,extrap,stype,indxs);

		fprintf(stderr,
" interpolation done from input %d live traces to output %d traces at %s=%d \n",nxi, nxo, pkey, ip);

	}


    	free(xi);
    	free(yi);
    	free(xo);
    	free(yo);
	free(hdrs);
	free(sort);
	free(sortindex);
	free(hdrs);

	return 0;

}
Esempio n. 17
0
int
main(int argc, char **argv)
{       
    FILE *dfp, *wfp;
    int smooth, verbose; /* flags */
    int i,icomp;    /* indices for components (in loops) */
    int nt;           /* number of time samples in one trace */
    int isl;          /* smoothing window length in samples */
    int itr;          /* trace number */
    char *wfile;      /* file containing weighting function */
    char *dfile;      /* file containing direction of polarization */ 
    float sl;         /* smooth window length in seconds */
    float dt;         /* sampling intervall in seconds */
    float wpow;       /* exponent of weighting function of filter */
    float dpow;       /* exponent of directivity functions */

    /* 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("wfile", &wfile)) wfile="polar.rl";
    if (!getparstring("dfile", &dfile)) dfile="polar.dir";
    if (!getparfloat("sl", &sl)) sl = 0.05;
    if (!getparfloat("dt", &dt)) dt = ((double) tr.dt)/1000000.0;
    if (!getparfloat("wpow", &wpow)) wpow = 1.0;
    if (!getparfloat("dpow", &dpow)) dpow = 1.0;
    if (!getparint("smooth", &smooth)) smooth = 1;
    if (!getparint("verbose", &verbose)) verbose = 0;

    /* convert seconds to samples */
    if (!dt) {
        dt = 0.004;
        warn("dt not set, assuming dt=0.004");
    }
    isl = NINT(sl/dt);
        
    if (verbose && smooth) warn("smoothing window = %d samples", isl);

    /* Open the other two files and read first trace(s) */
    if (!(dfp=fopen(dfile,"r"))) err("file %s does not exist", dfile);
    if (!(wfp=fopen(wfile,"r"))) err("file %s does not exist", wfile);
    if(!fgettr(dfp,&dtr)) err("can't get first trace of %s",dfile);
    if(!fgettr(wfp,&wtr)) err("can't get first trace of %s",wfile);
    

    /* data validation */
    if (smooth && isl<1) err("sl=%g must be positive", sl);
    if (smooth && isl>nt) err("sl=%g too long for trace", sl);
    if (nt!=dtr.ns) 
        err("stdin and %s have different ns (%d vs %d)", dfile, nt, dtr.ns);
    if (nt!=wtr.ns) 
        err("stdin and %s have different ns (%d vs %d)", wfile, nt, wtr.ns);
    
    /* loop over traces */
    icomp=0;
    itr=1;
    do {
       for (i=0;i<nt;i++) {
            dtr.data[i]=pow(fabs(dtr.data[i]),dpow);
        }
        if (smooth) do_smooth(dtr.data,nt,isl);
        if (!icomp) {
            for (i=0;i<nt;i++) {
                wtr.data[i]=pow(wtr.data[i],wpow);
            }
            if (smooth) do_smooth(wtr.data,nt,isl);
        }
        
        for (i=0;i<nt;i++) {
            tr.data[i]*=dtr.data[i]*wtr.data[i];
        }

        puttr(&tr);
      
        icomp++;
        if (icomp==3) {
            icomp=0;
            if (!fgettr(wfp,&wtr)) break;
        }
        itr++;
    } while(gettr(&tr) && fgettr(dfp,&dtr));
    
    if (verbose) warn("processed %d traces",itr);
    return(CWP_Exit());           
}
Esempio n. 18
0
main(int argc, char **argv)
{
	int nt, ntmax, nx, nz;
	int nzt, nxt, nst;
	float smint, xmint, zmint, dst, dxt, dzt;
	float x0, z0, dx, dz, dt, tmin;
	float ofimin, ofomin, dofo, ofimax, ofomax;
	float ofomini, dcdp;
	int nofo, lt, ntrace, i2p5;
	int nofoi,amptype;
	string ampfile, timefile;
	int iamp, *mtrace;
	FILE *infp, *outfp, *testfp;
	string datain, dataout, datains;
	char **dataini, **dataouti;
	char *dipfile="NULL";
	int im, nm, kofo, lseekout;
	int iofo, ix, ltrace;
	int intps,intpx,intpz,isize;
	int iofpm, intype, *lseekini; 
	int sort, mlimit;
	int dcdpout, fcdpout, tracl;
	int lagc;
        float tpow, aper, apan, apanl, apanr, v0, dxdip, dxtol;
	int lmem, idip, nxdip, llimit;
	float tmp;


        segychdr sgycrd ;
        segybhdr sgybin ;
	ghed gh; 
	float fhread;
	int ihread;
	int ierr=1;
	
	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);

/* copy tape header and binary header from datain to dataout */
	if (!getparstring("datain", &datain)) err("must specify datain"); 
	if (!getparstring("dataout", &dataout)) err("must specify dataout"); 
	if (!getparstring("datains", &datains)) datains=datain;

	if((infp = fopen(datain,"r"))==NULL)
		err("Input dataset %s not found \n",datain);

	outfp = efopen(dataout,"w");
       
        fgethdr(infp,&sgycrd,&sgybin) ;
	if(strncmp((char*)&sgycrd, "C 1 CLIENT",10)!=0) 
		err(" Input Not IEEE SEGY");

	/* Get info from first trace */ 
	if (!fgettr(infp,&tra))  err("can't get first trace");
	ntmax = tra.ns;

	fclose(infp);

/* parameters fetching */
	if (!getparint("nt", &nt)) nt = ntmax; 
	if ( nt > ntmax ) nt = ntmax;
	if (!getparfloat("dt", &dt)) dt = tra.dt/1000000.0;
	   if (!dt) err("invalid sampling interval");
	if (!getparfloat("tmin", &tmin)) tmin = tra.delrt/1000.0;

	if (!getparfloat("x0", &x0)) err("x0 missing from parameter list ");
	if (!getparfloat("dx", &dx)) dx = 0.0;
           if(dx <= 0.) err("x sampling interval invalid", dx);
	if (!getparint("nx", &nx))	nx = 0;
           if(nx <= 0) err("number of output x positions invalid", nx);
	if (!getparfloat("z0", &z0)) err("z0 missing from parameter list ");
	if (!getparfloat("dz", &dz))	dz = 0.0;
           if(dz <= 0.) err("z sampling interval invalid", dz);
	if (!getparint("nz", &nz))	nz = 0;
           if(nz <= 0) err("number of output z positions invalid", nz);

	if (!getparfloat("ofimin", &ofimin)) ofimin = 0.;   
	if (!getparfloat("ofimax", &ofimax)) ofimax = 999999.;   

	if (!getparfloat("ofomin", &ofomin)) ofomin = 0.;   
	if (!getparfloat("dofo", &dofo)) dofo = 999999.;   
	if (!getparint("nofo", &nofo)) nofo = 1;   
	ofomax = ofomin + (nofo-1)*dofo;

/* get parameters for travel time table and amplitude table */
	if (!getparstring("timefile", &timefile)) err("must specify timefile"); 

	/*check to see if timefile exist */
	if((testfp = fopen(timefile,"r"))==NULL)
		err("Input timefile %s not found \n",timefile);

	/* get header of time file */ 
	ierr = fgetghdr(testfp,&gh);
	if(ierr!=0) warn(" warning: non-standard timefile input \n");
	fclose(testfp);

	/* get dipfile */
	idip = 0;
	if(getparstring("dipfile", &dipfile)) {
		idip = 1;
		if((testfp = fopen(dipfile,"r"))==NULL)
			err("Input dipfile %s not found \n",dipfile);
		fclose(testfp);
	}

	if(!getparfloat("dxdip", &dxdip)) dxdip = 50. * dx;

	/*check to see if ampfile exist */
	iamp = 1;
	if (!getparstring("ampfile", &ampfile)) iamp=0;   
	if(iamp==1) {
		if((testfp = fopen(ampfile,"r"))==NULL)
			err("Input ampfile %s not found \n",ampfile);
		fclose(testfp);
	}

	/* check the following nine parameters */
	if (!getparfloat("zmint", &zmint)) {
		if(ierr==0) {
			getgval(&gh,"o1",&zmint);
		} else {
			zmint = z0;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"o1",&fhread);
			if(fabs(fhread-zmint)>0.01) 
				err(" check zmint & timefile ");	
		}
	}
	if (!getparfloat("xmint", &xmint)) {
		if(ierr==0) {
			getgval(&gh,"o2",&xmint);
		} else {
			xmint = x0;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"o2",&fhread);
			if(fabs(fhread-xmint)>0.01) 
				err(" check xmint & timefile ");	
		}
	}
	if (!getparfloat("smint", &smint)) {
		if(ierr==0) {
			getgval(&gh,"o3",&smint);
		} else {
			smint = x0;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"o3",&fhread);
			if(fabs(fhread-smint)>0.01)
				 err(" check smint & timefile ");	
		}
	}
	if (!getparfloat("dzt", &dzt)) {
		if(ierr==0) {
			getgval(&gh,"d1",&dzt);
		} else {
			dzt = dz;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"d1",&fhread);
			if(fabs(fhread-dzt)>0.01) 
				err(" check dzt & timefile");	
		}
	}
	if (!getparfloat("dxt", &dxt)) {
		if(ierr==0) {
			getgval(&gh,"d2",&dxt);
		} else {
			dxt = dx;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"d2",&fhread);
			if(fabs(fhread-dxt)>0.01)
				 err(" check dxt & timefile");	
		}
	}
	if (!getparfloat("dst", &dst)) {
		if(ierr==0) {
			getgval(&gh,"d3",&dst);
		} else {
			dst = dx;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"d3",&fhread);
			if(fabs(fhread-dst)>0.01) 
				err(" check dst & timefile");	
		}
	}
	if (!getparint("nzt", &nzt)) {
		if(ierr==0) {
			getgval(&gh,"n1",&fhread);
			fhread = fhread + 0.5;
			nzt = (int) fhread;
		} else {
			nzt = nz;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"n1",&fhread);
			fhread = fhread + 0.5;
			ihread = (int) fhread;
			if(ihread!=nzt) err(" check nzt & timefile ");	
		}
	}
	if (!getparint("nxt", &nxt)) {
		if(ierr==0) {
			getgval(&gh,"n2",&fhread);
			fhread = fhread + 0.5;
			nxt = (int) fhread;
		} else {
			nxt = nx;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"n2",&fhread);
			fhread = fhread + 0.5;
			ihread = (int) fhread;
			if(ihread!=nxt) err(" check nxt & timefile ");	
		}
	}
	if (!getparint("nst", &nst)) {
		if(ierr==0) {
			getgval(&gh,"n3",&fhread);
			fhread = fhread + 0.5;
			nst = (int) fhread;
		} else {
			nst = nx;
		}
	} else {
		if(ierr==0) {
			getgval(&gh,"n3",&fhread);
			fhread = fhread + 0.5;
			ihread = (int)fhread;
			if(ihread!=nst) err(" check nst & timefile ");	
		}
	}

	if (smint>x0) warn("=====> smint > x0 <=====\n");
        if (zmint>z0) warn("=====> zmint > z0 <=====\n");
        if (xmint>x0) warn("=====> xmint > x0 <=====\n");
        if ((smint+(nxt-1)*dxt)<(x0+(nx-1)*dx))
         warn ("=====> (smint+(nxt-1)*dxt) < (x0+(nx-1)*dx) <=====\n");
        if ((xmint+(nxt-1)*dxt)<(x0+(nx-1)*dx))
         warn ("=====> (xmint+(nxt-1)*dxt) < (x0+(nx-1)*dx) <=====\n");
        if ((zmint+(nzt-1)*dzt)<(z0+(nz-1)*dz))
         warn ("=====> (zmint+(nzt-1)*dzt) < (z0+(nz-1)*dz) <=====\n");

	if (!getparint("nm", &nm)) nm = 1;   
	if (!getparint("i2p5", &i2p5)) i2p5 = 1;   
	if (!getparint("intype", &intype)) intype = 0 ;   
	if (!getparfloat("dcdp", &dcdp)) dcdp = 0. ;   
	if (!getparint("sort", &sort)) sort = 0 ;   
	if (!getparint("amptype", &amptype)) amptype = 0 ;   
	if (!getparint("mlimit", &mlimit)) mlimit = 48 ;   
	if (!getparint("fcdpout", &fcdpout)) fcdpout = 1 ;   
	if (!getparint("dcdpout", &dcdpout)) dcdpout = 1 ;   
	if (!getparint("lagc", &lagc)) lagc = 0 ;
        if (!getparfloat("tpow", &tpow)) {
                if(lagc==0) {
                        tpow = 0. ;
                } else {
                        tpow = -2. ;
                }
        }
        if (!getparfloat("aper", &aper)) aper=nx*dx/4.;
        if (!getparfloat("apan", &apan)) apan=60.;
	if (!getparfloat("apanl", &apanl)) apanl=-apan;
        if (!getparfloat("apanr", &apanr)) apanr=apan;

	if (apanl<-89.9) apanl = -89.9;
        if (apanl>89.9) apanl = 89.9;
        if (apanl>-0.1 && apanl <0.1) {
		if(apanl>=0) {
			apanl = 0.1;
		} else {
			apanl = -0.1;
		}
	}
	if (apanr<-89.9) apanr = -89.9;
        if (apanr>89.9) apanr = 89.9;
        if (apanr>-0.1 && apanr <0.1) {
		if(apanr>=0) {
			apanr = 0.1;
		} else {
			apanr = -0.1;
		}
	}

        if (!getparfloat("v0", &v0)) v0=1500.;
        if (!getparfloat("dxtol", &dxtol)) dxtol=1.;
	if(dxtol<0.) dxtol = - dxtol;


/* update binary header */
        sgybin.hns = nz ;
        sgybin.ntrpr = nx ;
        sgybin.hdt = (short) ( dz < 1. ? dz*1000. : dz );
        sgybin.fold = nofo;
        sgybin.tsort = 3;
	
	
        fputhdr(outfp,&sgycrd,&sgybin) ;

	/* set length of migration trace to lt to intepolate input traces */
	if (!getparint("lt", &lt)) lt = 4*nt;   
	if (lt<nt) lt=nt;
        lt = lt/nt*nt;
	
/* number of offsets per subprocess to migrate */
	iofpm = (nofo+nm-1)/nm;

  	intpx = 1;
        if(x0==xmint && dx==dxt && nx<=nxt) intpx=0;
        intpz = 1;
        if(z0==zmint && dz==dzt && nz==nzt) intpz=0;
        intps = 1;
        if(x0==smint && dx==dst && nx<=nst) intps=0;
	
	fprintf(stderr,"x0=%f z0=%f nx=%d nz=%d \n",x0,z0,nx,nz);
        fprintf(stderr,"dx=%f dz=%f \n",dx,dz);
        fprintf(stderr,"timefile=%s \n",timefile);
        fprintf(stderr,"ampfile=%s \n",ampfile);
        fprintf(stderr,"nt=%d dt=%f tmin=%f \n",nt,dt,tmin);
        fprintf(stderr,"ofomin=%f dofo=%f nofo=%d \n",ofomin,dofo,nofo);
        fprintf(stderr,"xmint=%f zmint=%f smint=%f \n",xmint,zmint,smint);
        fprintf(stderr,"dxt=%f dzt=%f dst=%f \n",dxt,dzt,dst);
        fprintf(stderr,"nxt=%d nzt=%d nst=%d \n",nxt,nzt,nst);
        fprintf(stderr,"lt=%d i2p5=%d \n",lt,i2p5);
	fprintf(stderr,"intps=%d intpx=%d intpz=%d\n",intps,intpx,intpz);


	tmp = nx * dx / dxdip;
	nxdip = (int)tmp;
	/* compute memory requirements */
	lmem = (2*nzt*nxt + iofpm*(nx*nz+1) + 4*nx*nz + nx + 2*nz
                + nzt + 2*lt + nt)*sizeof(float)
              +(nx + nz) * sizeof(int) + idip*2*nxdip*nz*sizeof(float);
	lmem = lmem + nzt*nxt*nst*sizeof(short) +
		iamp * (nzt*nxt*nst*sizeof(short)+nzt*(nxt+1)*sizeof(float));

        fprintf(stderr," \n");
        fprintf(stderr," KIRMIG needs memory size=%d \n",lmem);
        fprintf(stderr," \n");
	
        llimit = mlimit * 1024 * 1024;
        if ( lmem > llimit ) {
	   fprintf(stderr,"travel time table disk i/o used \n");
	   if(iamp==1) fprintf(stderr,"amplitude table disk i/o used \n");
	   lmem = lmem - nzt*nxt*nst*sizeof(short) -
		iamp * (nzt*nxt*nst*sizeof(short)+nzt*(nxt+1)*sizeof(float));
           if ( lmem > llimit ) {
           	err("Need at least memory size mlimit=%d (Bytes)\n",lmem);
	   }
        }



	mtrace = (int *)malloc(nm*sizeof(int));
	lseekini = (int *)malloc(nm*sizeof(int));
	dataini = (char**) malloc(nm*sizeof(char *));
	dataouti = (char**) malloc(nm*sizeof(char *));

       	for(im=0;im<nm;im++) {
              dataouti[im] = (char*) malloc(strlen(dataout)+10);
              sprintf(dataouti[im],"%s%d",dataout,im+1) ;
        }

/* test to see if output offsets were created in the previous run */
        for(im=0;im<nm;im++) {
              nofoi = iofpm;
              kofo = im * iofpm + 1;
              if (kofo+nofoi-1 > nofo ) nofoi = nofo - kofo + 1;
              isize=0;
              if((infp = fopen(dataouti[im],"r"))!=NULL) {
                 fseek(infp,0L,SEEK_END);
                 isize= (int) ftell(infp);
                 fclose(infp);
              }
              if( isize!=(nz*sizeof(float)+HDRBYTES)*nx*nofoi ) {
                        isize = 0;
                        break;
              }
        }
        if(isize!=0) goto no_migration;


/* sort data into common offsets for each machine*/
	if ( nm > 1 && intype == 0 ) {
	   FILE ** fdataini  ;

	   fdataini = (FILE**) malloc(sizeof(FILE *)*nm);
	   for(kofo=1;kofo<=nm;kofo++) {
	      dataini[kofo-1] = (char*) malloc(strlen(datains)+10);
	      sprintf(dataini[kofo-1],"%s%d",datains,kofo) ;
	      if(sort==0 || sort==2) 
			fdataini[kofo-1] = efopen(dataini[kofo-1],"w") ;
           }

	   if ( sort == 0 || sort==2 ) {
	      infp = efopen(datain,"r");
	      fseek(infp,EBCBYTES+BNYBYTES,SEEK_SET);
	      while( fgettr(infp,&tra) ) {
	         float offset = tra.offset;
                 /* offset = tra.gx - tra.sx; */
                 iofo =  (int) ( ( fabs(offset) - ofomin ) /dofo  + 1.5 );
	         im = (iofo+iofpm-1)/iofpm;
	
	         if(iofo>0 && iofo<=nofo) fputtr(fdataini[im-1],&tra);
	      }
	      fclose(infp);
	   }
	   for(im=0; im<nm ; im++) {
	      if(sort==0 || sort==2) fclose(fdataini[im]) ;
              lseekini[im] = 0 ;
           }
	} 
	else if(nm>1 && intype == 1 ) {

	/* find out the average number of traces per machine to mig */
	   int ntrpm, trlen,jm;
	   infp = efopen(datain,"r");
	   fseek(infp,0L,SEEK_END);
	   trlen = ntmax*sizeof(float)+HDRBYTES; 
	   ntrpm = ((int)ftell(infp)-(EBCBYTES+BNYBYTES) )/trlen/nm; 
           ntrpm -= 1 ; /* to be "in average" before the offset to point to */

	/* find out where to seek */
	   lseekini[0] = EBCBYTES+BNYBYTES;
	   for( im=0; im<nm; im++ ) {
               int before = (im==0) ? 1 : 0 ;
	       fseek(infp,lseekini[im],SEEK_SET);
	       while( fgettr(infp,&tra) ) {
	          float offset = tra.offset;
		  if (offset<0.) 
			err("Negative offsets not allowed for intype=1 \n");
		  /* offset = tra.gx - tra.sx; */
                  iofo = (int)( ( fabs(offset) - ofomin ) /dofo + .5 ) ;
	          jm = iofo/iofpm;
                  if( jm < im ) {
                     /* smaller offset: increment the seek position */
                     before = 1 ;
                     lseekini[im] += trlen ;
                  } else if( jm == im && before ) {
                     /* initialize next machine seek position */
                     if( im < nm-1 ) lseekini[im+1] = lseekini[im]+trlen*ntrpm;
                     break ;
                  } else {
                     /* bigger or equal offset: I have to go back of 2 traces */
                     lseekini[im] -= trlen ;
	             fseek(infp,-2*trlen,SEEK_CUR);
                  } 
               }
               dataini[im] = datain ;
	   }
	   fclose(infp);
	} 
	else {
           dataini[0] = datain ;
           lseekini[0] = EBCBYTES+BNYBYTES ;
        }

        kofo = 0;

        dispatcher_attributes(argv[0],0) ;
	init_dispatch();
	
	for(im=0; im<nm ; im++) {
	      kofo = im * iofpm + 1;
              ofomini = ofomin + (kofo-1)*dofo;
              mtrace[im] = 0 ;
	      nofoi = iofpm;
	      if (kofo+nofoi-1 > nofo ) nofoi = nofo - kofo + 1; 
/* temporary dataset */
	      dataouti[im] = (char*) malloc(strlen(dataout)+10);
              sprintf(dataouti[im],"%s%d",dataout,im+1) ;
	      lseekout=0;
	      isize=0;
	      if((infp = fopen(dataouti[im],"r"))!=NULL) {
	         fseek(infp,0L,SEEK_END);
		 isize= (int) ftell(infp);
		 fclose(infp);
	      }

	      if ( nofoi<= 0 ) continue;	

	      if( isize!=(nz*sizeof(float)+HDRBYTES)*nx*nofoi ) {
                 
	         fprintf(stderr,"start dispatch im=%d \n",im+1);

	         dispatch("kirmigs",dataini[im],dataouti[im],
                                    lseekini[im],lseekout,
                                    timefile,ampfile,iamp,
                                    nt,nx,nz,lt,
                                    tmin,x0,z0,
                                    dt,dx,dz,
                                    smint,xmint,zmint,
                                    dst,dxt,dzt,
                                    nst,nxt,nzt,
                                    ofimin,ofimax,
                                    ofomini,dofo,nofoi,
                                    mtrace+im,i2p5,
				    intps,intpx,intpz,intype,dcdp,
				    amptype,mlimit,lagc,tpow,aper,apanl,apanr,
				    v0,fcdpout,dcdpout,dipfile,dxdip,dxtol);
	      }

	}
	wait_dispatched();

	no_migration:

   	fprintf(stderr,"Starting merge of %d offset datasets \n",nm);

	ntrace = 0;
        for(im=0; im<nm; im++ ) {
	    if(mtrace[im]==0) {
		warn(" zero trace migrated at im=%d \n",mtrace[im]);
	    } else if(mtrace[im]<0) {
		err(" error occured at im=%d",mtrace[im]);
	    }
	    ntrace = ntrace + mtrace[im];
        }
/* remove temporary input common-offset data sets */

       if( nm > 1 && intype == 0 && sort<=1 ) {
  	   for(kofo=0;kofo<nm;kofo++) {
            	unlink(dataini[kofo]); 
            /*  eremove(dataini[kofo]); */
           }
        }

	/* if( ntrace == 0 ) return 1 ; */

/* copy data from temporary datasets to output */
	fseek(outfp,EBCBYTES+BNYBYTES,SEEK_SET);

	tracl = 1;
	for(im=0;im<nm;im++) {
	      infp = efopen(dataouti[im],"r");
	      ltrace = nz*sizeof(float) + HDRBYTES;
	      nofoi = iofpm;
	      kofo = im * iofpm + 1;
	      if (kofo+nofoi-1 > nofo ) nofoi = nofo - kofo + 1; 
	      for(iofo=0;iofo<nofoi;iofo++) {
	         for(ix=0;ix<nx;ix++) {
		    fread((char *)&tra,sizeof(char),ltrace,infp);
		    tra.cdp = fcdpout + ix * dcdpout;
		    tra.cdpt = iofo + 1;
		    tra.mute = 0;
		    tra.muts = 0;
		    tra.mutb = 0;
		    tra.dz = dz;
		    tra.fz = z0;
		    tra.tracl = tracl;
		    fwrite((char *)&tra,sizeof(char),ltrace,outfp);
		    tracl = tracl + 1;
	         }
	      }
	      fclose(infp);
	      eremove(dataouti[im]);
	}
	      fclose(outfp);

   fprintf(stderr,"KIRMIG COMPLETED for total number of traces =%d \n",ntrace);
	
        return 0;
}
Esempio n. 19
0
main(int argc, char **argv)
{
    string ggfile;
    FILE *infp=stdin,*outfp=stdout,*gfp;
    int idz, nz, rsampz;
    int nzg, jz;
    float dz, dzint,z; 	
    float fzg, dzg; 
    float *gamgrid, *g2m1, *mout2, *dataint, *zint, *zx , *mute;
    float *g2;
    int oldcdp, oldoffset,ncdpg;
    float cdpming, dcdpg;
    float smute, osmute, odz, odz2, z0, fz;
    int mutes, newgamma ;
    int indz, indx, nzint, iz;
    float temp, res, zzint, odzint, str;
    int ierr;


    /* get parameters */
    initargs(argc,argv);
    askdoc(1);
/* read in first trace */
    if (!fgettr(infp,&tr)) err("can't get first trace");
    idz = tr.dt;
    if ( idz > 1000 ) idz = idz/1000;
    dz = idz;
    fz = tr.delrt/dz;
    if ( fz >1000. ) fz=fz/1000.;

    /* if dz defined in segy trace header, get it */
    if ( tr.dz != 0. ) {
	dz = tr.dz;
	fz = tr.fz;
    }

    nz = tr.ns;
    if ( !getparstring("ggfile",&ggfile)) err("ggfile must be given ! \n");
    if ( !getparfloat("smute",&smute)) smute=1.5;
    /* open ggfile and read header */
    gfp = efopen(ggfile,"r");
    ierr = fgetghdr(gfp,&gh);

	if(ierr!=0) warn(" grid header error \n");

    if ( !getparfloat("cdpming",&cdpming) ) {
	if(ierr==0) {
		getgval(&gh,"ocdp2",&cdpming);
		if(cdpming==0.) 
	      err(" grid file gh.ocdp2=0.; update gh.ocdp2 or spicify cdpming");
	} else {
		cdpming = tr.cdp;
	}
    }
    if ( !getparfloat("dcdpg",&dcdpg) ) {
	if(ierr==0) {
		getgval(&gh,"dcdp2",&dcdpg);
		if(dcdpg==0.) 
		err(" grid file gh.dcdp2=0.; update gh.dcdp2 or spicify dcdpg");
	} else {
		dcdpg = 1;
	}
    }
    if ( !getparfloat("fzg",&fzg) ) {
	if(ierr==0) {
		getgval(&gh,"o1",&fzg);
	} else {
		fzg = fz;
	}
    }
    if ( !getparfloat("dzg",&dzg) ) {
	if(ierr==0) {
		getgval(&gh,"d1",&dzg);
	} else {
		dzg = dz;
	} 
    }	

    if ( !getparint("nzg",&nzg) ) {
	if(ierr==0) {
		nzg = (int) (float)( gh.n1/gh.scale + 0.00001);
	} else {
		nzg = nz;
	}
    }
    if ( !getparint("ncdpg",&ncdpg) ) {
	if(ierr==0) {
		ncdpg = (int) (float)( gh.n2/gh.scale + 0.00001);
	} else {
    		fseek(gfp,0L,2);
    		ncdpg = ftell(gfp)/sizeof(float)/nzg;
        	fseek(gfp,0L,0);
	}
    }
    /* error checking */
    if (ierr==0) {
		if(ncdpg!=(int) (float)( gh.n2/gh.scale + 0.00001))
			err(" check gh.n2 ");
		if(nzg!=(int) (float)( gh.n1/gh.scale + 0.00001))
			err(" check gh.n1 ");
		if(dzg!=gh.d1/gh.scale)
			warn("dzg=%g not the same as gh.d1 = %g ", dzg, gh.d1/gh.scale);
		if(fzg!=gh.o1/gh.scale)
			warn("fzg not the same as gh.o1");
		if(dcdpg!=gh.dcdp2/gh.scale)
			warn("dcdpg not the same as gh.dcdp2");
		if(cdpming!=gh.ocdp2/gh.scale)
			warn("cdpming not the same as gh.ocdp2");
    } else {
                warn(" input ggfile non-standard, defaults used ");
    }

    if(dcdpg==0.) err(" dcdpg must not be 0"); 

    gamgrid = (float*)malloc(nzg*sizeof(float));

    /* sinc interpolate input traces before gmo for better accuracy */
    rsampz = 4.;
    nzint = nz * rsampz;
    dzint = 1./rsampz;
    odzint = rsampz;

    /* memory allocation */
    g2m1 = (float*)malloc(nz*sizeof(float));
    g2 = (float*)malloc(nz*sizeof(float));
    dataint = (float*)malloc(nzint*sizeof(float));
    zint = (float*)malloc(nzint*sizeof(float));
    mout2 = (float*)malloc(nz*sizeof(float));
    zx = (float*)malloc(nz*sizeof(float));
    mute = (float*)malloc(nz*sizeof(float));

    /* main loop over input traces */
    oldcdp = tr.cdp - 1;
    oldoffset=tr.offset - 1;
    odz = 1./dz;
    odz2 = odz*odz;

    for(iz=0;iz<nzint;iz++) zint[iz] = fz + iz*dzint;
    osmute = 1./smute;


    do { 

	/* find cdp index in gamma grid */
	if(tr.cdp!=oldcdp) {
	   newgamma = 1;
	   indx = (tr.cdp-cdpming)/dcdpg;
	   if(indx <0) {
	      indx = 0;
	   }
	   else if (indx >ncdpg-1) {
	      indx = ncdpg - 1;
	   }
           fseek(gfp,indx*nzg*sizeof(float),0);
    	   fread(gamgrid,sizeof(float),nzg,gfp);
	   /* compute (gamma^2-1) */
	   for(iz=0;iz<nz;iz++) { 
		z = fz + iz * dz;
		/* interpolate input ggrid */
		z = (z-fzg)/dzg;
		jz = z;
		if(jz<1) {
			jz = 1;
		} else if (jz>nzg-1) {
			jz = nzg - 1; 
		}
		/* store as 1./g2 */
		g2[iz] = 1./(gamgrid[jz]*gamgrid[jz]);
		g2m1[iz] = g2[iz]-1.;
	   }		
	} else {
	   newgamma = 0;
	}
	if (newgamma || tr.offset!=oldoffset) {
	   /* compute 0.25*offset^2/dz^2*(gamma^2-1)  */
	   temp = (tr.offset*tr.offset)*odz2*0.25;
	   for(iz=0;iz<nz;iz++) mout2[iz] = temp*g2m1[iz];
	}

	/* sinc interpolate the input trace */
	if(nzint>nz) {
	   ints8r(nz,1.0,fz,tr.data,0.0,0.0,nzint,zint,dataint);
	} else {
	   for(iz=0;iz<nz;iz++) dataint[iz]=tr.data[iz];
	}

	/* compute depth z(z0) (in sample) */
	for(iz=0,z0=fz; iz<nz; ++iz, z0+=1.0) { 
	   temp = z0*z0 + mout2[iz];
	   if (temp >= 0.) {
	      zx[iz] = sqrt(temp);
	      mute[iz] = 1.;
	   }
	   else {
	      zx[iz] = fz - 1.;
	      mute[iz] = 0.;
	   }
	}
	/* gmo */
	/* determine if stretch mute is needed */
	str = zx[1]-zx[0];
	if (g2m1[0]>=0.&& str < smute) {
	   mutes = 0;
	} else if(g2m1[0]<0.&& str > osmute) {
	   mutes = 0;
	} else {
	   mutes = 1;
	}
	if(mutes!=1){
	   zzint = (zx[0] - fz)*odzint;
	   indz = zzint;
	   res = zzint - indz;
	   if(indz>0 && indz<nzint-1) {
	      tr.data[0] = dataint[indz]+res*(dataint[indz+1]-dataint[indz]);	
	   } else {
	      tr.data[0] = 0.;	
	   }		
	} else {
	      tr.data[0] = 0.;
	}
	for(iz=1;iz<nz;iz++) {
	   str = zx[iz]-zx[iz-1];
	   if (g2m1[iz]>=0.&& str < smute) {
	      mutes = 0;
	   } else if(g2m1[iz]<0.&& str > osmute) {
	      mutes = 0;
	   } else {
	      mutes = 1;
	   }
	   if(mutes!=1) {
	      zzint = (zx[iz] - fz)*odzint;
	      indz = zzint;
	      res = zzint - indz;
	      if(indz>0 && indz<nzint-1) {
	         tr.data[iz]=dataint[indz]+res*(dataint[indz+1]-dataint[indz]);	
	      } else {
	         tr.data[iz]=0.;	
	      }
	   } else {
	         tr.data[iz]=0.;	
	   }
	}
	/* zero out those with negative inside sqrt */
	for(iz=0;iz<nz;iz++)tr.data[iz]=tr.data[iz]*mute[iz];
	   
	/* output */
	fputtr(outfp,&tr);
	/* update offset and cdp */
	oldcdp = tr.cdp;
	oldoffset = tr.offset;

    }while(fgettr(infp,&tr));

    free(gamgrid);
    free(g2m1);
    free(mout2);
    free(dataint);
    free(mute);
    free(zx);
    free(zint);

    fclose(outfp);
    

    return EXIT_SUCCESS;
}
Esempio n. 20
0
main(int argc, char **argv ){

   FILE *infp=stdin;

   FILE* bfp[MAX_SURFACES];
   FILE* tfp[MAX_SURFACES];

   char filename[PATH_MAX];

   float base[MAX_SURFACES];
   float top[MAX_SURFACES];

   float zscale = 1.0;

   float salt=4500;
   float dt;

   float x;
   float y;

   float line;
   float xline;

   int i;
   int j;
   int k;
   int n;
   int p;

   int in_salt;

   segytrace tr;

   memset( tfp ,0 ,sizeof(tfp) );
   memset( bfp ,0 ,sizeof(tfp) );

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

   initargs(argc,argv);
   askdoc(1);

   getparfloat("salt",&salt);
   getparfloat("zscale",&zscale);

   while( fgettr( infp ,&tr ) ){

      x = tr.sx;
      y = tr.sy;

      line  = tr.fldr;
      xline = tr.ep;
      dt    = tr.dt * zscale;

      j = 0;
      k = 0;

      in_salt = 0;

      /*-------------------------------------*/
      /* search for salt-sediment interfaces */
      /*-------------------------------------*/

      for( i=0; i<tr.ns; i++ ){

         if( !in_salt && tr.data[i] >= salt ){
            top[j++] = i*dt;
            in_salt = 1;

         }else if( in_salt && tr.data[i] < salt ){
            base[k++] = i*dt;
            in_salt = 0;

         }
      }

/*--------------------------------------------------------------------*\
  Note that the geometrical relationship defined here places salt
  between top[j] & base[j].  This is different from what Zhiming Li
  defined in his programs.
\*--------------------------------------------------------------------*/

      /*-------------------------------*/
      /* write out X-Y-Z to top  files */
      /*-------------------------------*/

      for( i=0; i<j; i++ ){

         if( !tfp[i] ){
            sprintf( filename ,"top_%d.xyz" ,i+1 );
            if( !(tfp[i] = fopen( filename ,"w" )) ){
               err( "Failed to open %s\n" ,filename );
            }
         }

         fprintf( tfp[i] ,"%20s "   ,""      );
         fprintf( tfp[i] ,"%9.1f "  ,line    );
         fprintf( tfp[i] ,"%9.1f "  ,xline   );
         fprintf( tfp[i] ,"%11.1f " ,x       );
         fprintf( tfp[i] ,"%11.1f " ,y       );
         fprintf( tfp[i] ,"%11.2f " ,top[i]  );

         fprintf( tfp[i] ,"\n" );
   
      }

      /*--------------------------------*/
      /* write out X-Y-Z to base  files */
      /*--------------------------------*/

      for( i=0; i<k; i++ ){

         if( !bfp[i] ){
            sprintf( filename ,"base_%d.xyz" ,i+1 );
            if( !(bfp[i] = fopen( filename ,"w" )) ){
               err( "Failed to open %s\n" ,filename );
            }
         }

         fprintf( bfp[i] ,"%20s "   ,""      );
         fprintf( bfp[i] ,"%9.1f "  ,line    );
         fprintf( bfp[i] ,"%9.1f "  ,xline   );
         fprintf( bfp[i] ,"%11.1f " ,x       );
         fprintf( bfp[i] ,"%11.1f " ,y       );
         fprintf( bfp[i] ,"%11.2f " ,base[i] );

         fprintf( bfp[i] ,"\n" );
   
      }

   }

   return 0;

}
Esempio n. 21
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;
}
Esempio n. 22
0
int readGather ( FILE* Fp ,segy** Gather ,int* MaxFold ,char* Header ){

   Value currentHeaderValue;
   Value previousHeaderValue;

   int i;
   int index;

   segy* gather = *Gather;

   static int first=1;
   static segy savedTrace;

   index = getindex(Header);

   /*---------------*/
   /* check for EOF */
   /*---------------*/

   if( feof( Fp ) ){
      return( 0 );
   }

   /*------------------*/
   /* copy saved trace */
   /*------------------*/

   if( !first ){
      memcpy( (char*) &(gather[0]) ,(char*)&savedTrace ,sizeof(segy ) );
   }else{
      first=0;
   }

   /*--------------------------------*/
   /* read data into existing buffer */
   /*--------------------------------*/

   
   gethval(&(gather[0]), getindex(Header) , &previousHeaderValue );

   for( i=1; i<*MaxFold; i++ ){
 
      if( !fgettr( Fp ,&(gather[i]) ) ){
         return( i );
      }

         gethval(&(gather[i]), index , &currentHeaderValue );
         if( currentHeaderValue.i != previousHeaderValue.i ){
         memcpy( (char*) &savedTrace ,(char*) &gather[i] ,sizeof(segy ) );
         return( i );
      }

   }

   /*-------------------------------------------------------------*/
   /* allocate additional space until entire gather has been read */
   /*-------------------------------------------------------------*/

   while( 1 ){

      *MaxFold += 10;

      if( !(gather = realloc( gather ,*MaxFold*sizeof(segy))) ){
         err( "realloc failed: %s %d" ,__FILE__ ,__LINE__ );
      }

      *Gather = gather;

      for( i=*MaxFold-10; i<*MaxFold; i++ ){ 
   
         if( !fgettr( Fp ,&(gather[i]) ) ){
            return( i );
         }
   
         gethval(&(gather[i]), index , &currentHeaderValue );
         if( currentHeaderValue.i != previousHeaderValue.i ){
            memcpy( (char*) &savedTrace ,(char*) &gather[i] ,sizeof(segy ) );

            return( i );
         }
   
      }    

   }

}
Esempio n. 23
0
main(int argc, char **argv)
{
	int nt,it;
	float dt;
	FILE *pxfp, *pyfp, *infp, *outfp=stdout;
	char *datain,*pxfile, *pyfile;
	int iy, ix;
	int ipow;
	int nx,ny,lt,lx,ly;
	int nxo,nyo,ixo,iyo,dxo,dyo,nto;
	int ii1, ii2, iyy, ntxo;
	float tmp, tmp1, tmp2;
	int nsegy;
	float *data, *pxo, *pyo, *work, *stack;
	float to0, dto;
	int hy, i2, i22, iy0, ierr, ht, hx;
	float *tt, *tx, *ty;
	int nycore, mlimit, n1, n2, n3,jy,ixx;
	float o1,o2,o3,d1,d2,d3,t0;

	long ltmp;

	segychdr ch;
    	segybhdr bh;
	usghed usgh;


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

/* open input data */
	if (!getparstring("datain",&datain)) err(" must specify datain ");
	if((infp = fopen(datain,"r"))==NULL)
             	err("datain %s open failed \n",datain);
	file2g(infp);
	fgethdr(infp,&ch,&bh);
	

	/* get information from the first header */
	if (!fgettr(infp,&tr)) err("can't get first trace");
	nt = tr.ns;
	dt = (float)tr.dt * 0.001;
	t0 = (float)tr.delrt;

	/* get required parameters */
	if (!getparstring("pxfile",&pxfile)) err(" must specify pxfile ");
	if (!getparstring("pyfile",&pyfile)) err(" must specify pyfile ");

	if (!getparint("nx",&nx)) err(" must specify nx");
	if (!getparint("ny",&ny)) err(" must specify ny");

	/* get optional parameters */
	if (!getparint("lt",&lt)) lt = 11;
	if (!getparint("ipow",&ipow)) ipow = 2;
	if (!getparint("lx",&lx)) lx = 11;
	if (!getparint("ly",&ly)) ly = 5;
	if(ny<ly) ly = (ny-1)/2*2+1;

	if (!getparint("ixo",&ixo)) ixo = 1;
	if (!getparint("dxo",&dxo)) dxo = 1;
	if (!getparint("nxo",&nxo)) nxo = nx;
	if (!getparint("iyo",&iyo)) iyo = 1;
	if (!getparint("dyo",&dyo)) dyo = 1;
	if (!getparint("nyo",&nyo)) nyo = ny;
	if (!getparfloat("to0",&to0)) to0 = tr.delrt;
	if (!getparfloat("dto",&dto)) dto = (float)tr.dt*0.001;
	if (!getparint("nto",&nto)) nto = nt;

	if (!getparint("mlimit",&mlimit)) mlimit = 256;



	if((pxfp = fopen(pxfile,"r"))==NULL)
             	err("pxfile %s open failed \n",pxfile);
	if((pyfp = fopen(pyfile,"r"))==NULL)
             	err("pyfile %s open failed \n",pyfile);

	pxo = (float*) emalloc(n1*sizeof(float));
	pyo = (float*) emalloc(n1*sizeof(float));
	work = (float*) emalloc(nt*sizeof(float));

	tmp = mlimit*1024*1024./(4.*nt*nx);
	nycore = (int) tmp;
	if(nycore<ly) err(" increase mlimit to %d \n",ly*nt*nx*4/1024/1024+1);
	if(dyo>=ly) nycore = ly;
	data = (float*) emalloc(nx*nycore*nt*sizeof(float));
	stack = (float*) emalloc(nto*sizeof(float));

	file2g(pxfp);
	file2g(pyfp);

	hy = (ly-1)/2;
	hx = (lx-1)/2;
	ht = (lt-1)/2;
	tt = (float*) emalloc(lt*sizeof(float));
	tx = (float*) emalloc(lx*sizeof(float));
	ty = (float*) emalloc(ly*sizeof(float));

	for(it=0;it<lt;it++) {
		tmp = it - ht;
		if(tmp<0) tmp = - tmp;
		tt[it]  = 2./(lt+1) * (1.-2.*tmp/(lt+1));
	}
	for(ix=0;ix<lx;ix++) {
		tmp = ix - hx;
		if(tmp<0) tmp = - tmp;
		tx[ix]  = 2./(lx+1) * (1.-2.*tmp/(lx+1));
	}
	for(iy=0;iy<ly;iy++) {
		tmp = iy - hy;
		if(tmp<0) tmp = - tmp;
		ty[iy]  = 2./(ly+1) * (1.-2.*tmp/(ly+1));
	}

	nsegy = 240+nt*sizeof(float);


	ierr = fgetusghdr(pxfp,&usgh);
		if(ierr!=0) err("error in input gridheader for pxfile ");
	fseek2g(pxfp,0,0);

	o1 = usgh.o1;
	d1 = usgh.d1;
	n1 = usgh.n1;
	o2 = usgh.o2;
	d2 = usgh.d2;
	n2 = usgh.n2;
	o3 = usgh.o3;
	d3 = usgh.d3;
	n3 = usgh.n3;

	jy  = -1;

	bh.hns = nto;
    	bh.hdt = dto*1000.;

        fputhdr(outfp,&ch,&bh);

	
	/* loop over output traces  */
	for(iy=0;iy<nyo;iy++) {

		iyy = iy*dyo + iyo;
		readdata(infp,data,tr1,&jy,iyy-1,ny,nt,nx,hy,nycore);

		for(ix=0;ix<nxo;ix++) {
			ixx = ix*dxo+ixo;
			readpxpy(pxfp,pyfp,o1,o2,o3,d1,d2,d3,n1,n2,n3,
				pxo,pyo,iyy,ixx);


			readhead(infp,tr1,ixx,iyy,nx,ny,nsegy);


			tr1.ns  = nto;
			tr1.delrt = to0;
			tr1.dt = dto*1000.;


			sstack_(data,pxo,pyo,stack,work,
				&iyy,&ixx,&jy,&nycore,&nx,
				&d1,&o1,&n1,
				&dt,&t0,&nt,
				&dto,&to0,&nto,
				&ipow,&hy,&hx,&ht,ty,tx,tt);


			for(it=0;it<nto;it++) {
				tr1.data[it] = stack[it]; 
			}

			fputtr(outfp,&tr1);
		}	

	}
	
	free(pxo);
	free(pyo);
	free(data);
	free(stack);
	free(tt);
	free(tx);
	free(ty);

	return EXIT_SUCCESS;
}
int main(int argc, char **argv) {

int  gelev_vmin, gelev_vmax, selev_vmin, selev_vmax;
int  gelev_min, gelev_max, selev_min, selev_max;
int  gelev_globalmin, gelev_globalmax, selev_globalmin, selev_globalmax;
int  gelev_num, selev_num;
int  imin, iminv, ifirst, nz1, nz, ns, ntr, ntrv, nsv;
double dfirst, delrt, delrtv, twt, dt, dtv, factor, z, amp_out;
double *depth, *tr_amp;
float ***velocity;
short verbose;
register int i, j, k, l;
cwp_String vfile;
FILE *fv;

initargs(argc, argv);
requestdoc (0);

if (!getparshort("verbose", &verbose)) verbose = 1;
if (!getparstring("vfile",&vfile)) vfile = "output.su";

ntr    = gettra (&tr,  0);
fv     = efopen (vfile, "r");
ntrv   = fgettra (fv, &vtr, 0);
delrt  = tr.delrt;
delrtv = vtr.delrt;
if (!getparint("ns",  &ns))  ns  = tr.ns;
if (!getparint("nsv", &nsv)) nsv = vtr.ns;
if (!getparint("nz", &nz)) nz=2000;

dt    = tr.dt  * 0.001;
dtv   = vtr.dt * 0.001;
imin  = nint ( delrt / dt );
iminv = nint ( delrtv / dtv );

depth  = ealloc1double ( ns );
tr_amp = ealloc1double ( ns );

factor = 0.0005;

if ( verbose ) {
   fprintf ( stderr, "\n" );
   fprintf ( stderr, "Number of input traces = %d\n", ntr );
   fprintf ( stderr, "Number of input samples per trace = %d\n", ns );
   fprintf ( stderr, "Number of output samples per trace = %d\n", nz );
   fprintf ( stderr, "Sample rate = %f ms.\n", dt );
   fprintf ( stderr, "Average velocity SU file name = %s\n", vfile );
   fprintf ( stderr, "Number of VAVG input traces = %d\n", ntrv );
   fprintf ( stderr, "Number of VAVG input samples per trace = %d\n", nsv );
   fprintf ( stderr, "VAVG Sample rate = %f ms.\n", dtv );
   fprintf ( stderr, "Input Delay = %f ms., First sample = %d\n", delrt, imin );
   fprintf ( stderr, "Velocity Delay = %f ms., First sample = %d\n", delrtv, iminv );
   fprintf ( stderr, "\n" );
}

rewind ( fv );
gelev_vmin = selev_vmin = INT_MAX;
gelev_vmax = selev_vmax = INT_MIN;
for ( i = 0; i < ntrv; ++i ) {
   fgettr (fv, &vtr);
   gelev_vmin = min ( gelev_vmin, vtr.gelev );
   gelev_vmax = max ( gelev_vmax, vtr.gelev );
   selev_vmin = min ( selev_vmin, vtr.selev );
   selev_vmax = max ( selev_vmax, vtr.selev );
}

if ( verbose ) fprintf ( stderr, "VELOCITY DATA - gelev_vmin = %d, gelev_vmax = %d, selev_vmin = %d, selev_vmax = %d\n", gelev_vmin, gelev_vmax, selev_vmin, selev_vmax );

rewind (stdin);
gelev_min = selev_min = INT_MAX;
gelev_max = selev_max = INT_MIN;
for ( i = 0; i < ntr; ++i ) {
   gettr (&tr);
   gelev_min = min ( gelev_min, tr.gelev );
   gelev_max = max ( gelev_max, tr.gelev );
   selev_min = min ( selev_min, tr.selev );
   selev_max = max ( selev_max, tr.selev );
}

if ( verbose ) fprintf ( stderr, "INPUT DATA -    gelev_min =  %d, gelev_max =  %d, selev_min =  %d, selev_max =  %d\n", gelev_min, gelev_max, selev_min, selev_max );

gelev_globalmin = max ( gelev_min, gelev_vmin );
selev_globalmin = max ( selev_min, selev_vmin );
gelev_globalmax = min ( gelev_max, gelev_vmax );
selev_globalmax = min ( selev_max, selev_vmax );

gelev_num = gelev_globalmax - gelev_globalmin + 1;
selev_num = selev_globalmax - selev_globalmin + 1;

if ( verbose ) {
   fprintf ( stderr, "\n" );
   fprintf ( stderr, "gelev_globalmin = %d, gelev_globalmax = %d, selev_globalmin = %d, selev_globalmax = %d\n", gelev_globalmin, gelev_globalmax, selev_globalmin, selev_globalmax );
   fprintf ( stderr, "gelev_num = %d, selev_num = %d\n", gelev_num, selev_num );
}

velocity = ealloc3float ( nsv, selev_num, gelev_num );

rewind ( fv );
ifirst = 0;
dfirst = 9999999999999999.9;
for ( k = 0; k < ntrv; ++k ) {
   fgettr (fv, &vtr);
   if ( vtr.gelev >= gelev_globalmin && vtr.gelev <= gelev_globalmax && vtr.selev >= selev_globalmin && vtr.selev <= selev_globalmax ) {
      i = vtr.gelev - gelev_globalmin;
      j = vtr.selev - selev_globalmin;
      memcpy( (void *) &velocity[i][j][0], (const void *) &vtr.data, nsv * FSIZE );
      dfirst = min ( dfirst, velocity[i][j][0] * delrtv * factor );
   }
}
efclose (fv);
ifirst = nint ( dfirst / dt );
nz1 = nz - ifirst;
if ( verbose ) fprintf ( stderr, "ifirst = %d, dfirst = %f, nz1 = %d\n", ifirst, dfirst, nz1 );

float zero;
double depth_max;

zero = 0.0;

rewind (stdin);
for ( l = 0; l < ntr; ++l ) {
   gettr (&tr);
   if ( tr.gelev >= gelev_globalmin && tr.gelev <= gelev_globalmax && tr.selev >= selev_globalmin && tr.selev <= selev_globalmax ) {
      i = tr.gelev - gelev_globalmin;
      j = tr.selev - selev_globalmin;
      for ( k = 0; k < nsv; ++k ) {
         twt = ( k * dtv ) + delrtv;
         tr_amp[k] = tr.data[k+iminv];
         depth[k] = velocity[i][j][k] * twt * factor;
      }
      depth_max = depth[nsv-1];
      fprintf ( stderr, "trace number = %5d, depth_max = %f\n", l, depth_max );
      for ( k=ifirst; k < nz1; ++k ) {
         z = k * dt;
         if ( z <= depth_max ) {
            dintlin ( nsv, depth, tr_amp, tr_amp[0], tr_amp[nsv-1], 1, &z, &amp_out );
            tr.data[k-ifirst] = (float) amp_out;
         } else {
            tr.data[k-ifirst] = zero;
         }
      }
      tr.trid = 1;
      tr.ns = nsv;
      tr.delrt = nint ( dfirst );
      tr.dt = nint(dt*1000);
      puttr (&tr);
   } 
} 

free1double (tr_amp);
free1double (depth);
free3float  (velocity);

return EXIT_SUCCESS;

}
Esempio n. 25
0
main (int argc, char **argv) 
{

	/* variables for hfile input */
	int *npicks,*hnums,ih,nhs,*difs,
		cdpxmini,cdpxmaxi;
	float *xpicks,*zpicks,*veltops,*velbots,*velavgs,*dvdzs,
		*dens,*qval,*pois,
		xmini,xmaxi,zmini,zmaxi,dcdpi,vmini,vmaxi;
	char hnames[maxhs][80], dunitsi[80], zattribi[80], vtypei[80];
	char *gathers;
	char *hfile;

	/* variable for this program */
	FILE *infp, *outfp, *paramfp, *modelfp, *geofp;
	FILE *datafp;
	int *hn, nh, jh, i, j, imax, ir1, ir2, ir3, ir4, ip, nr;
	int j1, j2, one=1, nn, ihfile;
	int rfsave, plot, comp, is, ns, js;
	int it,nt;
	float *sx,sz,r1,r2,r3,r4,dr,rz,amin,amax,da,dt,tmax,wl,f1,f2,f3,f4;
	float os;
	float ds,ssx,tmp, pp, rr1, rr2, rr3, rr4, dcdp, vint;
	float tmp1, tmp2;
	char cmd[1024];
	string direct="n";
	int *headhn, nhead;
	float dstn, xstn0;
	char param1[80], param2[80];
	char param1_1[80], param1_2[80];
	char fname[80];
	char **mn;
	char *mfile, *cbuf; 
	FILE *mfp;
	int maxnm=32, nm;

	float xpre, xnow;
	int icolor, ccolor, rcolor;
	int vcid;

	/* initialize getpar */
	initargs(argc,argv);
	askdoc(1);

	/* read in hfile */ 
	/* memory allocations for reading hfile */
	xpicks = (float *) malloc(maxhs*maxpks*sizeof(float));
	zpicks = (float *) malloc(maxhs*maxpks*sizeof(float));
	veltops = (float *) malloc(maxhs*maxpks*sizeof(float));
	velbots = (float *) malloc(maxhs*maxpks*sizeof(float));
	dens = (float *) malloc(maxhs*maxpks*sizeof(float));
	pois = (float *) malloc(maxhs*maxpks*sizeof(float));
	qval = (float *) malloc(maxhs*maxpks*sizeof(float));
	npicks = (int *) malloc(maxhs*sizeof(int));
	hnums = (int *) malloc(maxhs*sizeof(int));
	difs = (int *) malloc(maxhs*maxpks*sizeof(int));
	velavgs = (float *) malloc(maxhs*maxpks*sizeof(float));
	dvdzs = (float *) malloc(maxhs*maxpks*sizeof(float));

	for(ih=0;ih<maxhs;ih++) npicks[ih]=0;
	for(ih=0;ih<maxhs*maxpks;ih++) {
		veltops[ih]=0.;
		velbots[ih]=0.;
		difs[ih] = 0;
		velavgs[ih] = 0.;
		dvdzs[ih] = 0.;
	}

	/* read in hfile*/
	nhs = 0;
	dcdpi = 0.;
	if (!getparstring("hfile",&hfile)) err("hfile missing");
	infp = efopen(hfile,"r");
	ifileread(infp,&nhs,xpicks,zpicks,veltops,velbots,difs,
		  dens,qval,pois,velavgs,dvdzs,
              	  (char *)hnames,hnums,npicks,maxhs,maxpks,
		  &xmini,&xmaxi,&zmini,&zmaxi,
		  &cdpxmini,&cdpxmaxi,&vmini,&vmaxi,
		  vtypei,dunitsi,zattribi,&dcdpi,&ihfile);
	efclose(infp);

	free(dens);
	free(qval);
	free(pois);
	free(velavgs);
	free(dvdzs);

	hn = (int *) malloc(nhs*sizeof(int));
	mn = (char **) malloc(maxnm*sizeof(char *));
	headhn = (int *) malloc(nhs*sizeof(int));

	/* get parameters */
	if (!getparint("ns",&ns)) ns = 1;
	js = countparval("sx");
	if(js==0) js = 1;
	if(js>1) ns = js;
	sx = (float *) malloc(ns*sizeof(float));

	if (!getparfloat("sx",sx)) {
		if (!getparfloat("os",&os)) os = xmini;
		if (!getparfloat("ds",&ds)) ds = 0.;
		for(is=0;is<ns;is++) sx[is] = os + is*ds;
	} else {
		os = sx[0];
	}

	if (!getparint("is",&is)) is = 1;
	if (!getparfloat("sz",&sz)) sz = 0.;
	if (!getparfloat("r1",&r1)) r1 = 0.;
	if (!getparfloat("r2",&r2)) r2 = 25.;
	if (!getparfloat("r3",&r3)) r3 = 50.;
	if (!getparfloat("r4",&r4)) r4 = 2975.;
	if (!getparfloat("dr",&dr)) dr = 25.;
	if (!getparfloat("rz",&rz)) rz = 0.;
	if (!getparfloat("amin",&amin)) amin = -90.;
	if (!getparfloat("amax",&amax)) amax = 90.;
	if (!getparfloat("da",&da)) da = 1.;
	if (!getparfloat("dt",&dt)) dt = 4.;
	if (!getparfloat("tmax",&tmax)) tmax = 4000.;
	if (!getparfloat("wl",&wl)) wl = 150.;
	if (!getparfloat("f1",&f1)) f1 = 10.;
	if (!getparfloat("f2",&f2)) f2 = 25.;
	if (!getparfloat("f3",&f3)) f3 = 35.;
	if (!getparfloat("f4",&f4)) f4 = 50.;
	nh = countparval("hn");
	if (!getparint("hn",hn)) { 
		nh = nhs-1;
        	for (ih=0; ih<nh; ih++) hn[ih] = ih + 1;
	} else {
        	for (ih=0; ih<nh; ih++) hn[ih] = hn[ih] - 1;
	}
	if(nh==1 && hn[0]==-1) nh = 0;
	if(nh==1 && hn[0]==0) nh = 0;

	nhead = countparval("headhn");
	if (!getparint("headhn",headhn)) { 
		nhead = 0;
	} else {
        	for (ih=0; ih<nhead; ih++) headhn[ih] = headhn[ih] - 1;
	}
	if(nh>49) err("maximum 50 horizons allowed ");

	nm = 0;
	nm = getparstring("mfile",&mfile);
	if(nm>0) {
		mfp = efopen(mfile,"r");
		cbuf = (char *) malloc(81*sizeof(char));
		nm = 0;
		for(i=0;i<maxnm;i++) {
			if (feof(mfp) !=0 ) break;
			bzero(cbuf,81);
                	fgets(cbuf,81,mfp);
			if(strncmp(cbuf, "0", 1)==0 || 
			   strncmp(cbuf, "1", 1)==0 || 
			   strncmp(cbuf, "2", 1)==0 || 
			   strncmp(cbuf, "3", 1)==0 || 
			   strncmp(cbuf, "4", 1)==0 || 
			   strncmp(cbuf, "5", 1)==0 || 
			   strncmp(cbuf, "6", 1)==0 || 
			   strncmp(cbuf, "7", 1)==0 || 
			   strncmp(cbuf, "8", 1)==0 || 
			   strncmp(cbuf, "9", 1)==0 ) { 
              			mn[nm] = (char*) malloc(81);
				strncpy(mn[nm],cbuf,81);
			        nm = nm + 1;
			}
		}
		/*
		for(i=0;i<nm;i++) {
			fprintf(stderr,"mn=%s i=%d \n",mn[i],i);
		}
		*/
	}

	if (!getparint("rfsave",&rfsave)) rfsave = 0;
	if (!getparint("plot",&plot)) plot = 0;
	if (!getparint("comp",&comp)) comp = 1;
	if (!getparint("icolor",&icolor)) icolor = 7;
	if (!getparint("rcolor",&rcolor)) rcolor = 2;
	if (!getparint("ccolor",&ccolor)) ccolor = 3;
	if (!getparint("vcid",&vcid)) vcid = 0;
	getparstring("direct",&direct);
	if ( comp == 0 || comp==1 ) {
		ns = 1;
		sx[0] = sx[is-1];
	}
	if( comp == 2 || comp == -1) plot = -1;

	dstn = dr;
	xstn0 = sx[0] + r1;

	/* open shot gather */
	if(comp==1 || comp==2) {
		if (!getparstring("gathers",&gathers)) {
			err(" must specify name of gathers !");
		} else {
			outfp = efopen(gathers,"w");
		}
	}
	
	/* output model file */	
	bzero(fname,80);
	sprintf(fname,"model-file_os=%g\0",os);
	modelfp = fopen(fname,"w");
	if(nhs>maxint) err("too many horizons (max 50 allowed)");
	for(ih=0;ih<nhs;ih++) {
		imax = npicks[ih];
		if(imax>maxspl) {
			imax = maxspl;
			tmp = npicks[ih];
			tmp = tmp / (imax-1);
		} else {
			tmp = 1.0;
		}
		for(i=0;i<imax;i++) { 
			pp = i*tmp + 0.5;
			ip = pp;
			if ( ip<npicks[ih] ) {
				vint = 0.5*(veltops[ih*maxpks+ip]
					+velbots[ih*maxpks+ip]);
				fprintf(modelfp,"%9.2f   %9.2f   %9.2f\n",
				xpicks[ih*maxpks+ip],zpicks[ih*maxpks+ip],vint);
			}

			xpre = xnow;
			xnow = xpicks[ih*maxpks+ip];
			if(i>0) {
				if(xnow<=xpre) 
err(" x positions must be increasing in horizon %d xpre=%g xnow=%g of hfile",
	ih+1,xpre,xnow);
			} 
		}
		fprintf(modelfp," 1.000000   -99999.00   %9.2f\n",vint);
	}
	fprintf(modelfp,"%d\n",vcid);
	efclose(modelfp);


	/* output geometry file */
	bzero(fname,80);
	sprintf(fname,"geometry-file_os=%g\0",os);
	geofp = fopen(fname,"w");
	
	fprintf(geofp,
"1         %-9.2f                 :reference station number and x-coord\n",
	xstn0);
	fprintf(geofp,
"%-9.2f     %-9.2f                :station spacing and receiver depth\n",
	dstn,rz);

	for(js=0;js<ns;js++) {
		/* actual receiver positions */
		ssx = sx[js] - xstn0;
		rr1 = ssx + r1; 
		rr2 = ssx + r2; 
		rr3 = ssx + r3; 
		rr4 = ssx + r4; 
		tmp = rr1/dstn + 1.5;
		ir1 = tmp;	
		tmp = rr2/dstn + 1.5;
		ir2 = tmp;	
		tmp = rr3/dstn + 1.5;
		ir3 = tmp;	
		tmp = rr4/dstn + 1.5;
		ir4 = tmp;	
		ssx = ssx/dstn + 1;

		fprintf(geofp,
"%d  %d  %d   %d      %-6.2f %-5.1f        :shot %d - r1 r2 r3 r4 s sdepth\n",
			ir1,ir2,ir3,ir4,ssx,sz,js+1);
	}

	efclose(geofp);
	
	/* name param1_os=XXX */
	sprintf(param1,"param1_os=%g\0",os);
	sprintf(param1_1,"param1_1_os=%g\0",os);
	sprintf(param1_2,"param1_2_os=%g\0",os);
	/* name param2_os=XXX */
	sprintf(param2,"param2_os=%g\0",os);

	/* output param1_1 file */
	paramfp = fopen(param1_1,"w");
	fprintf(paramfp,
"model-file_os=%g                          :model file\n",os);
	fprintf(paramfp,
"%-2d                                  :#interfaces in model\n",nhs-1);
	fprintf(paramfp,
"plotcolors_os=%g                          :model colors file\n",os);
	if(plot==-1) {
	fprintf(paramfp,
"                                    :first plot descriptor (mwq)\n");
	} else {
	fprintf(paramfp,
"m                                   :first plot descriptor (mwq)\n");
	}
	fprintf(paramfp,
"don't care                          :well coordinates\n");
	fprintf(paramfp,
"s                                   :shooting mode (sd)\n");
	fprintf(paramfp,
"geometry-file_os=%g                       :receiver geometry\n",os);  
	if(plot==-1) {
	fprintf(paramfp,
"                                    :second plot descriptor (sgq)\n");
	fprintf(paramfp,
"l                                   :job descriptor (rlt)\n");
	} else {
	fprintf(paramfp,
"sg                                  :second plot descriptor (sgq)\n");
	fprintf(paramfp,
"rl                                  :job descriptor (rlt)\n");
	}
	fprintf(paramfp,
"csm_os=%g                                 :output filename(s)\n",os);
	fprintf(paramfp,
"%-5.1f  %-5.1f                        :range of takeoff angles\n",amin,amax);
	fprintf(paramfp,
"%-5.1f                               :increment in takeoff angle\n",da);
	for(ih=0;ih<nhs;ih=ih+3) {
		imax = 3;
		if(ih+imax >nhs) imax = nhs - ih;
		for(i=0;i<imax;i++) {
			jh = ih + i;
			tmp = 0.;
			j1 = 1;
			j2 = npicks[jh];
			nn = npicks[jh];
			if(ns==1) {
				tmp1 = sx[0]+r1;
				if(r1>0.) tmp1 = sx[0]; 
				tmp2 = sx[0]+r4;
				if(r4<0.) tmp2 = sx[0];
				if(tmp1>tmp2) {
					tmp = tmp2;
					tmp1 = tmp2;
					tmp2 = tmp;
				}
				if(tmp1<xpicks[jh*maxpks]) {
					j1 = 1;
				} else if(tmp1>xpicks[jh*maxpks+nn-1]) {
					j1 = nn;
				} else {
					bisear_(&nn,&one,
						xpicks+jh*maxpks,&tmp1,&j1);
				}
				if(tmp2<xpicks[jh*maxpks]) {
					j2 = 1;
				} else if(tmp2>xpicks[jh*maxpks+nn-1]) {
					j2 = nn;
				} else {
					bisear_(&nn,&one,
						xpicks+jh*maxpks,&tmp2,&j2);
				}
			}
		 	for(j=j1-1;j<j2;j++) {
				tmp = tmp + veltops[jh*maxpks+j] 
				    + velbots[jh*maxpks+j];
			}	
			tmp = tmp /(j2-j1+1);
			fprintf(paramfp,"%-7.1f ",0.5*tmp); 
		}
		if(ih+imax!=nhs) {
			fprintf(paramfp,"\n");
		} else {
			fprintf(paramfp,"                       :velocities\n");
		}
	}
	fprintf(paramfp,
"%1s                                   :direct wave? (y or n)\n",direct);
	if(nhead==0) {
		fprintf(paramfp,
"                                    :headwave interface numbers (1,2,...)\n");
	} else {
		for(ih=0;ih<nhead;ih++) {
			fprintf(paramfp,"%d ",headhn[ih]);
		}
		fprintf(paramfp,
"                                    :headwave interface numbers (1,2,...)\n");
	}
	fprintf(paramfp,
"n                                   :all primaries? (y or n)\n");
	for(ih=0;ih<nh;ih++) {
		fprintf(paramfp,
"%-2d                                  :reflection from interface %d\n",
			hn[ih],hn[ih]);
	}
	for(i=0;i<nm;i++) fprintf(paramfp, "%s",mn[i]);
	
	fclose(paramfp);

	/* output param1_2 file */
	paramfp = fopen(param1_2,"w");
	fprintf(paramfp,
"model-file_os=%g                          :model file\n",os);
	fprintf(paramfp,
"%-2d                                  :#interfaces in model\n",nhs-1);
	fprintf(paramfp,
"plotcolors_os=%g                          :model colors file\n",os);
	fprintf(paramfp,
"                                    :first plot descriptor (mwq)\n");
	fprintf(paramfp,
"don't care                          :well coordinates\n");
	fprintf(paramfp,
"s                                   :shooting mode (sd)\n");
	fprintf(paramfp,
"geometry-file_os=%g                       :receiver geometry\n",os);  
	fprintf(paramfp,
"                                    :second plot descriptor (sgq)\n");
	fprintf(paramfp,
"t                                   :job descriptor (rlt)\n");
	fprintf(paramfp,
"csm_os=%g                                 :output filename(s)\n",os);
	fprintf(paramfp,
"%-5.1f  %-5.1f                        :range of takeoff angles\n",amin,amax);
	fprintf(paramfp,
"%-5.1f                               :increment in takeoff angle\n",da);
	for(ih=0;ih<nhs;ih=ih+3) {
		imax = 3;
		if(ih+imax >nhs) imax = nhs - ih;
		for(i=0;i<imax;i++) {
			jh = ih + i;
                        tmp = 0.;
                        j1 = 1;
                        j2 = npicks[jh];
                        nn = npicks[jh];
                        if(ns==1) {
                                tmp1 = sx[0]+r1;
                                if(r1>0.) tmp1 = sx[0];
                                tmp2 = sx[0]+r4;
                                if(r4<0.) tmp2 = sx[0];
                                if(tmp1>tmp2) {
                                        tmp = tmp2;
                                        tmp1 = tmp2;
                                        tmp2 = tmp;
                                }
                                if(tmp1<xpicks[jh*maxpks]) {
                                        j1 = 1;
                                } else if(tmp1>xpicks[jh*maxpks+nn-1]) {
                                        j1 = nn;
                                } else {
                                        bisear_(&nn,&one,
                                                xpicks+jh*maxpks,&tmp1,&j1);
                                }
                                if(tmp2<xpicks[jh*maxpks]) {
                                        j2 = 1;
                                } else if(tmp2>xpicks[jh*maxpks+nn-1]) {
                                        j2 = nn;
                                } else {
                                        bisear_(&nn,&one,
                                                xpicks+jh*maxpks,&tmp2,&j2);
                                }
                        }
                        for(j=j1-1;j<j2;j++) {
                                tmp = tmp + veltops[jh*maxpks+j]
                                    + velbots[jh*maxpks+j];
                        }
                        tmp = tmp /(j2-j1+1);
                        fprintf(paramfp,"%-7.1f ",0.5*tmp);
			/*
			jh = ih + i;
			tmp = 0.;
		 	for(j=0;j<npicks[jh];j++) {
				tmp = tmp + veltops[jh*maxpks+j] 
				    + velbots[jh*maxpks+j];
			}	
			tmp = tmp /(npicks[jh]*2);
			fprintf(paramfp,"%-7.1f ",tmp); 
			*/
		}
		if(ih+imax!=nhs) {
			fprintf(paramfp,"\n");
		} else {
			fprintf(paramfp,"                       :velocities\n");
		}
	}
	fprintf(paramfp,
"%1s                                   :direct wave? (y or n)\n",direct);
	if(nhead==0) {
		fprintf(paramfp,
"                                    :headwave interface numbers (1,2,...)\n");
	} else {
		for(ih=0;ih<nhead;ih++) {
			fprintf(paramfp,"%d ",headhn[ih]);
		}
		fprintf(paramfp,
"                                    :headwave interface numbers (1,2,...)\n");
	}
	fprintf(paramfp,
"n                                   :primaries? (y or n)\n");
	for(ih=0;ih<nh;ih++) {
		fprintf(paramfp,
"%-2d                                  :reflection from interface %d\n",
			hn[ih],hn[ih]);
	}

	for(i=0;i<nm;i++) fprintf(paramfp, "%s",mn[i]);
		
	fclose(paramfp);

	/* output param2 file */
	tmp = (r2-r1)/dr + (r4-r3)/dr + 1 + 1 + 0.5;
	nr  = tmp;
	
	paramfp = fopen(param2,"w");
	fprintf(paramfp,
"s                                :job option (s,r)\n");
	fprintf(paramfp,
"1  %d                             :first, last shot for sort\n",ns);
	fprintf(paramfp,
"1  %d                           :first, last trace OR first last receiver\n",
		nr);
	fprintf(paramfp,
"%-4.1f %-4.1f %-4.1f %-4.1f              :frequency spectrum of wavelet\n",
				f1,f2,f3,f4);
	fprintf(paramfp,
"%-4.3f                            :wavelet length (secs)\n",wl*0.001);
	fprintf(paramfp,
"%-4.3f                            :sample rate (secs)\n",dt*0.001);
	fprintf(paramfp,
"%-6.3f                            :record length (secs)\n",tmax*0.001);
	fprintf(paramfp,
"csm_os=%gshot                          :input filename\n",os);
	fprintf(paramfp,
"csm_os=%gtraces                        :output filename\n",os);
	fclose(paramfp);

	/* output plotcolors file */
	sprintf(fname,"plotcolors_os=%g\0",os);
	paramfp = fopen(fname,"w");

	fprintf(paramfp, "0          receivers\n");
	fprintf(paramfp, "4          sources\n");
	fprintf(paramfp, "6          well color\n");
	fprintf(paramfp, "%d          caustic rays\n",ccolor);
	fprintf(paramfp, "%d          rays\n",rcolor);
	fprintf(paramfp, "%d          interfaces\n",icolor);
	fprintf(paramfp,"\n");
	fprintf(paramfp,"\n");
	fprintf(paramfp,"\n");
	fprintf(paramfp,"key:  (CWP's xgraph colors)\n");
	fprintf(paramfp,"0      black\n");
	fprintf(paramfp,"1      white\n");
	fprintf(paramfp,"2      red\n");
	fprintf(paramfp,"3      green\n");
	fprintf(paramfp,"4      dark blue\n");
	fprintf(paramfp,"5      light blue\n");
	fprintf(paramfp,"6      violet\n");
	fprintf(paramfp,"7      yellow\n");
	fclose(paramfp);	


	/* plot rays */
	bzero(cmd,1024);
	sprintf(cmd,"cp %s %s",param1_1,param1);
	system(cmd);
	if(comp==0 || comp==1) {
		bzero(cmd,1024);
		sprintf(cmd,
	"cshot1 param1=%s | cshotplot >csmplot_os=%g outpar=csmpar_os=%g",
			param1,os,os);
		system(cmd);
	}else if(comp==-1) {
		bzero(cmd,1024);
		sprintf(cmd,"cshot1 param1=%s >/dev/null",param1);
		system(cmd);
	}

	if(plot==0) {
		bzero(cmd,1024);
		if(rfsave==0) {
			sprintf(cmd,
"( xgraph <csmplot_os=%g par=csmpar_os=%g style=seismic title='Csmodel raypaths' label1=Depth label2=Distance x1beg=%g x1end=%g x2beg=%g x2end=%g ; /bin/rm -f csmpar_os=%g csmplot_os=%g ) &",
			os,os,zmini,zmaxi,xmini,xmaxi,os,os); 
		} else {
			sprintf(cmd,
"xgraph <csmplot_os=%g par=csmpar_os=%g style=seismic title='Csmodel raypaths' label1=Depth label2=Distance x1beg=%g x1end=%g x2beg=%g x2end=%g &",
			os,os,zmini,zmaxi,xmini,xmaxi); 
		}
	} else if(plot==1) {
		sprintf(cmd,"psgraph <csmplot_os=%g par=csmpar_os=%g title=Csmodel label1=Depth label2=Distance x1beg=%g x1end=%g x2beg=%g x2end=%g | lpr &",
			os,os,zmini,zmaxi,xmini,xmaxi); 
	}

	if(comp!=2 && comp!=-1 && plot!=-1) {
		system(cmd);
		if(plot==1 && rfsave==0) {
			bzero(cmd,1024);
			sprintf(cmd,"/bin/rm -f csmpar_os=%g csmplot_os=%g");
			system(cmd);
		}
	}

	if(comp==0 || comp==-1) goto notrace;

	bzero(cmd,1024);
	sprintf(cmd,"cp %s %s",param1_2,param1);
	system(cmd);
	bzero(cmd,1024);
	sprintf(cmd,"cshot1 param1=%s >/dev/null",param1);
	system(cmd);
	bzero(cmd,1024);
	sprintf(cmd,"cshot2 param2=%s",param2);
	system(cmd);
	nt = 1 + ( tmax + dt / 2. ) / dt;
	j = dt*1000;
	bzero(cmd,1024);
	sprintf(cmd,"suaddhead <csm_os=%gtraces ftn=1 ns=%d | sushw key=dt a=%d >csmtraces.segy_os=%g", os,nt,j,os);
	system(cmd);

	bzero(fname,80);
	sprintf(fname,"csm_os=%gtraces\0",os);
	if(rfsave==0) unlink(fname); 

	bzero(fname,80);
	sprintf(fname,"csmtraces.segy_os=%g\0",os);
	datafp = fopen(fname,"r");
	i = 0;
	dcdp = dr * 0.5;
	if (ds!=0. && ds<dr) dcdp = ds * 0.5; 

	fgethdr(datafp,&ch,&bh);
	nt = nt - 1;
	bh.hns = nt;
	bh.ntrpr = nr;
	bh.tsort = 1;
	bh.hdt = dt * 1000;
	bh.format = 1;
	fputhdr(outfp,&ch,&bh);

	while( fgettr(datafp,&tr) ) {
		i = i + 1;
		js = (i-1)/nr;
		tr.tracl = i;
		tr.sx = (int) sx[js];
		tmp = r1 + (i-js*nr-1)*dr + 0.0001; 
		if(tmp<=r2) {
			tr.gx = (int)tmp + tr.sx;
			j = i;
		} else {
			tmp = r3 + (i-j-1)*dr;
			tr.gx = (int) tmp + tr.sx;
		}
		tr.ep = js + 1;
		tr.fldr = js + 1;
		tr.tracf = i-js*nr;
		tr.offset = tr.gx - tr.sx;
		tmp = tr.gx + tr.sx;
		tmp = tmp * 0.5;
		tmp = tmp/dcdp + 1.5; 
		js  = tmp;
		tr.cdp = js;
		tr.scalco = 1;
		tr.trid = 1;
		tr.delrt = (int) dt;
		tr.ns = nt;
		for(it=0;it<nt;it++) tr.data[it] = tr.data[it+1]; 
		fputtr(outfp,&tr);
	}
	
	if(plot==0) {
		bzero(cmd,1024);
		if(rfsave==0) {
			sprintf(cmd,
	"( <csmtraces.segy_os=%g suxwigb title='Modeled gather' label1=Time label2=Trace xcur=2 grid1=solid perc=99 ; /bin/rm -f csmtraces.segy_os=%g ) & ",os,os,os); 
		} else {
			sprintf(cmd,
	"<csmtraces.segy_os=%g suxwigb title='Modeled gather' label1=Time label2=Trace xcur=2 grid1=solid perc=99 & ",os); 
		}
		system(cmd);
	} else {
		bzero(cmd,1024);
		sprintf(cmd,"<csmtraces.segy_os=%g supswigb title='Modeled gather' label1=Time label2=Trace xcur=2 grid1=solid perc=99 | lpr ",os);
		system(cmd);
		if(rfsave==0) {
			bzero(cmd,1024);
			sprintf(cmd,"/bin/rm -f csmtraces.segy_os=%g ",os);
			system(cmd);
		}
	}


	notrace:

	if(rfsave==0) {
		bzero(fname,80);
		sprintf(fname,"model-file_os=%g\0",os);
		unlink(fname);
		bzero(fname,80);
		sprintf(fname,"geometry-file_os=%g\0",os); 
		unlink(fname);
		unlink(param1_1);
		unlink(param1_2);
		unlink(param1);
		unlink(param2);
		bzero(fname,80);
		sprintf(fname,"plotcolors_os=%g\0",os); 
		unlink(fname);
		if(comp!=0) {
			bzero(fname,80);
			sprintf(fname,"csm_os=%gshot\0",os); 
			unlink(fname);
		}
		bzero(fname,80);
		sprintf(fname,"csm_os=%gdata\0",os); 
		unlink(fname);
		bzero(fname,80);
		sprintf(fname,"csm_os=%glisting\0",os); 
		unlink(fname);

		system("sleep 5");
		if(comp==1 || comp==2) {
			bzero(fname,80);
			sprintf(fname,"csmtraces.segy_os=%g\0",os); 
			unlink(fname);
		}
	}

	return(0);
}
Esempio n. 26
0
main(int argc, char **argv)
{

	segytrace tr;

	FILE *infp=stdin;
	int njobs, nfft, nt, ntmp;
	float fmin, fmax, fmaxend;
	int *ratio;
	float dt, df, dw, pi;
	int i1, i2, iwnum, iwmin, iwmax, i;
	float f1, f2, fjob, tmp, sum;
	int nfftq, iwend;
	int j;


  	/* get parameters */
   	initargs(argc,argv);
   	askdoc(1);

   	if (!getparint("njobs",&njobs)) err(" njobs missing ");
	j = countparval("ratio");
	if ( njobs != j && j > 0 ) err(" check ratio ");

	ratio = (int *)malloc(njobs*sizeof(int));
	if(!getparint("ratio",ratio)) {
		for(i=0;i<njobs;i++) ratio[i] = 1;
	}

	/* make file size to be able to exceed 2 G */
	file2g(infp);
	/* read in first trace for nt and dt */
    if (!fgettr(infp,&tr))  err("can't get first trace");
	nt = tr.ns; 
	dt = (float)tr.dt/1000000.; 

	/* optional parameters */
	if(!getparfloat("fmin",&fmin)) fmin = 0.05 * 0.5 / dt;
	if(!getparfloat("fmax",&fmax)) fmax = 1./2.0 * 0.5 / dt;
	if(!getparfloat("fmaxend",&fmaxend)) fmaxend = fmax;
	if(!getparint("nfft",&nfft)) nfft = nt * 3 / 2;

	ntmp = (nfft+1)/2*2;
	radix_(&ntmp,&nfft);
	nfftq = nfft/2+1;

	pi = 3.141592654;
	df = 1./(nfft*dt); 
	dw = 2.*pi/(nfft*dt); 
	tmp = fmin*2.*pi/dw;
	iwmin = tmp;
	if(iwmin<1) iwmin=1;
	if(iwmin>=nfftq) iwmin=nfftq-1;
	tmp = fmax*2.*pi/dw;
	iwmax = tmp;
	if(iwmax<1) iwmax=1;
	if(iwmax>=nfftq) iwmax=nfftq-1;
	tmp = fmaxend*2.*pi/dw;
	iwend = tmp;
	if(iwend<1) iwend=1;
	if(iwend>=nfftq) iwend=nfftq-1;

	if(iwmax<iwmin) iwmax = iwmin;
	if(iwend<iwmin) iwend = iwmin;

	tmp = (iwmax+iwend)/2. - iwmin;
	sum = 0.;
	for(i=0;i<njobs;i++) sum = sum + ratio[i];
	fjob = tmp / sum;

	printf(" ======= FXYMCAL ======= \n");
	printf(" ifmin_global=%d ifmax_global=%d ifend_global=%d nf_global=%d \n",
		iwmin,iwmax,iwend,iwmax-iwmin+1);

	i1 = iwmin;
	for(i=0;i<njobs;i++) {
		f1 = i1 * df;
		tmp = fjob * ratio[i] + 0.5;
		iwnum = tmp;
		i2 = i1 + iwnum -1;
		j = iwnum;
		if(i2>iwend && iwend<iwmax) {
			if(i1<iwend) {
				j = iwend - i1;
				i2 = iwend;
				do {
					i2 = i2 + 1;
					j = (iwend-i1) + 
						(2*(iwmax-iwend)-(i2-iwend))*(i2-iwend)/(iwmax-iwend)/2;
				} while (j<iwnum && i2<=iwmax);
			} else {
				i2 = i1;
				j = 0;
				do { 
					i2 = i2 + 1;
					j = (2*(iwmax-iwend)-(i1-iwend)-(i2-iwend))*
						(i2-i1)/(iwmax-iwend)/2;
				} while (j<iwnum && i2<=iwmax);
			}
		}
		if(i2>iwmax) i2 = iwmax;
		if(i==njobs-1) i2 = iwmax;
		iwnum = i2 - i1 + 1;
		f2 = i2*df;
		printf("ijob=%-2d:  ifmin=%-5d    ifmax=%-5d    nf=%-5d   fmin_i=%f fmax_i=%f \n",i+1,i1,i2,iwnum,f1,f2);
		i1 = i2 + 1;
	}

	return 0;
}
Esempio n. 27
0
/* main program */
main(int argc, char **argv)
{
	
	
	float *work; 		/* working buffer */
	int nt;			/* number of samples per trace */
	int it;			/* time index */
	FILE *infp=stdin;	/* standard input file pointer */
	FILE *outfp=stdout;	/* standard output file pointer */
	int datum, jt, shift,kt;
	float tmp, dt;
	

/* initialize */
	initargs(argc, argv);	/* initialize parameter reading */ 
	askdoc(1);		/* on-line self documentation */

/* parameters fetching */

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

/* id header processing (optional) */
        fgethdr(infp,&ch,&bh); 	/* read segy id (ascii and binary) headers */ 
        fputhdr(outfp,&ch,&bh); /* output id headers */

/* processing */ 

	if (!fgettr(infp,&trin))  err("can't get first trace");
				/* read in the first trace, exit if fail */

	nt = trin.ns;		/* obtain number of samples per trace */
	dt = trin.dt;
	dt = dt/1000;


	/* memory allocation */
	work = (float*) malloc(nt*sizeof(float));


	/* Main loop over traces */
	do {
		/* get trace header value offset */
		shift = trin.sstat+trin.gstat;
		tmp = (shift - datum)/dt ;
		jt = tmp;

		for(it=0;it<jt;it++) work[it] = 0.;

		/* shift trace to work */
		for(it=0;it<nt;it++) {
			kt = it - jt;
			if(kt>=0 && kt <nt) {
				work[it] = trin.data[kt];
			} else {
				work[it] = 0.;
			}
		}

		/* copy work to trace output */
		for(it=0;it<nt;it++) trout.data[it] = work[it];
		/* copy trace header (240 bytes) to output */
		bcopy(&trin, &trout, HDRBYTES);
		/* update trace header value delrt */
		trout.tstat=jt*dt;
		/* output trace */
	      	fputtr(outfp,&trout); 
	} while (fgettr(infp,&trin));		/* reading traces */

	/* free space */
	free(work);

	/* close input and output */
	fclose(infp);
	fclose(outfp);

	return 0;
}