Esempio n. 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;
}
Esempio n. 2
0
void save_run_parameters(Dbptr db,Pf *pf)
{
	char *dir,*dfile;
	char filename[512];
	char *vm,*vm3d;
	int ierr;
	
	dir = pfget_string(pf,"pmelrun_archive_directory");
	if(dir==NULL)elog_die(0,"Parameter pmelrun_archive_directory not in parameter file\n");
	if(makedir(dir))
		elog_die(0,"makedir failed on directory %s\n",dir);
	dfile = pfget_string(pf,"pmel_run_name");

	
	vm = pfget_string(pf,"travel_time_model");
	vm3d=pfget_string(pf,"3Dreference_model");
	if( (vm==NULL) || (vm3d==NULL) )
		elog_die(0,"Missing required velocity model definitions\nCheck parameters travel_time model and 3Dreference_model\n");
	db = dblookup(db,0,"pmelruns",0,0);
	ierr=dbaddv(db,0,"pmelrun",dfile,
		"vmodel",vm,
		"vmodel3d",vm3d,
		"dir",dir,
		"dfile",dfile,0);
	if(ierr < 0) elog_die(0,
		   "dbaddv error on pmelrun table\nVerify schema extensions for dbpmel and that the pmel_run_name parameter is unique\n");

	strcpy(filename,dir);
	strcat(filename,"/");
	strcat(filename,dfile);
	if(pfwrite(filename,pf))
		elog_die(0,"pfwrite error for file %s\n",filename);
}
RTlocate_Options parse_rt_options (Pf *pf)
{
	RTlocate_Options o;
	char failure_dirs[STRSZ] ;
	o.work_db=pfget_string(pf,"RT_working_db");
	if(o.work_db  == NULL) o.work_db = strdup("orbgenloc");
	o.logdir=pfget_string(pf,"RT_logfile_directory");
	if(o.logdir == NULL) {
	    o.logdir = strdup(".");
	} else { 
	    makedir ( o.logdir ) ; 
	}
	o.failure_sdir = pfget_string(pf,"RT_failure_subdir");
	strcpy ( failure_dirs, o.logdir ) ; 
	strcat ( failure_dirs, "/" ) ; 
	strcat ( failure_dirs, o.failure_sdir ) ; 
	makedir ( failure_dirs ) ; 
	if(o.failure_sdir == NULL) o.failure_sdir = strdup("failure");
	o.minimum_distance = pfget_double(pf,"RT_minimum_distance");
	o.maximum_distance = pfget_double(pf,"RT_maximum_distance");

	o.db_record_skip_timeout = pfget_int(pf,"RT_db_record_skip_limit");

	return(o);
}
/* These functions allow defaulting of double and ints respectively.*/
double pfget_double_wdef(Pf *pf, char *keyword, double def)
{
	if(pfget_string(pf,keyword) == NULL)
		return(def);
	else
		return(pfget_double(pf,keyword));
 }
int pfget_boolean_wdef(Pf *pf, char *keyword, int def)
{
	if(pfget_string(pf,keyword) == NULL)
		return(def);
	else
		return(pfget_boolean(pf,keyword));
 }
int get_stack_align_mode(Pf *pf)
{
	char *s;
	int align_opt;

	s=pfget_string(pf,"stack_alignment");
	if(s==NULL)
	{
		elog_notify(0,"stack_alignment parameter not defined\nDefaulting to model based estimate\n");
		align_opt=PMTHEORY;
	}
	else if(!strcmp(s,"theoretical"))
		align_opt=PMTHEORY;
	else if(!strcmp(s,"pmestimate"))
		align_opt=PMESTIMATE;
	else if(!strcmp(s,"vertical"))
		align_opt=PMZ;
	else
	{
		elog_notify(0,"Illegal stack_alignment parameter = %s\nUsing default=model-based estimate\n",
			s);
		align_opt=PMTHEORY;
	} 

	return(align_opt);
}
Esempio n. 7
0
enum FREEZE_METHOD get_freeze_method(Pf *pf)
{
	enum FREEZE_METHOD result;
	char *s;
	s=pfget_string(pf,"freeze_method");
	if(s==NULL)
	{
		elog_notify(0,"freeze_method parameter not defined in parameter file\nDefault to maximum arrival count space coordinates");
		result=ALLSPACE_MAXARRIVALS;
	}
	else if(strcmp(s,"depth_maxarrival")==0)
		result=DEPTH_MAXARRIVALS;
	else if(strcmp(s,"allspace_maxarrivals")==0)
		result=ALLSPACE_MAXARRIVALS;
	else if(strcmp(s,"all_maxarrivals")==0)
		result=ALL_MAXARRIVALS;
	else if(strcmp(s,"depth_minrms")==0)
		result=DEPTH_MINRMS;
	else if(strcmp(s,"allspace_minrms")==0)
		result=ALLSPACE_MINRMS;
	else if(strcmp(s,"all_minrms")==0)
		result=ALL_MINRMS;
	else
	{
		result=ALLSPACE_MAXARRIVALS;
		elog_notify(0,"Invalid keyword %s used for parameter freeze_method\nDefault allspace_maxarrivals",s);
	}
	return(result);
}
Esempio n. 8
0
static void 
id_clients( Pf *pf )
{
	Pf	*pfclients;
	Pf	*pfclient;
	char	client_summary[STRSZ];
	char	*serveraddress;
	char	*serverport;
	Tbl	*client_keys;
	int	ikey;
	char	*client_key;
	char	clientid_key[STRSZ];
	char	*clientaddress;
	char	*what;
	char	clientid[33];

	pfeval( pf, "server{address}", &serveraddress );
	pfeval( pf, "server{port}", &serverport );

	pfget( pf, "clients", (void **) &pfclients );

	client_keys = pfkeys( pfclients );

	for( ikey = 0; ikey < maxtbl( client_keys ); ikey++ ) {

		client_key = gettbl( client_keys, ikey );

		pfget( pfclients, client_key, (void **) &pfclient );

		clientaddress = pfget_string( pfclient, "address" );
		what = pfget_string( pfclient, "what" );

		sprintf( client_summary, "%s %s %s %s", 
				serveraddress, serverport,
				clientaddress, what );

		sprintf( clientid_key, "clients{%s}{clientid}", client_key );

		mdhex( clientid, client_summary, strlen( client_summary ) );

		pfset( pf, clientid_key, clientid );
	}

	freetbl( client_keys, 0 );

	return;
}
/* Simple little function to define the 3D reference model
used to compute bias components of solution.  It simply
uses the same mechanism used in dbgenloc to access a set of
standard models.
*/
Arr *parse_3D_phase(Pf *pf)
{
    Arr *a;
    Pf *pf3d;
    char *vmodel;

    vmodel = pfget_string(pf,"3Dreference_model");
    if(pfload("GENLOC_MODELS","tables/genloc",vmodel,&pf3d) != 0)
        elog_die(0,"pfload failed on 3Dreference model %s\n",vmodel);
    a = parse_phase_parameter_file(pf3d);
    pffree(pf3d);
    return(a);
}
Esempio n. 10
0
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	Pf 	*pf;
	char	*name;
	char	*mystring;
	mxArray	*input[1];

	if( nlhs > 1 ) 
	{
		antelope_mexUsageMsgTxt ( USAGE );
		return;
	}

	if( nrhs != 2 )
	{
		antelope_mexUsageMsgTxt ( USAGE );
		return;
	}
        else if( ! get_pf( prhs[0], &pf ) )
        {
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }
	else if( ! mtlb_get_string( prhs[1], &name ) )
	{
		antelope_mexUsageMsgTxt ( USAGE );
		return;
	}

	pfconfig( "ask", (void *) matlabPfprompt );

	mystring = pfget_string( pf, name );	
	antelope_mex_clear_register( 1 );

	mxFree( name );

	if( mystring == NULL )
	{
		mexErrMsgTxt( "pfget_num: Couldn't get specified value" );
	}
	else
	{
		input[0] = mxCreateString( mystring );
		mexCallMATLAB( 1, plhs, 1, input, "str2double" );
		mxDestroyArray( input[0] );
	}
}
Esempio n. 11
0
static PyObject *
python_pfget_string( PyObject *self, PyObject *args ) {
	char	*usage = "Usage: _stock._pfget_string( pfname, pfkey )\n";
	char	*pfname;
	char	*pfkey;
	char	*pfvalue;
	char	errmsg[STRSZ];
	Pf	*pf;

	if( ! PyArg_ParseTuple( args, "ss", &pfname, &pfkey ) ) {

		USAGE;

		return NULL;
	}

	if( ( pf = getPf( pfname ) ) == (Pf *) NULL ) {
		
		sprintf( errmsg, "Failure opening parameter file '%s'\n", pfname );

		raise_elog( ELOG_COMPLAIN, errmsg );

		return NULL;
	}

	pfvalue = pfget_string( pf, pfkey );

	if( pfvalue == NULL ) {

		sprintf( errmsg, "Failed to find parameter '%s' in parameter file '%s'\n", pfkey, pfname );

		raise_elog( ELOG_COMPLAIN, errmsg );

		return NULL;
	}

	return Py_BuildValue( "s", pfvalue );
}
Esempio n. 12
0
static Pf *
orbconnections2pf( Pf *pfanalyze )
{
	Pf	*pf;
	Pf	*pfserver;
	Pf	*pfconnections;
	Pf	*pfclients;
	Pf	*pfclient;
	Pf	*pfconnection;
	Tbl	*client_keys;
	int	ikey;
	char	*client_key;
	char	*clientid;
	char	*what;
	char	*perm;
	char	*clientaddress;
	char	*serveraddress;
	char	clientaddress_ipc[STRSZ];
	char	serveraddress_ipc[STRSZ];
	int	serverport;
	double	atime;
	regex_t	preg_findclient;
	char	closeorb[STRSZ];
	char	o2omachine[STRSZ];
	char	farorb[STRSZ];
	int	closeport;
	int	farport;
	char	orbstat_machine_hostname[STRSZ];
	char	orbstat_machine_ipc[STRSZ];
	int	orbstat_machine_ip;
	char	cmdline_fromorb[STRSZ];
	char	cmdline_toorb[STRSZ];
	char	cmdline_fromip[STRSZ];
	char	cmdline_fromipc[STRSZ];
	char	cmdline_toip[STRSZ];
	char	cmdline_toipc[STRSZ];
	char	formal_name[STRSZ];
	int	formal_count = 0;
	int	cmdline_fromport;
	int	cmdline_toport;
	struct in_addr addr;
	
	regcomp( &preg_findclient, "^orb2orb ", 0 );

	pf = pfnew( PFFILE );

	atime = pfget_time( pfanalyze, "client_when" );
	pfput_time( pf, "connections_when", atime );

	my_ip( orbstat_machine_hostname, 
	       orbstat_machine_ipc, 
	       &orbstat_machine_ip );

	if( is_localhost( orbstat_machine_ipc ) ) {
		
		elog_complain( 0, "libpforbstat: orbstat machine is localhost; giving up on connection analysis\n" );
		regfree( &preg_findclient );
		return pf;

	} else {

		pfput_string( pf, "orbstat_machine", orbstat_machine_ipc );
	}

	pfget( pfanalyze, "server", (void **) &pfserver );
	serveraddress = pfget_string( pfserver, "address" );
	serverport = pfget_int( pfserver, "port" );

	if( is_nonroutable( serveraddress ) && 
	    report_nonroutable( serveraddress ) ) {

		elog_complain( 0, "libpforbstat: warning: monitored server %s is nonroutable\n", serveraddress );
	}
	
	if( name2ip( serveraddress, &addr, serveraddress_ipc ) < 0 ) {
		
		elog_complain( 0, "libpforbstat: warning: name translation failed for %s\n", serveraddress );
		strcpy( serveraddress_ipc, serveraddress );
	}

	if( is_localhost( serveraddress ) ) {

		strcpy( closeorb, orbstat_machine_ipc );

	} else {

		strcpy( closeorb, serveraddress_ipc );
	}

	closeport = serverport;

	/* SCAFFOLD: this causes memory problems. Leave untranslated for now:
	pfput_string( pfserver, "address", closeorb ); Record the translated server address */

	pfget( pfanalyze, "clients", (void **) &pfclients );

	client_keys = pfkeys( pfclients );

	pfconnections = pfnew( PFTBL );

	for( ikey = 0; ikey < maxtbl( client_keys ); ikey++ ) {

		client_key = gettbl( client_keys, ikey );
		pfget( pfclients, client_key, (void **) &pfclient );

		what = pfget_string( pfclient, "what" );

		if( ! regexec( &preg_findclient, what, 0, 0, 0 ) ) {

			pfconnection = pfnew( PFARR );

			/* Easy things: */

			pfput_string( pfconnection, "what", what );

			if( ( clientid = pfget_string( pfclient, "clientid") ) != NULL ) {

				pfput_string( pfconnection, "clientid", clientid );
			}
			
			/* Preparatory raw-information acquisition: */

			extract_orb2orb_orbargs( what, 
						 cmdline_fromorb, 
						 cmdline_toorb );

			parse_orbname( cmdline_fromorb, 
				       cmdline_fromip, 
				       &cmdline_fromport );

			if( name2ip( cmdline_fromip, &addr, cmdline_fromipc ) < 0 ) {
		
				elog_complain( 0, 
					"libpforbstat: warning: name translation failed for %s\n", cmdline_fromipc );
				strcpy( cmdline_fromipc, cmdline_fromip );
			}

			parse_orbname( cmdline_toorb, 
				       cmdline_toip, 
				       &cmdline_toport );

			if( name2ip( cmdline_toip, &addr, cmdline_toipc ) < 0 ) {
		
				elog_complain( 0, 
					"libpforbstat: warning: name translation failed for %s\n", cmdline_toipc );
				strcpy( cmdline_toipc, cmdline_toip );
			}

			perm = pfget_string( pfclient, "perm" );

			clientaddress = pfget_string( pfclient, "address" );

			if( name2ip( clientaddress, &addr, clientaddress_ipc ) < 0 ) {
		
				elog_complain( 0, 
					"libpforbstat: warning: name translation failed for %s\n", clientaddress );
				strcpy( clientaddress_ipc, clientaddress );
			}

			/* Analysis */

			if( is_nonroutable( clientaddress ) &&
			    report_nonroutable( clientaddress ) ) { 
				
				elog_complain( 0, "libpforbstat: warning: clientaddress %s is nonroutable\n", 
						clientaddress );
			} 
			
			if( is_localhost( clientaddress ) ) {
			
				strcpy( o2omachine, serveraddress_ipc );

			} else {
				
				strcpy( o2omachine, clientaddress_ipc );
			}

			pfput_string( pfconnection, "o2omachine", o2omachine );

			if( STREQ( perm, "w" ) ) {

				strcpy( farorb, cmdline_fromipc );
				farport = cmdline_fromport;

			} else if( STREQ( perm, "r" ) ) {		

				strcpy( farorb, cmdline_toipc );
				farport = cmdline_toport;

			} else {
				elog_complain( 0, 
						"libpforbstat: unexpected perm '%s' in client info; giving up on client\n", 
						perm );
				pffree( pfconnection );
				continue;
			}

			if(is_localhost(farorb)) {

				strcpy( farorb, o2omachine );
			}

			if( STREQ( perm, "w" ) ) {
			
				pfput_string( pfconnection, "fromaddress", farorb );
				pfput_int( pfconnection, "fromport", farport );

				pfput_string( pfconnection, "toaddress", closeorb );
				pfput_int( pfconnection, "toport", closeport );

				pfput_string( pfconnection, "closeorb", "toaddress" );

			} else {	/* perm == "r" */

				pfput_string( pfconnection, "fromaddress", closeorb );
				pfput_int( pfconnection, "fromport", closeport );

				pfput_string( pfconnection, "toaddress", farorb );
				pfput_int( pfconnection, "toport", farport );

				pfput_string( pfconnection, "closeorb", "fromaddress" );
			} 	

			sprintf( formal_name, "client%03d", ++formal_count );
			pfput( pfconnections, formal_name, pfconnection, PFPF );
		}
	}

	pfput( pf, "connections", pfconnections, PFPF );

	regfree( &preg_findclient );

	return pf;
}
/* This is the main processing function for this program.  

Arguments:
	dbv - db pointer to a complex view of the database to be 
		processed.  That is, it has these properties:
		1.  It is a join of:
			event->origin->assoc->arrival
		2.  subset to single arrival name AND orid==prefor
		3.  sorted by evid/sta

	pf - input parameter space

The main processing loop here keys on the grouping defined in the view
passed as dbgrp.  That is, seismograms for each event group are processed
as a complete gather.  After that, are nested loops to do the multiwavelet
processing as described in Bear and Pavlis (1999a,b).  

Author:  Gary Pavlis
Date:  March 1999+
*/
#define LAG_ERROR -100000 /* Computed lags smaller than this returned
			by compute_optimal_lag are treated as an error
			condition.  Should probably be in an include file*/
