示例#1
1
int
main (int argc, char **argv)
{

    int             c,
                    errflg = 0;

    char           *in,
                   *out;
    int             orbin,
                    orbout;
    double          maxpkts = VERY_LARGE_NUMBER ;
    int             quit;
    char           *pktmatch = strdup(".*/pf/evtinfo"),
                   *reject = 0;
    int             nmatch;
    int             specified_after = 0;
    double          after = 0.0,
                    until = VERY_LARGE_NUMBER ;
    double          start_time,
                    end_time,
                    delta_t ;
    double          totpkts = 0,
                    totbytes = 0;
    Flags           flags;
    static int      last_pktid = -1;
    static double   last_pkttime = 0.0;
    char           *statefile = 0;
    double          last_burial = 0.0;
    double          decent_interval = 300.0;
    int             mode = PKT_NOSAMPLES;
    int             rcode;
    char            srcname[ORBSRCNAME_SIZE];
    double          pkttime = 0.0 ;
    int             pktid;
    int             nbytes;
    char           *packet = 0;
    int             packetsz = 0;
    Packet         *unstuffed = 0;
	Pf				*pf;
	Tbl				*tbl;
	Arr				*arr;
	char			*arrkey;
	char			*pffilename;

	Tbl				*channels;
	char			*net;
	char			*sta;
	char			*chan;
	char			netstachan[ORBSRCNAME_SIZE];
	Srcname			parts;
	double			maxtime,mintime,starttime,triggertime,duration,min_g,max_g,snr;
	char			*datalogger;
	int				evtfilesize,channelno,maxcts,mincts;
	char			*errors,*evtfilename,*ft,*filter,*srcid;
	char			*line;
	int				i;
	Pf				*pfnew;
	Dbptr			db;
	int 			put_tests=0;
	char 			*chanmatch=0;
	Hook			*hook=0;
	char			*tdummy=0;
	char 			*match=malloc(100);

	


    memset (&flags, 0, sizeof (flags));
    elog_init (argc, argv);
    elog_notify (0, "%s $Revision: 1.5 $ $Date: 2005/05/10 07:34:43 $\n",
		 Program_Name);

    while ((c = getopt (argc, argv, "m:n:r:S:c:tvV")) != -1) {
	switch (c) {
	  case 'm':
	    match = optarg;
		sprintf(pktmatch,"%s/pf/evtinfo",match);
	    break;
	  case 'c':
	 	chanmatch = optarg;
		break;
	  case 't':
	  	put_tests = 1;
		break;
	  case 'n':
	    maxpkts = atoi (optarg);
	    break;

	  case 'r':
	    reject = optarg;
	    break;

	  case 'S':
	    statefile = optarg;
	    break;

	  case 'v':
	    flags.verbose++;
	    break;

	  case 'V':
		flags.verbose++;
		flags.verbose++;
	    break;

	  case '?':
	    errflg++;
	}
    }

    if (errflg || argc - optind < 2 || argc - optind > 4)
	usage ();

    in = argv[optind++];
    out = argv[optind++];

    if (argc > optind) {
	after = str2epoch (argv[optind++]);
	specified_after = 1;
	if (argc > optind) {
	    until = str2epoch (argv[optind++]);
	    if (until < after) {
		until += after ;
	    }
	}
    }
    if ((orbin = orbopen (in, "r&")) < 0)
	die (0, "Can't open input '%s'\n", in);

    if (statefile != 0) {
		char           *s;
		if (exhume (statefile, &quit, RT_MAX_DIE_SECS, 0) != 0) {
	    elog_notify (0, "read old state file\n");
		}
		if (orbresurrect (orbin, &last_pktid, &last_pkttime) == 0) {
	    	elog_notify (0, "resurrection successful: repositioned to pktid #%d @ %s\n",
			 last_pktid, s = strtime (last_pkttime));
	    	free (s);
		} else {
	    	complain (0, "resurrection unsuccessful\n");
		}
    }
    if ((orbout = orbopen (out, "w&")) < 0) {
	die (0, "Can't open output '%s'\n", out);
    }
    if (pktmatch) {
	nmatch = orbselect (orbin, pktmatch);
    }
    if (nmatch < 0) {
	die (1, "select '%s' returned %d\n", pktmatch, nmatch);
    }
    if (reject) {
	nmatch = orbreject (orbin, reject);
    }
    if (nmatch < 0) {
		elog_die (1, "reject '%s' returned %d\n", reject, nmatch);
    } else {
		if (flags.verbose) {
			elog_notify (1,"%d sources selected\n", nmatch);
		}	
    }

    if (specified_after) {
	pktid = orbafter (orbin, after);
	if (pktid < 0) {
	    char           *s;
	    elog_complain (1, "seek to %s failed\n", s = strtime (after));
	    free (s);
	    pktid = forbtell (orbin);
	    elog_complain (1,"pktid is still #%d\n", pktid);
	} else {
	    if (flags.verbose) elog_notify (1,"new starting pktid is #%d\n", pktid);
	}
    }
    start_time = now ();

	db = dbtmp("rt1.0");

    while (!quit && pkttime < until && totpkts < maxpkts) {
	rcode = orbreap (orbin,
		    &pktid, srcname, &pkttime, &packet, &nbytes, &packetsz);

	switch (rcode) {
	  case 0:
	    totpkts++;
	    totbytes += nbytes;

	    if (flags.verbose>2) {
		showPkt (pktid, srcname, pkttime, packet, nbytes, stdout, mode);
	    }
	    if (statefile != 0
		    && last_pkttime - last_burial > decent_interval) {
		bury ();
		last_burial = pkttime;
	    }
	    if ((unstuffPkt (srcname, pkttime, packet, nbytes, &unstuffed))==Pkt_pf) {
		  	pf = 			unstuffed->pf;
			tbl=			pfkeys(pf);
			arrkey=			gettbl(tbl,0);
			pfget(pf,arrkey,&pfnew);
			datalogger=		pfget_string(pfnew,"datalogger");
			duration=		pfget_double(pfnew,"duration");
			errors=			pfget_string(pfnew,"errors");
			evtfilename=	pfget_string(pfnew,"evtfilename");
			evtfilesize=	pfget_int(pfnew,"evtfilesize");
			ft=				pfget_string(pfnew,"ft");
			starttime=		pfget_double(pfnew,"time");
			triggertime=	pfget_double(pfnew,"triggertime");

			channels=pfget_tbl(pfnew,"channels");
			if (strcasecmp(ft,"no")==0 || put_tests == 1) {
				for (i=0; i<maxtbl(channels);i++) {
					line=gettbl(channels,i);
					sscanf(line,"%s %d %lf %d %lf %lf %d %lf",
						netstachan,&channelno,&maxtime,&maxcts,&max_g,&mintime,&mincts,&min_g);
					split_srcname(netstachan,&parts);	
					strcpy(parts.src_suffix,"GENC");
					join_srcname(&parts,netstachan);
					if (flags.verbose>1) printf("%s,%s\n", netstachan,tdummy=strtime(triggertime));	
					if (chanmatch == 0 || 
							strmatches(parts.src_chan,chanmatch,&hook)) {
						if (flags.verbose) elog_notify(1,"putting detev for %s,%s\n", netstachan,tdummy=strtime(triggertime));	
						
						db=dblookup(db,0,"detev",0,"dbSCRATCH");
						dbputv(db,0,"sta",parts.src_sta,"chan",parts.src_chan,
							"filter",K2_FILTER,
							"time",	triggertime,
							"tron",  starttime - triggertime,
							"troff", starttime - triggertime + duration,
							"iphase","K2",
							"snr",(max_g * 1000.0  - min_g * 1000.0)/2.0,
							0);
						db2orbpkt(db,orbout);
					} else {
						if (flags.verbose>1) elog_notify(1,"ignoring %s,%s\n", netstachan,tdummy=strtime(triggertime));	

					}
				}
			}
			
	    }

	    last_pktid = pktid;
	    last_pkttime = pkttime;
	}

    }

    if (statefile != 0)
	bury ();

    end_time = now ();
    delta_t = end_time - start_time;
	if (flags.verbose>1) {
		if (totpkts > 0) {
		elog_notify (1,"\n%.0f %.2f byte packets (%.1f kbytes) in %.3f seconds\n\t%10.3f kbytes/s\n\t%10.3f kbaud\n\t%10.3f pkts/s\n",
			totpkts, totbytes / totpkts, totbytes / 1024,
			delta_t,
			totbytes / delta_t / 1024,
			totbytes / delta_t / 1024 * 8,
			totpkts / delta_t);
		} else {

		elog_notify (1,"\nno packets read\n");
		}
	}

    if (orbclose (orbin)) {
	elog_complain (1, "error closing read orb\n");
    }
    if (orbclose (orbout)) {
	elog_complain (1, "error closing write orb\n");
    }
    return 0;
}
int load_surface_velocity(Pf *pf, Arr *a)
{
	int nset;
	Tbl *t;
	char sta[10];
	double vp,vs;
	char *line;
	MWstation *s;
	int i;

	t = pfget_tbl(pf,"surface_velocities");
	if(t == NULL) elog_die(0,"surface_velocities table missing from parameter file\n");

	for(i=0,nset=0;i<maxtbl(t);i++)
	{
		line = gettbl(t,i);
		if((sscanf(line,"%s %lf %lf",sta,&vp,&vs)) != 3)
		{
			elog_notify(0,"Syntax error reading line from surface_velocity table\nOffending line->%s\n",
				line);
			continue;
		}
		s = (MWstation *)getarr(a,sta);
		if(s == NULL) 
		{
			elog_notify(0,"Station %s listed in surface_velocity table not found in master table\n",
				sta);
			continue;
		}
		s->vp0 = vp;
		s->vs0 = vs;
		++nset;
	}
	return(nset);
}
/* This function creates an associative array keyed by an integer
event id from a parameter file based descriptor &Tbl like this example:

pmel_calibration_events &Tbl{
	10 xyz
	11 xyzt
}
where 10 and 11 are event ids and the string defines coordinates to fix.

Author:  Gary Pavlis
*/
Arr *load_calibration_events(Pf *pf)
{
	Tbl *t;
	int evid;
	char *evidstr;
	char fix[5],*line;
	char *fptr;
	Arr *a;
	int i;

	a = newarr(0);

	t = pfget_tbl(pf,"pmel_calibration_events");
	if(t==NULL) 
	{
		elog_complain(0,
		  "pmel_calibration_events Tbl not in parameter file\nAssuming no calibration events exist\n");
	}
	else
	{
		for(i=0;i<maxtbl(t);++i)
		{
			line = (char *)gettbl(t,i);
			sscanf(line,"%d%s",&evid,fix);
			evidstr = make_evid_key(evid);
			fptr=strdup(fix);
			setarr(a,evidstr,fptr);
			free(evidstr);
		}
			
	}
	return(a);
}
示例#4
0
Arr *build_stachan_list(Pf *pf, int *nchan,int verbose)
{
	char sta[10], chan[10];
	char *key;
	Arr *a;
	int i;
	Tbl *t;
	char *line;
	int *channel_number;  /* value stored in arr */

	if(verbose)
		elog_notify(0,"Station   Channel_code    Channel_number\n");
	a = newarr(0);
	t = pfget_tbl(pf,"channels");
	if(t==NULL) elog_die(0,"Parameter file error:  no channels table\n");
	for(i=0;i<maxtbl(t);++i)
	{
		line = gettbl(t,i);
		sscanf(line,"%s %s",sta,chan);
		key = make_key(sta,chan);
		channel_number = (int *) malloc(sizeof(int));
		if(channel_number == NULL)
			elog_die(0,"malloc error for channel_number\n");
		*channel_number = i;
		setarr(a,key,(void *)channel_number);
		if(verbose)
			elog_notify(0,"%s  %s  %d\n",sta,chan,(*channel_number)+1);
		free(key);
	}
	*nchan = maxtbl(t);
	freetbl(t,free);
	return(a);
}
/* This is a companion routine to load_station_table for array beam code
tables.  At the moment it is essentially identical to the load_station_table
function, but changes may eventually occur in the beam table that will
make them diverge so I have produced to seperate functions */
Arr *load_array_table(Pf *pf)
{
	Arr *a;
	Tbl *t;
	int i;
	char *value;

	Seismic_Array *s;

        double elev_datum;
 
        a = newarr(0);
        elev_datum = pfget_double_wdef(pf,"elevation_datum",0.0);
	t = pfget_tbl(pf,"seismic_arrays");
	for(i=0;i<maxtbl(t);++i)
	{
		s = (Seismic_Array *) malloc(sizeof(Seismic_Array));
		if(s == NULL) elog_die(1,"load_array_table:  Cannot malloc Seismic_Array structure entry\n");
		value = gettbl(t,i);
		if(sscanf(value,"%s %lf %lf %lf",s->name,
			&(s->lat),&(s->lon),&(s->elev)) != 4)
			elog_complain(1,"Warning(load_array_table):  \
Read error in array tbl read from parameter file\n\
The following line of the array table was skipped\n%s\n",
				value);
		else
		{
                        s->elev -= elev_datum;
			setarr(a,s->name,s);
		}
	}
	return(a);
}
/* This function establishes the list of all stations that will actually
be used for processing.  I creates an associative array of MWstation 
objects keyed by the station name.  Note it is important to realize
the structure this function creates is NOT completely filled in, but
every element is at least initialized.  (see above).  The NULL pointers
are especially dangerous if not filled in.  

The main element of the MWstation structure that this function fills in
is the weights vector.  This vector is an array of weights used for
forming the stack in a given frequency band.  That is, weight[i] is
the weight given traces for this station in wavelet band i.

arguments:
	pf = input pf object to be parsed
	nbands = number of frequency bands to use in processing = length
		of weights vector created in s->weights

The weights array is created cautiously using nbands.  The input line
is parsed and if there are insufficient weights listed in the input
a diagnostic will be issued and the undefined weights set to 1.0.
If there are more numbers listed than required the list will be silently
truncated.  

History:
Created summer 1999

Modified march 2000

Added code for stations with bad timing.  
*/
Arr *create_station_objects(Pf *pf, int nbands)
{
	int i,j,k;
	Arr *a;
	Tbl *t;
	MWstation *s;
	char *sta;
	char *line,*word;
	char *white=" \t";

	t = pfget_tbl(pf,"station_weights");
	if(t == NULL) elog_die(0,"station_weights table not in parameter file\n");

	a = newarr(0);

	for(i=0;i<maxtbl(t);i++)
	{
		line = gettbl(t,i);
		sta = strtok(line,white);

		s = (MWstation *)malloc(sizeof(MWstation));
		if(s==NULL) 
		  elog_die(0,"Cannot malloc MWstation structure for station %s\n",sta);
		initialize_MWstation(s,nbands);
		allot(double *,s->weights,nbands);
		s->sta = strdup(sta);

		for(j=0;j<nbands;j++) 
		{
			word = strtok(NULL,white);
			if(word == NULL)
			{
				elog_notify(0,"error in station_weights parameter inputfor station %s\nExpected list of %d weights, found only %d\n",
					sta,nbands, j);
				if(j==0)
				{
					elog_notify(0,"No weights defined in any band for station %s\nSetting all weights to 1.0\n",
						sta);
					for(k=0;k<nbands;++k)s->weights[k]=1.0;
				}
				else
				{
					elog_notify(0,"Setting weights for station %s above band %d to %lf\n",
						sta,j-1,s->weights[j-1]);
					for(k=j;k<nbands;++k)
						s->weights[k]=s->weights[j-1];
				}
				break;
			}
			s->weights[j] = atof(word);
		}
		/* we set the clock_is_bad variable false here and depend
		upon the genloc bad clock definitions to set a station as
		being always bad with this flag */
		s->clock_is_bad = 0;
		setarr(a,s->sta,s);
	}

	return(a);
}
示例#7
0
Dbptr join_tables(Dbptr db, Pf *pf, Arr *tables)
{
	char *table_name;
	int *ilogic;
	Tbl *t;
	Dbptr dbj;
	long int nrec;
	int i;
	int ntables=0;

	/* This is an exact copy of above, but it is duplicated because
	this function could get stolen by another future program
	because it is pretty general */
	t = pfget_tbl(pf,"join_tables");
	if(t == NULL)
	{
		elog_die(0,"No list of tables to be joined\n");
	}
	for(i=0;i<maxtbl(t);++i)
	{
		table_name = gettbl(t,i);
		ilogic = (int *)getarr(tables,table_name);
		if(ilogic == NULL)
		{
			elog_die(0,"Table %s was not handled previously by check_tables.\nProgramming logic error\n",
				table_name);
		}
		else if(*ilogic)
		{
			if(ntables == 0)
				dbj = dblookup(db,0,table_name,0,0);
			else
				dbj=dbjoin(dbj,dblookup(db,0,table_name,0,0),
					NULL,NULL,0,NULL,0);
			++ntables;
			dbquery(dbj,dbRECORD_COUNT,&nrec);
			if(nrec == 0)
			{
				elog_complain(0,
					"join_tables error\njoined database has 0 length after joining table %s\n",
					table_name);
				dbj.record = dbINVALID;
				return(dbj);
			}
		}
	}
	return(dbj);
}
示例#8
0
void init( )

