Beispiel #1
0
    parser.add_argument('-i','--id', dest='eventid',
                        help='Output data in EHDF format')
    
    args = parser.parse_args()

    if args.limitContributor is not None:
        contriblist = checkContributors()
        if args.limitContributor not in contriblist:
            print 'Cannot restrict to contributor %s, as it is not in the list of valid contributors.'
            for c in contriblist:
                print '\t%s' % c
            sys.exit(1)
        
    
    eventlist = getPhaseData(bounds=args.bounds,radius=args.radius,starttime=args.startTime,
                             endtime=args.endTime,magrange=args.magRange,catalog=args.catalog,
                             contributor=args.contributor,eventid=args.eventid)
    if not len(eventlist):
        sys.stderr.write('No events found.  Exiting.\n')
        sys.exit(0)
        
    for event in eventlist:
        if args.limitContributor is not None:
            if not event.eventcode.startswith(args.limitContributor):
                continue
        if args.format == 'isf':
            text = event.renderISF()
        elif args.format == 'ehdf':
            text = event.renderEHDF()
        print text
        
Beispiel #2
0
    parser.add_argument('-i','--id', dest='eventid',
                        help='Output data in EHDF format')
    
    args = parser.parse_args()

    if args.limitContributor is not None:
        contriblist = checkContributors()
        if args.limitContributor not in contriblist:
            print 'Cannot restrict to contributor %s, as it is not in the list of valid contributors.'
            for c in contriblist:
                print '\t%s' % c
            sys.exit(1)
        
    
    eventlist = getPhaseData(bounds=args.bounds,radius=args.radius,starttime=args.startTime,
                             endtime=args.endTime,magrange=args.magRange,catalog=args.catalog,
                             contributor=args.contributor,eventid=args.eventid)
    if not len(eventlist):
        sys.stderr.write('No events found.  Exiting.\n')
        sys.exit(0)
        
    for event in eventlist:
        if args.limitContributor is not None:
            if not event.eventcode.startswith(args.limitContributor):
                continue
        if args.format == 'isf':
            text = event.renderISF()
        elif args.format == 'ehdf':
            text = event.renderEHDF()
        print text
        
