Example #1
0
def get_metadata(data_source, network, station, location, channel, starttime,
                 endtime):
    invselect = locals()
    del (invselect['data_source'])
    [(key, value)] = data_source.items()

    if key == 'local':
        inv = read_inventory(value, 'STATIONXML')
        inv = inv.select(**invselect)

    elif key == 'fdsn':
        cl = RoutingClient(value)
        #cl = fdsn_client(value)
        inv = cl.get_stations(**invselect, level='response')

    else:
        print('meta-data source should be "local" or "fdsn"')
        inv = []
    return inv
def get_data(data_source, inventory, starttime, endtime, margin_t=10):
    """
    """
    [(key, value)] = data_source.items()

    stream = Stream()
    for ms in stream:
        samp_rate = ms.stats.delta
        ms.trim(starttime, endtime - samp_rate)

    if key == 'local':
        cl = sds_client(value)
    elif key == 'fdsn':
        cl = RoutingClient(value)
        #cl = fdsn_client(value)

    for net in inventory:
        for sta in net:
            for cha in sta:
                try:
                    st = cl.get_waveforms(network=net.code,
                                          station=sta.code,
                                          location=cha.location_code,
                                          channel=cha.code,
                                          starttime=starttime - margin_t,
                                          endtime=endtime + margin_t)
                    stream += st
                except ValueError as e:
                    print(e)
                    pass

    for ms in stream:
        samp_rate = ms.stats.delta
        ms.trim(starttime, endtime - samp_rate)

    return stream
Example #3
0
    with open(catalogue,'r') as fid:
        temp=fid.readlines()
# read catalogue lines into a py container and make the directories
catList=[ UTCDateTime(x.strip()[:23]) for x in temp]
#catList.sort() # sort the origin times
latList=[]; lonList=[]
try:
    latList=[float(x[23:].split()[0]) for x in temp]
    lonList=[float(x[23:].split()[1]) for x in temp]
except:
    stations="*"
pathDict=makeEventFolders(catList,destination)
# get module and connect to client
if "iris-federator" == provider or "eida-routing" == provider:
    from obspy.clients.fdsn import RoutingClient as Client
    client=Client(provider)
else:
    from obspy.clients.fdsn import Client
    client=Client(provider)
# start iterations
for event in catList:
    if isinstance(stations,list):
        if '*' in stations and '*' in networks:
            codeList=getServiceStations(client,event)
        else:
            codeList=[]
            for net in networks:
                if '*' in stations:
                  try:
                    codeList+=getServiceStations(client,event,network=net)
                  except:
Example #4
0
VERDATE = '15/04/2019'
## imports ##
import logging
from obspy import UTCDateTime
if "iris-federator" in nodes or "eida-routing" in nodes:
    from obspy.clients.fdsn import RoutingClient as Client
else:
    from obspy.clients.fdsn import Client
# Logging params
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s')

# setup client #
for node in nodes:
    logging.info("Trying to get information from node '%s'" % node)
    clt = Client(node)
    inv = clt.get_stations(starttime=UTCDateTime(period[0]),
                           endtime=UTCDateTime(period[1]),
                           minlongitude=p1[0],
                           minlatitude=p1[1],
                           maxlongitude=p2[0],
                           maxlatitude=p2[1],
                           level=level)
    try:
        sumInv += inv
    except NameError:
        sumInv = inv

# how many stations did we find?
# correct end times while iterating to avoid bugs with matching metadata
now = UTCDateTime()
starttime = UTCDateTime("2020-01-28 19:15:00")
endtime = starttime + 1200
waveform = client.get_waveforms('IU', 'ANMO', '00', 'LHZ', starttime, endtime)
waveform.plot(size=(1024, 800),
              type='normal',
              automerge=True,
              equal_scale=False,
              starttime=starttime)

# Use wild cards to get data from the iris federator for seismometers near a location in Nepal
print(
    "Plot records from a station near Nepal for the M7.5 earthquake in the Kuril'sk Islands on 2020-02-13 10:33:44"
)
from obspy.clients.fdsn import RoutingClient

client = RoutingClient("iris-federator")
starttime = UTCDateTime("2020-02-13T10:33:44")
lat = 28.0
lon = 84.0
minradius = 0
maxradius = 10
st = client.get_waveforms(channel="BHZ",
                          station="*",
                          network="*",
                          starttime=starttime,
                          endtime=starttime + 1200,
                          latitude=lat,
                          longitude=lon,
                          minradius=minradius,
                          maxradius=maxradius)