{
    Pf  		*Param;
    Tbl 		*Site;
    DAS *das;
    struct Site 	 site;
    char 	*istr;
    char         dasid[6];
    int 		pkttype;
    int 		ntrec, i, j;
    int 		nsite;
    int 		*num = 0;

    if(pfread( pfile, &Param) != 0)
        die(0, "Can't read parameter file\n");

    /* Get Input & Network tables  */

    Site = pfget_tbl(Param, "Site");
    nsite = maxtbl(Site);

    if( nsite <= 0  )
        die( 0, "init(): parameter file is not complete.\n");

    Dases = newarr( 0 );
    Dasid = newarr( 0 );

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

        istr = (char *) gettbl(Site, i);
        sscanf(istr, STE_SCS,  STE_RVL(&site));
        if( !strcmp(site.up, "Y") )  {
            sprintf( dasid, "%d\0", site.sid );
            if( ( das = ( DAS *) getarr( Dases, dasid ) ) == NULL )  {
                das = new_das( site.sid, site.name );
                setarr(Dases, (char *) &dasid[0], (char *) das );
            }

            if( (num = ( int *) getarr( Dasid, site.name ) ) == NULL )  {
                allot( int *, num, 1 );
                *num = site.sid;
                setarr(Dasid, (char *) site.name, (char *) num );
            }
        }
示例#9
0
/* This routine looks for a Tbl in the parameter space that
defines a set of auxiliary tables that are to be used.  It
cautiously checks to see if that table is defined in the
schema and is nonempty.  It sets logical variables in associative
array it returns that define if the table is "ok".  This is serious
overkill added to make the code for expandable in the future.
At the moment the only table that would be used is "shot".
It would, however, be easy to add similar auxiliary tables for
segy constructs like statics, mute definition, etc.  In that
case there probably should be a more general mechanism than this
but I'm more or less laying out a useful functionality here rather
than doing it in a completely general way.
*/
Arr *check_tables(Dbptr db, Pf *pf)
{
	char *table;
	int *ilogic;
	int i;
	Tbl *t;
	Dbptr dbtmp;
	int table_ok;
	long int nrec;
	Arr *a;

	a = newarr(0);
	t = pfget_tbl(pf,"join_tables");
	if(t == NULL)
	{
		elog_die(0,"No list of tables to be joined\n");
	}
	for(i=0;i<maxtbl(t);++i)
	{
		/* This series of conditionals is safe:  It certifies
		a table (a) is defined in this schema and (b) is
		not empty.  */
		table = (char *)gettbl(t,i);
		dbtmp = dblookup(db,0,table,0,0);
		if(dbtmp.table == dbINVALID)
			table_ok = 0;
		else
			table_ok = 1;
		if(table_ok)
		{
			dbquery(dbtmp,dbRECORD_COUNT,&nrec);
			if(nrec > 0)
				table_ok = 1;
			else
				table_ok = 0;
		}
		ilogic = (int *) malloc(sizeof(int));
		if(ilogic == NULL) elog_die(0,"malloc error\n");
		*ilogic = table_ok;
		setarr(a,table,ilogic);
	}
	return(a);
}
示例#10
0
MWbasis  *load_multiwavelets_pf(Pf *pf,int *nwavelets)
{
	int i,j,k;
	char *line;
	double f0,fw;
	int nsamples;
	Tbl *w;
	MWbasis *mw;
	int nrows;

	nsamples = pfget_int(pf,"nsamples");
	*nwavelets =  pfget_int(pf,"nwavelets");
	f0 = pfget_double(pf,"f0");
	fw = pfget_double(pf,"fw");
	w = pfget_tbl(pf,"wavelets");
	nrows = maxtbl(w);
	if(nrows != (nsamples*(*nwavelets)))
		elog_die(0,"Size mismatch in wavelet parameter file\nExpected %d from %d wavelets each %d long\nFound %d instead\n",
			nsamples*(*nwavelets),*nwavelets,nsamples,nrows);
	mw = (MWbasis *)calloc(*nwavelets, sizeof(MWbasis));
	if(mw == NULL)
		elog_die(0,"Cannot alloc %d multiwavelet structures\n",*nwavelets);
	for(i=0,k=0;i<(*nwavelets);++i)
	{
		mw[i].r = calloc(nsamples,sizeof(float));
		mw[i].i = calloc(nsamples,sizeof(float));
		if((mw[i].r == NULL) || (mw[i].i == NULL) )
			elog_die(0,"Cannot alloc %d samples for complex wavelet %d\n",
				nsamples,i);
		mw[i].n = nsamples;
		mw[i].f0 = f0;
		mw[i].fw = fw;
		for(j=0;j<nsamples;j++,k++)
		{
			line = gettbl(w,k);
			if(sscanf(line,"%g%g",&(mw[i].r[j]),&(mw[i].i[j])) != 2)
				elog_die(0,"Error reading wavelets from parameter file on line %d of wavelet tbl\n",
					k);
		}
	}
	return(mw);
}
示例#11
0
int load_initial_statics(Pf *pf, Arr *a)
{
	int nset;
	Tbl *t;
	char sta[10];
	double statics;
	char *line;
	MWstation *s;
	int i;

	t = pfget_tbl(pf,"initial_statics");
	if(t == NULL) 
	{
		elog_notify(0,"initial_statics table missing from parameter file.  initial statics all set to 0.0\n");
		return(0);
	}

	for(i=0,nset=0;i<maxtbl(t);i++)
	{
		line = gettbl(t,i);
		if((sscanf(line,"%s %lf %lf",sta,&statics)) != 2)
		{
			elog_notify(0,"Syntax error reading line from initial_statics Tbl\nOffending line->%s\n",
				line);
			continue;
		}
		s = (MWstation *)getarr(a,sta);
		if(s == NULL) 
		{
			elog_notify(0,"Station %s listed in initial_statics table not found in master table\n",
				sta);
			continue;
		}
		elog_log(0,"Setting initials static for %s to %lf\n",
				sta,statics);
		s->initial_static = statics;
		++nset;
	}
	return(nset);
}
int ttlvz_init(char *phase, Pf *pf)
{
	Tbl *t;

	Vmodel *mod;

	if(ttlvz_models == NULL) ttlvz_models = newarr(0);
	mod = (Vmodel *)malloc(sizeof(Vmodel));
	if(mod == NULL) die(1,"ttlvz_init:  cannot malloc Vmodel structure for phase %s\n",phase);
	t = pfget_tbl(pf,"velocity_model");
	if(t == NULL) 
	{
		elog_complain(0,
		 "ttlvz_init:  no velocity model data found for phase %s\n",
			phase);
		return(1);
	}
	ttlvz_parse_vmodel(t,&(mod->velocity),&(mod->ztop),&(mod->nlayers));
	setarr(ttlvz_models,phase,mod);
	return(0);

}
示例#13
0
static int
is_dbprogram( char *what, char *dbprogram, char *dbpath ) 
{
	static Pf *pflib = 0;
	static Morphtbl *morphmap = 0;
	Tbl	*morphlist;
	int	rc;
	char	result[STRSZ];
	Tbl	*parts;

	rc = pfupdate( "libpforbstat", &pflib );

	if( rc < 0 || pflib == NULL ) {

		register_error( 0, "pforbstat: failed to load libpforbstat.pf "
				   "during database analysis\n" );
		return 0;

	}  else if( rc == 0 && morphmap == NULL ) {

		register_error( 0, "pforbstat: no morphmap present for database analysis\n" );
		return 0;
	}

	if( rc > 0 ) {

		if( morphmap != (Morphtbl *) NULL ) {

			freemorphtbl( morphmap );
			
			morphmap = 0;
		}

		morphlist = pfget_tbl( pflib, "dbprograms_morph" );

		if( morphlist == NULL ) {
			
			register_error( 0, "pforbstat: failed to get dbprograms_morph "
					"from libpforbstat.pf during database analysis\n" );
			return 0;
		}
		
		rc = newmorphtbl( morphlist, &morphmap );

		freetbl( morphlist, 0 );

		if( rc != 0 ) {

			register_error( 0, "pforbstat: %d errors translating dbprograms_morph "
					"from libpforbstat.pf during database analysis\n" );
			return 0;
		}
	} 
	
	rc = morphtbl( what, morphmap, 0, result );

	if( rc <= 0 ) {

		strcpy( dbprogram, "" );
		strcpy( dbpath, "" );

		return 0;

	} else {

		parts = split( result, ' ' );

		strcpy( dbprogram, gettbl( parts, 0 ) );
		strcpy( dbpath, gettbl( parts, 1 ) );
		
		freetbl( parts, 0 );

		return 1;
	} 
}
示例#14
0
Tbl *
get_frametbl( char *block_name, char *RTtype )
{
	static Arr *frametables = 0;
	Pf	*pf;
	Tbl	*frames;
	Tbl	*siterows;
	siteinfo *sinfo[6];
	char	key[STRSZ];
	int	i;

	sprintf( key, "%s:%s", block_name, RTtype );

	if( frametables == 0 )
	{
		frametables = newarr( 0 );
	}
	else if( ( frames = (Tbl *) getarr( frametables, key ) ) != 0 )
	{
		return frames;
	}

	pf = get_pf( block_name );

	siterows = pfget_tbl( pf, RTtype );
	frames = sitetbl2frametbl( siterows );
	freetbl( siterows, 0 );
	setarr( frametables, key, (void *) frames );

	sorttbl( frames, cmp_sinfo_order, 0 );

	if( STREQ( RTtype, "LPRT" ) )
	{
		if( maxtbl( frames ) % 3 != 0 )
		{
			fprintf( stderr, "Wrong # of components in LPRT table\n" );
			return 0;
		}
		for( i=0; i < maxtbl( frames ); i += 3 )
		{
			sinfo[0] = (siteinfo *) gettbl( frames, 0 );
			sinfo[1] = (siteinfo *) gettbl( frames, 1 );
			sinfo[2] = (siteinfo *) gettbl( frames, 2 );
			if( ! ( STREQ( sinfo[0]->sta, sinfo[1]->sta ) &&
			        STREQ( sinfo[1]->sta, sinfo[2]->sta ) ) )
			{
				fprintf( stderr, "Unexpected order in LPRT table\n" );
				return 0;
			}
		}
	}
	else if( STREQ( RTtype, "BBRT" ) )
	{
		if( maxtbl( frames ) % 6 != 0 )
		{
			fprintf( stderr, "Wrong # of components in BBRT table\n" );
			return 0;
		}
		for( i=0; i < maxtbl( frames ); i += 6 )
		{
			sinfo[0] = (siteinfo *) gettbl( frames, 0 );
			sinfo[1] = (siteinfo *) gettbl( frames, 1 );
			sinfo[2] = (siteinfo *) gettbl( frames, 2 );
			sinfo[3] = (siteinfo *) gettbl( frames, 3 );
			sinfo[4] = (siteinfo *) gettbl( frames, 4 );
			sinfo[5] = (siteinfo *) gettbl( frames, 5 );
			if( ! ( STREQ( sinfo[0]->sta, sinfo[1]->sta ) &&
			        STREQ( sinfo[1]->sta, sinfo[2]->sta ) &&
				STREQ( sinfo[2]->sta, sinfo[3]->sta ) &&
				STREQ( sinfo[3]->sta, sinfo[4]->sta ) &&
				STREQ( sinfo[4]->sta, sinfo[5]->sta ) ) )
			{
				fprintf( stderr, "Unexpected order in BBRT table\n" );
				return 0;
			}
		}
	}

	return frames;
}
示例#15
0
int main (int argc, char **argv) {
	int             c,
                    errflg = 0;
    Dbptr      db, tr;
    char       *database,*outfile, *pfname=0;
    Flags	   flags ;
    Pf          *pf,*pf_def,*pf_sta=NULL,*pf_stas;
    Tbl		   *input;
    char	   *start, *stop, *triggertimestring=NULL ;
    char	   *subset=0 ;
    long	    nrecords,nsamp1 ;
	int 		duration,nframes,sampsperframe;
	double		tstart, tstop, triggertime=0;
	char 		sta[STA_LEN],sta1[STA_LEN];
	char 		chan[STA_LEN],chan1[STA_LEN];
	double 		samprate,samprate1,t1,t2;
	FILE 			*fout;
	size_t			nw;
	unsigned char *hdrbuf=malloc(2040);
	unsigned char *framebuf=malloc(32);
	unsigned char *tagbuf=malloc(16);
	unsigned short cksum;
	unsigned char wfarr[3 * 12 * 100]; /*1000sps * 0.1 sec * 12 chan * 3bytes*/
	int sampindex=0;

	K2EvtFile *myhdr=malloc(2040);
	K2EvtTag *mytag=malloc(sizeof(K2EvtTag));
	K2EvtFrame *myframe=malloc(sizeof(K2EvtFrame));
	float *data[12] ;
	unsigned short channelBitmap=0;
	int	pf_serialno,pf_sensortype;
	double pf_sensitivity, pf_fullscale, pf_lat, pf_lon, pf_elev;

    memset ( &flags, 0, sizeof(flags)); 
    elog_init ( argc, argv ) ; 


    while ((c = getopt (argc, argv, "do:p:s:t:v")) != -1) {
		switch (c) {

			case 'd':
				flags.display = 1 ; 
				break ; 

			case 'p':
				pfname= optarg ;
				break;

			case 's':
				subset = optarg ; 
				break ;

			case 't':
				triggertimestring = optarg ; 
				break ;

			case 'v':
				flags.verbose++ ;
				break;

			default:
				errflg++;
				break ;
		}
    }

    if (errflg || argc-optind != 4)
		usage ();

	if (pfname==NULL) {
		pfname=Program_Name;
	}
    if (pfread (pfname, &pf) != 0)
		die (0, "Can't read parameter file %s\n",pfname);

	database = argv[optind++];
	outfile = argv[optind++];
	start = argv[optind++];
	stop = argv[optind++];
	tstart=str2epoch(start);
	tstop=str2epoch(stop);
	tstart=ceil(tstart);	/* make sure we have second boundaries, 
							   this also makes sure we have a integer number of frames */
	tstop=floor(tstop);
	duration=tstop - tstart;
    if ( dbopen(database, "r", &db) ) { 
        die ( 0, "Can't open database %s", database ) ;
    }

	input = pfget_tbl (pf, "view" ) ;
  	db = dbprocess ( db, input, 0 ) ;

	if (subset) {
		db=dbsubset(db,subset,0);
	}

    tr = dbinvalid() ;
    if ( trload_css ( db, start, stop, &tr, 0, 0 ) ) { 
		die ( 1, "trload_css failed" ) ; 
    }

    if ( trsplit(tr, 0, 0) ) { 
		complain ( 0, "trsplit failed" ) ; 
    }

    if ( trsplice(tr, 0, 0, 0) ) { 
		complain ( 0, "trsplice failed" ) ; 
    }

    if ( flags.display ) { 
		trdisp (tr, "will try to convert this stuff to evt") ;
    }
	tr.record=0;
	dbgetv(tr,0,"time",&t1,"endtime",&t2,"sta",sta1,"chan",chan1,"samprate",&samprate1,"nsamp",&nsamp1,NULL);
	samprate1=round(samprate1);
	

	dbquery ( tr, dbRECORD_COUNT, &nrecords ) ; 
	if (nrecords > 12) {
		printf("will only use the first 12 channels, consider modifying the subset...");
		nrecords=12;
	}
	for ( tr.record = 0 ; tr.record < nrecords ; tr.record++ ) { 
		double ts,te;
		dbgetv(tr,0,"time",&ts,"endtime",&te,"samprate",&samprate,"sta",sta,"chan",chan,NULL);
		samprate=round(samprate);
		if (t1 != ts || t2 != te) {
			die ( 0, "this simplistic version only works with 101% correct times and/or subsets, sorry..." ) ;
		}	
		if (strcmp(sta,sta1) !=0) {
			die ( 0, "%s <=> %s this simplistic version only works with ONE station, but the subset left more",sta,sta1 ) ;
		}
		if (samprate != samprate1) {
			die ( 0, "all channels in a K2-EVT File MUST have the same samplerate!" );
		}
	}

	newFileHeader(&myhdr, pf, sta);

	if (parse_param (pf, "sta_defaults", P_ARRPF, 1, &pf_def) < 0) {
		elog_die (0, "error parsing array sta_defaults.\n");
	}
	if (parse_param (pf, "sta_params", P_ARRPF, 1, &pf_stas) < 0) {
		elog_die (0, "error parsing array sta_params.\n");
	}
	if (parse_param (pf_stas, sta, P_ARRPF, 0, &pf_sta) < 0) {
		elog_die (0, "error parsing sta_params{%s}\n.",sta);
	}

	if (parse_param(pf_def,"sensortype",P_LINT,1,&pf_sensortype)< 0 ) {
		        elog_die (0, "error parsing default sensortype.\n");
	}
	if (parse_param(pf_def,"serialno",P_LINT,1,&pf_serialno)< 0 ) {
		        elog_die (0, "error parsing default serialno.\n");
	}
	if (parse_param(pf_def,"sensitivity",P_DBL,1,&pf_sensitivity)< 0 ) {
		        elog_die (0, "error parsing default sensitivity.\n");
	}
	if (parse_param(pf_def,"fullscale",P_DBL,1,&pf_fullscale)< 0 ) {
		        elog_die (0, "error parsing default fullscale.\n");
	}
	if (parse_param(pf_def,"lat",P_DBL,1,&pf_lat)< 0 ) {
		        elog_die (0, "error parsing default lat.\n");
	}
	if (parse_param(pf_def,"lon",P_DBL,1,&pf_lon)< 0 ) {
		        elog_die (0, "error parsing default lon.\n");
	}
	if (parse_param(pf_def,"elev",P_DBL,1,&pf_elev)< 0 ) {
		        elog_die (0, "error parsing default elev.\n");
	}
	if (pf_sta==NULL) {
		elog_notify (0, "can't parse array sta_params{%s}, will use defaults\n.",sta);
		pf_sta=pf_def;

	} else {
		if (parse_param(pf_def,"sensortype",P_LINT,0,&pf_sensortype)< 0 ) {
					elog_die (0, "error parsing sensortype.\n");
		}
		if (parse_param(pf_sta,"serialno",P_LINT,0,&pf_serialno)< 0 ) {
					elog_die (0, "error parsing serialno.\n");
		}
		if (parse_param(pf_sta,"sensitivity",P_DBL,0,&pf_sensitivity)< 0 ) {
					elog_die (0, "error parsing sensitivity.\n");
		}
		if (parse_param(pf_sta,"fullscale",P_DBL,0,&pf_fullscale)< 0 ) {
					elog_die (0, "error parsing fullscale.\n");
		}
		if (parse_param(pf_sta,"lat",P_DBL,0,&pf_lat)< 0 ) {
					elog_die (0, "error parsing lat.\n");
		}
		if (parse_param(pf_sta,"lon",P_DBL,0,&pf_lon)< 0 ) {
					elog_die (0, "error parsing lon.\n");
		}
		if (parse_param(pf_sta,"elev",P_DBL,0,&pf_elev)< 0 ) {
					elog_die (0, "error parsing elev.\n");
		}
	}
	myhdr->rw_stream.sps=samprate;		/* sampling rate */
	myhdr->rw_stream.preEvent=1;	/* in seconds */
	myhdr->rw_stream.postEvent=5;	/* in seconds */
	myhdr->rw_stream.minRunTime=6;	/* in seconds */
	myhdr->ro_stream.duration=duration;
	myhdr->ro_stream.nscans=duration* 10;
	myhdr->ro_stream.startTime=epoch2k2time(t1);
	myhdr->ro_stream.startTimeMsec=0;
	int ttms=0;
	if (triggertimestring) {
		triggertime=str2epoch(triggertimestring);
		ttms=remainder(triggertime,1.0 ) * 1000.0; 
		triggertime=epoch2k2time(triggertime);
	} else {
		triggertime=epoch2k2time(t1)+5;
		ttms=0;
	}
	myhdr->ro_stream.triggerTime=triggertime;
	myhdr->ro_stream.triggerTimeMsec=ttms;
	myhdr->rw_misc.nchannels=nrecords;
	for (int channo=0;channo< nrecords;channo++) {
		myhdr->rw_channel[channo].sensitivity=pf_sensitivity;	
		myhdr->rw_channel[channo].sensitivity=pf_fullscale;	
	}
	myhdr->rw_misc.elevation=pf_elev;		/* meters above sea level */
	myhdr->rw_misc.latitude=pf_lat;			/* degrees north */
	myhdr->rw_misc.longitude=pf_lon;		/* degrees east */

	nframes=duration * 10;
	myhdr->ro_stream.duration=nframes;
	myhdr->ro_stream.nscans=duration*samprate;

	channelBitmap=chanbitmap(nrecords);

	for ( tr.record = 0 ; tr.record < nrecords ; tr.record++ ) { 
		unsigned long i ; 
		int nsamp;
		char chan[7];
		unsigned long minoffset=0;
		unsigned long maxoffset=0;
		int	max=INT_MIN;
		int min=INT_MAX;
	    dbgetv(tr, 0, "chan",chan,"data", &data[tr.record], "nsamp", &nsamp, NULL ) ; 
	    for ( i=0 ; i<nsamp ; i++ ) { 
			if (data[tr.record][i] > max) {
				max=data[tr.record][i];
				maxoffset=i;
			}
			if (data[tr.record][i] < min) {
				min=data[tr.record][i];
				minoffset=i;
			}
			
	    }
		myhdr->ro_channel[tr.record].maxPeak=max;
		myhdr->ro_channel[tr.record].maxPeakOffset=maxoffset;
		myhdr->ro_channel[tr.record].minPeak=min;
		myhdr->ro_channel[tr.record].minPeakOffset=minoffset;
		memcpy(myhdr->rw_channel[tr.record].id,chan,K2EVT_CHANNEL_ID_LENGTH);
	}
	for ( tr.record = 0 ; tr.record < nrecords ; tr.record++ ) { 

	}

	newTag(&mytag,0, 2040, 0, 128,1234);
	encodek2header(hdrbuf,myhdr);
	cksum=k2_checksum(hdrbuf,2040);
	
	mytag->length=2040;/*header size*/
	mytag->dataLength=0;
	mytag->checksum=cksum;
	encodek2tag(tagbuf,mytag);
	fout=fopen(outfile,"w+");
	nw=fwrite(tagbuf,16,1,fout);
	nw=fwrite(hdrbuf,2040,1,fout);

	
	double t=t1 ;
	double k2t=round(epoch2k2time(t));
	newFrameHeader(&myframe,128,(sampsperframe*3*nrecords)+32, k2t);
	sampsperframe=TIME2SAMP(0,samprate,0.1);/*samples per frame*/
	
	for (int fn=0;fn < nframes;fn++) {
		cksum=0;
		sampindex=0;
		for (int s=0;s<sampsperframe;s++) {
			long val;
			unsigned char buf[4];
			for ( int channo = 0 ; channo < nrecords ; channo++ ) { 
				int index=((fn*sampsperframe) + s);
				val=round(data[channo][index]);
				/*debugging...*/
				//val=66051;/*0x010203*/
				memcpy(&buf,&val,4);
				val <<=8;
#ifdef WORDS_BIGENDIAN
				cksum+=buf[1];
				cksum+=buf[2];
				cksum+=buf[3];
				wfarr[sampindex++]=buf[1];
				wfarr[sampindex++]=buf[2];
				wfarr[sampindex++]=buf[3];
#else
				cksum+=buf[2];
				cksum+=buf[1];
				cksum+=buf[0];
				wfarr[sampindex++]=buf[2];
				wfarr[sampindex++]=buf[1];
				wfarr[sampindex++]=buf[0];
#endif
			}
		}

		mytag->checksum=cksum;
		mytag->length=32;/*header size*/
		mytag->dataLength=sampsperframe * nrecords * 3;
		myframe->frameSize=(sampsperframe*3*nrecords)+32;
		myframe->blockTime=round(k2t);
		myframe->msec=fmod(k2t,1.0) * 1000;
		myframe->channelBitMap=channelBitmap;
		
		encodek2Frame(framebuf,myframe);
		mytag->checksum+=k2_checksum(framebuf,32);
		encodek2tag(tagbuf,mytag);
		k2t+=0.1;
		//k2t=round((k2t+0.1)*10.0)/10.0;
		nw=fwrite(tagbuf,1,16,fout);
		if (nw!= 16) {
			die(0,"could not write file tag, wrote %d bytes instead of 16",nw);
		}
		nw=fwrite(framebuf,32,1,fout);
		nw=fwrite(&wfarr, 1,sampsperframe * 3 * nrecords, fout);
	}
	
	
	fclose(fout);

    tr.table = dbALL ;
    trfree(tr) ;
    pffree(pf) ; 
    return 0;
}
示例#16
0
int 
setup_ampfactors( Pf *pf )
{
	char	*pga_sitecorr_cutoffs_g;
	char	*arow;
	Tbl	*pga_sitecorr_table;
	Tbl	*cutoffs;
	Tbl	*amps;
	int	icut, ivel;

	pga_sitecorr_cutoffs_g = pfget_string( pf, "pga_sitecorr_cutoffs_g" );
	pga_sitecorr_table = pfget_tbl( pf, "pga_sitecorr_table" );

	if( pga_sitecorr_cutoffs_g == NULL ) {
		elog_complain( 0, "trinetsm_es99: need value for "
			     "pga_sitecorr_cutoffs_g\n" );
		return -1;
	}

	if( pga_sitecorr_table == NULL ) {
		elog_complain( 0, "trinetsm_es99: need value for "
			     "pga_sitecorr_table\n" );
		return -1;
	}

	pga_sitecorr_cutoffs_g = strdup( pga_sitecorr_cutoffs_g );
	cutoffs = split( pga_sitecorr_cutoffs_g, ' ' );

	Ncutoffs = maxtbl( cutoffs );

	if( Ncutoffs < 1 ) {
		elog_complain( 0, "trinetsm_es99: need at least one value in "
			     "pga_sitecorr_cutoffs_g\n" );
		free( pga_sitecorr_cutoffs_g );
		freetbl( cutoffs, 0 );
		return -1;
	}

	allot( double *, Ampfactor_cutoffs_g, Ncutoffs );

	for( icut = 0; icut < Ncutoffs; icut++ ) {

		Ampfactor_cutoffs_g[icut] = atof( gettbl( cutoffs, icut ) );
	}

	free( pga_sitecorr_cutoffs_g );
	freetbl( cutoffs, 0 );

	Nvelocities = maxtbl( pga_sitecorr_table );

	if( Nvelocities < 1 ) {
		elog_complain( 0, "trinetsm_es99: need at least one row in "
			     "pga_sitecorr_table\n" );
		free_ampfactors();
		return -1;
	}

	allot( double **, Ampfactors, Nvelocities );

	for( ivel = 0; ivel < Nvelocities; ivel++ ) {
		
		allot( double *, Ampfactors[ivel], Ncutoffs + 1 );

		arow = gettbl( pga_sitecorr_table, ivel );

		arow = strdup( arow );
		amps = split( arow, ' ' );

		if( maxtbl( amps ) != Ncutoffs + 1 ) {
			elog_complain( 0,
				"trinetsm_es99: wrong number of entries "
				"in pga_sitecorr_table row <%s>: should be "
				"\"minvel ampfactor ampfactor ....\" "
				"(need %d + minvel = %d entries, have %d)\n",
				arow, Ncutoffs, Ncutoffs+1, maxtbl( amps ));
			free( arow );
			freetbl( amps, 0 );
			free_ampfactors();
			return -1;
		} 
			
	   	for( icut = 0; icut < Ncutoffs + 1; icut++ ) {
			Ampfactors[ivel][icut] = atof( gettbl( amps, icut ) );	
	   	}

		free( arow );
		freetbl( amps, 0 );
	}

	freetbl( pga_sitecorr_table, 0 );

	return 0;
}
/* Modified Dec. 2006:  added two new Tbls for resid and slowness to
compute residuals only=tapro and tupro. */
int
load_observations ( Pf *pf, Dbptr db, Arr *arr_phase, 
	    Arr **stationsp, Arr **arraysp, Tbl **tap, Tbl **tup ,
		Tbl **tapro, Tbl **tupro) 
{ 
    Station *station ;
    Seismic_Array *array ;
    Arrival *a ;
    Tbl *ta, *tu ,*taro, *turo;
    Dbptr dbarr, dbsite ;
    static Hook *hook = 0 ; 
    static Tbl *matching ;
    Tbl *arrival_tbl ;
    Arr *stations ;
    Arr *arrays ;
    int i, narr ;
    char sta[32], iphase[32], timedef[16], azdef[16], slodef[16] ;
    double time, deltim, azimuth, delaz, slow, delslo ; 
    int arid ;
    Phase_handle *phase ;
    Slowness_vector *u ;
    int nobs = 0 ;

    if ( *stationsp == 0 ) {
	*stationsp = newarr(0) ; 
	*arraysp = newarr(0) ; 
    }
    stations = *stationsp ; 
    arrays = *arraysp ; 

    ta = *tap = newtbl(0) ;
    tu = *tup = newtbl(0) ;
    taro = *tapro = newtbl(0) ;
    turo = *tupro = newtbl(0) ;

    dbarr = dblookup ( db, 0, "arrival", 0, "dbSCRATCH" ) ; 
    dbsite = dblookup ( db, 0, "site", 0, 0 ) ; 

    arrival_tbl = pfget_tbl(pf, "arrival_table");
    narr = maxtbl(arrival_tbl);
    for (i = 0; i < narr; i++) {
	sscanf(gettbl(arrival_tbl, i),
	       "%d %s %s %lf %lf %s %lf %lf %s %lf %lf %s",
	       &arid,
	       sta,
	       iphase,
	       &time,
	       &deltim,
	       timedef,
	       &azimuth,
	       &delaz,
	       azdef,
	       &slow,
	       &delslo,
	       slodef
	    );

	if ( (station = getarr ( stations, sta ) ) == 0 ) {
	    dbputv ( dbarr, 0, "sta", sta, "time", time, NULL ) ; 
	    dbmatches ( dbarr, dbsite, 0, 0, &hook, &matching ) ;
	    if ( maxtbl(matching) < 1 ) {
		char *t ;
		complain ( 0, "No site table record for %s at time %s\n", 
		    sta, t=strtime(time));
		free(t) ;
		continue ;
	    }

	    dbsite.record = (long) gettbl(matching, 0) ;
	    freetbl(matching,0) ;
	    allot ( Station *, station, 1 ) ; 
	    allot ( Seismic_Array *, array, 1 ) ; 
	    dbgetv ( dbsite, 0, 
		"sta", station->name, "lat", &station->lat, "lon", &station->lon, "elev", &station->elev, NULL ) ;
	    dbgetv ( dbsite, 0, 
		"sta", array->name, "lat", &array->lat, "lon", &array->lon, "elev", &array->elev, NULL ) ;
	    setarr (stations, sta, station ) ; 
	    setarr (arrays, sta, array ) ; 
	} else {
示例#18
0
void main(int argc, char **argv)
{
	Dbptr db, dbv, dbge, dbgg;
	/*ensemble_mode is primary grouping, grouping_on set if secondary on*/
	int ensemble_mode,grouping_on;
	Tbl *ensemble_keys;
	Tbl *group_keys;
	int i;
	char *pfi=NULL;
	Pf *pf,*pfo_head,*pfo_total;
	Tbl *process_list;
	int dryrun=0;
	char *sift_exp=NULL;
	int sift;
/*Attributes listed in require will abort program if missing
passthrough parameters will generate an error message but not
cause the program to abort.  Both contain pointers to Attribute_map*/
	Tbl *require,*passthrough;
	Attribute_map *amap;
	FILE *fp;
	Tbl *error_list;
	char *tag;
	int sleep_time;  

	DB2PFS_verbose=0;

/*crack the command line*/
	if(argc<3) usage();
	elog_init(argc,argv);
	if(dbopen(argv[1],"r",&db)==dbINVALID)
	{
		elog_complain(0,"dbopen failed on database %s\n",argv[1]);
		usage();
	}

	for(i=3;i<argc;++i)
	{
		if(!strcmp(argv[i],"-pf"))
		{
			++i;
			if(i>argc) usage();
			pfi=argv[i];
		}
		else if(!strcmp(argv[i],"-V"))
			usage();
		else if(!strcmp(argv[i],"-v"))
			DB2PFS_verbose=1;
		else if(!strcmp(argv[i],"-n"))
			dryrun=1;
		else if(!strcmp(argv[i],"-sift"))
		{
			++i;
			if(i>argc) usage();
			sift=1;
			sift_exp=argv[i];
		}
		else
			usage();
	}
	if(!dryrun)
	{
		fp=fopen(argv[2],"r+");
		if(fp==NULL) usage();
	}
	
	if(pfi==NULL) pfi=strdup("db2pfstream");
	if(pfread(pfi,&pf))
		elog_die(0,"Error reading parameter file %s.pf\n",pfi);
	sleep_time=pfget_int(pf,"sleep_time");
	/* The output view gets a virtual table name that tags the
	overall collection of stuff.  This comes from the parameter file
	to make this program general, BUT it must be coordinated with
	the reader code. */
	tag = pfget_string(pf,"virtual_table_name");
	if(tag==NULL)elog_die(0,"Required parameter (virtual_table_name) missing from parameter file\n");
	ensemble_mode = pfget_boolean(pf,"ensemble_mode");
	if(ensemble_mode)
	{
		ensemble_keys=pfget_tbl(pf,"ensemble_keys");
		if(ensemble_keys==NULL)
			elog_die(0,
			 "ensemble_mode is on, but no grouping keys defined\nCheck parameter file\n");
		group_keys=pfget_tbl(pf,"group_keys");
		if(group_keys==NULL)
			grouping_on = 0;
		else
		{
			if(maxtbl(group_keys)>0)
				grouping_on = 1;
			else
				grouping_on = 0;
		}
	}
	if(DB2PFS_verbose && ensemble_mode)
	{
		char sm[128];
		char *key;
		strcpy(sm,"Defining ensemble with keys: ");
		for(i=0;i<maxtbl(ensemble_keys);++i)
		{
			key=gettbl(ensemble_keys,i);
			strcat(sm,key);
		}
		elog_log(0,"%s\n",sm);
		if(grouping_on)
		{
			strcpy(sm,"Grouping ensemble with keys:  ");
			for(i=0;i<maxtbl(group_keys);++i)
			{
				key = gettbl(group_keys,i);
				strcat(sm,key);
			}
			elog_log(0,"%s\n",sm);
		}
	}

	
	/*This function calls dbprocess using a tbl from pf*/
	dbv=dbform_working_view(db,pf,"dbprocess_list");
	if(dbv.record==dbINVALID)
		elog_die(0,"dbprocess failed:  check database and parameter file parameter dbprocess_list\n");
	if(sift_exp!=NULL)dbv=dbsubset(dbv,sift_exp,0);
	/*Now we form the groupings if needed */
	if(ensemble_mode)
	{
		dbge = dbgroup(dbv,ensemble_keys,"ensemble",1);
		if(dbge.record == dbINVALID)
			elog_die(0,"dbgroup with ensemble keys failed\n");
		if(grouping_on)
		{
			dbgg = dbgroup(dbv,group_keys,"groups",2);
			if(dbgg.record == dbINVALID)
				elog_die(0,"dbgroup on secondary grouping keys failed\n");
		}
	}

/*This builds the maps of which attributes will be saved */
	require = pfget_Attribute_map(pf,"require");
	if(require==NULL)
		elog_die(0,"Error in parameter file for parameter require\n");
	passthrough = pfget_Attribute_map(pf,"passthrough");
	if(passthrough==NULL)
		elog_die(0,"Error in parameter file for parameter passthrough\n");
	/* Unfortunately, we have two different loops for ensemble mode
	 and single object mode */
	if(ensemble_mode)
	{
		int number_ensembles;
		Dbptr db_bundle_1;
		Dbptr db_bundle_2;
		int is_ensemble, ie_ensemble;
		int isg, ieg;
		int number_groups;

		pfo_head=pfnew(0);
		pfput_tbl(pfo_head,"ensemble_keys",ensemble_keys);
		if(grouping_on) pfput_tbl(pfo_head,"group_keys",group_keys);
	

		dbquery(dbge,dbRECORD_COUNT,&number_ensembles);
		if(DB2PFS_verbose) elog_log(0,"database has %d ensembles\n",
					number_ensembles);
		if(grouping_on) 
		{
			dbgg.record=0;
			dbquery(dbgg,dbRECORD_COUNT,&number_groups);
			if(DB2PFS_verbose)
			  elog_log(0,"database has %d subgroups\n",
				number_groups);
		}
		for(dbge.record=0;dbge.record<number_ensembles;
					++dbge.record)
		{
			Pf_ensemble *pfe;
			int nmembers;
			char *grp_records;
			Tbl *grplist;

			dbgetv(dbge,0,"bundle",&db_bundle_1,0);
			dbget_range(db_bundle_1,&is_ensemble,&ie_ensemble);
			nmembers = ie_ensemble-is_ensemble;
			/* pfe does not need to hold the group records
			for this application so the ngroups variable is 
			passed as 0*/
			pfe=create_Pf_ensemble(nmembers,0);
			/*Now loop through and load the array of pf's
			with parameters defined by the attribute maps*/
			for(i=0,dbv.record=is_ensemble;i<nmembers;
				++i,++dbv.record)
			{
				pfe->pf[i]=pfnew(PFARR);
				error_list=db2pf(dbv,require,pfe->pf[i]);
				if(maxtbl(error_list)>0)
				{
				    if(dryrun)
				    {
					elog_log(0,"Ensemble %d at input database view record %d lacks required attributes\n",
						dbge.record,dbv.record);
					log_error_list(error_list);
				    }
				    else
				    {
					fprintf(fp,"%s\n",END_OF_DATA_SENTINEL);
					fflush(fp);
					elog_log(0,"FATAL ERROR: ensemble %d at input database view record %d lacks required attributes\nOUTPUT DATA STREAM TRUNCATED\n",
						i,dbv.record);
					log_error_list(error_list);
					exit(-1);
				    }
				}
				freetbl(error_list,free);
				error_list=db2pf(dbv,passthrough,pfe->pf[i]);
				if(DB2PFS_verbose)
				{
					elog_log(0,"Warning:  null passthrough attributes for ensemble %d at row %d\n",
						dbge.record,dbv.record);
					log_error_list(error_list);
				}
				freetbl(error_list,free);
				pfput_boolean(pfe->pf[i],"data_valid",1);
			}
			
			if(grouping_on)
			{
				grplist=newtbl(0);
				do {
				     dbgetv(dbgg,0,"bundle",&db_bundle_2,0);
				     dbget_range(db_bundle_2,&isg,&ieg);
				     grp_records=malloc(30);
				     sprintf(grp_records,"%d %d",
					isg-is_ensemble,ieg-is_ensemble-1);
				     pushtbl(grplist,grp_records);
				     ++dbgg.record;
				}
				while (ieg<ie_ensemble);
				pfput_tbl(pfo_head,"group_records",grplist);
			}

			pfo_total=build_ensemble(1,tag,pfo_head,pfe);
			free_Pf_ensemble(pfe);
			if(!dryrun) 
			{
				pfout(fp,pfo_total);
				fprintf(fp,"%s\n",ENDPF_SENTINEL);
				fflush(fp);
			}
			pffree(pfo_total);
			if(grouping_on)freetbl(grplist,free);
		}
	}
	else
	{
	/*This is the simpler, single block mode */
		int nrecords;
		Pf *pfo;

		dbquery(dbv,dbRECORD_COUNT,&nrecords);
		pfo=pfnew(PFARR);
		for(dbv.record=0;dbv.record<nrecords;++dbv.record)
		{
			error_list=db2pf(dbv,require,pfo);
			if(maxtbl(error_list)>0)
			{
			    if(dryrun)
			    {
				elog_log(0,"Input database view at row %d lacks required parameters\n",
					dbv.record);
				log_error_list(error_list);
			    }
			    else
			    {
				fprintf(fp,"%s\n",END_OF_DATA_SENTINEL);
				fflush(fp);
				elog_log(0,"FATAL: input database view at row %d lacks required parameters\n",
					dbv.record);
				log_error_list(error_list);
				exit(-1);
			    }
			}
			freetbl(error_list,free);
			error_list=db2pf(dbv,passthrough,pfo);
			pfput_boolean(pfo,"data_valid",1);
			if(DB2PFS_verbose)
			{
				elog_log(0,"Warning:  null passthrough attributes for row %d of input database view\n",
					dbv.record);
			}
			if(!dryrun)
			{
				pfout(fp,pfo);
				fprintf(fp,"%s\n",ENDPF_SENTINEL);
			}
		}
	}
	if(!dryrun)
	{
		fprintf(fp,"%s\n",END_OF_DATA_SENTINEL);
		fflush(fp);
		sleep(sleep_time);
		fclose(fp);
	}
	exit(0);
}
double *get_time_weight_function(char *tblname, double t0, double dt, int nt, Pf *pf)
{
	Tbl *t;
	int npairs,nused;
	int i,ii,ierr;
	double *tpairs, *wpairs;
	double *timeweight;

	t = pfget_tbl(pf,tblname);
	if(maxtbl(t)<=0)
	{
		elog_complain(0,"get_time_weight_function: %s tbl object is not in input parameter file\n",
			tblname);
		return(NULL);
	}
	npairs=maxtbl(t);
	allot(double *,tpairs,npairs);
	allot(double *,wpairs,npairs);
	for(i=0,ii=0,nused=0;i<npairs;++i)
	{
		char *line;
		line=gettbl(t,i);
		sscanf(line,"%lf%lf",tpairs+ii,wpairs+ii);
		if(i==0)
		{
			++ii;
			++nused;
		}
		else
		{
			if(tpairs[ii]<tpairs[ii-1])
			{
				elog_complain(0,"get_time_weight_function: Illegal input for time weight function:  list of time-weight pairs must be in time order\nFound %lf following %lf;  dropping this point and attempting to continue\n",
					tpairs[ii],tpairs[ii-1]);
			}
			else
			{
				++ii;
				++nused;
			}
		}
	}
	if(nused<=1)
	{
		elog_complain(0,"get_time_weight_function: Not enough time-weight pairs found to define a valid time window\nParsed only %d valid pairs.  Correct parameter file and try again\n",
			nused);
		return(NULL);
	}
	allot(double *,timeweight,nt);
	ierr = irregular_to_regular_interpolate(tpairs,wpairs,nused,
		timeweight,t0,dt,nt);
	if(ierr)
	{
		elog_complain(0,"get_time_weight_function: Interpolation of window pairs to data interval failed.\n");
		free(timeweight);
		return(NULL);
	}
	free(tpairs);
	free(wpairs);		
	return(timeweight);
}
示例#20
0
/* This function is used to check a list of pf names to verify they
are in the parameter space.  It is useful for any program that uses
parameter files that cracks the pf space anywhere except up front.
That is, the pf space is a convenient place to store all the run time
parameters of any program and is a convenient way to pass a large
control structure.  However, because flow can be complex it is possible
to have parameters that are only accessed deep within a program and 
in these situations it is desirable to run a check at program initialization
to verify the required parameters will be there when required.  

Normally a string variable will not cause pfget to die, but it will
here if it is listed as required

Parameters to be checked are grouped by type.  Each numerical fields
can contain an optional range check.  This is not allowed for strings.
Code below only checks int, double, boolean, and string variables.  Because of
the complexity of Tbl and Arrs I thought this not worth messing with.
Furthermore, it is not unusual to have an empty Tbl list or Arr that
the program should handle correctly.  

Function will die on the first occurence of a problem parameter.
It is void because it only returns if everything checks out.

Author:  Gary L. Pavlis
*/
void check_required_pf(Pf *pf)
{
	Tbl *t,*testtbl;
	Pf *pf_required;
	char *key;
	int i,j,nitems;
	int itest, ilowcheck, ihighcheck;
	double dtest, dlowcheck, dhighcheck;
	int bool;
	char *line;
	char *ctest;
	char name[50];

	/* This cracks the "required" &Arr dies if it isn't present 
	at all.  This assumes you wouldn't call this routine if you
	weren't serious about checking */
	if(pfget(pf,"require",(void **)&pf_required) != PFARR)
		die(0,"Arr of required parameters (require &Arr) missing from parameter space\nMust be present to execute this program\n");
	t=pfkeys(pf_required);
	for(i=0;i<maxtbl(t);++i)
	{
		key = gettbl(t,i);
		if(!strcmp(key,"int"))
		{
			testtbl = pfget_tbl(pf_required,"int");
			for(j=0;j<maxtbl(testtbl);++j)
			{
				line = gettbl(testtbl,i);
				nitems = sscanf(line,"%s%d%d",name,&ilowcheck,
							&ihighcheck);
				itest = pfget_int(pf,name);
				if(nitems == 3)
				{
					if( (itest < ilowcheck)
					  || (itest > ihighcheck) ) die(0,
						"Parameter %s has value %d which is outside required range of %d to %d\n",
						   name,itest,ilowcheck,ihighcheck);
				}
			}
		}
		else if(!strcmp(key,"double"))
		{
			testtbl = pfget_tbl(pf_required,"double");
			for(j=0;j<maxtbl(testtbl);++j)
			{
				line = gettbl(testtbl,i);
				nitems = sscanf(line,"%s%lg%lg",name,&dlowcheck,
							&dhighcheck);
				dtest = pfget_double(pf,name);
				if(nitems == 3)
				{
					if( (dtest < dlowcheck)
					  || (dtest > dhighcheck) ) die(0,
						"Parameter %s has value %lg which is outside required range of %lg to %lg\n",
						   name,dtest,dlowcheck,dhighcheck);
				}
			}
		}
		else if(!strcmp(key,"boolean"))
		{
			testtbl = pfget_tbl(pf_required,"boolean");
			for(j=0;j<maxtbl(testtbl);++j)
			{
				line = gettbl(testtbl,i);
				itest = pfget_boolean(pf,line);
			}
		}
		else if(!strcmp(key,"string"))
		{
			testtbl=pfget_tbl(pf_required,"string");
			for(j=0;j<maxtbl(testtbl);++j)
			{
				line = gettbl(testtbl,i);
				ctest = pfget_string(pf,line);
				if(ctest == NULL)
					die(0,"Missing required string variable = %s\n",
						line);
			}
		}
		else
		{
			elog_notify(0,"Unknown required type name = %s\nRequired parameters under this heading will not be checked\n",
				key);
		}
	}
	freetbl(t,0);
}
/* Init function for uniform table.
 phase = phase name to tag this table with
 pf = input parameter file object to be parsed.


The following keys are required to be found in pf:
	int:
	nx, nz
	scalar double:
	dx, dz
	&Tbl:
	uniform_grid_time_slowness_table

The later contains the actual tables.  They are ascii tables make up
of nx*nz lines (x varies most rapidly) of the following format:
	time, slowness, slowness derivative wrt distance, branch

The "branch" variable is a character key defined in location.h

Optional parameters with defaults:
	scalar double:
	x0, y0 coordinates of first point in table  (default = (0,0))
	strings:

Notice that this routine requires mixed units.  dx, dz, x0, and y0
must all be specified in degrees.  Everything else has units derived
from km and s.  That is, time is is in seconds, slowness (p) is
assumed to be in s/km, and dpdx (slowness derivative) is (s/km)/km.
This was done because the input tables are ascii, and these numbers
are scaled to units that make sense to most of us.  This format is
connected to a related program called taup_convert that writes
ttables in this format using the tau-p library.

Returns 0 if no problems are encountered.  REturns 1 if a serious
error occurred that rendered setup impossible for this phase.
In the later case, register_error is always called and should be
handled by calling program.

There are some fatal errors that lead to die being called here from
things like malloc failures.
*/
int uniform_table_interpolate_init(char *phase, Pf *pf)
{
    XZ_table_uniform *ttable, *utable;

    Tbl *t;  /* pfget_tbl return to hold strings of prototables stored
		in the pf structure. */
    int i,j,k;

    GenlocVerbose = verbose_exists() ;

    if(time_tables_uniform==NULL) time_tables_uniform = newarr(0);
    if(slow_tables_uniform==NULL) slow_tables_uniform = newarr(0);

    ttable = (XZ_table_uniform *)malloc(sizeof(XZ_table_uniform));
    utable = (XZ_table_uniform *)malloc(sizeof(XZ_table_uniform));


    if( (ttable == NULL) || (utable == NULL) )
        elog_die(1,"Can't alloc memory in uniform_table_interpolate_init\n");

    /* This version requires t and u tables to be parallel.  This
    restriction would not be necessary, but it simplifies things
    greatly and we only have to store times in the values matrix
    and the slowness values in the slopes matrix. */

    ttable->nx = pfget_int(pf, "nx");
    ttable->nz = pfget_int(pf, "nz");
    utable->nx = ttable->nx;
    utable->nz = ttable->nz;
    ttable->dx = pfget_double(pf, "dx");
    ttable->dz = pfget_double(pf, "dz");
    utable->dx = ttable->dx;
    utable->dz = ttable->dz;
    /* These parameters default to 0 */
    if(pfget_string(pf,"x0")==NULL)
    {
        ttable->x0 = 0.0;
        utable->x0 = 0.0;
    }
    else
    {
        ttable->x0 = pfget_double(pf,"x0");
        utable->x0 = ttable->x0;
    }
    if(pfget_string(pf,"z0")==NULL)
    {
        ttable->z0 = 0.0;
        utable->z0 = 0.0;
    }
    else
    {
        ttable->z0 = pfget_double(pf,"z0");
        utable->z0 = ttable->z0;
    }

    /* IMPORTANT WARNING:  notice I only alloc one space for the
    slowness values array, although it gets placed in two different
    places -> values section of utable and slopes section of ttable
    This leaves a nasty dependency if this space is to be freed, but
    saves a lot of memory.  p.s  I did the same thing with velocity,
    but not with the branch array (see below) */

    ttable->values = dmatrix(0,(ttable->nx)-1,0,(ttable->nz)-1);
    if(ttable->values == NULL)
        elog_die(1,"Cannot alloc memory for travel time table of size %d by %d for phase %s\n",
                 ttable->nx, ttable->nz, phase);
    ttable->slopes = dmatrix(0,(ttable->nx)-1,0,(ttable->nz)-1);
    if(ttable->slopes == NULL)
        elog_die(1,"Cannot alloc memory for slowness table of size %d by %d for phase %s\n",
                 ttable->nx, ttable->nz, phase);
    ttable->branch = cmatrix(0,(ttable->nx)-1,0,(ttable->nz)-1);
    if(ttable->branch == NULL)
        elog_die(1,"Cannot alloc memory for time branch table for phase %s\n",
                 phase);
    utable->branch = cmatrix(0,(utable->nx)-1,0,(utable->nz)-1);
    if(utable->branch == NULL)
        elog_die(1,"Cannot alloc memory for slowness branch table for phase %s\n",
                 phase);

    ttable->velocity = (double *) calloc(ttable->nz,sizeof(double));
    if(ttable->velocity == NULL)
        elog_die(1,"Cannot alloc memory for velocity model for phase %s\n",
                 phase);

    utable->slopes = dmatrix(0,(utable->nx)-1,0,(utable->nz)-1);
    if(utable->slopes == NULL)
        elog_die(1,"Cannot alloc memory for dudr table of size %d by %d for phase %s\n",
                 utable->nx, utable->nz, phase);

    /* here is where we set the redundant pointers */
    utable->values = ttable->slopes;
    utable->velocity = ttable->velocity;


    /* Now it is time to actually parse the tables.  We assume the
    table is entered as a pf &Tbl, and table is scanned with x
    varying most rapidly.  (i.e. you get the tables for x=x0 first,
    then x=x0+dx, etc. Note we read three entries for each grid
    point:  time, slowness, branch_code */
    t = pfget_tbl(pf,"uniform_grid_time_slowness_table");
    if(t == NULL)
    {
        elog_log(1,"Can't find travel time-slowness table for phase %s\n",
                 phase);
        free_uniform_table(ttable, utable);
        return(1);
    }

    if( maxtbl(t) != ( (ttable->nx)*(ttable->nz) ) )
    {
        elog_log(1,"Table size mismatch for phase %s\nTable should have %d rows\nFound %ld\n",
                 phase, (ttable->nx)*(ttable->nz), maxtbl(t));
        free_uniform_table(ttable, utable);
        return(1);
    }

    for(j=0,k=0; j<ttable->nz; ++j)
    {
        for(i=0; i<ttable->nx; ++i)
        {
            char *s;
            int nitems;
            double tt,u,dudx;
            char b;
            s = gettbl(t,k);
            nitems = sscanf(s,"%lf%lf%lf%1s",
                            &tt, &u, &dudx,&b);
            if(nitems !=4)
            {
                elog_log(1,"Syntax error reading table for phase %s, Problem read value for i=%d, j=%d\n",
                         phase,i,j);
                free_uniform_table(ttable, utable);
                return(1);
            }
            ttable->values[i][j] = tt;
            ttable->slopes[i][j] = u;
            utable->slopes[i][j] = dudx;
            ttable->branch[i][j] = b;
            ++k;
        }
    }

    /* In order to utilize a common set of interpolation routines,
    scan the time->branch matrix.  Mark the crossover points for
    time as jump discontinuities for slowness (which they are) */
    for(j=0; j<ttable->nz; ++j)
        for(i=0; i<ttable->nx; ++i)
            if(ttable->branch[i][j] == CROSSOVER)
                utable->branch[i][j] = JUMP;
            else
                utable->branch[i][j] = ttable->branch[i][j];
    /* An error check is needed here so we don't have to worry about it
    later.  Other than a blunder, this can happen if x0 is anything
    other than 0, so we need to watch for this.  We could try to
    repair this automatically, but because it mostly likely indicates
    a serious blunder we abort */

    for(j=0; j<ttable->nz; ++j)
        if( (utable->branch[0][j] == CROSSOVER)
                || (ttable->branch[0][j] == CROSSOVER)
                || (utable->branch[0][j] == JUMP)
                || (ttable->branch[0][j] == JUMP) )
        {

            elog_log(1,
                     "Error in travel time table for phase %s\nFirst point cannot be marked as a crossover or jump discontinuity\n",phase);
            free_uniform_table(ttable, utable);
            return(1);
        }
    /* Now we read the velocity model parameters */
    t = pfget_tbl(pf,"velocities");
    if((ttable->nz) != maxtbl(t))
    {
        elog_log(1,"Error in phase parameter file.  \
Mismatch between velocity entries and table entries\n\
Tables have %d depth entries, but velocity vector is of length %ld\n",
                 ttable->nz, maxtbl(t));
        free_uniform_table(ttable,utable);
        return(1);
    }
    for(i=0; i<maxtbl(t); ++i)
    {
        char *s;
        s = gettbl(t,i);
        sscanf(s,"%lf", &(ttable->velocity[i]));
    }
    setarr(time_tables_uniform,phase,ttable);
    setarr(slow_tables_uniform,phase,utable);
    return(0);
}
示例#22
0
int
main( int argc, char **argv )
{
	int	c;
	int	errflag = 0;
	int	orb;
	int	stop = 0;
	long	nrecs;
	char	*match = ".*/pf/st";
	char	*from = 0;
	char	*statefile = 0;
	char	*pfname = "orb2rrdc";
	char	*orbname;
	char	*dbcache;
	char	*rrdtool;
	char	command[STRSZ];
	char	net[STRSZ];
	char	sta[STRSZ];
	char	rrdvar[STRSZ];
	char	key[STRSZ];
	char	path[FILENAME_MAX];
	Dbptr	db;
	Dbptr	dbt;
	Pf	*pf;
	char	*Default_network;
	Tbl	*dlslines;
	Arr	*Dls_vars_dsparams;
	Arr	*Dls_vars_rras;
	Tbl	*Dls_vars_keys;
	char	*line;
	char	*dls_var;
	char	*dsparams;
	Tbl	*rras;
	int	i;
	int	j;
	OrbreapThr *ort;
	int	pktid;
	char	srcname[ORBSRCNAME_SIZE];
	double	time = 0;
	char	*packet = 0;
	int	nbytes = 0;
	int	bufsize = 0;
	Packet	*pkt = 0;
	int	rc;
	char	*s;
	Pf	*dlspf;
	Tbl	*dlspfkeys;
	char	*element;
	Tbl	*parts;
	double	val;
	Pf	*pfval = 0;

	elog_init( argc, argv );

	while( ( c = getopt( argc, argv, "vVd:s:p:m:f:" ) ) != -1 ) {

		switch( c ) {

		case 'd':
			CacheDaemon = optarg;
			break;

		case 'f':
			from = optarg;
			break;

		case 'm':
			match = optarg;
			break;

		case 'p': 
			pfname = optarg;
			break;

		case 's':
			statefile = optarg;
			break;
			
		case 'v':
			Verbose++;
			break;

		case 'V':
			VeryVerbose++;
			Verbose++;
			break;
		
		default:
			elog_complain( 0, "Unknown option '%c'\n", c );
			errflag++;
			break;
		}
	}

	if( errflag || argc - optind != 2 ) {

		usage();
	}

	if( Verbose ) {

		elog_notify( 0, "Starting at %s (%s $Revision$ $Date$)\n", 
				zepoch2str( str2epoch( "now" ), "%D %T %Z", "" ),
				Program_Name );
	}

	orbname = argv[optind++];
	dbcache = argv[optind++];

	pfread( pfname, &pf );

	rrdtool = pfget_string( pf, "rrdtool" );

	if( rrdtool == NULL || ! strcmp( rrdtool, "" ) ) {

		elog_die( 0, "Error: no rrdtool executable name specified in parameter file\n" );

	} else if( ( rrdtool[0] == '/' && ! is_present( rrdtool ) ) || ( rrdtool[0] != '/' && ! datafile( "PATH", rrdtool ) ) ) {

		elog_die( 0, "Error: can't find rrdtool executable by name of '%s' (check PATH environment " 
			"variable, or absolute path name if given)\n", rrdtool );

	} else if( rrdtool[0] == '/' ) {

		sprintf( command, "%s -", rrdtool );

	} else {

		sprintf( command, "rrdtool -" );
	}

	Suppress_egrep = pfget_string( pf, "suppress_egrep" );

	if( Suppress_egrep != NULL && strcmp( Suppress_egrep, "" ) ) {
		
		if( ! datafile( "PATH", "egrep" ) ) {

			elog_complain( 0, "Ignoring suppress_egrep parameter: can't find egrep on path\n" ); 

		} else {

			sprintf( command, "%s 2>&1 | egrep -v '%s'", command, Suppress_egrep );
		}
	}

	if( VeryVerbose ) {

		elog_notify( 0, "Executing command: %s\n", command );
	}

	Rrdfp = popen( command, "w" );

	if( Rrdfp == (FILE *) NULL ) {

		elog_die( 0, "Failed to open socket to rrdtool command\n" );
	}

	orb = orbopen( orbname, "r&" );

	if( orb < 0 ) {

		elog_die( 0, "Failed to open orb '%s' for reading. Bye.\n", orbname );
	}

	orbselect( orb, match );

	if( from != NULL && statefile == NULL ) {

		pktid = orbposition( orb, from );

		if( Verbose ) {

			elog_notify( 0, "Positioned to packet %d\n", pktid );
		}

	} else if( from != NULL ) {

		elog_complain( 0, "Ignoring -f in favor of existing state file\n" );
	}

	if( statefile != NULL ) {

		stop = 0;

		exhume( statefile, &stop, 15, 0 );

		orbresurrect( orb, &pktid, &time );

		if( Verbose ) {

			elog_notify( 0, "Resurrecting state to pktid %d, time %s\n",
				pktid, s = strtime( time ) );

			free( s );
		}

		orbseek( orb, pktid );
	}

	dbopen( dbcache, "r+", &db );

	if( db.database < 0 ) {
		
		elog_die( 0, "Failed to open cache database '%s'. Bye.\n", dbcache );

	} else {
		
		db = dblookup( db, "", "rrdcache", "", "" );

		if( db.table < 0 ) {

			elog_die( 0, "Failed to lookup 'rrdcache' table in '%s'. Bye.\n", dbcache );
		}
	}

	dbcrunch( db );

	dbt = dbsubset( db, "endtime == NULL", NULL );

	Rrd_files = newarr( 0 );

	dbquery( dbt, dbRECORD_COUNT, &nrecs );

	for( dbt.record = 0; dbt.record < nrecs; dbt.record++ ) {

		dbgetv( dbt, 0, "net", &net, "sta", &sta, "rrdvar", &rrdvar, NULL );

		dbfilename( dbt, (char *) &path );

		sprintf( key, "%s:%s:%s", net, sta, rrdvar );

		if( ! is_present( path ) ) {
			
			elog_complain( 0, "WARNING: rrd file '%s', listed in database, does not exist. "
				"Removing database entry.\n", path );

			dbmark( dbt );

		} else {

			setarr( Rrd_files, key, strdup( path ) );

			if( VeryVerbose ) {

				elog_notify( 0, "Re-using rrd file '%s' for '%s'\n", path, key );
			}
		}
	}

	Rrdfile_pattern = pfget_string( pf, "rrdfile_pattern" );
	Status_stepsize_sec = pfget_double( pf, "status_stepsize_sec" );
	Default_network = pfget_string( pf, "default_network" );
	dlslines = pfget_tbl( pf, "dls_vars" );

	Dls_vars_dsparams = newarr( 0 );
	Dls_vars_rras = newarr( 0 );

	for( i = 0; i < maxtbl( dlslines ); i++ ) {
		
		line = gettbl( dlslines, i );
		
		strtr( line, "\t", " " );
		rras = split( line, ' ' );

		dls_var = shifttbl( rras );
		dsparams = shifttbl( rras );

		setarr( Dls_vars_dsparams, dls_var, dsparams );
		setarr( Dls_vars_rras, dls_var, rras );
	}

	ort = orbreapthr_new( orb, -1., 0 );

	for( ; stop == 0; ) {

		orbreapthr_get( ort, &pktid, srcname, &time, &packet, &nbytes, &bufsize );

		if( statefile ) {

			rc = bury();

			if( rc < 0 ) {

				elog_complain( 0, "Unexpected failure of bury command! " 
					"(are there two orb2rrdc's running with the same state" 
					"file?)\n" );

				clear_register( 1 );
			}
		}

		rc = unstuffPkt( srcname, time, packet, nbytes, &pkt );

		if( rc == Pkt_pf ) {

			if( VeryVerbose ) {

				/* Parameter files generally too big for elog */

				fprintf( stderr, "Received a parameter-file '%s' at %s\n%s\n\n", 
						srcname, 
						s = strtime( time ), 
						pf2string( pkt->pf ) );

				free( s );

			} else if( Verbose ) {

				elog_notify( 0, "Received a parameter-file '%s' at %s\n", 
						srcname, s = strtime( time ) );

				free( s );
			}

			pfmorph( pkt->pf );

			if( VeryVerbose ) {

				fprintf( stderr, "Morphed parameter-file '%s' to interpret 'opt':\n%s\n\n", 
						srcname, 
						pf2string( pkt->pf ) );
			}

			pfget( pkt->pf, "dls", (void **) &dlspf );

			dlspfkeys = pfkeys( dlspf );
			Dls_vars_keys = keysarr( Dls_vars_dsparams );

			for( i = 0; i < maxtbl( dlspfkeys ); i++ ) {
			   
			   element = gettbl( dlspfkeys, i );

			   if( strcontains( element, "_", 0, 0, 0 ) ) {

				parts = split( (s = strdup( element )), '_' );

				sprintf( net, "%s", (char *) gettbl( parts, 0 ) );
				sprintf( sta, "%s", (char *) gettbl( parts, 1 ) );

				free( s );
				freetbl( parts, 0 );

			   } else {

				sprintf( net, "%s", Default_network );

				sprintf( sta, "%s", element );
			   }

			   for( j = 0; j < maxtbl( Dls_vars_keys ); j++ ) {

			   	dls_var = gettbl( Dls_vars_keys, j );

				sprintf( key, "%s{%s}", element, dls_var );

				if( pfresolve( dlspf, key, 0, &pfval ) < 0 ) {

					elog_complain( 0, "Unable to extract variable '%s' "
						"(not present or wrong type) from element '%s' "
						"in packet from '%s', timestamped '%s'; Skipping\n",
						key, element, srcname, s = strtime( time ) );

					free( s );

					pfval = 0;

					continue;

				} else if( pfval != (Pf *) NULL &&
					   pfval->value.s != (char *) NULL &&
					   ! strcmp( pfval->value.s, "-" ) ) {

					if( VeryVerbose ) {

						elog_notify( 0, "Non-floating point value '-' in variable '%s', "
							"in packet from '%s', timestamped '%s'; Skipping data point\n",
							key, srcname, s = strtime( time ) );

						free( s );
					}

					continue;

				} else {

					val = pfget_double( dlspf, key );
				}

				archive_dlsvar( db, net, sta, dls_var, 
						(char *) getarr( Dls_vars_dsparams, dls_var ),
						(Tbl *) getarr( Dls_vars_rras, dls_var ),
						time, val );
			   }

			}

			freetbl( dlspfkeys, 0 );
			freetbl( Dls_vars_keys, 0 );

		} else if( rc == Pkt_stash ) {

			; /* Do nothing */

		} else {

			if( Verbose ) {

				elog_notify( 0, "Received a packet that's not a parameter file " 
					"(type '%d' from unstuffPkt); skipping\n", rc );
			}
		}
	}
}
Tbl *pfget_Attribute_map(Pf *pf, char *name)
{
	Attribute_map *amap;
	Tbl *t;
	Tbl *tout;
	int nlist;
	int i;

	t=pfget_tbl(pf,name);
	if(t==NULL)
	{
		elog_complain(0,"parameter %s to define Attribute_map not in parameter file\n",name);
		freetbl(t,0);
		return(NULL);
	}
	nlist=maxtbl(t);
	tout=newtbl(nlist);
	for(i=0;i<nlist;++i)
	{
		char dbname[80],type[20],pfname[80];
		char *s;
		s=gettbl(t,i);
		allot(Attribute_map *,amap,1);
		if(sscanf(s,"%s %s %s",dbname,type,pfname)!=3)
		{
			elog_complain(0,"Syntax error in input line for input list %s defining attribute mapping\nBadline:  %s\n",
				name,s);
			freetbl(t,0);
			freetbl(tout,free);
		}
		/*the type fields here are defined by an enum in db2pfstream.h
		minor added code to make the input more flexible here. */
		if((!strcmp(type,"int")) || (!strcmp(type,"INT"))
				|| (!strcmp(type,"integer")) )
			amap->type=DBINT;
		else if((!strcmp(type,"real")) || (!strcmp(type,"REAL"))
				|| (!strcmp(type,"double")) 
				|| (!strcmp(type,"DOUBLE"))
				|| (!strcmp(type,"float")) 
				|| (!strcmp(type,"FLOAT")))
			amap->type=DBREAL;
		else if((!strcmp(type,"string")) || (!strcmp(type,"STRING"))
				|| (!strcmp(type,"str"))
				|| (!strcmp(type,"STR")) )
			amap->type=DBSTR;
		else if((!strcmp(type,"time")) || (!strcmp(type,"TIME")) )
			amap->type=DBTIME;
		else
		{
			elog_complain(0,"Syntax error:  unknown data type %s used to define Attribute mapping\n",
				type);
			freetbl(t,0);
			freetbl(tout,free);
			return(NULL);
		}
		amap->dbname = strdup(dbname);
		amap->pfname = strdup(pfname);
		pushtbl(tout,amap);
	}

	freetbl(t,0);
	return(tout);
}