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

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

        fputtr(fileptr, &tr);
    }
    erewind(headerptr);
}
Exemple #3
0
main(int argc, char **argv)
{

	segytrace tr;

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


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

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

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

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

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

	return 0;

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

/* parameters fetching */

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

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

/* processing */ 

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

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

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



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

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

	/* Main loop over traces */
	do {

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

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

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

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

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

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

	free(count);
	free(plots);

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

	/* get required parameters */

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

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

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


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

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

	/* loop over traces */
	do {

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

	/* output last gather */
	if(nfold>0) {
		for(ix=0;ix<nfold;ix++) {
			if(op==1) {
				scale = 1./fold[iofo[ix]];
			} else {
				scale = fold[iofo[ix]];
			}
			for(it=0;it<nt;it++) 
				tro.data[it] = data[it+ix*nt]*scale; 
			bcopy(header+ix*HDRBYTES,(char*)&tro,HDRBYTES);
			fputtr(outfp,&tro);
		}
	}
	
	return EXIT_SUCCESS;
}
Exemple #6
0
int main(int argc, char **argv)
{
  int verbose;
  time_t start,finish;
  double elapsed_time;
  int ix,nt,nx,nx_out;
  float dt,dh,hmin,hmax;
  float *h,*h_out;
  float **din,**dout,**din_tw,**dout_tw;
  int *ih,*ih_out;
  int padt,padx;
  int Ltw,Dtw;   
  int twstart;
  float taper;
  int itw,Itw,Ntw,niter;
  float fmin,fmax;

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

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

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

  dout  = ealloc2float(nt,nx_out);

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

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

  /* ***********************************************************************
  output data
  *********************************************************************** */
  rewind(stdin);
  for (ix=0;ix<nx_out;ix++){ 
    memcpy((void *) tr.data,(const void *) dout[ix],nt*sizeof(float));
    tr.offset=(int) h_out[ix];
    tr.ntr=nx_out;
    tr.ns=nt;
    tr.dt = NINT(dt*1000000.);
    tr.tracl = ix+1;
    tr.tracr = ix+1;    
    fputtr(stdout,&tr);
  }
  
  /******** End of output **********/
  finish=time(0);
  elapsed_time=difftime(finish,start);
  fprintf(stderr,"Total time required: %6.2fs\n", elapsed_time);
  
  free1float(h);
  free1float(h_out);
  free2float(din);
  free2float(dout);
  free1int(ih);
  free1int(ih_out);
  free2float(din_tw);
  free2float(dout_tw);
  
  return EXIT_SUCCESS;
}
Exemple #7
0
int
main(int argc, char **argv)
{
	char plotcmd[BUFSIZ];	/* build command for popen		*/
	FILE *plotfp;		/* fp for plot data			*/
	float d1;		/* time/depth sample rate 		*/
	float d2;		/* trace/dx sample rate 		*/
	float f1;		/* tmin/zmin				*/
	float f2;		/* tracemin/xmin			*/
	int nt;			/* number of samples on trace		*/
	int ntr;		/* number of traces			*/
	int verbose;		/* verbose flag				*/
	cwp_Bool seismic;	/* is this seismic data?		*/
	cwp_Bool have_ntr=cwp_false;/* is ntr known from header or user?	*/
	cwp_String mode;	/* sumax mode parameter			*/
	char *tmpdir;		/* directory path for tmp files		*/
	cwp_Bool istmpdir=cwp_false;/* true for user given path		*/

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

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

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

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

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

	if (!getparfloat("f2", &f2)) {
		if      (tr.f2)     f2 = tr.f2;
		else if (tr.tracr)  f2 = (float) tr.tracr;
		else if (tr.tracl)  f2 = (float) tr.tracl;
		else if (seismic)   f2 = 1.0;
		else 		    f2 = 0.0;
	}
	
	if (getparint("n2", &ntr) || getparint("ntr", &ntr)) have_ntr = cwp_true;
	if (!getparstring("mode", &mode)) mode = "max";

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

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

		bindir = (char *) emalloc(BUFSIZ);

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


	/* Allocate trace buffer */
	if (!have_ntr) {
		/* Store traces and headers in tmpfile while getting a count */
		if (verbose) {
			warn(" n2 not getparred or header field ntr not set");
			warn(" ....    counting traces");
		}

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

		/* Loop over input data and read to temporary file */
		ntr = 0;
		do {
			   ++ntr;
			   efwrite(&tr, 1, HDRBYTES, headerfp);
			   efwrite(tr.data, FSIZE, nt, tracefp);
		   } while (gettr(&tr));

	}

	/* System call to xgraph */
	sprintf(plotcmd, "%ssumax output=binary mode=%s | %sxgraph n=%d", 
			 bindir, mode, bindir, ntr);
	for (--argc, ++argv; argc; --argc, ++argv) {
		if ( 
			strncmp(*argv, "output=", 7)  &&
			strncmp(*argv, "mode=", 5)  &&
			strncmp(*argv, "n=", 2) &&
			strncmp(*argv, "n2=", 3) &&/*xgraph honors n2,nplot*/
			strncmp(*argv, "nplot=", 6) ) { 

			strcat(plotcmd, " ");   /* put a space between args */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
			strcat(plotcmd, *argv); /* add the arg */
			strcat(plotcmd, "\"");  /* user quotes are stripped */
		}
	}


	/* Open pipe; write data to plotcmd */
	plotfp = epopen(plotcmd, "w");
	
	if (!have_ntr) {
		rewind(headerfp);
		rewind(tracefp);
		{ register int itr;
		for (itr = 0; itr < ntr; ++itr) {
			efread(&tr, 1, HDRBYTES, headerfp);
			efread(tr.data, FSIZE, nt, tracefp);
			fputtr(plotfp, &tr);
		}
		}
	} else { /* pump out traces and let sumax and psimage do the work */
                do {
                        fputtr(plotfp,&tr);
                } while (gettr(&tr));
        }


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

	return EXIT_SUCCESS;
}
Exemple #8
0
main(int argc, char **argv)
{
    string ggfile;
    FILE *infp=stdin,*outfp=stdout,*gfp;
    int idz, nz, rsampz;
    int nzg, jz;
    float dz, dzint,z; 	
    float fzg, dzg; 
    float *gamgrid, *g2m1, *mout2, *dataint, *zint, *zx , *mute;
    float *g2;
    int oldcdp, oldoffset,ncdpg;
    float cdpming, dcdpg;
    float smute, osmute, odz, odz2, z0, fz;
    int mutes, newgamma ;
    int indz, indx, nzint, iz;
    float temp, res, zzint, odzint, str;
    int ierr;


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

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

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

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

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

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

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

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

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

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

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

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


    do { 

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

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

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

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

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

    fclose(outfp);
    

    return EXIT_SUCCESS;
}
Exemple #9
0
void intout(float *xi, float *xo, float *yo, char *hdrs, int nxi, int nxo,
		int nt, FILE *outfp, int extrap,
		String hdtp, int index) {

	segytrace tro, tr1, tr2;
	float tmp, res, ftmp;
	int one=1, indx, itmp, ix, it;
	float sx, gx, sy, gy, mx, my, dd, ofo;
	Value val;

 
	/* output interpolated result */
	for(ix=0;ix<nxo;ix++) {
		for(it=0;it<nt;it++) tro.data[it]=yo[it+ix*nt];
		tmp = xo[ix];
		bisear_(&nxi,&one,xi,&tmp,&indx);
		if(tmp<=xi[0]) {
			itmp = 1;
			bcopy(hdrs,(char*)&tro,HDRBYTES);
		} else if(tmp>=xi[nxi-1]) {
			itmp = nxi-1;
			bcopy(hdrs+(nxi-1)*HDRBYTES,
				(char*)&tro,HDRBYTES);
		} else {
			if(indx==nxi) indx=indx-1;
			itmp = indx;
			if(abs(tmp-xi[itmp-1])<abs(tmp-xi[itmp])) {
				bcopy(hdrs+(itmp-1)*HDRBYTES,
					(char*)&tro,HDRBYTES);
			} else {
				bcopy(hdrs+itmp*HDRBYTES,
					(char*)&tro,HDRBYTES);
			}
		}

		bcopy(hdrs+(itmp-1)*HDRBYTES,(char*)&tr1,
			HDRBYTES);
		bcopy(hdrs+itmp*HDRBYTES,(char*)&tr2,
			HDRBYTES);
		res = (tmp-xi[itmp-1])/(xi[itmp]-xi[itmp-1]);

		ftmp  = tr1.cdp + res*(tr2.cdp-tr1.cdp) + .5;
		tro.cdp = ftmp;
		ftmp = tr1.mute + res*(tr2.mute-tr1.mute) + .5; 
		tro.mute = ftmp;

		ftmp = tr1.sx + res*(tr2.sx-tr1.sx) + .5; 
		tro.sx = ftmp;
		ftmp = tr1.sy + res*(tr2.sy-tr1.sy) + .5; 
		tro.sy = ftmp;
		ftmp = tr1.gx + res*(tr2.gx-tr1.gx) + .5; 
		tro.gx = ftmp;
		ftmp = tr1.gy + res*(tr2.gy-tr1.gy) + .5; 
		tro.gy = ftmp;

		/* if offsets are the same sign, linearly interpolate
		   to get the output offset; otherwise, use the
		   closest trace's offset */

		if(tr1.offset*tr2.offset >= 0.) {
			ftmp = tr1.offset + res*(tr2.offset-tr1.offset) + .5; 
			tro.offset = ftmp;
		} 

		if(abs(tmp-xi[itmp-1])<0.1 || abs(tmp-xi[itmp])<0.1) {
			tro.duse = 1;
		} else {
			tro.duse = 2;
		}

		changeval(hdtp,&val,xo[ix]);
		puthval(&tro, index, &val);

		/* need to adjust (x,y) of source and receiver, with
		the new offset for pre-stack migration */

		sx = tro.sx;
		sy = tro.sy;
		gx = tro.gx;
		gy = tro.gy;
		mx = (sx+gx)/2.;
		my = (sy+gy)/2.;
		dd = sqrt((sx-gx)*(sx-gx)+(sy-gy)*(sy-gy));
		if(tro.scalco>1) {
			dd = dd * tro.scalco;
		} else if(tro.scalco<0) {
			dd =  - dd / tro.scalco;
		}
		ofo = tro.offset;
		if(ofo<0) ofo = - ofo;
		if (dd>0.) {
			tro.sx = mx+(tro.sx-mx)*ofo/dd;
			tro.gx = mx+(tro.gx-mx)*ofo/dd;
			tro.sy = my+(tro.sy-my)*ofo/dd;
			tro.gy = my+(tro.gy-my)*ofo/dd;
		} else {
			tro.sx = mx-ofo/2;
			tro.gx = mx-ofo/2;
			tro.sy = my;
			tro.gy = my;
		}

		if(xi[0]-tmp>0.1 || tmp-xi[nxi-1]>0.1 ) {
			if(extrap==0) {
				tro.trid = 2;
				bzero(tro.data,nt*sizeof(float));
			}
		}

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

/* subroutine kmigs */

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

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

        char chost[MAXHOSTNAMELEN] ;
	int nxdip;

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

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

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

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

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

	if (notrace==1) goto skipmig; 

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

	/* initialize mtrace */
	*mtrace = 0;

	do {

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

/* output traces */

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

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

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

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

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

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

	fclose(infp);
	fclose(outfp);

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

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

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

/* parameters fetching */

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

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

/* processing */ 

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

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


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


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

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

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

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

	/* free space */
	free(work);

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

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

	long ltmp;

	segychdr ch;
    	segybhdr bh;
	usghed usgh;


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

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

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

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

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

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

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

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



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

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

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

	file2g(pxfp);
	file2g(pyfp);

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

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

	nsegy = 240+nt*sizeof(float);


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

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

	jy  = -1;

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

        fputhdr(outfp,&ch,&bh);

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

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

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


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


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


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


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

			fputtr(outfp,&tr1);
		}	

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

			/* rewind file */
			rewind(tmpfp);

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

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

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

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

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

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

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

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

	return(CWP_Exit());

}
Exemple #15
0
main(int argc, char **argv)
{
	int nt;			/* number of points on trace		*/
	int databytes;		/* ... in bytes 			*/
	int ntr;		/* number of traces			*/
	string stype;		/* noise type (gauss, flat) as string	*/
	int itype;		/* ... as integer (for use in switch)	*/
	float sn;		/* signal to noise ratio		*/
	unsigned int seed;	/* random number seed			*/
	FILE *hdrfp;		/* fp for header storage file		*/
	FILE *sigfp;		/* fp for data ("signal")		*/
	int nfloats;		/* number of floats in "signal"		*/
	float *noise;		/* noise vector				*/
	float noiscale;		/* scale for noise			*/
	float absmaxsig;	/* absolute maximum in signal		*/
	float noipow;		/* a measure of noise power		*/
	float f1;		/* left lower corner frequency		*/
	float f2;		/* left upper corner frequency		*/
	float f4;		/* right lower corner frequency		*/
	float f3;		/* right upper corner frequency		*/
        char * scrdir;          /* scratch dir to put temporary data set */

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


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

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


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


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

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


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


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


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


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


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


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

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


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

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

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

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

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

	} /* End optional bandlimiting */
		


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


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


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

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

		puttr(&tr);
	  }
	}


	return EXIT_SUCCESS;
}
Exemple #16
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;
}
Exemple #17
0
int
main (int argc, char **argv)
{
	int 	nt,nzt,nxt,nz,nxo,nxs,ns,nx,nr,is,ixo,ixs;
	int 	ls,jtr,mtr,tracl,mzmax;
	off_t nseek;
	float   ft,fzt,fxt,fz,fx,fxo,fs,fxs,dt,dzt,dxt,dz,dx,dxo,ds,dxs,
		ext,ezt,es,ex,ez,xo,s,xs,xg,fpeak;	
	float 	v0,dvz;
	float 	fmax,angmax,offmax,rmax,aperx;
	float **mig,**migi,***ttab,**tb,**pb,**cosb,**sigb,**tsum,**tt;
	
	char *infile="stdin",*outfile="stdout",*ttfile,*jpfile;
	FILE *infp,*outfp,*ttfp,*jpfp;
	Wavelet *w;


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

	/* open input and output files	*/
	if( !getparstring("infile",&infile)) {
		infp = stdin;
	} else  
		if ((infp=fopen(infile,"r"))==NULL)
			err("cannot open infile=%s\n",infile);
	if( !getparstring("outfile",&outfile)) {
		outfp = stdout;
	} else { 
		outfp = fopen(outfile,"w");
	}
	efseeko(infp,(off_t) 0,SEEK_CUR);
	warn("Got A");
	efseeko(outfp,(off_t) 0,SEEK_CUR);
	if( !getparstring("ttfile",&ttfile))
		err("must specify ttfile!\n");
	if ((ttfp=fopen(ttfile,"r"))==NULL)
		err("cannot open ttfile=%s\n",ttfile);
	if( !getparstring("jpfile",&jpfile)) {
		jpfp = stderr;
	} else  
		jpfp = fopen(jpfile,"w");

	/* get information for seismogram traces */
	if (!getparint("nt",&nt)) nt = 501;
	if (!getparfloat("dt",&dt)) dt = 0.004;
	if (!getparfloat("ft",&ft)) ft = 0.0;
	if (!getparfloat("fmax",&fmax)) fmax = 1.0/(4*dt);
	fpeak = 0.2/dt;
	if (!getparint("nxs",&nxs)) nxs = 101;
	if (!getparfloat("dxs",&dxs)) dxs = 15;
	if (!getparfloat("fxs",&fxs)) fxs = 0.0;
	if (!getparint("nxo",&nxo)) nxo = 1;
	if (!getparfloat("dxo",&dxo)) dxo = 50;
	if (!getparfloat("fxo",&fxo)) fxo = 0.0;
	
	/* get traveltime table parameters	*/
	if (!getparint("nxt",&nxt)) err("must specify nxt!\n");
	if (!getparfloat("fxt",&fxt)) err("must specify fxt!\n");
	if (!getparfloat("dxt",&dxt)) err("must specify dxt!\n");
	if (!getparint("nzt",&nzt)) err("must specify nzt!\n");
	if (!getparfloat("fzt",&fzt)) err("must specify fzt!\n");
	if (!getparfloat("dzt",&dzt)) err("must specify dzt!\n");
	if (!getparint("ns",&ns)) err("must specify ns!\n");
	if (!getparfloat("fs",&fs)) err("must specify fs!\n");
	if (!getparfloat("ds",&ds)) err("must specify ds!\n");
	ext = fxt+(nxt-1)*dxt;
	ezt = fzt+(nzt-1)*dzt;
	es = fs+(ns-1)*ds;

	/* check source and receiver coordinates */
 	for (ixs=0; ixs<nxs; ++ixs) {
		xs = fxs+ixs*dxs;
		for (ixo=0; ixo<nxo; ++ixo) {
			xg = xs+fxo+ixo*dxo;
			if (fs>xs || es<xs || fs>xg || es<xg) 
		err("shot or receiver lie outside of specified (x,z) grid\n");
		}
	} 

	/* get migration section parameters	*/
	if (!getparint("nx",&nx)) err("must specify nx!\n");
	if (!getparfloat("fx",&fx)) err("must specify fx!\n");
	if (!getparfloat("dx",&dx)) err("must specify dx!\n");
	if (!getparint("nz",&nz)) err("must specify nz!\n");
	if (!getparfloat("fz",&fz)) err("must specify fz!\n");
	if (!getparfloat("dz",&dz)) err("must specify dz!\n");
	ex = fx+(nx-1)*dx;
	ez = fz+(nz-1)*dz;
	if(fxt>fx || ext<ex || fzt>fz || ezt<ez) 
		err(" migration section is out of traveltime table!\n");

	if (!getparfloat("v0",&v0)) v0 = 1500;
	if (!getparfloat("dvz",&dvz)) dvz = 0;
	if (!getparfloat("angmax",&angmax)) angmax = 60.;
	if  (angmax<0.00001) err("angmax must be positive!\n");
	mzmax = dx*sin(angmax*PI/180.)/dz;
	if(mzmax<1) mzmax = 1;
	if (!getparfloat("aperx",&aperx)) aperx = 0.5*nxt*dxt;

	if (!getparint("ls",&ls))	ls = 1;
	if (!getparint("mtr",&mtr))	mtr = 100;

	fprintf(jpfp,"\n");
	fprintf(jpfp," Modeling parameters\n");
	fprintf(jpfp," ================\n");
	fprintf(jpfp," infile=%s \n",infile);
	fprintf(jpfp," outfile=%s \n",outfile);
	fprintf(jpfp," ttfile=%s \n",ttfile);
	fprintf(jpfp," \n");
	fprintf(jpfp," nzt=%d fzt=%g dzt=%g\n",nzt,fzt,dzt);
	fprintf(jpfp," nxt=%d fxt=%g dxt=%g\n",nxt,fxt,dxt);
 	fprintf(jpfp," ns=%d fs=%g ds=%g\n",ns,fs,ds);
	fprintf(jpfp," \n");
	fprintf(jpfp," nz=%d fz=%g dz=%g\n",nz,fz,dz);
	fprintf(jpfp," nx=%d fx=%g dx=%g\n",nx,fx,dx);
	fprintf(jpfp," \n");
	fprintf(jpfp," nxs=%d fxs=%g dxs=%g\n",nxs,fxs,dxs);
	fprintf(jpfp," nxo=%d fxo=%g dxo=%g\n",nxo,fxo,dxo);
	fprintf(jpfp," \n");
	
	/* compute reference traveltime and slowness  */
	offmax = MAX(ABS(fxo),ABS(fxo+(nxo-1)*dxo));
	rmax = MAX(es-fxt,ext-fs);
	rmax = MIN(rmax,0.5*offmax+aperx);
	nr = 2+(int)(rmax/dx);
	tb = ealloc2float(nzt,nr);
	pb = ealloc2float(nzt,nr);
	sigb = ealloc2float(nzt,nr);
	cosb = ealloc2float(nzt,nr);
	timeb(nr,nzt,dx,dzt,fzt,dvz,v0,tb,pb,sigb,cosb);

	fprintf(jpfp," nt=%d ft=%g dt=%g fpeak=%g \n",nt,ft,dt,fpeak);
	fprintf(jpfp," v0=%g dvz=%g \n",v0,dvz);
 	fprintf(jpfp," aperx=%g angmax=%g offmax=%g\n",aperx,angmax,offmax);
 	fprintf(jpfp," mtr=%d ls=%d\n",mtr,ls);
	fprintf(jpfp," ================\n");
	fflush(jpfp);

	/* allocate space */
	mig = ealloc2float(nz,nx);
	migi = ealloc2float(nz+2*mzmax,nx);
	ttab = ealloc3float(nzt,nxt,ns);
	tt = ealloc2float(nzt,nxt);
	tsum = ealloc2float(nzt,nxt);


	/* make wavelet */
	makericker(fpeak,dt,&w);

	/* 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;

	fprintf(jpfp," read traveltime tables \n");
	fflush(jpfp);

	/* compute traveltime residual	*/
	for(is=0; is<ns; ++is){
		nseek = (off_t) nxt*nzt*is;
		efseeko(ttfp,nseek*((off_t) sizeof(float)),SEEK_SET);
		fread(ttab[is][0],sizeof(float),nxt*nzt,ttfp);
		s = fs+is*ds;
		resit(nxt,fxt,dxt,nzt,nr,dx,tb,ttab[is],s);		
	}

	fprintf(jpfp," read migration section \n");
	fflush(jpfp);

	/* read migration section	*/
	fread(mig[0],sizeof(float),nx*nz,infp);

	/* integrate migration section for constructing anti-aliasing 
		filter	*/
	integ(mig,nz,dz,nx,mzmax,migi);
                       
	fprintf(jpfp," start synthesis ... \n");
	fprintf(jpfp," \n");
	fflush(jpfp);
	
	jtr = 0;
	/* loop over shots  */
	for (ixs=0,xs=fxs,tracl=0; ixs<nxs; ++ixs,xs+=dxs) {
		/* loop over offsets */
		for (ixo=0,xo=fxo; ixo<nxo; ++ixo,xo+=dxo) {
	    		float as,res;
	    		int is;
			xg = xs+xo; 
			/* set segy trace header parameters */
			tr.tracl = tr.tracr = ++tracl;
			tr.fldr = 1+ixs;
			tr.tracf = 1+ixo;
			tr.offset = NINT(xo);
			tr.sx = NINT(xs);
			tr.gx = NINT(xg);

	    		as = (xs-fs)/ds;
	    		is = (int)as;
			if(is==ns-1) is=ns-2;
			res = as-is;
			if(res<=0.01) res = 0.0;
			if(res>=0.99) res = 1.0;
			sum2(nxt,nzt,1-res,res,ttab[is],ttab[is+1],tsum);

	    		as = (xg-fs)/ds;
	    		is = (int)as;
			if(is==ns-1) is=ns-2;
			res = as-is;
			if(res<=0.01) res = 0.0;
			if(res>=0.99) res = 1.0;
			sum2(nxt,nzt,1-res,res,ttab[is],ttab[is+1],tt);
			sum2(nxt,nzt,1,1,tt,tsum,tsum);
				fflush(jpfp);

			/* make one trace */
			maketrace(tr.data,nt,ft,dt,xs,xg,mig,migi,aperx,
			  nx,fx,dx,nz,fz,dz,mzmax,ls,angmax,v0,fmax,w,
			  tb,pb,sigb,cosb,nr,tsum,nxt,fxt,dxt,nzt,fzt,dzt);
			
			/* write trace */
			fputtr(outfp,&tr);

	        	jtr++;
	        	if((jtr-1)%mtr ==0 ){
				fprintf(jpfp," generated trace %d\n",jtr);
				fflush(jpfp);
	    		}
		}
	}


	fprintf(jpfp," generated %d traces in total\n",jtr);


	fprintf(jpfp," \n");
	fprintf(jpfp," output done\n");
	fflush(jpfp);

	efclose(jpfp);
	efclose(outfp);

	    
	free2float(tsum);
	free2float(tt);
	free2float(pb);
	free2float(tb);
	free2float(cosb);
	free2float(sigb);
	free3float(ttab);
	free2float(mig);
	free2float(migi);

	return(CWP_Exit());
}
Exemple #18
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;
}
Exemple #19
0
int main (int argc, char **argv)
{
	float *rv;	/* array of rock velocity from cfile */
	float *rd;	/* array of rock density from dfile on p knots */
	float *rd1_5;	/* array of rock density from dfile on v knots */
	float *p;	/* pressure */
	float *v;	/* particle velocity */
	float tmax, dt, t0;	/* maximum time , time step,  		*/
				/* time delay for near causal source	*/
	float vmax;		/* maximum rock velocity		*/
	int verbose;		/* is verbose?				*/
	int nz, nt;		/* number of z samples, time samples	*/
	float fz, dz;		/* first sample depth spatial depth	*/
	float sz;		/* source coordinate			*/
	int abs[2];		/* array of absorbing conditions	*/
	int isz;		/* source location index		*/
	float rz;		/* receiver depth */
	int irz;		/* zcoordinate (in samples) of the source */
	int iz, it, itsis;	/* counter */
	int ies;		/* end of source index */
	int press;		/* to choose  between pressure or particle */
				/* velocity */
	float t;		/* time */
	int td=1, zd=1;		/* time and depth decimation */
	segy snapsh, sismo;	/* recording of the seismic field, */
				/*  seismogram */
	char *dfile="";		/* density file name */
	char *wfile="";		/* seismogram file name */
	char *velfile="";	  /* velocity file name */
	char *sfile="";		/* velocity file name */
	float freq=0.0;		/* source center freq */
	float alpha=0.0;	/* source exp		*/
	float epst0=0.0;	/* source first amp ratio */
	int styp;		/* source type */

	FILE *seisfp=stdout;	/* pointer to seismic trace output file */
	FILE *wavefp=NULL;	/* pointer to wave field output file */
	FILE *velocityfp=stdin;	/* pointer to input velocity file */
	FILE *densityfp=NULL;	/* pointer to input density file */


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

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

	/* get required parameters */
	if (!getparint ("nz",&nz)) err("must specify nz ! ");
	if (verbose) warn("nz= %d", nz);

	if (!getparfloat ("tmax",&tmax)) err("must specify tmax ! ");
	if (verbose) warn("tmax= %f", tmax);

	if (!getparfloat("sz", &sz)) err ("must specify sz ! ");
	if (verbose) warn("sz= %f", sz);
	
	

	/* get optional parameters */
	if (!getparint ("nt", &nt)) nt=0; 
	if (verbose) warn("nt= %d", nt);
	if (!getparint ("styp", &styp)) styp=0;
	if (verbose) warn("styp= %d ", styp);
	if (!getparfloat ("dz", &dz)) dz=1;
	if (!getparfloat ("fz", &fz)) fz=0.0;

	/* source coordinates to samples */
	isz=NINT((sz-fz)/dz);
	if (verbose) warn( "source on knot number %d ", isz);


	if (!getparfloat("rz", &rz)) rz=0.0;
	irz = NINT ((rz-fz)/dz);
	if (verbose) warn("receiver depth : %f on knot # %d ", rz, irz);

	if (!getparfloat("freq", &freq)) freq=15.0;
	if (verbose) warn("frequency : %f  Hz",freq);

	getparstring ("velfile", &velfile);
	if (verbose) {
		if (*velfile != '\0' ) warn("Velocity file : %s ",velfile);
		else warn("Velocity file supplied via stdin");
	}

	getparstring ("sfile", &sfile);
	if (verbose) {
		if (*sfile != '\0' ) warn("Output trace file : %s ",sfile);
		else warn("Output trace via stdout");
	}

	getparstring ("dfile", &dfile);
	if (verbose) {
		if (*dfile != '\0' ) warn("Density file : %s ",dfile);
		else warn("No density file supplied ");
	}

	getparstring ("wfile", &wfile);
	if (verbose) {
		if (*wfile != '\0' ) warn("Wave file : %s ",wfile);
		else warn("No wave file requested ");
	}

	if ( NINT((float) nz/((float) zd)) + 1  >SU_NFLTS) {
		warn ("Too many depth points : impossible to output wave field. Increase zd ?");
		*wfile='\0';
	}
	

	/* get absorbing conditions */
	if (!getparint("abs",abs)) {  abs[0]=0; abs[1]=1;  }
	if (verbose) {
		if (abs[0]==1) warn("absorbing condition on top ");
		if (abs[1]==1) warn("absorbing condition on bottom ");
	}
	/* get decimation coefficients */
	if (!getparint("td",&td)) td=1 ;
	if (verbose) warn("time decimation ccoefficent: %d ",td);
	if (!getparint("zd",&zd)) zd=1 ;
	if (verbose) warn("depth decimation ccoefficent: %d ",zd);

	/* choose pressure or particle velocity */
	if (!getparint("press", &press)) press=1 ;
	if ((press != 0) && (press != 1)) err ("press must equal 0 or 1");
	if (verbose) {
		if (press==1) warn( "program will output pressure values");
		else if (press==0) warn( "program will output particle velocity values");
	}
		

	/* allocate space */
	p=alloc1float(nz);
	v=alloc1float(nz);
	rv=alloc1float(nz);
	rd=alloc1float(nz);
	rd1_5=alloc1float(nz);

	/* read velocity file */
	if (*velfile != '\0' ) {
		if ((velocityfp=fopen(velfile,"r"))=='\0') err("cannot open velfile=%s ",velfile);
	}
	if (efread (rv, sizeof(float), nz, velocityfp)!=nz) 
	   err("cannot read %d velocity values ", nz);

	/* read density file  and linearly inderpolate on corrrect location */
	if (*dfile != '\0') {
		if ((densityfp=fopen(dfile,"r"))=='\0') err("cannot open dfile=%s ",dfile);
		if (fread(rd,sizeof(float), nz, densityfp)!=nz) err("error reading dfile %s",dfile);
		fclose(densityfp);
	}
	else for (iz=0; iz<nz; iz++) rd[iz]=2500;
	for (iz=0; iz<nz-1; iz++) rd1_5[iz]=(rd[iz]+rd[iz+1])/2;
	rd1_5[nz-1]=rd[nz-1];

	/* time step computation */
	vmax=0;
	for (iz=0; iz<nz; iz++) if (rv[iz]>vmax) vmax=rv[iz];if (verbose) warn( "vmax= %f ", vmax);
	dt=dz/1.414/vmax/2; if (verbose) warn( "time step dt= %f ", dt);

	/* maximum number of iterations */
	if (nt==0) nt=1+tmax/dt;
	if (verbose) warn( "number of time steps nt= %d ", nt);
	if (NINT( (float) nt/((float)td))+1>SU_NFLTS) err("too many time steps. Increase td ?");

	/* source parameter computation */
	   alpha=2*9.8696*freq*freq;

	/* time shift to get a t0 centered source */

	if ((styp==0) || (styp == 2)) epst0=fabs(source (0, styp, dt, dz, 0, alpha) / 1e4);
	else if (styp==1) epst0=fabs(source (1/sqrt(2*alpha), styp, dt, dz, 0, alpha)) / 1e4;
	if (verbose) warn( "epst0 = %f ", epst0);

	t=tmax+dt;
	do t=t-dt; while (fabs(source(t, styp, dt, dz, 0, alpha))<epst0);
	t0=t;
	ies=2*t/dt;

	if (verbose) warn("time shift t0 = %f s", t0);

/* array initialization */
	for (iz=0; iz<nz; iz++) {  v[iz]=0; p[iz]=0;  }

	if (*wfile != '\0') {
		wavefp=fopen (wfile,"w");
		snapsh.d1=dz*zd; snapsh.f1=fz ; snapsh.ns=nz/zd+1; snapsh.d2=dt*td; snapsh.f2=0; 
		/* snapsh.f2=0 is useless since 0 is the "no value" code for SU headers */
	}
	/* propagation computation */
	itsis=0;
	for (it=0; it<=nt; it++) {
		t=it*dt;
		if (abs[0]==1) p[0]=(p[0]*(1-rv[0]*dt/dz)+2*rd[0]*rv[0]*rv[0]*dt/dz*v[0])/(1+rv[0]*dt/dz);
		else p[0]=0;
		for (iz=1; iz<nz; iz++) p[iz]=p[iz]+rd[iz]*rv[iz]*rv[iz]*dt/dz*(v[iz]-v[iz-1]);
		if (abs[1]!=1) p[nz-1]=0;
		if (it<ies) {
		p[isz]=p[isz]+source(t, styp, dt, dz, t0, alpha);
		}

		for (iz=0; iz<nz-1; iz++) v[iz]=v[iz]+dt/rd1_5[iz]/dz*(p[iz+1]-p[iz]);
		
		if (abs[1] != 1) v[nz-1]=0;
		else
		v[nz-1]=((rd1_5[nz-1]*dz-dt*rd[nz-1]*rv[nz-1])*v[nz-1]-2*dt*p[nz-1])/(rd1_5[nz-1]*dz+dt*rd[nz-1]*rv[nz-1]);

	  if (it % td == 0) {
		   if (press==1) 
			sismo.data[itsis]=p[irz];
		   else
			sismo.data[itsis]=v[irz];
		   itsis++;
		}

		if ((*wfile!='\0') && (it % td == 0)) {
		if (press==1) 
			for (iz=0; iz<nz/zd; ++iz) snapsh.data[iz]=p[iz*zd];
		else
			for (iz=0; iz<nz/zd; ++iz) snapsh.data[iz]=v[iz*zd];

	   	fputtr(wavefp, &snapsh);
		}

	}

	if (*wfile!='\0') fclose (wavefp);

	sismo.dt=td*dt*1e6;
	sismo.ns=itsis;
	sismo.delrt=-t0*1000;
	sismo.trid=TREAL;
	sismo.tracl=1;

	if (*sfile != '\0') seisfp=efopen(sfile,"w");
	fputtr (seisfp, &sismo);
	

return(CWP_Exit());
}
Exemple #20
0
main(int argc, char* argv[] ){

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

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

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

   int len;

   int a;
   int b;

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

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

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

   getparint( "len" ,&len );

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

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

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

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

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

   }else{
      w = len / 2;
   }

   do {

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

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

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

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

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

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

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

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

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

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

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

         k -= j;
         j--;

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

      }

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

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

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

      }

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

      k = 0;
      j = 0;

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

         k += j;

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

      }

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

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

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

   return 0;

}
Exemple #21
0
main(int argc, char **argv)
{
	int nt, ntmax, nx, nz;
	int nzt, nxt, nst;
	float smint, xmint, zmint, dst, dxt, dzt;
	float x0, z0, dx, dz, dt, tmin;
	float ofimin, ofomin, dofo, ofimax, ofomax;
	float ofomini, dcdp;
	int nofo, lt, ntrace, i2p5;
	int nofoi,amptype;
	string ampfile, timefile;
	int iamp, *mtrace;
	FILE *infp, *outfp, *testfp;
	string datain, dataout, datains;
	char **dataini, **dataouti;
	char *dipfile="NULL";
	int im, nm, kofo, lseekout;
	int iofo, ix, ltrace;
	int intps,intpx,intpz,isize;
	int iofpm, intype, *lseekini; 
	int sort, mlimit;
	int dcdpout, fcdpout, tracl;
	int lagc;
        float tpow, aper, apan, apanl, apanr, v0, dxdip, dxtol;
	int lmem, idip, nxdip, llimit;
	float tmp;


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

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

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

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

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

	fclose(infp);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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


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

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



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

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

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


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

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

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

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

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

        kofo = 0;

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

	      if ( nofoi<= 0 ) continue;	

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

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

	}
	wait_dispatched();

	no_migration:

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

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

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

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

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

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

   fprintf(stderr,"KIRMIG COMPLETED for total number of traces =%d \n",ntrace);
	
        return 0;
}