void mwap_process(Dbptr dbv,char *phase,  Pf *pf) 
{
	int nevents;  /* number of events=number of groups in dbgrp */
	MWbasis *mw;  /* Multiwavelet basis functions */
	Tbl **decimators;  /* List of loaded decimators used to construct
				multiwavelet transforms in lower bands */
        Tbl **dec_objects;  /*Actual decimation filter objects */
	/* Note:  mw and dec_objects define the multiwavelet transform */
	int nwavelets,nbands;

	/* sets coherence mode used to determine optimal lag */
	int coherence_type;
	
	Arr *stations;  /* This associative array holds MWstation objects
			that contain header like data that is station 
			dependent */
	Arr *badclocks;  /* associative array keyed by sta name holding
			list of time intervals with bad timing */
	char *refsta;  /* Name of reference station */
	double refelev;  /* reference elevation from parameter file */
	int nsta;  /* number of stations */
	int ntest;
	Dbptr db;  /* generic db lookup parameter */
	Dbptr dbgrp;  /* evid group db pointer */
	Dbptr tr;  /* trace database */
	Dbptr dbmps;  /* mwpredslow table */
	Tbl *sortkeys,*sortkeys2;  /* used because different tr routines require
				different sort orders */

	int *pad;  /* vector of length nbands holding computed time padding
			lengths for each band in samples */
	int tpad;  /*time pad actually used  (max of *pad) */
	Time_Window *swin, *nwin;  /* arrays defining time windows
		for signal and noise respectively (relative to arrival)*/
	Time_Window swinall, nwinall;  /*define read time intervals (extracted
			from swin and nwin arrays */
	int *decfac;  /* array of decimation factors needed at times */
	Arr *mwarr;  /* Holds indexed multiwavelet transformed trace objects*/
	/* We keep three copies of arrival time information.  
		arrival0 = original times read from db (never altered)
		arrivals = current working copy
		arrival_new = new estimate obtained from "arrivals" 
	*/
	Arr *arrival0,*arrivals,*arrival_new;
	Arr *static_result;  /* Holds error statistics for static estimates */
	MWSlowness_vector u0,u;
	int i,j;
	double avgamp, amperr;
	int ampndgf;
	int iterations;
	double ucovariance[9];
	char *array_name;
	int accumulate;

	/* These are channel code names used in trace library rotation
	functions rotate_to_standard and trrotate.  */
	char *stdchans[3]={ EW, NS , VERTICAL };
	char *pcchans[3]={"R","T","ZL"};

	Arr *mwsig_arr,*mwnoise_arr;  /* these index pointers to mw transformed
			signal and noise series */
	Arr **sn_ratios;  /* vector of Arr pointers of length nbands indexing
		signal to noise ratio estimates (stored in a structure) for
		every station */
	Spherical_Coordinate polarization0,polarization;
	Spherical_Coordinate polarz={1.0,0.0,0.0};
	Arr *model_times=NULL;
	MWSlowness_vector model_slow;
	double rctm[9];  /*ray coordinate transformation matrix*/
	double timeref;  /* time reference at reference station */
	double time;
	double t0,twin;
	double si;
	double fc,fwin;
	int evid;
	int lag;  /* optimal lab computed by coherence measure */
	double peakcm;  /*Peak value of coherence measure */
	/* For a given gather we set moveout computed moveout time in
	seconds relative to the reference station.  This time includes
	the combined current static estimates.  This is a vector workspace
	that is recycled for every gather.  It is alloced soon as we
	know the number of stations in the site table.  */
	double *moveout;
	MWgather **gathers;
	Particle_Motion_Ellipse *avgpm;
	Particle_Motion_Error *avgerr;
	char *pmtype_to_use;  /* type of particle motion estimate to use
				for polarization */
	Arr *pm_arr,*pmerr_arr;
	Arr *pmarray,*errarray;
	/* This vector defines the "up" direction.  For P waves this
	initialization is correct.  For S it may not be appropriate, but
	this is something to repair later */
	double up[3]={0.0,0.0,1.0};
	int bankid;  /* mutliwavelet group id */
	int band_exit = 0;
	/* name of parameter file produced by GUI to control this program */
	char *guipf;
	int stack_alignment;
	Pf *pfcontrol;
	int loopback;
	int numberpasses=0;
	/* These define the relative time window used for stack and
	particle motion.  s denotes stack, ts0 etc are pm */
	double sts0,ste0;  /* we don't need the equivalent of ts1 and te1 */
	double ts0,ts1,te1,te0;

	/* This is essential or copy_arrival_array can produce garbage */
	arrival0=NULL;
	arrivals = NULL;
	arrival_new=NULL;
	pm_arr = NULL;
	pmerr_arr = NULL;
	pmarray = NULL;
	errarray = NULL;
	si = pfget_double(pf,"sample_interval");
	/* First we need to load the multiwavelet functions and the 
	associated decimators for the transform.  Each of these
	routines will die if serious problems occur and have no
	error returns.  Wavelet functions can be loaded from a parameter
	file or a db.  */
	if(pfget_boolean(pf,"get_wavelets_from_database"))
	{	
		mw = load_multiwavelets_db(dbv,pf,&nwavelets,&bankid);
	}
	else
	{
        	mw = load_multiwavelets_pf(pf,&nwavelets);
		bankid = pfget_int(pf,"bankid");
	}
        decimators = define_decimation(pf,&nbands);
	allot(int *,decfac,nbands);
        dec_objects = build_decimation_objects(decimators,nbands,decfac);

	print_band_info(mw,decfac,pf);

	/* This creates the station objects.  The time extracted here
	is needed to sort out the ontime:endtime key in the site table.
	This is done is a less than bombproof fashion by randomly 
	grabbing the time in the first record view.
	Because of the way the site table works this will always work
	in some fashion.  It will only matter if a station ever moves
	and then we have a bad problem anyway.  */
	dbv.record = 0;
	dbgetv(dbv,0,"time",&time,0);
	stations = build_station_objects(dbv,pf,time);
	refsta = get_refsta(stations);
	array_name = pfget_string(pf,"array_name");
	if(array_name == NULL)
	{
		elog_complain(0,"WARNING:  array_name not defined in parameter file.  Set to default of ARRAY\n");
		array_name = strdup("ARRAY");

	}
	refelev = pfget_double(pf,"reference_elevation");
	/* This loads a definition of bad clocks from an extension
	table called timing.  This comes from libgenloc where it
	is used to handle automatic switching to S-P times. */
	badclocks=newarr(0);
	if(db_badclock_definition(dbv,pf,badclocks))
	{
		elog_notify(0,"Problems in setting up table of stations with timing problems\n");
	}
	/* This function can define stations as always having bad timing
	based on a parameter Tbl list of station names keyed by bad_clock.*/
	pfget_badclocks(pf,badclocks);

	pmtype_to_use = pfget_string(pf,"array_particle_motion_to_use");
	if(pmtype_to_use==NULL) pmtype_to_use=strdup(PMOTION_BEAM);
	/* this used to be a variable, but we no longer have a choice.*/
	coherence_type=USE_COHERENCE;
	
	/* This variable sets if we should reset the arrival estimates
	to starting values for each band.  When true the results accumulate
	from band to band.  That is we keep adding corrections from previous
	band to progressively higher frequency.*/
	accumulate = pfget_boolean(pf,"accumulate_statics");
	/* compute time pad lengths for each band of the mw transforms */
	pad = compute_tpad(dec_objects, mw, stations,pf);

	/* These routine parses the parameter file for noise and
	analysis time window information respectively returning
	arrays of Time_Window structures of length nbands*/
	decfac = get_decimation_factors(dec_objects, pf);
	swin = get_signal_windows(decfac,pad,pf);
	nwin = get_noise_windows(decfac,pad,pf);
	print_window_data(decfac,nbands,swin,nwin,pf);	

	/* This gets time windows for signal and noise needed for
	reading data (i.e. largest time ranges needed) */
	swinall = compute_time_window(swin,decfac,nbands);
	nwinall = compute_time_window(nwin,decfac,nbands);

	guipf = pfget_string(pf,"mwapcontrol");
	/* better safe than sorry */
	if(guipf==NULL)
	{
		elog_die(0,"Missing required parameter mwapcontrol");
	}

	/* We can create these works spaces now for efficiency so 
	we don't have to constantly recreate them dynamically below */
	allot(double *,moveout,cntarr(stations));
	allot(MWgather **,gathers,nwavelets);

	/* This associative array holds indexed pointers to multiwavelet
	transformed traces.  We create it here, but it is repeatedly
	freed and cleared below */
	mwarr = newarr(0);
	/* This one has to be initialized*/
	static_result=newarr(0);

	/* We need this table repeatedly below so we avoid constant 
	lookups */
	dbmps = dblookup(dbv,0,"mwpredslow",0,0);
	if(dbmps.record == dbINVALID)
		elog_die(0,"db lookup failed for mwpredslow table\nMWavelet schema extensions are required\n");

	/* Now we loop through the outer loop event by event.  
	This is structured here by using a dbgroup defined db pointer
	that is passed through the argument list.  The db pointer 
	is incremented and then the bundle is taken apart to crack
	apart each group of traces (the gather).  Note we use
	a defined name to look up the evid grouped table. */
	dbgrp = dblookup(dbv,0,EVIDBDLNAME,0,0);
	if (dbgrp.record == dbINVALID)
		elog_die(0,"Error in dblookup for named evid group table = %s\n",
			EVIDBDLNAME);
        dbquery(dbgrp,dbRECORD_COUNT,&nevents);
        fprintf(stdout,"Processing begins for %d events\n",nevents);

	sortkeys = newtbl(0);
	pushtbl(sortkeys,"sta");
	pushtbl(sortkeys,"chan");
	pushtbl(sortkeys,"time");
	sortkeys2 = newtbl(0);
	pushtbl(sortkeys2,"time");
	pushtbl(sortkeys2,"sta");
	pushtbl(sortkeys2,"chan");

	for(dbgrp.record=0;dbgrp.record<nevents;++dbgrp.record)
	{
		Dbptr db_bundle;
		int evid; 
		int is, ie; 
		int ierr;
		double modaz;

		if(dbgetv(dbgrp,0,"evid", &evid,
                        "bundle", &db_bundle,0) == dbINVALID)
		{
                        elog_complain(1,"dbgetv error for row %d of event group\nAttempting to continue by skipping to next event\n",
                                dbgrp.record);
			continue;
		}

                dbget_range(db_bundle,&is,&ie);

		if(ie-is<3)
		{
			elog_complain(0,"Insufficient data to process for evid %d\nNeed at least three station -- found only %d\n",
				evid,ie-is);
			continue;
		}
		/* We utilize what we call plane wave statics here
		to approximately correct for wavefront curvature.
		We set the record number to is so we can access 
		the correct origin information from the db.  Because
		we used a join allrows of this group should have the
		same origin data.  */
		ierr = set_pwstatics(stations,refsta,phase,db_bundle,pf);
		if(ierr)elog_complain(0,"%d errors computing %d plane wave statics for evid %d\n",
			ierr,ie-is,evid);

		/* This routine loads an Arr of arrival times from 
		the input db to be used to compute initial slowness
		vector and initial statics.  */
		arrival0 = get_arrivals(db_bundle);

		/* We edit the MWstation array to flag stations
		with bad timing in this function */
		MWcheck_timing(arrival0,stations,badclocks);

		/* Save these times */
		copy_arrival_array(arrival0,&arrivals);


		/* Initialize slowness vector to 0 and then estimate
		it from data using current arrival times */
		u0.ux = 0.0;  u0.uy = 0.0;  u0.refsta = refsta;
		timeref = compute_time_reference(stations,arrivals,refsta,u0);
		/* for the first pass we use weights defined for the 
		lowest frequency band.  This is done because it asssumed
		that if frequency dependent weighting is actually used
		the lowest band would have the widest effective aperture. */
		ierr = estimate_slowness_vector(u0,arrivals,stations,
			refsta, refelev, timeref, phase, nbands-1,&u);
		/* It is necessary to reset the time reference to handle 
		the case correctly when the reference station does not
		actually record this event.  This function uses a moveout
		correction that depends upon the slowness vector, so it can
		float about a bit in that situation */
		if(ierr>0)
			elog_notify(0,"%d nonfatal errors in estimate_slowness_vetor for evid %d\n",ierr,evid);
		else if(ierr < 0)
		{
			elog_complain(0,"estimate_slowness_vector failed for initial slowness estimate for evid %d\nData for this event will be skipped\n",
				evid);
			continue;
		}
		/* This routine returns the slowness vector and an arr of 
		estimated arrival times.  The slowness vector is saved
		in the mwpredslow table immediately below.  Arrival times
		are used to compute residuals later. */
		ierr = MWget_model_tt_slow(stations, refsta, phase,
			db_bundle, pf, &model_times, &model_slow);

		timeref = compute_time_reference(stations,arrivals,refsta,u);
		polarization0=estimate_initial_polarization(model_slow,stations,
			refsta,phase);

		modaz = atan2(model_slow.ux,model_slow.uy);

		if(dbaddv(dbmps,0,"sta",array_name,
			"evid",evid,
			"phase",phase,
			"time",timeref,
			"slo",hypot(model_slow.ux,model_slow.uy),
			"azimuth",deg(modaz),
			"majoraz",deg(polarization0.phi),
			"majorema",deg(polarization0.theta),
			"vmodel",pfget_string(pf,"TTmodel"),0) == dbINVALID)
		{
			elog_complain(0,"dbaddv error for evid %d on mwpredslow table\n",
				evid);
		}

		/* This function reads in the trace data for this event
		using time windows defined above */
		tr = mwap_readdata(dbgrp,arrivals,swinall, nwinall);
		if(tr.record == dbINVALID)
		{
			elog_complain(0,"Serious problems reading data for evid %d -- no data processed for this event\n",evid);
			continue;
		}
		tr = dblookup(tr,0,"trace",0,0);
		/* We first glue together any possible recording break
		generated entries -- common with continuous data.
		This also seems to require a resort because of the
		way data was read in.   */
/*
		tr = dbsort(tr,sortkeys,0,0);
*/
		trsplice(tr,0.1,0,0);

		/* We run trsplit to break up waveform segments at real gaps.
		I'm not sure later code will work correctly if it isn't an 
		all or nothing situations (e.g. gap in Z component, but 
		not in N or E).  In any case, we have to deal with 
		potential multiple segments later.  */
		trsplit(tr,0,0);

		trapply_calib(tr);
		trdemean_seg(tr);
		/* Now we have reorder the traces or this will not work
		correctly*/
		tr = dbsort(tr,sortkeys2,0,0);
		ierr = rotate_to_standard(tr,stdchans);
		if(ierr<0)
		{
			elog_complain(0,"rotate_to_standard failed processing evid %d -- no data processed for this event\n",
				evid);
			continue;
		}
		if(ierr>0)elog_complain(0,"rotate_to_standard failed for %d stations\n",
				ierr);

		/* This releases the space held by the raw data traces
		keeping only the rotate_to_standard outputs */
		free_noncardinal_traces(tr);

		elog_log(0,"Computing multiwavelet transform:  be\
 patient as this can take a while with many channels\n");
		/* This function computes the multiwavelet transform
		of all traces currently in tr for signals around arrival*/
		mwsig_arr = tr_mwtransform(tr,arrivals,swin,decfac,dec_objects,
				nbands,mw,nwavelets);

		/* We repeat the same thing for noise windows */
		mwnoise_arr = tr_mwtransform(tr,arrivals,nwin,decfac,
				dec_objects,nbands,mw,nwavelets);
		/* Now compute signal to noise ratio figures for all
		nbands storing the structures that define the results
		in an Arr keyed by station. Note this is actually 
		a vector of Arr pointers of length nbands.  Further
		note the following function creates this complicated
		object, and it must be freed after each event is 
		processed. */
		sn_ratios=compute_signal_to_noise(mwsig_arr,mwnoise_arr,
					stations,arrivals,swin,nwin,
					nbands,nwavelets);

		/* Now we get to the heart of this program.  This is
		the outer loop over frequency.  Note the loop goes
		backward because the lowest frequencies are the final
		row of the mw transform matrices of pointers */

		copy_MWslowness_vector(&u,&u0);
		if(numberpasses>0)
		{
			fprintf(MWpout,"NEWEVENT %d\n",evid);
		}
		for(i=nbands-1;i>=0;--i)
		{
			if(!accumulate)
				copy_arrival_array(arrival0,&arrivals);

			copy_arrival_array(arrivals,&arrival_new);
			fc = (mw[i].f0)/(2.0*si*decfac[i]);
			fwin = (mw[i].fw)/(2.0*si*decfac[i]);

			fprintf(stdout,"Processing begins on band %d with center frequency %lf\nWait for -Hit Accept button when ready- prompt\n",
				i,fc);

			/* This builds the basic working gathers for
			each wavelet and builds a shortcut of pointers
			to MWtraces that are related */
			for(j=0;j<nwavelets;++j)
			{
				gathers[j] = build_MWgather(i,j,
						mwsig_arr,stations,
						sn_ratios[i],pf);
			}
			fprintf(stdout,"Working gather for this band has %d stations\n",
				gathers[0]->nsta);
			/* Testing band 0 should be sufficient.  The
			signal-to-noise is averaged overall wavelets so
			the same stations should be deleted in all
			wavelet of the group */
			if(gathers[0]->nsta < 3)
			{
				elog_notify(0,"Insufficient data in band %d to passed signal-to-noise cutoff defined for this band for evid %d\nSkipping to next frequency band\n",
					i,evid);
				continue;
			}
			/* This may not be necessary, but it is certainly 
			important for debugging.  We check that all
			the gathers in the group have the same length.  
			If they aren't, we are in trouble because we use
			a single vector to hold moveout information */
			check_gather_consistency(gathers,nwavelets);

			/* Now we compute the moveout information assuming
			stations are in the same order in the gather for
			each wavelet */
			if(compute_total_moveout(*gathers,stations,refsta,
				u,refelev,phase,moveout))
			{
				elog_die(0,"Cannot find reference station to compute moveout:  Should not happen unless program overwrites itself\n");
			}

			if(numberpasses>0)
			{
				fprintf(MWpout,"NEWBAND %d\n",i);
				fflush(MWpout);
			}
			else
			{
				char ctmp[40];
				fprintf(stdout,"Starting processing of first event\nSelect and options and press the Start button when ready\n");
				fprintf(MWpout,"STARTUP %d %d\n", 
					evid,i);
				fflush(MWpout);
				fgets(ctmp,40,MWpin);
			}
			++numberpasses;

			/* This is placed here to allow changing the
			alignment options on the fly.  Choice may
			depend on data. */
			pfread(guipf,&pfcontrol);
			stack_alignment=get_stack_align_mode(pfcontrol);
			pffree(pfcontrol);
			
			/* kind of a odd loop construct here made 
			necessary by differences in stackalignment
			options.  If we align with theoretical value
			or use the vertical we do not need to repeat
			this loop and we fall out the bottom.  If we
			use the pm estimate, however, we have to 
			realign the stack rotated to the new major
			ellipse estimate.  In that case we have to
			repeat the whole procedure.*/
			loopback=2;
			do {
				MWstack *stack;
				switch(stack_alignment)
				{
				case PMTHEORY:
					copy_polarization(&polarization0,&polarization);
					loopback=0;
					break;
				case PMZ:
					copy_polarization(&polarz,&polarization);
					loopback=0;
					break;
				case PMESTIMATE:
				default:
				/* This uses theoretical version for the
				first pass then the estimate on the 
				second */
					if(loopback==2)
					  copy_polarization(&polarization0,
						&polarization);
				}
				stack=MWcompute_arrival_times(gathers,
    					   nwavelets,timeref,moveout,
    					   polarization,swin[i],
					   sn_ratios[i],guipf,
    					   &arrival_new,&static_result,
                                            &avgamp, &amperr, &ampndgf);
				if(stack==NULL)
				{
					/* I use a flag to avoid an
					evil goto here */
					band_exit = 1;
					/* This is strange but necessary
					to stop string of bogus errors from
					copy_arrival_array function when
					this loops back */
					if(arrival_new!=NULL)
						freearr(arrival_new,free);
					arrival_new = NULL;

					break;
				}
					
					
				/* Note this routine updates residual
				static values to new values relative to
				the new slowness vector estimate */
	                	ierr = estimate_slowness_vector(u0,
					arrival_new,stations,
                        		refsta, refelev, timeref, 
					phase, i, &u);
				/* We need to recompute the moveout to 
				now be relative to the new slowness vector
				estimate.  We then use this for particle 
				motion analysis which can change the 
				polarization vector */
				compute_total_moveout(*gathers,stations,refsta,
				u,refelev,phase,moveout);
				/* This segment converts particle motions
				for 3-c arrays.  */
				if(gathers[0]->ncomponents==3)
				{
					MWstack *spm; 
					Time_Window pmtwindow;
					double *timeweight;
					
					/* We extract the time window
					from a control parameter file which
					is assumed to be created by a GUI
					with tcl/tk */
					pfread(guipf,&pfcontrol);
					ts0=pfget_double(pfcontrol,"pm_ts0");
					ts1=pfget_double(pfcontrol,"pm_ts1");
					te1=pfget_double(pfcontrol,"pm_te1");
					te0=pfget_double(pfcontrol,"pm_te0");
					/* we need these below, not here */
					sts0=pfget_double(pfcontrol,"stack_ts0");
					ste0=pfget_double(pfcontrol,"stack_te0");
					twin = ste0-sts0;
					pffree(pfcontrol);
					pmtwindow.tstart = nint(ts0/(stack->dt));
					pmtwindow.tend = nint(te0/(stack->dt));

					spm = MWextract_stack_window(stack,
						&pmtwindow);
					if(spm==NULL)
						elog_die(0,
						  "Fatal error in MWextract_stack_window\n");
					/* Sets time weight function for 
					a trapezoidal window */
					timeweight=MWstack_set_trapezoidal_window(spm->tstart,
						spm->dt,spm->nt,
						ts0,ts1,te1,te0);
					dcopy(spm->nt,timeweight,1,spm->timeweight,1);
					free(timeweight);
					MWstack_apply_timeweight(spm);

					if(MWcompute_array_particle_motion(gathers,
					  nwavelets,spm,timeref,moveout,
					  up,&pmarray,&errarray, &pm_arr,&pmerr_arr) )
					{
					  elog_complain(0,"Errors in MWcompute_array_particle_motion\n");
					}
					avgpm = (Particle_Motion_Ellipse *)getarr(pmarray,pmtype_to_use);
					avgerr = (Particle_Motion_Error *)getarr(pmarray,pmtype_to_use);

					polarization
					  =unit_vector_to_spherical(avgpm->major);
					destroy_MWstack(spm);
				}
				peakcm=stack->coherence[idamax(
					stack->nt,
					stack->coherence,1)];
				copy_arrival_array(arrival_new,&arrivals);
				freearr(arrival_new,free);
				arrival_new = NULL;
				destroy_MWstack(stack);
				if(stack_alignment==PMESTIMATE)
						--loopback;
			}while(loopback>0);
			if(band_exit)
			{
				band_exit = 0;
				continue;
			}

			/* This routine computes the covariance of
			the estimated slowness vector */
			if(compute_slowness_covariance(stations,static_result,
				ucovariance) )
				elog_complain(0,"Problems computing slowness vector covariance estimate for evid %d and band %d\n",
					evid, i);
			/* routines below save a time window.  We compute
			the lag corrected start time at the reference station
			here as t0 to simplify this in functions that
			need this.*/
			t0 = timeref + sts0;
			/* This series of functions save results in a set
			of css3.0 extension tables.  */

			/* ampndgf+1 here is a cheap solution to the
			number of stations used in a solution.  This 
			confusion is necessary because autoediting reduces
			the data set.  Poor planning caused me to not
			force this to be saved explicitly, but ampndgf is
			an exact surrogate.  The +1 is needed because the
			calculation uses number_used - 1 since the average
			amplitude is extracted as a free parameter.
			*/
			if(MWdb_save_slowness_vector(phase,&u,t0,twin,
				array_name,evid,bankid,fc,fwin,
				ucovariance,ampndgf+1,3,
				coherence_type,peakcm,dbv))
					dbsave_error("mwslow",evid,i);
			if(MWdb_save_avgamp(array_name, evid, bankid, phase,
				fc, t0, twin, avgamp,amperr,ampndgf,
				dbv) )
					dbsave_error("mwavgamp",evid,i);
			if(MWdb_save_statics(evid, bankid, phase, fc, t0,
				twin,refelev,*gathers,moveout,static_result,
				stations,sn_ratios[i],
				arrivals, model_times,dbv))
					dbsave_error("mwtstatic:mwastatic:mwsnr",evid,i);
			t0=timeref+ts0;
			twin = te0-ts0;
			if(MWdb_save_pm(array_name,evid,bankid,phase,fc,t0,
				twin,*gathers,moveout,pm_arr,pmerr_arr,
				avgpm,avgerr,dbv)  )
					dbsave_error("mwpm",evid,i);
			/* We have to release the memory held in these
			associative arrays.  In the earlier loop the 
			function that creates them always clears them
			before continuing when they are not null.  
			The explicit NULL set after the free is done
			to make sure in looping back the particle
			motion routine clears these correctly.  */
			freearr(pm_arr,free);
			pm_arr = NULL;
			freearr(pmerr_arr,free);
			pmerr_arr = NULL;
			/* same for static arr */
			freearr(static_result,free);
			static_result = NULL;
		}
		/*release main work spaces with this series of complicated free routines.
		Here is where you really wish C had garbage collection */
		free_sn_ratios_arr(sn_ratios,nbands);
		free_MWtransform_arr(mwsig_arr,nbands,nwavelets);
		free_MWtransform_arr(mwnoise_arr,nbands,nwavelets);
		trdestroy(&tr);
		freearr(arrival0,free);
		freearr(arrivals,free);
		/* This may not be necessary, but better safe than sorry */
		arrivals = NULL;   arrival0 = NULL;   arrival_new = NULL;
	}
	free(moveout);
	free(swin);
	free(nwin);
	free(refsta);
}
Esempio n. 14
0
static void
parse_orbname( char *orbname, char *orb_address, int *orb_port )
{
	char	*split_orbname;
	Tbl	*orbname_parts;
	char	orbname_port[STRSZ];
	Hook	*hook = 0;
	static Pf *pfnames = 0;
	int	len = 0;
		
	if( STREQ( orbname, ":" ) ) {
		
		strcpy( orb_address, "127.0.0.1" );
		strcpy( orbname_port, "" );

	} else {
		
		split_orbname = strdup( orbname );
		orbname_parts = split( split_orbname, ':' );

		if( maxtbl( orbname_parts ) == 1 && orbname[0] == ':' ) {

			strcpy( orb_address, "127.0.0.1" );
			strcpy( orbname_port, poptbl( orbname_parts ) );

		} else if( maxtbl( orbname_parts ) == 1 ) {

			strcpy( orb_address, shifttbl( orbname_parts ) );
			strcpy( orbname_port, "" );

		} else if( maxtbl( orbname_parts ) == 2 ) {

			strcpy( orb_address, shifttbl( orbname_parts ) );
			strcpy( orbname_port, poptbl( orbname_parts ) );

		} else {

			elog_complain( 0, "pforbstat: unexpected error translating orb2orb argument <%s>\n",
				  orbname );
			strcpy( orb_address, "" );
			strcpy( orbname_port, "" );
		}

		free( split_orbname );
		freetbl( orbname_parts, 0 );
	}

	if( ( len = strlen( orbname_port ) ) > 0 ) {

		if( orbname_port[len-1] == '@' ) {
			
			orbname_port[len-1] = '\0';
		}
	}

	if( STREQ( orbname_port, "" ) ) {
		
		*orb_port = ORB_TCP_PORT;

	} else if( strmatches( orbname_port, "^[0-9]+$", &hook ) ) {
		
		*orb_port = atoi( orbname_port );

	} else {

		if( pfnames == 0 ) {

			pfread( "orbserver_names", &pfnames );
		}

		if( pfget_string( pfnames, orbname_port ) == 0 ) {

			elog_complain( 0, "pforbstat: couldn't translate orb port \":%s\"\n", orbname_port );

			*orb_port = 0;

		} else {
		
			*orb_port = pfget_int( pfnames, orbname_port );
		}
	}

	return;
}
Esempio n. 15
0
static Pf *
orbdatabases2pf( Pf *pfanalyze ) 
{
	Pf	*pf;
	Pf	*pfdatabases;
	Pf	*pfdatabase;
	Pf	*pfclients;
	Pf	*pfclient;
	double	atime;
	Tbl	*client_keys;
	int	ikey;
	char	*client_key;
	char	*what;
	char	*serverhost;
	char	*clientid;
	char	*clientaddress;
	char	*serveraddress;
	char	*serverport;
	char	dbprogram[STRSZ];
	char	dbpath[STRSZ];
	char	dir[STRSZ];
	char	dfile[STRSZ];
	char	formal_name[STRSZ];
	int	formal_count = 0;
	char	*delim = ":";
	char	*hostdir;
	char	*serverhostcopy;
	char	*abspath;

	pf = pfnew( PFFILE );

	pfdatabases = pfnew( PFTBL );

	atime = pfget_time( pfanalyze, "client_when" );
	pfput_time( pf, "databases_when", atime );

	pfeval( pfanalyze, "server{address}", &serveraddress );
	pfeval( pfanalyze, "server{port}", &serverport );
	pfeval( pfanalyze, "server{host}", &serverhost );

	serverhostcopy = strdup( serverhost );
	strtok_r( serverhostcopy, delim, &hostdir );

	pfget( pfanalyze, "clients", (void **) &pfclients );

	client_keys = pfkeys( pfclients );

	for( ikey = 0; ikey < maxtbl( client_keys ); ikey++ ) {

		client_key = gettbl( client_keys, ikey );
		pfget( pfclients, client_key, (void **) &pfclient );

		what = pfget_string( pfclient, "what" );
		clientaddress = pfget_string( pfclient, "address" );
		clientid = pfget_string( pfclient, "clientid" );

		if( is_dbprogram( what, dbprogram, dbpath ) ) {

			pfdatabase = pfnew( PFARR );

			pfput_string( pfdatabase, "clientid", clientid );
			pfput_string( pfdatabase, "serveraddress", serveraddress );
			pfput_string( pfdatabase, "serverport", serverport );
			pfput_string( pfdatabase, "dbprogram", dbprogram );

			if( is_localhost( clientaddress ) ) {

				pfput_string( pfdatabase, "dbmachine", serveraddress );

				abspath = concatpaths( hostdir, dbpath, 0 );
				parsepath( abspath, dir, dfile, 0 );
				free( abspath );

			} else {

				pfput_string( pfdatabase, "dbmachine", clientaddress );

				abspath = concatpaths( "", dbpath, 0 );
				parsepath( abspath, dir, dfile, 0 );
				free( abspath );
			}

			pfput_string( pfdatabase, "dir", dir );
			pfput_string( pfdatabase, "dfile", dfile );

			sprintf( formal_name, "client%03d", ++formal_count );
			pfput( pfdatabases, formal_name, pfdatabase, PFPF );
		}
	}

	free( serverhostcopy );

	pfput( pf, "databases", pfdatabases, PFPF );

	return pf;
}
Esempio n. 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;
}
Location_options parse_options_pf (Pf *pf)
{
	Location_options o;
	char *s;  /* string buffer */
	int i;
	int recenter=0;  /* recenter flag */

	o = load_default_options();
	s = pfget_string(pf,"arrival_residual_weight_method");
	/* Note this implicitly accepts the default if the keyword is missing */
	if(s != NULL)
	{
		if(!strcasecmp(s,"bisquare")) o.atime_residual_weight = BISQUARE;
		if(!strcasecmp(s,"thomson")) o.atime_residual_weight = THOMSON;
		if(!strcasecmp(s,"huber")) o.atime_residual_weight = HUBER;
		if(!strcasecmp(s,"none")) o.atime_residual_weight = NONE;
	}
	/* Do the same for slowness */
	s = pfget_string(pf,"slowness_residual_weight_method");
	if(s != NULL)
	{
		if(!strcasecmp(s,"bisquare")) o.slow_residual_weight = BISQUARE;
		if(!strcasecmp(s,"thomson")) o.slow_residual_weight = THOMSON;
		if(!strcasecmp(s,"huber")) o.slow_residual_weight = HUBER;
		if(!strcasecmp(s,"none")) o.slow_residual_weight = NONE;
	}

	o.atime_distance_weight = pfget_boolean_wdef(pf,
		"time_distance_weighting",o.atime_distance_weight);
	o.slow_distance_weight = pfget_boolean_wdef(pf,
			"slowness_distance_weighting",o.slow_distance_weight);
	o.slowness_weight_scale_factor = (float) pfget_double_wdef(pf,
				"slowness_weight_scale_factor",
				o.slowness_weight_scale_factor);
	o.min_error_scale = (float) pfget_double_wdef(pf,
				"min_error_scale",o.min_error_scale);
	o.max_error_scale = (float) pfget_double_wdef(pf,
					"max_error_scale",o.max_error_scale);
	for(i=0;i<4;++i) o.fix[i] = 0;
	if(pfget_boolean_wdef(pf,"fix_longitude",0)) o.fix[0] = 1;
	if(pfget_boolean_wdef(pf,"fix_latitude",0)) o.fix[1] = 1;
	if(pfget_boolean_wdef(pf,"fix_depth",0)) o.fix[2] = 1;
	if(pfget_boolean_wdef(pf,"fix_origin_time",0)) o.fix[3] = 1;
	if(pfget_boolean_wdef(pf,"recenter",0)) recenter = 1;
	s = pfget_string(pf,"generalized_inverse");
	if(s != NULL)
	{
	    if(!strcasecmp(s,"marquardt"))
	    {
		o.min_relative_damp = (float) pfget_double_wdef(pf,
			"min_relative_damp",o.min_relative_damp);
		if(o.min_relative_damp < FLT_EPSILON)
		{
			elog_log(0,"Warning:  minimum relative damping must be at least single precision epsilon.\nParameter file wanted %f\nReset to %f\n",
				o.min_relative_damp, FLT_EPSILON);
			o.min_relative_damp = FLT_EPSILON;
		}
		o.max_relative_damp = (float) pfget_double_wdef(pf,
				"max_relative_damp",o.max_relative_damp);
		o.damp_adjust_factor = (float) pfget_double_wdef(pf,
			"damp_adjust_factor",o.damp_adjust_factor);
		if(recenter)
			o.generalized_inverse = DAMPED_RECENTERED;
		else
			o.generalized_inverse = DAMPED_INVERSE;
	    }
	    if(!strcasecmp(s,"pseudoinverse"))
	    {
		o.sv_relative_cutoff = (float) pfget_double_wdef(pf,
				"singular_value_cutoff",o.sv_relative_cutoff);
		if(recenter)
			o.generalized_inverse = PSEUDO_RECENTERED;
		else
			o.generalized_inverse = PSEUDOINVERSE;
	    }
	}
	o.depth_ceiling = (float) pfget_double_wdef(pf,
				"depth_ceiling",o.depth_ceiling);
	o.depth_floor = (float) pfget_double_wdef(pf,
			"depth_floor",o.depth_floor);
	o.step_length_scale_factor = (float) pfget_double_wdef(pf,
			"step_length_scale_factor",o.step_length_scale_factor);
	o.min_step_length_scale = (float) pfget_double_wdef(pf,
			"min_step_length_scale",o.min_step_length_scale);
	if(o.step_length_scale_factor >= 1.0) 
	{
		elog_log(0,"Step length damping factors reset\nScale factors must be less than 1.0\nResetting to default of %f\n",DEFAULT_SLSF);
		o.step_length_scale_factor = DEFAULT_SLSF;
		if(o.min_step_length_scale >= o.step_length_scale_factor)
		{
			
			o.min_step_length_scale = (float)pow(DEFAULT_SLSF,SLSF_POW_MIN);
			elog_log(0,"Min step length scale also reset to %f\n",
					o.min_step_length_scale);
		}
	}
	if(o.min_step_length_scale >= o.step_length_scale_factor)
	{
		o.min_step_length_scale = (float)pow(o.step_length_scale_factor,
								SLSF_POW_MIN);
		elog_log(0,"Min step length scale is not consistent with step length scale factor parameter\nReset to %f\n",
			o.min_step_length_scale);
	}
	o.max_hypo_adjustments = pfget_int_wdef(pf,
		"maximum_hypocenter_adjustments",o.max_hypo_adjustments);
	o.dx_convergence = (float) pfget_double_wdef(pf,
		"deltax_convergence_size",o.dx_convergence);
	o.relative_rms_convergence = (float) pfget_double_wdef(pf,
		"relative_rms_convergence_value",o.relative_rms_convergence);
	return(o);
}
Esempio n. 18
0
int main(int argc, char **argv)
{
	Dbptr db;
	char *dbname;
	Pf *pf;
	char *progname="Xphase2db";
	char line[1024];
	int year,jday,hour,min;
	double sec;
	double twin,deltim;
	int other1,other2,pol;
	char fname[512];
	char tstring[100];
	double time;
	char *seperators;  /* holds seperators passed to strtok*/
	int ista,ichan;  /* token positions of station and channel 
			strings */
	char *phase;
	char *fm,*up="uc",*down="dr";
	char *token;
	char *sta,*chan;
	int i,j;


	if(argc < 2) die(0,"usage:  %s dbout [-phase x]\n",progname);
	if(argc == 4)
	{
		if(!strcmp(argv[2],"-phase"))
			die(0,"usage:  %s dbout [-phase x]\n",progname);
		phase = argv[3];
	}
	else
		phase = strdup("P");
	dbname = argv[1];
	if(pfread(progname,&pf))
		die(0,"Failure reading parameter file %s.pf\n",
				progname);
	if(dbopen(dbname,"r+",&db) == dbINVALID)
		die(0,"dbopen failure for database %s\n",dbname);
	db = dblookup(db,0,"arrival",0,0);
	seperators = pfget_string(pf,"seperators");
	if(seperators == NULL) die(0,"required parameter separators no in parameter file\n");
	ista = pfget_int(pf,"station_token_number");
	ichan = pfget_int(pf,"chan_token_number");

	while( fgets(line,1024,stdin) != NULL)
	{
		sscanf(line,"%d%d%d%d%lf%d%lf%lf%d%d%s",
			&year,&jday,&hour,&min,
			&sec,&other1,&twin,&deltim,&other2,&pol,fname);

		if(pol<0)
			fm = down;
		else
			fm = up;
		sprintf(tstring,"%4d%3d:%2d:%2d:%7.4lf",year,jday,hour,min,sec);
		/* There is a way to avoid this in formats for sprintf, but
		I'll be damned if I can find it.  Easier to do by brute force*/
		for(j=0;j<strlen(tstring);++j) 
			if(tstring[j]==' ')tstring[j]='0';
		time = str2epoch(tstring);
		token = strtok(fname,seperators);
		i=1;
		while(token != NULL)
		{
			if(i == ista)  sta = token;
			if(i == ichan) chan = token;
			++i;
			token = strtok(NULL,seperators);
		}
		dbaddv(db,0,
			"sta",sta,
			"chan",chan,
			"time",time,
			"deltim",deltim,
			"iphase",phase,
			"fm",fm,
			"auth","Xphase",
			0);
	}
}
Esempio n. 19
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);
}
int
delegate_to_perl( Dbptr db, Pf *delegate_pf )
{
	char	scriptfile[FILENAME_MAX];
	char	fifofile[FILENAME_MAX];
	char	pffile[FILENAME_MAX];
	char	*commands;
	char	*mypath;
	char	*cwd;
	FILE	*fp;
	Tbl	*keys;
	char	*key;
	Pf	*pfpart;
	pid_t	pid;
	int	status;
	int	i;

	if( ( mypath = datafile( "PATH", "perl" ) ) == 0 ) {

		complain( 0, "Couldn't find perl on path.\n" );

		return -1;

	} else if( access( mypath, R_OK|X_OK ) ) {

		complain( 0, "Couldn't find perl on path.\n" );
		
		return -1;
	}

	if( ( commands = pfget_string( delegate_pf, "commands" ) ) == NULL ) {

		complain( 0, "No commands &Literal in parameter file\n" );

		return -1;
	}

	cwd = getcwd( NULL, FILENAME_MAX );

	sprintf( scriptfile, "/tmp/dbgme_script_%d_%d.pl", getuid(), getpid() );
	sprintf( fifofile, "/tmp/dbgme_fifo_%d_%d.fifoview", getuid(), getpid() );
	sprintf( pffile, "/tmp/dbgme_pf_%d_%d.pf", getuid(), getpid() );

	mkfifo( fifofile, 0775 );

	fp = fopen( pffile, "w" ); 
	keys = pfkeys( delegate_pf );
	for( i = 0; i < maxtbl( keys ); i++ ) {

		key = gettbl( keys, i );

		if( ! strcmp( key, "commands" ) ) {

			continue;
		}

		pfresolve( delegate_pf, key, 0, &pfpart );

		fprintf( fp, "%s ", key );
		pfout( fp, pfpart ); 
	}
	fclose( fp ); 
	
	fp = fopen( scriptfile, "w" );
	fprintf( fp, "@db = dbopen_table( \"%s\", \"r\" );\n", fifofile );
	fprintf( fp, "$pf = \"%s\";\n", pffile );
	fprintf( fp, "%s\n", commands );
	fprintf( fp, "exit\n" );
	fclose( fp );

	if( ( pid = fork() ) == 0 ) {

		if( Verbose ) {

			fprintf( stderr, "Running Perl delegate\n" );

		} else {

			fflush( stderr );
			fclose( stdout );
		}

		execlp( "perl", "perl", "-e", scriptfile, NULL );

	} else {

		fp = fopen( fifofile, "w" );
		dbwrite_view( db, fp );
		fclose( fp );

		wait( &status );
	}

	if( Verbose ) {

		fprintf( stderr, "Perl exit status is %d\n", status );
	}

	free( cwd );

	unlink( scriptfile );
	unlink( fifofile );
	unlink( pffile );

	if( status != 0 ) {

		return -1;

	} else {

		return 0;
	}
}
Esempio n. 21
0
int main(int argc, char **argv)
{
	SEGYBinaryFileHeader reel;
	SEGYTraceHeader *header;
	char *dbin;
	char *outfile;
	FILE *fp;
	Pf *pf;
	Arr *channels;  /* channel order list */
	Arr *table_list;  /* array of valid tables */
	int nchan;
	char *stest;

	float **traces;
	char text_file_header[SEGY_TEXT_HEADER_SIZE];
	Dbptr db, trdb, dbj;
	Dbptr trdbss;
	int nsamp0;
	double time0, endtime0, samprate0;
	long int nsamp;
	double samprate;
	int i,j;
	char stime[30],etime[30];
	char s[128];
	double tlength;
	double phi, theta;
	char *newchan_standard[3]={"X1","X2","X3"};
	char *trsubset="chan=~/X./";
	char *newchan[3]={"R","T","Z"};
	Tbl *sortkeys=newtbl(0);
	char sta[10],chan[10];
	double lat, lon, elev, dnorth, deast, edepth;
	char segtype;
	char refsta[10];
	int total_traces=0;
	char *time_str;
	long int evid,shotid=1;
	int rotate=0;
	long int ntraces;
        int ichan;
	int map_to_cdp;  /* logical switch to output data like cdp stacked data */
	char *fmt="%Y %j %H %M %S %s";
	char *pfname;
	int Verbose=0;
	/* New features added 2009 */
	/* this is a boolean.  If true (nonzero) it is assumed stdin will
	contain four numbers:  time,lat, lon, elev.  If false, only the
	time field is read and remainder of any input on each line is dropped.*/
	int input_source_coordinates;
	/* scale factor for source coordinates.  Needed because segy uses
	an int to store source coordinates.  Sensible choices are
	3600 for arc seconds and 10000 for a pseudodecimal. Note this
	parameter is ignored unless input_source_coordinates is true.*/
	int coordScale;
	/* If true use passcal 32 bit extension num_samps as record length.
	SEGY standard uses a 16 bit entry that easily overflows with large
	shots at long offset.  In this ase assume the 16 bit quantity is
	meaningless. */
	int use_32bit_nsamp;
	/* This is switched on by argument switch.  When set to a nonzero
	(default) the reel headers are written.  When 0 `
	the reel headers will not be written -- used by seismic unix
	and passcal*/
	int write_reel_headers=1;

	/* SEG-Y version to output. Default is original 1975 spec (rev 0) */
	int16_t segy_format = SEGY_FORMAT_REV_0;

	/* dbsubset query string */
	char *substr=NULL;

	/* text_header_description is a buffer holding a user-supplied description
	 * to be placed in the 3200-byte text header block. It is controlled by
	 * the parameter file value text_header_description or by the -d command
	 * line option, with the latter taking precedence */
	char* text_header_description=NULL;

	if(argc < 3) usage();
	dbin = argv[1];
	outfile = argv[2];
	pfname = NULL;
	for(i=3;i<argc;++i)
	{
		if(!strcmp(argv[i],"-pf"))
		{
			++i;
			pfname = argv[i];
		}
		else if(!strcmp(argv[i],"-SU"))
		{
			write_reel_headers=0;
		}
		else if(!strcmp(argv[i],"-v"))
		{
			Verbose=1;
		}
		else if(!strcmp(argv[i],"-d"))
		{
			++i;
			text_header_description = strdup(argv[i]);
		}
		else if(!strcmp(argv[i],"-ss"))
		{
			++i;
			substr=argv[i];
		}
		else if(!strcmp(argv[i],"-V"))
		{
			++i;
			if     (!strcmp(argv[i],"0")) {segy_format = SEGY_FORMAT_REV_0;}
			else if(!strcmp(argv[i],"1")) {segy_format = SEGY_FORMAT_REV_1_0;}
			else if(!strcmp(argv[i],"SU"))
			{
				segy_format = SEGY_FORMAT_SU;
				write_reel_headers=0;
			}
			else
			{
				elog_complain(0, "SEG-Y Version must be either 1 or 0");
				usage();
			}
		}
		else
		{
			usage();
		}
	}
	/* Command-line parameter sanity checking */
	if (write_reel_headers==0 && segy_format != SEGY_FORMAT_SU){
		complain(0, "The SU option cannot be used with the -V option");
		usage();
	}
	if(pfname == NULL) pfname = strdup("db2segy");

	elog_init(argc, argv);

	if(pfread(pfname,&pf)) {
		elog_die(0,"pfread error for pf file %s.pf\n",argv[0]);
	}

	/* Read the text_header_description if we weren't passed the -d option */
	if (!text_header_description) {
		text_header_description=pfget_string(pf, "text_header_description");
	}

	/* rotation parameters */
	rotate=pfget_boolean(pf,"rotate");
	if(rotate)
	{
		phi = pfget_double(pf,"phi");
		theta = pfget_double(pf,"theta");
	}
	/* This function creates the channel order list keyed by
	station channel names */
	channels = build_stachan_list(pf,&nchan,Verbose);

	map_to_cdp = pfget_boolean(pf,"map_to_cdp");
	if(map_to_cdp && Verbose)
		elog_notify(0,"Casting data as CDP stacked section\n");
	if(dbopen(dbin,"r",&db) == dbINVALID)
	{
		elog_complain(1,"Cannot open db %s\n", dbin);
		usage();
	}
	/* We grab the sample rate and trace length (in seconds) and
	use this to define global sample rates for the data.
	SEG-Y REV0 REQUIRES fixed length records and sample rates, so
	irregular sample rates will cause this program to die.
	One could add a decimate/interpolate function, but this
	is not currently implemented */
	samprate0 = pfget_double(pf,"sample_rate");
	tlength = pfget_double(pf,"trace_length");
	nsamp0 = (int)(tlength*samprate0);
	use_32bit_nsamp=pfget_boolean(pf,"use_32bit_nsamp");
	if (ntohs(segy_format) >= 0x0100 && use_32bit_nsamp) {
		elog_complain(0,"The 32-bit extension field is incompatible with SEG-Y REV 1. Ignoring 'use_32bit_nsamp' from the parameter file");
		use_32bit_nsamp=0;
	}

	/* nsamp in segy is a 16 bit field.  Handling depends on
	setting of use_32bit_nsamp boolean */
	if(nsamp0 > SEGY_MAX_NSAMP)
	{
		if(use_32bit_nsamp)
		{
			elog_notify(0,"Warning:  segy uses a 16 bit entity to store number of samples\nThat field is garbage. Using the 32 bit extension field.");
		}
		else
		{
		elog_complain(0,
		  "Warning:  segy uses a 16 bit entity to store number of samples. Requested %d samples per trace.  Trucated to %d", nsamp0, SEGY_MAX_NSAMP);
		nsamp0 = SEGY_MAX_NSAMP;
		}
	}

	/* boolean.  When nonzero set coordinates as geographic arc seconds values */
	int use_geo_coordinates=pfget_boolean(pf,"use_geo_coordinates");

	/* boolean. When nonzero, output decimal degrees instead of arcseconds if
	 * the requested output format supports it (rev1 only) */
	int prefer_decimal_degrees=pfget_boolean(pf, "prefer_decimal_degrees");

	/* We now have enough information to decide the coordUnits for all traces */
	int coordUnits = 0;
	if (!use_geo_coordinates) {
		coordUnits=SEGY_TRACE_COORDUNITS_LENGTH;
	} else if (ntohs(segy_format) >= 0x0100 && prefer_decimal_degrees) {
		coordUnits=SEGY_TRACE_COORDUNITS_DECIMAL_DEGREES;
	} else {
		coordUnits=SEGY_TRACE_COORDUNITS_ARCSECONDS;
	}
	/* We should have set our coordinate units now */
	assert(coordUnits!=0);

	input_source_coordinates=pfget_boolean(pf,"input_source_coordinates");
	if(input_source_coordinates)
	{
		coordScale=pfget_int(pf,"coordinate_scale_factor");
	}
	else if (coordUnits==SEGY_TRACE_COORDUNITS_DECIMAL_DEGREES)
	{
		/* Use a sane scalar for decimal degrees. 10000 gives four decimal
		 * places of accuracy, which matches the CSS3.0 spec for lat and lon */
		coordScale=10000;
	}
	else
	{
		coordScale=1;
	}

	/* Print a diagnostic message if the user gave a sub-optimal value for the
	 * coordScale */
	if (coordUnits == SEGY_TRACE_COORDUNITS_DECIMAL_DEGREES &&
			coordScale < 10000)
	{
		elog_alert(0,
				"The supplied parameter 'coordinate_scale_factor' value of %d is less than 10000, and will cause loss of precision for decimal degree coordinates.",
				coordScale);
	}
    else if (coordUnits == SEGY_TRACE_COORDUNITS_ARCSECONDS)
    {
        if (coordScale > 1000) {
            elog_alert(0,
                    "The supplied parameter 'coordinate_scale_factor' value of %d is greater than 1000, and will cause loss of precision for arcsecond coordinates.",
                    coordScale);
        }
    }

	/* trace_gain_type: signed int */
	int16_t trace_gain_type = pfget_int(pf,"trace_gain_type");
	if (trace_gain_type < 0)
	{
		die(0, "The trace_gain_type must be zero or greater");
	}
	else
	{
		trace_gain_type=htons(trace_gain_type);
	}


	/* check list of tables defined in pf.  Return array of
	logicals that define which tables are valid and join
	tables. */
	table_list = check_tables(db,pf);
	check_for_required_tables(table_list);
	dbj = join_tables(db,pf,table_list);
	if(dbj.record == dbINVALID) elog_die(0,"dbjoin error\n");
	if(substr!=NULL) dbj=dbsubset(dbj,substr,0);
	long int ndbrows;
	dbquery(dbj,dbRECORD_COUNT,&ndbrows);
	if(ndbrows<=0)
	{
		elog_complain(1,"Working database view is empty\n");
		if(substr!=NULL) elog_complain(0,"Subset condtion =%s a likely problem\n",
				substr);
		usage();
	}

	fp = fopen(outfile,"w");
	if(fp == NULL)
	{
		elog_complain(0,"Cannot open output file %s\n",outfile);
		usage();
	}

	/* These are needed for sort below */
	pushtbl(sortkeys,"sta");
	pushtbl(sortkeys,"chan");

    /* Set up and write the Textual File Header */
	initialize_text_header(text_file_header, segy_format,
			text_header_description);

	if(write_reel_headers){
		if ( fwrite(text_file_header,1,SEGY_TEXT_HEADER_SIZE,fp) \
				!= SEGY_TEXT_HEADER_SIZE ) {
			elog_die(1,"An error occurred writing the textual file header");
		}
	}

	/* memory allocation for trace data.  This is a large matrix
	that is cleared for each event.  This model works because of
	segy's fixed length format.*/
	traces = calloc(nchan, sizeof(float*));
	if(traces == NULL)
		elog_die(1,"out of memory");
	for (int r = 0; r < nchan; r++)
	{
		traces[r] = calloc(nsamp0, sizeof(float));
		if(traces[r] == NULL)
			elog_die(1,"out of memory");
	}
	header = (SEGYTraceHeader *)calloc((size_t)nchan,sizeof(SEGYTraceHeader));
	if(header == NULL)
			elog_die(0,"Cannot alloc memory for %d segy header workspace\n",nchan);
	if(write_reel_headers)
	{
		if (Verbose) {
			elog_debug(0,"Binary Headers - Using segy_format code 0x%04X\n", ntohs(segy_format));
		}
		initialize_binary_file_header(&reel, segy_format);

		/* now fill in the binary reel header and write it */
		reel.kjob   = htonl(1);
		reel.kline  = htonl(1);
		reel.kreel  = htonl(1);
		reel.kntr   = htons((int16_t)nchan);
		reel.knaux  = htons(0);
		reel.sr     = htons((int16_t)(1000000.0/samprate0));
		reel.kfldsr = reel.sr;
		reel.knsamp = htons((int16_t)nsamp0);
		reel.kfsamp = htons((int16_t)nsamp0);
		reel.dsfc   = htons(5);  /* This is ieee floats*/
		reel.kmfold = htons(0);
		if(map_to_cdp)
			reel.ksort = htons(2);
		else
			reel.ksort = htons(1);
		reel.kunits = htons(1);  /* This sets units to always be meters */

		if(fwrite((void *)(&reel),sizeof(SEGYBinaryFileHeader),1,fp) != 1)
		{
			elog_die(1,"Write error for binary reel header");
		}
	}

	/* Now we enter a loop over stdin reading start times.
	Program will blindly ask for data from each start time to
	time+tlength.  The trace buffer will be initialized to
	zeros at the top of the loop always.  If nothing is found
	only zeros will be written to output.
	*/
	while((stest=fgets(s,80,stdin)) != NULL)
	{
		double slat,slon,selev;  /* Used when reading source location*/
		if(Verbose)
			elog_notify(0,"Processing:  %s\n",s);
		for(i=0;i<nchan;++i)
		{
			initialize_trace_header(&(header[i]), segy_format);
			header[i].gainType = trace_gain_type;
			header[i].lineSeq = htonl(total_traces + i + 1);
			header[i].reelSeq = header[i].lineSeq;
			if(map_to_cdp)
			{
				header[i].cdpEns = htonl(i + 1);
				header[i].traceInEnsemble = htonl(1);/* 1 trace per cdp faked */
			}
			else
			{
				header[i].channel_number = htonl(i + 1);
			}
			header[i].event_number   = htonl(shotid);
			header[i].energySourcePt = htonl(shotid);
			for(j=0;j<nsamp0;++j)  traces[i][j] = htonf((Trsample)0.0);
		}
		if(input_source_coordinates)
		{
			char stmp[40];
			sscanf(s,"%s%ld%lf%lf%lf",stmp,&shotid,&slon,&slat,&selev);
			time0=str2epoch(stmp);
			if(coordUnits == SEGY_TRACE_COORDUNITS_ARCSECONDS) {
				slat*=3600.0;
				slon*=3600.0;
			}
			slat *= (double)coordScale;
			slon *= (double)coordScale;
		}
		else
		{
			time0 = str2epoch(s);
		}
		endtime0 = time0 + tlength;
		sprintf(stime,"%20.4f",time0);
		sprintf(etime,"%20.4f",endtime0);
		trdb.database = -1;
		if(trload_css(dbj,stime,etime,&trdb,0, 0) < 0)
		{
			if(Verbose)
			{
			  elog_notify(0,"trload_css failed for shotid=%ld",shotid);
			  elog_notify(0,"  No data in time range %s to %s\n",
			  	strtime(time0),strtime(endtime0) );
			  elog_notify(0,"No data written for this shotid block.");
			  elog_notify(0,"  Handle this carefully in geometry definitions.\n");
			}

			continue;
		}
		/* This does gap processing */
		repair_gaps(trdb);

		trapply_calib(trdb);

		if(rotate)
		{
			if(rotate_to_standard(trdb,newchan_standard))
				elog_notify(0,"Data loss in rotate_to_standard for event %s to %s\n",
					stime, etime);
			/* This is need to prevent collisions of channel names */
			trdbss = dbsubset(trdb,trsubset,0);
			if(trrotate(trdbss,phi,theta,newchan))
				elog_notify(0,"Data loss in trrotate for event %s to %s\n",
					stime, etime);
		}
		if(Verbose)
			elog_notify(0,"Station  chan_name  chan_number seq_number shotid  evid\n");
		trdb = dbsort(trdb,sortkeys,0,0);
		dbquery(trdb,dbRECORD_COUNT,&ntraces);
		if(Verbose) elog_debug(0,"Read %ld traces for event at time%s\n",
			ntraces,strtime(time0));
		for(trdb.record=0;trdb.record<ntraces;++trdb.record)
		{
			Trsample *trdata;
			if(dbgetv(trdb,0,
			    "evid",&evid,
			    "sta",sta,
			    "chan",chan,
			    "nsamp", &nsamp,
			    "samprate",&samprate,
			    "data",&trdata,
			    "lat", &lat,
			    "lon", &lon,
			    "elev",&elev,
			    "refsta",refsta,
			    "dnorth",&dnorth,
			    "deast",&deast,
			    "edepth",&edepth,
			    "segtype",&segtype,
			    NULL) == dbINVALID)
			{
				elog_complain(0," dbgetv error reading record %ld. Trace will be skipped for station %s and channel %s",
				trdb.record,sta,chan);
				continue;
			}
			/* Allow 1 percent samprate error before killing */
			double fsrskew=fabs((samprate-samprate0)/samprate0);
			double frskewcut=0.01;
			if(fsrskew>frskewcut)
			{
				elog_complain(0,"%s:%s sample rate %f is significantly different from base sample rate of %f. Trace skipped -- segy requires fixed sample rates",
					sta,chan,samprate,samprate0);
				continue;
			}
			if(nsamp > nsamp0)
			{
				elog_complain(0,"%s:%s trace has extra samples=%ld. Truncated to length %d",
					sta, chan, nsamp, nsamp0);
				nsamp = nsamp0;
			}
			else if(nsamp < nsamp0)
			{
				elog_complain(0,"%s:%s trace is shorter than expected %d samples. Zero padded after sample %ld",
					sta, chan, nsamp0, nsamp);
			}

			ichan = get_channel_index(channels,sta,chan);
			if(ichan > nchan)
			{
				elog_die(0,"Channel index %d outside limit of %d. Cannot continue",
					ichan, nchan);
			}
			if(ichan >= 0)
			{
				if(Verbose)
					elog_debug(0,"%s:%s\t%-d\t%-d\t%-ld\t%-ld\n",
					sta,chan,ichan+1,
					ntohl(header[ichan].reelSeq),
					shotid, evid);
				header[ichan].traceID = get_trace_id_code_from_segtype(segtype);
				for(j=0;j<nsamp;++j) {
				   traces[ichan][j] = htonf((float)trdata[j]);
				}
				/* header fields coming from trace table */
				header[ichan].samp_rate = htonl(
						(int32_t) (1000000.0/samprate0));
				/* according to the behavior specified in the man page:
				 * if use_geo_coordinates is false:
				 * - coordUnits is length (meters)
				 * - therefore, we use deast for X and dnorth for Y
				 * if use_geo_coordinates is true:
				 * - we're using either arcseconds or decimal degrees
				 * - and therefore, we use lon for X and lat for Y
				 *
				 * coordUnits is based on use_arcseconds and the requested
				 * version of segY */

				/* set the coordinate units in the trace header */
				header[ichan].coordUnits = coordUnits;

				/* Pick the source db fields for our receiver X and Y */
				double recLongOrX = 0;
				double recLatOrY  = 0;
				if (coordUnits == SEGY_TRACE_COORDUNITS_LENGTH) {
					/* Use deast and dnorth
					 * CSS3.0 Schema specifies deast and dnorth are in KM.
					 * SEG-Y specifies easting and northing as meters,
					 * hence the 1000.0 multiplier here. */
					recLongOrX = deast  * 1000.0;
					recLatOrY  = dnorth * 1000.0;
				} else if (coordUnits == SEGY_TRACE_COORDUNITS_ARCSECONDS){
					/* Use lat and lon, converted to arcseconds */
					recLongOrX = lon * 3600.0;
					recLatOrY  = lat * 3600.0;
				} else {
					/* Default case, which covers decimal degrees */
					recLongOrX = lon;
					recLatOrY  = lat;
				}

				/* Apply our coordScale - the user can specify negative numbers,
				 * but they are treated as inverting the value, not as a divisor
				 * as in the SEG-Y field usage. See below where we always treat
				 * the scalar as a divisor in the SEG-Y field */
				recLongOrX *= (double)coordScale;
				recLatOrY  *= (double)coordScale;

				/* Set the coordScale in the header.
				 * Note negative here.  This is a oddity of segy that - means
				 * divide by this to get actual.  Always make this negative in
				 * case user inputs a negative number.
				 * Don't set it -1 for cosmetic reasons */
				if (abs(coordScale) == 1)
				{
					header[ichan].coordScale = htons(1);
				} else
				{
					header[ichan].coordScale = htons(-abs(coordScale));
				}

				/* Finally, write out the X and Y */
				header[ichan].recLongOrX
					= htonl((int32_t)recLongOrX);
				header[ichan].recLatOrY
					= htonl((int32_t)recLatOrY);

				/* CSS3.0 specfies elev as being in km, SEG-Y wants it in m */
				header[ichan].recElevation = htonl((int32_t)(elev*1000.0));

				header[ichan].deltaSample = htons(
						(int16_t) (1000000.0/samprate0));
				header[ichan].sampleLength = htons((int16_t)nsamp0);
				if (ntohs(segy_format)<0x0100)
				{
					header[ichan].num_samps = htonl((int32_t)nsamp0);
				}
				/* This cracks the time fields */
				time_str = epoch2str(time0,fmt);
				int16_t hyear, hday, hhour, hminute, hsecond, hm_secs;
				hyear=hday=hhour=hminute=hsecond=hm_secs=0;
				sscanf(time_str,"%hd %hd %hd %hd %hd %hd",
						&hyear, &hday, &hhour, &hminute, &hsecond, &hm_secs);
				header[ichan].year   = htons(hyear);
				header[ichan].day    = htons(hday);
				header[ichan].hour   = htons(hhour);
				header[ichan].minute = htons(hminute);
				header[ichan].second = htons(hsecond);
				header[ichan].m_secs = htons(hm_secs);
				if (ntohs(segy_format)<0x0100)
				{
					/* These are IRIS-PASSCAL extensions */
					header[ichan].trigyear   = header[ichan].year;
					header[ichan].trigday    = header[ichan].day;
					header[ichan].trighour   = header[ichan].hour;
					header[ichan].trigminute = header[ichan].minute;
					header[ichan].trigsecond = header[ichan].second;
				}
				free(time_str);
				if(input_source_coordinates)
				{
					/* Write out our pre-scaled and optionally
					 * arcsecond-converted source lat/lon plus our elevation */
					header[ichan].sourceLongOrX = htonl((int32_t)slon);
					header[ichan].sourceLatOrY  = htonl((int32_t)slat);
					header[ichan].sourceSurfaceElevation
						= htonl((int32_t)selev);
					/* No easy way to specify both elev and depth*/
					header[ichan].sourceDepth=htonl(0);
				}
				else if(map_to_cdp)
				{
				/* When faking CDP data we make this look
				like a zero offset, single fold data set */
					header[ichan].sourceLongOrX   = header[ichan].recLongOrX;
					header[ichan].sourceLatOrY    = header[ichan].recLatOrY;
					header[ichan].sourceSurfaceElevation
					                              = header[ichan].recElevation;
					header[ichan].sourceDepth     = htonl(0);
					header[ichan].sourceToRecDist = htonl(0);
				}
				else
				{
				/* This is the mechanism for adding other
				information with added tables.  The one
				table currently supported is a "shot" table
				that holds shot coordinates.  If other tables
				were added new functions could be added with
				a similar calling sequence.  This procedure
				silently does nothing if a shot table is not
				present.*/
					set_shot_variable(db,table_list,
						evid,&header[ichan]);
				}
			}
			else
			{
				if(Verbose)
					elog_notify(0,"Station %s and channel %s skipped\n",
						sta,chan);
			}

		}
		/* Now we write the data */
		for(i=0;i<nchan;++i)
		{
			if(fwrite((void *)(&(header[i])),sizeof(SEGYTraceHeader),1,fp) != 1)
				elog_die(0,"Write error on header for trace %d\n",total_traces+i);
			if(fwrite((void *)traces[i],sizeof(float),
					(size_t)nsamp0,fp) != nsamp0)
				elog_die(0,"Write error while writing data for trace %d\n",
					total_traces+i);
		}
		total_traces += nchan;
		trdestroy(&trdb);
		if(!input_source_coordinates) ++shotid;
	}
	return 0 ;
}
Esempio n. 22
0
int
main (int argc, char **argv)
{
	int	c;
	int 	errflg = 0;
	Dbptr	db;
	char	*database;
	int	verbose = 0;
	int	primary = 0;
	Pf	*pf = NULL;
	char	*xmlstring = NULL;
	char	*rootname = NULL;
	char	*rowname = NULL;
	char	*stylesheet = NULL;
	char	xslt_processor[STRSZ];
	char	command[STRSZ];
	char	tempfile[FILENAME_MAX];
	FILE	*tempfs = NULL;
	Tbl	*fields = 0;
	Tbl	*expressions = 0;
	int	rc;
	int	flags = 0;

	elog_init( argc, argv ) ; 

	while ((c = getopt (argc, argv, "pd:r:t:v")) != -1) {
		switch (c) {

		case 'v':
			verbose++;
			break;

		case 't':
			stylesheet = strdup( optarg );
			break;

		case 'd':
			rootname = strdup( optarg );
			break;

		case 'p':
			primary++;
			break;

		case 'r':
			rowname = strdup( optarg );
			break;

		default:
			errflg++;
			break ;
		}
	}

	if( errflg || argc - optind < 1 || (((argc-optind) % 2) != 1)) {
		usage ();
	}

	pfread( "db2xml", &pf );

	database = argv[optind++];
	
	if( dbopen_table( database, "r+", &db ) < 0 ) { 

		elog_die( 0, "Can't open database %s\n", database ); 
	}

	if( argc - optind > 0 ) {

		fields = newtbl( 20 );	
		expressions = newtbl( 20 );

		while( argc - optind > 0 ) {
			pushtbl( fields, argv[optind++] );	
			pushtbl( expressions, argv[optind++] );	
		}
		
		if( primary ) {
			elog_complain( 1, 
			"Useless use of '-p' with specified expressions, ignoring\n" );
		}

	} else if( primary ) {

		flags |= DBXML_PRIMARY;
	}

	rc = db2xml( db, rootname, rowname, fields, expressions, 
		(void **) &xmlstring, flags );

	if( rc < 0 || xmlstring == NULL ) {
		
		elog_clear_register( 1 );

		elog_die( 0, "db2xml failed\n" );

	} else if( stylesheet != NULL ) {

		sprintf( tempfile, "/tmp/db2xml_%d_%d.xml", getuid(), getpid() );

		tempfs = fopen( tempfile, "w" );

		fwrite( xmlstring, sizeof(char), strlen( xmlstring ), tempfs );

		fclose( tempfs );

		sprintf( xslt_processor, "%s", pfget_string( pf, "xslt_processor" ) );

		strsub( xslt_processor, "STYLESHEET", stylesheet, xslt_processor );

		strsub( xslt_processor, "XMLFILE", tempfile, command );

		system( command );

		unlink( tempfile );

	} else {

		fwrite( xmlstring, sizeof(char), strlen( xmlstring ), stdout );
	}

	free( xmlstring );

	return 0;
}
Esempio n. 23
0
static void
pfmorph( Pf *pf ) {
	Pf	*dlspf;
	Pf	*stapf;
	Tbl	*stas;
	int	ista;
	char	*sta;
	char	*opt_string;

	if( pfget( pf, "dls", (void **) &dlspf ) == PFINVALID ) {

		return;
	}

	stas = pfkeys( dlspf );

	for( ista = 0; ista < maxtbl( stas ); ista++ ) {

		sta = gettbl( stas, ista );

		if( pfget( dlspf, sta, (void **) &stapf ) == PFINVALID ) {
			
			continue;
		}


		if( ( opt_string = pfget_string( stapf, "opt" ) ) == (char *) NULL ||
		    ! strcmp( opt_string, "-" ) ) {

			pfset( stapf, "acok", "-" );
			pfset( stapf, "api",  "-" );
			pfset( stapf, "isp1", "-" );
			pfset( stapf, "isp2", "-" );
			pfset( stapf, "ti",   "-" );

		} else {

			if( strcontains( opt_string, "acok", NULL, NULL, NULL ) ) {

				pfset( stapf, "acok", "1" );
				
			} else {

				pfset( stapf, "acok", "0" );
			}

			if( strcontains( opt_string, "api", NULL, NULL, NULL ) ) {

				pfset( stapf, "api", "1" );
				
			} else {

				pfset( stapf, "api", "0" );
			}

			if( strcontains( opt_string, "isp1", NULL, NULL, NULL ) ) {

				pfset( stapf, "isp1", "1" );
				
			} else {

				pfset( stapf, "isp1", "0" );
			}

			if( strcontains( opt_string, "isp2", NULL, NULL, NULL ) ) {

				pfset( stapf, "isp2", "1" );
				
			} else {

				pfset( stapf, "isp2", "0" );
			}

			if( strcontains( opt_string, "ti", NULL, NULL, NULL ) ) {

				pfset( stapf, "ti", "1" );
				
			} else {

				pfset( stapf, "ti", "0" );
			}
		}
	}

	freetbl( stas, 0 );

	return;
}
Esempio n. 24
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);
}
Esempio n. 25
0
/* This function computes theoretical arrival times and a slowness vector
(at the reference station for an array) based on a model and method
defined in a parameter file and using the generic travel time interface
of datascope/antelope.  

Arguments:
///inputs////
	stations - Associative array of MWstation objects used in 
			multiwavelet programs
	refsta - name of reference station to use.  The slowness 
		vector is computed based on a source location accessed
		through the db pointer (see below) and the location of
		the reference station.  If the refsta is not found in 
		the stations array the first element of the sorted list
		of stations will be used in an attempt to recover.  For
		most arrays this would be a minor error.
	phase - name of seismic phase to compute theoretical times and
		slowness vector for.  
	db - This db pointer MUST point to a single row of a db view with 
		the origin table joined as part of the view.   The hypocenter
		information is read with dbgetv passing this db pointer 
		directly.
	pf - parameter space pointer.  We search for model and method
		fields from pf to get the interface right. 
///outputs///
	times - associative array keyed by station name of theoretical
		arrival times (stored as double * s).  If there are 
		problems computing any travel times they will be absent
		from this array.  When this array is used, be aware you
		can't assume all the times are filled.
	slow - theoretical slowness vector.  If the slowness vector
		calculation fails this is set to 0 and the refsta field
		is set to "BAD".  This allows the use of the slowness 
		vector without errors in a less than ideal way.  The 
		BAD condition should be trapped.

Return codes:
	0 = normal return, no problems
	> 0 = count of travel time failures
	< 0 = nothing was computed.  Both slowness and times should be
		assumed invalid.

Author:  Gary Pavlis
Written: December 2000
*/

