int save_origin(int nass, int evid, Dbptr master_db, Dbptr dbtmp,
			Hypocenter h,Location_options o, int orb)
{
	int ndef;
	char dtype[2];
        char algorithm[16]="ggnloc";
	char auth[16]="orbgenloc";
	int grn, srn;
	int orid;  /* orid returned */

	orid = dbnextid(master_db,"orid");
	if(orid  < 0 )
		elog_die(1,"save_origin:  dbnextid failure asking for new orid\n");
        if(o.fix[2])
        {
                ndef = h.degrees_of_freedom + 3;
                strcpy(dtype,"r");
        }
        else
        {
                ndef = h.degrees_of_freedom + 4;
                strcpy(dtype,"f");
        }
	grn = grnumber(h.lat, h.lon) ;
	srn = srnumber ( grn ) ;
	dbtmp = dblookup(dbtmp,0,"origin",0,0);
	dbtmp.record = dbSCRATCH;
	if((dbputv(dbtmp,0,
                "lat",h.lat,
                "lon",h.lon,
                "depth",h.z,
                "time",h.time,
                "orid",orid,
		"evid",evid,
		"nass",nass,
		"grn", grn,
		"srn", srn,
		"dtype",dtype,
		"ndef",ndef,
		"algorithm",algorithm,
		"auth",auth,0))
			 == dbINVALID)
	{
		elog_complain(0,"dbputv error while building origin record for orid %d\nNo results saved\n",
			orid);
	}
	else
	{
		if(save_dbrecord(dbtmp,orb))
			elog_complain(0,"Errors saving orid %d\n",orid);
	}
	return(orid);
}
long save_origin(Dbptr dbi, long is, long ie, int depth_fixed,
	Hypocenter h, Dbptr dbo)
{
	long orid;

	/* These are parameters copied from input db -- names = css names */
	long evid;
	long jdate;
	long grn;
	long srn;
	char etype[8];
	double mb;
	long mbid;
	double ms;
	long msid;
	double ml;
	long mlid;
	/* These obtained from this solution */

	long nass;
	long ndef;
	char dtype[2];
	char algorithm[16]="genloc-nlls";
	char auth[20];
	double lddate;
	

	/* these are intentionally left null: ndp,depdp,commid*/


	/* set but obtained directly from hypo structure 
	lat, lon, depth, time */

	dbo = dblookup(dbo,0,"origin",0,0);
	
	/* Grab what we need from the input db for copying.  Note
	that because the joins used here, each of the input db
	records have the same origin entries.  Thus, we just fetch
	stuff from row is.  */
	dbi.record = is;
	if( dbgetv(dbi,0,
		"origin.evid", &evid,
		"origin.jdate", &jdate,
		"origin.grn", &grn,
		"origin.srn", &srn,
		"origin.etype", etype,
		"origin.mb", &mb,
		"origin.mbid", &mbid,
		"origin.ms", &ms,
		"origin.msid", &msid,
		"origin.ml", &ml,
		"origin.mlid", &mlid,
				NULL) == dbINVALID)
	{
		elog_die(1,"save_origin: dbgetv error reading origin fields of input view at record %ld\n",
				is);
	}
	nass = ie - is;
	/* ndef is potentially wrong by this calculation.  We set ndef 
	from the number of degrees of freedom in the solution + npar
	where npar is 3 when depth is fixed and 4 otherwise.  This does
	not match the real definition of ndef, especially when array 
	data are used because each arrival then then has 3 data points
	used to constrain the solution.  These is either an error in 
	my (glp) understanding of the css3.0 schema or a flaw in its 
	design.*/
	if(depth_fixed)
	{
		ndef = h.degrees_of_freedom + 3;
		strcpy(dtype,"r");
	}
	else
	{
		ndef = h.degrees_of_freedom + 4;
		strcpy(dtype,"f");
	}
	my_username(auth);
	lddate = std_now();
	orid = dbnextid(dbo,"orid");
	if(dbaddv(dbo,0,
                "lat",h.lat,
                "lon",h.lon,
                "depth",h.z,
                "time",h.time,
                "orid",orid,
                "evid",evid,
                "jdate",jdate,
                "nass",nass,
                "ndef",ndef,
                "grn",grn,
                "srn",srn,
                "etype",etype,
                "dtype",dtype,
                "mb",mb,
                "mbid",mbid,
                "ms",ms,
                "msid",msid,
                "ml",ml,
                "mlid",mlid,
                "algorithm",algorithm,
                "auth",auth,
                "lddate",lddate,
			NULL) == dbINVALID)
	{
		elog_die(1,"save_origin: dbaddv error writing orid %ld\n",
				orid);
	}
	return(orid);
}
Esempio n. 3
0
save_ms ( Dbptr dborig ) {

     Dbptr db;
     Event *event;
     Tbl  *AllMs;
     double sum, unc;
     char auth[64], net[16], sta[16];
     char magtype[8];
     char *str, orig_str[16];
     int numms, total;
     int smags, nmags;
     int i;
     int arid, orid, evid, msid, magid;



     AllMs = keysarr( AllEv );
     numms = maxtbl( AllMs );
     if( numms <= 0 )  {
         complain (0, "Ther are no MS found for current orid.\n");
         return 0 ;
     }

     unc = 0.0; sum=0.0; total=0;

     for( i = 0; i < numms; i++ )  {
           str = ( char *) gettbl( AllMs, i );
           event = ( Event *) getarr( AllEv, str );
           if( event->ms < 0 )  continue;
           sum += event->ms;
           total ++;
     }
     sum /= total;
     if( total > 1 )  {
        for( i = 0; i < numms; i++ )  {
            str = ( char *) gettbl( AllMs, i );
            event = ( Event *) getarr( AllEv, str );
            if( event->ms < 0 )  continue;
            unc += (event->ms-sum) * (event->ms-sum);
        }
        unc /= (total-1);
        unc = sqrt(unc);
     } else unc = -1.0;


     /*  Fill netmag table  */

     db = dblookup (dborig, 0, "netmag", 0, 0);
     dbquery (db, dbRECORD_COUNT, &nmags);
	  
     magid = -1;
     for ( db.record = 0; db.record < nmags; db.record++) {
	dbgetv (db, 0, 
                "net", net, 
		"orid", &orid, 
                "magtype", magtype, 0);

        sprintf( orig_str, "%d\0", orid);
        if( !regexec( &orig_match, orig_str, (size_t) 0, NULL, 0 ) &&
            /*!regexec( &net_match, net, (size_t) 0, NULL, 0 ) &&  */
            orid == event->orid &&
            !strcmp(magtype, "ms")) break;
    }
   
    if ( db.record < nmags) {
	dbgetv (db, 0, "magid", &magid, 0);
	dbputv (db, 0, 
                "magid", magid, 
		"evid", event->evid,
		"magtype", "ms",
		"nsta", total,
		"magnitude", sum,
		"uncertainty", unc,
		"auth", "dbms", 0);
   } else  if ( sum > 0) {
		magid = dbnextid (db, "magid");
		db.field = dbALL;
		db.record = dbSCRATCH;
		dbputv (db, 0, 
			"net", event->net,
			"orid", event->orid,
			"evid", event->evid,
			"magid", magid, 
			"magtype", "ms",
			"nsta", total,
			"magnitude", sum,
			"uncertainty", unc,
			"auth", "dbms", 0);
		dbadd (db, 0);
   }

   msid = magid;

   /*	Fill origin table with MS  */                           
 
   if( !regexec( &orig_match, orig_str, (size_t) 0, NULL, 0 ) &&
       !regexec( &auth_match, event->auth, (size_t) 0, NULL, 0 ) ) {
	db = dball;
        db.record = Crnt_record;
	dbputv (db, 0, "ms", sum, "msid", msid, 0);
    }

   
    /*	Fill MS into stamag table  */
     

   db = dball;
   db = dblookup (db, 0, "stamag", 0, 0);
   dbquery (db, dbRECORD_COUNT, &smags);

   for( i = 0; i < numms; i ++ )  {
       str = ( char *) gettbl( AllMs, i );
       event = ( Event *) getarr( AllEv, str );
       if( event->ms < 0 )  continue;
       for (db.record=0; db.record<smags; db.record++) {
           dbgetv (db, 0, "sta", sta, "magid", &magid, 0);
           if (magid == msid && !strcmp(event->sta, sta)) break;
       }
       if (db.record<smags) {
 	   dbputv (db, 0, 
		"arid", event->arid,
		"orid", event->orid,
		"evid", event->evid,
		"phase", event->phase,
		"magtype", "ms",
		"magnitude", event->ms,
		"auth", "dbms", 0);
       } else if (event->ms > 0) {
		db.field = dbALL;
		db.record = dbSCRATCH;
		dbputv (db, 0, 
			"sta", event->sta,
			"arid", event->arid,
			"orid", event->orid,
			"evid", event->evid,
			"phase", event->phase,
			"magid", msid, 
			"magtype", "ms",
			"magnitude", event->ms,
			"auth", "dbms", 0);
		dbadd (db, 0);
       }	
       free(event);
       delarr( AllEv, str);
   }
 

    freetbl( AllMs, 0 );
    return (1);
}
Esempio n. 4
0
int main(int argc, char *argv[])
{
  unsigned int irand;
  int      isamp,wsamp,exists,iret,jdate,nsamp,wfid,itype,i,half;
  long int nw;
  double   samprate,time,endtime,toff,width;
  float    *s,*n,del,nfactor,mean,stdv,dummy,h;
  char     sta[7],chan[9],*database,*type;
  char     dir[65],dfile[33],outfile[100];
  Dbptr    db,dbw;
  FILE     *fp;
 
  database = malloc(80);
  type = malloc(20);

  if (argc < 13) 
  {
    printf("Usage: %s type toff width nfactor sta chan time samprate nsamp database dir filename\n",argv[0]);
    return 1;
  }

  type = argv[1];
  sscanf(argv[2],"%lf",&toff);
  sscanf(argv[3],"%lf",&width);
  sscanf(argv[4],"%f",&nfactor);
  strcpy(sta,argv[5]);
  strcpy(chan,argv[6]);
  sscanf(argv[7],"%lf",&time);
  sscanf(argv[8],"%lf",&samprate);
  sscanf(argv[9],"%d",&nsamp);
  database = argv[10];
  strcpy(dir,argv[11]);
  strcpy(dfile,argv[12]);
  s = malloc(nsamp*sizeof(float));
  n = malloc(nsamp*sizeof(float));

/*Open the output database.*/

  exists = 1;
  if ( (fp = fopen(database,"r")) == NULL)
    exists = 0;
  else
    fclose(fp);

/*It exists, so check if it can be opened and written to.*/

  if (exists)
  {
    if (dbopen(database,"r+",&db) < 0)
    {
      complain(0,"Could not open existing database for writing.\n");
      return 1;
    }
  }
  else
  {
    if (dbcreate(database,"css3.0",0,0,0) != 0)
    {
      complain(0,"Could not create new database.\n");
      return 1;
    }
    else
    {
      if (dbopen(database,"r+",&db) != 0)
      {
        complain(0,"Could not open new database for writing.\n");
        return 1;
      }
    }
  }

  dbw = dblookup(db,0,"wfdisc",0,0);
  iret = dbquery(dbw,dbRECORD_COUNT,&nw);
  printf("nw = %ld\n",nw);
  wfid = dbnextid(db,"wfid");

/*Create the synthetic trace.*/
  if (strcmp(type,"zeros"    ) == 0) itype = 1;
  if (strcmp(type,"delta"    ) == 0) itype = 2;
  if (strcmp(type,"boxcar"   ) == 0) itype = 3;
  if (strcmp(type,"triangle" ) == 0) itype = 4;
  if (strcmp(type,"sine"     ) == 0) itype = 5;
  if (strcmp(type,"impulse"  ) == 0) itype = 6;
  if (strcmp(type,"noise"    ) == 0) itype = 7;

/*Generate a zero-mean, unit rms, random noise series, whether used or not.*/
  irand = now()-1200000000;
  srand(irand);        /* sets the RNG with a random start integer*/
  for (i=0;i<nsamp;i++)
  {
/*    Use a trick to make sure some abnormal number is not generated.*/
      n[i] = 10.0;
      while (fabs(n[i]) > 9.9) n[i] = sqrt(-2.0*log(1.0 - 
        ((float) rand())/RAND_MAX))*cos(6.2832 * ((float) rand())/RAND_MAX);
  }
  del = 1/samprate;
  printf("itype = %d\n",itype);
  switch (itype) 
  {
    case 1:
      /*This creates a series of zeroes.*/
      for (i=0;i<nsamp;i++) s[i] = 0.0;
      break;
    case 2:
      /*This creates a delta function.*/
      for (i=0;i<nsamp;i++) s[i] = 0.0;
      isamp = toff*samprate;
      s[isamp] = 1.0;
      if (nfactor > 0)
      { 
        for (i=0;i<nsamp;i++) s[i] = s[i] + nfactor*n[i];
      }
      break;
    case 3:
      /*This creates a boxcar function.*/
      for (i=0;i<nsamp;i++) s[i] = 0.0;
      wsamp = width*samprate;
      /*Make it odd number of points, with center point splitting the boxcar.*/
      if (wsamp%2 == 0) wsamp = wsamp + 1;
      isamp = toff*samprate;
      for (i=isamp;i<isamp+wsamp;i++) s[i] = 1.0;
      if (nfactor > 0)
      { 
        for (i=0;i<nsamp;i++) s[i] = s[i] + nfactor*n[i];
      }
      break;
    case 4:
      /*This creates a triangle function.*/
      for (i=0;i<nsamp;i++) s[i] = 0.0;
      wsamp = width*samprate;
      /*Make it odd number of points, with peak at center point.*/
      if (wsamp%2 == 0) wsamp = wsamp + 1;
      half = wsamp/2;
      isamp = toff*samprate;
      for (i=isamp;i<isamp+half;i++) s[i] = 1.0*(i-isamp)/(float)half;
      s[isamp+half] = 1.0;
      for (i=isamp+half+1;i<isamp+wsamp;i++) s[i] = 1.0*(isamp+wsamp-i-1)/(float)half;
      if (nfactor > 0)
      { 
        for (i=0;i<nsamp;i++) s[i] = s[i] + nfactor*n[i];
      }
      break;
    case 5:
      /*This creates a 1/width Hz sine wave.*/ 
      for (i=0;i<nsamp;i++) s[i] = sin(2*pi*i*del/width);
      if (nfactor > 0)
      { 
        for (i=0;i<nsamp;i++) s[i] = s[i] + nfactor*n[i];
      }
      break;
    case 6:
      /*This creates an exponentially decaying sine wave, like a seismometer
        delta response (damping = 0.7).*/
      h = 0.7;
      for (i=0;i<nsamp;i++) s[i] = 0.0;
      isamp = toff*samprate;
      for (i=0;i<nsamp-isamp;i++) 
        s[i+isamp] = sin(2*pi*sqrt(1-h*h)*i*del/width)*exp(-0.7*2*pi*i*del/width);
      if (nfactor > 0)
      { 
        for (i=0;i<nsamp;i++) s[i] = s[i] + nfactor*n[i];
      }
      break;
    case 7:
      /*This creates a random white-noise series.*/
      for (i=0;i<nsamp;i++) s[i] = n[i];
      iret = stats(s,nsamp,2,&mean,&stdv,&dummy,&dummy);
      printf("mean,stdv = %f %f\n",mean,stdv);
      break;
    default:
      printf("Input 'type' does not match any options.\n");
      return 1;
  }

/*Write out the new trace.*/
  memcpy(outfile,"\0",1);
  strcat(outfile,dir);
  strcat(outfile,"/");
  strcat(outfile,dfile);
  printf("outfile = %s\n",outfile);
  if((fp=fopen(outfile,"w")) == NULL)
  {
    fprintf(stderr,"Can't open %s\n",outfile);
    return 1;
  }
  fwrite(s,sizeof(float),(unsigned int)nsamp,fp);
  fclose(fp);

/*Add entry to wfdisc. Note that, due to problem with dbaddv, we force the
  adding of the record with dbputv after a null record is created.*/
  dbw.record = dbaddnull(dbw);
  jdate = yearday(time);
  endtime = time + (nsamp - 1)/samprate;
  if (dbputv(dbw,0,
        "sta", sta,
        "chan", chan,
        "time", time,
        "endtime", endtime,
        "jdate", jdate,
        "nsamp", nsamp,
        "samprate", samprate,
        "datatype", "u4",
        "dir", dir,
        "dfile", dfile,
        "foff", 0,
        "wfid",wfid,
        NULL) < 0)
  {
      complain(0,"Could not add record to wfdisc file.\n");
      return 1;
  }

  dbclose(db);

} /*End main routine.*/
Esempio n. 5
0
long writePolygonData(Dbptr db, Point *poly, long npoints, char *pname, int closed, int level, char *ptype, char *auth, char *dir, char *dfile, int pcode) {
	/* writes poygon data into file
   		if dir and o dfile are NULL, use defaults
		returns record number if successful,dbINVALID else
	 */		
	long i;
	char datafilename[PATH_MAX];
	FILE *dfh;
	int foff;
	char *ftype;
	int int1,int2;
	float float1,float2;
	double north=-360.0,east=-360.0,west=360.0,south=360.0;
	double lat,lon;
	int pid;
	int free_dir=0;
	int free_dfile=0;
	char closed_flag[2];

	if (closed) {
		strcpy(closed_flag,"y");
	} else {
		strcpy(closed_flag,"n");
	}

	pid=dbnextid(db,"pid");
	
	db=dblookup(db, 0, "polygon", 0, 0);
	if ( (db.record=dbaddnull(db) ) ==dbINVALID) {
		elog_log(0,"writePolygonData: problem adding row...");
		return dbINVALID;
	}
	
	if (dir == NULL) {
		dir = strdup(default_dir);
		free_dir=1;
	}
	if (dfile == NULL) {
		dfile = strdup(default_dfile);
		free_dfile=0;
	}

	if (dbputv(db,0,"pid",pid,"dir",dir,"dfile",dfile,NULL ) == dbINVALID) {
		elog_log(0,"writePolygonData: error putting dir %s & dfile %s",dir,dfile);
		if (free_dir) free(dir);
		if (free_dfile) free(dfile);
		return dbINVALID;
	}
	/* some fix needed here when in "relative" directories...*/
	switch (dbfilename(db,datafilename)) {
		case -1:
			if (makedir(dir)<0) {
				elog_log(0,"writePolygonData: dir %s is NOT writable!",dir);
				if (free_dir) free(dir);
				if (free_dfile) free(dfile);
				return dbINVALID;
			}
			if ((dfh= fopen(datafilename,"w"))==NULL) {
				elog_log(0,"writePolygondata: error crating %s/%s",dir,dfile);
				if (free_dir) free(dir);
				if (free_dfile) free(dfile);
				return dbINVALID;
				}
			foff= 0;
			break;
		case 0:
			/*make file*/
			if (makedir(dir)<0) {
				elog_log(0,"problem creating directory %s",dir);
				if (free_dir) free(dir);
				if (free_dfile) free(dfile);
				return dbINVALID;
			}
			if ((dfh= fopen(datafilename,"w"))==NULL) {
				elog_log(0,"problem creating file %s",dir);
				if (free_dir) free(dir);
				if (free_dfile) free(dfile);
				return dbINVALID;
			}
			foff= 0;
			break;
		case 1:
			/*append*/	
			dfh= fopen(datafilename,"a");
			fseek(dfh,0,2);
			foff= ftell(dfh);
			break;
		case 2:
			/*.Z exists....*/
			elog_log(0,"writePolygonData: compression not yet supported...");
			if (free_dir) free(dir);
			if (free_dfile) free(dfile);
			return dbINVALID;
			break;
		default:
			elog_log(0,"writePolygondata: unknown return value from dbfilename, giving up...");
			if (free_dir) free(dir);
			if (free_dfile) free(dfile);
			return dbINVALID;	
			
	}
	ftype = polytype(pcode);
	
	switch (pcode) {
		case polyINT:
			for (i=0;i < npoints;i++) {
				lon=poly[i].lon;
				west = (lon<west) ? lon : west;
				east = (lon>east) ? lon : east;
				int1=lon * 1e6;
				H2N4((char *)(&int2),(char *)(&int1),1);
				fwrite(&int2,sizeof(int),1,dfh);

				lat=poly[i].lat;
				south = (lat < south) ? lat : south;
				north = (lat > north) ? lat : north;
				int1=lat * 1e6;
				H2N4((char *)(&int2),(char *)(&int1),1);
				fwrite(&int2,sizeof(int),1,dfh);
			}
			fclose(dfh);
			break;
		case polyINTELINT:
			for (i=0;i < npoints;i++) {
				lon=poly[i].lon;
				west = (lon<west) ? lon : west;
				east = (lon>east) ? lon : east;
				int1=lon * 1e6;
				#ifdef WORDS_BIGENDIAN
					swap4(&int1,&int2,1);
				#else
					int2=int1;
				#endif
				fwrite(&int2,sizeof(int),1,dfh);

				lat=poly[i].lat;
				south = (lat < south) ? lat : south;
				north = (lat > north) ? lat : north;
				int1=lat * 1e6;
				#ifdef WORDS_BIGENDIAN
					swap4(&int1,&int2,1);
				#else
					int2=int1;
				#endif
				fwrite(&int2,sizeof(int),1,dfh);
			}
			fclose(dfh);
			break;
		case polyFLOAT:
			for (i=0;i < npoints;i++) {
				lon=poly[i].lon;
				west = (lon<west) ? lon : west;
				east = (lon>east) ? lon : east;
				float1=lon;
				H2N4((char *)(&float2),(char *)(&float1),1);
				fwrite(&float2,sizeof(float),1,dfh);

				lat=poly[i].lat;
				south = (lat < south) ? lat : south;
				north = (lat > north) ? lat : north;
				float1=lat;
				H2N4((char *)(&float2),(char *)(&float1),1);
				fwrite(&float2,sizeof(float),1,dfh);
			}
			fclose(dfh);
			break;	
		case polyINTELFLOAT:
			for (i=0;i < npoints;i++) {
				lon= poly[i].lon;
				west= (lon<west) ? lon : west;
				east= (lon>east) ? lon : east;
				float1=lon;
				#ifdef WORDS_BIGENDIAN
					swap4(&float1,&float2,1);
				#else	
					float2= float1;
				#endif
				fwrite(&float2,sizeof(float),1,dfh);
				lat= poly[i].lat;
				south= (lat < south) ? lat : south;
				north= (lat > north) ? lat : north;
				float1=lat;
				#ifdef WORDS_BIGENDIAN
					swap4(&float1,&float2,1);
				#else	
					float2= float1;
				#endif
				fwrite(&float2,sizeof(float),1,dfh);
			}
			fclose(dfh);
			break;	
		case polyGSHHS:
			elog_log(0,"writePolygonData: storage type %s not yet implemented... ",ftype);
			if (free_dir) free(dir);
			if (free_dfile) free(dfile);
			return dbINVALID;
			break;
		default:
			elog_log(0,"writePolygonData: unknown storage type pcode, giving up");
			if (free_dir) free(dir);
			if (free_dfile) free(dfile);
			return dbINVALID;
	}	
	if (dbputv(db,0,"north",north, "east",east, "south",south, "west",west,
			"pname",pname,"closed",closed_flag,"level",level,"ptype",ptype, "auth",auth,"npoints",npoints, "ftype",ftype,"foff",foff,NULL ) == dbINVALID) {
		elog_log(0,"writePolygonData: error putting values!");
		//free (ftype);
		if (free_dir) free(dir);
		if (free_dfile) free(dfile);
		return dbINVALID;
	} else {
		//free (ftype);
		if (free_dir) free(dir);
		if (free_dfile) free(dfile);
		return db.record;
	}
}
Esempio n. 6
0
int
write_trace (Dbptr db, char *sta, char *chan, char *dir, char *dfile, Trace *trace, double tstart, double tend, int overwrite)