print(st.__str__(extended=True))
 def create_client(self, routing_client):
     try:
         return RoutingClient(routing_client)
     except:
         log.error('Couldn\'t connect to %s' % routing_client)
         raise SystemExit
VERDATE = '15/04/2019'
## imports ##
import logging
from obspy import UTCDateTime
if "iris-federator" in nodes or "eida-routing" in nodes:
    from obspy.clients.fdsn import RoutingClient as Client
else:
    from obspy.clients.fdsn import Client
# Logging params
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s')

# setup client #
for node in nodes:
    logging.info("Trying to get information from node '%s'" % node)
    clt = Client(node)
    inv = clt.get_events(starttime=UTCDateTime(period[0]),
                         endtime=UTCDateTime(period[1]),
                         minlongitude=p1[0],
                         minlatitude=p1[1],
                         maxlongitude=p2[0],
                         maxlatitude=p2[1],
                         includearrivals=arrivals)
    try:
        sumInv += inv
    except NameError:
        sumInv = inv
# how many stations found?
logging.info("Found %i events" % len(sumInv))
# write output
sumInv.write(outName, outType)
Example #8
0
def fdsn_serial_parallel(stas_avail, event, input_dics, target_path, req_cli,
                         info_event):
    """
    retrieving data from FDSN
    :param stas_avail:
    :param event:
    :param input_dics:
    :param target_path:
    :param req_cli:
    :param info_event:
    :return:
    """
    print('%s -- event: %s' % (req_cli, target_path))

    if req_cli.lower() in ["iris-federator", "eida-routing"]:
        client_fdsn = RoutingClient(req_cli)
    else:
        client_fdsn = Client_fdsn(base_url=req_cli,
                                  user=input_dics['username_fdsn'],
                                  password=input_dics['password_fdsn'])
        #debug=True)
    client_syngine = Client_syngine()

    if input_dics['req_parallel']:
        if input_dics['password_fdsn']:
            print("[INFO] Restricted data from %s" % req_cli)
            print("[WARNING] parallel retrieving is now possible!")
            print("[WARNING] serial retrieving is activated!")
            # num_req_np = 1
            num_req_np = input_dics['req_np']
        else:
            num_req_np = input_dics['req_np']
        par_jobs = []
        st_counter = 0
        for st_avail in stas_avail:
            st_counter += 1
            info_station = '[%s-%s/%s]' % (info_event, st_counter,
                                           len(stas_avail))
            p = multiprocessing.Process(
                target=fdsn_download_core,
                args=(st_avail, event, input_dics, target_path, client_fdsn,
                      client_syngine, req_cli, info_station))
            par_jobs.append(p)

        sub_par_jobs = []
        for l in range(len(par_jobs)):
            counter = num_req_np
            while counter >= num_req_np:
                counter = 0
                for ll in range(len(sub_par_jobs)):
                    if par_jobs[sub_par_jobs[ll]].is_alive():
                        counter += 1
            par_jobs[l].start()
            sub_par_jobs.append(l)

        counter = num_req_np
        while counter > 0:
            counter = 0
            for ll in range(len(par_jobs)):
                if par_jobs[ll].is_alive():
                    counter += 1
    else:
        st_counter = 0
        for st_avail in stas_avail:
            st_counter += 1
            info_station = '[%s-%s/%s]' % (info_event, st_counter,
                                           len(stas_avail))
            fdsn_download_core(st_avail, event, input_dics, target_path,
                               client_fdsn, client_syngine, req_cli,
                               info_station)

    update_sta_ev_file(target_path, event)

    if input_dics['bulk']:
        input_dics['waveform'] = True
        sta_saved_path = glob.glob(os.path.join(target_path, 'raw', '*.*.*.*'))
        print('\n[INFO] adjusting the station_event file for bulk request...',
              end='')

        sta_saved_list = []
        for sta_num in range(len(sta_saved_path)):
            sta_saved_list.append(os.path.basename(sta_saved_path[sta_num]))

        sta_ev_new = []
        for line in fileinput.FileInput(
                os.path.join(target_path, 'info', 'station_event')):
            line_split = line.split(',')
            if not '%s.%s.%s.%s' \
                    % (line_split[0], line_split[1], line_split[2],
                       line_split[3]) in sta_saved_list:
                pass
            else:
                sta_ev_new.append(line)

        file_staev_open = open(
            os.path.join(target_path, 'info', 'station_event'), 'wt')
        file_staev_open.writelines(sta_ev_new)
        file_staev_open.close()
        print('DONE')