static Hook *hook=0;  /*Used by ttcalc */
int MWget_model_tt_slow(Arr *stations,
			char *refsta,
			char *phase,
			Dbptr db,
			Pf *pf,
			Arr **times,
			MWSlowness_vector *slow)
{
	Tbl *t;  /* used to hold keys with keysarr */
	char *key;  /* key returned from Tbl *t */
	int i;
	MWstation *s, *s0; 
	char *model;
	char *method;
	TTGeometry geometry;
	TTTime *atime;
	TTSlow *u0,*u;
	Tbl *treturn=NULL,*ureturn=NULL;
	int error_count=0;
	double *twork;

	s0 = (MWstation *)getarr(stations,refsta);
	if(s0 == NULL) elog_complain(0,"MWget_model_tt_slow:  cannot find reference station %s\nWill arbitarily pick first station found as refererence for computing model based time and slowness\n",refsta);
	if(dbgetv(db,0,"origin.lat",&(geometry.source.lat),
		"origin.lon",&(geometry.source.lon),
		"origin.depth",&(geometry.source.z),
		"origin.time",&(geometry.source.time),0) == dbINVALID)
	{
		elog_complain(0,"MWget_model_tt_slow:  dbgetv error reading origin data\nCannot compute theoretical arrival times and slowness\n");
		return(-1);	
	}
	model = pfget_string(pf,"TTmodel");
	method = pfget_string(pf,"TTmethod");
	if( (model == NULL) || (method == NULL) )
	{
		elog_complain(0,"MWget_model_tt_slow:  TTmodel or TTmethod missing from parameter file\nCannot compute theoretical travel times and slowness vector\n");
		return(-1);
	}
	t = keysarr(stations);
	if(maxtbl(t)<=0)
	{
		elog_complain(0,"MWget_model_tt_slow:  no data to process\n");
		return(-1);
	}
	/* recover from reference station error */
	if(s0==NULL)
	{
		key = gettbl(t,0);
		
		elog_log(0,"Setting reference station to %s for travel time computation\n",
			key);
	}
	/* We now compute the slowness vector estimated for the reference
	station location at 0 elevation. */
	strcpy(geometry.receiver.name,s0->sta);
	geometry.receiver.lat = s0->lat;
	geometry.receiver.lon = s0->lon;
	geometry.receiver.z = 0.0;
	if(slow->refsta == NULL) slow->refsta = strdup(refsta);
	if(ucalc(method,model,phase,0,&geometry,&ureturn,&hook))
	{
		elog_complain(0,"MWget_model_tt_slow:  slowness vector calculation failed for reference station %s\nSetting model slowness vector to zero and attempting to continue.\n",
			s0->sta);
		slow->ux = 0.0;
		slow->uy = 0.0;
	}
	else
	{
		u0 = (TTSlow *)gettbl(ureturn,0);
		slow->ux = u0->ux;
		slow->uy = u0->uy;
	}
	/* If the output times array is not empty we have to free it up 
	and start fresh.  Otherwise we will have a memory leak or access
	old values stored there.  This probably should be handled 
	externally, but better to be redundant.*/
	if(*times != NULL) freearr(*times,free);
	*times = newarr(0);

	/* Look through the station list */
	for(i=0;i<maxtbl(t);i++)
	{
		double estatic;
		key = gettbl(t,i);
		s = (MWstation *)getarr(stations,key);
		strcpy(geometry.receiver.name,s->sta);
		geometry.receiver.lat = s->lat;
		geometry.receiver.lon = s->lon;
		geometry.receiver.z = 0.0;
		if(ttcalc(method,model,phase,0,&geometry,&treturn,&hook))
		{
			elog_complain(0,"MWget_model_tt_slow: Travel time computation failed computing travel time for station %s\nCannot compute residuals\n",
				s->sta);
			++error_count;
		}
		else
		{
			atime = (TTTime *)gettbl(treturn,0);
			estatic = compute_elevation_static(s,*slow,0.0,phase);
			allot(double *,twork,1);
			*twork = geometry.source.time
				+ (atime->value) + estatic;
			setarr(*times,key,twork);
		}
	}
	freetbl(ureturn,0);
	freetbl(treturn,0);
	return(error_count);
}
Esempio n. 26
0
MWbasis *load_multiwavelets_db(Dbptr db, Pf *pf,int *nwavelets, int *bankid)
{
	MWbasis *mwb;
	int nw;
	char *select_condition;
	Dbptr dbv;
	int nrecords;
	/* These are the attribute in the mwdisc table minus
	those returned in the argument list */

	int nsamp,foff;
	double f0,fw;
	char datatype[4],mworder[4];
	char fname[128];
	FILE *fp;
	int i,j,jj;
	
	dbv = dblookup(db,0,"mwdisc",0,0);
	if(dbv.record == dbINVALID) elog_die(0,"load_multiwavelets_db:  no mwdisc table in input database\nThese are required for multiwavelet transform\nCheck database descriptor\n");
	select_condition=pfget_string(pf,"multiwavelet_select_condition");
	if(select_condition==NULL)
		elog_die(0,"Missing required parameter string called multiwavelet_select_condition\nThis is required when loading multiwavelets from a database\n");
	dbv=dbsubset(dbv,select_condition,0);
	dbquery(dbv,dbRECORD_COUNT,&nrecords);
	if(nrecords<=0)
		elog_die(0,"load_multiwavelet_db:  no records in mwdisc match condition: %s\n",
			select_condition);
	else if (nrecords>1)
		elog_complain(0,"load_multiwavelet_db:  multiple records in mwdisc match the condition %s\nUsing first record found\n",
			select_condition);
	dbv.record=0;
	dbgetv(dbv,0,"bankid",bankid,
		"nsamp",&nsamp,
		"nwavelets",nwavelets,
		"f0",&f0,
		"fw",&fw,
		"datatype",datatype,
		"foff",&foff,
		"mworder",mworder,0);
	if(strcmp(datatype,"t4"))
		elog_die(0,"multiwavelets must be in t4 binary form\n");
	if(strcmp(mworder,"ti") || strcmp(mworder,"ts") )
	{
		if(dbextfile(dbv,0,fname)<=0)
			elog_die(0,"load_multiwavelet_db: multiwavelet basis file %s not found\n",
				fname);
		fp = fopen(fname,"r");
		if(foff>0) fseek(fp,foff,0);
		allot(MWbasis *,mwb,*nwavelets);
		for(i=0;i<*nwavelets;++i)
		{
			allot(float *,mwb[i].r,nsamp);
			allot(float *,mwb[i].i,nsamp);
			mwb[i].n=nsamp;
			mwb[i].f0=f0;
			mwb[i].fw=fw;
		}
		
		if(!strcmp(mworder,"ti"))
		{
			/* This is case for storage as complex number */
			float *buffer;
			allot(float *,buffer,2*nsamp);
			for(i=0;i<*nwavelets;++i)
			{
				if(fread(buffer,sizeof(float),2*nsamp,fp)
					!= (2*nsamp))
				{
					elog_die(0,"read error on file %s while reading wavelet %d\n",
						fname,i);
				}
				for(j=0,jj=0;j<nsamp;++j,jj+=2)
				{
					mwb[i].r[j]=buffer[jj];
					mwb[i].i[j]=buffer[jj+1];
				}
			
			}
			free(buffer);
		}
		else
		{
			for(i=0;i<*nwavelets;++i)
Esempio n. 27
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 );
			}
		}
	}
}
/* 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);
}
int main(int argc, char **argv)
{
	char *dbin;  /* Input db name */
	char *dbout;  /* output db name */
	Dbptr db;  /* input db pointer */
	Dbptr dbo;  /* base output db pointer */
	Dbptr dbv;  /* set to view formed by join */
	char *pfin=NULL;  /* input parameter file */
	char *sift_exp;  /* sift expression for subset */
	int sift = 0;  /* default is no sift.  */
	Tbl *sortkeys;
	Tbl *joinkey1, *joinkey2;
	/*Pointers to views returned by dbgroup (keyed to origin and event
	respectively */
	Dbptr dborigin_group;
	Tbl *origin_group;  /* relation keys used in grouping*/
	long nevents;
	/* db row variables */
	long evid;
	long nrows, nrows_raw;

	int useold=0;
	Pf *pf;
	Tbl *ta,*tu;
	Tbl *reason_converged, *residual;
	Location_options o;
	Arr *arr_phase;
	int i;
	Tbl *converge_history;

	Hypocenter h0;
	Hypocenter *hypos;
	long niterations;

	char *vmodel;

	int ret_code;  /* ggnloc return code */
	double **C;   /* covariance matrix*/
	float emodel[4];  

	/* entries for S-P feature */
	long nbcs;
	Arr *badclocks;
	/* need global setting of this to handle fixed depth solutions*/
	int global_fix_depth;

	C=dmatrix(0,3,0,3);

	if(argc < 3) usage();
	dbin = argv[1];
	dbout = argv[2];
	for(i=3;i<argc;++i)
	{
		if(!strcmp(argv[i],"-pf"))
		{
			++i;
			if(i>=argc) usage();
			pfin = argv[i];
		}
		else if(!strcmp(argv[i],"-sift"))
		{
			++i;
			if(i>=argc) usage();
			sift_exp = argv[i];
			sift = 1;
		}
		else if(!strcmp(argv[i],"-useold"))
			useold = 1;
		else
			usage();
	}
	/* set default this way*/
	if(pfin == NULL) pfin = strdup("relocate");


	/* Initialize the error log and write a version notice */
	elog_init (argc, argv) ;
	cbanner("Version $Revision$ $Date$\n",
			"relocate inputdb outputdb [-pf pf -sift expression -useold]\n",
			"Gary Pavlis",
                        "Indiana University",
                        "*****@*****.**");

	/* Alway join assoc, arrival, and site.  We join site 
	to make sure station table is properly dynamic to account for
	time changes.  With this setup, the stations can even move
	around and this should still work.*/


	if(dbopen(dbin,"r",&db) == dbINVALID) 
		elog_die(1,"Unable to open input database %s\n",dbin);
	if(dbopen(dbout,"r+",&dbo) == dbINVALID) 
		elog_die(1,"Unable to open output database %s\n",dbout);

	dbv = dbjoin ( dblookup(db,0,"event",0,0),
		dblookup(db,0,"origin",0,0),
		0,0,0,0,0);
	if(dbv.table == dbINVALID)
		elog_die(1,"event->origin join failed\n");
	dbv = dbjoin ( dbv, dblookup(db,0,"assoc",0,0),
			0,0,0,0,0);
	if(dbv.table == dbINVALID)
		elog_die(1,"event->origin->assoc join failed\n");
	dbv = dbjoin ( dbv, dblookup(db,0,"arrival",0,0),
			0,0,0,0,0);
	if(dbv.table == dbINVALID)
		elog_die(1,"event->origin->assoc->arrival join failed\n");
	/* We will explicitly set the keys for this join because it
	was found to fail sometimes */
	joinkey1 = newtbl(0);
	joinkey2 = newtbl(0);
	pushtbl(joinkey1,"arrival.sta");
	pushtbl(joinkey1,"arrival.time");
	pushtbl(joinkey2,"sta");
	pushtbl(joinkey2,"ondate::offdate");
	dbv = dbjoin ( dbv, dblookup(db,0,"site",0,0),
			&joinkey1,&joinkey2,0,0,0);
	if(dbv.table == dbINVALID)
		elog_die(1,"event->origin->assoc->arrival->site join failed\n");

	/* Subset using sift_key if requested */
	if(sift)
	{
		dbv = dbsubset(dbv,sift_exp,0);
		if(dbv.record == dbINVALID)
			elog_die(1,"dbsubset of %s with expression %s failed\n",
				dbin, sift_exp);
	}
	/* This keeps only the prefered origin records intact */
	dbv = dbsubset(dbv,"orid == prefor", 0);
	if(dbv.record == dbINVALID)
			elog_die(1,"Subset to preferred origin records failed\n");

	/* First we have to run a unique key sort in the following order
	to remove redundant picks made on multiple channels.  We will
	issue a warning if the record count changes. */
	dbquery(dbv, dbRECORD_COUNT, &nrows_raw);
	sortkeys = newtbl(0);
	pushtbl(sortkeys,"evid");
	pushtbl(sortkeys,"sta");
	pushtbl(sortkeys,"phase");
	dbv = dbsort(dbv,sortkeys,UNIQUE,0);
	dbquery(dbv, dbRECORD_COUNT, &nrows);
	if(nrows != nrows_raw)
		elog_complain(0,"Input database has duplicate picks of one or more phases on multiple channels\n\
Which picks will be used here is unpredictable\n\
%ld total picks, %ld unique\nContinuing\n", nrows_raw, nrows);

	/* This sort is the required one for the grouping that follows*/

	sortkeys = newtbl(3);
	pushtbl(sortkeys,"evid");
	pushtbl(sortkeys,"orid");
	pushtbl(sortkeys,"arrival.time");
	dbv = dbsort(dbv,sortkeys,0,0);
	if(dbv.record == dbINVALID)
		elog_die(1,"dbsort on evid,orid,arrival.time failed\n");

	/* Set up grouping by events */
	origin_group = newtbl(0);
	pushtbl(origin_group, "evid");
	dborigin_group = dbgroup(dbv, origin_group, "origin_group",1);
	if(dborigin_group.record == dbINVALID)
		elog_die(1,"dbgroup by origin failed\n");

	dbquery(dborigin_group,dbRECORD_COUNT,&nevents);
	elog_notify(0,"Attempting to relocate %ld events in subsetted database\n",
		nevents);
	

	/* DB is now set up correctly, now we turn to the parameter files */
	i = pfread(pfin,&pf);
	if(i != 0) elog_die(1,"Pfread error\n");

	o = parse_options_pf (pf);
	global_fix_depth=o.fix[2];
 	arr_phase = parse_phase_parameter_file(pf);
	vmodel = pfget_string(pf,"velocity_model_name");

	/* set up minus phase for bad clock problems */
	badclocks = newarr(0);
	if(db_badclock_definition(db,pf,badclocks))
		elog_complain(0,"Warning:  problems in database definitions of bad clock time periods\n");
	pfget_badclocks(pf,badclocks);
	nbcs = cntarr(badclocks);
	if(nbcs>0) fprintf(stdout,"relocate:  bad clock feature enabled\n\n");
        /* Change by JN to output evid and orid. */
        /* fprintf(stdout,"lat lon depth time rms wrms interquartile ndata ndgf iterations\n"); */
	fprintf(stdout,"evid orid lat lon depth time rms wrms interquartile ndata ndgf iterations\n");

	/* Main loop.  We utilize the group views and loop through by 
	events */
	for(dborigin_group.record=0;
		dborigin_group.record< nevents;++dborigin_group.record)
	{
		Dbptr db_bundle;  /* db pointer returned from bundle field 
				of dborigin_group for current event */
		Arr *station_table;
		Arr *array_table;
		long is, ie; 
		long orid;  /* orid assigned relocated event in output db */

		if(dbgetv(dborigin_group,0,"evid", &evid,
			"bundle", &db_bundle,NULL ) == dbINVALID)
			elog_complain(1,"dbgetv error for row %ld of event group\n",
				dborigin_group.record);
		dbget_range(db_bundle,&is,&ie);

		station_table = dbload_station_table(dbv,
						is,ie,pf);
		array_table = dbload_array_table(dbv,
						is,ie,pf);
		ta = dbload_arrival_table(dbv,
				is,ie,station_table, arr_phase);


		tu = dbload_slowness_table(dbv,
				is,ie,array_table, arr_phase);
		/* this actually sets up the minus phase feature for bad clocks*/
		if(nbcs)
		{
			if(minus_phases_arrival_edit(ta,arr_phase,badclocks))
				elog_complain(0,"Warning(relocate):  problems in minus_phase_arrival_edit function\n");
		}
		if(useold)
		{
			char dtype[2];
			h0 = db_load_initial(dbv,is);
			/* keep fixed depth if done before.  
			setting dbv.record here is a bit of
			a potential maintenance problem */
			dbv.record=is;
			dbgetv(dbv,0,"dtype",dtype,NULL );
			if( (!strcmp(dtype,"g")) || (!strcmp(dtype,"r")) )
				o.fix[2]=1;
			
		}
		else
			h0 = initial_locate(ta, tu, o, pf);

		ret_code = ggnloc(h0,ta,tu,o,
			&converge_history,&reason_converged,&residual);
			
		if(ret_code < 0)
		{
			elog_complain(1,"ggnloc failed to produce a solution\n");
		}
		else 
		{
			if(ret_code > 0)
			    elog_complain(1,"%d travel time calculator failures in ggnloc\nSolution ok\n",
				ret_code);
			
			niterations = maxtbl(converge_history);
			hypos = (Hypocenter *)gettbl(converge_history,
								niterations-1);
			predicted_errors(*hypos,ta,tu,o,C,emodel);

                        /* Next 3 calls changed by JN to output evid, orid and number_data */
			orid = save_origin(dbv,is,ie,o.fix[3],*hypos,dbo);
			evid = save_event(dbv,is,ie,orid,dbo);

			fprintf(stdout,"%ld %ld %lf %lf %lf %lf %g %g %g %d %d %ld\n",
					evid,
					orid,
					hypos->lat,hypos->lon,hypos->z,hypos->time,
					hypos->rms_raw, hypos->rms_weighted,
					hypos->interquartile,
					hypos->number_data,
					hypos->degrees_of_freedom,
					niterations);
	
			save_origerr(orid,*hypos,C,dbo);
			save_assoc(dbv,is,ie,orid,vmodel,residual,*hypos,dbo);
			/* These save genloc add on tables */
			save_emodel(orid,emodel,dbo);
			save_predarr(dbo,ta,tu,*hypos,orid,vmodel);
		}
		o.fix[2]=global_fix_depth;
		if(maxtbl(converge_history)>0)freetbl(converge_history,free);
		if(maxtbl(reason_converged)>0)freetbl(reason_converged,free);
		if(maxtbl(residual)>0)freetbl(residual,free);
		destroy_data_tables(tu, ta);
		destroy_network_geometry_tables(station_table,array_table);
	}
	return(0);
}
Esempio n. 30
0
void compute_location(Location_options o,
	RTlocate_Options rtopts,
	Arr *stations, Arr *arrays, Arr *phases, 
	Pf *pf,
	Dbptr master_db, Dbptr dbtmp, ORB_Hypocenter hyp, int orbout)
{
	Tbl *ta,*tu;  /* Arrival and slowness tables respectively */
	Hypocenter h0;
	int ret_code;
	Tbl *converge_history,*reason_converged,*residual;
	Hypocenter *hypo;
	int niterations;
	char *vmodel;
	int i;
	char *s;
	int orid;
	Point origin;
	double delta, seaz;
	double **C;
	float *emodel;
	int nass;

	initialize_hypocenter(&h0);

	/* It is inefficient to reread these from the parameter
	space on each entry, but preferable to a burdensome
	argument list */  
	origin.lat = pfget_double(pf,"center_latitude");
	origin.lon = pfget_double(pf,"center_longitude");
	origin.z = 0.0;

	/* This routine translates hyp structure to return tbl
	of arrival object pointers */
	ta = orbhypo_to_genloc(&hyp,phases,stations);
	/* this is a pure place holder */
	tu = newtbl(0);

	vmodel = pfget_string(pf,"velocity_model_name");

	/* By default we use the location transmitted by orbassoc.
	This can be overriden in the parameter file by using the
	other options allowed in genloc*/
	s=pfget_string(pf,"initial_location_method");
	h0.lat = hyp.lat;
	h0.lon = hyp.lon;
	h0.z = hyp.depth;
	h0.time = hyp.time;
	/* this strange logic is to allow this parameter to be defaulted.
	If the "initial_location_method" is not defined, or set
	to "manual", we use the location given by orbassoc.  Otherwise
	we utilize genlocs suite of initial locate options. */
	if(s != NULL)
		if(strcmp(s,"manual"))
			h0 = initial_locate(ta, tu, o, pf);

	/* Now compute distance from origin, and process only if 
	the event falls in the specified range */
	dist(rad(origin.lat),rad(origin.lon),rad(h0.lat),rad(h0.lon),
			&delta,&seaz);
	delta = deg(delta);
	/* this is the distance sifting test to ignore things outside
	specified distance range */
	if( ((delta>=rtopts.minimum_distance) 
		&& (delta <= rtopts.maximum_distance)) )
	{

	/* Location with Generic Gauss_Newton code */
		orid = -1;
		nass = maxtbl(ta);
		ret_code = ggnloc(h0,ta,tu,o,
				&converge_history,&reason_converged,&residual);
        	if(ret_code < 0)
        	{
                	elog_notify (0,"ggnloc failed to produce a solution for evid %d\n",hyp.evid);
        	}
        	else
		{
			if(ret_code > 0)
				elog_notify(0,"Warning:  %d travel time calculator failures in ggnloc\nSolution ok for evid %d\n",
                                	ret_code,hyp.evid);
			C = dmatrix(0,3,0,3);
			emodel = (float *) calloc(4,sizeof(float));
			if((emodel == NULL) || (*C == NULL) )
				elog_die(0,"Malloc error for error arrays\n");
			niterations = maxtbl(converge_history);
                	hypo = (Hypocenter *)gettbl(converge_history,
							niterations-1);
			predicted_errors(*hypo, ta, tu, o, C, emodel);
               		orid = save_origin(nass,hyp.evid,master_db,
					 dbtmp,*hypo,o,orbout);

                	save_origerr(orid,*hypo,C,dbtmp,orbout);
			save_assoc(ta, tu, orid, vmodel, 
				*hypo, dbtmp,orbout);
			elog_notify(0,"orid %d converged in %d iterations\n",
				orid,niterations);
			elog_notify(0,"Reason(s) for convergence:  \n");
			for(i=0;i<maxtbl(reason_converged);++i)
                        	elog_notify(0,"%s",gettbl(reason_converged,i));
			elog_notify(0,"\n");
			s=format_hypo(hypo);
			elog_notify(0,"%s\n",s);
			free(emodel);
			free_matrix((char **)C,0,3,0);
			free(s);
		}
		write_to_logfile(rtopts, orid, hyp.evid,
			  pf, converge_history, reason_converged,residual);

		if(maxtbl(converge_history)>0)freetbl(converge_history,free);
		if(maxtbl(reason_converged)>0)freetbl(reason_converged,free);
		if(maxtbl(residual)>0)freetbl(residual,free);

	}
	destroy_data_tables(ta, tu);
	return;
}