Beispiel #3
0
def main(args):
    eventid = args.id
    radius = args.radius
    #does the bayesloc folder exist?
    if not os.path.isdir(BAYESDIR):
        print FOLDER_ERROR
        sys.exit(1)
    bayesbin = os.path.join(BAYESDIR,'bin',BAYESBIN)
    ttimes = glob.glob(os.path.join(BAYESDIR,'ttimes','ak135.*'))
    if not os.path.isfile(bayesbin):
        print FOLDER_ERROR
        sys.exit(1)
    if not len(ttimes):
        print FOLDER_ERROR
        sys.exit(1)
    bayesdb = os.path.join(BAYESDIR,BAYESDB)
    # if startOver and os.path.isfile(bayesdb):
    #     os.remove(bayesdb)
    #does the database exist - if not, create it
    if not os.path.isfile(bayesdb):
        db = sqlite3.connect(bayesdb)
        cursor = db.cursor()
        createTables(db,cursor)
    else:
        db = sqlite3.connect(bayesdb)
        cursor = db.cursor()

    #Delete selected list of events
    if args.delete:
        nevents = deleteEvents(db,cursor,args.delete)
        print '%i events deleted from the database.' % nevents
        sys.exit(0)
        
    #Return some stats about the current database
    if args.stats:
        nevents,nstations,narrivals = getStats(cursor)
        print 'Your database contains information about:'
        print '\t%i events' % nevents
        print '\t%i stations' % nstations
        print '\t%i picks' % narrivals
        sys.exit(0)
        
    eventinfo = getPhaseData(eventid=eventid)
    if not len(eventinfo):
        print 'Could not find event %s in ComCat.  Returning.'
        sys.exit(1)

    #get the information about the input event
    eventinfo = eventinfo[0]
    eventlat = eventinfo.origins[0]['lat']
    eventlon = eventinfo.origins[0]['lon']
    eventtime = eventinfo.origins[0]['time']
    if eventtime < args.begindate or eventtime > args.enddate:
        fmt = 'Event %s (%s) is outside the time bounds you specified. %s to %s.  Exiting.' 
        print fmt % (eventinfo.eventcode,eventtime,args.begindate,args.enddate)
        sys.exit(1)

    tnow = datetime.utcnow()
    eventfolder = os.path.join(BAYESDIR,'events',eventid)
    if not os.path.isdir(eventfolder):
        os.makedirs(eventfolder)

    # eventlist1 = getEventData(radius=(eventlat,eventlon,0,radius),
    #                          starttime=args.begindate,
    #                          endtime=args.enddate,catalog='pde')
    eventlist = getEventData(radius=(eventlat,eventlon,0,radius),
                              starttime=args.begindate,
                              endtime=args.enddate,catalog='us')
    #eventlist = eventlist1 + eventlist2

    if args.count:
        fmt = 'There are %i events inside %.1f km radius around event %s (%.4f,%.4f)'
        print fmt % (len(eventlist),radius,eventid,eventlat,eventlon)
        sys.exit(0)
    
    #check to see if event has already been located - if so, stop, unless we're being forced
    if not args.force:
        sql = 'SELECT id,code,rlat,rlon,rdepth,rtime FROM event WHERE code="%s"' % eventid
        cursor.execute(sql)
        row = cursor.fetchone()
        if row is not None and row[2] is not None:
            print 'Event %s is already in the database.  Stopping.' % eventid
            sys.exit(0)
    
    priors = getEventPriors(eventlist,cursor)
    stations,arrivals,newevents = getProcessedData(eventlist,db,cursor,ndays=NWEEKS*7)
    fmt = 'In database: %i stations, %i arrivals.  %i events not in db.'
    #print fmt % (len(stations),len(arrivals),len(newevents))
    missing_stations = []
    for event in newevents:
        phasedata = getPhaseData(eventid=event)
        if phasedata is None:
            continue
        if not len(phasedata[0].magnitudes):
            continue
        newstations,newarrivals,ms = insertPhaseData(phasedata[0],db,cursor)
        stations = dict(stations.items() + newstations.items())
        arrivals += newarrivals
        missing_stations += ms

    print 'After searching online:'
    fmt = 'In database: %i stations, %i arrivals.  %i missing stations.'
    print fmt % (len(stations),len(arrivals),len(missing_stations))
    stafile = 'station.dat'
    stationfile = os.path.join(eventfolder,stafile)
    f = open(stationfile,'wt')
    f.write('sta_id lat lon elev\n')
    for stationcode,stationvals in stations.iteritems():
        slat,slon,elev = stationvals
        f.write('%s %.4f %.4f %.3f\n' % (stationcode,slat,slon,elev))
    f.close()

    arrfile = 'arrival.dat'
    arrivalfile = os.path.join(eventfolder,arrfile)
    f = open(arrivalfile,'wt')
    f.write('ev_id sta_id phase time\n')
    for arrival in arrivals:
        eid,scode,phase,time = arrival
        f.write('%i %s %s %.3f\n' % (eid,scode,phase,time))
    f.close()

    prifile = 'prior.dat' #??
    priorfile = os.path.join(eventfolder,prifile)
    f = open(priorfile,'wt')
    f.write('ev_id lat_mean lon_mean dist_sd depth_mean depth_sd time_mean time_sd\n')
    for prior in priors:
        evid,plat,plon,pdepth,ptime = prior
        f.write('%i %.4f %.4f 0.0 %.1f 0.0 %.3f 0.0\n' % (evid,plat,plon,pdepth,ptime))
    f.close()

    #write the config file
    configfile = os.path.join(eventfolder,'bayesloc.cfg')
    config = CONFIG.replace('BAYESLOC',BAYESLOC)
    config = config.replace('EVENTFOLDER',eventfolder)
    fcfg = open(configfile,'wt')
    fcfg.write(config)
    fcfg.close()

    #Run the BayesLoc program
    #change to the eventfolder
    cwd = os.getcwd()
    os.chdir(eventfolder)
    bayesbin = os.path.join(BAYESLOC,'bin','bayesloc')
    cmd = '%s %s' % (bayesbin,configfile)
    print 'Running command %s...' % cmd
    t1 = datetime.now()
    # process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
    # for c in iter(lambda: process.stdout.read(1), ''):
    #     sys.stderr.write(c)
    res,stdout,stderr = getCommandOutput(cmd)
    t2 = datetime.now()
    if not res:
        print 'BayesLoc command "%s" failed.  \n%s\n%s.' % (cmd,stdout,stderr)
        sys.exit(1)
    else:
        dt = ((t2-t1).seconds)/60.0
        print 'BayesLoc command was successful - took %.1f minutes.' % dt
    os.chdir(cwd)

    resultfile = os.path.join(eventfolder,'output','origins_ned_stats.out')
    f = open(resultfile,'rt')
    f.readline()
    eventlist = []
    fieldlist = ['lat','lon','depth','time','rlat','rlon','rdepth','rtime','mag','nevents']
    nevents = len(priors) + len(newevents)
    for line in f.readlines():
        parts = line.split()
        eid = int(parts[0])
        lat = float(parts[1])
        lon = float(parts[2])
        depth = float(parts[3])
        time = UTCDateTime(float(parts[4])).datetime
        efmt = 'UPDATE event set rlat=%.4f,rlon=%.4f,rdepth=%.1f,rtime="%s",nevents=%i WHERE id=%i'
        equery = efmt % (lat,lon,depth,time,nevents,eid)
        cursor.execute(equery)
        db.commit()
        query = 'SELECT %s FROM event WHERE id=%i' % (','.join(fieldlist),eid)
        cursor.execute(query)
        row = cursor.fetchone()
        eventlist.append(dict(zip(fieldlist,row)))
    f.close()

    #make a map of all the relocated events
    fname = makeMap(eventlist,eventlat,eventlon,eventfolder)
    print 'Relocated events: %s' % fname
    
    #tell the user what happened with the relocation
    fmt = 'SELECT lat,lon,depth,time,rlat,rlon,rdepth,rtime,nevents FROM event WHERE code="%s"'
    query = fmt % (eventid)
    cursor.execute(query)
    row = cursor.fetchone()
    lat,lon,depth,time,rlat,rlon,rdepth,rtime,nevents = row
    time = UTCDateTime(time).datetime
    rtime = UTCDateTime(rtime).datetime
    if rtime >= time:
        dt = (rtime-time).seconds + ((rtime-time).microseconds)/float(1e6)
    else:
        dt = (time-rtime).seconds + ((time-rtime).microseconds)/float(1e6)
    dd,az1,az2 = gps2DistAzimuth(lat,lon,rlat,rlon)
    dd /= 1000.0
    print 'Event %s was relocated using %i events.' % (eventid,nevents)
    print 'Starting:  %s (%.4f,%.4f) %.1f km' % (time.strftime('%Y-%m-%d %H:%M:%S'),lat,lon,depth)
    print 'Relocated: %s (%.4f,%.4f) %.1f km' % (rtime.strftime('%Y-%m-%d %H:%M:%S'),rlat,rlon,rdepth)
    print '%.1f km (%.1f degrees), %.1f seconds' % (dd,az1,dt)
    cursor.close()
    db.close()