Exemplo n.º 1
0
int main(int argc, char **argv)
{
	int i;

	char *srcfile;
	char *datfile;
	float b,e,k,a;
	int nv; float *v;

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

	/* Get parameters */
	if (!getparstring("src", &srcfile)) err("must specify src= source file");
	if (!getparstring("dat", &datfile)) err("must specify dat= data file");
	if (!getparfloat("b", &b)) b=-INFINITY;
	if (!getparfloat("e", &e)) e=INFINITY;
	if (!getparfloat("k", &k)) k=0.01;
	if (!getparfloat("a", &a)) a=0;
	if ((nv=countparval("v"))) {
		v=malloc(nv*sizeof(float));
		getparfloat("v",v);
	}

	/* Print out parameters */
	printf("src=%s dat=%s b=%f e=%f k=%f a=%f v=",srcfile,datfile,b,e,k,a);
	for (i=0;i<nv;i++) printf("%f,",v[i]);
	printf("\n");

	return 0;
}
Exemplo n.º 2
0
main(int argc, char **argv)
{
	int nt;		/* number of time samples			*/
	float dt;	/* time sampling interval			*/
	int ntr;	/* number of traces				*/
	float dx;	/* trace spacing (spatial sampling interval)	*/
	int nslopes;	/* number of slopes specified			*/
	float *slopes;	/* slopes at which amplitudes are specified	*/
	int namps;	/* number of amplitudes specified		*/
	float *amps;	/* amplitudes corresponding to slopes		*/
	float bias;	/* slope bias					*/
	FILE *hdrfp;	/* fp for header storage file			*/
	FILE *datafp;	/* fp for trace storage file			*/


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


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


	/* Get parameters */
	dt = (float) tr.dt/1000000.0;
	if (!dt) getparfloat("dt", &dt);
	if (!dt) dt = 1.0;
	if (!getparfloat("dx", &dx)) dx = 1.0;
	slopes = alloc1float(countparval("slopes"));
	amps = alloc1float(countparval("amps"));
	if (!(nslopes = getparfloat("slopes", slopes))) {
		nslopes = 1;
		slopes[0] = 0.0;
	}
	if (!(namps = getparfloat("amps", amps))) {
		namps = 1;
		amps[0] = 1.0;
	}
	if (!getparfloat("bias", &bias)) bias = 0.0;


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


	/* Store traces and headers in tmpfile while getting a count */
	hdrfp  = etmpfile();
	datafp = etmpfile();
	ntr = 0;
	do { 
		++ntr;
		efwrite(&tr, 1, HDRBYTES, hdrfp);
		efwrite(tr.data, FSIZE, nt, datafp);
	} while (gettr(&tr));


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


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

}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{
	int nz;		/* numer of depth samples */
	int iz;		/* counter */
	int nt;		/* number of time samples */

	int nzpar;	/* number of getparred depth values for velocities */
	int nvpar;	/* number of getparred velocity values */
	int izpar;	/* counter */

	int verbose;	/* verbose flag, =0 silent, =1 chatty */

	float dz=0.0;	/* depth sampling interval */
	float fz=0.0;	/* first depth value */
	float dt=0.0;	/* time sampling interval for velocities */
	float ft=0.0;	/* first time value */
	float z=0.0;	/* depth values for times */
	float vmin=0.0;	/* minimum velocity */
	float vmax=0.0;	/* maximum velocity */

	float *zpar=NULL;	/* values of z getparred */
	float *vpar=NULL;	/* values of v getparred */
	float *vz=NULL;		/* v(z) velocity as a function of z */
	float *zt=NULL;		/* z(t) depth as a function of t */
	float *temp=NULL;	/* temporary storage array */
	char *vfile="";		/* name of the velocity file */

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

	/* get time sampling from first header */
	if (!gettr(&tr)) err("can't get first trace");
	nz = tr.ns;

	/* get depth sampling */
	if (!getparfloat("dz",&dz)) dz = ((float) tr.d1);

	/* determine velocity function v(t) */
	vz = ealloc1float(nz);
	if (!getparstring("vfile",&vfile)) {
		nzpar = countparval("z");
		if (nzpar==0) nzpar = 1;
		zpar = ealloc1float(nzpar);
		if (!getparfloat("z",zpar)) zpar[0] = 0.0;
		nvpar = countparval("v");
		if (nvpar==0) nvpar = 1;
		if (nvpar!=nzpar)err("number of t and v values must be equal");
		vpar = ealloc1float(nvpar);
		if (!getparfloat("v",vpar)) vpar[0] = 1500.0;
		for (izpar=1; izpar<nzpar; ++izpar)
			if (zpar[izpar]<=zpar[izpar-1])
				err("zpar must increase monotonically");
		for (iz=0,z=0.0; iz<nz; ++iz,z+=dz)
			intlin(nzpar,zpar,vpar,vpar[0],vpar[nzpar-1],
				1,&z,&vz[iz]);
	} else { /* read from a file */
		if (fread(vz,sizeof(float),nz,fopen(vfile,"r"))!=nz)
			err("cannot read %d velocities from file %s",nz,vfile);
	}

	/* determine minimum and maximum velocities */
	for (iz=1,vmin=vmax=vz[0]; iz<nz; ++iz) {
		if (vz[iz]<vmin) vmin = vz[iz];
		if (vz[iz]>vmax) vmax = vz[iz];
	}

	/* get parameters */
	if (!getparfloat("dt",&dt)) dt = 2.0*dz/vmin;
	if (!getparfloat("ft",&ft)) ft = 2.0*ft/vz[0];
	if (!getparint("nt",&nt)) nt = 1+(nz-1)*dz*2.0/(dt*vmax);
	if (!getparint("verbose",&verbose)) verbose = 0;
	CHECK_NT("nt",nt);

	/* if requested, print time sampling, etc */
	if (verbose) {
		warn("Input:");
		warn("\tnumber of depth samples = %d",nz);
		warn("\tdepth sampling interval = %g",dz);
		warn("\tfirst depth sample = %g",fz);
		warn("Output:");
		warn("\tnumber of time samples = %d",nt);
		warn("\ttime sampling interval = %g",dt);
		warn("\tfirst time sample = %g",ft);
	}

	/* allocate workspace */
	zt = ealloc1float(nt);
	temp = ealloc1float(nz);

	/* make z(t) function */
	makezt(nz,dz,fz,vz,nt,dt,ft,zt);
	
	/* loop over traces */
	do {
		/* update header fields */
		tr.trid = TREAL;
		tr.ns = nt;
		tr.dt = dt*1000000.0;
		tr.f1 = ft;
		tr.d1 = 0.0;

		/* resample */
		memcpy((void *) temp, (const void *) tr.data,nz*sizeof(float));
		ints8r(nz,dz,fz,temp,0.0,0.0,nt,zt,tr.data);

		/* put this trace before getting another */
		puttr(&tr);

	} while(gettr(&tr));

	return(CWP_Exit());
}
Exemplo n.º 4
0
int
main(int argc, char **argv)
{
   char *tmpdir ;                 /* directory path for tmp files */
   cwp_Bool istmpdir=cwp_false ;  /* true for user given path */
   float *hedr ;                  /* the headers */
   float *data ;                  /* the data */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   }

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

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

   rewind(headerfp);
   rewind(tracefp);

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

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

   free1(hedr) ;
   free1(data) ;

   return(CWP_Exit()) ;
}
Exemplo n.º 5
0
int main( int argc, char *argv[] )
{
	cwp_String keyg;	/* header key word from segy.h		*/
	cwp_String typeg;	/* ... its type				*/
	Value valg;
	cwp_String key[SU_NKEYS];	/* array of keywords		 */
	cwp_String type[SU_NKEYS];	/* array of keywords		 */
	int index[SU_NKEYS];	/* name of type of getparred key	 */
	
	segy **rec_o;		/* trace header+data matrix */	
	
	int first=0;	/* true when we passed the first gather */
	int ng=0;
	float dt;	/* time sampling interval		*/
	int nt;		/* number of time samples per trace	*/
	int ntr;	/* number of traces per ensemble	*/
	
	int nfft=0;		/* lenghth of padded array		*/
	float snfft;		/* scale factor for inverse fft		*/
	int nf=0;		/* number of frequencies		*/
	float d1;		/* frequency sampling int.		*/
	float *rt;		/* real trace				*/
	complex *ctmix;		/* complex trace			*/
	complex **fd;		/* frequency domain data		*/

	
	float padd;
	
	int nd;			/* number of dimensions */
	float *dx=NULL;
	float fac;
	float vmin;
	int vf;
	
	/* Trimming arrays */
	float *itrm=NULL;
	float *rtrm=NULL;
	float *wht=NULL;
	float trimp=15;
		
	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);
	
	if (!getparstring("keyg", &keyg)) keyg ="ep";
	if (!getparint("vf", &vf)) vf = 1;
	if (!getparfloat("vmin", &vmin)) vmin = 5000;
	if (!getparfloat("padd", &padd)) padd = 25.0;
	padd = 1.0+padd/100.0;
	
	/* Get "key" values */
	nd=countparval("key");
	getparstringarray("key",key);

	/* get types and indexes corresponding to the keys */
	{ int ikey;
		for (ikey=0; ikey<nd; ++ikey) {
			type[ikey]=hdtype(key[ikey]);
			index[ikey]=getindex(key[ikey]);
		}
	}

	dx = ealloc1float(nd);
	MUSTGETPARFLOAT("dx",(float *)dx);
	
	if (!getparfloat("fac", &fac)) fac = 1.0;
	fac = MAX(fac,1.0);

	/* get the first record */
	rec_o = get_gather(&keyg,&typeg,&valg,&nt,&ntr,&dt,&first);
	if(ntr==0) err("Can't get first record\n");
	
	/* set up the fft */
	nfft = npfar(nt*padd);
	if (nfft >= SU_NFLTS || nfft >= PFA_MAX)
		 	err("Padded nt=%d--too big", nfft);
	nf = nfft/2 + 1;
	snfft=1.0/nfft;
	d1 = 1.0/(nfft*dt);
	
	rt = ealloc1float(nfft);
	ctmix = ealloc1complex(nf);
	
	
	do {
		ng++;
		 	
		fd = ealloc2complex(nf,ntr); 
		memset( (void *) ctmix, (int) '\0', nf*sizeof(complex));
		
		itrm = ealloc1float(ntr);
		rtrm = ealloc1float(ntr);
		wht = ealloc1float(ntr);

		/* transform the data into FX domain */
		{ unsigned int itr;
			for(itr=0;itr<ntr;itr++) {
				memcpy( (void *) rt, (const void *) (*rec_o[itr]).data,nt*FSIZE);
				memset( (void *) &rt[nt], (int) '\0', (nfft - nt)*FSIZE);
				pfarc(1, nfft, rt, fd[itr]);
			
			}
		}
		
		/* Do the mixing */
		{ unsigned int imx=0,itr,ifr;
		  float dist;
		  
		  	
			/* Find the trace to mix */
			for(itr=0;itr<ntr;itr++) 
				if((*rec_o[itr]).mark) {
					imx = itr;
					break;
				}
			
			memcpy( (void *) ctmix, (const void *) fd[imx],nf*sizeof(complex));
			
			/* Save the header */
			memcpy( (void *) &tr, (const void *) rec_o[imx],HDRBYTES);
 		  	
			/* weights */
			wht[imx] = 1.0;
			for(itr=0;itr<imx;itr++) {
				 dist=n_distance(rec_o,index,type,dx,nd,imx,itr);
				 wht[itr] = MIN(1.0/dist,1.0);
				 wht[itr] = 1.0;
			}
			
			for(itr=imx+1;itr<ntr;itr++) {
				 dist=n_distance(rec_o,index,type,dx,nd,imx,itr);
				 wht[itr] = MIN(1.0/dist,1.0);
				 wht[itr] = 1.0;
			}
				 
			
			/* Do the alpha trim for each trace */			
			for(ifr=0;ifr<nf;ifr++) {
 		  		for(itr=0;itr<ntr;itr++) {
					itrm[itr] = fd[itr][ifr].i;
					rtrm[itr] = fd[itr][ifr].r;
				}
				ctmix[ifr].i = alpha_trim_w(itrm,wht,ntr,trimp);
				ctmix[ifr].r = alpha_trim_w(rtrm,wht,ntr,trimp);
			}
			
					
		}
		
		
		{ unsigned int it;
			pfacr(-1, nfft, ctmix, rt);
				for(it=0;it<nt;it++) 		
					tr.data[it]=rt[it]*snfft;
		}
			
		free2complex(fd);

		{ unsigned int itr;
			for(itr=0;itr<ntr;itr++) {
				free1((void *)rec_o[itr]);
			}
		}
		
		puttr(&tr);
		
	    	rec_o = get_gather(&keyg,&typeg,&valg,&nt,&ntr,&dt,&first);
		
		fprintf(stderr," %d %d\n",ng,ntr);
		
		free1float(rtrm);
		free1float(itrm);
		free1float(wht);
		
	} while(ntr);
		
	
	free1float(rt);

	warn("Number of gathers %10d\n",ng);
	 
	return EXIT_SUCCESS;
}
Exemplo n.º 6
0
int
main(int argc, char **argv)
{
	int nt;		/* number of time samples per trace */
	float dt;	/* time sampling interval */
	float ft;	/* time of first sample */
	int it;		/* time sample index */
	int ncdp;	/* number of cdps specified */
	float *cdp;	/* array[ncdp] of cdps */
	int icdp;	/* index into cdp array */
	int jcdp;	/* index into cdp array */
	int nvnmo;	/* number of vnmos specified */
	float *vnmo;	/* array[nvnmo] of vnmos */
	int ntnmo;	/* number of tnmos specified */
	float *tnmo;	/* array[ntnmo] of tnmos */
	float **ovv;	/* array[ncdp][nt] of sloth (1/velocity^2) functions */
	float *ovvt;	/* array[nt] of sloth for a particular trace */
	int nanis1;	/* number of anis1's specified */
	int nanis2;	/* number of anis2's specified */
	float *anis1;	/* array[nanis1] of anis1's */
	float *anis2;	/* array[nanis2] of anis2's */
	float **oa1;	/* array[ncdp][nt] of anis1 functions */
	float **oa2;	/* array[ncdp][nt] of anis2 functions */
	float *oa1t;	/* array[nt] of anis1 for a particular trace */
	float *oa2t;	/* array[nt] of anis2 for a particular trace */
	float smute;	/* zero samples with NMO stretch exceeding smute */
	float osmute;	/* 1/smute */
	int lmute;	/* length in samples of linear ramp for mute */
	int itmute=0;	/* zero samples with indices less than itmute */
	int sscale;	/* if non-zero, apply NMO stretch scaling */
	int invert;	/* if non-zero, do inverse NMO */
	float sy;	/* cross-line offset component */
	int ixoffset;	/* indes for cross-line offset component */
	long oldoffset;	/* offset of previous trace */
	long oldcdp;	/* cdp of previous trace */
	int newsloth;	/* if non-zero, new sloth function was computed */
	float tn;	/* NMO time (time after NMO correction) */
	float v;	/* velocity */
	float *qtn;	/* NMO-corrected trace q(tn) */
	float *ttn;	/* time t(tn) for NMO */
	float *atn;	/* amplitude a(tn) for NMO */
	float *qt;	/* inverse NMO-corrected trace q(t) */
	float *tnt;	/* time tn(t) for inverse NMO */
	float *at;	/* amplitude a(t) for inverse NMO */
	float acdp;	/* temporary used to sort cdp array */
	float *aovv;	/* temporary used to sort ovv array */
	float *aoa1;	/* temporary used to sort oa1 array */
	float *aoa2;	/* temporary used to sort oa2 array */
	float temp;	/* temporary float */
	float tsq;	/* temporary float */
	int i;		/* index used in loop */
	int upward;	/* scans upward if it's nonzero. */

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

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

	/* get velocity functions, linearly interpolated in time */
	ncdp = countparval("cdp");
	if (ncdp>0) {
		if (countparname("vnmo")!=ncdp)
			err("a vnmo array must be specified for each cdp");
		if (countparname("tnmo")!=ncdp)
			err("a tnmo array must be specified for each cdp");
		if (countparname("anis1")!=ncdp &&
		    countparname("anis1")!=0)
			err("an anis1 array must be specified for each cdp, "
			    "or omitted at all");
		if (countparname("anis2")!=ncdp &&
		    countparname("anis2")!=0)
			err("an anis2 array must be specified for each cdp, "
			    "or omitted at all");
	} else {
		ncdp = 1;
		if (countparname("vnmo")>1)
			err("only one (or no) vnmo array must be specified");
		if (countparname("tnmo")>1)
			err("only one (or no) tnmo array must be specified");
		if (countparname("anis1")>1)
			err("only one (or no) anis1 array must be specified");
		if (countparname("anis2")>1)
			err("only one (or no) anis2 array must be specified");
	}
	cdp = ealloc1float(ncdp);
	if (!getparfloat("cdp",cdp)) cdp[0] = tr.cdp;
	ovv = ealloc2float(nt,ncdp);
	oa1 = ealloc2float(nt,ncdp);
	oa2 = ealloc2float(nt,ncdp);
	for (icdp=0; icdp<ncdp; ++icdp) {
		nvnmo = countnparval(icdp+1,"vnmo");
		ntnmo = countnparval(icdp+1,"tnmo");
		nanis1 = countnparval(icdp+1,"anis1");
		nanis2 = countnparval(icdp+1,"anis2");
		if (nvnmo!=ntnmo && !(ncdp==1 && nvnmo==1 && ntnmo==0))
			err("number of vnmo and tnmo values must be equal");
		if (nanis1!=nvnmo && nanis1 != 0)
			err("number of vnmo and anis1 values must be equal");
		if (nanis2!=nvnmo && nanis2 != 0)
			err("number of vnmo and anis2 values must be equal");
		if (nvnmo==0) nvnmo = 1;
		if (ntnmo==0) ntnmo = nvnmo;
		if (nanis1==0) nanis1 = nvnmo;
		if (nanis2==0) nanis2 = nvnmo;
		/* equal numbers of parameters vnmo, tnmo, anis1, anis2 */
		vnmo = ealloc1float(nvnmo);
		tnmo = ealloc1float(nvnmo);
		anis1 = ealloc1float(nvnmo);
		anis2 = ealloc1float(nvnmo);
		if (!getnparfloat(icdp+1,"vnmo",vnmo)) vnmo[0] = 1500.0;
		if (!getnparfloat(icdp+1,"tnmo",tnmo)) tnmo[0] = 0.0;
		if (!getnparfloat(icdp+1,"anis1",anis1)) 
			for (i=0; i<nvnmo; i++) anis1[i] = 0.0;
		if (!getnparfloat(icdp+1,"anis2",anis2))
			for (i=0; i<nvnmo; i++) anis2[i] = 0.0;
		for (it=1; it<ntnmo; ++it)
			if (tnmo[it]<=tnmo[it-1])
				err("tnmo values must increase monotonically");
		for (it=0,tn=ft; it<nt; ++it,tn+=dt) {
			intlin(ntnmo,tnmo,vnmo,vnmo[0],vnmo[nvnmo-1],1,&tn,&v);
			ovv[icdp][it] = 1.0/(v*v);
		}
		for (it=0,tn=ft; it<nt; ++it,tn+=dt) {
			intlin(ntnmo,tnmo,anis1,anis1[0],anis1[nanis1-1],1,&tn,
			       &oa1[icdp][it]);
		}
		for (it=0,tn=ft; it<nt; ++it,tn+=dt) {
			intlin(ntnmo,tnmo,anis2,anis2[0],anis2[nanis2-1],1,&tn,
			       &oa2[icdp][it]);
		}
		free1float(vnmo);
		free1float(tnmo);
		free1float(anis1);
		free1float(anis2);
	}

	/* sort (by insertion) sloth and anis functions by increasing cdp */
	for (jcdp=1; jcdp<ncdp; ++jcdp) {
		acdp = cdp[jcdp];
		aovv = ovv[jcdp];
		aoa1 = oa1[jcdp];
		aoa2 = oa2[jcdp];
		for (icdp=jcdp-1; icdp>=0 && cdp[icdp]>acdp; --icdp) {
			cdp[icdp+1] = cdp[icdp];
			ovv[icdp+1] = ovv[icdp];
			oa1[icdp+1] = oa1[icdp];
			oa2[icdp+1] = oa2[icdp];
		}
		cdp[icdp+1] = acdp;
		ovv[icdp+1] = aovv;
		oa1[icdp+1] = aoa1;
		oa2[icdp+1] = aoa2;
	}

	/* get other optional parameters */
	if (!getparfloat("smute",&smute)) smute = 1.5;
	if (!getparint("ixoffset",&ixoffset)) ixoffset=0; 
	  if (ixoffset==0) sy = 0.0;
	if (smute<=0.0) err("smute must be greater than 0.0");
	if (!getparint("lmute",&lmute)) lmute = 25;
	if (!getparint("sscale",&sscale)) sscale = 1;
	if (!getparint("invert",&invert)) invert = 0;
	if (!getparint("upward",&upward)) upward = 0;

	/* allocate workspace */
	ovvt = ealloc1float(nt);
	oa1t = ealloc1float(nt);
	oa2t = ealloc1float(nt);
	ttn = ealloc1float(nt);
	atn = ealloc1float(nt);
	qtn = ealloc1float(nt);
	tnt = ealloc1float(nt);
	at = ealloc1float(nt);
	qt = ealloc1float(nt);

	/* interpolate sloth and anis function for first trace */
	interpovv(nt,ncdp,cdp,ovv,oa1,oa2,(float)tr.cdp,ovvt,oa1t,oa2t);

	/* set old cdp and old offset for first trace */
	oldcdp = tr.cdp;
	oldoffset = tr.offset-1;

	warn("sy = %f",sy);

	/* loop over traces */
	do {
		/* if necessary, compute new sloth and anis function */
		if (tr.cdp!=oldcdp && ncdp>1) {
			interpovv(nt,ncdp,cdp,ovv,oa1,oa2,(float)tr.cdp,
				  ovvt,oa1t,oa2t);
			newsloth = 1;
		} else {
			newsloth = 0;
		}

		/* if sloth and anis function or offset has changed */
		if (newsloth || tr.offset!=oldoffset) {
			/* compute time t(tn) (normalized) */
			temp = ((float) tr.offset*(float) tr.offset + sy*sy)/(dt*dt);
			for (it=0,tn=ft/dt; it<nt; ++it,tn+=1.0) {
				tsq = temp*ovvt[it] + \
				      oa1t[it]*temp*temp / (1.0+oa2t[it]*temp);
				if (tsq<0.0)
					err("negative moveout; check anis1, "
					    "anis2, or suwind far-offset "
					    "traces");
				if ((1.0+oa2t[it]*temp)<=0.0)
					err("anis2 negative and too small; "
					    "check anis2, or suwind far-offset"
					    " traces");
				ttn[it] = sqrt (tn*tn + tsq);
				}
			/* compute inverse of stretch factor a(tn) */
			atn[0] = ttn[1]-ttn[0];
			for (it=1; it<nt; ++it)
				atn[it] = ttn[it]-ttn[it-1];
			
			/* determine index of first sample to survive mute */
			osmute = 1.0/smute;
			if( !upward ) {
				for (it=0; it<nt-1 && atn[it]<osmute; ++it)
					;
			} else {
				/* scan samples from bottom to top */
				for (it=nt-1; it>0 && atn[it]>=osmute; --it)
					;
			}
			itmute = it;

			/* if inverse NMO will be performed */
			if (invert) {
							
				/* compute tn(t) from t(tn) */
				yxtoxy(nt-itmute,1.0,ft/dt+itmute,&ttn[itmute],
					nt-itmute,1.0,ft/dt+itmute,
					ft/dt-nt,ft/dt+nt,&tnt[itmute]);
			
				/* adjust mute time */
				itmute = 1.0+ttn[itmute]-ft/dt;
				itmute = MIN(nt-2,itmute);
								
				/* compute a(t) */
				if (sscale) {
					for (it=itmute+1; it<nt; ++it)
						at[it] = tnt[it]-tnt[it-1];
					at[itmute] = at[itmute+1];
				}
			}
		}
		
		/* if forward (not inverse) nmo */
		if (!invert) {
	
			/* do nmo via 8-point sinc interpolation */
			ints8r(nt,1.0,ft/dt,tr.data,0.0,0.0,
				nt-itmute,&ttn[itmute],&qtn[itmute]);
			
			/* apply mute */
			for (it=0; it<itmute; ++it)
				qtn[it] = 0.0;
			
			/* apply linear ramp */
			for (it=itmute; it<itmute+lmute && it<nt; ++it)
				qtn[it] *= (float)(it-itmute+1)/(float)lmute;
			
			/* if specified, scale by the NMO stretch factor */
			if (sscale)
				for (it=itmute; it<nt; ++it)
					qtn[it] *= atn[it];
			
			/* copy NMO corrected trace to output trace */
			memcpy( (void *) tr.data,
					(const void *) qtn, nt*sizeof(float));
		
		/* else inverse nmo */
		} else {
	
			/* do inverse nmo via 8-point sinc interpolation */
			ints8r(nt,1.0,ft/dt,tr.data,0.0,0.0,
				nt-itmute,&tnt[itmute],&qt[itmute]);
			
			/* apply mute */
			for (it=0; it<itmute; ++it)
				qt[it] = 0.0;
			
			/* if specified, undo NMO stretch factor scaling */
			if (sscale)
				for (it=itmute; it<nt; ++it)
					qt[it] *= at[it];
			
			/* copy inverse NMO corrected trace to output trace */
			memcpy( (void *) tr.data,
					(const void *) qt,nt*sizeof(float));
		}

		/* write output trace */
		puttr(&tr);

		/* remember offset and cdp */
		oldoffset = tr.offset;
		oldcdp = tr.cdp;

	} while (gettr(&tr));

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

	int ntmig,nvmig;	

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

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

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

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

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

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


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

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

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


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

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

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

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

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

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

	return(CWP_Exit());	
}
Exemplo n.º 8
0
main(int argc, char **argv)
{
	char *s;
	short h, vh[N];
	unsigned short u, vu[N];
	long l, vl[N];
	unsigned long v, vv[N];
	int i, vi[N], ipar, npar, nval;
	unsigned int p, vp[N];
	float f, vf[N];
	double d, vd[N];

	initargs(argc, argv);

	/* int parameters */
	npar = countparname("i");
	printf("\nnumber of i pars = %d\n",npar);
	for (ipar=1; ipar<=npar; ++ipar) {
		getnparint(ipar,"i",&i);
		printf("occurence %d of i=%d\n",ipar,i);
	}
	if (getparint("i", &i))	
		printf("last occurence of i=%d\n",i);
	npar = countparname("vi");
	printf("number of vi pars = %d\n",npar);
	for (ipar=1; ipar<=npar; ++ipar) {
		nval = countnparval(ipar,"vi");
		printf("occurence %d has %d values\n",ipar,nval);
		nval = getnparint(ipar,"vi",vi);
		printf("vi=");
		for (i=0; i<nval; i++)
			printf("%d%c",vi[i],i==nval-1?'\n':',');
	}
	if (npar>0) {
		nval = countparval("vi");
		printf("last occurence has %d values\n",nval);
		getparint("vi",vi);
		printf("vi=");
		for (i=0; i<nval; i++)
			printf("%d%c",vi[i],i==nval-1?'\n':',');
	}

	/* float parameters */
	npar = countparname("f");
	printf("\nnumber of f pars = %d\n",npar);
	for (ipar=1; ipar<=npar; ++ipar) {
		getnparfloat(ipar,"f",&f);
		printf("occurence %d of f=%g\n",ipar,f);
	}
	if (getparfloat("f", &f))	
		printf("last occurence of f=%g\n",f);
	npar = countparname("vf");
	printf("number of vf pars = %d\n",npar);
	for (ipar=1; ipar<=npar; ++ipar) {
		nval = countnparval(ipar,"vf");
		printf("occurence %d has %d values\n",ipar,nval);
		nval = getnparfloat(ipar,"vf",vf);
		printf("vf=");
		for (i=0; i<nval; i++)
			printf("%g%c",vf[i],i==nval-1?'\n':',');
	}
	if (npar>0) {
		nval = countparval("vf");
		printf("last occurence has %d values\n",nval);
		getparfloat("vf",vf);
		printf("vf=");
		for (i=0; i<nval; i++)
			printf("%g%c",vf[i],i==nval-1?'\n':',');
	}

	/* string parameters */
	npar = countparname("s");
	printf("\nnumber of s pars = %d\n",npar);
	for (ipar=1; ipar<=npar; ++ipar) {
		getnparstring(ipar,"s",&s);
		printf("occurence %d of s=%s\n",ipar,s);
	}
	if (getparstring("s", &s))	
		printf("last occurence of s=%s\n",s);
	
	if( auxgetpar("aux","i","i",&i) ) 
		printf("in aux last occurence of i=%d\n",i);
	if( auxgetpar("aux","f","f",&f) )
		printf("in aux last occurence of f=%f\n",f);
	if( auxgetpar("aux","s","s",&s) ) 
		printf("in aux last occurence of s=%s\n",s);

	if (getparint("i", &i))	
		printf("last occurence of i=%d\n",i);
	if( auxgetpar("aux","junk","s",&s) ) 
		printf("in aux last occurence of junk=%s\n",s);

	return EXIT_SUCCESS;
}
Exemplo n.º 9
0
Arquivo: recvPar.c Projeto: sun031/Jan
int recvPar(recPar *rec, float sub_x0, float sub_z0, float dx, float dz, int nx, int nz)
{
	float *xrcv1, *xrcv2, *zrcv1, *zrcv2;
	int ix0, ix1, iz0, iz1, i, ix, iz, ir, isign, verbose;
	float dxrcv, dzrcv, *dxr, *dzr, r, rr;
	float rrcv, dphi, oxrcv, ozrcv;
	float xrange, zrange;
	int Nx1, Nx2, Nz1, Nz2, Ndx, Ndz, iarray, nskip, nrec;
	int nxrcv, nzrcv, ncrcv, nrcv, max_nrec;
	float *xrcva, *zrcva;

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


	nrec=0;
	/* check if receiver positions on a circle are defined */
	if (getparfloat("rrcv", &rrcv)) {
		if (!getparfloat("dphi",&dphi)) dphi=2.0;
		if (!getparfloat("oxrcv",&oxrcv)) oxrcv=0.0;
		if (!getparfloat("ozrcv",&ozrcv)) ozrcv=0.0;
		ncrcv = NINT(360.0/dphi);
		
		for (ix=0; ix<ncrcv; ix++) {
			rec->xr[ix] = oxrcv-sub_x0+rrcv*cos(((ix*dphi)/360.0)*(2.0*M_PI));
			rec->zr[ix] = ozrcv-sub_z0+rrcv*sin(((ix*dphi)/360.0)*(2.0*M_PI));
			rec->x[ix] = NINT((oxrcv-sub_x0+rrcv*cos(((ix*dphi)/360.0)*(2.0*M_PI)))/dx);
			rec->z[ix] = NINT((ozrcv-sub_z0+rrcv*sin(((ix*dphi)/360.0)*(2.0*M_PI)))/dz);
			if (verbose>4) fprintf(stderr,"Receiver Circle: xrcv[%d]=%f zrcv=%f\n", ix, rec->xr[ix]+sub_x0, rec->zr[ix]+sub_z0);
		}
		nrec += ncrcv;
	}

	/* check if receiver array is defined */
	nxrcv = countparval("xrcva");
	nzrcv = countparval("zrcva");
	if (nxrcv != nzrcv) {
		verr("Number of receivers in array xrcva (%d), zrcva(%d) are not equal",nxrcv, nzrcv);
	}       
	
	if (nxrcv != 0) {
		/* receiver array is defined */
		xrcva = (float *)malloc(nxrcv*sizeof(float));
		zrcva = (float *)malloc(nxrcv*sizeof(float));
		getparfloat("xrcva", xrcva);
		getparfloat("zrcva", zrcva);
		for (ix=0; ix<nxrcv; ix++) {
			rec->xr[nrec+ix] = xrcva[ix]-sub_x0;
			rec->zr[nrec+ix] = zrcva[ix]-sub_z0;
			rec->x[nrec+ix] = NINT((xrcva[ix]-sub_x0)/dx);
			rec->z[nrec+ix] = NINT((zrcva[ix]-sub_z0)/dz);
			if (verbose>4) fprintf(stderr,"Receiver Array: xrcv[%d]=%f zrcv=%f\n", ix, rec->xr[nrec+ix]+sub_x0, rec->zr[nrec+ix]+sub_z0);
		}
		nrec += nxrcv;
		free(xrcva);
		free(zrcva);
	}
	
	/* linear receiver arrays */
	
	Nx1 = countparval("xrcv1");
	Nx2 = countparval("xrcv2");
	Nz1 = countparval("zrcv1");
	Nz2 = countparval("zrcv2");
	assert(Nx1==Nx2);
	assert(Nz1==Nz2);
	assert(Nx1==Nz1);
		
	if (nrec==0 && Nx1==0) { /* no receivers are defined use default linear array of receivers on top of model */
		Nx1=1;
	}
	
	if (Nx1!=0) {
		xrcv1 = (float *)malloc(Nx1*sizeof(float));
		xrcv2 = (float *)malloc(Nx1*sizeof(float));
		zrcv1 = (float *)malloc(Nx1*sizeof(float));
		zrcv2 = (float *)malloc(Nx1*sizeof(float));
		
		if(!getparfloat("xrcv1", xrcv1)) xrcv1[0]=sub_x0;
		if(!getparfloat("xrcv2", xrcv2)) xrcv2[0]=(nx-1)*dx+sub_x0;
		if(!getparfloat("zrcv1", zrcv1)) zrcv1[0]=sub_z0;
		if(!getparfloat("zrcv2", zrcv2)) zrcv2[0]=zrcv1[0];		
		
		Ndx = countparval("dxrcv");
		Ndz = countparval("dzrcv");

		dxr = (float *)malloc(Nx1*sizeof(float));
		dzr = (float *)malloc(Nx1*sizeof(float));
		if(!getparfloat("dxrcv", dxr)) dxr[0]=dx;
		if(!getparfloat("dzrcv", dzr)) dzr[0]=0.0;
		if ( (Ndx<=1) && (Ndz==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dzr[i] = dzr[0];
			}
			Ndx=1;
		}
		else if ( (Ndz==1) && (Ndx==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dzr[i] = dzr[0];
			}
			Ndz=1;
		}
		else { /* make sure that each array has dzrcv or dxrcv defined for each line or receivers */
			if (Ndx>1) assert(Ndx==Nx1);
			if (Ndz>1) assert(Ndz==Nx1);
		}
		
/*
		if ( (Ndx!=0) && (Ndz!=0) ) {
			vwarn("Both dzrcv and dxrcv are set: dxrcv value is used");
			Ndz=0;
			for (i=0; i<Nx1; i++) dzr[i] = 0.0;
		}
*/
		
		/* check if receiver arrays fit into model */
		for (iarray=0; iarray<Nx1; iarray++) {
			xrcv1[iarray] = MAX(sub_x0,      xrcv1[iarray]);
			xrcv1[iarray] = MIN(sub_x0+nx*dx,xrcv1[iarray]);
			xrcv2[iarray] = MAX(sub_x0,      xrcv2[iarray]);
			xrcv2[iarray] = MIN(sub_x0+nx*dx,xrcv2[iarray]);
			
			zrcv1[iarray] = MAX(sub_z0,      zrcv1[iarray]);
			zrcv1[iarray] = MIN(sub_z0+nz*dz,zrcv1[iarray]);
			zrcv2[iarray] = MAX(sub_z0,      zrcv2[iarray]);
			zrcv2[iarray] = MIN(sub_z0+nz*dz,zrcv2[iarray]);
		}


		/* calculate receiver array and store into rec->x,z */
		
		for (iarray=0; iarray<Nx1; iarray++) {
	
			xrange = (xrcv2[iarray]-xrcv1[iarray]); 
			zrange = (zrcv2[iarray]-zrcv1[iarray]); 
			if (dxr[iarray] != 0.0) {
				nrcv = NINT(abs(xrange/dxr[iarray]))+1;
				dxrcv=dxr[iarray];
				dzrcv = zrange/(nrcv-1);
				if (dzrcv != dzr[iarray]) {
					vwarn("For receiver array %d: calculated dzrcv=%f given=%f", iarray, dzrcv, dzr[iarray]);
					vwarn("The calculated receiver distance %f is used", dzrcv);
				}
			}
			else {
				if (dzr[iarray] == 0) {
					verr("For receiver array %d: receiver distance dzrcv is not given", iarray);
				}
				nrcv=NINT(abs(zrange/dzr[iarray]))+1;
				dxrcv = xrange/(nrcv-1);
				dzrcv = dzr[iarray];
				if (dxrcv != dxr[iarray]) {
					vwarn("For receiver array %d: calculated dxrcv=%f given=%f", iarray, dxrcv, dxr[iarray]);
					vwarn("The calculated receiver distance %f is used", dxrcv);
				}
			}

			// calculate coordinates
			for (ir=0; ir<nrcv; ir++) {
				rec->xr[nrec]=xrcv1[iarray]-sub_x0+ir*dxrcv;
				rec->zr[nrec]=zrcv1[iarray]-sub_z0+ir*dzrcv;

				rec->x[nrec]=NINT((rec->xr[nrec])/dx);
				rec->z[nrec]=NINT((rec->zr[nrec])/dz);
				nrec++;
			}
			if (nrec >= max_nrec) {
				verr("Number of receivers in arrays xrcv1,xrcv2,zrcv1,zrcv2 are larger than max: increas max_nrec %d",max_nrec);
			}
		}
	
		free(xrcv1);
		free(xrcv2);
		free(zrcv1);
		free(zrcv2);
		free(dxr);
		free(dzr);
	}
	rec->n = nrec;

	return 0;
}
Exemplo n.º 10
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());
}
Exemplo n.º 11
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);
}
Exemplo n.º 12
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;
}
Exemplo n.º 13
0
int main(int argc, char **argv)
{
  FILE *fpint, *fpcp, *fpcs, *fpro;
  int   example, verbose, writeint, nb;
  int	above, diffrwidth, dtype;
  int   Ngp, Ngs, Ngr, Np, Ns, Nr, Ng, Ni, Nv, Nvi, No, Noi;
  int   jint, jcount, j, ix, iz, nx, nz, nxp, nzp, *zp, nmaxx, nminx, optgrad, poly, gradt; 
  int	ncp, nro, ncs, nvel, skip, rayfile, store_int;
	long lseed;
  size_t  nwrite;
  float *data_out, orig[2], cp0, cs0, ro0;
  float	*x, *z, *var, *interface, **inter;
  float back[3], sizex, sizez, dx, dz;
  float **cp ,**cs, **ro, aver, gradlen, gradcp, gradcs, gradro;
  
  /* Gradient unit flag    */
  /* ------------------    */
  /* - 0 Unit : m/s per dz */
  /* - 1 Unit : m/s per m  */
  int gradunit;
  /* Number of Z-reference points (one per layer) */
  int Nzr=0;
  
  float   **gridcp, **gridcs, **gridro;
  segy    *hdrs;
  FILE    *fpout;
  char    *file, intt[10], *file_base, filename[150];
  
  initargs(argc, argv);
  requestdoc(1);
  
  if (!getparint("example", &example)) example=0;
  else { plotexample(); exit(0); }
  
  if(getparstring("file",&file_base)) 
    vwarn("parameters file is changed to file_base");
  else {
    if(!getparstring("file_base",&file_base))
      verr("file_base not specified.");
  }
  if(getparfloat("back", back)) {
    vwarn("parameters back is not used anymore");
    vwarn("it has changed into cp0 (ro0,cs0 are optional)");
    nb = countparval("back");
    if (nb == 1) {
      vwarn("The new call should be cp0=%.1f",back[0]);
      cp0 = back[0];
    }
    if (nb == 2) {
      vwarn("The new call should be cp0=%.1f",back[0]);
      vwarn("                       ro0=%.1f",back[1]);
      cp0 = back[0];
      ro0 = back[1];
    }
    if (nb == 3) {
      vwarn("The new call should be cp0=%.1f",back[0]);
      vwarn("                       cs0=%.1f",back[1]);
      vwarn("                       ro0=%.1f",back[2]);
      cp0 = back[0];
      cs0 = back[1];
      ro0 = back[2];
    }
    vmess("Don't worry everything still works fine");
  }
  else {
    if(!getparfloat("cp0", &cp0)) verr("cp0 not specified.");
    if(!getparfloat("cs0", &cs0)) cs0 = -1;
    if(!getparfloat("ro0", &ro0)) ro0 = -1;
  }
  if(!getparfloat("sizex", &sizex)) verr("x-model size not specified.");
  if(!getparfloat("sizez", &sizez)) verr("z-model size not specified.");
  if(!getparfloat("dx", &dx)) verr("grid distance dx not specified.");
  if(!getparfloat("dz", &dz)) verr("grid distance dz not specified.");
  if(!getparfloat("orig", orig)) orig[0] = orig[1] = 0.0;
  if(!getparint("gradt", &gradt)) gradt = 1;
  if(!getparint("gradunit", &gradunit)) gradunit = 0;
  if(!getparint("writeint", &writeint)) writeint = 0;
  if(!getparint("rayfile", &rayfile)) rayfile = 0;
  if(!getparint("skip", &skip)) skip = 5;
  if(!getparint("above", &above)) above=0;
  if(!getparint("verbose", &verbose)) verbose=0;
  if(!getparint("dtype", &dtype)) dtype = 0;
  
  if ((writeint == 1) || (rayfile == 1)) store_int = 1;
  else store_int = 0;
  
  /*=================== check parameters =================*/
  
  Np = countparname("cp");
  Ns = countparname("cs");
  Nr = countparname("ro");
  Ng = countparname("grad");
  No = countparname("poly");
  Ni = countparname("intt");
  Nv = countparname("var");
  Ngp = countparname("gradcp");
  Ngs = countparname("gradcs");
  Ngr = countparname("gradro");
  
  Nvi = 0;
  for (jint = 1; jint <= Ni; jint++) {
    getnparstring(jint,"intt", &file);
    strcpy(intt, file);
    if (strstr(intt,"sin") != NULL) Nvi++;
    if (strstr(intt,"rough") != NULL) Nvi++;
    if (strstr(intt,"fract") != NULL) Nvi++;
    if (strstr(intt,"elipse") != NULL) Nvi++;
	if (strstr(intt,"random") != NULL) Nvi++;
//	if (strstr(intt,"randdf") != NULL) Nvi++;
    if (strstr(intt,"diffr") != NULL || strstr(intt,"randdf") != NULL) {
	  Nvi++;
//      if (Ng != 0) Ng++; 
//      if (No != 0) No++;
    }
  }
//  fprintf(stderr,"Nvi=%d ng=%d No=%d np=%d,", Nvi,Ng,No,Np);
  
  if (Np != Nr && ro0 > 0) verr("number of cp and ro not equal.");
  if (Np != Ni) verr("number of cp and interfaces not equal.");
  if (Nvi != Nv) verr("number of interface variables(var) not correct.");
  if (Ns == 0 && Nr == 0) if (verbose>=2) vmess("Velocity model.");
  if (Ns == 0) { if (verbose>=2) vmess("Acoustic model."); }
  else {
    if (verbose>=2) vmess("Elastic model.");
    if (Np != Ns) verr("number of cp and cs not equal");
  }
  
  if (Ng == 0) {
    if (verbose>=2) vmess("No boundary gradients are defined.");
  }
  else if (Ng != Np) {
    verr("number of boundary gradients and interfaces are not equal.");
  }
  if (Ngp == 0) {
    if (verbose>=2) vmess("No interface gradients for cp defined.");
  }
  else if (Ngp != Np) {
    verr("gradcp gradients and interfaces are not equal.");
  }
  if (Ngs == 0) {
    if (verbose>=2) vmess("No interface gradients for cs defined.");
  }
  else if (Ngs != Np) {
    verr("gradcs gradients and interfaces are not equal.");
  }
  if (Ngr == 0) {
    if (verbose>=2) vmess("No interface gradients for rho defined.");
  }
  else if (Ngr != Np) {
    verr("gradro gradients and interfaces are not equal.");
  }
  if (No == 0) {
    if (verbose>=2) vmess("All interfaces are linear.");
  }
//  else if (No != Np) {
//    verr("number of poly variables and interfaces are not equal.");
//  }
  
  if (Np > 0) {
    if (countparname("x") != Np)
      verr("a x array must be specified for each interface.");
    if (countparname("z") != Np)
      verr("a z array must be specified for each interface.");
  } 
  else Np = 1;

  if (Nzr != Np && Nzr !=0) {
    verr("number of zref gradients not equal to number of interfaces");
  }
  
  /*=================== initialization of arrays =================*/
  
  nz = NINT(sizez/dz)+1;
  nx = NINT(sizex/dx)+1;
  
  zp = (int *)malloc(nx*sizeof(int));
  interface = (float *)malloc(nx*sizeof(float));
  var = (float *)malloc(8*sizeof(float));
  gridcp = alloc2float(nz, nx);
  if(gridcp == NULL) verr("memory allocation error gridcp");
  if (Ns || (NINT(cs0*1e3) >= 0)) {
    gridcs = alloc2float(nz, nx);
    if(gridcs == NULL) verr("memory allocation error gridcs");
  }
  else gridcs = NULL;
  if (Nr || (NINT(ro0*1e3) >= 0)) {
    gridro = alloc2float(nz, nx);
    if(gridro == NULL) verr("memory allocation error gridro");
  }
  else gridro = NULL;
  
  cp = alloc2float(nx,3);
  cs = alloc2float(nx,3);
  ro = alloc2float(nx,3);
  if (store_int == 1) inter = alloc2float(nx, 2*Np);
  
  if (verbose) {
    vmess("Origin top left (x,z) . = %.1f, %.1f", orig[0], orig[1]);
    vmess("Base name ............. = %s", file_base);
    vmess("Number of interfaces .. = %d", Np);
    vmess("length in x ........... = %f (=%d)", sizex, nx);
    vmess("length in z ........... = %f (=%d)", sizez, nz);
    vmess("delta x ............... = %f", dx);
    vmess("delta z ............... = %f", dz);
    vmess("cp0 ................... = %f", cp0);
    if (Ns) vmess("cs0 ................... = %f", cs0);
    if (Nr) vmess("ro0 ................... = %f", ro0);
    vmess("write interfaces ...... = %d", writeint);
    vmess("store interfaces ...... = %d", store_int);
    if (above) vmess("define model above interface");
    else vmess("define model below interface");
  }

  /*========== initializing for homogeneous background =============*/
  
  nminx = 0;
  nmaxx = nx;
  for (j = nminx; j < nmaxx; j++) {
    cp[0][j] = cp0;
    cs[0][j] = cs0;
    ro[0][j] = ro0;
    zp[j] = 0;
    cp[1][j] = cp0;
    cs[1][j] = cs0;
    ro[1][j] = ro0;
  }
  
  gradlen = 0.0;
  gradcp = gradcs = gradro = 0.0;
  optgrad = 3;
  if (above == 0) {
    Nvi = 1; Noi = 1;
  } else {
    Nvi = Ngp; Noi = Ngp;
  }
  grid(gridcp, gridcs, gridro, zp, cp, cs, ro, nminx, nmaxx, optgrad,
       gradlen, gradcp, gradcs, gradro, dx, dz, nz);
  
  nxp = nzp = 2;
  x = (float *)malloc(nxp*sizeof(float));
  z = (float *)malloc(nzp*sizeof(float));
  
  if (Ni == 0) {
    if (verbose) vmess("No interfaces are defined, Homogeneous model.");
    Np = 0;
  }
  
  /*========== filling gridded model with interfaces =============*/
  
  for (jcount = 1; jcount <= Np; jcount++) {
    
    /* for above interface definition reverse	*/
    /* order of interfaces to scan 			*/
    if (above == 0) jint=jcount;
    else jint=Np+1-jcount;
    
    if (verbose) vmess("***** Interface number %d *****", jint);
    
    getnparstring(jint,"intt", &file);
    strcpy(intt, file);
    
    nxp = countnparval(jint,"x");
    nzp = countnparval(jint,"z");
    if (nxp != nzp) {
      vmess("nxp = %d nzp =%d for interface %d",nxp, nzp, jint);
      verr("Number of x and z values not equal for interface %d",jint);
    }
    ncp = countnparval(jint,"cp");
    nro = countnparval(jint,"ro");
    ncs = countnparval(jint,"cs");
    
    if (ncp == 1) {
      if (verbose>=2) vmess("No lateral gradient in P velocity");
    }
    else if (ncp == 2) {
      if (verbose) vmess("lateral P-gradient from begin to end");
    }
    else if (ncp != nxp) {
      vmess("ncp = %d nxp =%d for interface %d",ncp, nxp, jint);
      verr("Number of cp's and x not equal for interface %d",jint);
    }
    if (nro <= 1) {
      if (verbose>=2) vmess("No lateral gradient in density");
    }
    else if (nro == 2) {
      if (verbose) vmess("lateral Rho-gradient from begin to end");
    }
    else if (nro != nxp) {
      vmess("nro = %d nxp =%d for interface %d",nro, nxp, jint);
      verr("Number of ro's and x not equal for interface %d",jint);
    }
    if (ncs <= 1) {
      if (verbose>=2) vmess("No lateral gradient in S velocity");
    }
    else if (ncs == 2) {
      if (verbose) vmess("lateral S-gradient from begin to end");
    }
    else if (ncs != nxp) {
      vmess("ncs = %d nxp =%d for interface %d",ncs, nxp, jint);
      verr("Number of cs's and x not equal for interface %d",jint);
    }
    
    nvel = MAX(ncp, MAX(nro, ncs));
    
    free(x);
    free(z);
    x = (float *)malloc(nxp*sizeof(float));
    z = (float *)malloc(nzp*sizeof(float));
	memset(interface, 0, nx*sizeof(float));
    
    getnparfloat(jint,"x",x);
    getnparfloat(jint,"z",z);
    getnparfloat(jint,"cp",cp[2]);
    if (Nr == 0) ro[2][0] = 0.0;
    else getnparfloat(jint,"ro", ro[2]);
    if (Ns == 0) cs[2][0] = 0.0;
    else getnparfloat(jint,"cs", cs[2]);
    if (Ng == 0) gradlen = 0.0;
    else getnparfloat(Noi,"grad", &gradlen);
    if (No == 0) poly = 0;
    else getnparint(Noi,"poly", &poly);
    if (Ngp == 0) gradcp = 0.0;
    else getnparfloat(Noi,"gradcp", &gradcp);
    if (Ngs == 0) gradcs = 0.0;
    else getnparfloat(Noi,"gradcs", &gradcs);
    if (Ngr == 0) gradro = 0.0;
    else getnparfloat(Noi,"gradro", &gradro);
    /* if gradunit is in meters, recalculate gradcp,gradcs and gradro */
    if (gradunit > 0) {
      gradcs = gradcs * dz;
      gradcp = gradcp * dz;
      gradro = gradro * dz;
    }
    
    if (nvel != 1) {
      if (ncp == 1) {
	for (j = 1; j < nvel; j++) cp[2][j] = cp[2][0];
      }
      if (ncs == 1) {
	for (j = 1; j < nvel; j++) cs[2][j] = cs[2][0];
      }
      if (nro == 1) {
	for (j = 1; j < nvel; j++) ro[2][j] = ro[2][0];
      }
    }
    
    if (verbose) {
      vmess("Interface type .......... = %s", intt);
      vmess("Boundary gradient ....... = %f", gradlen);
      vmess("Interface gradient cp ... = %f", gradcp);
      if (Ns) vmess("Interface gradient cs ... = %f", gradcs);
      if (Nr) vmess("Interface gradient ro ... = %f", gradro);
      if (verbose>=2) {
	vmess("Polynomal ............... = %d", poly);
	vmess("Number of (x,z) points... = %d", nxp);
	vmess("P-wave velocities ....... = %d", ncp);
	if (Ns) vmess("S-wave velocities ....... = %d", ncs);
	if (Nr) vmess("Densities ............... = %d", nro);
      }
      for (j = 0; j < nxp; j++) {
	vmess("x = %6.1f \t z = %6.1f", x[j], z[j]);
	if (nvel != 1) {
	  vmess("    cp = %f", cp[2][j]);
	  if (Ns) vmess("    cs = %f", cs[2][j]);
	  if (Nr) vmess("   rho = %f", ro[2][j]);
	}
      }
      if (nvel == 1) {
	vmess("    cp = %f", cp[2][0]);
	if (Ns) vmess("    cs = %f", cs[2][0]);
	if (Nr) vmess("    rho = %f", ro[2][0]);
      }
    }
    
    for (j = 0; j < nxp; j++) {
      x[j] -= orig[0];
      z[j] -= orig[1];
    }
    for (j = 0; j < nxp; j++) {
      if(x[j] > sizex) verr("x coordinate bigger than model");
      if(z[j] > sizez) verr("z coordinate bigger than model");
    }
    if (gradlen > 0) optgrad = gradt;
    else optgrad = 3;
    
	if (strstr(intt,"random") != NULL) {
		Nv = countnparval(Nvi,"var");
		if (Nv != 1) verr("Random interface must have 1 variables.");
		getnparfloat(Nvi,"var", var);
		lseed = (long)var[0];
		srand48(lseed);
		gradcp=gradcs=gradro=var[0];
		optgrad = 4;
        if (above == 0) Noi++; else Noi--;
        if (above == 0) Nvi++; else Nvi--;
	}
	  
    if ((strstr(intt,"diffr") == NULL) && (strstr(intt,"randdf") == NULL)) {
      interpolation(x, z, nxp, nx, poly, &nminx, &nmaxx, dx, 
		    cp, cs, ro, nvel, interface);
    }

    if ( (strstr(intt,"def") != NULL) || (strstr(intt,"random") != NULL) ) {
      linearint(zp, nminx, nmaxx, dz, interface);
      if (above == 0) Noi++; else Noi--;
    }

    if (strstr(intt,"sin") != NULL) {
      Nv = countnparval(Nvi,"var");
      if (Nv != 2) verr("Sinus interface must have 2 variables.");
      getnparfloat(Nvi,"var", var);
      sinusint(zp, nminx, nmaxx, dz, interface, dx, var[0], var[1]);
      if (above == 0) Noi++; else Noi--;
      if (above == 0) Nvi++; else Nvi--;
    }
    else if (strstr(intt,"rough") != NULL) {
      Nv = countnparval(Nvi,"var");
      if (Nv != 3) verr("Rough interface must have 3 variables.");
      getnparfloat(Nvi,"var", var);
      roughint(zp, nminx, nmaxx, dz, interface, var[0],var[1],var[2]);
      if (above == 0) Noi++; else Noi--;
      if (above == 0) Nvi++; else Nvi--;
    }
    else if (strstr(intt,"fract") != NULL) {
      Nv = countnparval(Nvi, "var");
      if (Nv != 6) verr("Fractal interface must have 6 variables.");
      getnparfloat(Nvi,"var", var);
      fractint(zp, nminx, nmaxx, dx, dz, interface, var[0], var[1], 
	       var[2], var[3], var[4], var[5]);
      if (above == 0) Noi++; else Noi--;
      if (above == 0) Nvi++; else Nvi--;
    }
   	else if (strstr(intt,"randdf") != NULL) {
		float x0, z0, dsx, dsz;
		int i;
		Nv = countnparval(Nvi, "var");
		if (Nv != 2) verr("randdf interface must have 2 variables: number of points, width.");
		getnparfloat(Nvi,"var", var);
        if(!getparint("dtype", &dtype)) dtype = -1;
        
        randdf(x, z, nxp, dx, dz, gridcp, gridcs, gridro, cp, cs, ro,
              interface, zp, nx, sizex, sizez, var[0], (int)var[1], dtype);

		if (above == 0) Noi++; else Noi--;
		if (above == 0) Nvi++; else Nvi--;
	}
	else if (strstr(intt,"elipse") != NULL) {
		Nv = countnparval(Nvi, "var");
		if (Nv != 2) verr("Elipse interface must have 2 variables.");
		getnparfloat(Nvi,"var", var);
		elipse(x, z, nxp, dx, dz, gridcp, gridcs, gridro, 
			cp, cs, ro, interface, zp, nz, nx, var[0], var[1], gradcp, gradcs, gradro);
		if (above == 0) Noi++; else Noi--;
		if (above == 0) Nvi++; else Nvi--;
	}
	else if ((strstr(intt,"diffr") != NULL)) {
		Nv = countnparval(Nvi, "var");
        if (Nv == 2 || Nv == 1) {
            getnparfloat(Nvi,"var", var);
            diffrwidth=(int)var[0];
            if (Nv==1) {
            	if(!getparint("dtype", &dtype)) dtype = 0;
			}
            else dtype=(int)var[1];
        }
        else {
            verr("diffr interface must have 1 or 2 variables: width,type.");
        }
        
		diffraction(x, z, nxp, dx, dz, gridcp, gridcs, gridro,
			cp, cs, ro, interface, zp, nx, diffrwidth, dtype);
		if (above == 0) Noi++; else Noi--;
		if (above == 0) Nvi++; else Nvi--;
	}
    else {
		if (above == 0) {
			grid(gridcp, gridcs, gridro, zp, cp, cs, ro, nminx, nmaxx, 
				optgrad, gradlen, gradcp, gradcs, gradro, dx, dz, nz);
		} 
		else {
			gridabove(gridcp, gridcs, gridro, zp, cp, cs, ro, nminx, nmaxx, 
				optgrad, gradlen, gradcp, gradcs, gradro, dx, dz, nz);
		}
	}
    
    if (store_int == 1) {
      for(j = 0; j < nminx; j++) inter[jint-1][j] = 0.0;
      for(j = nminx; j < nmaxx; j++) inter[jint-1][j] = interface[j];
      for(j = nmaxx; j < nx; j++) inter[jint-1][j] = 0.0;
      
      for(j = 0; j < nminx; j++) inter[jint-1+Np][j] = 0.0;
      for(j = nminx; j < nmaxx; j++) inter[jint-1+Np][j] = zp[j]*dz;
      for(j = nmaxx; j < nx; j++) inter[jint-1+Np][j] = 0.0;
    }
  } /* end of loop over interfaces */
  
  if (verbose) vmess("Writing data to disk.");
  
  hdrs = (segy *) calloc(nx,sizeof(segy));
  for(j = 0; j < nx; j++) {
	hdrs[j].f1= orig[1];
	hdrs[j].f2= orig[0];
	hdrs[j].d1= dz;
	hdrs[j].d2= dx;
    hdrs[j].ns= nz;
	hdrs[j].trwf= nx;
	hdrs[j].tracl= j;
	hdrs[j].tracf= j;
    hdrs[j].gx = (orig[0] + j*dx)*1000;
    hdrs[j].scalco = -1000;
    hdrs[j].timbas = 25;
    hdrs[j].trid = TRID_DEPTH;
  }

  /* due to bug in SU, int-file has to be opened before other files are closed */
  if (writeint == 1) {
    strcpy(filename, file_base);
    name_ext(filename, "_int");
    fpint = fopen(filename,"w");
    assert(fpint != NULL);
  }
  
  /* write P-velocities in file */
  strcpy(filename, file_base);
  name_ext(filename, "_cp");
  fpcp = fopen(filename,"w");
  assert(fpcp != NULL);
  
  data_out = (float *)malloc(nx*nz*sizeof(float));
  for(ix = 0; ix < nx; ix++) {
    for(iz = 0; iz < nz; iz++) {
      data_out[ix*nz+iz] = gridcp[ix][iz];
	}
    nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpcp);
    assert(nwrite == TRCBYTES);
    nwrite = fwrite( &data_out[ix*nz], sizeof(float), nz, fpcp);
    assert(nwrite == nz);
  }
  fclose(fpcp);
  free2float(gridcp);
  
  /* write S-velocities in file */
  if (Ns > 0 || getparfloat("cs0", &cs0)) {
    strcpy(filename, file_base);
    name_ext(filename, "_cs");
    fpcs = fopen(filename,"w");
    assert(fpcs != NULL);
    
    for(ix = 0; ix < nx; ix++) {
      for(iz = 0; iz < nz; iz++) {
	     data_out[ix*nz+iz] = gridcs[ix][iz];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpcs);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[ix*nz], sizeof(float), nz, fpcs);
      assert(nwrite == nz);
    }
    fclose(fpcs);
    free2float(gridcs);
    
  } /* end of writing S-velocity file */
  
  /* write densities in file */
  if (Nr > 0 || getparfloat("ro0", &ro0)) {
    strcpy(filename, file_base);
    name_ext(filename, "_ro");
    fpro = fopen(filename,"w");
    assert(fpro != NULL);
    
    for(ix = 0; ix < nx; ix++) {
      for(iz = 0; iz < nz; iz++) {
	     data_out[ix*nz+iz] = gridro[ix][iz];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpro);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[ix*nz], sizeof(float), nz, fpro);
      assert(nwrite == nz);
    }
    fclose(fpro);
    free2float(gridro);
  } /* end of writing density file */
  
  /* write depths of the interfaces */
  if (writeint == 1) {
    free(hdrs);
    hdrs = (segy *) calloc(Np,sizeof(segy));
    for(j = 0; j < Np; j++) {
      hdrs[j].fldr = 1;
      hdrs[j].timbas = 25;
	  hdrs[j].f1= orig[0];
	  hdrs[j].f2= 0.0;
	  hdrs[j].d1= dx;
	  hdrs[j].d2= dz;
	  hdrs[j].ns= nx;
	  hdrs[j].trwf= Np;
	  hdrs[j].tracl= j;
	  hdrs[j].tracf= j;
	  hdrs[j].trid= TRID_DEPTH;
    }
    
    /* note that due to bug in SU, interface file ha salready been opened */
    strcpy(filename, file_base);
    name_ext(filename, "_int");

    free(data_out);
    data_out = (float *)malloc(nx*Np*sizeof(float));
    for(jint = 0; jint < Np; jint++) {
      for(j = 0; j < nx; j++) {
	    data_out[jint*nx+j] = inter[jint][j]+orig[1];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpint);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[jint*nx], sizeof(float), nx, fpint);
      assert(nwrite == nx);
    }
    
	for(j = 0; j < Np; j++) hdrs[j].fldr = 2;
    for(jint = 0; jint < Np; jint++) {
      for(j = 0; j < nx; j++) {
	     data_out[jint*nx+j] = inter[jint+Np][j]+orig[1];
      }
      nwrite = fwrite( &hdrs[ix], 1, TRCBYTES, fpint);
      assert(nwrite == TRCBYTES);
      nwrite = fwrite( &data_out[jint*nx], sizeof(float), nx, fpint);
      assert(nwrite == nx);
    }
    fclose(fpint);
    
  } /* end of writing interface file */
  
  if (rayfile == 1) {
    strcpy(filename, file_base);
    strcpy(strrchr(filename, '.'), ".mod");
    
    fpout = fopen(filename, "w+");
    fprintf(fpout,"RAYTRACE MODEL FILE\n");
    fprintf(fpout,"# ASCII file for ray-tracer\n\n");
    fprintf(fpout,"# Top interface\n\n");
    fprintf(fpout,"x=0,%.1f\n", sizex);
    fprintf(fpout,"z=0.,0.\n");
    
    /*		for(i = 1; i <= Np; i++) {
		fprintf(fpout,"\n# %d th interface\n\nx=",i);
		nxp = countnparval(i,"x");
		nzp = countnparval(i,"z");
		free(x);
		free(z);
		x = (float *)malloc(nxp*sizeof(float));
		z = (float *)malloc(nzp*sizeof(float));
		getnparfloat(i,"x",x);
		getnparfloat(i,"z",z);
		for(j = 0; j < (nxp-1); j ++) fprintf(fpout,"%.1f,", x[j]);
		fprintf(fpout,"%.1f\nz=", x[nxp-1]);
		for(j = 0; j < (nxp-1); j ++) fprintf(fpout,"%.1f,", z[j]);
		fprintf(fpout,"%.1f\n", z[nxp-1]);
		}
    */
    for(jint = 0; jint < Np; jint++) {
      fprintf(fpout,"\n# %d th interface\n\nx=0",jint+1);
      for(j = skip; j < nx; j += skip) 
	fprintf(fpout,",%.1f", (float)j*dx);
      
      fprintf(fpout,"\nz=%.1f", inter[jint][0]);
      for(j = skip; j < nx; j += skip) 
	fprintf(fpout,",%.1f", inter[jint][j]);
      fprintf(fpout,"\n");
    }
    fprintf(fpout,"\n# %d th interface\n\nx=0",jint+1);
    for(j = skip; j < nx; j += skip) 
      fprintf(fpout,",%.1f", (float)j*dx);
    
    fprintf(fpout,"\nz=%.1f", sizez);
    for(j = skip; j < nx; j += skip) 
      fprintf(fpout,",%.1f", sizez);
    fprintf(fpout,"\n");
    
    /**/
    fprintf(fpout,"\n\n");
    fprintf(fpout,"cp=%.1f,", back[0]);
    for(jint = 1; jint <= Np; jint++) {
      aver = 0.0;
      ncp = countnparval(jint,"cp");
      getnparfloat(jint,"cp",cp[2]);
      for(j = 0; j < ncp; j++) 
	aver += cp[2][j];
      aver = aver/((float)ncp);
      if (jint == Np ) fprintf(fpout,"%.1f", aver);
      else fprintf(fpout,"%.1f,", aver);
    }
    
    fclose(fpout);
    free2float(inter);
  }
  
  free(hdrs);
  
  return 0;
}
Exemplo n.º 14
0
int
main (int argc, char **argv)
{
	int nr,er,ob,sp,ir,ixz,ls,smooth,ndpfz,ns,
		ixo,ixsm,nxo,nxs,nxm,nt,nxsm,
		shots,midpoints,verbose,tracl,
		*nxz;
	float x0,z0,v00,gamma,dvdx,dvdz,vmin,tmin,tminr,
		x,z,v,t,dsmax,fpeak,
		dxs,dxm,dxo,dt,fxs,fxm,fxo,ft,dxsm,
		xs,zs,xg,zg,
		*xo,*ar,**xr,**zr;
	Reflector *r;
	Wavelet *w;

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

	/* get parameters */
	if (!getparint("nt",&nt)) nt = 101; CHECK_NT("nt",nt);
	if (!getparfloat("dt",&dt)) dt = 0.04;
	if (!getparfloat("ft",&ft)) ft = 0.0;
	if ((nxo=countparval("xo"))!=0) {
		xo = ealloc1float(nxo);
		getparfloat("xo",xo);
	} else {
		if (!getparint("nxo",&nxo)) nxo = 1;
		if (!getparfloat("dxo",&dxo)) dxo = 0.05;
		if (!getparfloat("fxo",&fxo)) fxo = 0.0;
		xo = ealloc1float(nxo);
		for (ixo=0; ixo<nxo; ++ixo)
			xo[ixo] = fxo+ixo*dxo;
	}
	shots = (getparint("nxs",&nxs) || 
		getparfloat("dxs",&dxs) || 
		getparfloat("fxs",&fxs));
	midpoints = (getparint("nxm",&nxm) || 
		getparfloat("dxm",&dxm) || 
		getparfloat("fxm",&fxm)); 
	if (shots && midpoints)
		err("cannot specify both shot and midpoint sampling!\n");
	if (shots) {
		if (!getparint("nxs",&nxs)) nxs = 101;
		if (!getparfloat("dxs",&dxs)) dxs = 0.05;
		if (!getparfloat("fxs",&fxs)) fxs = 0.0;
		nxsm = nxs;
		dxsm = dxs;
	} else {
		midpoints = 1;
		if (!getparint("nxm",&nxm)) nxm = 101;
		if (!getparfloat("dxm",&dxm)) dxm = 0.05;
		if (!getparfloat("fxm",&fxm)) fxm = 0.0;
		nxsm = nxm;
		dxsm = dxm;
	}
	if (!getparint("nxm",&nxm)) nxm = 101;
	if (!getparfloat("dxm",&dxm)) dxm = 0.05;
	if (!getparfloat("fxm",&fxm)) fxm = 0.0;
	if (!getparfloat("x0",&x0)) x0 = 0.0;
	if (!getparfloat("z0",&z0)) z0 = 0.0;
	if (!getparfloat("v00",&v00)) v00 = 2.0;
	if (!getparfloat("gamma",&gamma)) gamma = 1.0;
	if (!getparfloat("dvdx",&dvdx)) dvdx = 0.0;
	if (!getparfloat("dvdz",&dvdz)) dvdz = 0.0;
	if (!getparfloat("fpeak",&fpeak)) fpeak = 0.2/dt;
	if (!getparint("ls",&ls)) ls = 0;
	if (!getparint("er",&er)) er = 0;
	if (!getparint("ob",&ob)) ob = 1;
	if (!getparint("sp",&sp)) sp = 1;
	if (!getparfloat("tmin",&tmin)) tmin = 10.0*dt;
	if (!getparint("ndpfz",&ndpfz)) ndpfz = 5;
	if (!getparint("smooth",&smooth)) smooth = 0;
	if (!getparint("verbose",&verbose)) verbose = 0;
	decodeReflectors(&nr,&ar,&nxz,&xr,&zr);
	if (!smooth) breakReflectors(&nr,&ar,&nxz,&xr,&zr);

	/* convert velocity v(x0,z0) to v(0,0) */
	v00 -= dvdx*x0+dvdz*z0;
	
	/* determine minimum velocity and minimum reflection time */
	for (ir=0,vmin=FLT_MAX,tminr=FLT_MAX; ir<nr; ++ir) {
		for (ixz=0; ixz<nxz[ir]; ++ixz) {
			x = xr[ir][ixz];
			z = zr[ir][ixz];
			v = v00+dvdx*x+dvdz*z;
			if (v<vmin) vmin = v;
			t = 2.0*z/v;
			if (t<tminr) tminr = t;
		}
	}

	/* determine maximum reflector segment length */
	tmin = MAX(tmin,MAX(ft,dt));
	dsmax = vmin/(2*ndpfz)*sqrt(tmin/fpeak);
 	
	/* make reflectors */
	makeref(dsmax,nr,ar,nxz,xr,zr,&r);

	/* count reflector segments */
	for (ir=0,ns=0; ir<nr; ++ir)
		ns += r[ir].ns;

	/* make wavelet */
	makericker(fpeak,dt,&w);
	
	/* if requested, print information */
	if (verbose) {
		warn("\nSYNLVCW:");
		warn(
			"Minimum possible reflection time (assuming sources\n"
			"and receivers are at the surface Z=0) is %g s.\n"
			"You may want to adjust the \"minimum time of \n"
			"interest\" parameter.",tminr);
		warn(
			"Total number of small reflecting\n"
			"segments is %d.",ns);
	}
	
	/* set constant segy trace header parameters */
	memset( (void *) &tr, 0, sizeof(segy));
	tr.trid = 1;
	tr.counit = 1;
	tr.ns = nt;
	tr.dt = 1.0e6*dt;
	tr.delrt = 1.0e3*ft;
	
	/* loop over shots or midpoints */
	for (ixsm=0,tracl=0; ixsm<nxsm; ++ixsm) {
	
		/* loop over offsets */
		for (ixo=0; ixo<nxo; ++ixo) {
		
			/* compute source and receiver coordinates */
			if (shots)
				xs = fxs+ixsm*dxs;
			else
				xs = fxm+ixsm*dxm-0.5*xo[ixo];
			zs = 0.0;
			xg = xs+xo[ixo];
			zg = 0.0;
			
			/* set segy trace header parameters */
			tr.tracl = tr.tracr = ++tracl;
			if (shots) {
				tr.fldr = 1+ixsm;
				tr.tracf = 1+ixo;
			} else {
				tr.cdp = 1+ixsm;
				tr.cdpt = 1+ixo;
			}
			tr.offset = NINT(1000.0*(dxsm>0.0?xo[ixo]:-xo[ixo]));
			tr.sx = NINT(1000.0*xs);
			tr.gx = NINT(1000.0*xg);
				
			/* make one trace */
			makeone(v00,dvdx,dvdz,ls,er,ob,sp,w,gamma,
				xs,zs,xg,zg,
				nr,r,nt,dt,ft,tr.data);
			
			/* write trace */
			puttr(&tr);
		}
	}
	return(CWP_Exit());
}
Exemplo n.º 15
0
int
main(int argc, char **argv)
{
	int nt;			/* number of points on input trace	*/
	float dt;		/* sample spacing			*/
	float tmin;		/* time of first sample			*/
	float *vt;		/* velocity function			*/
	float *vrms;		/* rms velocity picks			*/
	float *trms;		/* times corresponding to vrms picks	*/
	cwp_String vfile="";	/* binary file giving vrms(t)		*/
	float *divcor;		/* divergence correction function	*/
	float denom=1.0; 	/* vrms to divide by 			*/

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


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


	/* Determine velocity function v(t) */
	vt = ealloc1float(nt);
	if (!getparstring("vfile", &vfile)) {
		int ntrms = countparval("trms");
		int nvrms = countparval("vrms");
		int npar;
		register int it, itrms;

		if (nvrms != ntrms)
			err("number of trms and vrms must be equal");

		if (!ntrms)  ntrms = 2;  /* default case */
		trms = ealloc1float(ntrms);
		if (!(npar = getparfloat("trms", trms))) {
			trms[0] = 0.0;
			trms[1] = dt;
		}
		if (npar == 1) trms[1] = trms[0] + dt; /* const vel case */
		
		if (!nvrms)  nvrms = 2;  /* default case */
		vrms = ealloc1float(nvrms);
		if (!(npar = getparfloat("vrms", vrms))) {
			vrms[0] = 1500.0;
			vrms[1] = 1500.0;
		}
		if (npar == 1) vrms[1] = vrms[0];  /* const vel case */

		for (itrms = 1; itrms < ntrms; ++itrms)
			if (trms[itrms] <= trms[itrms-1])
				err("trms must increase monotonically");

		for (it = 0; it < nt; ++it) {
			float t = tmin + it*dt;
			intlin(ntrms,trms,vrms,vrms[0],vrms[ntrms-1],
				1,&t,&vt[it]);
		}
		denom = trms[1]*vrms[1]*vrms[1];
		
	} else {  /* user gave a vfile */
		FILE *fp = efopen(vfile, "r");
		
		if (nt != efread(vt, FSIZE, nt, fp)) {
			err("cannot read %d velocities from file %s",
				nt, vfile);
		} else denom = (tmin + dt)*vt[1]*vt[1];
	}

	/* Form divergence correction vector */
	{ register int it;
	  
	  divcor = ealloc1float(nt);
	  for (it = 0; it < nt; ++it) {
	  	float t = tmin + it*dt;
		divcor[it] = t*vt[it]*vt[it] / denom;
	  }
	}
   
	  
	/* Main loop over traces */
	do {
		register int it;

	  	for (it = 0; it < nt; ++it)  tr.data[it] *=  divcor[it];
		puttr(&tr);
	} while (gettr(&tr));

	return(CWP_Exit());
}
Exemplo n.º 16
0
int main (int argc, char **argv)
{
  int n1,n2,n3,n1s,n2s,n3s,n1c,n2c,n3c,i1,i2,i3,i1c,i2c,i3c,
    i1beg,i1end,i2beg,i2end,i3beg,i3end,i1step,i2step,i3step,
    n1tic,n2tic,n3tic,grid1,grid2,grid3,nz,iz,
    verbose,faces,hls,bps,style=SEISMIC,bbox[4],
    legend,ugrid=SOLID,lstyle=VERTLEFT,lz,lbegsup=0,lendsup=0,ln=256,
    lbbox[4];
  float d1,d2,d3,d1s,d2s,d3s,f1,f2,f3,size1,size2,size3,xbox,ybox,angle,
    x1min,x1max,x2min,x2max,x3min,x3max,
    x1beg,x1end,x2beg,x2end,x3beg,x3end,
    d1num,f1num,d2num,f2num,d3num,f3num,
    p1beg,p1end,p2beg,p2end,p3beg,p3end,
    clip,bclip,wclip,perc,bperc,wperc,
    zscale,zoffset,zi,labelsize,titlesize,
    *z,*zfront,*zside,*ztop,*temp,matrix[6],colors[3][2],
    lwidth,lheight,lx,ly,lbeg,lend,
    lmin=(float)FLT_MAX,lmax=(float)-FLT_MAX,
    ldnum,lfnum,ld,lf=0,labmatrix[6];
  unsigned char *czfront,*czside,*cztop,
    *szfront,*szside,*sztop,*czp,
    *data_legend=NULL;
  char *label1="",*label2="",*label3="",*title="",
    *labelfont="Helvetica",*titlefont="Helvetica-Bold",
    *grid1s="none",*grid2s="none",*grid3s="none",
    *titlecolor="black",*axescolor="black",*gridcolor="black",
    *frontf,*sidef,*topf,
    *units="", *legendfont="times_roman10", *lstyles="vertleft",*lgrids="none";
  FILE *infp=stdin,*frontfp,*sidefp,*topfp;
  
  /* initialize getpar */
  initargs(argc,argv);
  requestdoc(1);
  
  /* get parameters describing 1st dimension sampling */
  if (!getparint("n1",&n1)) err("must specify n1!\n");
  if (!getparfloat("d1",&d1)) d1 = 1.0;
  if (!getparfloat("f1",&f1)) f1 = 0.0;
  
  /* get parameters describing 2nd dimension sampling */
  if (!getparint("n2",&n2)) err("must specify n2!\n");
  if (!getparfloat("d2",&d2)) d2 = 1.0;
  if (!getparfloat("f2",&f2)) f2 = 0.0;
  
  /* get parameters describing 3rd dimension sampling */
  if (!getparint("n3",&n3)) err("must specify n3!\n");
  if (!getparfloat("d3",&d3)) d3 = 1.0;
  if (!getparfloat("f3",&f3)) f3 = 0.0;
  
  /* determine input type */
  if (!getparint("faces",&faces)) faces = 0;
  
  /* read color parameters */
  bps = 8;
  hls = 0;
  colors[R][0] = colors[G][0] = colors[B][0] = 0.0;
  colors[R][1] = colors[G][1] = colors[B][1] = 1.0;
  if (countparval("brgb") || countparval("wrgb")) {
    float brgb[3],wrgb[3];
    brgb[R] = brgb[G] = brgb[B] = 0.0;
    wrgb[R] = wrgb[G] = wrgb[B] = 1.0;
    getparfloat("brgb",&brgb[0]);
    getparfloat("wrgb",&wrgb[0]);
    brgb[R] = MAX(0.0,MIN(1.0,brgb[R]));
    wrgb[R] = MAX(0.0,MIN(1.0,wrgb[R]));
    brgb[G] = MAX(0.0,MIN(1.0,brgb[G]));
    wrgb[G] = MAX(0.0,MIN(1.0,wrgb[G]));
    brgb[B] = MAX(0.0,MIN(1.0,brgb[B]));
    wrgb[B] = MAX(0.0,MIN(1.0,wrgb[B]));
    colors[R][0] = brgb[R];  colors[R][1] = wrgb[R];
    colors[G][0] = brgb[G];  colors[G][1] = wrgb[G];
    colors[B][0] = brgb[B];  colors[B][1] = wrgb[B];
		if (!getparint("bps",&bps)) bps = 12;
		if (bps!=12 && bps!=24)
		  err("bps must equal 12 or 24 for color plots!\n");
  } else if (countparval("bhls") || countparval("whls")) {
    float bhls[3],whls[3];
    hls = 1;
    bhls[H] = whls[H] = 0.0;
    bhls[L] = 0.0;  whls[L] = 1.0;
    bhls[S] = whls[S] = 0.0;
    getparfloat("bhls",&bhls[0]);
    getparfloat("whls",&whls[0]);
    bhls[L] = MAX(0.0,MIN(1.0,bhls[L]));
    whls[L] = MAX(0.0,MIN(1.0,whls[L]));
    bhls[S] = MAX(0.0,MIN(1.0,bhls[S]));
    whls[S] = MAX(0.0,MIN(1.0,whls[S]));
    colors[H][0] = bhls[0];  colors[H][1] = whls[0];
    colors[L][0] = bhls[1];  colors[L][1] = whls[1];
    colors[S][0] = bhls[2];  colors[S][1] = whls[2];
    if (!getparint("bps",&bps)) bps = 12;
    if (bps!=12 && bps!=24)
      err("bps must equal 12 or 24 for color plots!\n");
  }
  
  /* allocate space */
  nz = n1*n2+n1*n3+n2*n3;
  z = ealloc1float(nz);
  zfront = z;
  zside = zfront+n1*n2;
  ztop = zside+n1*n3;
  
  /* read data */
  if (getparstring("front",&frontf)
      && getparstring("side",&sidef)
      && getparstring("top",&topf)) {
    
    /* read face files */
    if ((frontfp = fopen(frontf,"r")) == NULL)
      err("error opening front file!\n");
    if (fread(zfront,sizeof(float),n1*n2,frontfp)!=n1*n2)
      err("error reading front file!\n");
    if ((sidefp = fopen(sidef,"r")) == NULL)
      err("error opening side file!\n");
    if (fread(zside,sizeof(float),n1*n3,sidefp)!=n1*n3)
      err("error reading side file!\n");
    if ((topfp = fopen(topf,"r")) == NULL)
      err("error opening top file!\n");
    if (fread(ztop,sizeof(float),n2*n3,topfp)!=n2*n3)
      err("error reading top file!\n");
    
  } else if (getparstring("front",&frontf)
	     || getparstring("side",&sidef)
	     || getparstring("top",&topf)) {
    
    err("must specify all or none of face, side, and top!\n");
    
  } else if (faces) {
    /* read faces from stdin */
    if (fread(zfront,sizeof(float),n1*n2,infp)!=n1*n2)
      err("error reading front from input!\n");
		if (fread(zside,sizeof(float),n1*n3, infp)!=n1*n3)
		  err("error reading side from input!\n");
		if (fread(ztop,sizeof(float),n2*n3, infp)!=n2*n3)
		  err("error reading top from input!\n");
  } else {
    /* read cube from stdin, pick off faces */
    temp = ealloc1float(n1);
    for (i3=0; i3<n3; i3++) {
      for (i2=0; i2<n2; i2++) {
	if (fread(temp,sizeof(float),n1,infp)!=n1)
	  err("error reading cube from input!\n");
	if (i3==0) 
	  for (i1=0; i1<n1; i1++)
	    zfront[i1+i2*n1] = temp[i1];
	if (i2==n2-1)
	  for (i1=0; i1<n1; i1++)
	    zside[i1+i3*n1] = temp[i1];
	ztop[i2+i3*n2] = temp[0];
      }
    }
    free1float(temp);
  }
  
  /* if necessary, determine clips from percentiles */
  if (getparfloat("clip",&clip)) {
    bclip = clip;
    wclip = -clip;
  }
  if ((!getparfloat("bclip",&bclip) || !getparfloat("wclip",&wclip)) &&
      !getparfloat("clip",&clip)) {
    perc = 100.0;  getparfloat("perc",&perc);
    temp = ealloc1float(nz);
    for (iz=0; iz<nz; iz++)
      temp[iz] = z[iz];
    if (!getparfloat("bclip",&bclip)) {
      bperc = perc;	getparfloat("bperc",&bperc);
      iz = (nz*bperc/100.0);
      if (iz<0) iz = 0;
      if (iz>nz-1) iz = nz-1;
      qkfind(iz,nz,temp);
      bclip = temp[iz];
    }
    if (!getparfloat("wclip",&wclip)) {
      wperc = 100.0-perc;  getparfloat("wperc",&wperc);
      iz = (nz*wperc/100.0);
      if (iz<0) iz = 0;
      if (iz>nz-1) iz = nz-1;
      qkfind(iz,nz,temp);
      wclip = temp[iz];
    }
    free1float(temp);
  }
  if (!getparint("verbose",&verbose)) verbose = 1;
  if (verbose) warn("bclip=%g wclip=%g",bclip,wclip);
  
  /* get scaled sampling intervals */
  if (!getparfloat("d1s",&d1s)) d1s = 1.0;
  if (!getparfloat("d2s",&d2s)) d2s = 1.0;
  if (!getparfloat("d3s",&d3s)) d3s = 1.0;
  d1s = fabs(d1s);  d1s *= d1;
  d2s = fabs(d2s);  d2s *= d2;
  d3s = fabs(d3s);  d3s *= d3;
  
  /* get projection angle, convert to radians */
  if(!getparfloat("angle",&angle)) angle = 45.0;
  angle = MAX(angle,0.00001);
  angle = MIN(angle,90.0);
  angle *= PI/180.0;
  
  /* get axes parameters */
  if(!getparfloat("size1",&size1)) size1 = 4.0;
  if(!getparfloat("size2",&size2)) size2 = 4.0;
  if(!getparfloat("size3",&size3)) size3 = 3.0;
  if (!getparfloat("xbox",&xbox)) xbox = 1.5;
  if (!getparfloat("ybox",&ybox)) ybox = 1.5;
 
  /* compute extreme values */
  x1min = (d1>0.0)?f1:f1+(n1-1)*d1;
  x1max = (d1<0.0)?f1:f1+(n1-1)*d1;
  x2min = (d2>0.0)?f2:f2+(n2-1)*d2;
  x2max = (d2<0.0)?f2:f2+(n2-1)*d2;
  x3min = (d3>0.0)?f3:f3+(n3-1)*d3;
  x3max = (d3<0.0)?f3:f3+(n3-1)*d3;
  
  /* get axis1 parameters */
  x1beg = x1min;
  x1end = x1max; getparfloat("x1end",&x1end);
  d1num = 0.0; getparfloat("d1num",&d1num);
  f1num = x1min; getparfloat("f1num",&f1num);
  n1tic = 1; getparint("n1tic",&n1tic);
  getparstring("grid1",&grid1s);
  if (STREQ("dot",grid1s)) grid1 = DOT;
  else if (STREQ("dash",grid1s)) grid1 = DASH;
  else if (STREQ("solid",grid1s)) grid1 = SOLID;
  else grid1 = NONE;
  getparstring("label1",&label1);
  
  /* get axis2 parameters */
  x2beg = x2min; getparfloat("x2beg",&x2beg);
  x2end = x2max; 
  d2num = 0.0; getparfloat("d2num",&d2num);
  f2num = x2min; getparfloat("f2num",&f2num);
  n2tic = 1; getparint("n2tic",&n2tic);
  getparstring("grid2",&grid2s);
  if (STREQ("dot",grid2s)) grid2 = DOT;
  else if (STREQ("dash",grid2s)) grid2 = DASH;
  else if (STREQ("solid",grid2s)) grid2 = SOLID;
  else grid2 = NONE;
  getparstring("label2",&label2);
  
  /* get axis3 parameters */
  x3beg = x3min; 
  x3end = x3max; getparfloat("x3end",&x3end);
  d3num = 0.0; getparfloat("d3num",&d3num);
  f3num = x3min; getparfloat("f3num",&f3num);
  n3tic = 1; getparint("n3tic",&n3tic);
  getparstring("grid3",&grid3s);
  if (STREQ("dot",grid3s)) grid3 = DOT;
  else if (STREQ("dash",grid3s)) grid3 = DASH;
  else if (STREQ("solid",grid3s)) grid3 = SOLID;
  else grid3 = NONE;
  getparstring("label3",&label3);
  
  /* get additional font parameters */
  getparstring("labelfont",&labelfont);
  labelsize = 18.0; getparfloat("labelsize",&labelsize);
  getparstring("title",&title);
  getparstring("titlefont",&titlefont);
  titlesize = 24.0; getparfloat("titlesize",&titlesize);
  getparstring("titlecolor",&titlecolor);
  getparstring("axescolor",&axescolor);
  getparstring("gridcolor",&gridcolor);
  style = SEISMIC;
  
 
  /* adjust x1beg and x1end to fall on sampled values */
  i1beg = NINT((x1beg-f1)/d1);
  i1beg = MAX(0,MIN(n1,i1beg));
  x1beg = f1+i1beg*d1;
  i1end = NINT((x1end-f1)/d1);
  i1end = MAX(0,MIN(n1-1,i1end));
  x1end = f1+i1end*d1;
  
  /* adjust x2beg and x2end to fall on sampled values */
  i2beg = NINT((x2beg-f2)/d2);
  i2beg = MAX(0,MIN(n2-1,i2beg));
  x2beg = f2+i2beg*d2;
  i2end = NINT((x2end-f2)/d2);
  i2end = MAX(0,MIN(n2-1,i2end));
  x2end = f2+i2end*d2;
  
  /* adjust x3beg and x3end to fall on sampled values */
  i3beg = NINT((x3beg-f3)/d3);
  i3beg = MAX(0,MIN(n3-1,i3beg));
  x3beg = f3+i3beg*d3;
  i3end = NINT((x3end-f3)/d3);
  i3end = MAX(0,MIN(n3-1,i3end));
  x3end = f3+i3end*d3;

  /* allocate space for image bytes */
  n1c = 1+abs(i1end-i1beg);
  n2c = 1+abs(i2end-i2beg);
  n3c = 1+abs(i3end-i3beg);
  czfront = ealloc1(n1c*n2c,sizeof(char));
  czside = ealloc1(n1c*n3c,sizeof(char));
  cztop = ealloc1(n2c*n3c,sizeof(char));
  
  /* compute conversion constants */
  zscale = (wclip!=bclip)?255.0/(wclip-bclip):1.0e10;
  zoffset = -bclip*zscale;
  i1step = (i1end>i1beg)?1:-1;
  i2step = (i2end>i2beg)?1:-1;
  i3step = (i3end>i3beg)?1:-1;
  
  /* convert front data to be imaged into unsigned characters */
  czp = czfront;
  for (i2c=0,i2=i2beg; i2c<n2c; i2c++,i2+=i2step) {
    for (i1c=0,i1=i1beg; i1c<n1c; i1c++,i1+=i1step) {
      zi = zoffset+zfront[i1+i2*n1]*zscale;
      if (zi<0.0) zi = 0.0;
      if (zi>255.0) zi = 255.0;
      *czp++ = (unsigned char)zi;
    }
  }
  
  /* convert side data to be imaged into unsigned characters */
  czp = czside;
  for (i3c=0,i3=i3beg; i3c<n3c; i3c++,i3+=i3step) {
    for (i1c=0,i1=i1beg; i1c<n1c; i1c++,i1+=i1step) {
      zi = zoffset+zside[i1+i3*n1]*zscale;
      if (zi<0.0) zi = 0.0;
      if (zi>255.0) zi = 255.0;
      *czp++ = (unsigned char)zi;
    }
  }

  /* convert top data to be imaged into unsigned characters */
  czp = cztop;
  for (i3c=0,i3=i3beg; i3c<n3c; i3c++,i3+=i3step) {
    for (i2c=0,i2=i2beg; i2c<n2c; i2c++,i2+=i2step) {
      zi = zoffset+ztop[i2+i3*n2]*zscale;
      if (zi<0.0) zi = 0.0;
      if (zi>255.0) zi = 255.0;
      *czp++ = (unsigned char)zi;
    }
  }
  free1float(z);
  
  /* determine sampling after scaling */
  n1s = MAX(1,NINT(1+(n1c-1)*d1/d1s));
  d1s = (n1s>1)?d1*(n1c-1)/(n1s-1):d1;
  n2s = MAX(1,NINT(1+(n2c-1)*d2/d2s));
  d2s = (n2s>1)?d2*(n2c-1)/(n2s-1):d2;
  n3s = MAX(1,NINT(1+(n3c-1)*d3/d3s));
  d3s = (n3s>1)?d3*(n3c-1)/(n3s-1):d3;
  
  /* if necessary, interpolate front to scaled sampling intervals */
  if (n1s!=n1c || n2s!=n2c) {
    szfront = ealloc1(n1s*n2s,sizeof(char));
    intl2b(n1c,d1,0.0,n2c,d2,0.0,czfront,
	   n1s,d1s,0.0,n2s,d2s,0.0,szfront);
    free1(czfront);
  } else {
    szfront = czfront;
  }
  
  /* if necessary, interpolate side to scaled sampling intervals */
  if (n1s!=n1c || n3s!=n3c) {
    szside = ealloc1(n1s*n3s,sizeof(char));
    intl2b(n1c,d1,0.0,n3c,d3,0.0,czside,
	   n1s,d1s,0.0,n3s,d3s,0.0,szside);
    free1(czside);
  } else {
    szside = czside;
  }
  
  /* if necessary, interpolate top to scaled sampling intervals */
  if (n2s!=n2c || n3s!=n3c) {
    sztop = ealloc1(n2s*n3s,sizeof(char));
    intl2b(n2c,d2,0.0,n3c,d3,0.0,cztop,
	   n2s,d2s,0.0,n3s,d3s,0.0,sztop);
    free1(cztop);
  } else {
    sztop = cztop;
  }
  
  /* determine axes pads */
  p1beg = (x1end>x1beg)?-fabs(d1s)/2:fabs(d1s)/2;
  p1end = (x1end>x1beg)?fabs(d1s)/2:-fabs(d1s)/2;
  p2beg = (x2end>x2beg)?-fabs(d2s)/2:fabs(d2s)/2;
  p2end = (x2end>x2beg)?fabs(d2s)/2:-fabs(d2s)/2;
  p3beg = (x3end>x3beg)?-fabs(d3s)/2:fabs(d3s)/2;
  p3end = (x3end>x3beg)?fabs(d3s)/2:-fabs(d3s)/2;
  
  /* get legend specs BEREND, Schoenfelder */
  legend = 0; getparint("legend", &legend); /* BEREND, Schoenfelder */
  getparstring("units", &units); /* BEREND, Schoenfelder */
  getparstring("legendfont", &legendfont);     /* BEREND, Schoenfelder */
  
  /* Get or calc legend parameters */
  /* Legend min and max: Calc from data read in */
  if (legend) {
    for (lz=0;lz<nz;lz++) {
      lmin=FMIN(lmin,z[lz]);
      lmax=FMAX(lmax,z[lz]);
    }
    if (verbose==2) warn("lmin=%g lmax=%g",lmin,lmax);
  
    lbeg = lmin; if (getparfloat("lbeg",&lbeg)) lbegsup=1;
    lend = lmax; if (getparfloat("lend",&lend)) lendsup=1;
    /* Change wclip,bclip to be inside legend range */
    wclip = FMAX(lbeg,wclip); /* [wclip,bclip] has to be in [lbeg,lend] */
    bclip = FMIN(lend,bclip);
    if (lbegsup!=1) { /* Add white and black areas to show possible clipping */ 
      float rangeperc=(bclip-wclip)/20.;
      lbeg=wclip-rangeperc;
    }
    if (lendsup!=1) {
      float rangeperc=(bclip-wclip)/20.;
      lend=bclip+rangeperc;
    }
    
    lfnum = lmin; getparfloat("lfnum",&lfnum);
    
    getparstring("lstyle",&lstyles);
    if (STREQ("vertright",lstyles))
      lstyle = VERTRIGHT;
    else if (STREQ("horibottom",lstyles))
      lstyle = HORIBOTTOM;
    /* legend dimensions (BEREND), Schoenfelder */
    lwidth = 0.1 ;lheight = size1+sin(angle)*size3/2;
    if (lstyle==HORIBOTTOM) {
      lwidth=size2+cos(angle)*size3/1.2 ;lheight = 0.24;
    }
    getparfloat("lwidth",&lwidth);
    getparfloat("lheight",&lheight);
    
    lx=.8;ly = ybox+(size1+sin(angle)*size3-lheight)/2;
    if (lstyle==VERTRIGHT) {
      lx=xbox+size2+cos(angle)*size3+0.1;
    } else if (lstyle==HORIBOTTOM) {
      lx=xbox+(size2+cos(angle)*size3-lwidth)/2.0;ly = 1.0;
    }
    getparfloat("lx",&lx);
    getparfloat("ly",&ly);
    
    getparstring("lgrid",&lgrids);
    if (STREQ("dot",lgrids))
      ugrid = DOT;
    else if (STREQ("dash",lgrids))
      ugrid = DASH;
    else if (STREQ("solid",lgrids))
      ugrid = SOLID;
    else
      ugrid = NONE;
  }
  

  if (legend) {
    /* Make legend color values */
    int lll=0,lcount,perc5=13,ilbeg,ilend; /* color scale */
    if (lbegsup!=1) {
      ln+=perc5; /* white area */
    }
    if (lendsup!=1) {
      ln+=perc5; /* black area */
    }
    data_legend = ealloc1(ln,sizeof(char));
    if (lbegsup!=1) {
      for (lll=0;lll<perc5;lll++) data_legend[lll]=(char) 255; /* white area */
    }
    for (lcount=255;lcount>=0;lcount--,lll++) data_legend[lll]=(char) lcount;
    if (lendsup!=1) {
      for (;lll<ln;lll++) data_legend[lll]=(char) 0; /* black area */
    }
    lf=lbeg;ld=(lend-lbeg)/(ln-1);
    if (!(getparfloat("ldnum",&ldnum)))	ldnum=0.0;
    
    /* adjust lbeg and lend to fall on sampled values */
    
    ilbeg = NINT((lbeg-lf)/ld);
    ilbeg = MAX(0,MIN(ln-1,ilbeg));
    lbeg = lf+ilbeg*ld;
    ilend = NINT((lend-lf)/ld);
    ilend = MAX(0,MIN(ln-1,ilend));
    lend = lf+ilend*ld;

    /* convert legend parameters to points */  
    lx *= 72.0; /* Schoenfelder */
    ly *= 72.0; /* Schoenfelder */
    lwidth *= 72.0; /* Schoenfelder */
    lheight *= 72.0; /* Schoenfelder */
  }

  /* convert axes parameters to points */  
  size1 *= 72;
  size2 *= 72;
  size3 *= 72;
  xbox *= 72;
  ybox *= 72;
  
  /* set bounding box */
  psAxesBBox(xbox,ybox,size2+cos(angle)*size3,size1+sin(angle)*size3,
	     labelfont,labelsize,titlefont,titlesize,style,bbox);
  if (legend) {
    psLegendBBox( /* Space for legend Schoenfelder */
		 lx,ly,lwidth,lheight,
		 labelfont,labelsize,
		 lstyle,lbbox);
    /* Include space for legend Schoenfelder */
    bbox[0]=MIN(bbox[0],lbbox[0]);
    bbox[1]=MIN(bbox[1],lbbox[1]);
    bbox[2]=MAX(bbox[2],lbbox[2]);
    bbox[3]=MAX(bbox[3],lbbox[3]);
  }
  boundingbox(bbox[0],bbox[1],bbox[2],bbox[3]);
  
  /* begin PostScript */
  begineps();
  
  /* save graphics state */
  gsave();
  
  /* translate coordinate system by box offset */
  translate(xbox,ybox);
  
  /* begin front */
  gsave();
  
  /* transform coordinates */
  translate(0,0);
  scale(size2,size1);
  
  /* determine image matrix */
  matrix[0] = 0;  matrix[1] = n2s;  matrix[2] = -n1s;
  matrix[3] = 0;  matrix[4] = n1s;  matrix[5] = 0;
  
  /* draw the image */
  drawimage(hls,colors,n1s,n2s,bps,matrix,szfront);
  
  /* end front */
  grestore();
  
  /* begin side */
  gsave();
  
  /* transform and skew coordinates */
  matrix[0] = 1;  matrix[1] = tan(angle);  matrix[2] = 0;
  matrix[3] = 1;  matrix[4] = 0;  matrix[5] = 0;
  translate(size2,0);
  concat(matrix);
  scale(size3*cos(angle),size1);
  
  /* determine image matrix */
  matrix[0] = 0;  matrix[1] = n3s;  matrix[2] = -n1s;
  matrix[3] = 0;  matrix[4] = n1s;  matrix[5] = 0;
  
  /* draw the image */
  drawimage(hls,colors,n1s,n3s,bps,matrix,szside);
  
  /* end side */
  grestore();
  
  /* begin top */
  gsave();
  
  
  /* transform and skew coordinates */
  matrix[0] = 1;  matrix[1] = 0;  matrix[2] = 1.0/tan(angle);
  matrix[3] = 1;  matrix[4] = 0;  matrix[5] = 0;
  translate(0,size1);
  concat(matrix);
  scale(size2,size3*sin(angle));
  
  /* determine image matrix */
  matrix[0] = n2s;  matrix[1] = 0;  matrix[2] = 0;
  matrix[3] = n3s;  matrix[4] = 0;  matrix[5] = 0;
  
  /* draw the image */
  drawimage(hls,colors,n2s,n3s,bps,matrix,sztop);
  
  /* end top */
  grestore();
  
  if (legend) {
    gsave();
  /* translate coordinate system by box offset */
  translate(-xbox,-ybox);
    translate(lx,ly);
    scale(lwidth,lheight);
    if ((lstyle==VERTLEFT) || (lstyle==VERTRIGHT)) {
      labmatrix[0] = 1;	 labmatrix[1] = 0;  labmatrix[2] = 0;
      labmatrix[3] = ln; labmatrix[4] = 0;  labmatrix[5] = 0;
      drawimage(hls,colors,1,ln,bps,labmatrix,data_legend);
    } else {
      labmatrix[0] = -1; labmatrix[1] = 0;  labmatrix[2] = 0;
      labmatrix[3] = ln; labmatrix[4] = 0;  labmatrix[5] = 0;
      rotate(-90);
      drawimage(hls,colors,1,ln,bps,labmatrix,data_legend);
      rotate(90);
    }
    grestore();
  }
  /* restore graphics state */
  grestore();
  
  psCubeAxesBox(xbox,ybox,size1,size2,size3,angle,
		x1beg,x1end,p1beg,p1end,
		d1num,f1num,n1tic,grid1,label1,
		x2beg,x2end,p2beg,p2end,
		d2num,f2num,n2tic,grid2,label2,
		x3beg,x3end,p3beg,p3end,
		d3num,f3num,n3tic,grid3,label3,
		labelfont,labelsize,
		title,titlefont,titlesize,
		titlecolor,axescolor,gridcolor);
  
	/* draw axes and title for legend Schoenfelder*/
	if (legend) {
	  float lpbeg,lpend;
	  int lntic=1;
	  gsave();
	  lpbeg = 0.0; /*(lend>lbeg)?-fabs(d1s)/2:fabs(d1s)/2;*/
	  lpend = 0.0; /*(lend>lbeg)?fabs(d1s)/2:-fabs(d1s)/2;*/
  
	  psLegendBox(
		    lx,ly,lwidth,lheight,
		    lbeg,lend,lpbeg,lpend,
		    ldnum,lf,lntic,ugrid,units,
		    labelfont,labelsize,
		    axescolor,gridcolor,
		    lstyle);
	  grestore();
	}
  /* end PostScript */
  showpage();
  endeps();
  
  return 0;
}
Exemplo n.º 17
0
int main(int argc, char **argv)
{
	usghed usghin, usghtop, usghbot, usghlayer;
	usghed usghvtop, usghvbot, usghglayer;
	FILE *infp,*outfp,*topfp,*botfp,*layerfp;
	FILE *vtopfp,*vbotfp,*glayerfp;
	char *infile,*outfile,*layertop, *layerbot;
	char *gtopgrid, *gbotgrid;
	char *layers, *glayers;
	int ibot, itop;
	int ierr;
	int nz, iz;
	float *dzrl, sm2top, sm2bot, sm3top, sm3bot;
	float gabovetop, gbelowbot;
	int igabovetop, igbelowbot;
	float g0, r0;
	int ginterp=0;

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

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

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

	int nlayer, nglayer;


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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

		}
	}

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

	ierr = fputusghdr(outfp,&usghin);
	
	free(ztop);
	free(zbot);
	free(vtop);
	free(vbot);
	free(zs);
	free(vs);
	free(work);
	free(grid);
	exit(0);
}
Exemplo n.º 18
0
int
main (int argc, char **argv)
{
	int n1,n2,n3,nbpe,perm,i1,i2,i3,verbose;
	char *v=NULL;
	char *tempstem=NULL, **tempdirs=NULL;
	int ntempdirs;
	char tmpstem[] = "foo";
	char tmpdir[] = "/tmp";
	FILE *infp=stdin,*outfp=stdout;
	VND *handle;
	long N[3] ;
	long key[3] ;

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

	/* get parameters */
	if (!getparint("n1",&n1)) err("must specify n1!");
	if (!getparint("n2",&n2)) err("must specify n2!");
	ntempdirs = countparval("scratchdir");
	if(ntempdirs > 0) {
		tempdirs = (char **) ealloc1(ntempdirs, sizeof(char *));
		getparstringarray("scratchdir",tempdirs);
	} else  {
		ntempdirs = 1;
		tempdirs = (char **) ealloc1(ntempdirs, sizeof(char *));
		strcpy(tempdirs[0],tmpdir);
	}
	if (!getparstring("scratchstem",&tempstem))
		tempstem = &tmpstem[0];
	if (!getparint("nbpe",&nbpe)) nbpe = sizeof(float);
	if (!getparint("perm",&perm)) perm = 231; /* trace to time slice */
	if (!getparint("n3",&n3)) {
		if (efseeko(infp,(off_t) 0,SEEK_END)==-1)
			err("input file size unknown; specify n3\n");
		n3 = (int) (eftello(infp)/(((off_t)n1)*((off_t)n2)*((off_t)nbpe)));
		efseeko(infp, (off_t) 0,SEEK_SET);
	}
	verbose = 0;  getparint("verbose",&verbose);
	if (verbose) warn("n1=%d  n2=%d n3=%d nbpe=%d perm=%d\n",n1,n2,n3,nbpe,perm);

	/* allocate space for a single vector in any dimension */
	v = ealloc1((n1+n2+n3),nbpe);

	/* allocate big matrix state */
	N[0] = n1; N[1] = n2; N[2] = n3;
	handle = VNDop(2,200000000,3,N,1,nbpe,tempstem,ntempdirs,tempdirs,1);

	/* put vectors along 1st dimension to big matrix */
	if (verbose) warn("Reading input file");
	for (i3=0; i3<n3; i3++) {
	for (i2=0; i2<n2; i2++) {
		if (fread(v,1,nbpe*n1,infp)!=nbpe*n1)
			err("Error reading input file:  i2=%d\n",i2);
		key[0] = 0; key[1] = i2; key[2] = i3;
		VNDrw('w',0,handle,0,key,0,v,0,1,n1,21,NULL);
	}
	}

	/* get vectors along 2nd dimension from big matrix */
	if (verbose) warn("Writing output file");
	switch(perm) {

	case 123:
		for (i3=0; i3<n3; i3++) {
		for (i2=0; i2<n2; i2++) {
			key[0] = 0; key[1] = i2; key[2] = i3;
			VNDrw('r',0,handle,0,key,0,v,0,1,n1,123,NULL);
		if (fwrite(v,1,nbpe*n1,outfp)!=nbpe*n1)
			err("Error writing output file:  i2=%d i3=%d",i2,i3);
		}
		}
		break;

	case 132:
		for (i2=0; i2<n2; i2++) {
		for (i3=0; i3<n3; i3++) {
			key[0] = 0; key[1] = i2; key[2] = i3;
			VNDrw('r',0,handle,0,key,0,v,0,1,n1,132,NULL);
		if (fwrite(v,1,nbpe*n1,outfp)!=nbpe*n1)
			err("Error writing output file:  i2=%d i3=%d",i2,i3);
		}
		}
		break;

	case 213:
		for (i3=0; i3<n3; i3++) {
		for (i1=0; i1<n1; i1++) {
			key[0] = i1; key[1] = 0; key[2] = i3;
			VNDrw('r',0,handle,1,key,0,v,0,1,n2,213,NULL);
		if (fwrite(v,1,nbpe*n2,outfp)!=nbpe*n2)
			err("Error writing output file:  i1=%d i3=%d",i1,i3);
		}
		}
		break;

	case 231:
		for (i1=0; i1<n1; i1++) {
		for (i3=0; i3<n3; i3++) {
			key[0] = i1; key[1] = 0; key[2] = i3;
			VNDrw('r',0,handle,1,key,0,v,0,1,n2,231,NULL);
		if (fwrite(v,1,nbpe*n2,outfp)!=nbpe*n2)
			err("Error writing output file:  i1=%d i3=%d",i1,i3);
		}
		}
		break;

	case 312:
		for (i2=0; i2<n2; i2++) {
		for (i1=0; i1<n1; i1++) {
			key[0] = i1; key[1] = i2; key[2] = 0;
			VNDrw('r',0,handle,2,key,0,v,0,1,n3,312,NULL);
		if (fwrite(v,1,nbpe*n3,outfp)!=nbpe*n3)
			err("Error writing output file:  i1=%d i2=%d",i1,i2);
		}
		}
		break;

	case 321:
		for (i1=0; i1<n1; i1++) {
		for (i2=0; i2<n2; i2++) {
			key[0] = i1; key[1] = i2; key[2] = 0;
			VNDrw('r',0,handle,2,key,0,v,0,1,n3,321,NULL);
		if (fwrite(v,1,nbpe*n3,outfp)!=nbpe*n3)
			err("Error writing output file:  i1=%d i2=%d",i1,i2);
		}
		}
		break;

	default:
		err("Unrecognized transpose permutation %d",perm);
	}

	/* free big matrix state */
	VNDcl(handle,1);
	if (verbose) warn("Transpose done!");

	return(CWP_Exit());
}
Exemplo n.º 19
0
int
main(int argc, char **argv)
{
	float phase;		/* phase shift = phasefac*PI		*/
	float power;		/* phase shift = phasefac*PI		*/
	register float *rt;	/* real trace				*/
	register complex *ct;	/* complex transformed trace		*/
	complex *filt;		/* complex power	 		*/
	int nt;			/* number of points on input trace	*/
	size_t ntsize;		/* nt in bytes				*/
	int ncdp;               /* number of cdps specified */
	int icdp;       	/* index into cdp array */

	long oldoffset;         /* offset of previous trace */
        long oldcdp;    	/* cdp of previous trace */
        int newsloth;   	/* if non-zero, new sloth function was computed */
	int jcdp;       	/* index into cdp array */
	float dt;		/* sample spacing (secs) on input trace	*/
	float tn;		/* sample spacing (secs) on input trace	*/
	float omega;		/* circular frequency			*/
	float domega;		/* circular frequency spacing (from dt)	*/
	int nfft;		/* number of points in nfft		*/
	int ntnmo;      	/* number of tnmos specified            */
	float *cdp;     	/* array[ncdp] of cdps */

	float *vnmo;   		/* array[nvnmo] of vnmos               */
	float *ovvt;   		/* array[nvnmo] of vnmos               */
	int nvnmo;      	/* number of tnmos specified            */
	float *fnmo;   		 /* array[ntnmo] of tnmos               */
	float **ovv;   		 /* array[nf] of fnmos                  */
	float doffs;             /* offset                            */
	float acdp;     	/* temporary used to sort cdp array */
        float *aovv;    	/* temporary used to sort ovv array */

        int invert;              /*  if non-zero, do invers DLMO       */
        int cm;                  /*  if non-zero, the offset in cm     */
        int nf;                 /* number of frequencies (incl Nyq)     */
        int it;                 /* number of frequencies (incl Nyq)     */
	float onfft;		/* 1 / nfft				*/
	float v;                 /* velocity                            */
	size_t nzeros;		/* number of padded zeroes in bytes	*/
	
	
	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);

	/* Set parameters */
	power=0.0;

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

	nt = tr.ns;

	if (!getparfloat("dt", &dt))	dt = ((double) tr.dt)/1000000.0;
	if (!dt)	err("dt field is zero and not getparred");
	ntsize = nt * FSIZE;

        if (!getparint("invert",&invert)) invert = 0;
        if (!getparint("cm",&cm)) cm = 0;

	/* Set up for fft */
	nfft = npfaro(nt, LOOKFAC * nt);
	if (nfft >= SU_NFLTS || nfft >= PFA_MAX)
		err("Padded nt=%d -- too big", nfft);

        nf = nfft/2 + 1;
        onfft = 1.0 / nfft;
	nzeros = (nfft - nt) * FSIZE;
	domega = TWOPI * onfft / dt;


	/* get velocity functions, linearly interpolated in frequency */

	ncdp = countparval("cdp");

	if (ncdp>0) {
                if (countparname("vnmo")!=ncdp)
                        err("a vnmo array must be specified for each cdp");
                if (countparname("fnmo")!=ncdp)
                        err("a tnmo array must be specified for each cdp");
        } else {
                ncdp = 1;
                if (countparname("vnmo")>1)
                        err("only one (or no) vnmo array must be specified");
                if (countparname("fnmo")>1)
                        err("only one (or no) tnmo array must be specified");
        }

	cdp = ealloc1float(ncdp);
        if (!getparfloat("cdp",cdp)) cdp[0] = tr.cdp;
        ovv = ealloc2float(nf,ncdp);

	for (icdp=0; icdp<ncdp; ++icdp) {
                nvnmo = countnparval(icdp+1,"vnmo");
                ntnmo = countnparval(icdp+1,"fnmo");
                if (nvnmo!=ntnmo && !(ncdp==1 && nvnmo==1 && ntnmo==0))
                        err("number of vnmo and tnmo values must be equal");
                if (nvnmo==0) nvnmo = 1;
                if (ntnmo==0) ntnmo = nvnmo;
                /* equal numbers of parameters vnmo, fnmo  */

                vnmo = ealloc1float(nvnmo);
                fnmo = ealloc1float(nvnmo);

                if (!getnparfloat(icdp+1,"vnmo",vnmo)) vnmo[0] = 400.0;
                if (!getnparfloat(icdp+1,"fnmo",fnmo)) fnmo[0] = 0.0;
		

		for (it=0; it<ntnmo; ++it)
			fnmo[it]*=TWOPI;

                for (it=1; it<ntnmo; ++it)
                        if (fnmo[it]<=fnmo[it-1])
                                err("tnmo values must increase monotonically");

		for (it=0,tn=0; it<nf; ++it,tn+=domega) {
			intlin(ntnmo,fnmo,vnmo,vnmo[0],vnmo[nvnmo-1],1,&tn,&v);
			ovv[icdp][it] = 1.0/(v); 
		}
                free1float(vnmo);
                free1float(fnmo);
        }