Example #9
0
#Lesson 12: Automated section plotter
from obspy.clients.fdsn import RoutingClient
from obspy import UTCDateTime, Stream
from obspy.geodetics.base import locations2degrees
import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
CLIENT = RoutingClient("iris-federator")
# Set up the event properties from https://earthquake.usgs.gov/earthquakes/eventpage/ci39406880/executive
START_TIME = UTCDateTime("2020-04-27 03:46:00")  # time of the earthquake
EQNAME = "M4 - 13km SW of Searles Valley CA"  # name of the earthquake
EQLAT = 35.674  # latitude of the epicentre
EQLON = -117.496  # longitude of the epicentre
MIN_RADIUS = 0  # minimum radius in degrees
MAX_RADIUS = 5  # maximum radius to search for in degrees
SEPARATION = 0.05  # minimum distance between traces in degrees
EXCLUDE = [
    'BUCR', 'TCHL', 'TWIT', 'JEPS', 'FARB', 'BRK'
]  # list of stations to exclude from the plot for noise or other quality reasons
DURATION = 200  # Duration of trace shown on section in seconds
F1 = 1.0  # Highpass filter corner in Hz
F2 = 6.0  # Lowpass filter corner in Hz
# collect the station data
inventory = CLIENT.get_stations(channel="BHZ",
                                network="*",
                                station="*",
                                starttime=START_TIME - 10,
                                endtime=START_TIME + DURATION + 10,
                                latitude=EQLAT,
                                longitude=EQLON,
                                minradius=MIN_RADIUS,
                                maxradius=MAX_RADIUS)
Example #10
0
import requests
from csv import DictReader
import obspy
from obspy.clients.fdsn import Client
from obspy import UTCDateTime
from obspy.geodetics import gps2dist_azimuth
from obspy.geodetics.base import locations2degrees
from obspy.clients.fdsn import RoutingClient
from obspy.taup import TauPyModel
model = TauPyModel(model='iasp91')
# URL for Geonet Earthquake data
START = '2020-01-01T00:00:00'
END = '2020-07-12T20:30:00'
DURATION = 240
MINMAG = "5.5"
CLIENT = RoutingClient("iris-federator")
data_url = 'https://quakesearch.geonet.org.nz/csv?bbox=164.00391,-49.18170,182.54883,-32.28713&minmag=' + MINMAG + '&startdate=' + START + '&enddate=' + END
# Peform the query
resp = requests.get(data_url)
quakes = list(DictReader(resp.text.splitlines()))
# pick the most recent earthquake
starttime = UTCDateTime(quakes[0]['origintime'])
inventory = CLIENT.get_stations(channel="HHZ",
                                network="NZ",
                                station="*",
                                starttime=starttime,
                                latitude=quakes[0][' latitude'],
                                longitude=quakes[0]['longitude'],
                                minradius=0,
                                maxradius=10)
