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

   cwp_String prefix=NULL; /* Common prefix to build the SPS filenames. */
   cwp_String Rname=NULL;  /* file name for R file                 */
   int numR=0;             /* number of receiver points            */
   FILE *fpR=NULL;         /* file pointer for R file              */
   cwp_String Sname=NULL;  /* file name for S file                 */
   FILE *fpS=NULL;         /* file pointer for S file              */
   int numS=0;             /* number of source points              */
   cwp_String Xname=NULL;  /* file name for X file                 */
   FILE *fpX=NULL;         /* file pointer for X file              */
   int numX=0;             /* number of relation points entries    */
                           /* WARNING: a record can have more than */
                           /*          one relation entry.  E.g. 3D*/
   int rev;                /* SPS revision to process              */

   int   RC;               /* Return code from functions           */
   int   i;                /* Just the "i".                        */
   float scalco;           /* scale factor                         */
   float scalel;           /* scale factor                         */
   float temp;             /* temporary float value                */

   double Xcdp;            /* CDP X Coordinate                     */
   double Ycdp;            /* CDP Y Coordinate                     */
   float ibin;             /* Inline bin size/cdp interval         */
   //float xbin;             /* Xline bin size/ Not used             */

   float dt;               /* sample spacing - I don't need, just check */
   //int nt;                 /* number of points on input trace      */
   cwp_Bool seismic;       /* is this seismic data?      */

   // File control
   int oldfldr;  //  fldr for last trace processed
   int oldskip;  //  still skipping the same fldr?
   int curx;     //  relation entry control
   int curtrl;   //  keeping track of current trace (in case of skip)

   int idxR;     //  Index of receiver station entry
   int idxS;     //  Index of shot point entry
   float recsta; //  receiver station
   //float srcsta; //  source point station

   int nproct = 0; // number of processed traces
   //int nprocf = 0; // number of processed files
        
   /* Initialize */
   initargs(argc, argv);
   requestdoc(1);

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

   /* get SPS revision to process */
   if (!getparint("rev", &rev))   rev=2;

   /* get inline bin interval     */
   if (!getparfloat("ibin", &ibin))   ibin=0.;

   /* lets prepare the geometry informations */

   /* ==========================================  */
   /* Lets try to get common prefix. ===========  */
   /* ==========================================  */
   getparstring("prefix", &prefix);
   // if ( prefix == NULL )  Who cares?

   /* ==========================================  */
   /* Receiver points information ==============  */
   /* ==========================================  */
   getparstring("rps", &Rname);
   if ( Rname == NULL ) {
      if ( prefix == NULL )
         err("**** Missing required parameter 'rps=', see self-doc");
      //  I have a prefix and need build this file name.
      Rname = calloc(strlen(prefix)+2,sizeof(cwp_String));
      if ( Rname == NULL )
         err("**** Unable to allocate memory for R-File name.");
      strcpy(Rname,prefix);
      strcat(Rname,".r");
   }
   if (verbose)
      warn("Receiver file: %s",Rname);

   fpR = efopen(Rname, "r");
   if ( fpR == NULL )
         err("**** Error opening the receiver information file");

   numR = countRec(fpR, 'R');
   warn("Found %d receiver points entries.",numR);
   if ( numR == 0 )
      err("**** No receiver point information found!!");

   // Allocate area for the receiver informations
   // calloc zero out memory.
   RecInfo = calloc(numR,sizeof(struct PointInfo));
   if ( RecInfo == NULL ){
      err("**** Unable to allocate memory for Receiver Point Informations!!");
   }

   //  Get all Receiver Points info into memory
   RC = getPoints(fpR, 'R', rev, RecInfo);
   if ( RC != numR) {
      warn("Short read for Receiver Point Informations!");
      warn("Read %d receiver points entries instead of expected%d.",RC,numR);
   }
   if (verbose) {
      warn("Stored: %d Receiver Point Informations.",RC);
      for (i=0; i<RC; i++)
          warn("R %10.2f,%10.2f,%4.1f,%10.2lf,%10.2lf,%5.1f",
          RecInfo[i].Line,
          RecInfo[i].Point,
          RecInfo[i].PDepth,
          RecInfo[i].X,
          RecInfo[i].Y,
          RecInfo[i].Elev);
   }


   /* ==========================================  */
   /* Source points information ================  */
   /* ==========================================  */
   getparstring("sps", &Sname);
   if ( Sname == NULL ) {
      if ( prefix == NULL )
         err("**** Missing required parameter 'sps=', see self-doc");
      //  I have a prefix and need build this file name.
      Sname = calloc(strlen(prefix)+2,sizeof(cwp_String));
      if ( Sname == NULL )
         err("**** Unable to allocate memory for S-File name.");
      strcpy(Sname,prefix);
      strcat(Sname,".s");
   }
   if (verbose)
      warn("Source file: %s",Sname);

   fpS = efopen(Sname, "r");
   if ( fpS == NULL )
      err("**** Error opening the source information file");

   numS = countRec(fpS, 'S');
   warn("Found %d source points entries.",numS);
   if ( numS == 0 )
      err("**** No source point information found!!");

   // Allocate area for the Source informations
   // calloc zero out memory.
   SrcInfo = calloc(numS,sizeof(struct PointInfo));
   if ( SrcInfo == NULL ){
      err("**** Unable to allocate memory for Source Point Informations!!");
   }

   //  Get all Source Point info into memory
   RC = getPoints(fpS, 'S', rev, SrcInfo);
   if ( RC != numS) {
      warn("Short read for Source Point Informations!");
      warn("Read %d source point entries instead of expected%d.",RC,numS);
   }
   if (verbose) {
      warn("Stored: %d Source Point Informations.",RC);
      for (i=0; i<RC; i++)
          warn("S %10.2f,%10.2f,%4.1f,%10.2lf,%10.2lf,%5.1f",
          SrcInfo[i].Line,
          SrcInfo[i].Point,
          SrcInfo[i].PDepth,
          SrcInfo[i].X,
          SrcInfo[i].Y,
          SrcInfo[i].Elev);
   }
   /* ------------------------------------------  */

   /* ==========================================  */
   /* Relation (records) information ===========  */
   /* ==========================================  */
   getparstring("xps", &Xname);
   if ( Xname == NULL ) {
      if ( prefix == NULL )
         err("**** Missing required parameter 'xps=', see self-doc");
      //  I have a prefix and need build this file name.
      Xname = calloc(strlen(prefix)+2,sizeof(cwp_String));
      if ( Xname == NULL )
         err("**** Unable to allocate memory for X-File name.");
      strcpy(Xname,prefix);
      strcat(Xname,".x");
   }
   if (verbose)
      warn("Relation file: %s",Xname);

   fpX = efopen(Xname, "r");
   if ( fpX == NULL )
      err("**** Error opening the relation information file");

   numX = countRec(fpX, 'X');
   warn("Found %d relation information entries.",numX);
   if ( numX == 0 )
      err("**** No relation information found!!");

   // Allocate area for the Register informations
   // calloc zero out memory.
   FileInfo = calloc(numX,sizeof(struct RegInfo));
   if ( FileInfo == NULL ){
      err("**** Unable to allocate memory for Registers Informations!!");
   }

   //  Get all Record info into memory
   RC = getFiles(fpX, rev, FileInfo);
   if ( RC != numX) {
      warn("Short read for File Informations!");
      warn("Read %d file entries instead of expected%d.",RC,numX);
   }
   if (verbose) {
      warn("Stored: %d Register Information entries.",RC);
      for (i=0; i<RC; i++)
          warn("X %4d,%1d,%9.1f,%9.1f,%4d,%4d,%1d,%9.1f,%9.1f,%10.1f,%1d",
          FileInfo[i].Num,
          FileInfo[i].Inc,
          FileInfo[i].SLine,
          FileInfo[i].SPoint,
          FileInfo[i].FChan,
          FileInfo[i].TChan,
          FileInfo[i].IncChan,
          FileInfo[i].RLine,
          FileInfo[i].FRecv,
          FileInfo[i].TRecv,
          FileInfo[i].RInc);
   }
   /* ------------------------------------------  */
   /* ==========================================  */
   /* ==========================================  */
   /* ==========================================  */

   /* 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; // Don't use dt
   }
   else 
   {
      if (verbose) warn("input is not seismic data, trid=%d",tr.trid);
      // dt = tr.d1; // Don't use dt
   }

   /* error trapping so that the user can have a default value of dt */
   if (!(dt || getparfloat("dt", &dt))) {
      // dt = .004;  // Don't use dt
      warn("WARNING:  neither dt nor d1 are set, nor is dt getparred!");
      warn("WARNING:  It is not used, just checked!!");
   }

   //nt = tr.ns;
   oldfldr  = 0;  //  fldr for last trace processed
   oldskip = 0;   //  still skipping the same fldr?
   curx = -1;      //  relation entry control
   curtrl = 0;    //  keeping tracl of current trace (in case of skip)

      
   /* ------------------------------------------  */

   /* ==========================================  */
   /* ======  Main loop over traces  ===========  */
   /* ==========================================  */

   do {

      if (tr.fldr != oldfldr) { //  Ok, we have a new fldr.
         // Advance relation entry?
         if 
            (curx+1 < numX && tr.fldr == FileInfo[curx+1].Num) {
            curx++;
            if ( curx == numX ) break;  //  No more relation available.
            // fprintf(stderr,"==> 1-curx %d\n",curx); // Debug
            // Process this one
            if ( verbose )
               warn("** processing fldr=%d",tr.fldr);
            oldfldr = tr.fldr;
            //fprintf(stderr,"==> New file %d: %d\n",curx,tr.fldr); // Debug
         }
         else {  // skip until the next file is found
            if ( tr.fldr != oldskip ) {  //  Skipping new fldr!
               if ( curx+1 == numX) {
                  curx++;
                  break;  //  No more relation available
               }
               warn("** skipping fldr=%d, looking for %d", 
                     tr.fldr,FileInfo[curx+1].Num);
               oldskip = tr.fldr;
            }
            continue;
         }
      }  // (tr.fldr != oldfldr)

      //  Ok, we are processing current fldr
      //  Is this channel within range?
      if ( tr.tracf < FileInfo[curx].FChan ) { // skip this one
         warn("** skipping fldr=%d, tracf=%d, looking for tracf=%d ",
               tr.fldr,tr.tracf,FileInfo[curx].FChan);
         continue;
      }
      else if ( tr.tracf > FileInfo[curx].TChan ) { // <FIXME> still unsure
              if ( curx+1 == numX) { // Is there any more relation info?
                 curx++; // Signal the end of table
                 break;  // Exit, no more relation available
              }
              if ( tr.fldr == FileInfo[curx+1].Num ) { // Is there more info?
                 do {
                    // Advance the register info
                    curx++;
                    if ( tr.tracf >= FileInfo[curx].FChan &&  // If chan ok,
                          tr.tracf <= FileInfo[curx].TChan) { // exit loop
                       break; // Found it
                    }

                 } while (tr.fldr == FileInfo[curx+1].Num);
                 //  Why did I get here?
                 //  do we have a new fldr?
                 if ( tr.tracf < FileInfo[curx].FChan ||
                      tr.tracf > FileInfo[curx].TChan) { // Ok, we have a new fldr.
                    //  skip this trace, look for a new file
                    continue;
                 }

              }
      }

      //  Ok, seems that we are good to process this one.
      //  Lets update the header
      //  We will keep fldr and trcf untoutched
      //  But will update tracl
      curtrl++;
      tr.tracl = curtrl;


      if ( tr.ep == 0 ) // Only if zeroed out, keep otherwise
         tr.ep = FileInfo[curx].SPoint; // No fractionary sp so far.

      tr.cdp = 0;  // not updating it yet

      //  This computes the receiver station 
      //  <FIXME>  Not sure if this use of IncChan is correct. :(
      //  It should group each IncChan channels in a single station
      //  for multicomponent data.  
      recsta = FileInfo[curx].FRecv + 
               (FileInfo[curx].TRecv-FileInfo[curx].FRecv) * 
               ((tr.tracf-FileInfo[curx].FChan)/FileInfo[curx].IncChan)/
               (FileInfo[curx].TChan-FileInfo[curx].FChan);

      //  Get the index of the point at corresponding point  structure
      idxR = GetPointIndex(RecInfo, numR, recsta,FileInfo[curx].RLine);
      idxS = GetPointIndex(SrcInfo, numS, FileInfo[curx].SPoint,
                           FileInfo[curx].SLine);
      // <FIXME> - Take care for information not available!
      // if ( idx[[R|S] < 0 ) { failed!  Skip trace/file! }

      // Avoid division by zero.
      if ( tr.scalel == 0 ) tr.scalel = 1;
      if ( tr.scalco == 0 ) tr.scalco = 1;
      
      // The scale factor
      scalel = 1./tr.scalel;
      scalco = 1./tr.scalco;
      if ( tr.scalel  < 0 )  scalel = -tr.scalel;
      if ( tr.scalco  < 0 )  scalco = -tr.scalco;

      //  Source coordinates
      tr.sx = SrcInfo[idxS].X * scalco;
      tr.sy = SrcInfo[idxS].Y * scalco;
      //  Receiver coordinates
      tr.gx = RecInfo[idxR].X * scalco;
      tr.gy = RecInfo[idxR].Y * scalco;

      if ( ibin != 0 )  {  // compute CDP number

         //  CDP Position (where to store?)
         Xcdp = (RecInfo[idxR].X+SrcInfo[idxS].X)/2.;
         Ycdp = (RecInfo[idxR].Y+SrcInfo[idxS].Y)/2.;

         //  First try for cdp computation.
         //  (may work for 2D straight lines)
         //
         temp = sqrt(pow(Xcdp-RecInfo[0].X,2) + 
                     pow(Ycdp-RecInfo[0].Y,2));
         tr.cdp = 100.5 + temp / ibin;  // 100 is just arbitrary
                                        // .5  if for rounding :P
         // Debug: print cdp# Xcdp Ycdp
         //fprintf(stderr,"cdp %5d  %10.2f  %10.2f\n",tr.cdp,Xcdp,Ycdp);

      }

      // Elevations
      tr.gelev = RecInfo[idxR].Elev * scalel;
      tr.selev = SrcInfo[idxS].Elev * scalel;
      tr.sdepth = SrcInfo[idxS].PDepth * scalel;

      // Offset - The offset signal is just an educated guess.  :/
      tr.offset = sqrt(pow(SrcInfo[idxS].X-RecInfo[idxR].X,2) + 
                       pow(SrcInfo[idxS].Y-RecInfo[idxR].Y,2));
      if ( SrcInfo[idxS].Point > RecInfo[idxR].Point )
         tr.offset = -tr.offset;

      // Assuming all coordinates in UTM projection
      tr.counit = 1;

      tr.sstat = SrcInfo[idxS].StaCor;
      tr.gstat = RecInfo[idxR].StaCor;

      puttr(&tr);
      nproct++; // count processed traces

   } while (gettr(&tr));

   /* ==========================================  */
   /* =========  End of Main loop ==============  */
   /* ==========================================  */

   /* ------------------------------------------  */

   if ( curx >= numX ) {
      warn("***  Last record processed -> fldr %d  ***",oldfldr);
      warn("***  Records after this were discarded ***");
   }

   warn("***  %d traces processed...",nproct);

   return(CWP_Exit());
}
Esempio n. 2
0
int main(int argc, char **argv)
{
	char *plotcmd;		/* build pswigb command for popen	*/
	float *trbuf;		/* trace buffer				*/
	FILE *plotfp;		/* fp for plot data			*/
	int nt;			/* number of samples on trace	  	*/
	int ntr;		/* number of traces			*/
	int verbose;		/* verbose flag				*/
	float d1;		/* time/depth sample rate		*/
	float d2;		/* trace/dx sample rate			*/
	float f1;		/* tmin/zmin			   	*/
	float f2;		/* tracemin/xmin			*/
	cwp_Bool seismic;	/* is this seismic data?		*/
	cwp_Bool have_ntr=cwp_false;/* is ntr known from header or user?	*/
	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		*/

	/* Support for irregularly spaced data */
	cwp_String key;		/* header key word with x2 information  */
	cwp_String type1=NULL;	/* ... its type				*/
	int index1=0;		/* ... its index			*/
	Value val;		/* value of key				*/
	Value scale;		/* Value of scaler			*/
	cwp_String type2=NULL;	/* ... its type				*/
	int index2=0;		/* ... its index			*/
	cwp_Bool isDepth=cwp_false;	/* Is this key a type of depth?		*/
	cwp_Bool isCoord=cwp_false;	/* Is this key a type of coordinate?	*/
	cwp_Bool irregular=cwp_false;  /* if true, reading x2 from header	*/ 
	cwp_String x2string;	/* string of x2 values			*/
	off_t x2len;		/* ... its length 			*/
	cwp_String style;	/* style parameter			*/


	/* 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("f1", &f1)) {
		if      (tr.f1)     f1 = tr.f1;
		else if (tr.delrt)  f1 = (float) tr.delrt/1000.0;
		else		f1 = 0.0;
	}

	/* Get or set ntr */
	if (getparint("n2", &ntr) || getparint("ntr", &ntr)) have_ntr = cwp_true;
	if (!getparfloat("d2", &d2)) d2 = (tr.d2) ? tr.d2 : 1.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 (!getparstring("style", &style)) style = "seismic";
	 	
	if (getparstring("key", &key)) {
		type1 = hdtype(key);
		if ( (index1 = getindex(key)) == -1 )
			err("%s: keyword not in segy.h: '%s'", __FILE__, key);
		irregular = cwp_true;
		isDepth = IS_DEPTH(key);
		isCoord = IS_COORD(key);
		if (isDepth) {
		   index2 = getindex("scalel");
		   type2 = hdtype("scalel");
		} else if (isCoord) {
		   index2 = getindex("scalco");
		   type2 = hdtype("scalco");
		}
	}


	/* 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 */
	trbuf = ealloc1float(nt);


	if (!have_ntr || irregular ) { /* count traces */
		if (verbose) {
			if (irregular) {
				warn("trace spacing from header field %s",key);
				warn("... getting positions");

			} else {
				warn("n2 not getparred and "
				     "ntr header field not set");
				warn("....  counting traces");
			}
		}

		/* Create temporary "file" to hold data */
		if (STREQ(tmpdir,"")) {
			datafp = etmpfile();
			if (irregular) x2fp = etmpfile();
			if (verbose) warn("using tmpfile() call");
		} else { /* user-supplied tmpdir */
			char directory[BUFSIZ];
			strcpy(directory, tmpdir);
			strcpy(datafile, temporary_filename(directory));
			strcpy(x2file, temporary_filename(directory));
			/* Handle user interrupts */
			signal(SIGINT, (void (*) (int)) closefiles);
			signal(SIGQUIT, (void (*) (int)) closefiles);
			signal(SIGHUP,  (void (*) (int)) closefiles);
			signal(SIGTERM, (void (*) (int)) closefiles);
			datafp = efopen(datafile, "w+");
			if (irregular) x2fp = efopen(x2file, "w+");
			istmpdir=cwp_true;		
			if (verbose)
			      warn("putting temporary files in %s", directory);
		}

		/* Loop over input data and read to temporary file */
		ntr = 0;
		if(irregular ) {
		     float x,xmin=FLT_MAX,xmax=-FLT_MAX;

		     fprintf(x2fp,"x2=");
		     do {
			if(ntr) fprintf(x2fp,",");
			++ntr;
			gethval(&tr,index1,&val);
			if (isDepth || isCoord) {
			   gethval(&tr,index2,&scale);
			   x = (float) (vtod(type1,val) *
				 pow(10.0,vtod(type2,scale)));
			} else
			   x = vtof(type1,val);
			fprintf(x2fp,"%g",x);
			xmin = MIN(xmin,x);
			xmax = MAX(xmax,x);
			if (isDepth && STREQ(style,"vsp")) {
				int i;
				for (i = 0; i < nt; ++i) tr.data[i] *= -1.0;
			}
			efwrite(tr.data, FSIZE, nt, datafp);
		     } while (gettr(&tr));

		     /* Flip vertical axis if style = vsp */
		     if (isDepth && STREQ(style,"vsp")) {
			fprintf(x2fp," x2beg=%g x2end=%g",xmax,xmin);
			style = "normal";
		     }

		     if(xmin==xmax) {
			warn("values in header %s all equal,",key);
			warn("using f2=%f d2=%f",f2,d2);
			irregular=cwp_false;
			have_ntr=cwp_false;
			efclose(x2fp);
			if (istmpdir) eremove(x2file);
		     }

		} else {
			do {
				++ntr;
				efwrite(tr.data, FSIZE, nt, datafp);
			} while (gettr(&tr));
			/* Save naive user */
			if (STREQ(style,"vsp")) {
				style = "normal";
				warn("style=vsp requires key= to be set");
			}
		}


	}

	/* Set up pswigb command line */
	if (irregular ) {
		x2len = (off_t) eftell( x2fp );
		x2string = (char *) emalloc( ++x2len );
		rewind(x2fp);
		fread(x2string,sizeof(char),x2len,x2fp);
		plotcmd = (char *) emalloc(x2len+BUFSIZ);
		if (STREQ(style,"vsp")) {
			style = "normal";
		}
		sprintf(plotcmd, "%spswigb n1=%d d1=%f f1=%f %s style=%s", bindir,
			   nt, d1, f1, x2string, style);
		free(x2string);
	} else {
		if (STREQ(style,"vsp")) {
			style = "normal";
		}
		plotcmd = (char *) emalloc(BUFSIZ);
		sprintf(plotcmd,
			"%spswigb n1=%d n2=%d d1=%f d2=%f f1=%f f2=%f style=%s", bindir,
			   nt, ntr, d1, d2, f1, f2, style);
	}


	for (--argc, ++argv; argc; --argc, ++argv) {
		if (strncmp(*argv, "d1=", 3) && /* skip those already set */
		    strncmp(*argv, "d2=", 3) &&
		    strncmp(*argv, "f1=", 3) &&
		    strncmp(*argv, "f2=", 3) &&
		    strncmp(*argv, "style=", 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 to pswigb and send the traces */
	plotfp = epopen(plotcmd, "w");
	free(plotcmd);

	if (!have_ntr || irregular) { /* send out stored traces one by one */
		rewind(datafp);
		{ register int itr;
			for (itr = 0; itr < ntr; ++itr) {
				efread (trbuf, FSIZE, nt, datafp);
				efwrite(trbuf, FSIZE, nt, plotfp);
			}
		}
	} else { /* just pump out traces and let pswigb do the work */
		do {
			efwrite(tr.data, FSIZE, nt, plotfp);
		} while (gettr(&tr));
	}


	/* Clean up */
	epclose(plotfp);
	if (!have_ntr) {
		efclose(datafp);
		if (istmpdir) eremove(datafile);
	}
	if (irregular) {
		efclose(x2fp);
		if (istmpdir) eremove(x2file);
	}

	return EXIT_SUCCESS;
}
Esempio n. 3
0
int
main(int argc, char **argv)
{
	char plotcmd[BUFSIZ];	/* build psmovie command for popen 	*/
	float *trbuf;		/* trace buffer			 	*/
	FILE *plotfp;		/* fp for plot data			*/
	int nt;			/* number of samples on trace		*/
	int n2;			/* number of traces per frame		*/
	int n3;			/* number of frames in data		*/
	int ntr;		/* number of traces			*/
	int verbose;		/* verbose flag				*/
	float d1;		/* time/depth sample rate 		*/
	float d2;		/* trace/dx sample rate 		*/
	float f1;		/* tmin/zmin				*/
	float f2;		/* tracemin/xmin	 		*/
	cwp_Bool seismic;	/* is this seismic data?		*/
	cwp_Bool have_n2 = cwp_false;/* was n2 getparred?			*/
	cwp_Bool have_n3 = cwp_false;/* was n3 getparred?			*/
	cwp_Bool have_ntr = cwp_false;/* was ntr set in header?		*/
	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 (!getparfloat("f2", &f2)) f2 = 1.0;

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

	/* 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 */
	trbuf = ealloc1float(nt);

	/* Get or set n2 and n3 */
	if (getparint("n2", &n2)) have_n2 = cwp_true;
	if (getparint("n3", &n3)) have_n3 = cwp_true;
	if (have_n2 && have_n3) have_ntr = cwp_true;

	if (!have_ntr) { /* count traces */
		if (verbose) {
		   warn("n2 or n3 not getparred, or ntr header field not set");
		   warn("         ... counting traces");
		}

		/* Create temporary "file" to hold data */
		if (STREQ(tmpdir,"")) {
			tracefp = etmpfile();
			if (verbose) warn("using tmpfile() call");
		} else { /* user-supplied tmpdir */
			char directory[BUFSIZ];
			strcpy(directory, tmpdir);
			strcpy(tracefile, temporary_filename(directory));
			/* Handle user interrupts */
			signal(SIGINT, (void (*) (int)) closefiles);
			signal(SIGTERM, (void (*) (int)) closefiles);
			tracefp = efopen(tracefile, "w+");
			istmpdir=cwp_true;		
			if (verbose)
			      warn("putting temporary files in %s", directory);
		}

       
		/* Loop over input frames & put them into the data file */
		ntr = 0;
		do {
			++ntr;
			efwrite(tr.data, FSIZE, nt, tracefp);
		} while (gettr(&tr));

	} 

	/* Set dimensions of movie */
	if (!have_n2 && !have_n3) { n2 = ntr; n3=1; } 
	if (have_n2 && !have_n3) n3 = ntr/n2;
	if (!have_n2 && have_n3) n2 = ntr/n3;

	/* Set up psmovie command line */
	sprintf(plotcmd,
		"%spsmovie n1=%d n2=%d n3=%d d1=%f d2=%f f1=%f f2=%f", bindir,
			   nt, n2, n3, d1, d2, f1, f2);

	fprintf(stderr, "%s\n", plotcmd);

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


	/* Open pipe to psmovie and send the traces */
	plotfp = epopen(plotcmd, "w");
	
	if (!have_ntr){
			/* send out stored traces one by one */
		rewind(tracefp);
		{ register int itr;
			for (itr = 0; itr < ntr; ++itr) {
				efread (trbuf, FSIZE, nt, tracefp);
				efwrite(trbuf, FSIZE, nt, plotfp);
			}
		}
	} else { /* just pump out traces and let psmovie do the work */
		do {
			efwrite(tr.data, FSIZE, nt, plotfp);
		} while (gettr(&tr));
	}


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


	return EXIT_SUCCESS;
}
Esempio n. 4
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());
}
Esempio n. 5
0
int
main(int argc, char **argv)
{
	char *key=NULL;		/* header key word from segy.h		*/	
	char *type=NULL;	/* ... its type				*/
	int index;		/* ... its index			*/
	Value val;		/* ... its value			*/
	float fval;		/* ... its value cast to float		*/
	float twfval;		/* ... its value cast to float		*/
	float *xmute=NULL;	/* array of key mute curve values	*/
	float *tmute=NULL;	/* ...		mute curve time values 	*/
	float *twindow=NULL;	/* ...	mute window time values mode=4	*/
	float linvel;		/* linear velocity			*/
	float tm0;		/* time shift of mute=2 or 3 for 'key'=0*/
	float *taper=NULL;	/* ...		taper values		*/
	int nxmute=0;		/* number of key mute values		*/
	int ntmute;	/* ...		mute time values 	*/
	int ntwindow;	/* ...		mute time values 	*/
	int ntaper;	/* ...		taper values		*/

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

	seismic = ISSEISMIC(tr.trid);

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

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

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

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

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

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

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

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


		}
		puttr(&tr);
	} while (gettr(&tr));
	
	return(CWP_Exit());
}
Esempio n. 6
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;
}
Esempio n. 7
0
int
main(int argc, char **argv)
{
	cwp_String mode;	/* display: real, imag, amp, arg	*/
	int imode=AMP;		/* integer abbrev. for mode in switch	*/
	register complex *ct;	/* complex trace			*/
	int nt;			/* number of points on input trace	*/
	float dt;		/* sample spacing			*/
	float *data;		/* array of data from each trace	*/
	float *hdata;		/* array of Hilbert transformed data	*/
	float unwrap;		/* PI/unwrap=min dphase assumed to by wrap*/
	int wint;		/* n time sampling to window */
	cwp_Bool seismic;	/* is this seismic data?		*/
	int ntout;
	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);
	

	/* Get info from first trace */
	if (!gettr(&tr)) err("can't get first trace");
	nt = tr.ns;
	dt = ((double) tr.dt)/1000000.0;
	ntout = nt + nt -1;

	/* check to see if data type is seismic */
	seismic = ISSEISMIC(tr.trid);

	if (!seismic)
		warn("input is not seismic data, trid=%d", tr.trid);

	/* Get mode; note that imode is initialized to AMP */
	if (!getparstring("mode", &mode))	mode = "amp";

	if      (STREQ(mode, "phase"))  imode = ARG;
	else if (STREQ(mode, "freq"))	imode = FREQ;
	else if (STREQ(mode, "bandwidth")) imode = BANDWIDTH;
	else if (STREQ(mode, "normamp")) imode = NORMAMP;
	else if (STREQ(mode, "freqw")) imode = FREQW;
	else if (STREQ(mode, "thin")) imode = THIN;
	else if (STREQ(mode, "fdenv")) imode = FENV;
	else if (STREQ(mode, "sdenv")) imode = SENV;
	else if (STREQ(mode, "q")) imode = Q;
	else if (!STREQ(mode, "amp"))
		err("unknown mode=\"%s\", see self-doc", mode);

	/* getpar value of unwrap */
	switch(imode) {
	case FREQ:
		if (!getparfloat("unwrap", &unwrap))	unwrap=1;
	break;
	case Q:
		if (!getparfloat("unwrap", &unwrap))	unwrap=1;
	break;
	case FREQW:
		if (!getparfloat("unwrap", &unwrap))	unwrap=1;
		if (!getparint("wint", &wint))	wint=3; 
	break;
	case THIN:
		if (!getparfloat("unwrap", &unwrap))	unwrap=1;
		if (!getparint("wint", &wint))	wint=3;
	break;
	case ARG:
		if (!getparfloat("unwrap", &unwrap))	unwrap=0;
	break;
	}

	/* allocate space for data and hilbert transformed data, cmplx trace */
	data = ealloc1float(nt);
	hdata = ealloc1float(nt);
	ct = ealloc1complex(nt);


	/* Loop over traces */
	do {
		register int i;

		/* Get data from trace */
		for (i = 0; i < nt; ++i)  data[i] = tr.data[i];

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

		/* build the complex trace */
		for (i = 0; i < nt; ++i)  ct[i] = cmplx(data[i],hdata[i]);

		/* Form absolute value, phase, or frequency */
		switch(imode) {
		case AMP:
			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				tr.data[i] = sqrt(re*re + im*im);
			}
			
			/* set trace id */
			tr.trid = ENVELOPE;
		break;
		case ARG:
		{
			float *phase = ealloc1float(nt);

			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				if (re*re+im*im)  phase[i] = atan2(im, re);
				else              phase[i] = 0.0;
			}

			/* phase unwrapping */
			/* default unwrap=0 for this mode */
			if (unwrap!=0) unwrap_phase(nt, unwrap, phase);
			
			/* write phase values to tr.data */
			for (i = 0; i < nt; ++i) tr.data[i] = phase[i];
			
			/* set trace id */
			tr.trid = INSTPHASE;
		}
		break;
		case FREQ:
		{
			float *phase = ealloc1float(nt);
			float	fnyq = 0.5 / dt;

			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				if (re*re+im*im) {
					phase[i] = atan2(im, re);
				} else {
					phase[i] = 0.0;
				}
				
			}

			/* unwrap the phase */
			if (unwrap!=0) unwrap_phase(nt, unwrap, phase);

			/* compute freq(t)=dphase/dt */
			differentiate(nt, 2.0*PI*dt, phase);
			
			/* correct values greater nyquist frequency */
			for (i=0 ; i < nt; ++i)	{
				if (phase[i] > fnyq)
					phase[i] = 2 * fnyq - phase[i];
			}
                                        
			/* write freq(t) values to tr.data */
			for (i=0 ; i < nt; ++i) tr.data[i] = phase[i];

			/* set trace id */
			tr.trid = INSTFREQ;
		}
		break;
		case FREQW:
		{
			float	fnyq = 0.5 / dt;
			float *freqw = ealloc1float(nt);
			float *phase = ealloc1float(nt);
			float *envelop = ealloc1float(nt);
			float *envelop2 = ealloc1float(nt);
			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				if (re*re+im*im) {
					phase[i] = atan2(im, re);
					} else {
						phase[i] = 0.0;
						}
				envelop[i] = sqrt(re*re + im*im);
			}

			/* unwrap the phase */
			if (unwrap!=0) unwrap_phase(nt, unwrap, phase);

			/* compute freq(t)=dphase/dt */
			differentiate(nt, 2.0*PI*dt, phase);
			
			/* correct values greater nyquist frequency */
			for (i=0 ; i < nt; ++i)	{
				if (phase[i] > fnyq)
					phase[i] = 2 * fnyq - phase[i];
			envelop2[i]=envelop[i]*phase[i];
			}
			twindow(nt, wint, envelop);
			twindow(nt, wint, envelop2);
			/* correct values greater nyquist frequency */
			for (i=0 ; i < nt; ++i) {
			freqw[i] = (envelop[i] == 0.0) ? 0.0 :envelop2[i]/envelop[i];
			}
			/* write freq(t) values to tr.data */
			for (i=0 ; i < nt; ++i) tr.data[i] = freqw[i];
			
			/* set trace id */
			tr.trid = INSTFREQ;
		}
		break;
		case THIN:
		{
			float	fnyq = 0.5 / dt;
			float *phase = ealloc1float(nt);
			float *freqw = ealloc1float(nt);
			float *phase2 = ealloc1float(nt);



			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;

				if (re*re+im*im) {
					phase[i] = atan2(im, re);
				} else {
					phase[i] = 0.0;
				}
			}

			/* unwrap the phase */
			if (unwrap!=0) unwrap_phase(nt, unwrap, phase);

			/* compute freq(t)=dphase/dt */
			differentiate(nt, 2.0*PI*dt, phase);

			/* correct values greater nyquist frequency */
			for (i=0 ; i < nt; ++i)	{
				if (phase[i] > fnyq)
					phase[i] = 2 * fnyq - phase[i];
					phase2[i]= 2 * fnyq - phase[i];
			}
			/* Do windowing for Average Ins . Freq over wint*/
			twindow(nt, wint, phase2);

			for (i=0 ; i < nt; ++i)	{
				freqw[i] = phase[i] - phase2[i];
			/*	if (abs(freqw[i]) > fnyq)
				freqw[i] = 2 * fnyq - freqw[i];
			*/
			/* write Thin-Bed(t) values to tr.data */
				tr.data[i] = freqw[i];
				}
			/* set trace id */
			tr.trid = INSTFREQ;
		}
		break;
		case BANDWIDTH:
		{
			float *envelop = ealloc1float(nt);
			float *envelop2 = ealloc1float(nt);

		/* Bandwidth (Barnes 1992)

		          |d(envelope)/dt|
		band =abs |--------------|
		          |2 PI envelope |
	 	*/

			for (i = 0; i < nt; ++i) {
				float er = ct[i].r;
				float em = ct[i].i;
				envelop[i] = sqrt(er*er + em*em);
				envelop2[i]=sqrt(er*er + em*em);

			}
				differentiate(nt, dt, envelop);

				for (i = 0; i < ntout; ++i) {
				   if (2.0*PI*envelop2[i]!=0.0) {
					tr.data[i] = ABS(envelop[i]/(2.0*PI*envelop2[i]));
				   } else {
				        tr.data[i]=0.0;
				   }
				}
				tr.trid = ENVELOPE;
		}
		break;
		case NORMAMP:
		{
			float phase;
			float *na = ealloc1float(nt);
			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				if (re*re+im*im)  phase = atan2(im, re);
				else              phase = 0.0;
				na[i] = cos(phase);
			}
			for (i=0 ; i < nt; ++i) tr.data[i] = na[i];
			
			/* set trace id */
			tr.trid = INSTPHASE;
			}
		break;
		case FENV:
		{
			float *amp = ealloc1float(nt);
			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				amp[i] = sqrt(re*re + im*im);
			}
		/*conv(nt, 0, envelop, nt, 0, time, ntout, 0, ouput);*/

		differentiate(nt, 2.0*PI*dt, amp);
		for (i=0 ; i < nt; ++i) tr.data[i] = amp[i];
			/* set trace id */
			tr.trid = ENVELOPE;
		}
		break;
		case SENV:
		{
			float *amp = ealloc1float(nt);
			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				amp[i] = sqrt(re*re + im*im);
			}

		differentiate(nt, 2.0*PI*dt, amp);
		differentiate(nt, 2.0*PI*dt, amp);
		for (i=0 ; i < nt; ++i) tr.data[i] = amp[i];
			/* set trace id */
			tr.trid = ENVELOPE;
		}
		break;

		case Q:
		{
			float *envelop = ealloc1float(nt);
			float *envelop2 = ealloc1float(nt);
			float *phase = ealloc1float(nt);
			float	fnyq = 0.5 / dt;

		/* Banswith (Barnes 1992)

		        -PI Freq(t) d(envelope)/dt
		band =  --------------------------
		                 envelope(t)
	 	*/

			for (i = 0; i < nt; ++i) {
				float re = ct[i].r;
				float im = ct[i].i;
				envelop[i] = sqrt(re*re + im*im);
				envelop2[i]=sqrt(re*re + im*im);
				if (re*re+im*im) {
					phase[i] = atan2(im, re);
				} else {
					phase[i] = 0.0;
				}

			}
			/* get envelope diff */
			differentiate(nt, dt, envelop);
			/* unwrap the phase */
			if (unwrap!=0) unwrap_phase(nt, unwrap, phase);
			/* compute freq(t)=dphase/dt */
			differentiate(nt, 2.0*PI*dt, phase);

			for (i=0 ; i < nt; ++i)	{
				if (phase[i] > fnyq)
					phase[i] = 2 * fnyq - phase[i];
			}

			for (i = 0; i < ntout; ++i) {
				if (envelop[i]!=0.0)
				tr.data[i] = -1*PI*phase[i]*envelop2[i]/envelop[i];
				else
				tr.data[i]=0.0;
				}
				tr.trid = INSTFREQ;
		}
		break;
		default:
			err("%s: mysterious mode=\"%s\"", __LINE__, mode);
		}


		tr.d1 = dt;   /* for graphics */
		puttr(&tr);

	} while (gettr(&tr));


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

        /* OUTPUT FILE POINTERS */
    FILE *stalta=NULL;
    FILE *headerfp=NULL; /* temporary file for trace headers */
        
    char *file=NULL;         /* base of output file name(s) */
    char *fname=NULL;        /* complete output file name */
        
    int nt;			/* number of samples in one trace	*/
    int nsta;               /* number of samples for short term window */
    int nlta;               /* number of samples for long term window  */
    int verbose;		/* design info flag 			*/
    int it;                 /* index for time sample in main loop */


    double *data_trace;      /* individual trace data                */
   	double dt;		/* sample spacing, sec			*/