{
    int fd;
    char outdir[1024];
    char outbase[1024];
    char fname[1024];
    int sz, size, ret;
    int is, ie, ns;
    Dbvalue dbv;

    is = (tstart-trace->tstart)/trace->dt + 0.0001;
    ie = (tend-trace->tstart)/trace->dt - 0.0001;
    if (is > trace->nsamps-1) return (1);
    if (ie < 0) return (1);
    if (is < 0) is = 0;
    if (ie > trace->nsamps-1) ie = trace->nsamps-1;
    ns = ie - is + 1;
    if (ns < 1) return (1);
    db = dblookup (db, 0, "wfdisc", 0, 0);
    if (dir[0] == '/') {
        sprintf (fname, "%s/%s", dir, dfile);
    } else {
        dbquery (db, dbTABLE_DIRNAME, &dbv);
        strcpy (outbase, dbv.t);
        sprintf (fname, "%s/%s/%s", outbase, dir, dfile);
    }
    if (!overwrite) {
        if (zaccess(fname, F_OK) != -1) {
            fprintf (stderr, "write_trace: wf file conflict for '%s'.\n",
                     fname);
            return (0);
        }
    }
    dirbase (fname, outdir, outbase);
    if (makedir(outdir) == -1) {
        fprintf (stderr, "write_trace: Unable to create %s\n", outdir);
        return (0);
    }
    fd = open (fname, (O_RDWR|O_CREAT|O_TRUNC), 0666);
    if (fd < 0) {
        fprintf (stderr, "write_trace: Open error on '%s'.\n", fname);
        return (0);
    }
    sz = atoi(&trace->rawdata_format[strlen(trace->rawdata_format)-1]);
    size = sz*ns;
    ret = write (fd, &(((char *)trace->raw_data)[is*sz]), size);
    close (fd);
    if (ret < size) {
        fprintf (stderr, "write_trace: Write error on '%s'.\n", fname);
        return (0);
    }
    db.record = dbNULL;
    db.field = dbALL;
    dbget(db, 0);
    db.record = dbSCRATCH;
    dbputv (db, 0,	"sta", sta,
            "chan", chan,
            "time", trace->tstart+is*trace->dt,
            "wfid", dbnextid(db, "wfid"),
            /*			"chanid", chanid,*/
            "jdate", yearday(trace->tstart),
            "endtime", trace->tstart+trace->dt*(trace->nsamps-1),
            "nsamp", (long)ns,
            "samprate", 1.0/trace->dt,
            "calib", trace->calib,
            "calper", trace->calper,
            "instype", "BEAM",
            "segtype", trace->rawdata_type,
            "datatype", trace->rawdata_format,
            /*			"clip", clip,*/
            "dir", dir,
            "dfile", dfile,
            "foff", (long)0,
            NULL);
    dbadd (db, 0);
    return (1);
}
Esempio n. 7
0
int dbpmel_save_results(Dbptr db,
	int nevents,
	long *evid,
	Hypocenter *h,
	Tbl **ta,
	Location_options o,
	Pf *pf)