#print(len(inventory.networks[0]))
    def run_get_waveform(self):
        """
        Get SAC waveforms for an event
        
        basic usage:
        run_get_waveform(event)
        
        c              -  client
        event          -  obspy Event object
        ref_time_place -  reference time and place (other than origin time and place - for station subsetting)
        """

        c = self.client
        event = self.ev
        ref_time_place = self.ref_time_place

        evtime = event.origins[0].time
        reftime = ref_time_place.origins[0].time

        if (self.idb == 1) or (self.idb == 5):
            # 2019-03-12 I added idb #5 here and not in a separate block since
            # the station retrieval is common to #1 and #5 and I rather not repeat the same block.
            # note that CH stations may not provide all sensor metadata (required when using idb #1) and this crashes with later requests in the code
            # another option is to add sta retrieval after #3 below but unsure if this creates conflicts.
            # TODO use 'is' instead of 'in' to avoid wrong calls (eg FZ or GFZ)
            if ("BK" in self.network) or ("BG" in self.network) or (
                    "BP" in self.network):
                # NOTE BK network doesn't return data when using the IRIS client.
                # this option switches to NCEDC if BK is in networkname.
                client_name = "NCEDC"
            elif "CH" in self.network:
                client_name = "ETH"
            elif "GFZ" in self.network:
                client_name = "GFZ"
            elif "Z3" in self.network:  # 2019-07-31 for AlpArray
                client_name = "ORFEUS"
                #client_name = "GFZ"
                #client_name = "ETH"
            elif "IV" in self.network:
                client_name = "INGV"
            elif "DE" in self.network:
                client_name = "EMSC"  # or BGR GFZ LMU ...
            else:
                client_name = "IRIS"  # default

            c = Client(client_name)
            #-----------------------------------------------------------
            # Check if requesting AlpArray data
            # the following are ongoing TESTS (alparray data)
            #c = Client(client_name, password='******')
            #c = Client(client_name, password='******')
            #c = Client(client_name, password='******')
            #c = RoutingClient('iris-federator') # 2019-06-18 This downloads a list of station data, but no waveforms. Also it requires removing radius-related infor (below) and doesn't have a field for eidatoken.
            #c = RoutingClient('iris-federator', credentials={'EIDA_TOKEN': './eidatoken'}, debug=True)
            #c = RoutingClient('iris-federator', credentials={'EIDA_TOKEN': './eidatoken'})
            #c = RoutingClient('eida-routing',   credentials={'EIDA_TOKEN': '/home/calvizur/.eidatoken'}, debug=True) # 2019-07-31 TEST?
            ## try again AlpArray, arclink
            # NB doesnt work. 'response' level is not accepted which means I would have to prepare data manually
            # option: use script similar to Veronica's
            #c = Client(user='******') # test, AlpArray Client
            #c.max_status_requests = 2000
            if "Z3" in self.network:
                # 2019-07-31 WORKS! (bondo event)
                # replace client if requesting AlpArray data
                c = RoutingClient(
                    'iris-federator',
                    credentials={'EIDA_TOKEN': '/home/calvizur/.eidatoken'},
                    debug=True)
            #-----------------------------------------------------------
            print(c)
            print("\n** WARNING ** Preparing request for client", client_name)
            print("Download stations...")
            if "Z3" in self.network:
                # *** alparray only ***
                stations = c.get_stations(network=self.network,
                                          station=self.station,
                                          channel=self.channel,
                                          starttime=reftime - self.tbefore_sec,
                                          endtime=reftime + self.tafter_sec,
                                          level="response")
            else:
                # default
                stations = c.get_stations(
                    network=self.network,
                    station=self.station,
                    channel=self.channel,
                    starttime=reftime - self.tbefore_sec,
                    endtime=reftime + self.tafter_sec,
                    #----------------------------------------------------------
                    # NOTE RoutingClient (AlpArray) does not have the following
                    minlatitude=self.min_lat,
                    maxlatitude=self.max_lat,
                    minlongitude=self.min_lon,
                    maxlongitude=self.max_lon,
                    longitude=self.elon,  # required for maxradius
                    latitude=self.elat,  # required for maxradius 
                    maxradius=18,  # note 18 deg ~ 2000 km
                    #----------------------------------------------------------
                    level="response")
            inventory = stations  # so that llnl and iris scripts can be combined

            if self.ifverbose:
                print("Printing stations")
                print(stations)
                print("Done Printing stations...")

            sta_limit_distance(ref_time_place,
                               stations,
                               min_dist=self.min_dist,
                               max_dist=self.max_dist,
                               min_az=self.min_az,
                               max_az=self.max_az,
                               ifverbose=self.ifverbose)
            #print("Printing stations NEW")
            #print(stations)
            #print("Done Printing stations...")

            #stations.plotprojection="local")
            # Find P and S arrival times
            t1s = []
            t2s = []
            phases = self.phases
            if self.phase_window:

                #model = TauPyModel(model=taupmodel)
                model = TauPyModel(model=self.taupmodel)

                for net in stations:
                    for sta in net:
                        dist, az, baz = obspy.geodetics.gps2dist_azimuth(
                            event.origins[0].latitude,
                            event.origins[0].longitude, sta.latitude,
                            sta.longitude)
                        dist_deg = kilometer2degrees(dist / 1000, radius=6371)
                        Phase1arrivals = model.get_travel_times(
                            source_depth_in_km=event.origins[0].depth / 1000,
                            distance_in_degree=dist_deg,
                            phase_list=[phases[0]])
                        if len(Phase1arrivals) == 0:
                            if phases[0] == "P":
                                phases[0] = "p"
                            elif phases[0] == "p":
                                phases[0] = "P"
                            elif phases[0] == "S":
                                phases[0] = "s"
                            elif phases[0] == "s":
                                phases[0] = "S"
                            Phase1arrivals = model.get_travel_times(
                                source_depth_in_km=event.origins[0].depth /
                                1000,
                                distance_in_degree=dist_deg,
                                phase_list=[phases[0]])

                        Phase2arrivals = model.get_travel_times(
                            source_depth_in_km=event.origins[0].depth / 1000,
                            distance_in_degree=dist_deg,
                            phase_list=[phases[1]])
                        if len(Phase2arrivals) == 0:
                            if phases[1] == "P":
                                phases[1] = "p"
                            elif phases[1] == "p":
                                phases[1] = "P"
                            elif phases[1] == "S":
                                phases[1] = "s"
                            elif phases[1] == "s":
                                phases[1] = "S"
                            Phase2arrivals = model.get_travel_times(
                                source_depth_in_km=event.origins[0].depth /
                                1000,
                                distance_in_degree=dist_deg,
                                phase_list=[phases[1]])

                        #somearr = model.get_travel_times(source_depth_in_km=event.origins[0].depth/1000,distance_in_degree=dist_deg)
                        #print("Print arrivals")
                        #print(somearr)

                        try:
                            if Phase2arrivals[0].time < Phase1arrivals[0].time:
                                # You are assuming that the first index is the first arrival.  Check this later.
                                t1s.append(event.origins[0].time +
                                           Phase2arrivals[0].time -
                                           self.tbefore_sec)
                                t2s.append(event.origins[0].time +
                                           Phase1arrivals[0].time +
                                           self.tafter_sec)
                            else:
                                t1s.append(event.origins[0].time +
                                           Phase1arrivals[0].time -
                                           self.tbefore_sec)
                                t2s.append(event.origins[0].time +
                                           Phase2arrivals[0].time +
                                           self.tafter_sec)
                        except:
                            t1s.append(reftime - self.tbefore_sec)
                            t2s.append(reftime + self.tafter_sec)

            else:
                t1s = [reftime - self.tbefore_sec]
                t2s = [reftime + self.tafter_sec]

            print("Downloading waveforms...")
            # this needs to change
            bulk_list = make_bulk_list_from_stalist(stations,
                                                    t1s,
                                                    t2s,
                                                    channel=self.channel)

            stream_raw = c.get_waveforms_bulk(bulk_list)
            # save ev_info object
            pickle.dump(
                self,
                open(self.evname + '/' + self.evname + '_ev_info.obj', 'wb'))

        elif self.idb == 3:
            client_name = "LLNL"
            print("Preparing request for LLNL ...")

            # Get event an inventory from the LLNL DB.
            event_number = int(event.event_descriptions[0].text)
            # event = llnl_db_client.get_obspy_event(event)
            inventory = c.get_inventory()

            nsta_llnl = len(inventory.get_contents()["stations"])
            print("--> Total stations in LLNL DB: %i" % nsta_llnl)
            sta_limit_distance(event,
                               inventory,
                               min_dist=self.min_dist,
                               max_dist=self.max_dist,
                               min_az=self.min_az,
                               max_az=self.max_az)
            print("--> Stations after filtering for distance: %i" %
                  (len(inventory.get_contents()["stations"])))

            stations = set([sta.code for net in inventory for sta in net])

            _st = c.get_waveforms_for_event(event_number)
            stream_raw = obspy.Stream()
            for tr in _st:
                if tr.stats.station in stations:
                    stream_raw.append(tr)

        #-----------------------------------------------------------
        elif self.idb == 99:
            # IRIS federator to figure out who has waveform data for that
            # particular query and subsequently call the individual data
            # centers to actually get the data.
            # https://docs.obspy.org/packages/obspy.clients.fdsn.html
            print("Preparing request through iris-federator")
            c = RoutingClient('iris-federator', debug=True)
            stations = c.get_stations(
                #network     = self.network,
                #station     = self.station,
                channel=self.channel,
                starttime=reftime - self.tbefore_sec,
                endtime=reftime + self.tafter_sec,
                #minlatitude = self.min_lat,
                #maxlatitude = self.max_lat,
                #minlongitude = self.min_lon,
                #maxlongitude = self.max_lon,
                longitude=self.elon,  # required for maxradius
                latitude=self.elat,  # required for maxradius 
                #maxradius   = 18,         # note 18 deg ~ 2000 km
                maxradius=18,  # note 18 deg ~ 2000 km
                level="response")
            print("Downloading waveforms...")
            # this needs to change
            bulk_list = make_bulk_list_from_stalist(stations,
                                                    t1s,
                                                    t2s,
                                                    channel=self.channel)

            stream_raw = c.get_waveforms_bulk(bulk_list)
            # save ev_info object
            pickle.dump(
                self,
                open(self.evname + '/' + self.evname + '_ev_info.obj', 'wb'))
        #-----------------------------------------------------------

        # set reftime
        stream = obspy.Stream()
        stream = set_reftime(stream_raw, evtime)

        print("--> Adding SAC metadata...")
        if self.ifverbose: print(inventory)
        st2 = add_sac_metadata(stream,
                               idb=self.idb,
                               ev=event,
                               stalist=inventory,
                               taup_model=self.taupmodel,
                               phases=phases,
                               phase_write=self.write_sac_phase)

        # Do some waveform QA
        do_waveform_QA(st2, client_name, event, evtime, self.tbefore_sec,
                       self.tafter_sec)

        if self.demean:
            st2.detrend('demean')

        if self.detrend:
            st2.detrend('linear')

        if self.remove_response:
            resp_plot_remove(st2, self.ipre_filt, self.pre_filt,
                             self.iplot_response, self.scale_factor, stations,
                             self.outformat, self.ifverbose)
        else:
            # output RAW waveforms
            decon = False
            print("WARNING -- NOT correcting for instrument response")

        if self.ifFilter:
            prefilter(st2, self.f1, self.f2, self.zerophase, self.corners,
                      self.filter_type)

        if self.scale_factor > 0:
            amp_rescale(st2, self.scale_factor)
            if self.idb == 3:
                amp_rescale_llnl(st2, self.scale_factor)

        # Set the sac header KEVNM with event name
        # This applies to the events from the LLNL database
        # NOTE this command is needed at the time of writing files, so it has to
        # be set early
        st2, evname_key = rename_if_LLNL_event(st2, evtime)
        self.evname = evname_key

        # save station plot
        # Note: Plotted are stations in the inventory and NOT the ones with the traces
        # It could be possible that there might not be waveforms for some of these stations.
        try:
            fig = inventory.plot(projection="local",
                                 resolution="i",
                                 label=False,
                                 show=False)
            Catalog([self.ev]).plot(fig=fig,
                                    outfile=self.evname + '/station_map.pdf')
        except:
            print("There is a problem with creating the station map!")

        # Get list of unique stations + locaiton (example: 'KDAK.00')
        stalist = []
        for tr in stream.traces:
            if self.ifverbose: print(tr)
            station_key = "%s.%s.%s.%s" % (tr.stats.network, tr.stats.station,
                                           tr.stats.location,
                                           tr.stats.channel[:-1])
            stalist.append(station_key)

        # Crazy way of getting a unique list of stations
        stalist = list(set(stalist))

        #  Resample
        if self.resample_TF == True:
            # NOTE !!! tell the user if BOTH commands are disabled NOTE !!!
            if (client_name == "IRIS"):
                resample(st2, freq=self.resample_freq)
            elif (client_name == "LLNL"):
                resample_cut(st2, self.resample_freq, evtime, self.tbefore_sec,
                             self.tafter_sec)
        else:
            print(
                "WARNING. Will not resample. Using original rate from the data"
            )

        # match start and end points for all traces
        st2 = trim_maxstart_minend(stalist, st2, client_name, event, evtime,
                                   self.resample_TF, self.resample_freq,
                                   self.tbefore_sec, self.tafter_sec,
                                   self.ifverbose)
        if len(st2) == 0:
            raise ValueError("no waveforms left to process!")

        # save raw waveforms in SAC format
        if self.isave_raw:
            path_to_waveforms = evname_key + "/RAW"
            write_stream_sac_raw(stream_raw,
                                 path_to_waveforms,
                                 evname_key,
                                 self.idb,
                                 event,
                                 stations=inventory)

        # Taper waveforms (optional; Generally used when data is noisy- example: HutchisonGhosh2016)
        # https://docs.obspy.org/master/packages/autogen/obspy.core.trace.Trace.taper.html
        # To get the same results as the default taper in SAC, use max_percentage=0.05 and leave type as hann.
        if self.taper:
            st2.taper(max_percentage=self.taper,
                      type='hann',
                      max_length=None,
                      side='both')

        # save processed waveforms in SAC format
        # evname_key/RAW_processed = traces after waveform_QA + demean + detrend +
        #                            resample + remove response + filtering +
        #                            resampling + scaling + tapering
        # NOTE: The orientation is same as that of extracted waveforms
        #       Waveforms are rotated to ENZ, in case they are not already orientated,
        #       in the next step (self.rotateRTZ)
        if self.isave_raw_processed:
            path_to_waveforms = os.path.join(evname_key, 'RAW_processed')
            write_stream_sac(st2, path_to_waveforms, evname_key)

        # Rotate to ENZ (save: optional)
        #if self.rotateENZ:
        st2 = rotate2ENZ(st2, evname_key, self.isave_ENZ, self.icreateNull,
                         self.ifverbose)

        # rotate to UVW and save
        if self.rotateUVW:
            rotate2UVW(st2, evname_key)

        # Rotate to RTZ and save
        if self.rotateRTZ:
            rotate2RTZ(st2, evname_key, self.ifverbose)

        # save CAP weight files
        if self.output_cap_weight_file:
            write_cap_weights(st2, evname_key, client_name, event,
                              self.ifverbose)

        # save event info
        if self.output_event_info:
            write_ev_info(event, evname_key)

        # Plot spectrograms
        if self.ifplot_spectrogram:
            plot_spectrogram(st2, evname_key)

        # save pole zero file (Needed for MouseTrap)
        if self.ifsave_sacpaz:
            write_resp(inventory, evname_key)

        # save station inventory as XML file
        if self.ifsave_stationxml:
            xmlfilename = evname_key + "/stations.xml"
            try:
                inventory.write(xmlfilename,
                                format="stationxml",
                                validate=True)
            except:
                print('Could not create stationxml file')
        print("### DEBUG ###")