//  	double nyq;		/* nyquist frequency			*/
//    double sta=0;              /* short term avg. value              */
//    double lta=1.0e-99;              /* long term avg. value           */
    double trigger;          /* threshold value for detection        */
    double *charfct=NULL; /* output sta/lta trace                */

	cwp_Bool seismic;	/* is this seismic data?		*/



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


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


	/* Get Parameters */
	if (!getparint("verbose", &verbose))	verbose = 0;
	if (!getparint("nlta", &nlta))	nlta = nt/ 10;
	if (!getparint("nsta", &nsta))	nsta = nlta / 10;
    if (!getparstring("file", &file)) file="sta_lta";	
	
    /* allocate space for input data and analysis vectors */
    data_trace = ealloc1double(nt); data_trace-=1;


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

    /* set filenames and open files */
    fname = malloc( strlen(file)+7 );    
    sprintf(fname, "%s.su", file);    stalta = efopen(fname, "w");	    
    free(fname);    
    
    /* allocate and zero out space for output data */
    charfct = ealloc1double(nt); 
    memset((void *) charfct, 0, nt*FSIZE);    

        /* Main loop over traces */
        

	do {
	    /* store trace header in temporary file and read data */
        efwrite(&tr, HDRBYTES, 1, headerfp);
      	memcpy((void *) data_trace, (const void *) &tr.data, nt*FSIZE);        


        /* STA/LTA trace generation */
        recstalta(data_trace, charfct, nt, nsta, nlta);           
        fputdata(stalta, headerfp, charfct, nt);


	} while (gettr(&tr));

   /* close files */
   efclose(headerfp);
   efclose(stalta);
	return(CWP_Exit());
}
Esempio n. 9
0
int
main(int argc, char **argv)
{
	register float *rt;	/* real trace				*/
	register complex *ct;	/* complex transformed trace		*/
	int nt;			/* number of points on input trace	*/
	int nfft;		/* transform length			*/
	int nf;			/* number of frequencies		*/
	int sign;		/* sign in exponent of transform	*/
	int verbose;		/* flag to get advisory messages	*/
	float dt;		/* sampling interval in secs		*/
	float d1;		/* output sample interval in Hz		*/
	cwp_Bool seismic;	/* is this seismic data? */
	float c;		/* multiplier				*/
	float w0, w1, w2;	/* weights				*/

	/* Initialize */
	initargs(argc, argv);
	requestdoc(1);
	if (!getparint("verbose", &verbose))	verbose=1;

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

	/* check for seismic or well log data */
	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) {
		dt = .004;
		if (verbose) warn("dt or d1 not set, assumed to be .004");
	}

	/* Set up pfa fft */
	nfft = npfaro(nt, LOOKFAC * nt);
	if (nfft >= SU_NFLTS || nfft >= PFA_MAX)  err("Padded nt=%d--too big", nfft);
	nf = nfft/2 + 1;
	d1 = 1.0/(nfft*dt);

	if (!getparint("sign", &sign)) sign = 1;
	if (sign != 1 && sign != -1)   err("sign = %d must be 1 or -1", sign);

	/* get weights */
	if (!getparfloat("w0",&w0)) w0 = 0.75;
	if (!getparfloat("w1",&w1)) w1 = 1.00;
	if (!getparfloat("w2",&w2)) w2 = 0.75;

	rt = ealloc1float(nfft);
	ct = ealloc1complex(nf);

	/* If dt not set, issue advisory on frequency step d1 */
	if (dt && verbose)  warn("d1=%f", 1.0/(nfft*dt));

	/* Main loop over traces */
	do {
		register int i;

		/* Load trace into rt (zero-padded) */
		memcpy((void *) rt, (const void *) tr.data, nt*FSIZE);
		memset((void *) (rt + nt), (int) '\0', (nfft-nt)*FSIZE);

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

		/* Store values */
		for (i = 0; i < nf; ++i) {
			c =w0*rcabs(ct[i-1])+w1*rcabs(ct[i])+w2*rcabs(ct[i+1]);
			if (i==0 || i==nf) {
				tr.data[2*i]   = ct[i].r / rcabs(ct[i]);
				tr.data[2*i+1] = ct[i].i / rcabs(ct[i]);
			} else {
				tr.data[2*i]   = ct[i].r / c;
				tr.data[2*i+1] = ct[i].i / c;
			}
		}

		/* Set header values--npfaro makes nfft even */
		tr.ns = 2 * nf;
		tr.trid = FUNPACKNYQ;
		tr.d1 = d1;
		tr.f1 = 0.0;

		puttr(&tr);

	} while (gettr(&tr));


	return(CWP_Exit());
}