Esempio n. 1
0
int writeSnapTimes(modPar mod, snaPar sna, bndPar bnd, int ixsrc, int izsrc, int itime, float *vx, float *vz, float *tzz, float *txx, float *txz, int verbose)
{
	FILE    *fpvx, *fpvz, *fptxx, *fptzz, *fptxz, *fpp, *fppp, *fpss;
	int append, isnap;
	static int first=1;
	int n1, ibndx, ibndz, ixs, izs, ize, i, j;
	int ix, iz, ix2;
	float *snap, sdx;
	segy hdr;

	if (sna.nsnap==0) return 0;

    ibndx = mod.ioXx;
    ibndz = mod.ioXz;
	n1    = mod.naz;
	sdx   = 1.0/mod.dx;

	if (sna.withbnd) {
		sna.nz=mod.naz;
		sna.z1=0;
		sna.z2=mod.naz-1;
		sna.skipdz=1;

		sna.nx=mod.nax;
		sna.x1=0;
		sna.x2=mod.nax-1;
		sna.skipdx=1;
	}

	/* check if this itime is a desired snapshot time */
	if ( (((itime-sna.delay) % sna.skipdt)==0) && 
		  (itime >= sna.delay) &&
		  (itime <= sna.delay+(sna.nsnap-1)*sna.skipdt) ) {

		isnap = NINT((itime-sna.delay)/sna.skipdt);
		if (verbose) vmess("Writing snapshot(%d) at time=%.4f", isnap+1, itime*mod.dt);
	
		if (first) {
			append=0;
			first=0;
		}
		else {
			append=1;
		}

		if (sna.type.vx)  fpvx  = fileOpen(sna.file_snap, "_svx", append);
		if (sna.type.vz)  fpvz  = fileOpen(sna.file_snap, "_svz", append);
		if (sna.type.p)   fpp   = fileOpen(sna.file_snap, "_sp", append);
		if (sna.type.txx) fptxx = fileOpen(sna.file_snap, "_stxx", append);
		if (sna.type.tzz) fptzz = fileOpen(sna.file_snap, "_stzz", append);
		if (sna.type.txz) fptxz = fileOpen(sna.file_snap, "_stxz", append);
		if (sna.type.pp)  fppp  = fileOpen(sna.file_snap, "_spp", append);
		if (sna.type.ss)  fpss  = fileOpen(sna.file_snap, "_sss", append);
	
		memset(&hdr,0,TRCBYTES);
		hdr.dt     = 1000000*(sna.skipdt*mod.dt);
		hdr.ungpow  = (sna.delay*mod.dt);
		hdr.scalco = -1000;
		hdr.scalel = -1000;
		hdr.sx     = 1000*(mod.x0+ixsrc*mod.dx);
		hdr.sdepth = 1000*(mod.z0+izsrc*mod.dz);
		hdr.fldr   = isnap+1;
		hdr.trid   = 1;
		hdr.ns     = sna.nz;
		hdr.trwf   = sna.nx;
		hdr.ntr    = (isnap+1)*sna.nx;
		hdr.f1     = sna.z1*mod.dz+mod.z0;
		hdr.f2     = sna.x1*mod.dx+mod.x0;
		hdr.d1     = mod.dz*sna.skipdz;
		hdr.d2     = mod.dx*sna.skipdx;
		if (sna.withbnd) {
        	if ( !ISODD(bnd.top)) hdr.f1 = mod.z0 - bnd.ntap*mod.dz;
        	if ( !ISODD(bnd.lef)) hdr.f2 = mod.x0 - bnd.ntap*mod.dx;
        	//if ( !ISODD(bnd.rig)) ;
        	//if ( !ISODD(bnd.bot)) store=1;
		}

/***********************************************************************
* vx velocities have one sample less in x-direction
* vz velocities have one sample less in z-direction
* txz stresses have one sample less in z-direction and x-direction
***********************************************************************/

		snap = (float *)malloc(sna.nz*sizeof(float));

		/* Decimate, with skipdx and skipdz, the number of gridpoints written to file 
		   and write to file. */
		for (ixs=sna.x1, i=0; ixs<=sna.x2; ixs+=sna.skipdx, i++) {
			hdr.tracf  = i+1;
			hdr.tracl  = isnap*sna.nx+i+1;
			hdr.gx     = 1000*(mod.x0+ixs*mod.dx);
			ix = ixs+ibndx;
			ix2 = ix+1;

			izs = sna.z1+ibndz;
			ize = sna.z2+ibndz;

			if (sna.withbnd) {
				izs = 0;
				ize = sna.z2;
				ix = ixs;
				ix2 = ix;
				if (sna.type.vz || sna.type.txz) izs = -1;
        		if ( !ISODD(bnd.lef)) hdr.gx = 1000*(mod.x0 - bnd.ntap*mod.dx);
			}

			if (sna.type.vx) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = vx[ix2*n1+iz];
				}
				traceWrite(&hdr, snap, sna.nz, fpvx);
			}
			if (sna.type.vz) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = vz[ix*n1+iz+1];
				}
				traceWrite(&hdr, snap, sna.nz, fpvz);
			}
			if (sna.type.p) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = tzz[ix*n1+iz];
				}
				traceWrite(&hdr, snap, sna.nz, fpp);
			}
			if (sna.type.tzz) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = tzz[ix*n1+iz];
				}
				traceWrite(&hdr, snap, sna.nz, fptzz);
			}
			if (sna.type.txx) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = txx[ix*n1+iz];
				}
				traceWrite(&hdr, snap, sna.nz, fptxx);
			}
			if (sna.type.txz) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = txz[ix2*n1+iz+1];
				}
				traceWrite(&hdr, snap, sna.nz, fptxz);
			}
			/* calculate divergence of velocity field */
			if (sna.type.pp) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = sdx*((vx[(ix+1)*n1+iz]-vx[ix*n1+iz])+
									(vz[ix*n1+iz+1]-vz[ix*n1+iz]));
				}
				traceWrite(&hdr, snap, sna.nz, fppp);
			}
			/* calculate rotation of velocity field */
			if (sna.type.ss) {
				for (iz=izs, j=0; iz<=ize; iz+=sna.skipdz, j++) {
					snap[j] = sdx*((vx[ix*n1+iz]-vx[ix*n1+iz-1])-
									(vz[ix*n1+iz]-vz[(ix-1)*n1+iz]));
				}
				traceWrite(&hdr, snap, sna.nz, fpss);
			}

		}

		if (sna.type.vx) fclose(fpvx);
		if (sna.type.vz) fclose(fpvz);
		if (sna.type.p) fclose(fpp);
		if (sna.type.txx) fclose(fptxx);
		if (sna.type.tzz) fclose(fptzz);
		if (sna.type.txz) fclose(fptxz);
		if (sna.type.pp) fclose(fppp);
		if (sna.type.ss) fclose(fpss);

		free(snap);
	}

	return 0;
}
Esempio n. 2
0
int main(int argc, char *argv[])
{
	FILE    *shot_file, *vel_file, *out_file, *beam_file;
	size_t  nread, bytes, size, trace_sz, size_out;
	int     verbose,  method, ntraces, verb_root;
	int     nxv, nyv, nzv, binary_file, dstep, id, id1, id2;
	int     d, nt, ndepth, i, j, conjg, conjgs, mode, out_su;
	int     ntap, tap_opt, order, McC, oplx, oply, fine, MB;
	int     stackmigr, imc, area, ixmin, ixmax, iymin, iymax, ns;
	int     nfft, nfreq, nw_high, nw_low, nw, sx, sy, ix, iy;
	int     npages_w, sxy, iw, one_shot, traces_shot, sign, is; 
	int     traces_read_in, nxy, fd, nx, ny, num_threads, nel, oper_opt;
	int		fldr_w, power_of_2, beam_su, nterms, filter_inc, beam;
	Area    shot_area;
	float   alpha, weight, scl, sclw;
	float   fmin, fmax, dt;
	float   *tot_beam, *beams, scale;
	float   *velocity, weights, tshift, zrcv;
	float   xvmin, yvmin, zvmin, dxv, dyv, dzv, vmin, vmax;
	float   dw, df, om, dtw, tdw, t_w, tr, ti;
	double  t0, t1, t2, t3, t_migr=0, t_io=0, t_table=0, t_init=0;
	double  t_comm=0;
	complex *rec_all, *rec_field, *rec;
	char    *file_vel, *file_in, *file_out, *file_beam, *file_table;
	char    *tmp_dir, sys_call[256];
	segy *hdr;
	int     npes, pe, root_pe=0, nlw, maxlw, *freq_index, fdist, ipe;
#ifdef MPI
	int *nlwcounts, *recvcounts, *displacements;
	int nlw_tag;
	complex  *gath_rec_field;
	MPI_Status status;
	MPI_Request request;

	MPI_Init( &argc, &argv );
	MPI_Comm_size( MPI_COMM_WORLD, &npes );
	MPI_Comm_rank( MPI_COMM_WORLD, &pe );
#else
	npes = 1;
	pe   = 0;
#endif

	t0 = wallclock_time();

/* Read in parameters */

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

	if(!getparstring("file_in", &file_in)) file_in=NULL;
	if(!getparstring("file_vel", &file_vel)) file_vel=NULL; 
	if(!getparstring("file_out", &file_out)) file_out=NULL;
	if(!getparstring("file_beam", &file_beam)) file_beam=" ";
	if(!getparstring("file_table", &file_table)) file_table=NULL;
	if(!getparstring("tmp_dir", &tmp_dir)) tmp_dir="/tmp";
	if(!getparfloat("fmin", &fmin)) fmin = 0.0;
	if(!getparfloat("fmax", &fmax)) fmax = 45.0;
	if(!getparint("mode", &mode)) mode = 1;
	if(!getparint("ntap", &ntap)) ntap = 0;
	if(!getparint("tap_opt", &tap_opt)) tap_opt = 1;
	if(!getparint("method", &method)) method = 1;
	if(!getparint("conjg", &conjg)) conjg = 0;
	if(!getparint("conjgs", &conjgs)) conjgs = 0;
	if(!getparint("area", &area)) area = 0;
	if(!getparint("oplx", &oplx)) oplx = 25;
	if(!getparint("oply", &oply)) oply = oplx;
	if(!getparint("order", &order)) order = 13;
	if(!getparint("McC", &McC)) McC = 1;
	if(!getparint("oper_opt", &oper_opt)) oper_opt = 1;
	if(!getparint("nterms", &nterms)) nterms = 1;
	if(!getparint("filter_inc", &filter_inc)) filter_inc = 1;
	if(!getparfloat("alpha", &alpha)) alpha = 65.0;
	if(!getparfloat("weight", &weight)) weight = 5e-5;
	if(!getparfloat("weights", &weights)) weights = 1e-2;
	if(!getparint("fine", &fine)) fine = 2;
	if(!getparint("beam", &beam)) beam = 0;
	if(!getparint("verbose", &verbose)) verbose = 0;
	
	if(!ISODD(oplx)) oplx += 1;
	if(!ISODD(oply)) oply += 1;
	if(conjg)  conjg  = -1; else  conjg = 1;
	if(conjgs)  conjgs  = -1; else  conjgs = 1;
	if(mode >= 0) mode = 1;
	if(mode < 0) mode = -1;
	assert(McC <= 2 && McC >= 1);
	assert(method <= 4 && method >= 1);
	assert(file_vel != NULL);
	assert(file_out != NULL);
	out_su = (strstr(file_out, ".su")!=NULL);
	beam_su = (strstr(file_beam, ".su")!=NULL);
    if (verbose && pe==root_pe) verb_root=verbose;
    else verb_root = 0;

	t1 = wallclock_time(); t_init += t1-t0;

	/* Clean up 'old' velocity files */
	    
	sprintf(sys_call,"rm -rf %s/velocity*.bin\n",tmp_dir);
	system(sys_call);
#ifdef MPI
	MPI_Barrier(MPI_COMM_WORLD);
#endif

/* Open velocity file and determine the size of the file */

	openVelocityFile(file_vel, &vel_file, &shot_area, verb_root);

#ifdef MPI
	MPI_Barrier(MPI_COMM_WORLD);
#endif
	xvmin = shot_area.xmin;
	yvmin = shot_area.ymin;
	zvmin = shot_area.zmin;
	nxv   = shot_area.nx;
	nyv   = shot_area.ny;
	nzv   = shot_area.nz;
	dxv   = shot_area.dx;  
	dyv   = shot_area.dy;
	dzv   = shot_area.dz;
	nxy   = shot_area.sxy;


	if(!getparfloat("zrcv", &zrcv)) zrcv = zvmin+(nzv-1)*dzv;
	ndepth = NINT((zrcv-zvmin)/dzv);
	if(!getparint("dstep", &dstep)) dstep = MIN(5, ndepth);
	if(!getparfloat("vmin", &vmin)) vmin = 1500;
	if(!getparfloat("vmax", &vmax)) vmax = 4800;


/* Open file_in file and read first header */
	
	hdr = (segy *)calloc(1,sizeof(segy));
	if (file_in == NULL) shot_file = stdin;
	else shot_file = fopen( file_in, "r" );
	assert( shot_file );
	nread = fread( hdr, 1, TRCBYTES, shot_file );
	assert (nread == TRCBYTES);

	fseek ( shot_file, 0, SEEK_END );
	bytes    = ftell(shot_file); 
	nt       = hdr[0].ns;
	dt       = 1e-6*hdr[0].dt;
	trace_sz = sizeof(float)*nt+TRCBYTES;
	ntraces  = (int) (bytes/trace_sz);
	nfft     = optncr(nt);
	nfreq    = nfft/2 + 1;
	df       = 1.0/(nfft*dt);
	dw       = 2.*M_PI*df;
	nw_high  = MIN( (int)(fmax/df), nfreq );
	nw_low   = MAX( (int)((fmin)/df), 1 );
	nw       = nw_high - nw_low + 1;
	sx       = hdr[0].sx;
	sy       = hdr[0].sy;
	if (hdr[0].scalco < 0) scl = 1.0/fabs(hdr[0].scalco);
	else if (hdr[0].scalco == 0) scl = 1.0;
	else scl = hdr[0].scalco;

	t2 = wallclock_time(); t_io += t2-t1;

/*======= compute frequency distribution for multiple CPU's ========*/

	fdist = 0;
	maxlw = ceil((float)nw/(float)npes);
	freq_index = (int *)malloc(maxlw*sizeof(int));
	nlw = frequency_distribution(nw_low, nw, npes, pe, maxlw, 
		freq_index, fdist );

#ifdef MPI
	if( verbose ) {
		/* print out all the frequencies for each process */
		MPI_Barrier(MPI_COMM_WORLD);
		for( ipe=0; ipe<npes; ipe++ ) {
			if( pe == ipe ) {
				fprintf(stderr, "pe=%d:\tf[%d] = df*{", pe, nlw );
				if( nlw > 0 )
				for( iw=0; iw<nlw; iw++ )
					fprintf(stderr, " %d", freq_index[iw] );
				fprintf( stderr, " }\n" );
				fflush(stderr);
			}
			MPI_Barrier(MPI_COMM_WORLD);
		}
	}
	if (npes == 1) nlw = nw;
	nlwcounts = (int *)malloc(npes*sizeof(int));
	recvcounts = (int *)malloc(npes*sizeof(int));
	displacements = (int *)malloc(npes*sizeof(int));
	nlw_tag = 1;
	if (pe == root_pe) {
		displacements[0] = 0;
		nlwcounts[0] = nlw;
		for( ipe=1; ipe<npes; ipe++ ) {
			MPI_Recv(&nlwcounts[ipe], 1, MPI_INT, ipe, nlw_tag, 
				MPI_COMM_WORLD, &status);
			displacements[ipe] = displacements[ipe-1]+nlwcounts[ipe-1];
		}
	}
	else {
		MPI_Send(&nlw, 1, MPI_INT, root_pe, nlw_tag, MPI_COMM_WORLD);
	}
#else
	nlw = nw;
#endif

	fmin = MAX(0,-df + df*freq_index[0]);
	fmax =  df + df*freq_index[nlw-1];

	assert( fmax < 1.0/(2.0*dt) ); /* Nyguist in time */
	assert( (2.0*fmax)/vmin < 1.0/dxv ); /* Nyguist in space */
	assert( (2.0*fmax)/vmin < 1.0/dyv ); /* Nyguist in space */

	size = (size_t)nlw*nxy*sizeof(complex);
	if (verb_root) {
		fprintf(stderr," minimum velocity = %.2f\n", vmin);
		fprintf(stderr," maximum velocity = %.2f\n", vmax);
		MB = 1024*1024;
		fprintf(stderr,"\n    DATA INFORMATION\n");
		fprintf(stderr," nw = %d\n", nw);
		fprintf(stderr," fmin = %.3f fmax = %.3f\n", nw_low*df, nw_high*df);
		fprintf(stderr," dt = %.4f nt = %d nfft = %d\n", dt, nt, nfft);
		fprintf(stderr," size of rec_field = %ld Mbytes\n", size/MB);
		size_out = (size_t)(nt)*(size_t)(nxy)*sizeof(float);
		if (out_su) size_out += (TRCBYTES*nxy);
		fprintf(stderr," size of output file = %ld Mbytes\n", size_out/MB);
	}

	/* Open beam file if beam == 1 */

    if (beam && pe == root_pe) {
		beam_file = fopen( file_beam, "w+" );
		assert( beam_file );
	}
	t1 = wallclock_time(); t_init += t1-t2;

/* Calculate operator tables */

	if (method == 1) {
		tablecalc_2D(oplx, oply, nxv, dxv, nyv, dyv, dzv, alpha, fmin, fmax,
			vmin, vmax, df, weight, fine, oper_opt, file_table, verb_root);
	} 
	else if (method == 2) {
		tablecalc_1D(order, nxv, dxv, dzv, alpha, fmin, fmax, vmin, vmax, df,
			fine, oper_opt, verb_root);
	}
	t2 = wallclock_time(); t_table = t2-t1;
	if (verb_root) 
		fprintf(stderr," time to calculate tables      : %.3f s.\n", t_table);

/* ============ INITIALIZE AND CHECK PARAMETERS =============== */

/* allocate rec field to zero and distribute along machine */

	rec_field = (complex *)calloc(nlw*nxy, sizeof(complex));
	assert(rec_field != NULL);
	velocity = (float *)malloc(dstep*nxy*sizeof(float));
	assert(velocity != NULL);
	if (beam) {
		beams = (float *)calloc(dstep*nxy, sizeof(float));
		assert(beams != NULL);
#ifdef MPI
		tot_beam = (float *)calloc(dstep*nxy, sizeof(float));
		assert(tot_beam != NULL);
#endif 
	}

#ifdef MPI
	if (pe == root_pe) {
		gath_rec_field = (complex *)calloc(nxy*nw,sizeof(complex));
		assert(gath_rec_field != NULL);
	}
#endif

	one_shot    = 1;
	traces_shot = 0;
	traces_read_in = 0;
	ixmin = nxv-1; ixmax = 0;
	iymin = nxv-1; iymax = 0;
	t1 = wallclock_time(); t_init += t1-t2;

	fseek(shot_file, 0, SEEK_SET);

	read_FFT_DataFile(shot_file, rec_field, shot_area, nfft, nlw, 
		freq_index[0], &traces_read_in, &traces_shot, 
		&ixmin, &ixmax, &iymin, &iymax, &sx, &sy, conjgs, verb_root);

	t2 = wallclock_time(); t_io += t2-t1;

	if (verb_root) 
		fprintf(stderr," time to initialize migration  : %.3f s.\n", t1-t0);


/* Loop over input traces */

	is = 0;
	while (one_shot) {
		t1 = wallclock_time(); 

		if (verb_root) {
			fprintf(stderr,"\n    EXTRAPOLATION INFORMATION\n");
			fprintf(stderr," source position (x,y) : %.2f, %.2f\n", 
				sx*scl, sy*scl);
			fprintf(stderr," number of traces in shot : %d\n", traces_shot);
			fprintf(stderr," traces done = %d to do %d\n", 
				traces_read_in-traces_shot, ntraces-traces_read_in+traces_shot);
			fprintf(stderr," shot region is      x:%d-%d        y:%d-%d\n", 
				ixmin, ixmax, iymin, iymax);
		}
		
	/* determine aperture to be extrapolated */

		if (area>0) {
			ixmin = MAX(0,ixmin-area);
			ixmax = MIN(nxv-1,ixmax+area);
			iymin = MAX(0,iymin-area);
			iymax = MIN(nyv-1,iymax+area);
		}
		else {
			ixmin = 0;
			iymin = 0;
			ixmax = nxv-1;
			iymax = nyv-1;
		}
		nx = ixmax-ixmin+1;
		ny = iymax-iymin+1;

		shot_area.ixmin = ixmin;
		shot_area.ixmax = ixmax;
		shot_area.iymin = iymin;
		shot_area.iymax = iymax;
		shot_area.dx    = dxv;
		shot_area.dy    = dyv;
		shot_area.dz    = dzv;
		shot_area.nx    = nxv;
		shot_area.ny    = nyv;
		shot_area.sxy   = nxy;
	
		if (verb_root) {
			fprintf(stderr," work area is x:%d-%d (%d) y:%d-%d (%d)\n",
				ixmin, ixmax, nx, iymin, iymax, ny);
		}

		t2 = wallclock_time(); t_init += t2-t1;

		/* write beam for depth=0 */
		if (beam)  {
			scale = 1.0/(float)(nw);
			for (iw=0; iw<nlw; iw++) {
				rec = (complex*) (rec_field + iw*nxy);
				for (ix = 0; ix < nxy; ix++) {
					beams[ix] += sqrt(rec[ix].r*rec[ix].r+rec[ix].i*rec[ix].i)*scale;
				}
			}
			t1 = wallclock_time(); t_init += t1-t2;
#ifdef MPI
			MPI_Reduce(beams, tot_beam, nxy, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD);
#else
			tot_beam = beams;
#endif
			t2 = wallclock_time(); t_comm += t2-t1;

			/* write image to output file */
			if (pe == root_pe) {
				write_ImageFile(beam_file, tot_beam, shot_area, is, 0, beam_su, verbose);
			}
			t1 = wallclock_time(); t_io += t1-t2;
		}


	/* Start of depth loop */

		for (d=0; d<ndepth; d+=dstep) {
			t1 = wallclock_time();
			id1 = d;
			id2 = MIN(id1+dstep, ndepth);
			nel = (id2-id1)*nxy;

			/* Read dstep depth slices */

			for (id=id1,i=0; id<id2; id++,i++) {
				readVelocitySlice(vel_file, &velocity[i*nxy], id, nyv, nxv);
			}
			t2 = wallclock_time(); t_io += t2-t1;

			if (verb_root > 1) {
				fprintf(stderr," extrapolating from depth level ");
				fprintf(stderr,"%d (%.2f) to %d (%.2f) \n",
				id1, zvmin+dzv*id1, id2, zvmin+dzv*id2);
			}

			if (beam) memset(&beams[0], 0, nxy*dstep*sizeof(float));
			for (iw=0; iw<nlw; iw++) {
				om = freq_index[iw]*dw;
				rec = (complex*) (rec_field + iw*nxy);

				for (id=id1,i=0; id<id2; id++,i++) {

					/* Extrapolation */
					xwExtr3d(rec, &velocity[i*nxy], vmin, oplx, oply,
						order, McC, om, nterms, filter_inc, ntap, tap_opt,
						&shot_area, mode, method);

					if (beam) {
						for (ix = 0; ix < nxy; ix++) {
							beams[i*nxy+ix] += sqrt(rec[ix].r*rec[ix].r+rec[ix].i*rec[ix].i)*scale;
						}
					}

				} /* end of depth loop */
			} /* end of frequency loop */
			t1 = wallclock_time(); t_migr += t1-t2;

			if (beam) {
#ifdef MPI
				MPI_Reduce(beams, tot_beam, dstep*nxy, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD);
#else
				tot_beam = beams;
#endif

				t3 = wallclock_time(); t_comm += t3-t1;

				/* write beam to output file */

				if (pe == root_pe) {
					for (id=id1,i=0; id<id2; id++,i++) {
						write_ImageFile(beam_file, &tot_beam[i*nxy], shot_area,
							is, id, beam_su, verbose);
					}
				}
				t2 = wallclock_time(); t_io += t2-t3;
			}

		} /* end of outer (dstep) depth loop */

		t2 = wallclock_time();

		/* communicate data from all PE's to root_pe */

#ifdef MPI
		fflush(stderr);
		if (pe == root_pe) {
			displacements[0] = 0;
			recvcounts[0] = nlw*nxy*2;
			for( ipe=1; ipe<npes; ipe++ ) {
				recvcounts[ipe] = nlwcounts[ipe]*nxy*2;
				displacements[ipe] = displacements[ipe-1]+recvcounts[ipe-1];
			}
		}
		MPI_Gatherv(rec_field, nxy*nlw*2, MPI_FLOAT, gath_rec_field, recvcounts,
			displacements, MPI_FLOAT, root_pe, MPI_COMM_WORLD);

		if (pe == root_pe) {
			rec_all = gath_rec_field;
		}
#else 
		rec_all = rec_field;
#endif

		t1 = wallclock_time(); t_comm += t1-t2;

		if (pe == root_pe) {
			/* Write modelling result to output file */
			if (verb_root) 
				fprintf(stderr," End of depth loop, writing data.\n");

			if (is == 0) 
				out_file = fopen( file_out, "w+" ); 
			else 
				out_file = fopen( file_out, "a" ); 

			assert( out_file );

			write_FFT_DataFile(out_file, rec_all, shot_area, (is+1),  
				nt, nfft, nw, nw_low, dt, out_su, conjg, verb_root);

			fclose(out_file);
		}


	/* Read next shot record */

		if (traces_read_in == ntraces) {
			one_shot = 0;
		}
		else {
			read_FFT_DataFile(shot_file, rec_field, shot_area, nfft, 
				nlw, freq_index[0], &traces_read_in, &traces_shot,
				&ixmin, &ixmax, &iymin, &iymax, &sx, &sy, conjgs, verb_root);
		}
		is++;

		t2 = wallclock_time(); t_io += t2-t1;

		if (verb_root) {
			fprintf(stderr," subtime for extrapolation : %.3f s.\n", t_migr);
			fprintf(stderr," subtime for io            : %.3f s.\n", t_io);
			fprintf(stderr," subtime for communication : %.3f s.\n\n", t_comm);
		}

	} /* end of while loop over input traces */

	free(velocity);
	free(hdr);
	free(rec_field);
	fclose(vel_file);
	if (beam) {
		if (pe == root_pe) fclose(beam_file);
		free(beams);
#ifdef MPI
		free(tot_beam);
#endif
	}

/* Write total image result to output file */

	fclose(shot_file);

	t2 = wallclock_time(); t_io += t2-t1;

/* clean temporary velocity files */

	sprintf(sys_call,"rm -rf %s/velocity%d.bin\n",tmp_dir, getpid());
	system(sys_call);

/* print the timing results */

	if (verb_root) {
		fprintf(stderr,"Time for total job        : %.3f s.\n", t2-t0);
		fprintf(stderr,"  time for extrapolation  : %.3f s.\n", t_migr);
		fprintf(stderr,"  time for tables         : %.3f s.\n", t_table);
		fprintf(stderr,"  time for io             : %.3f s.\n", t_io);
		fprintf(stderr,"  time for communication  : %.3f s.\n", t_comm);
		fprintf(stderr,"  time for initialization : %.3f s.\n", t_init);
	}

#ifdef MPI
	MPI_Barrier(MPI_COMM_WORLD);
	if (pe == root_pe) free(gath_rec_field);
	free(nlwcounts);
	free(recvcounts);
	free(displacements);
	MPI_Finalize();
#endif

	return;
}
Esempio n. 3
0
int
main(int argc, char **argv)
{
	float a, b;		/* powers for amp and phase		*/
	register float *rt=NULL;/* real trace				*/
	register complex *ct=NULL;	/* complex transformed trace		*/
	complex filt;		/* pow'd input at one frequency	 	*/
	int nt;			/* number of points on input trace	*/
	size_t ntsize;		/* nt in bytes				*/
	float dt;		/* sample spacing (secs) on input trace	*/
	int nfft;		/* number of points in nfft		*/
	int nf;		 	/* number of frequencies (incl Nyq)     */
	float onfft;		/* 1 / nfft				*/
	int verbose;		/* flag to get advisory messages	*/
	size_t nzeros;		/* number of padded zeroes in bytes	*/
	cwp_Bool seismic;	/* is this seismic data?		*/
	int ntout, sym;		/* output params			*/
	
	
	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);


	/* Set parameters */
	if (!getparint("verbose", &verbose))	  verbose  =  0;
	if (!getparfloat("a", &a))	  a = 0.0;
	if (!getparfloat("b", &b))	  b = 0.0;
	if (!getparint("sym",&sym)) 	  sym = 0;

	/* Get info from first trace */
	if (!gettr(&tr))	err("can't get first trace");
	seismic = ISSEISMIC(tr.trid);
	if (seismic) {
		if (verbose)	warn("input is seismic data, trid=%d",tr.trid);
		dt = ((double) tr.dt)/1000000.0;
	}
	else {
		if (verbose)	warn("input is not seismic data, trid=%d",tr.trid);
		dt = tr.d1;
	}
	if (!dt)	err("dt or d1 field is zero and not getparred");
	nt = tr.ns;
	ntsize = nt * FSIZE;

	if (!getparint("ntout",&ntout))   ntout=tr.ns;

	/* Set up for fft 
	   extra 2 in nfft is to avoid wrap around */
	nfft = npfaro(nt, LOOKFAC * nt);
	if (nfft >= SU_NFLTS || nfft >= PFA_MAX)
		err("Padded nt=%d -- too big", nfft);

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

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

	
	/* Loop over traces */
	do {
		/* Load trace into rt (zero-padded) */
		memcpy( (void *) rt, (const void *) tr.data, ntsize);
		memset((void *) (rt + nt), 0, nzeros);

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

		/* Apply filter */
		{ register int i;
			for (i = 0; i < nf; ++i) {

				filt = dopow(ct[i], a, b);
				ct[i] = cmul(ct[i], filt);

				/* symmetric output: flip sign of odd values */
				if (sym){
					if (ISODD(i)) {
						ct[i].r = -ct[i].r;
						ct[i].i = -ct[i].i;
					}
				}

			}
		}

		/* Invert */
		pfacr(-1, nfft, ct, rt);

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

		puttr(&tr);

	} while (gettr(&tr));


	return(CWP_Exit());
}
int bdIsOdd(T a)
{
	assert(a);
	return ISODD(a->digits[0]);
}
Esempio n. 5
0
main(int argc, char **argv)
{
	int nt,nx;		/* numbers of samples			*/
	float dt,dx;		/* sampling intervals			*/
	float d1,d2;		/* output intervals in F, K		*/
	float f1,f2;		/* output first samples in F, K		*/
	int it,ix;		/* sample indices			*/
	int ntfft,nxfft;	/* dimensions after padding for FFT	*/
	int nF,nK;		/* transform (output) dimensions	*/
	int iF,iK;		/* transform sample indices		*/
	register complex **ct;	/* complex FFT workspace		*/
	register float **rt;	/* float FFT workspace			*/
	FILE *tracefp;		/* temp file to hold traces		*/


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


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


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


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


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


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


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


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


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

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

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

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


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

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

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

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

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

		puttr(&outtrace);
	}
}
Esempio n. 6
0
void
spwv (type_signal Signal,
    double *WindowT, int WindowT_Length,
    double *WindowF, int WindowF_Length,
    type_TFR tfr)