st.remove_response(inventory=inventory, water_level=20)
st.plot()

# If you have time, assemble and plot another similar dataset (e.g. like before stations at a certain distance from a big event, or use Transportable Array data for a big event, etc.)

# #### Routed/Federated Clients
#
# Finally, all of the above queries can not only be directed at one specific data center, but instead can be sent to either ..
#
#  * [IRIS Federator](https://service.iris.edu/irisws/fedcatalog/1/), or
#  * [EIDA routing](http://www.orfeus-eu.org/data/eida/webservices/routing/) service
#
# .. to query data across all existing FDSN web service data centers (or at least those registered with IRIS/EIDA).
# These federation/routing services support station lookup and waveform request queries.
#
# This example queries the IRIS Federator which in turn combines data from all other FDSN web service data centers.

# +
from obspy.clients.fdsn import RoutingClient

client = RoutingClient('iris-federator')  # or use 'eida-routing' for the EIDA routing service

# Tohoku Earthquake
t = obspy.UTCDateTime('2011-03-11T14:46:24+09')

st = client.get_waveforms(
    channel="LHZ", starttime=t, endtime=t+20,
    latitude=50, longitude=14, maxradius=10)
print(st)
Example #13
0
def fdsn_available(input_dics, cl, event, target_path):
    """
    check the availablity of FDSN stations
    :param input_dics:
    :param cl:
    :param event:
    :param target_path:
    :return:
    """
    print("check the availability: %s" % input_dics['data_source'][cl])

    if input_dics['username_fdsn']:
        include_restricted = True
    else:
        include_restricted = None

    sta_fdsn = []
    try:
        if input_dics['data_source'][cl].lower() in ["iris-federator", "eida-routing"]:
            client_fdsn = RoutingClient(input_dics['data_source'][cl].lower())

            available = client_fdsn.get_stations(
                network=input_dics['net'],
                station=input_dics['sta'],
                location=input_dics['loc'],
                channel=input_dics['cha'],
                starttime=event['t1'],
                endtime=event['t2'],
                level='channel')

        else:
            client_fdsn = Client_fdsn(
                base_url=input_dics['data_source'][cl].upper(),
                user=input_dics['username_fdsn'],
                password=input_dics['password_fdsn'])

            available = client_fdsn.get_stations(
                network=input_dics['net'],
                station=input_dics['sta'],
                location=input_dics['loc'],
                channel=input_dics['cha'],
                starttime=event['t1'],
                endtime=event['t2'],
                latitude=input_dics['lat_cba'],
                longitude=input_dics['lon_cba'],
                minradius=input_dics['mr_cba'],
                maxradius=input_dics['Mr_cba'],
                minlatitude=input_dics['mlat_rbb'],
                maxlatitude=input_dics['Mlat_rbb'],
                minlongitude=input_dics['mlon_rbb'],
                maxlongitude=input_dics['Mlon_rbb'],
                includerestricted=include_restricted,
                level='channel')

        for network in available.networks:
            for station in network:
                for channel in station:
                    st_id = '%s_%s_%s_%s' % (network.code,
                                             station.code,
                                             channel.location_code,
                                             channel.code)
                    sta_fdsn.append([network.code, station.code,
                                     channel.location_code, channel.code,
                                     channel.latitude, channel.longitude,
                                     channel.elevation, channel.depth,
                                     input_dics['data_source'][cl], st_id,
                                     channel.azimuth, channel.dip])

        if input_dics['bulk']:
            print('creating a list for bulk request...')
            bulk_list = []
            for bulk_sta in sta_fdsn:
                if input_dics['cut_time_phase']:
                    t_start, t_end = calculate_time_phase(event, bulk_sta)
                else:
                    t_start = event['t1']
                    t_end = event['t2']
                bulk_list.append((bulk_sta[0], bulk_sta[1], bulk_sta[2],
                                  bulk_sta[3], t_start, t_end))

            bulk_list_fio = open(os.path.join(
                target_path, 'info',
                'bulkdata_list_%s' % input_dics['data_source'][cl]), 'ab+')
            pickle.dump(bulk_list, bulk_list_fio, protocol=2)
            bulk_list_fio.close()

    except Exception as error:
        exc_file = open(os.path.join(target_path, 'info', 'exception'), 'at+')
        ee = 'availability -- %s -- %s\n' % (input_dics['data_source'][cl],
                                             error)
        exc_file.writelines(ee)
        exc_file.close()
        print('ERROR: %s' % ee)
        return []

    if len(sta_fdsn) == 0:
        sta_fdsn = []
    sta_fdsn.sort()
    return sta_fdsn