#endif
{
	Dbptr dbe,dbo,dba,dboe; 
	Dbptr dbes,dbos,dbas;
	Dbptr dbs;  /* subset view created by dblist2subset */
	Tbl *opat,*aspat,*aspat2;
	Tbl *matches=NULL,*match2;  /* output list of matching records */
	/* Dan Q advises it is wise to have a separate hook for each
	table passed through dbmatches */
	Hook *hooke=NULL,*hooko=NULL,*hooka=NULL,*hooka2=NULL;
	long prefor;
	int i,j;
	char *auth;
	Arrival *a;
	long orid;
	int nmatch;
	double **C;
	float emodel[4];
	char *alg=(char *)strdup("dbpmel");
	/* A collection of variables from assoc that have to be 
	copied.  Earlier algorithm using dbget raw on a subset 
	view failed so I have to copy by this mechanism */
	double belief;
	char timedef[2],slodef[2],azdef[2];
	double azres,slores,emares;
	Tbl *utbl;  


	/* This is needed as a stub for the predicted_error function.
	Because we don't support slowness vector data in pmel this 
	has to be an empty (NOT NULL) tbl list */
	utbl=newtbl(0);
	/* All of these are used repeatedly so we do one lookup at the
	top */
	dbe = dblookup(db,0,"event",0,0);
	dbo = dblookup(db,0,"origin",0,0);
	dba = dblookup(db,0,"assoc",0,0);
	dboe = dblookup(db,0,"origerr",0,0);
	dbes = dblookup(db,0,"event",0,0);
	dbos = dblookup(db,0,"origin",0,0);
	dbas = dblookup(db,0,"assoc",0,0);
	dbes.record = dbSCRATCH;
	dbos.record = dbSCRATCH;
	dbas.record = dbSCRATCH;

	opat = strtbl("orid",NULL );
	aspat = strtbl("orid",NULL );
	aspat2 = strtbl("arid","orid","sta",NULL );

	auth = pfget_string(pf,"author");

	C = dmatrix(0,3,0,3);
	/* outer loop over nevents */
	for(i=0;i<nevents;++i)
	{		
    		double conf;
		char *modtype;
		int model;
		double smajax,sminax,strike,sdepth,stime;
		int rc;

		/* Save nothing for events marked no use */
		if(h[i].used==0) continue;  
		/* Start with event table to get prefor */
		dbputv(dbes,0,"evid",evid[i],NULL );
		dbe.record = dbALL;
		if(dbmatches(dbes,dbe,0,0,&hooke,&matches)!=1)
			elog_complain(0,"WARNING:  multiple records in event table have evid=%ld.\nThis is a serious database problem that should be corrected.  Using first one found in table\n",
				evid[i]);
		dbe.record = (long)gettbl(matches,0);
		/* this is excessively paranoid, but better safe than sorry*/
		if(dbe.record<0)
		{
			elog_complain(0,"dbmatches invalid record %ld\nSkip saving evid %ld\n",
				dbe.record,evid[i]);
			continue;
		}
		dbgetv(dbe,0,"prefor",&prefor,NULL );
		freetbl(matches,0);
		matches=NULL;

		dbputv(dbos,0,"orid",prefor,NULL );
		dbo.record = dbALL;
		nmatch=dbmatches(dbos,dbo,&opat,&opat,&hooko,&matches);
		if(nmatch>1)
			elog_complain(0,"WARNING:  multiple records in origin table match orid=%ld.\nThis is a serious database problem that should be corrected.  Using first one found in table\n",
				prefor);
		else if(nmatch<=0)
		{
			elog_complain(0,"Cannot find matching origin\
record for orid %ld prefor of event %ld\n",
				prefor,evid[i]);
		}
		dbo.record = (long)gettbl(matches,0);
		if(dbget(dbo,0)==dbINVALID)
		{
			elog_complain(0,"dbget error on origin table for orid %ld\nData for evid %ld will not be saved\n",
				prefor,evid[i]);
			continue;
		}
		freetbl(matches,0);
		matches=NULL;

		/* origerr code cloned from dbgenloc */
		conf = pfget_double(pf,"confidence");
		modtype = pfget_string(pf,"ellipse_type");
     		if(modtype == NULL)
     		{
        		elog_complain(0,"parameter ellipse_type not defined--default to chi_square");
        		model = CHI_SQUARE;
     		}
     		else if( strcmp( modtype, "chi_square" ) == 0 )
     		{
        		model = CHI_SQUARE;
     		}
     		else if( strcmp( modtype, "F_dist" ) == 0 )
     		{
        		model = F_DIST;
     		}
     		else
     		{
        		elog_complain(0, "parameter ellipse_type %s incorrect (must be F_dist or chi_square)--default to chi_square", modtype );
        		model = CHI_SQUARE;
     		}
		predicted_errors(h[i],ta[i],utbl,o,C,emodel);
    		rc = project_covariance( C, model, &conf,
                             h[i].rms_weighted, h[i].degrees_of_freedom,
                             &smajax, &sminax, &strike, &sdepth, &stime );

    		if( rc != 0 )
    		{
        		elog_complain(0, "project_covariance failed." );
        		smajax = -1;
        		sminax = -1;
        		strike = -1;
        		sdepth = -1;
        		stime = -1;
        		conf = 0.;
    		}
		orid = dbnextid(dbo,"orid");

		if(dbaddv(dboe,0,
                	"orid", orid,
                	"sxx",C[0][0],
                	"syy",C[1][1],
                	"szz",C[2][2],
                	"stt",C[3][3],
                	"sxy",C[0][1],
                	"sxz",C[0][2],
                	"syz",C[1][2],
                	"stx",C[0][3],
                	"sty",C[1][3],
                	"stz",C[2][3],
                	"sdobs", h[i].rms_raw,
                	"smajax", smajax,
                	"sminax", sminax,
                	"strike", strike,
                	"sdepth", sdepth,
                	"stime", stime,
                	"conf", conf,
                		NULL ) < 0 )
		{
			elog_complain(0,"Problem adding origerr record for evid %ld\n",
				evid[i]);
		} 


		/* This edits the scratch record and adds it to the end 
		of the origin table */
		dbputv(dbos,0,"orid",orid,
				"lat",h[i].lat,
				"lon",h[i].lon,
				"depth",h[i].z,
				"time",h[i].time,
				"algorithm",alg,
				"auth",auth,NULL );

/*
		printf("Added to origin table: %8d %9.4lf %9.4lf %9.4lf"
			" %17.5lf %-15s %-15s\n", orid, h[i].lat, 
			h[i].lon, h[i].z, h[i].time, alg, auth);
*/

		if(dbadd(dbo,0)==dbINVALID)
			elog_complain(0,"dbadd error for origin table\
for new orid %ld of evid %ld\n",
				orid,evid[i]);
		/* The assoc tables is much more complex.  Rather than
		do a row for row match against each arrival in ta, I
		use a staged reduction.  Than is I first match the full
		assoc table against orid=prefor only to get a full list
		of records for that event.  We then run matches against
		the smaller table for sta/phase in the arrival list.
		Untested but from previous experience with dbmatches on
		large tables I'm fairly sure this is a necessary 
		complication to keep this from be very slow*/
		dbputv(dbas,0,"orid",prefor,NULL );
		dba.record = dbALL;
		nmatch=dbmatches(dbas,dba,&aspat,&aspat,&hooka,&matches);
		if(nmatch<=0)
		{
			elog_complain(0,"No assoc records for orid %ld\
found\nFail to create new assoc records for orid %ld\n",
				prefor,orid);
			freetbl(matches,0);
			continue;
		}