Esempio n. 1
0
int grtr_sc_create(Dbptr dbsc, char *net_expr, char *sta_expr, 
        char *chan_expr, double tstart, double tend, char *gap,
        int calib, int ir, Dbptr *trscgr)
{
	char time_str[100];
	char endtime_str[100];
	int ret, n, n2, i;
	double time, time2, endtime, endtime2;
	char sta[32], chan[32];
	char sta2[32], chan2[32];
	char string[1024];
	char string2[64];
	int new_view = 0;
	int is, crunch;
	Response *resp;
	Dbptr db;

	/* Subset input view */

	strcpy (string, "");
	if (sta_expr) {
		strcpy (string, "( ");
        	sprintf (string2, "sta =~ /%s/", sta_expr);
        	strcat (string, string2);
	}
	if (chan_expr) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "chan =~ /%s/", chan_expr);
        	strcat (string, string2);
	}
	if (string[0]) {
		strcat (string, " )");
		dbsc = dbsubset (dbsc, string, 0);
		new_view = 1;
	}
        dbquery (dbsc, dbRECORD_COUNT, &n);
        if (n < 1) {
		register_error (0, "grtr_sc_create: No data to process.\n");
		if (new_view) dbfree (dbsc);
		return (-1);
        }

	/* Read in data */

	if (tstart == 0.0 && tend == 0.0) {
		dbquery (dbsc, dbRECORD_COUNT, &n);
		for (dbsc.record = 0; dbsc.record < n; dbsc.record++) {
			if (dbgetv (dbsc, 0, "time", &time, "endtime", &endtime, 0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
        		if (tstart == 0.0 && tend == 0.0) {
        			tstart = time;
        			tend = endtime;
			} else {
				if (time < tstart) tstart = time;
				if (endtime > tend) tend = endtime;
			}
		}
	}
        sprintf (time_str, "(%.5f)", tstart);
        sprintf (endtime_str, "(%.5f)", tend);
	dbsc.record = dbALL;
        ret = trload_css (dbsc, time_str, endtime_str, trscgr, "wfdisc", 0);

	/* Split, splice, apply calib */

	if (gap == NULL) strcpy (string, "seg");
	else strcpy (string, gap);
	if (!strcmp(string, "leave")) {
	} else if (!strcmp(string, "seg")) {
		trsplit (*trscgr, 0, 0);
		trsplice (*trscgr, 0.5, 0, 0);
	} else if (!strcmp(string, "interp")) {
		register_error (0, "grtr_sc_create: gap value '%s' not implemented yet.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	} else if (!strcmp(string, "zero")) {
		register_error (0, "grtr_sc_create: gap value '%s' not implemented yet.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	} else if (!strcmp(string, "drop")) {
		trsplit (*trscgr, 0, 0);
		trsplice (*trscgr, 0.5, 0, 0);
		crunch = 0;
		dbquery (*trscgr, dbRECORD_COUNT, &n);
		strcpy (sta2, "");
		strcpy (chan2, "");
		n2 = 0;
		db = *trscgr;
		for (trscgr->record=0; trscgr->record<n; (trscgr->record)++) {
			if (dbgetv (*trscgr, 0, "sta", sta, "chan", chan,
					0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
			if (strcmp(sta, sta2) || strcmp(chan, chan2)) {
				if (n2 > 1) {
        				for (db.record = is; db.record < is+n2; db.record++) {
        					trfree (db);
        					crunch = 1;
        				}
				}
				n2 = 1;
				is = trscgr->record;
				strcpy (sta2, sta);
				strcpy (chan2, chan);
				continue;
        		}
        		n2++;
		}
		if (n2 > 1) {
       			for (db.record = is; db.record < is+n2; db.record++) {
       				trfree (db);
       				crunch = 1;
       			}
		}
		if (crunch) {
			dbcrunch (db);
		}
	} else {
		register_error (0, "grtr_sc_create: Illegal gap value '%s'.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	}
	if (calib) trapply_calib (*trscgr);

	/* Read in instrument responses. */

	if (ir )
	{
	/* Run this section if instrument response is to be loaded */
	    dbsc.record = 0;
	    if (dbgetv (dbsc, 0, "instrument.inid", &i, 0) != dbINVALID && i >= 0) {
		dbquery (*trscgr, dbRECORD_COUNT, &n);
		dbquery (dbsc, dbRECORD_COUNT, &n2);
		for (trscgr->record=0; trscgr->record<n; (trscgr->record)++) {
			if (dbgetv (*trscgr, 0, "sta", sta, "chan", chan,
					"time", &time, 0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
			for (dbsc.record=0; dbsc.record<n2; dbsc.record++) {
				if (dbgetv (dbsc, 0, "sta", sta2, "chan", chan2,
					"time", &time2, "endtime", &endtime2, 0) == dbINVALID) {
        				register_error (0, "grtr_sc_create: dbgetv() error.\n");
					if (new_view) dbfree (dbsc);
        				return (-1);
				}
				if (strcmp(sta, sta2)) continue;
				if (strcmp(chan, chan2)) continue;
				if (time < time2) continue;
				if (time >= endtime2) continue;
				dbextfile (dbsc, "instrument", string);
				resp = (Response *) getarr (resp_arr, string);
				dbputv (*trscgr, 0, "response", resp, 0);
				break;
			}
		}
	    }
	}
	clear_register (0);
	if (new_view) dbfree (dbsc);

	/* Normal exit. */

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

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

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


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

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

			case 'p':
				pfname= optarg ;
				break;

			case 's':
				subset = optarg ; 
				break ;

			case 't':
				triggertimestring = optarg ; 
				break ;

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

			default:
				errflg++;
				break ;
		}
    }

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

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

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

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

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

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

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

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

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

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

	newFileHeader(&myhdr, pf, sta);

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

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

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

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

	channelBitmap=chanbitmap(nrecords);

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

	}

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

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

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

    tr.table = dbALL ;
    trfree(tr) ;
    pffree(pf) ; 
    return 0;
}