#Lesson 12b: Automated section plotter with arrival lines that doesn't download excess traces
from obspy.clients.fdsn import RoutingClient
from obspy import UTCDateTime, Stream
from obspy.geodetics.base import locations2degrees
import matplotlib.pyplot as plt
from matplotlib.transforms import blended_transform_factory
from obspy.taup import TauPyModel
from matplotlib import cm
from numpy import linspace
CLIENT = RoutingClient("iris-federator")
# Set up the event properties from https://earthquake.usgs.gov/earthquakes/eventpage/ci39406880/executive
START_TIME = UTCDateTime("2020-04-27 03:46:00")  # time of the earthquake
EQNAME = "M4 - 13km SW of Searles Valley CA"  # name of the earthquake
EQLAT = 35.674  # latitude of the epicentre
EQLON = -117.496  # longitude of the epicentre
EVT_Z = 8.8
MIN_RADIUS = 0  # minimum radius in degrees
MAX_RADIUS = 5  # maximum radius to search for in degrees
SEPARATION = 0.05  # minimum distance between traces in degrees
EXCLUDE = ['BUCR', 'TCHL', 'TWIT', 'JEPS', 'FARB', 'BRK',
           'BABI']  # list of stations to exclude from the plot for noise
EXCLUDE += [
    'B917', 'MCA', 'WCT', 'POC', 'SCH', 'WMD', 'ORC', 'MGN', 'ANT', 'ADH',
    'HCK', 'LHV', 'BHU', 'BHP', 'FLV', 'BEN', 'BON', 'MCC', 'LUL', 'CPX',
    'REDF', 'MPT', 'GVAR1'
]
DURATION = 200  # Duration of trace shown on section in seconds
F1 = 1.0  # Highpass filter corner in Hz
F2 = 6.0  # Lowpass filter corner in Hz
PHASES = ["P", "S"]  # list of phases for which to compute theoretical times
PHASE_PLOT = "line"  # choose lines or spots for phases