/* sort (by insertion) sloth and anis functions by increasing cdp */

        for (jcdp=1; jcdp<ncdp; ++jcdp) {
                acdp = cdp[jcdp];
                aovv = ovv[jcdp];
                for (icdp=jcdp-1; icdp>=0 && cdp[icdp]>acdp; --icdp) {
                        cdp[icdp+1] = cdp[icdp];
                        ovv[icdp+1] = ovv[icdp];
                }
                cdp[icdp+1] = acdp;
                ovv[icdp+1] = aovv;
        }

/* allocate workspace */


        ovvt = ealloc1float(nf);

/* interpolate sloth and anis function for first trace */

        interpovv(nf,ncdp,cdp,ovv,(float)tr.cdp,ovvt);

        /* set old cdp and old offset for first trace */
        oldcdp = tr.cdp;
        oldoffset = tr.offset-1;



	/* Allocate fft arrays */
	rt   = ealloc1float(nfft);
	ct   = ealloc1complex(nf);
	filt = ealloc1complex(nf);


		

	/* Loop over traces */
	do {

		/* if necessary, compute new sloth and anis function */
                	if (tr.cdp!=oldcdp && ncdp>1) {
                        interpovv(nt,ncdp,cdp,ovv,(float)tr.cdp,
                                  ovvt);
                        newsloth = 1;
                } else {
                        newsloth = 0;
                }

		/* if sloth and anis function or offset has changed */

                if (newsloth || tr.offset!=oldoffset) {

		doffs = (fabs)((float)(tr.offset));
		if (cm==1) doffs/=100;
		/* Load trace into rt (zero-padded) */
		memcpy( (void *) rt, (const void *) tr.data, ntsize);
		memset((void *) (rt + nt), (int) '\0', nzeros);

		/* FFT */
		pfarc(1, nfft, rt, ct);


		/* Apply filter */
		{ register int i;
		for (i = 0; i < nf; ++i){
			omega = i * domega;
			if (power < 0 && i == 0) omega = FLT_MAX;
			if (invert==0)
			phase = -1.0*omega*ovvt[i]*doffs;
			else
			phase = 1.0*omega*ovvt[i]*doffs;
			
		/*	filt[i] = cmplx(cos(phase),sin(phase)); */
			filt[i] = cwp_cexp(crmul(I,phase)); 
			filt[i] = crmul(filt[i], onfft);
			ct[i] = cmul(ct[i], filt[i]);
			
			}
		}
	  }
		/* Invert */
		pfacr(-1, nfft, ct, rt);


		/* Load traces back in, recall filter had nfft factor */
		{ register int i;
		for (i = 0; i < nt; ++i)  tr.data[i] = rt[i];
		}


		puttr(&tr);

	} while (gettr(&tr));


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


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


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


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

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

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

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

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

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


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


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

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

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


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


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

	return(CWP_Exit());
}
Exemplo n.º 21
0
int main (int argc, char **argv)
{
	int nt,it,np,ntau,itau,nx,ix,nk,nkmax,ik,
		ntfft,nxfft,nv,trans,norm,conv,verbose;
	float dt,dx,dpx,k,dk,kscl,t,*tt,*vt,*tmig,*vmig,
		(*vsind)[4],**ptx,**divcor;
	complex **ptk;
	char *vfile="";
	FILE *hfp,*tfp;
	
	/* hook up getpar */
	initargs(argc,argv);
	requestdoc(1);

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

	/* get parameters */
	if (!getparfloat("dxcdp",&dx)) err("dxcdp required");
	if (!getparint("np",&np)) np=50;
	if (!getparint("trans",&trans)) trans=0;
	if (!getparint("norm",&norm)) norm=1;
	if (!getparint("conv",&conv)) conv=0;
	if (!getparint("verbose",&verbose)) verbose=0;

	/* get velocity function */
	vt=ealloc1float(nt);
	tt=ealloc1float(nt);
	for (it=0; it<nt; it++)
		tt[it]=it*dt;
	if (!getparstring ("vfile",&vfile)){
		ntau = countparval("tmig");

		if (ntau==0) ntau=1;
		tmig = ealloc1float(ntau);

		if (!getparfloat("tmig",tmig)) tmig[0] = 0.0;

		nv = countparval("vmig");

		if (nv==0) nv=1;

		if (nv!=ntau) 
			err("number of tmig and vmig must be equal");

		vmig = ealloc1float(nv);

		if (!getparfloat("vmig",vmig)) vmig[0] = 1500.0;
		for (itau=1; itau<ntau; itau++)
			if (tmig[itau]<=tmig[itau-1])
			    err("tmig must increase monotonically");
		for (it=0,t=0.0; it<nt; ++it,t+=dt)
			intlin(ntau,tmig,vmig,vmig[0],vmig[ntau-1],
				1,&t,&vt[it]);
		if (ntau!=nt){
			vsind = (float (*)[4])ealloc1float(ntau*4);
			cmonot(ntau,tmig,vmig,vsind);
			intcub(0,ntau,tmig,vsind,nt,tt,vt);
		}
	} else{
		if (fread(vt,sizeof(float),nt,fopen(vfile,"r"))!=nt)
			err("Not %d velocities in file %s",nt,vfile);
	}

	/* copy traces and headers to temporary files */
	tfp = tmpfile();
	hfp = tmpfile();
	nx = 0;
	do {
		nx++;
		fwrite(&tr,HDRBYTES,1,hfp);
		fwrite(tr.data,sizeof(float),nt,tfp);

	} while(gettr(&tr));
  	fseek(hfp,0L,SEEK_SET);
	fseek(tfp,0L,SEEK_SET);
	if (verbose) fprintf(stderr,"\t%d traces input\n",nx);

	/* determine wavenumber and frequency sampling */
	nxfft = npfar(nx);
	ntfft = npfa(nt);
	nk = nxfft/2+1;
	dx *= 0.001;
	dk = 2.0*PI/(nxfft*dx);

	/* allocate space for Fourier transform */
	ptk = ealloc2complex(nt,nk);
	ptx = ealloc1(nxfft,sizeof(float*));
	for (ix=0; ix<nxfft; ++ix)
		ptx[ix] = (float*)ptk[0]+ix*nt;

	/* allocate space for divergence correction */
	divcor=ealloc2float(nt,np);

	/* build table of divergence corrections */
	divcortable(nt,np,dt,tt,vt,divcor,trans,norm);	

	/* apply conventional correction if required */
	if (conv==1){
		for (ix=0; ix<nx; ++ix){
			efread(ptx[ix],sizeof(float),nt,tfp);
		for (it=0; it<nt; ++it)
			ptx[ix][it] *= divcor[0][it];
		}
	} else {
		/* read and apply fft scaling to traces */ 
		kscl = 1.0/nxfft;
		for (ix=0; ix<nx; ++ix) {
			efread(ptx[ix],sizeof(float),nt,tfp);
			for (it=0; it<nt; ++it)
				ptx[ix][it] *= kscl;
		}
		/* pad with zeros */
		for (ix=nx; ix<nxfft; ++ix)
			for (it=0; it<nt; ++it)
				ptx[ix][it] = 0.0;

		/* Fourier transform ptx(t,x) to ptk(t,k) */
		pfa2rc(-1,2,nt,nxfft,ptx[0],ptk[0]);
		if (verbose) fprintf(stderr,"\tFourier transform done\n");

		/* define relevant k range */
		nkmax = MIN(nk,NINT(PI/dt/vt[0]/dk));
		dpx = 1.0/(np-1)/vt[0];
		fprintf(stderr,
			"nkmax %d nk %d dk %f dpx %f \n",nkmax,nk,dk,dpx);

		/* special case k=0 */
		for (it=0; it<nt; it++){
			ptk[0][it].r *= divcor[0][it];
			ptk[0][it].i *= divcor[0][it];
		}
	
		/* loop over wavenumbers */
		for (ik=1,k=dk; ik<nkmax; ++ik,k+=dk){

			/* report */
			if (verbose && ik%(nkmax/10>0?nkmax/10:1)==0)
				fprintf(stderr,"\t%d of %d wavenumbers done\n",
						ik,nkmax);
		
			/* dip filter divergence correction */
			dipfilt(k,dpx,dt,np,ntfft,nt,divcor,ptk[ik],ptk[ik]);
		}

		/* Fourier transform p(t,k) to p(t,x) */
		pfa2cr(1,2,nt,nxfft,ptk[0],ptx[0]);
		if (verbose) 
			fprintf(stderr,"\tinverse Fourier transform done\n");
	} /* end else dipdivcor */

	/* output migrated traces with headers */
	for (ix=0; ix<nx; ++ix) {
		efread(&tr,HDRBYTES,1,hfp);
		memcpy((void *) tr.data,
			(const void *) ptx[ix], nt*sizeof(float));
		puttr(&tr);
	}
	
	return EXIT_SUCCESS;
}
Exemplo n.º 22
0
main(int argc, char **argv)
{
    FILE     *ifp;     /* file pointer for input       */
    FILE     *hfp;     /* file pointer for popen write */
    int       bfd;     /* file descriptor for bfile    */

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

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

    file2g(stdout); 

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

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

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

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

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

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

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

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

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

	if(nmap>0) {
		free(ibstart);
		free(ibyte);
		free(itype);
		free(obstart);
		free(obyte);
		free(otype);
	}
    
    return EXIT_SUCCESS;
}
Exemplo n.º 23
0
int
main(int argc, char **argv)
{
	cwp_String key[SU_NKEYS];  /* array of keywords			*/
	cwp_String type[SU_NKEYS]; /* array of keywords			*/
	int index[SU_NKEYS];	/* name of type	of getparred key	*/

	int ikey;		/* key counter 				*/
	int nkeys;		/* number of header fields set		*/
	int count=0;		/* number of header fields from file	*/
	double i;		/* parameters for computing fields	*/
	int itr = 0;		/* trace counter 			*/
	Value val;		/* value of key field 			*/

	char *infile="";	/* name of input file of header values	*/
	FILE *infp=NULL;	/* pointer to input file		*/
	cwp_Bool from_file=cwp_false; /* is the data from infile?	*/

	float *afile=NULL;	/* array of "a" values from file	*/
	double *a=NULL;		/* array of "a" values			*/
	double *b=NULL;		/* array of "b" values			*/
	double *c=NULL;		/* array of "c" values			*/
	double *d=NULL;		/* array of "d" values			*/
	double *j=NULL;		/* array of "j" values			*/
	int n;			/* number of a,b,c,d,j values		*/

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

	/* Get "key" values */
	if ((nkeys=countparval("key"))!=0) {
		getparstringarray("key",key);

	} else {
		key[0]="cdp";
	}

	/* get types and indexes corresponding to the keys */
	for (ikey=0; ikey<nkeys; ++ikey) {
		type[ikey]=hdtype(key[ikey]);
		index[ikey]=getindex(key[ikey]);
	}


	/* get name of infile */
	getparstring("infile",&infile);

	/* if infile is specified get specified keys from file */
	if (*infile!='\0') {

		/* open infile */
		if((infp=efopen(infile,"r"))==NULL)
			err("cannot open infile=%s\n",infile);

		/* set from_file flag */
		from_file=cwp_true;
	}

	/* If not from file, getpar a,b,c,d,j */
	if (!from_file) { 
		/* get "a" values */
		if ((n=countparval("a"))!=0) { 
			if (n!=nkeys)
			err("number of a values not equal to number of keys");

			a=ealloc1double(n);
			getpardouble("a",a);
		} else {
			a=ealloc1double(nkeys);
			for (ikey=0; ikey<nkeys; ++ikey) a[ikey]=0.;
		}
		
		/* get "b" values */
		if ((n=countparval("b"))!=0) { 
			if (n!=nkeys)
			err("number of b values not equal to number of keys");

			b=ealloc1double(n);
			getpardouble("b",b);
		} else {
			b=ealloc1double(nkeys);
			for (ikey=0; ikey<nkeys; ++ikey) b[ikey]=0.;
		}
		
		/* get "c" values */
		if ((n=countparval("c"))!=0) { 
			if (n!=nkeys)
			err("number of c values not equal to number of keys");

			c=ealloc1double(n);
			getpardouble("c",c);
		} else {
			c=ealloc1double(nkeys);
			for (ikey=0; ikey<nkeys; ++ikey) c[ikey]=0.;
		}

		/* get "d" values */
		if ((n=countparval("d"))!=0) { 
			if (n!=nkeys)
			err("number of d values not equal to number of keys");

			d=ealloc1double(n);
			getpardouble("d",d);
		} else {
			d=ealloc1double(nkeys);
			for (ikey=0; ikey<nkeys; ++ikey) d[ikey]=0.;
		}

		/* get "j" values */
		if ((n=countparval("j"))!=0) { 
			if (n!=nkeys)
			err("number of j values not equal to number of keys");

			j=ealloc1double(n);
			getpardouble("j",j);

			/* make sure that j!=0 */
			for (ikey=0; ikey<nkeys; ++ikey)
				if(j[ikey]==0) j[ikey]=ULONG_MAX;
		} else {
			j=ealloc1double(nkeys);
			for (ikey=0; ikey<nkeys; ++ikey) j[ikey]=ULONG_MAX;
		}
	} else { /* if reading from a file */
		/* allocate space for afile */
		afile=ealloc1float(nkeys);
	}

        checkpars();

	/* loop over traces */
	while (gettr(&tr)) {

		if (from_file) {
			/* use the "a" value from file to trace by trace */
			if (efread(afile,FSIZE,nkeys,infp)!=0) {
				for (ikey=0; ikey<nkeys; ++ikey) {
					double a_in;
					a_in=(double) afile[ikey];
					setval(type[ikey],&val,a_in,
							 0,0,0,ULONG_MAX);
					puthval(&tr,index[ikey],&val);
				++count;
				}
			}
		} else { /* use getparred values of a,b,c,d,j */
			for (ikey=0; ikey<nkeys; ++ikey) {
				i = (double) itr + d[ikey];
				
				setval(type[ikey],&val,a[ikey],b[ikey],
						c[ikey],i,j[ikey]);
				puthval(&tr,index[ikey],&val);
			}

		}

		++itr;
		puttr(&tr);
	}

	if (from_file) {
		efclose(infp);
		if (count < (int)(itr*nkeys) ) {
		   warn("itr=%d > count=%d %s",(int) itr*count,count);
		   warn("n traces=%d > data count =%d",(itr*nkeys),count);
		}
	}


	return(CWP_Exit());
}
Exemplo n.º 24
0
int
main(int argc, char **argv)
{
	cwp_String key[SU_NKEYS];	/* array of keywords		*/
	cwp_String type[SU_NKEYS];	/* array of types for key	*/
	int index[SU_NKEYS];		/* array of indexes for key	*/
	int ikey;		/* key counter				*/
	int nkeys;		/* number of header fields set		*/
	int n;			/* number of min,max values   		*/
	Value val;		/* value of key field			*/
	double fval;		/* value of key field			*/
	float *min=NULL;	/* array of "min" values		*/
	float *max=NULL;	/* array of "max" values		*/

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

	/* Get "key" values */
	if ((nkeys=countparval("key"))!=0) {
		getparstringarray("key",key);

	} else {
		key[0]="cdp";
	}

	/* get types and indexes corresponding to the keys */
	for (ikey=0; ikey<nkeys; ++ikey) {
		type[ikey]=hdtype(key[ikey]);
		index[ikey]=getindex(key[ikey]);
	}

	/* get "min" values */
	if ((n=countparval("min"))!=0) { 
		if (n!=nkeys)
		err("number of a values not equal to number of keys");
		min=ealloc1float(n);
		getparfloat("min",min);
	} else {
		min=ealloc1float(nkeys);
		for (ikey=0; ikey<nkeys; ++ikey) min[ikey]=0.;
	}

	/* get "max" values */
	if ((n=countparval("max"))!=0) { 
		if (n!=nkeys)
		err("number of a values not equal to number of keys");
		max=ealloc1float(n);
		getparfloat("max",max);
	} else {
		max=ealloc1float(nkeys);
		for (ikey=0; ikey<nkeys; ++ikey) max[ikey]=ULONG_MAX;
	}

	/* get types and index values */
	for (ikey=0; ikey<nkeys; ++ikey) {
		type[ikey] = hdtype(key[ikey]);
		index[ikey] = getindex(key[ikey]);
	}

	while (gettr(&tr)) {
		for (ikey=0; ikey<nkeys; ++ikey) {
			gethval(&tr, index[ikey], &val);
			fval = vtof(type[ikey], val);
			if (fval < min[ikey]) {
				changeval(type[ikey], &val, min[ikey]);
				puthval(&tr, index[ikey], &val);
			} else if (fval > max[ikey]) {
				changeval(type[ikey], &val, max[ikey]);
				puthval(&tr, index[ikey], &val);
			}
		}
		puttr(&tr);
	}

	return(CWP_Exit());
}
Exemplo n.º 25
0
int main(int argc, char **argv)
{
	int i,ix,it;		/* loop counters */
	int wtype;		/* =1 psv. =2 sh wavefields */
	int wfield;		/* =1 displcement =2 velocity =3 acceleration */
	int stype;		/* source type */
	int int_type;		/* =1 for trapezoidal rule. =2 for Filon */
	int flt;		/* =1 apply earth flattening correction */
	int rand;		/* =1 for random velocity layers */
	int qopt;		/* some flag ???? */
	int vsp;		/* =1 for vsp, =0 otherwise */
	int win;		/* =1 if frequency windowing required */
	int verbose;		/* flag to output processing information */
	int nt;			/* samples per trace in output traces */
	int ntc;		/* samples per trace in computed traces */
	int nx;			/* number of output traces */
	int np;			/* number of ray parameters */
	int nlint=0;		/* number of times layer interp is required */
	int lsource;		/* layer on top of which the source is located*/
	int nw;			/* number of frequencies */
	int nor;		/* number of receivers */
	int nlayers;		/* number of reflecting layers */
	int layern;
	int nrand_layers;	/* maximum number of random layers permitted */
	int nf;			/* number of frequencies in output traces */
	int *filters_phase=NULL;	/* =0 for zero phase, =1 for minimum phase fil*/
	int nfilters;		/* number of required filters */
	int wavelet_type;	/* =1 spike =2 ricker1 =3 ricker2 =4 akb */

	float dt;		/* time sampling interval */
	float tsec;		/* trace length in seconds */
	float fpeak;		/* peak frequency for output wavelet */
	float fref;		/* first frequency */
	float p2w;		/* maximum ray parameter value */
	float bp;		/* smallest ray parameter (s/km) */
	float bx;		/* beginning of range in Kms. */
	float fx;		/* final range in Kms. */
	float dx;		/* range increment in Kms. */
	float pw1,pw2,pw3,pw4;	/* window ray parameters (to apply taper) */
	float h1;		/* horizontal linear part of the source */ 
	float h2;		/* vertical linear part of the source */ 
	float m0;		/* seismic moment */
	float m1,m2,m3;		/* components of the moment tensor */

	float delta;		/* dip */
	float lambda;		/* rake */
	float phis;		/* azimuth of the fault plane */
	float phi;		/* azimuth of the receiver location */

	float sdcl,sdct;	/* standar deviation for p and s-wave vels */
	float z0=0.0;		/* reference depth */
	float zlayer;		/* thickness of random layers */
	int layer;		/* layer over on top of which to compute rand*/
	float tlag;		/* time lag in output traces */
	float red_vel;		/* erducing velocity */

	float w1=0.0;		/* low end frequency cutoff for taper */
	float w2=0.0;		/* high end frequency cutoff for taper */
	float wrefp;		/* reference frequency for p-wave velocities */
	float wrefs;		/* reference frequency for s-wave velocities */

	float epsp;		/* .... for p-wave velocities */
	float epss;		/* .... for p-wave velocities */
	float sigp;		/* .... for p-wave velocities */
	float sigs;		/* .... for s-wave velocities */
	float fs;		/* sampling parameter, usually 0.07<fs<0.12 */
	float decay;		/* decay factor to avoid wraparound */

	int *lobs;		/* layers on top of which lay the receivers */
	int *nintlayers=NULL;	/* array of number of layers to interpolate */
	int *filters_type;	/* array of 1 lo cut, 2 hi cut, 3 notch */

	float *dbpo=NULL;	/* array of filter slopes in db/octave */
	float *f1=NULL;		/* array of lo frequencies for filters */
	float *f2=NULL;		/* array of high frequencies for filters */
	float *cl;		/* array of compressional wave velocities */
	float *ql;		/* array of compressional Q values */
	float *ct;		/* array of shear wave velocities */
	float *qt;		/* array of shear Q values */
	float *rho;		/* array of densities */
	float *t;		/* array of absolute layer thickness */

	int *intlayers=NULL;	/* array of layers to interpolate */

	float *intlayth=NULL;	/* array of thicknesses over which to interp */
	float **wavefield1;	/* array for pressure wavefield component */
	float **wavefield2=NULL;/* array for radial wavefield component */
	float **wavefield3=NULL;/* array for vertical wavefield component */

	char *lobsfile="";	/* input file receiver layers */
	char *clfile="";	/* input file of p-wave velocities */
	char *qlfile="";	/* input file of compressional Q-values */
	char *ctfile="";	/* input file of s-wave velocities */
	char *qtfile="";	/* input file of shear Q-values */
	char *rhofile="";	/* input file of density values */
	char *tfile="";		/* input file of absolute layer thicknesses */
	char *intlayfile="";	/* input file of layers to interpolate */
	char *nintlayfile="";	/* input file of number of layers to interp */
	char *intlaythfile="";	/*input file of layer thickness where to inter*/
	char *filtypefile="";	/* input file of filter types to apply */
	char *fphfile="";	/* input file of filters phases */
	char *dbpofile="";	/* input file of filter slopes in db/octave */
	char *f1file="";	/* input file of lo-end frequency */
	char *f2file="";	/* input file of hi-end frequency */

	char *wfp="";		/* output file of pressure */
	char *wfr="";		/* output file of radial wavefield */
	char *wfz="";		/* output file of vertical wavefield */
	char *wft="";		/* output file of tangential wavefield */
	char *outf="";		/* output file for processing information */

	FILE *wfp_file;		/* file pointer to output pressure */
	FILE *wfr_file;		/* file pointer to output radial wavefield */
	FILE *wfz_file;		/* file pointer to output vertical wavefield */
	FILE *wft_file;		/* file pointer to output tangential wavefield*/
	FILE *outfp=NULL;	/* file pointer to processing information */
	FILE *infp;		/* file pointer to input information */

	
	/* hook up getpar to handle the parameters */
	initargs(argc,argv);
	requestdoc(0);			/* no input data */

	/* get required parameter, seismic moment */
	if (!getparfloat("m0",&m0))	
		err("error: the seismic moment, m0, is a required parameter\n");

	/*********************************************************************/
	/* get general flags and set their defaults */
	if (!getparint("rand",&rand))			rand	= 0;
	if (!getparint("qopt",&qopt))			qopt	= 0;
	if (!getparint("stype",&stype))			stype	= 1;
	if (!getparint("wtype",&wtype))			wtype	= 1;
	if (!getparint("wfield",&wfield))		wfield	= 1;
	if (!getparint("int_type",&int_type))		int_type= 1;
	if (!getparint("flt",&flt))			flt	= 0;
	if (!getparint("vsp",&vsp))			vsp	= 0;
	if (!getparint("win",&win))			win	= 0;
	if (!getparint("wavelet_type",&wavelet_type))	wavelet_type = 1;
	if (!getparint("verbose",&verbose))		verbose	= 0;

	/* get model parameters and set their defaults */
	if (!getparint("lsource",&lsource))		lsource = 0;
	if (!getparfloat("fs",&fs)) 			fs	= 0.07;
	if (!getparfloat("decay",&decay))		decay	= 50.0;
	if (!getparfloat("tsec",&tsec))			tsec	= 2.048;

	/* get response parameters and set their defaults */
	if (!getparfloat("fref",&fref))			fref	= 1.0;
	if (!getparint("nw",&nw))			nw	= 100;
	if (!getparint("nor",&nor))			nor	= 100;
	if (!getparint("np",&np))			np	= 1300;
	if (!getparfloat("p2w",&p2w))			p2w	= 5.0;
	if (!getparfloat("bx",&bx))			bx	= 0.005;
	if (!getparfloat("bp",&bp))			bp	= 0.0;
	if (!getparfloat("fx",&fx))			fx	= 0.1;
	if (!getparfloat("dx",&dx))			dx	= 0.001;
	if (!getparfloat("pw1",&pw1))			pw1	= 0.0;
	if (!getparfloat("pw2",&pw2))			pw2	= 0.1;
	if (!getparfloat("pw3",&pw3))			pw3	= 6.7;
	if (!getparfloat("pw4",&pw4))			pw4	= 7.0;
	if (!getparfloat("h1",&h1))			h1	= 1.0;
	if (!getparfloat("h2",&h2))			h2	= 0.0;

	/* get output parameters and set their defaults */
	if (!getparint("nx",&nx))			nx	= 100;
	if (!getparfloat("dt",&dt))			dt	= 0.004;
	if (!getparint("nt",&nt))			nt	= tsec/dt;
	if (!getparint("nf",&nf))			nf	= 50;
	if (!getparfloat("red_vel",&red_vel))		red_vel	= 5;
	if (!getparfloat("fpeak",&fpeak))		fpeak	= 25.;
	if (!getparfloat("tlag",&tlag))			tlag	= 0.;

	/* get names of output files */
	if (wtype==1) {
		getparstring("wfp",&wfp);
		getparstring("wfr",&wfr);
		getparstring("wfz",&wfz);
	} else if (wtype==2) {
		getparstring("wft",&wft);
	} else err ("wtype has to be zero or one");

	/*********************************************************************/
	/* get or compute moment tensor components */
	if (stype==1) {

		/* get source parameters */
		if (!getparfloat("delta",&delta))	
			err("if stype==1, delta is a required parameter\n");
		if (!getparfloat("lambda",&lambda))	
			err("if stype==1, lambda is a required parameter\n");
		if (!getparfloat("phis",&phis))	
			err("if stype==1, phis is a required parameter\n");
		if (!getparfloat("phi",&phi))	
			err("if stype==1, phi is a required parameter\n");

		/* compute moment tensor components */
		compute_moment_tensor (wtype, phi, lambda, delta, phis, m0, 
			&m1, &m2, &m3);

	} else if (stype==2) {

		/* get moment tensor components from input */	
		if (!getparfloat("m1",&m1))	
			err("if stype==2, m1 is a required parameter\n");
		if (!getparfloat("m2",&m2))	
			err("if stype==2, m2 is a required parameter\n");
		if (!getparfloat("m3",&m3))	
			err("if stype==2, m3 is a required parameter\n");

	} else err("error, stype flag has to be one or two\n");

	/*********************************************************************/
	/* if q-option is not requesed, set corresponding parameters to zero */
	if (!getparint("layern",&layern))		layern	=0;	
	if (!getparfloat("wrefp",&wrefp))		wrefp	=0.0;
	if (!getparfloat("wrefs",&wrefs))		wrefs	=0.0;
	if (!getparfloat("epsp",&epsp))			epsp	=0.0;
	if (!getparfloat("epss",&epss))			epss	=0.0;
	if (!getparfloat("sigp",&sigp))			sigp	=0.0;
	if (!getparfloat("sigs",&sigs))			sigs	=0.0;

	/*********************************************************************/
	/* get number of layers and check input parameters */
	if (*clfile=='\0') {	/* p-wave vels input from the comand line */
		nlayers=countparval("cl");
	} else  {		/* p-wave vels input from a file */
		getparint("nlayers",&nlayers);
	}
	if (*ctfile=='\0') {	/* s-wave vels input from the comand line */
		if (nlayers !=countparval("cl")) 
			err("number of p-wave and s-wave velocities"
				"has to be the same");
	}
	if (*qlfile=='\0') { 	/* compressional q-values from comand line */
		if (nlayers !=countparval("ql")) 
			err("number of p-wave velocities and q-values"
				"has to be the same");
	}
	if (*qtfile=='\0') { 	/* shear q-values input from comand line */
		if (nlayers !=countparval("qt")) 
			err("number of p-wave velocities and shear q-values"
				"has to be the same");
	}
	if (*rhofile=='\0') { 	/* densities input from comand line */
		if (nlayers !=countparval("rho")) 
			err("number of p-wave velocities and densities"
				"has to be the same");
	}
	if (*tfile=='\0') { 	/* layer thicknesses input from comand line */
		if (nlayers !=countparval("t")) 
			err("number of p-wave velocities and thicknesses"
				"has to be the same");
	}
	if (int_type!=1 && int_type!=2) err("int_type flag has to be one or two");

	/*********************************************************************/
	/* if layer interpolation is requested, get parameters */
	if (*intlayfile !='\0') {
		getparint("nlint",&nlint);
		if ((infp=efopen(intlayfile,"r"))==NULL)
			err("cannot open file of layer interp=%s\n",intlayfile);
		intlayers=alloc1int(nlint);
		fread (intlayers,sizeof(int),nlint,infp);
		efclose(infp);
	} else if (countparval("intlayers") !=0) {
		nlint=countparval("intlayers");
		intlayers=alloc1int(nlint);
		getparint("intlayers",intlayers);
	}
	if (*nintlayfile !='\0') {
		if ((infp=efopen(nintlayfile,"r"))==NULL)
			err("cannot open file of layer inter=%s\n",nintlayfile);
		nintlayers=alloc1int(nlint);
		fread (nintlayers,sizeof(int),nlint,infp);
		efclose(infp);
	} else if (countparval("nintlayers") !=0) {
		if (nlint !=countparval("nintlayers")) 
			err("number of values in intlay and nintlay not equal");
		nintlayers=alloc1int(nlint);
		getparint("nintlayers",nintlayers);
	}
	if (*intlaythfile !='\0') {
		if ((infp=efopen(intlaythfile,"r"))==NULL)
			err("cannot open file=%s\n",intlaythfile);
		intlayth=alloc1float(nlint);
		fread (intlayth,sizeof(int),nlint,infp);
		efclose(infp);
	} else if (countparval("intlayth") !=0) {
		if (nlint !=countparval("intlayth")) 
			err("# of values in intlay and intlayth not equal");
		intlayth=alloc1float(nlint);
		getparfloat("intlayth",intlayth);
	}
	/* update total number of layers */
	if (nlint!=0) {
		for (i=0; i<nlint; i++) nlayers +=intlayers[i]-1;
	}
		
	/*********************************************************************/
	/* if random velocity layers requested, get parameters */
	if (rand==1) {
		getparint("layer",&layer);
		getparint("nrand_layers",&nrand_layers);
		getparfloat("zlayer",&zlayer);
		getparfloat("sdcl",&sdcl);
		getparfloat("sdct",&sdct);
	} else nrand_layers=0;	

	/*********************************************************************/
	/* allocate space */
	cl = alloc1float(nlayers+nrand_layers);
	ct = alloc1float(nlayers+nrand_layers);
	ql = alloc1float(nlayers+nrand_layers);
	qt = alloc1float(nlayers+nrand_layers);
	rho = alloc1float(nlayers+nrand_layers);
	t = alloc1float(nlayers+nrand_layers);
	lobs = alloc1int(nor+1);
	lobs[nor]=0;

	/*********************************************************************/
	/* read  input parameters from files or command line */
	if (*clfile !='\0') {			/* read from a file */	
		if ((infp=efopen(clfile,"r"))==NULL)
			err("cannot open file of pwave velocities=%s\n",clfile);
		fread(cl,sizeof(float),nlayers,infp);
		efclose(infp);
	} else getparfloat("cl",cl);		/* get from command line */
	if (*qlfile !='\0') {
		if ((infp=efopen(qlfile,"r"))==NULL)
			err("cannot open file of compressional Q=%s\n",qlfile);
		fread(ql,sizeof(float),nlayers,infp);
		efclose(infp);
	} else getparfloat("ql",ql);
	if (*ctfile !='\0') {
		if ((infp=efopen(ctfile,"r"))==NULL)
			err("cannot open file of swave velocities=%s\n",ctfile);
		fread(ct,sizeof(float),nlayers,infp);
		efclose(infp);
	} else getparfloat("ct",ct);
	if (*qtfile !='\0') {
		if ((infp=efopen(qtfile,"r"))==NULL)
			err("cannot open file of shear Q=%s\n",qtfile);
		fread(qt,sizeof(float),nlayers,infp);
		efclose(infp);
	} else getparfloat("qt",qt);
	if (*rhofile !='\0') {
		if ((infp=efopen(rhofile,"r"))==NULL)
			err("cannot open file of densities=%s\n",rhofile);
		fread(rho,sizeof(float),nlayers,infp);
		efclose(infp);
	} else getparfloat("rho",rho);
	if (*tfile !='\0') {
		if ((infp=efopen(tfile,"r"))==NULL)
			err("cannot open file of thicknesses=%s\n",tfile);
		fread(t,sizeof(float),nlayers,infp);
		efclose(infp);
	} else getparfloat("t",t);
	if (*lobsfile !='\0') {
		if ((infp=efopen(lobsfile,"r"))==NULL)
			err("can't open file of receiver layers=%s\n",lobsfile);
		fread(lobs,sizeof(int),nor,infp);
		efclose(infp);
	} else getparint("lobs",lobs);

	/*********************************************************************/
	/* if requested, do interpolation and/or parameter adjustment */
	if (nlint!=0)
		parameter_interpolation (nlayers, intlayers, nintlayers, 
				intlayth, cl, ql, ct, qt, rho, t);	

	/* if requested, compute random velocity layers */
	if (rand==1) {
		random_velocity_layers (&nlayers, &lsource, nrand_layers, sdcl,
			sdct, layer, zlayer, cl, ql, ct, qt, rho, t);
	}

	/* if requested, apply earth flattening approximation */
	if (flt==1) {
		apply_earth_flattening (nlayers, z0, cl, ct, rho, t);
	}


	/*********************************************************************/
	/* get filter parameters */
	if (*filtypefile !='\0') {
		if ((infp=efopen(filtypefile,"r"))==NULL)
			err("cannot open file=%s\n",filtypefile);
		getparint("nfilters",&nfilters);
		filters_type=alloc1int(nfilters);
		fread (filters_type,sizeof(int),nfilters,infp);
		efclose(infp);
	} else {
		nfilters=countparval("filters_type");
		filters_type=alloc1int(nfilters);
		getparint("filters_type",filters_type);
	}
	if (*fphfile !='\0') {
		if ((infp=efopen(fphfile,"r"))==NULL)
			err("cannot open file=%s\n",fphfile);
		filters_phase=alloc1int(nfilters);
		fread (filters_phase,sizeof(float),nfilters,infp);
		efclose(infp);
	} else if (nfilters == countparval("filters_phase")) {
		filters_phase=alloc1int(nfilters);
		getparint("filters_phase",filters_phase);
	} else err("number of elements infilterstype and phase must be equal");
	if (*dbpofile !='\0') {
		if ((infp=efopen(dbpofile,"r"))==NULL)
			err("cannot open file=%s\n",dbpofile);
		dbpo=alloc1float(nfilters);
		fread (dbpo,sizeof(float),nfilters,infp);
		efclose(infp);
	} else if (nfilters == countparval("dbpo")) {
		dbpo=alloc1float(nfilters);
		getparfloat("dbpo",dbpo);
	} else err("number of elements in filters_type and dbpo must be equal");
	if (*f1file !='\0') {
		if ((infp=efopen(f1file,"r"))==NULL)
			err("cannot open file=%s\n",f1file);
		f1=alloc1float(nfilters);
		fread (f1,sizeof(float),nfilters,infp);
		efclose(infp);
	} else if (nfilters == countparval("f1")) {
		f1=alloc1float(nfilters);
		getparfloat("f1",f1);
	} else err("number of elements in filters_type and f1 must be equal");
	if (*f2file !='\0') {
		if ((infp=efopen(f2file,"r"))==NULL)
			err("cannot open file=%s\n",f2file);
		f2=alloc1float(nfilters);
		fread (f2,sizeof(float),nfilters,infp);
		efclose(infp);
	} else if (nfilters == countparval("f2")) {
		f2=alloc1float(nfilters);
		getparfloat("f2",f2);
	} else err("number of elements in filters_type and f2 must be equal");
		

	/*********************************************************************/
	/* allocate space for wavefield computations */
	wavefield1=alloc2float(nt,nx);
	if (wtype==1) {
		wavefield2=alloc2float(nt,nx);
		wavefield3=alloc2float(nt,nx);
	}
	/* get name of output file for processing information */
	if (verbose==2||verbose==3) {
		if (!getparstring("outf",&outf))	outf="info";
		if ((outfp=efopen(outf,"w"))==NULL) {
			warn("cannot open processing file =%s, no processing\n"
			"information file will be generated\n",outf);
			verbose=1;
		}
	}

	/* initialize wavefields */
	if (wtype==1) {
		for (ix=0;ix<nx;ix++) {
			for (it=0;it<nt;it++) {
				wavefield1[ix][it]=0.0;
				wavefield2[ix][it]=0.0;
				wavefield3[ix][it]=0.0;
			}
		}
	} else if (wtype==2) {
		for (ix=0;ix<nx;ix++) {
			for (it=0;it<nt;it++) {
				wavefield1[ix][it]=0.0;
			}
		}
	}

	/* number of time samples in computed traces */
	ntc=tsec/dt;
	if (int_type==2) bp=0.0;

	/*********************************************************************/
	/* Now, compute the actual reflectivities */
	compute_reflectivities (int_type, verbose, wtype, wfield, vsp, flt,
		win, nx, nt, ntc, nor, nf, nlayers, lsource, layern, nfilters,
		filters_phase, nw, np, bp, tlag, red_vel, w1, w2, fx, dx, bx,
		fs, decay, p2w, tsec, fref, wrefp, wrefs, epsp, epss, sigp,
		sigs, pw1, pw2, pw3, pw4, h1, h2, m1, m2, m3, fref, lobs,
		filters_type, dbpo, f1, f2, cl, ct, ql, qt, rho, t, wavefield1,
		wavefield2, wavefield3, outfp);
	/*********************************************************************/

	/* if open, close processing information file */
	if (verbose==2||verbose==3) efclose(outfp);

	/* convolve with a wavelet and write the results out */
	if (wtype==1) {			/* PSV */
		
		/* convolve with a wavelet to produce the seismograms */
		convolve_wavelet (wavelet_type, nx, nt, dt, fpeak, wavefield1); 
		convolve_wavelet (wavelet_type, nx, nt, dt, fpeak, wavefield2); 
		convolve_wavelet (wavelet_type, nx, nt, dt, fpeak, wavefield3); 

		/* output results in SU format */
		if(*wfp!='\0'){
			if ((wfp_file=efopen(wfp,"w"))==NULL)
				err("cannot open pressure file=%s\n",wfp);
			{	register int ix;
				for (ix=0; ix<nx; ix++) {
					for (it=0; it<nt; it++)
						tr1.data[it]=wavefield1[ix][it];

					/* headers*/
					tr1.ns=nt;
					tr1.dt=1000*(int)(1000*dt);
					tr1.offset=(bx+ix*dx)*1000;
	
					/* output trace */
					fputtr(wfp_file, &tr1);
				}
				efclose (wfp_file);
			}
		}
		if (*wfr !='\0') {
			if ((wfr_file=efopen(wfr,"w"))==NULL)
					err("cannot open radial wfield file=%s\n",wfr);
			{	register int ix;
				for (ix=0; ix<nx; ix++) {
					for (it=0; it<nt; it++)
						tr2.data[it]=wavefield2[ix][it];
					tr2.ns=nt;
					tr2.dt=1000*(int)(1000*dt);
					tr2.offset=(bx+ix*dx)*1000;
					fputtr(wfr_file, &tr2);
				}
				efclose (wfr_file);
			}
		}
		if (*wfz !='\0') {
			if ((wfz_file=efopen(wfz,"w"))==NULL)
				err("canno open vertical field file=%s\n",wfz);
			{	register int ix;
				for (ix=0; ix<nx; ix++) {
					for (it=0; it<nt; it++)
							tr3.data[it]=wavefield3[ix][it];
					tr3.ns=nt;
					tr3.dt=1000*(int)(1000*dt);
					tr3.offset=(bx+ix*dx)*1000;
					fputtr(wfz_file, &tr3);
				}
				efclose (wfz_file);
			}
		}
		
		/* free allocated space */
		free2float(wavefield1);
		free2float(wavefield2);
		free2float(wavefield3);

	} else if (wtype==2) {			/* SH */

		/* convolve with a wavelet to produce the seismogram */
		convolve_wavelet (wavelet_type, nx, nt, dt, fpeak, wavefield1); 

		/* output the result in SU format */
		if (*wft !='\0') {
			if ((wft_file=efopen(wft,"w"))==NULL)
				err("cannot open tangential file=%s\n",wft);
			{	register int ix;
				for (ix=0; ix<nx; ix++) {
					for (it=0; it<nt; it++)
							tr1.data[it]=wavefield1[ix][it];
					tr1.ns=nt;
					tr1.dt=1000*(int)(1000*dt);
					tr1.offset=(bx+ix*dx)*1000;
					fputtr(wft_file, &tr1);
				}
				efclose (wft_file);
			}
		}

		/* free allocated space */
		free2float(wavefield1);
	}

	/* free workspace */
	free1float(cl);
	free1float(ct);
	free1float(ql);
	free1float(qt);
	free1float(rho);
	free1float(t);
	free1int(lobs);
	free1int(filters_type);
	free1int(filters_phase);
	free1float(dbpo);
	free1float(f1);
	free1float(f2);
	return EXIT_SUCCESS;
}
Exemplo n.º 26
0
int
main(int argc, char **argv)
{
	char *key=NULL;		/* header key word from segy.h		*/	
	char *type=NULL;	/* ... its type				*/
	int index;		/* ... its index			*/
	Value val;		/* ... its value			*/
	float fval;		/* ... its value cast to float		*/
	float twfval;		/* ... its value cast to float		*/
	float *xmute=NULL;	/* array of key mute curve values	*/
	float *tmute=NULL;	/* ...		mute curve time values 	*/
	float *twindow=NULL;	/* ...	mute window time values mode=4	*/
	float linvel;		/* linear velocity			*/
	float tm0;		/* time shift of mute=2 or 3 for 'key'=0*/
	float *taper=NULL;	/* ...		taper values		*/
	int nxmute=0;		/* number of key mute values		*/
	int ntmute;	/* ...		mute time values 	*/
	int ntwindow;	/* ...		mute time values 	*/
	int ntaper;	/* ...		taper values		*/

	int below;	/* mute below curve			*/
	int mode;	/* kind of mute (top, bottom, linear)	*/
	int absolute;    /* Take absolute value of key for mode=2 */
	int hmute=0;	/* read mute times from header		*/

	int nxtmute;	/* number of mute values 		*/
	cwp_String xfile="";	/* file containing positions by key	*/
	FILE *xfilep;		/* ... its file pointer			*/
	cwp_String tfile="";	/* file containing times	 	*/
	FILE *tfilep;		/* ... its file pointer			*/

	cwp_String twfile="";	/* file containing mute time windows 	*/
	FILE *twfilep;		/* ... its file pointer			*/

	cwp_Bool seismic;	/* cwp_true if seismic, cwp_false not seismic */

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


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

	if (getparstring("hmute", &key)) { hmute = 1; } else

	if (!(getparstring("xfile",&xfile) && getparstring("tfile",&tfile))) {
		if (!(nxmute = countparval("xmute")))
			err("must give xmute= vector");
		if (!(ntmute = countparval("tmute")))
			err("must give tmute= vector");
		if (nxmute != ntmute)
			err("lengths of xmute, tmute must be the same");
		xmute = ealloc1float(nxmute);	getparfloat("xmute", xmute);
		tmute = ealloc1float(nxmute);	getparfloat("tmute", tmute);
		if (mode==4) {
			if (!(ntwindow = countparval("twindow")))
				err("must give twindow= vector");
			if (nxmute != ntwindow)
				err("lengths of xmute, twindow must be the same");
			twindow = ealloc1float(nxmute);
			getparfloat("twindow", twindow);
		}
	} else {
		MUSTGETPARINT("nmute",&nxtmute);
		nxmute = nxtmute;
		xmute = ealloc1float(nxtmute);
		tmute = ealloc1float(nxtmute);

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

		if((tfilep=fopen(tfile,"r"))==NULL)
			err("cannot open tfile=%s\n",tfile);
		if (fread(tmute,sizeof(float),nxtmute,tfilep)!=nxtmute)
			err("error reading tfile=%s\n",tfile);
		fclose(tfilep);

		if (mode==4) {
			if((twfilep=fopen(twfile,"r"))==NULL)
				err("cannot open tfile=%s\n",twfile);
			if (fread(twindow,sizeof(float),nxtmute,twfilep)!=nxtmute)
				err("error reading tfile=%s\n",tfile);
			fclose(twfilep);
		}
	}

	if (!getparint("ntaper", &ntaper))	ntaper = 0;
	if (getparint("below", &below))	{
		mode = below; 
		warn ("use of below parameter is obsolete. mode value set to %d \n", mode);
	}
	if (!getparint("absolute", &absolute))		absolute = 1;
	if (hmute==0) if (!getparstring("key", &key))	key = "offset";
	if (!getparfloat("linvel", &linvel))	linvel = 330;
	if (!getparfloat("tm0", &tm0))		tm0 = 0;
        checkpars();
	if (linvel==0) err ("linear velocity can't be 0");

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

	/* Set up taper weights if tapering requested */
	if (ntaper) {
		register int k;
		taper = ealloc1float(ntaper);
		for (k = 0; k < ntaper; ++k) {
			float s = sin((k+1)*PI/(2*ntaper));
			taper[k] = s*s;
		}
	}

						
	/* Get info from first trace */
	if (!gettr(&tr)) err("can't read first trace");

	seismic = ISSEISMIC(tr.trid);

	if (seismic) {
		if (!tr.dt) err("dt header field must be set");
	} else if (tr.trid==TRID_DEPTH) {   /* depth section */
		if (!tr.d1) err("d1 header field must be set");
	} else {
		err ("tr.trid = %d, unsupported trace id",tr.trid);
	}

	/* Loop over traces */
	do {
		int nt     = (int) tr.ns;
		float tmin = tr.delrt/1000.0;
		float dt = ((double) tr.dt)/1000000.0;
		float t;
		float tw;
		int nmute;
		int itaper;
		int topmute;
		int botmute;
		int ntair=0;
		register int i;

		if (!seismic) { 
			tmin = 0.0;
			dt = tr.d1;	
		}

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

		if (hmute==1) {
			t = fval/1000.;
		} else {
		/* linearly interpolate between (xmute,tmute) values */
		intlin(nxmute,xmute,tmute,tmin,tmute[nxmute-1],1,&fval,&t); 
		}

		if (absolute) fval = abs(fval);
		/* do the mute */
		if (mode==0) {	/* mute above */
			nmute = MIN(NINT((t - tmin)/dt),nt);
			if (nmute>0) memset( (void *) tr.data, 0, nmute*FSIZE);
			for (i = 0; i < ntaper; ++i)
				if (i+nmute>0) tr.data[i+nmute] *= taper[i];
			if (seismic) {
				tr.muts = NINT(t*1000);
			} else	{
				tr.muts = NINT(t);
			}
		} else if (mode==1){	/* mute below */
			nmute = MAX(0,NINT((tmin + nt*dt - t)/dt));
			memset( (void *) (tr.data+nt-nmute), 0, nmute*FSIZE);
			for (i = 0; i < ntaper; ++i)
				if (nt>nmute+i && nmute+i>0)
					tr.data[nt-nmute-1-i] *= taper[i];
			if (seismic) {
				tr.mute = NINT(t*1000);
			} else	{
				tr.mute = NINT(t);
			}
		} else if (mode==2){	/* air wave mute */
			nmute = NINT((tmin+t)/dt);
			ntair=NINT(tm0/dt+fval/linvel/dt);
			topmute=MIN(MAX(0,ntair-nmute/2),nt);
			botmute=MIN(nt,ntair+nmute/2);
			memset( (void *) (tr.data+topmute), 0,
					(botmute-topmute)*FSIZE);
			for (i = 0; i < ntaper; ++i){
				itaper=ntair-nmute/2-i;
				if (itaper > 0) tr.data[itaper] *=taper[i];
			}	
			for (i = 0; i < ntaper; ++i){
				itaper=ntair+nmute/2+i;
				if (itaper<nt) tr.data[itaper] *=taper[i];
			}
		} else if (mode==3) {	/* hyperbolic mute */
			nmute = NINT((tmin + t)/dt);
			ntair=NINT(sqrt( SQ((float)(tm0/dt))+SQ((float)(fval/linvel/dt)) ));
			topmute=MIN(MAX(0,ntair-nmute/2),nt);
			botmute=MIN(nt,ntair+nmute/2);
			memset( (void *) (tr.data+topmute), 0,
					(botmute-topmute)*FSIZE);
			for (i = 0; i < ntaper; ++i){
				itaper=ntair-nmute/2-i;
				if (itaper > 0) tr.data[itaper] *=taper[i];
			}	
			for (i = 0; i < ntaper; ++i){
				itaper=ntair+nmute/2+i;
				if (itaper<nt) tr.data[itaper] *=taper[i];
			}
		} else if (mode==4) {	/* polygonal mute */
			tmin=twindow[0];
			intlin(nxmute,xmute,twindow,tmin,twindow[nxmute-1],1,&twfval,&tw); 
			if (absolute) twfval = abs(twfval);

			nmute = NINT(tw/dt);
			ntair = NINT(t/dt);

			topmute=MIN(MAX(0,ntair-nmute/2),nt);
			botmute=MIN(nt,ntair+nmute/2);
			memset( (void *) (tr.data+topmute), 0,
					(botmute-topmute)*FSIZE);
			for (i = 0;i < ntaper; ++i){
				itaper=ntair-nmute/2-i;
				if (itaper > 0) tr.data[itaper] *=taper[i];
			}	
			for (i = 0; i < ntaper; ++i){
				itaper=ntair+nmute/2+i;
				if (itaper<nt) tr.data[itaper] *=taper[i];
			}


		}
		puttr(&tr);
	} while (gettr(&tr));
	
	return(CWP_Exit());
}
Exemplo n.º 27
0
int
main(int argc, char **argv)
{
	char *key=NULL;		/* header key word from segy.h		*/
	char *type=NULL;	/* ... its type				*/
	int index;		/* ... its index			*/
	Value val;		/* ... its value			*/
	float fval;		/* ... its value cast to float		*/

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

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

	int nxtshift;		/* number of shift values 		*/

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

	float dt;		/* time sampling interval		*/

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	}

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

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

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

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

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

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

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

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

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

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

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

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

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

			/* write trace to output file */
			efwrite(ps,sizeof(float),n1s,outfp);
		}
	}
}
Exemplo n.º 29
0
long recvPar3D(recPar *rec, float sub_x0, float sub_y0, float sub_z0, 
	float dx, float dy, float dz, long nx, long ny, long nz)
{
	float   *xrcv1, *xrcv2, *yrcv1, *yrcv2, *zrcv1, *zrcv2;
	long    i, ix, iy, ir, verbose;
	float   dxrcv, dyrcv, dzrcv, *dxr, *dyr, *dzr;
	float   rrcv, dphi, oxrcv, oyrcv, ozrcv, arcv;
	double  circ, h, a, b, e, s, xr, yr, zr, dr, srun, phase;
	float   xrange, yrange, zrange, sub_x1, sub_y1, sub_z1;
	long    Nx1, Nx2, Ny1, Ny2, Nz1, Nz2, Ndx, Ndy, Ndz, iarray, nrec, nh;
	long    nxrcv, nyrcv, nzrcv, ncrcv, nrcv, ntrcv, *nlxrcv, *nlyrcv;
	float   *xrcva, *yrcva, *zrcva;
	char*   rcv_txt;
	FILE    *fp;

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

    /* Calculate Model Dimensions */
    sub_x1=sub_x0+(nx-1)*dx;
    sub_y1=sub_y0+(ny-1)*dy;
    sub_z1=sub_z0+(nz-1)*dz;

/* Compute how many receivers are defined and then allocate the receiver arrays */

    /* Receiver Array */
    nxrcv=countparval("xrcva");
    nyrcv=countparval("yrcva");
    nzrcv=countparval("zrcva");
    if (nxrcv!=nzrcv) verr("Number of receivers in array xrcva (%li), yrcva (%li), zrcva(%li) are not equal",nxrcv,nyrcv,nzrcv);
    if (verbose&&nxrcv) vmess("Total number of array receivers: %li",nxrcv);

    /* Linear Receiver Arrays */
	Nx1 = countparval("xrcv1");
	Nx2 = countparval("xrcv2");
	Ny1 = countparval("yrcv1");
	Ny2 = countparval("yrcv2");
	Nz1 = countparval("zrcv1");
	Nz2 = countparval("zrcv2");
    if (Nx1!=Nx2) verr("Number of receivers starting points in 'xrcv1' (%li) and number of endpoint in 'xrcv2' (%li) are not equal",Nx1,Nx2);
    if (Ny1!=Ny2) verr("Number of receivers starting points in 'yrcv1' (%li) and number of endpoint in 'yrcv2' (%li) are not equal",Ny1,Ny2);
    if (Nz1!=Nz2) verr("Number of receivers starting points in 'zrcv1' (%li) and number of endpoint in 'zrcv2' (%li) are not equal",Nz1,Nz2);
    if (Nx1!=Ny2) verr("Number of receivers starting points in 'xrcv1' (%li) and number of endpoint in 'yrcv2' (%li) are not equal",Nx1,Ny2);
    if (Nx1!=Nz2) verr("Number of receivers starting points in 'xrcv1' (%li) and number of endpoint in 'zrcv2' (%li) are not equal",Nx1,Nz2);

    rec->max_nrec=nyrcv*nxrcv;

	/* no receivers are defined use default linear array of receivers on top of model */
    if (!rec->max_nrec && Nx1==0) Nx1=1; // Default is to use top of model to record data
    if (!rec->max_nrec && Ny1==0) Ny1=1;

    if (Nx1) {
        /* Allocate Start & End Points of Linear Arrays */
        xrcv1=(float *)malloc(Nx1*sizeof(float));
        xrcv2=(float *)malloc(Nx1*sizeof(float));
        yrcv1=(float *)malloc(Nx1*sizeof(float));
        yrcv2=(float *)malloc(Nx1*sizeof(float));
        zrcv1=(float *)malloc(Nx1*sizeof(float));
        zrcv2=(float *)malloc(Nx1*sizeof(float));
        if (!getparfloat("xrcv1",xrcv1)) xrcv1[0]=sub_x0;
        if (!getparfloat("xrcv2",xrcv2)) xrcv2[0]=sub_x1;
        if (!getparfloat("yrcv1",yrcv1)) yrcv1[0]=sub_y0;
        if (!getparfloat("yrcv2",yrcv2)) yrcv2[0]=sub_y1;
        if (!getparfloat("zrcv1",zrcv1)) zrcv1[0]=sub_z0;
        if (!getparfloat("zrcv2",zrcv2)) zrcv2[0]=zrcv1[0];

		/* check if receiver arrays fit into model */
		for (iarray=0; iarray<Nx1; iarray++) {
			xrcv1[iarray] = MAX(sub_x0,      xrcv1[iarray]);
			xrcv1[iarray] = MIN(sub_x0+nx*dx,xrcv1[iarray]);
			xrcv2[iarray] = MAX(sub_x0,      xrcv2[iarray]);
			xrcv2[iarray] = MIN(sub_x0+nx*dx,xrcv2[iarray]);
			
			yrcv1[iarray] = MAX(sub_y0,      yrcv1[iarray]);
			yrcv1[iarray] = MIN(sub_y0+ny*dy,yrcv1[iarray]);
			yrcv2[iarray] = MAX(sub_y0,      yrcv2[iarray]);
			yrcv2[iarray] = MIN(sub_y0+ny*dy,yrcv2[iarray]);

			zrcv1[iarray] = MAX(sub_z0,      zrcv1[iarray]);
			zrcv1[iarray] = MIN(sub_z0+nz*dz,zrcv1[iarray]);
			zrcv2[iarray] = MAX(sub_z0,      zrcv2[iarray]);
			zrcv2[iarray] = MIN(sub_z0+nz*dz,zrcv2[iarray]);
		}

        /* Crop to Fit Model */
/* Max's addtion still have to check if it has the same fucntionality */
        for (iarray=0;iarray<Nx1;iarray++) {
            if (xrcv1[iarray]<sub_x0) {
                if (xrcv2[iarray]<sub_x0) {
                    verr("Linear array %li outside model bounds",iarray);
                }
				else {
                    vwarn("Cropping element %li of 'xrcv1' (%f) to model bounds (%f)",iarray,xrcv1[iarray],sub_x0);
                    xrcv1[iarray]=sub_x0;
                }
            } 
			else if (xrcv1[iarray] > sub_x1) {
                verr("Linear array %li outside model bounds",iarray);
            }
            if ( (xrcv2[iarray] < xrcv1[iarray]) ) {
                verr("Ill defined linear array %li, 'xrcv1' (%f) greater than 'xrcv2' (%f)",iarray,xrcv1[iarray],xrcv2[iarray]);
            }
			else if (xrcv2[iarray]>sub_x1) {
                vwarn("Cropping element %li of 'xrcv2' (%f) to model bounds (%f)",iarray,xrcv2[iarray],sub_x1);
                xrcv2[iarray]=sub_x1;
            }

            if (yrcv1[iarray]<sub_y0) {
                if (yrcv2[iarray]<sub_y0) {
                    verr("Linear array %li outside model bounds",iarray);
                }
				else {
                    vwarn("Cropping element %li of 'yrcv1' (%f) to model bounds (%f)",iarray,yrcv1[iarray],sub_y0);
                    yrcv1[iarray]=sub_y0;
                }
            } 
			else if (yrcv1[iarray] > sub_y1) {
                verr("Linear array %li outside model bounds",iarray);
            }
            if ( (yrcv2[iarray] < yrcv1[iarray]) ) {
                verr("Ill defined linear array %li, 'yrcv1' (%f) greater than 'yrcv2' (%f)",iarray,yrcv1[iarray],yrcv2[iarray]);
            }
			else if (yrcv2[iarray]>sub_y1) {
                vwarn("Cropping element %li of 'yrcv2' (%f) to model bounds (%f)",iarray,yrcv2[iarray],sub_y1);
                yrcv2[iarray]=sub_y1;
            }

            if (zrcv1[iarray] < sub_z0) {
                if (zrcv2[iarray] < sub_z0) {
                    verr("Linear array %li outside model bounds",iarray);
                }
				else {
               		vwarn("Cropping element %li of 'zrcv1' (%f) to model bounds (%f)",iarray,zrcv1[iarray],sub_z0);
                	zrcv1[iarray]=sub_z0;
                }
            }
			else if (zrcv1[iarray] > sub_z1) {
                verr("Linear array %li outside model bounds",iarray);
            }
            if ( (zrcv2[iarray] < zrcv1[iarray]) ) {
                verr("Ill defined linear array %li, 'zrcv1' (%f) greater than 'zrcv2' (%f)",iarray,zrcv1[iarray],zrcv2[iarray]);
            }
			else if (zrcv2[iarray]>sub_z1) {
                vwarn("Cropping element %li of 'xrcv2' (%f) to model bounds (%f)",iarray,zrcv2[iarray],sub_z1);
                zrcv2[iarray]=sub_z1;
            }
        }

        /* Get Sampling Rates */
		Ndx = countparval("dxrcv");
		Ndy = countparval("dyrcv");
		Ndz = countparval("dzrcv");

		dxr = (float *)malloc(Nx1*sizeof(float));
		dyr = (float *)malloc(Nx1*sizeof(float));
		dzr = (float *)malloc(Nx1*sizeof(float));
		if(!getparfloat("dxrcv", dxr)) dxr[0]=dx;
		if(!getparfloat("dyrcv", dyr)) dyr[0]=dy;
		if(!getparfloat("dzrcv", dzr)) dzr[0]=0.0;
		if ( (Ndx<=1) && (Ndy<=1) && (Ndz==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dyr[i] = dyr[0];
				dzr[i] = dzr[0];
			}
			Ndx=1;
            Ndy=1;
			Ndz=1;
		}
		else if ( (Ndz==1) && (Ndx==0) && (Ndy==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dyr[i] = dyr[0];
				dzr[i] = dzr[0];
			}
			Ndz=1;
            Ndy=1;
			Ndx=1;
		}
		else { /* make sure that each array has dzrcv or dxrcv defined for each line or receivers */
			if (Ndx!=Ndz) {
				verr("Number of 'dxrcv' (%li) is not equal to number of 'dzrcv' (%li) or 1",Ndx,Ndz);
			}
			if (Ndx!=Ndy) {
				verr("Number of 'dxrcv' (%li) is not equal to number of 'dyrcv' (%li) or 1",Ndx,Ndy);
			}
			if (Ndx!=Nx1 && Ndx!=1) {
				verr("Number of 'dxrcv' (%li) is not equal to number of starting points in 'xrcv1' (%li) or 1",Ndx,Nx1);
			}
			if (Ndy!=Ny1 && Ndy!=1) {
				verr("Number of 'dyrcv' (%li) is not equal to number of starting points in 'yrcv1' (%li) or 1",Ndy,Ny1);
			}
		}

		/* check consistency of receiver steps */
        for (iarray=0; iarray<Ndx; iarray++) {
            if (dxr[iarray]<0) {
				dxr[i]=dx;
				vwarn("'dxrcv' element %li (%f) is less than zero, changing it to %f'",iarray,dxr[iarray],dx);
			}
        }
        for (iarray=0; iarray<Ndy; iarray++) {
            if (dyr[iarray]<0) {
				dyr[i]=dx;
				vwarn("'dyrcv' element %li (%f) is less than zero, changing it to %f'",iarray,dyr[iarray],dy);
			}
        }
        for (iarray=0;iarray<Ndz;iarray++) {
            if (dzr[iarray]<0) {
				dzr[iarray]=dz;
				vwarn("'dzrcv' element %li (%f) is less than zero, changing it to %f'",iarray,dzr[iarray],dz);
			}
        }
        for (iarray=0;iarray<Ndx;iarray++){
            if (dxr[iarray]==0 && dzr[iarray]==0) {
                xrcv2[iarray]=xrcv1[iarray];
				dxr[iarray]=1.;
                vwarn("'dxrcv' element %li & 'dzrcv' element 1 are both 0.",iarray+1);
                vmess("Placing 1 receiver at (%li,%li)",xrcv1[iarray],zrcv1[iarray]);
            }
        }
        for (iarray=0;iarray<Ndx;iarray++){
            if (xrcv1[iarray]==xrcv2[iarray] && dxr[iarray]!=0) {
                dxr[iarray]=0.;
                vwarn("Linear array %li: 'xrcv1'='xrcv2' and 'dxrcv' is not 0. Setting 'dxrcv'=0",iarray+1);
            }
        }
        for (iarray=0;iarray<Ndx;iarray++){
            if (yrcv1[iarray]==yrcv2[iarray] && dyr[iarray]!=0) {
                dyr[iarray]=0.;
                vwarn("Linear array %li: 'yrcv1'='yrcv2' and 'dyrcv' is not 0. Setting 'dyrcv'=0",iarray+1);
            }
        }
        for (iarray=0;iarray<Ndx;iarray++){
            if (zrcv1[iarray]==zrcv2[iarray] && dzr[iarray]!=0.){
                dzr[iarray]=0.;
                vwarn("Linear array %li: 'zrcv1'='zrcv2' and 'dzrcv' is not 0. Setting 'dzrcv'=0",iarray+1);
            }
        }

        /* Calculate Number of Receivers */
		nrcv = 0;
        nlxrcv=(long *)malloc(Nx1*sizeof(long));
        nlyrcv=(long *)malloc(Nx1*sizeof(long));
		for (iarray=0; iarray<Nx1; iarray++) {
			xrange = (xrcv2[iarray]-xrcv1[iarray]); 
			yrange = (yrcv2[iarray]-yrcv1[iarray]); 
			zrange = (zrcv2[iarray]-zrcv1[iarray]); 
			if (dxr[iarray] != 0.0 && dyr[iarray] != 0.0) {
				nlxrcv[iarray] = NINT(fabs(xrange/dxr[iarray]))+1;
				nlyrcv[iarray] = NINT(fabs(yrange/dyr[iarray]))+1;
			}
			else if (dxr[iarray] != 0.0) {
				nlxrcv[iarray] = NINT(fabs(xrange/dxr[iarray]))+1;
				nlyrcv[iarray] = 1;
			}
			else if (dyr[iarray] != 0.0) {
				nlxrcv[iarray] = 1;
				nlyrcv[iarray] = NINT(fabs(yrange/dyr[iarray]))+1;
			}
			else {
				if (dzr[iarray] == 0) {
					verr("For receiver array %li: receiver distance dzrcv is not given", iarray);
				}
				nlxrcv[iarray] = NINT(fabs(zrange/dzr[iarray]))+1;
				nlyrcv[iarray] = NINT(fabs(zrange/dzr[iarray]))+1;
			}
            nrcv+=nlyrcv[iarray]*nlxrcv[iarray];
		}

        /* Calculate Number of Receivers */
        if (verbose) vmess("Total number of linear array receivers: %li",nrcv);
        if (!nrcv) {
            free(xrcv1);
            free(xrcv2);
            free(yrcv1);
            free(yrcv2);
            free(zrcv1);
            free(zrcv2);
            free(dxr);
            free(dyr);
            free(dzr);
            free(nlxrcv);
            free(nlyrcv);
        }
        rec->max_nrec+=nrcv;
    } 
	else {
		nrcv=0;
	}

/* allocate the receiver arrays */

    /* Total Number of Receivers */
    if (verbose) vmess("Total number of receivers: %li",rec->max_nrec);

    /* Allocate Arrays */
    rec->x  = (long *)calloc(rec->max_nrec,sizeof(long));
    rec->y  = (long *)calloc(rec->max_nrec,sizeof(long));
    rec->z  = (long *)calloc(rec->max_nrec,sizeof(long));
    rec->xr = (float *)calloc(rec->max_nrec,sizeof(float));
    rec->yr = (float *)calloc(rec->max_nrec,sizeof(float));
    rec->zr = (float *)calloc(rec->max_nrec,sizeof(float));

/* read in the receiver postions */

	nrec=0;
    /* Receiver Array */
	if (nxrcv != 0 && nyrcv != 0) {
		/* receiver array is defined */
		xrcva = (float *)malloc(nxrcv*sizeof(float));
		yrcva = (float *)malloc(nxrcv*sizeof(float));
		zrcva = (float *)malloc(nxrcv*sizeof(float));
		getparfloat("xrcva", xrcva);
		getparfloat("yrcva", yrcva);
		getparfloat("zrcva", zrcva);
		for (iy=0; iy<nyrcv; iy++) {
            for (ix=0; ix<nxrcv; ix++) {
                rec->xr[nrec+iy*nxrcv+ix] = xrcva[ix]-sub_x0;
                rec->yr[nrec+iy*nxrcv+ix] = yrcva[iy]-sub_y0;
                rec->zr[nrec+iy*nxrcv+ix] = zrcva[ix]-sub_z0;
                rec->x[nrec+iy*nxrcv+ix] = NINT((xrcva[ix]-sub_x0)/dx);
                rec->y[nrec+iy*nxrcv+ix] = NINT((yrcva[iy]-sub_y0)/dy);
                rec->z[nrec+iy*nxrcv+ix] = NINT((zrcva[ix]-sub_z0)/dz);
                if (verbose>4) fprintf(stderr,"Receiver Array: xrcv[%li]=%f yrcv[%li]=%f zrcv=%f\n", ix, rec->xr[nrec+ix]+sub_x0, iy, rec->yr[nrec+ix]+sub_y0, rec->zr[nrec+ix]+sub_z0);
            }
        }
		free(xrcva);
		free(yrcva);
		free(zrcva);
		nrec += nyrcv*nxrcv;
	}

    /* Linear Receiver Arrays */
    if (nrcv!=0) {
		xrcv1 = (float *)malloc(Nx1*sizeof(float));
		xrcv2 = (float *)malloc(Nx1*sizeof(float));
		yrcv1 = (float *)malloc(Nx1*sizeof(float));
		yrcv2 = (float *)malloc(Nx1*sizeof(float));
		zrcv1 = (float *)malloc(Nx1*sizeof(float));
		zrcv2 = (float *)malloc(Nx1*sizeof(float));
		
		if(!getparfloat("xrcv1", xrcv1)) xrcv1[0]=sub_x0;
		if(!getparfloat("xrcv2", xrcv2)) xrcv2[0]=(nx-1)*dx+sub_x0;
		if(!getparfloat("yrcv1", yrcv1)) yrcv1[0]=sub_y0;
		if(!getparfloat("yrcv2", yrcv2)) yrcv2[0]=(ny-1)*dy+sub_y0;
		if(!getparfloat("zrcv1", zrcv1)) zrcv1[0]=sub_z0;
		if(!getparfloat("zrcv2", zrcv2)) zrcv2[0]=zrcv1[0];		
		
		Ndx = countparval("dxrcv");
		Ndy = countparval("dyrcv");
		Ndz = countparval("dzrcv");

		dxr = (float *)malloc(Nx1*sizeof(float));
		dyr = (float *)malloc(Nx1*sizeof(float));
		dzr = (float *)malloc(Nx1*sizeof(float));
		if(!getparfloat("dxrcv", dxr)) dxr[0]=dx;
		if(!getparfloat("dyrcv", dyr)) dyr[0]=dy;
		if(!getparfloat("dzrcv", dzr)) dzr[0]=0.0;
		if ( (Ndx<=1) && (Ndy<=1) && (Ndz==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dyr[i] = dyr[0];
				dzr[i] = dzr[0];
			}
			Ndx=1;
            Ndy=1;
		}
        else if ( (Ndx<=1) && (Ndy==0) && (Ndz==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dyr[i] = dyr[0];
				dzr[i] = dzr[0];
			}
			Ndx=1;
		}
        else if ( (Ndy<=1) && (Ndx==0) && (Ndz==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dyr[i] = dyr[0];
				dzr[i] = dzr[0];
			}
			Ndy=1;
		}
		else if ( (Ndz==1) && (Ndy==0) && (Ndx==0) ){ /* default values are set */
			for (i=1; i<Nx1; i++) {
				dxr[i] = dxr[0];
				dyr[i] = dyr[0];
				dzr[i] = dzr[0];
			}
			Ndz=1;
		}
		else { /* make sure that each array has dzrcv or dxrcv defined for each line or receivers */
			if (Ndx>1) assert(Ndx==Nx1);
			if (Ndy>1) assert(Ndy==Ny1);
			if (Ndz>1) assert(Ndz==Nx1);
		}
		
		/* check if receiver arrays fit into model */
		for (iarray=0; iarray<Nx1; iarray++) {
			xrcv1[iarray] = MAX(sub_x0,      xrcv1[iarray]);
			xrcv1[iarray] = MIN(sub_x0+nx*dx,xrcv1[iarray]);
			xrcv2[iarray] = MAX(sub_x0,      xrcv2[iarray]);
			xrcv2[iarray] = MIN(sub_x0+nx*dx,xrcv2[iarray]);

			yrcv1[iarray] = MAX(sub_y0,      yrcv1[iarray]);
			yrcv1[iarray] = MIN(sub_y0+ny*dy,yrcv1[iarray]);
			yrcv2[iarray] = MAX(sub_y0,      yrcv2[iarray]);
			yrcv2[iarray] = MIN(sub_y0+ny*dy,yrcv2[iarray]);
			
			zrcv1[iarray] = MAX(sub_z0,      zrcv1[iarray]);
			zrcv1[iarray] = MIN(sub_z0+nz*dz,zrcv1[iarray]);
			zrcv2[iarray] = MAX(sub_z0,      zrcv2[iarray]);
			zrcv2[iarray] = MIN(sub_z0+nz*dz,zrcv2[iarray]);
		}

		/* calculate receiver array and store into rec->x,y,z */

		for (iarray=0; iarray<Nx1; iarray++) {
			xrange = (xrcv2[iarray]-xrcv1[iarray]); 
			yrange = (yrcv2[iarray]-yrcv1[iarray]); 
			zrange = (zrcv2[iarray]-zrcv1[iarray]); 
			if (dxr[iarray] != 0.0) {
				nrcv = nlyrcv[iarray]*nlxrcv[iarray];
				dxrcv = dxr[iarray];
				dyrcv = yrange/(nlyrcv[iarray]-1);
				dzrcv = zrange/(nlxrcv[iarray]-1);
				if (dyrcv != dyr[iarray]) {
					vwarn("For receiver array %li: calculated dyrcv=%f given=%f", iarray, dyrcv, dyr[iarray]);
					vwarn("The calculated receiver distance %f is used", dyrcv);
				}
				if (dzrcv != dzr[iarray]) {
					vwarn("For receiver array %li: calculated dzrcv=%f given=%f", iarray, dzrcv, dzr[iarray]);
					vwarn("The calculated receiver distance %f is used", dzrcv);
				}
			}
            else if (dyr[iarray] != 0.0) {
				nrcv = nlyrcv[iarray]*nlxrcv[iarray];
				dxrcv = xrange/(nlxrcv[iarray]-1);
				dyrcv = dyr[iarray];
				dzrcv = zrange/(nlxrcv[iarray]-1);
				if (dxrcv != dxr[iarray]) {
					vwarn("For receiver array %li: calculated dxrcv=%f given=%f", iarray, dxrcv, dxr[iarray]);
					vwarn("The calculated receiver distance %f is used", dxrcv);
				}
				if (dzrcv != dzr[iarray]) {
					vwarn("For receiver array %li: calculated dzrcv=%f given=%f", iarray, dzrcv, dzr[iarray]);
					vwarn("The calculated receiver distance %f is used", dzrcv);
				}
			}
			else {
				if (dzr[iarray] == 0) {
					verr("For receiver array %li: receiver distance dzrcv is not given", iarray);
				}
				nrcv = nlyrcv[iarray]*nlxrcv[iarray];
				dxrcv = xrange/(nrcv-1);
				dyrcv = yrange/(nrcv-1);
				dzrcv = dzr[iarray];
				if (dxrcv != dxr[iarray]) {
					vwarn("For receiver array %li: calculated dxrcv=%f given=%f", iarray, dxrcv, dxr[iarray]);
					vwarn("The calculated receiver distance %f is used", dxrcv);
				}
				if (dyrcv != dyr[iarray]) {
					vwarn("For receiver array %li: calculated dyrcv=%f given=%f", iarray, dyrcv, dyr[iarray]);
					vwarn("The calculated receiver distance %f is used", dyrcv);
				}
			}

			// calculate coordinates
			for (iy=0; iy<nlyrcv[iarray]; iy++) {
                for (ix=0; ix<nlxrcv[iarray]; ix++) {
                    rec->xr[nrec]=xrcv1[iarray]-sub_x0+ix*dxrcv;
                    rec->yr[nrec]=yrcv1[iarray]-sub_y0+iy*dyrcv;
                    rec->zr[nrec]=zrcv1[iarray]-sub_z0+ix*dzrcv;

                    rec->x[nrec]=NINT((rec->xr[nrec])/dx);
                    rec->y[nrec]=NINT((rec->yr[nrec])/dy);
                    rec->z[nrec]=NINT((rec->zr[nrec])/dz);
                    nrec++;
                }
            }
		}
		free(xrcv1);
		free(xrcv2);
		free(yrcv1);
		free(yrcv2);
		free(zrcv1);
		free(zrcv2);
		free(dxr);
		free(dyr);
		free(dzr);
        free(nlxrcv);
        free(nlyrcv);
	}

    rec->n=rec->max_nrec;
	return 0;
}
Exemplo n.º 30
0
int
main(int argc, char **argv)
{
	int nt;		/* number of time samples per trace */
	float dt;	/* time sampling interval */
	float ft;	/* time of first sample */
	int it;		/* time sample index */
	int cdpmin;	/* minimum cdp to process */
	int cdpmax;	/* maximum cdp to process */
	float dx;	/* cdp sampling interval */
	int nx;		/* number of cdps to process */
	int nxfft;	/* number of cdps after zero padding for fft */
	int nxpad;	/* minimum number of cdps for zero padding */
	int ix;		/* cdp index, starting with ix=0 */
	int noffmix;	/* number of offsets to mix */
	float *tdmo;	/* times at which rms velocities are specified */
	float *vdmo;	/* rms velocities at times specified in tdmo */
	float gamma;	/* upgoing to downging velocity ratio */
	float *zoh=NULL;/* tabulated z/h */
	float *boh=NULL;/* tabulated b/h */
	int ntable;	/* number of tabulated zoh and boh */
	float sdmo;	/* DMO stretch factor */
	float s1;	/* DMO stretch factor */
	float s2;	/* DMO stretch factor */
	float temps;	/* temp value used in excahnging s1 and s2 */
	int flip;	/* apply negative shifts and exchange s1 and s2 */
	float sign; 	/* + if flip=0, negative if flip=1 */
	int ntdmo;	/* number tnmo values specified */
	int itdmo;	/* index into tnmo array */
	int nvdmo;	/* number vnmo values specified */
	float fmax;	/* maximum frequency */
	float *vrms;	/* uniformly sampled vrms(t) */
	float **p;	/* traces for one offset - common-offset gather */
	float **q;	/* DMO-corrected and mixed traces to be output */
	float offset;	/* source-receiver offset of current trace */
	float oldoffset;/* offset of previous trace */
	int noff;	/* number of offsets processed in current mix */
	int ntrace;	/* number of traces processed in current mix */
	int itrace;	/* trace index */
	int gottrace;	/* non-zero if an input trace was read */
	int done;	/* non-zero if done */
	int verbose;	/* =1 for diagnostic print */
	FILE *hfp;	/* file pointer for temporary header file */

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

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

	/* get parameters */
	if (!getparint("cdpmin",&cdpmin)) err("must specify cdpmin");
	if (!getparint("cdpmax",&cdpmax)) err("must specify cdpmax");
	if (cdpmin>cdpmax) err("cdpmin must not be greater than cdpmax");
	if (!getparfloat("dxcdp",&dx)) err("must specify dxcdp");
	if (!getparint("noffmix",&noffmix)) err("must specify noffmix");
	ntdmo = countparval("tdmo");
	if (ntdmo==0) ntdmo = 1;
	tdmo = ealloc1float(ntdmo);
	if (!getparfloat("tdmo",tdmo)) tdmo[0] = 0.0;
	nvdmo = countparval("vdmo");
	if (nvdmo==0) nvdmo = 1;
	if (nvdmo!=ntdmo) err("number of tdmo and vdmo must be equal");
	vdmo = ealloc1float(nvdmo);
	if (!getparfloat("vdmo",vdmo)) vdmo[0] = 1500.0;
	for (itdmo=1; itdmo<ntdmo; ++itdmo)
		if (tdmo[itdmo]<=tdmo[itdmo-1])
			err("tdmo must increase monotonically");
	if (!getparfloat("gamma",&gamma)) gamma = 0.5;
	if (!getparint("ntable",&ntable)) ntable = 1000;
	if (!getparfloat("sdmo",&sdmo)) sdmo = 1.0;
	if (!getparint("flip",&flip)) flip=0;
	if (flip)
		sign = -1.0;
	else
		sign = 1.0;
	if (!getparfloat("fmax",&fmax)) fmax = 0.5/dt;
	if (!getparint("verbose",&verbose)) verbose=0;
        checkpars();

	/* allocate and generate tables of b/h and z/h if gamma not equal 1 */
	if(gamma != 1.0){
		zoh=alloc1float(ntable);
		boh=alloc1float(ntable);
		table(ntable, gamma, zoh, boh);
	}

	/* make uniformly sampled rms velocity function of time */
	vrms = ealloc1float(nt);
	mkvrms(ntdmo,tdmo,vdmo,nt,dt,ft,vrms);

	/* determine number of cdps to process */
	nx = cdpmax-cdpmin+1;

	/* allocate and zero common-offset gather p(t,x) */
	nxpad = 0.5*ABS(offset/dx);
	nxfft = npfar(nx+nxpad);
	p = ealloc2float(nt,nxfft+2);
	for (ix=0; ix<nxfft; ++ix)
		for (it=0; it<nt; ++it)
			p[ix][it] = 0.0;

	/* allocate and zero offset mix accumulator q(t,x) */
	q = ealloc2float(nt,nx);
	for (ix=0; ix<nx; ++ix)
		for (it=0; it<nt; ++it)
			q[ix][it] = 0.0;

	/* open temporary file for headers */
	hfp = tmpfile();

	/* initialize */
	oldoffset = offset;
	gottrace = 1;
	done = 0;
	ntrace = 0;
	noff = 0;

	/* get DMO stretch/squeeze factors s1 and s2 */
	stretchfactor (sdmo,gamma,&s1,&s2);
	if(flip) {
		temps = s1;
		s1 = s2;
		s2 = temps;
	}

	/* print useful information if requested */
	if (verbose)fprintf(stderr,"stretching factors: s1=%f s2=%f\n",s1,s2);

	/* loop over traces */
	do {
		/* if got a trace, determine offset */
		if (gottrace) offset = tr.offset;

		/* if an offset is complete */
		if ((gottrace && offset!=oldoffset) || !gottrace) {

			/* do dmo for old common-offset gather */
			dmooff(oldoffset,fmax,nx,dx,nt,dt,ft,vrms,p,
			gamma,boh,zoh,ntable,s1,s2,sign);

			/* add dmo-corrected traces to mix */
			for (ix=0; ix<nx; ++ix)
				for (it=0; it<nt; ++it)
					q[ix][it] += p[ix][it];

			/* count offsets in mix */
			noff++;

			/* free space for old common-offset gather */
			free2float(p);

			/* if beginning a new offset */
			if (offset!=oldoffset) {

				/* allocate space for new offset */
				nxpad = 0.5*ABS(offset/dx);
				nxfft = npfar(nx+nxpad);
				p = ealloc2float(nt,nxfft+2);
				for (ix=0; ix<nxfft; ++ix)
					for (it=0; it<nt; ++it)
						p[ix][it] = 0.0;
			}
		}

		/* if a mix of offsets is complete */
		if (noff==noffmix || !gottrace) {

			/* rewind trace header file */
			efseeko(hfp, (off_t) 0,SEEK_SET);

			/* loop over all output traces */
			for (itrace=0; itrace<ntrace; ++itrace) {

				/* read trace header and determine cdp index */
				efread(&tro,HDRBYTES,1,hfp);

				/* get dmo-corrected data */
				memcpy((void *) tro.data,
					(const void *) q[tro.cdp-cdpmin],
					nt*sizeof(float));

				/* write output trace */
				puttr(&tro);
			}

			/* report */
			if (verbose)
				fprintf(stderr,"\tCompleted mix of "
					"%d offsets with %d traces\n",
					noff,ntrace);

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

			/* rewind trace header file */
			efseeko(hfp, (off_t) 0,SEEK_SET);

			/* reset number of offsets and traces in mix */
			noff = 0;
			ntrace = 0;

			/* zero offset mix accumulator */
			for (ix=0; ix<nx; ++ix)
				for (it=0; it<nt; ++it)
					q[ix][it] = 0.0;
		}

		/* if cdp is within range to process */
		if (tr.cdp>=cdpmin && tr.cdp<=cdpmax) {

			/* save trace header and update number of traces */
			efwrite(&tr,HDRBYTES,1,hfp);
			ntrace++;

			/* remember offset */
			oldoffset = offset;

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

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

	} while (!done);

	return(CWP_Exit());
}