{
  int            Nfft, column, row, time;
  int            half_WindowT_Length, half_WindowF_Length;
  int            taumin, taumax, tau;
  int            mumin, mumax, mu;
  double        *lacf_real, *lacf_imag;		/* local autocorrelation function */
  double         normT, normF;
  double         R0_real, R0_imag, R1_real, R1_imag, R2_real, R2_imag;

 /*--------------------------------------------------------------------*/
 /*                      Test the input variables                      */
 /*--------------------------------------------------------------------*/


   if (tfr.is_complex == TRUE)
    {
      printf ("spwv.c : The tfr matrix must be real valued\n");
      exit(0);
    }

  if (tfr.N_freq <= 0)
    {
      printf ("spwv.c : The field tfr.N_freq is not correctly set\n");
      exit(0);
    }

  if (tfr.N_time <= 0)
    {
      printf ("spwv.c : The field tfr.N_time is not correctly set\n");
      exit(0);
    }

  if (ISODD(WindowT_Length) == 0)
    {
      printf ("spwv.c : The time-window Length must be an ODD number\n");
      exit(0);
    }

  if (ISODD(WindowF_Length) == 0)
    {
      printf ("spwv.c : The frequency-window Length must be an ODD number\n");
      exit(0);
    }

  /*--------------------------------------------------------------------*/
  /*                    Determines some internal constants              */
  /*--------------------------------------------------------------------*/
  half_WindowT_Length = (WindowT_Length - 1) / 2;
  half_WindowF_Length = (WindowF_Length - 1) / 2;
  normF=WindowF[half_WindowF_Length];

  for(row = 0; row < WindowF_Length; row++)
    {
      WindowF[row] = WindowF[row]/normF;
    }
  /*--------------------------------------------------------------------*/
  /*           creation of the vector of frequency bins  (output)       */
  /*--------------------------------------------------------------------*/
  Nfft = po2 (tfr.N_freq);

  for (row = 0; row < tfr.N_freq; row++)
    {
     tfr.freq_bins[row] = (double) (0.5 * row) / tfr.N_freq;
    }
  /*--------------------------------------------------------------------*/
  /* memory allocation and init. of the local autocorrelation fuction   */
  /*--------------------------------------------------------------------*/
  lacf_real = (double *) ALLOC (tfr.N_freq , sizeof (double));
  lacf_imag = (double *) ALLOC (tfr.N_freq , sizeof (double));

 /* initialization of the intermediary vectors */
 for (row = 0; row < tfr.N_freq ; row++)
   {
    lacf_real[row] = 0.0;
    lacf_imag[row] = 0.0;
   }

 /*--------------------------------------------------------------------*/
 /*      computation of the fft for the current windowed signal        */
 /*--------------------------------------------------------------------*/
  for (column = 0; column < tfr.N_time; column++)
    {

      /* time instants of interest to compute the tfr */
      time = ((int) tfr.time_instants[column]) - 1;

      taumax = MIN((time+half_WindowT_Length),(Signal.length-time-1+half_WindowT_Length));
      taumax = MIN(taumax,(tfr.N_freq / 2 - 1));
      taumax = MIN(taumax, half_WindowF_Length);

      /* determination of the begin and end of mu */
      mumin=MIN(half_WindowT_Length,(Signal.length-time-1));
      mumax=MIN(half_WindowT_Length,time);
      
      /* Normalization of the time-smoothing window */
      /* window norm */
      normT=0;
      for(row = -mumin ; row <= mumax ; row++)
	{
	  normT=normT+ WindowT[half_WindowT_Length+row];
	}
      
      R0_real=0.0;
      R0_imag=0.0;
      for(mu=-mumin;mu<=mumax;mu++)
	{
	  if (Signal.is_complex == TRUE)
	    {
	      R0_real=R0_real +   (Signal.real_part[time-mu]
				   *  Signal.real_part[time-mu]
				   +   Signal.imag_part[time-mu]
				   *  Signal.imag_part[time-mu])
		*    WindowT[half_WindowT_Length+mu]/normT;
	    }
	  else
	    {
	      R0_real=R0_real +   Signal.real_part[time-mu]
                               *  Signal.real_part[time-mu]
		               *  WindowT[half_WindowT_Length+mu]/normT;
	    }
          }

      lacf_real[0]=R0_real;
      lacf_imag[0]=R0_imag;

      /* The signal is windowed around the current time */
      for (tau = 1; tau <= taumax; tau++)
	{
	  R1_real=0;R2_real=0;
	  R1_imag=0;R2_imag=0;

	  mumin=MIN(half_WindowT_Length,(Signal.length-time-1-tau));
	  mumax=MIN(half_WindowT_Length,time-tau);

	  /* window norm */
	  normT=0;
	  for(row = -mumin ; row <= mumax ; row++)
	    {
	      normT = normT + WindowT[half_WindowT_Length+row];
	    }

	  for(mu=-mumin;mu<=mumax;mu++)
	    {
	      if (Signal.is_complex == TRUE)
		{
		  R1_real = R1_real +  (Signal.real_part[time+tau-mu]
                                      * Signal.real_part[time-tau-mu]
	        		     +  Signal.imag_part[time+tau-mu]
                                      * Signal.imag_part[time-tau-mu])
  		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R1_imag = R1_imag +  (Signal.imag_part[time+tau-mu]
                                      * Signal.real_part[time-tau-mu]
				     -  Signal.real_part[time+tau-mu]
                                      * Signal.imag_part[time-tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R2_real = R2_real +  (Signal.real_part[time-tau-mu]
                                      * Signal.real_part[time+tau-mu]
				     +  Signal.imag_part[time-tau-mu]
                                      * Signal.imag_part[time+tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R2_imag = R2_imag +  (Signal.imag_part[time-tau-mu]
                                      * Signal.real_part[time+tau-mu]
				     -  Signal.real_part[time-tau-mu]
                                      * Signal.imag_part[time+tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		}
	      
	      else
		{
		  R1_real = R1_real +  (Signal.real_part[time+tau-mu]
                                      * Signal.real_part[time-tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R1_imag = 0.0;
		  
		  R2_real = R2_real +  (Signal.real_part[time-tau-mu]
                                      * Signal.real_part[time+tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R2_imag = 0.0;
		}
	    }
	  
	  lacf_real[tau] = R1_real * WindowF[half_WindowF_Length+tau];
	  lacf_imag[tau] = R1_imag * WindowF[half_WindowF_Length+tau];
	  lacf_real[tfr.N_freq-tau] = R2_real * WindowF[half_WindowF_Length-tau];
	  lacf_imag[tfr.N_freq-tau] = R2_imag * WindowF[half_WindowF_Length-tau];
	  
        }
      

     tau=floor(tfr.N_freq/2);
     if ((time<=Signal.length-tau-1)&(time>=tau)&(tau<=half_WindowF_Length))
       {
        mumin=MIN(half_WindowT_Length,(Signal.length-time-1-tau));
	     mumax=MIN(half_WindowT_Length,time-tau);

        normT=0;
	     for(row = -mumin ; row <= mumax ; row++)
	       {
	        normT = normT + WindowT[half_WindowT_Length+row];
	        }

       R1_real=0;R2_real=0;
	    R1_imag=0;R2_imag=0;
       for(mu=-mumin;mu<=mumax;mu++)
	    {
	      if (Signal.is_complex == TRUE)
		   {
		    R1_real = R1_real +  (Signal.real_part[time+tau-mu]
                                      * Signal.real_part[time-tau-mu]
	        		                       +  Signal.imag_part[time+tau-mu]
                                      * Signal.imag_part[time-tau-mu])
  		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		    R1_imag = R1_imag +  (Signal.imag_part[time+tau-mu]
                                      * Signal.real_part[time-tau-mu]
				                         -  Signal.real_part[time+tau-mu]
                                      * Signal.imag_part[time-tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R2_real = R2_real +  (Signal.real_part[time-tau-mu]
                                      * Signal.real_part[time+tau-mu]
				                          +  Signal.imag_part[time-tau-mu]
                                      * Signal.imag_part[time+tau-mu])
		                       *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R2_imag = R2_imag +  (Signal.imag_part[time-tau-mu]
                                      * Signal.real_part[time+tau-mu]
				     -  Signal.real_part[time-tau-mu]
                                      * Signal.imag_part[time+tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		}
	      
	      else
		{
		  R1_real = R1_real +  (Signal.real_part[time+tau-mu]
                                      * Signal.real_part[time-tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R1_imag = 0.0;
		  
		  R2_real = R2_real +  (Signal.real_part[time-tau-mu]
                                      * Signal.real_part[time+tau-mu])
		                    *   WindowT[half_WindowT_Length+mu]/normT;
		  
		  R2_imag = 0.0;
		}
	    }
	  
	  lacf_real[tau] = 0.5*(R1_real * WindowF[half_WindowF_Length+tau]
                      + R2_real * WindowF[half_WindowF_Length-tau]);
	  lacf_imag[tau] = 0.5*(R1_imag * WindowF[half_WindowF_Length+tau]
                      + R2_imag * WindowF[half_WindowF_Length-tau]);
	  }

      /* fft of the local autocorrelation function lacf */
      fft (tfr.N_freq, Nfft, lacf_real, lacf_imag);


      /* the fft is put in the tfr matrix  */
      for (row = 0; row < tfr.N_freq; row++)
	{
	  *(tfr.real_part +row +column*tfr.N_freq)= lacf_real[row];
	  lacf_real[row] = 0.0;
	  lacf_imag[row] = 0.0;
        }
    }
 /*--------------------------------------------------------------------*/
 /*                free the memory used in this program                */
 /*--------------------------------------------------------------------*/
  FREE (lacf_real);
  FREE (lacf_imag);

}
Esempio n. 7
0
int
main( int argc, char *argv[] )
{
 

	int nx;
	int fbt;
	int nt;
	
	float *stacked=NULL;
	int *nnz=NULL;
	int itr=0;
	
 
	initargs(argc, argv);
   	requestdoc(1);
	
	if (!getparint("nx", &nx)) nx = 51;
	if( !ISODD(nx) ) {
		nx++;
		warn(" nx has been changed to %d to be odd.\n",nx);
	}
	
	if (!getparint("fbt", &fbt)) fbt = 60;
        checkpars();
	
	/* Get info from first trace */ 
	if (!gettr(&tr))  err("can't get first trace");
	nt = tr.ns;
	
	stacked = ealloc1float(fbt);
	nnz = ealloc1int(fbt);
	memset((void *) nnz, (int) '\0', fbt*ISIZE);
	memset((void *) stacked, (int) '\0', fbt*FSIZE);

	/* read nx traces and stack them */
	/* The first trace is already read */
	
	{ int i,it;
	  float **tr_b;
	  char  **hdr_b;
	  int NXP2=nx/2;
	  short shft,scaler;
	  
		/* ramp on read the first nx traces and create stack */
		
	  	tr_b = ealloc2float(nt,nx);
		hdr_b = (char**)ealloc2(HDRBYTES,nx,sizeof(char));
		
		memcpy((void *) hdr_b[0], (const void *) &tr, HDRBYTES);
		memcpy((void *) tr_b[0], (const void *) &tr.data, nt*FSIZE);
		
		for(i=1;i<nx;i++) {
			gettr(&tr);
			memcpy((void *) hdr_b[i], (const void *) &tr, HDRBYTES);
			memcpy((void *) tr_b[i], (const void *) &tr.data, nt*FSIZE);
		}
		
		for(i=0;i<nx;i++) 
			for(it=0;it<fbt;it++) 
				stacked[it] += tr_b[i][it];
		
		
		for(it=0;it<fbt;it++)
			stacked[it] /=(float)nx;
		
			
		/* filter and write out the first nx/2 +1 traces */
		for(i=0;i<NXP2+1;i++) {
			memcpy((void *) &tr, (const void *) hdr_b[i], HDRBYTES);
			memcpy((void *) tr.data, (const void *) tr_b[i], nt*FSIZE);
			
			remove_fb(tr.data,stacked,fbt,&scaler,&shft);
			tr.trwf = scaler;
			tr.grnors = shft;

			puttr(&tr);
			++itr;
		}
		
		/* do the rest of the traces */
		gettr(&tr);
		
		do {
			
			/* Update the stacked trace  - remove old */
			for(it=0;it<fbt;it++) 
				stacked[it] -= tr_b[0][it]/(float)nx;
				
			/* Bump up the storage arrays */
			/* This is not very efficient , but good enough */
			{int ib;
				for(ib=1;ib<nx;ib++) {
				    memcpy((void *) hdr_b[ib-1],
					(const void *) hdr_b[ib], HDRBYTES);
				memcpy((void *) tr_b[ib-1],
					(const void *) tr_b[ib], nt*FSIZE);
				}
			}
			
			/* Store the new trace */
			memcpy((void *) hdr_b[nx-1], (const void *) &tr, HDRBYTES);
			memcpy((void *) tr_b[nx-1], (const void *) &tr.data, nt*FSIZE);
			
			/* Update the stacked array  - add new */
			for(it=0;it<fbt;it++) 
				stacked[it] += tr_b[nx-1][it]/(float)nx;
			
			/* Filter and write out the middle one NXP2+1 */
			memcpy((void *) &tr, (const void *) hdr_b[NXP2], HDRBYTES);
			memcpy((void *) tr.data, (const void *) tr_b[NXP2], nt*FSIZE);
			
			remove_fb(tr.data,stacked,fbt,&scaler,&shft);
			
			tr.trwf = scaler;
			tr.grnors = shft;
			puttr(&tr);
			++itr;
			
			
		} while(gettr(&tr));

		/* Ramp out - write ot the rest of the traces */
		/* filter and write out the last nx/2 traces */
		for(i=NXP2+1;i<nx;i++) {
			memcpy((void *) &tr, (const void *) hdr_b[i], HDRBYTES);
			memcpy((void *) tr.data, (const void *) tr_b[i], nt*FSIZE);
			
			remove_fb(tr.data,stacked,fbt,&scaler,&shft);
			
			tr.trwf = scaler;
			tr.grnors = shft;
			puttr(&tr);
			itr++;
		
		}
		
		
	}
		
  
	
	free1float(stacked);
	free1int(nnz);
   	return EXIT_SUCCESS;
}
Esempio n. 8
0
void functional_crypto(UNUSED(void **state))
{
  unsigned char nonce[crypto_box_NONCEBYTES];
  unsigned char initiatenonce[crypto_box_NONCEBYTES];
  unsigned char hellopacket[192] = {0};
  unsigned char initiatepacket[256] = {0};
  unsigned char messagepacket[120];
  unsigned char messagepacketout[120] = {0};
  unsigned char allzeroboxed[96] = {0};
  unsigned char initiatebox[160] = {0};
  unsigned char pubkeybox[96] = {0};
  unsigned char lengthbox[40] = {0};
  uint64_t plaintextlen;
  uint64_t readlen;
  outputstream write;

  connect_to_db();

  wrap_crypto_write = false;

  assert_int_equal(0, filesystem_load(".keys/server-long-term.pub",
      serverlongtermpk, sizeof serverlongtermpk));

  cc.nonce = (uint64_t) randommod(281474976710656LL);

  if (!ISODD(cc.nonce)) {
    cc.nonce++;
  }

  cc.receivednonce = 0;
  cc.state = TUNNEL_INITIAL;

  memcpy(nonce, "splonebox-client", 16);
  uint64_pack(nonce + 16, cc.nonce);

  /* pack hello packet */
  memcpy(hellopacket, "oqQN2kaH", 8);
  /* pack compressed nonce */
  memcpy(hellopacket + 104, nonce + 16, 8);

  /* generate client ephemeral keys */
  if (crypto_box_keypair(clientlongtermpk, clientlongtermsk) != 0)
    return;
  /* generate client ephemeral keys */
  if (crypto_box_keypair(clientshorttermpk, clientshorttermsk) != 0)
    return;

  memcpy(hellopacket + 8, clientshorttermpk, 32);

  assert_int_equal(0, crypto_box(allzeroboxed, allzeroboxed, 96, nonce,
      serverlongtermpk, clientshorttermsk));

  memcpy(hellopacket + 112, allzeroboxed + 16, 80);

  crypto_init();

  /* positiv test */
  assert_int_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));

  /* wrong identifier */
  memcpy(hellopacket, "deadbeef", 8);
  assert_int_not_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));
  memcpy(hellopacket, "oqQN2kaH", 8);

  /* wrong nonce */
  cc.receivednonce = cc.nonce + 1;
  assert_int_not_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));
  cc.receivednonce = 0;

  /* wrong pubkey */
  memset(hellopacket + 8, '0', 32);
  assert_int_not_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));
  memcpy(hellopacket + 8, clientshorttermpk, 32);

  assert_int_equal(0, crypto_recv_hello_send_cookie(&cc, hellopacket, &write));

  /* crypto_recv_initiate() test */

  /* pack initiate packet */
  memcpy(initiatepacket, "oqQN2kaI", 8);
  memcpy(initiatepacket + 8, cookie, 96);
  /* pack compressed nonce */
  memcpy(initiatepacket + 104, nonce + 16, 8);

  memcpy(initiatebox + 32, clientlongtermpk, 32);
  randombytes(initiatebox + 64, 16);
  memcpy(initiatenonce, "splonePV", 8);
  memcpy(initiatenonce + 8, initiatebox + 64, 16);

  memcpy(pubkeybox + 32, clientshorttermpk, 32);
  memcpy(pubkeybox + 64, servershorttermpk, 32);

  assert_int_equal(0, crypto_box(pubkeybox, pubkeybox, 96, initiatenonce,
      serverlongtermpk, clientlongtermsk));

  memcpy(initiatebox + 80, pubkeybox + 16, 80);

  assert_int_equal(0, crypto_box(initiatebox, initiatebox, 160, nonce,
      servershorttermpk, clientshorttermsk));

  memcpy(initiatepacket + 112, initiatebox + 16, 144);

  /* without valid certificate */
  assert_int_not_equal(0, crypto_recv_initiate(&cc, initiatepacket));

  /* all plugins are allowed to connect */
  db_authorized_set_whitelist_all();
  assert_int_equal(0, crypto_recv_initiate(&cc, initiatepacket));

  /* crypto_write() test */
  assert_int_equal(0, crypto_write(&cc, (char*) allzeroboxed,
      sizeof(allzeroboxed), &write));

  /* crypto_read() test */

  /* pack message packet */
  memcpy(messagepacket, "oqQN2kaM", 8);

  /* pack compressed nonce */
  memcpy(nonce, "splonebox-client", 16);
  uint64_pack(nonce + 16, cc.nonce);
  memcpy(messagepacket + 8, nonce + 16, 8);

  uint64_pack(lengthbox + 32, 120);

  assert_int_equal(0, crypto_box(lengthbox, lengthbox, 40, nonce,
      servershorttermpk, clientshorttermsk));

  memcpy(messagepacket + 16, lengthbox + 16, 24);

  uint64_pack(nonce + 16, cc.nonce + 2);

  memset(allzeroboxed, 0, 96);
  assert_int_equal(0, crypto_box_afternm(allzeroboxed, allzeroboxed, 96, nonce,
      cc.clientshortservershort));

  memcpy(messagepacket + 40, allzeroboxed + 16, 80);

  assert_int_equal(0, crypto_verify_header(&cc, messagepacket, &readlen));

  assert_int_equal(0, crypto_read(&cc, messagepacket, (char*)messagepacketout,
      readlen, &plaintextlen));

  db_close();
}
Esempio n. 9
0
void
kernel (int type, double *parameters, int nb_param, type_AF ker)
{
  int            line, col;
  double         doppler, delay;
  double         inter;


  /* some tests */

  if ((ker.N_doppler <1) || (ker.N_delay < 1))
    {
      printf("kernel.c : invalid number of lines / columns in the kernel matrix \n");
      exit(0);
    }

  switch (type)
    {
      /***************************************************************
       *              Multiform Tiltable Exponentiel Kernel          *
       ***************************************************************
       * The parameters vector is made of                            *
       * alpha, beta, gamma, r, tau0, nu0, lambda]                   *
       *   see the reference :                                       * 
       *	H. Costa and G.F. Boudreaux-Bartels,                 *
       *	Design of Time-Frequency Representations Using a     *
       *		  Multiform, Tiltable Exponential Kernel     *
       *	IEEE Trans. on Signal Processing                     *
       *	October 1995, vol. 43, no 10, pp 2283-2301           *
       ***************************************************************/
      /* LOCAL VARIABLES                                             *
       * Name           |                   role                     *
       * A              | intermediary in the computation of the     *
       *                | MTEK kernel                                *
       ***************************************************************/
   case MTEK:
      {
	/* local variables for the MTEK */

	double         A;

	/* Kernel Construction */
	for (line = 0; line < ker.N_doppler; line++)
	  {
	    doppler = (line - ker.N_doppler / 2.0 + 1.0) / ker.N_doppler;
	    for (col = 0; col < ker.N_delay; col++)
	      {
		delay = col - ker.N_delay / 2.0 + 1.0;
		A = (doppler * delay) / (TAU_0 * NU_0);

		/* case of the symmetrical kernel */
		if ((BETA == 2) && (GAMMA == 0.5))
		  {
		    A = ABS (A);
		  }

		/* case where the marginals do not have to be verified */
		if (ALPHA == 0)
		  {
		    inter = sqr (delay / TAU_0) + sqr (doppler / NU_0)
		      + 2.0
		      * R * A;
		  }
		/* case where the marginals have to be verified */
		else
		  {
		    inter = sqr (delay / TAU_0) * powof (sqr (doppler /
							      NU_0), ALPHA)
		      + sqr (doppler / NU_0) * powof (sqr (delay /
							   TAU_0), ALPHA)
		      + 2.0 * R * A;
		  }
		/* test to avoid the computation of log(0) */
		if (inter == 0)
		  {
		    ker.real_part[idx (line, col, ker.N_doppler)] = 1.0;
		  }
		else
		  {
		    ker.real_part[idx (line, col, ker.N_doppler)] =
		      exp (-pi * powof (sqr (inter), LAMBDA));
		  }
		inter = 0;
		A = 0;
	      }
	  }
      }
      break;
      /***************************************************************
       *                 Radially Gaussian kernel                    *
       ***************************************************************
       * The parameters vector is made according to the rule :       *
       * if the order of the kernel is p, the vector is              *
       * [ c ,a1 , ... , ap, b1,... ,bp] where c is the constant     *
       * ai are the cosine coefficients and bi the sine              *
       * coefficients in the Fourier series decomposition of the     *
       * contour. See the reference :                                *
       *     M. Davy and C. Doncarli,                                *
       *    Optimal Kernels of Time-Frequency Representations for    *
       *    Signal Classification,                                   *
       *	  TFTS 1998, pp 581-584.                             *
       ***************************************************************/
      /* LOCAL VARIABLES                                             *
       * Name           |                   role                     *
       * order          | Fixes the maximum p in the vector of params*
       * p              | Current parameter p in the vector of params*
       * a,b            | Vectors containing the parameters ap, bp   *
       *                | from the vector of params                  *
       * c              | The minimum value of the contour function  *
       * inter, mini    | Intermediary values in the computations    *
       * phi            | angle parameter in the polar coordinates   *
       * rho2           | square radius parameter in polar coord.    *         
       ***************************************************************/


    case RGK:
      {
	/* local variables for the RGK */
	int            order, p;
	double         *a, *b;
	double         c, inter, mini;
	double         phi, rho2;


	/* some error cases to avoid ... */
	if (ISODD(nb_param) == 0)
	  {
	    printf("kernel.c : the number of RGK parameters must be ODD\n");
	    exit(0);
	  } 


	order = (nb_param - 1) / 2;


	/* memory allocation for a and b */
	a = (double *) ALLOC ( order , sizeof(double) );
	b = (double *) ALLOC ( order , sizeof(double) );

	/* variables recovery */
	c = parameters[0];
	for (p = 0; p < order; p++)
	  {
	    a[p] = parameters[p + 1];
	    b[p] = parameters[order + p + 1];
	  }
	/*-----------------------------------------------*/
	/*             Kernel Construction               */
	/*-----------------------------------------------*/

	/* minimum value of the contour function */
	mini = 0;	


	/* construction of the matrix of the contour function */
	for (line = 0; line < ker.N_doppler; line++)
	  {
	    /* current doppler value */
	    doppler = (line - ker.N_doppler / 2.0 + 1.0) / ker.N_doppler;
	    /* normalization of the doppler to have angles in radians */
	    doppler = doppler * sqrt (ker.N_delay);

	    for (col = 0; col < ker.N_delay; col++)
	      {
		/* currrent delay value */
		delay = col - ker.N_delay / 2.0 + 1.0;
		/* normalization of the delay to have angles in radians */
		delay = delay / sqrt (ker.N_delay);

		/* computation of the angles in the ambiguity plane */
		if (((delay > 0) && (doppler > 0))
		    || ((delay < 0) && (doppler < 0)))
		  {
		    phi = atan (doppler / delay);
		  }
		else
		  {
		    phi = atan (doppler / delay) + pi;
		  }

		inter = 0;
		for (p = 0; p < order; p++)
		  {
		    inter = inter + a[p] * cos (2.0 * (p + 1) * phi) +
		      b[p]
		      * sin (2.0 * (p + 1) * phi);
		  }
		/* look for the minimum */
		if (inter < mini)
		  {
		    mini = inter;
		  }
		/* matrix of the contour function : each element in this */
		/* matrix contains the value of the contour function for */
		/* the corresponding delay and doppler values */
		ker.real_part[idx (line, col, ker.N_doppler)] = inter;

	      }
	  }

	/* construction of the RGK matrix */
	for (line = 0; line < ker.N_doppler; line++)
	  {
	    /* current normalized doppler */
	    doppler = (line - ker.N_doppler / 2.0 + 1.0) / ker.N_doppler;
	    doppler = doppler * sqrt (ker.N_delay);

	    for (col = 0; col < ker.N_delay; col++)
	      {
		/* current normalized delay */
		delay = col - ker.N_delay / 2.0 + 1.0;
		delay = delay / sqrt (ker.N_delay);
		/* Square Polar radius */
		rho2 = sqr (doppler) + sqr (delay);
		ker.real_part[idx (line, col, ker.N_doppler)] =
		  exp (-(rho2 / 2.0) / 
		       sqr (ker.real_part[idx (line, col, ker.N_doppler)]
			    - mini + c));

		/* case of the center of the ambiguity plane */
		if ((delay == 0) && (doppler == 0))
		  ker.real_part[idx (line, col, ker.N_doppler)] = 1.0;
	      }
	  }
	/* free the memory used here */
	FREE (a);
	FREE (b);
      }
      break;

      /***************************************************************
       *          Generalized Marginals Choi-Williams                *
       ***************************************************************
       * The parameters vector is made of the width of the           *
       * branches "sigma" and the angle of each branch theta_i       *
       * (0 to Pi). The number of branches is given by the number    *
       * of coefficients                                             *
       * [ sigma theta_1 theta_2  ... theta_p]                       *
       *                                                             *
       * see the reference :                                         *
       * X.-G. Xia and Y. Owechko and B. H. Soffer and R. M. Matic,  *
       * Generalized-Marginal Time-Frequency Distributions,          *
       * TFTS 1996, pp. 509-51                                       *
       ***************************************************************/
      /* LOCAL VARIABLES                                             *
       * Name           |                   role                     *
       * N_Branch       | Number of kernel branches                  *
       * branch         | Current branch number                      *
       * angle          | vector of branches angles                  *
       * sigma          | value of the parameter sigma (kernel width)*
       * inter          | intermediary variable                      *
       ***************************************************************/


    case GMCWK:
      {
	/* local variables for the RGK */
	int            N_branch, branch;
	double         *angle, sigma, inter;



	/* some error cases to avoid ... */
	if (nb_param < 2)
	  {
	    printf("kernel.c : at least 2 GMCWK parameters required\n");
	    exit(0);
	  } 


	/* variables recovery */
	sigma = parameters[0];
	N_branch = nb_param - 1;



	/* recovery of the angles */
	angle = &(parameters[1]);

	/* Kernel Construction  */
	for (line = 0; line < ker.N_doppler; line++)
	  {
	    doppler = (line - ker.N_doppler / 2.0 + 1.0) 
	      / ker.N_doppler;
	    doppler = doppler * sqrt (ker.N_delay);

	    for (col = 0; col < ker.N_delay; col++)
	      {
		delay = col - ker.N_delay / 2.0 + 1.0;
		delay = delay / sqrt (ker.N_delay);
		inter = 1;
		for (branch = 0; branch < N_branch; branch++)
		  {
		    inter = inter 
		      * sqr (doppler * cos (angle[branch])
			     + delay * sin (angle[branch]));
		  }
		ker.real_part[idx (line, col, ker.N_doppler)] = 
		  exp (-inter / sigma);
	      }
	  }
      }
      break;
      /***************************************************************
       *                Wigner-Ville kernel                          *
       ***************************************************************
       * No parameter is required. The matrix is equal to            *
       * one in each point                                           *
       ***************************************************************/


    case WIGNER:
      {



	/* Kernel Construction  */
	for (line = 0; line < ker.N_doppler; line++)
	  {
	    for (col = 0; col < ker.N_delay; col++)
	      {
		ker.real_part[idx (line, col, ker.N_doppler)] = 1.0;
	      }
	  }
      }
      break;
      /***************************************************************
       *                   Spectrogram  kernel                       *
       ***************************************************************
       *  The paremters are the window points in the time            *
       * domain. The kernel is the ambiguity function of the window  *
       ***************************************************************/
      /* LOCAL VARIABLES                                             *
       * Name           |                   role                     *
       * window         | structure containing the window of the     *
       *                | spectrogram                                *
       * AF_h           | Ambiguity function of th window            *
       * min_delay |    | in order to pad with zeros, defines the    *
       * max_delay |    | indices where the zero padding begins/ends *
       * index          | indice to access the elements in matrices  *
       *                | (stored as vectors)                        *
       ***************************************************************/



    case SPECTRO:
      {
	/* local variable */
	type_signal    window;
	type_AF        AF_h;
	int            min_delay, max_delay, index;

	/* some error cases to avoid ... */
	if (ISODD(nb_param) == 1)
	  {
	    printf("kernel.c : the window length must be EVEN for SPECTRO\n");
	    exit(0);
	  } 



	/* initialization of the local variables : window */
	window.length = ker.N_delay;
	window.is_complex = TRUE;
	/* creation of memory */
	window.real_part = (double *) ALLOC (window.length, sizeof (double));
	window.imag_part = (double *) ALLOC (window.length, sizeof (double));


	min_delay = (int) (window.length / 2 - nb_param / 2);
	max_delay = (int) (window.length / 2 + nb_param / 2 - 1);

	/* initialization of the imaginary part for the window 
	   and zero padding out of [min_delay;max_delay] */
	for (col = 0; col < window.length; col++)
	  {
	    if ((col >= min_delay) && (col <= max_delay))
	      {
		window.real_part[col] = parameters[col - min_delay];
	      }
	    else
	      {
		window.real_part[col] = 0;
	      }
	    window.imag_part[col] = 0;
	  }


	/* initialization of the local variables : AF_h */
	AF_h.N_doppler = ker.N_doppler;
	AF_h.N_delay = ker.N_delay;
	AF_h.is_complex = TRUE;

	mem_alloc_AF (&AF_h, NULL, NULL, NULL, NULL);
 	for (index = 0; index < AF_h.N_delay; index++)
	  {
	    AF_h.delay_bins[index] = -AF_h.N_delay / 2.0 + 1.0 + index;
	  }




	/* computation of the AF of the window */
	af (window, AF_h);

	/* Warning : if ker.N_delay != ker.N_doppler,
	   one must add or suppress lines in this AF */
	for (line = 0; line < ker.N_doppler; line++)
	  {
	    for (col = 0; col < ker.N_delay; col++)
	      {
		index = idx (line, col, ker.N_delay);
		ker.real_part[idx (line, col, ker.N_doppler)] =
		  sqrt (sqr (AF_h.real_part[index])
			+ sqr (AF_h.imag_part[index]));
	      }
	  }
	/* free memory !! */

	mem_free_AF (&AF_h);
	FREE (window.real_part);
	FREE (window.imag_part);

      }
      break;
    }
}
Esempio n. 10
0
void
deriv_n_gauss(double dt, int nt, double t0, float fpeak, int n, double *w,
	    int sign, int verbose)
/****************************************************************************
  deriv_n_gauss:  Compute n-th order derivative of a Gaussian 
                    in double precision.
*****************************************************************************
Input:
dt		sampling interval
nt		length of waveform in samples
t0		time shift for (pseudo-) causality
fpeak		maximum frequency
n		order of derivative
sign		multiplier for polarity of waveform
verbose		flag for diagnostic messages
*****************************************************************************
Output:
w	array of size nt containing the waveform
*****************************************************************************
Return: none
*****************************************************************************
Notes:
Copyright (c) 2007 by the Society of Exploration Geophysicists.
For more information, go to http://software.seg.org/2007/0004 .
You must read and accept usage terms at:
http://software.seg.org/disclaimer.txt before use.
*****************************************************************************
Author: Werner M. Heigl, Apache Corporation, E&P Technology, November 2006
*****************************************************************************/
{
	int i;			/* loop variable			*/
	double sigma;		/* temporal variance of Gaussian	*/
	double C;		/* normalization constant		*/
	double *h  = NULL;	/* Hermite polynomial			*/
	double *h0 = NULL;	/* temp array for H_{n-1}		*/
	double *h1 = NULL;	/* temp array for H_{n}			*/
	double *t  = NULL;	/* time vector				*/

	
	/* allocate & initialize memory */
	t  = alloc1double(nt);
	h  = alloc1double(nt);
	h0 = alloc1double(nt);
	h1 = alloc1double(nt);

	memset((void *) t , 0, DSIZE * nt);
	memset((void *) h , 0, DSIZE * nt);
	memset((void *) h0, 0, DSIZE * nt);
	memset((void *) h1, 0, DSIZE * nt);
	if (verbose)
		fprintf(stderr,"memory allocated and initialized/n");

	/* initialize time vector */
	for (i = 0; i < nt; ++i)	t[i] = i * dt - t0;
	if (verbose)	fprintf(stderr,"t[] initialized/n");
	
	/* compute Gaussian */
	sigma = n / ( 4 * PI * PI * fpeak * fpeak );
	if (verbose)	fprintf(stderr,"sigma=%f",sigma);
	for (i = 0; i < nt; ++i)
		w[i] = exp( - t[i] * t[i] / (2 * sigma) );
	if (verbose)	fprintf(stderr,"Gaussian computed/n");
	
	/* compute Hermite polynomial */
	for (i = 0; i < nt; ++i) {
		h0[i] = 1.0;
		h1[i] = t[i] / sigma;
	}
	if (n==1)	memcpy((void *) h, (const void *) h1, DSIZE * nt);
	if (n>1)	hermite_n_polynomial(h, h0, h1, t, nt, n, sigma);
	if (verbose)	fprintf(stderr,"Hermite polynomial H_%d computed/n",n);
	
	/* compute waveform */
	for (i = 0; i < nt;++i)		w[i] = h[i] * w[i];
	if (verbose)	fprintf(stderr,"waveform computed/n");
	
	/* find normalization constant */
	C = fabs(w[0]);
	for (i = 1; i < nt; ++i)
		if (fabs(w[i]) > C)	C = fabs(w[i]);
	if (ISODD(n))	C = -C;	/* to account for (-1)^n */
	if (verbose)	fprintf(stderr,"C=%f/n",C);
	
	/* and finally normalize */
	for (i = 0; i < nt; ++i)	w[i] = sign * w[i] / C;
	if (verbose)	fprintf(stderr,"waveform normalized/n");

	/* check amplitude a t=0 */
	if (verbose)	fprintf(stderr,"w[o]=%.12f",w[0]);
	
	/* free memory */
	free1double(h); free1double(h0); free1double(h1);
	free1double(t);
	if (verbose)	fprintf(stderr,"memory freed/n");
}