Esempio n. 1
0
def get_line_parallels(pts, rngkm):
    from obspy.core.util.geodetics import gps2DistAzimuth
    from oq_tools import reckon

    # set outputs
    posazpts = []
    negazpts = []

    for j, pt in enumerate(pts):
        # if 1st point
        if j == 0:
            rngm, az, baz = gps2DistAzimuth(pts[j][1], pts[j][0], \
                                            pts[j+1][1], pts[j+1][0])

        # if last point
        elif j == len(pts) - 1:
            rngm, az, baz = gps2DistAzimuth(pts[j-1][1], pts[j-1][0], \
                                            pts[j][1], pts[j][0])

        # use points either side (assumes evenly spaced)
        else:
            rngm, az, baz = gps2DistAzimuth(pts[j-1][1], pts[j-1][0], \
                                            pts[j+1][1], pts[j+1][0])

        # get azimuth for new points
        azpos = az + 90.
        azneg = az - 90.
        # get points
        posazpts.append(reckon(pts[j][1], pts[j][0], rngkm, azpos))
        negazpts.append(reckon(pts[j][1], pts[j][0], rngkm, azneg))

    return posazpts, negazpts
Esempio n. 2
0
def get_line_parallels(pts, rngkm):
    from obspy.core.util.geodetics import gps2DistAzimuth
    from mapping_tools import reckon
    '''
    pts are an N x [lon, lat] matrix, i.e.:
                   [[lon1, lat1],
                    [lon2, lat2]]
    '''
    # set outputs
    posazpts = []
    negazpts = []

    for j, pt in enumerate(pts):
        # if 1st point
        if j == 0:
            rngm, az, baz = gps2DistAzimuth(pts[j][1], pts[j][0], \
                                            pts[j+1][1], pts[j+1][0])

        # if last point
        elif j == len(pts) - 1:
            rngm, az, baz = gps2DistAzimuth(pts[j-1][1], pts[j-1][0], \
                                            pts[j][1], pts[j][0])

        # use points either side (assumes evenly spaced)
        else:
            rngm, az, baz = gps2DistAzimuth(pts[j-1][1], pts[j-1][0], \
                                            pts[j+1][1], pts[j+1][0])

        # get azimuth for new points
        azpos = az + 90.
        azneg = az - 90.
        # get points
        posazpts.append(reckon(pts[j][1], pts[j][0], rngkm, azpos))
        negazpts.append(reckon(pts[j][1], pts[j][0], rngkm, azneg))
    '''    
    # for testing only
    x=[]
    y=[]
    xx=[]
    yy=[]
    xxx=[]
    yyy=[]
    for j, pt in enumerate(pts):
        x.append(pt[0])
        y.append(pt[1])
        xx.append(posazpts[j][0])
        yy.append(posazpts[j][1])
        xxx.append(negazpts[j][0])
        yyy.append(negazpts[j][1])
        
    plt.plot(x,y,'b-')
    plt.plot(xx,yy,'r-')
    plt.plot(xxx,yyy,'g-')
    plt.show()
    '''
    return posazpts, negazpts
Esempio n. 3
0
    def process_function(st, inv):
        st.detrend("linear")
        st.detrend("demean")
        st.taper(max_percentage=0.05, type="hann")

        st.attach_response(inv)
        st.remove_response(output="DISP", pre_filt=pre_filt, zero_mean=False,
                           taper=False)

        st.detrend("linear")
        st.detrend("demean")
        st.taper(max_percentage=0.05, type="hann")

        st.interpolate(sampling_rate=sampling_rate, starttime=starttime,
                       npts=npts)

        station_latitude = inv[0][0].latitude
        station_longitude = inv[0][0].longitude
        _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude,
                                    event_latitude, event_longitude)

        components = [tr.stats.channel[-1] for tr in st]
        if "N" in components and "E" in components:
            st.rotate(method="NE->RT", back_azimuth=baz)

        # Convert to single precision to save space.
        for tr in st:
            tr.data = np.require(tr.data, dtype="float32")

        return st
Esempio n. 4
0
def StDistandAzi(traces, hyp, dir):
    '''
    Given a list with st ids, a tuple with 
    (lat, lon, depth) of the hypocentre and 
    thw directory with the xml metafiles; it returns 
    dictionary with the distance and the azimuth of
    each station       
       
    '''
    Stdistribution = {}
    for trid in traces:     
            
        metafile = dir + "META." + trid + ".xml"
        META = DU.getMetadataFromXML(metafile)[trid]
        lat = META['latitude']
        lon = META['longitude']            
        dist = locations2degrees(hyp[0],hyp[1],lat,lon)                                
        azi =  -np.pi/180.*gps2DistAzimuth(lat,lon,
                   hyp[0],hyp[1])[2]
        Stdistribution[trid] = {'azi' : azi, 'dist' : dist} 

    
    #~ fig = plt.figure()  
    #~ plt.rc('grid', color='#316931', linewidth=1, linestyle='-')
    #~ plt.show()
    
    return Stdistribution
Esempio n. 5
0
 def test_issue_375(self):
     """
     Test for #375.
     """
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 + 1)
     self.assertEqual(round(azim, 0), 32)
     self.assertEqual(round(bazim, 0), 213)
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 - 1)
     self.assertEqual(round(azim, 0), 328)
     self.assertEqual(round(bazim, 0), 147)
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 + 1)
     self.assertEqual(round(azim, 0), 147)
     self.assertEqual(round(bazim, 0), 327)
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 - 1)
     self.assertEqual(round(azim, 0), 213)
     self.assertEqual(round(bazim, 0), 33)
Esempio n. 6
0
def StDistandAzi(traces, hyp, dir):
    '''
    Given a list with st ids, a tuple with 
    (lat, lon, depth) of the hypocentre and 
    thw directory with the xml metafiles; it returns 
    dictionary with the distance and the azimuth of
    each station       
       
    '''
    Stdistribution = {}
    for trid in traces:

        metafile = dir + "META." + trid + ".xml"
        META = DU.getMetadataFromXML(metafile)[trid]
        lat = META['latitude']
        lon = META['longitude']
        dist = locations2degrees(hyp[0], hyp[1], lat, lon)
        azi = -np.pi / 180. * gps2DistAzimuth(lat, lon, hyp[0], hyp[1])[2]
        Stdistribution[trid] = {'azi': azi, 'dist': dist}

    #~ fig = plt.figure()
    #~ plt.rc('grid', color='#316931', linewidth=1, linestyle='-')
    #~ plt.show()

    return Stdistribution
Esempio n. 7
0
 def test_issue_375(self):
     """
     Test for #375.
     """
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 + 1)
     self.assertEqual(round(azim, 0), 32)
     self.assertEqual(round(bazim, 0), 213)
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 - 1)
     self.assertEqual(round(azim, 0), 328)
     self.assertEqual(round(bazim, 0), 147)
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 + 1)
     self.assertEqual(round(azim, 0), 147)
     self.assertEqual(round(bazim, 0), 327)
     _, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 - 1)
     self.assertEqual(round(azim, 0), 213)
     self.assertEqual(round(bazim, 0), 33)
Esempio n. 8
0
def src2sta(station_file,source):
    '''
    Compute cartesian source to station distances and azimuths for all station/source pairs.
    
    IN:
        station_file: Path to station file
        source: numpy 1d array with source info read from file
        coord_type: =0 if coordinates are cartesian, =1 if they are lat/lon
    OUT:
        d - sorted distances vector in km
        az - azimuth from source to station in degrees
    '''
    
    from numpy import genfromtxt,zeros,array
    from obspy.core.util.geodetics import gps2DistAzimuth
    
    
    #Read station file
    #staname=genfromtxt(home+station_file,dtype="S6",usecols=0)
    x=genfromtxt(station_file,dtype="f8",usecols=1)
    y=genfromtxt(station_file,dtype="f8",usecols=2)
    if x.shape==() or y.shape==(): #Single station file
        x=array([x])
        y=array([y])
    d=zeros(x.shape)
    az=zeros(x.shape)
    baz=zeros(x.shape)
    xs=source[1]
    ys=source[2]
    for k in range(len(x)):
        d[k],az[k],baz[k]=gps2DistAzimuth(ys,xs,y[k],x[k])
    d=d/1000
    return d,az
Esempio n. 9
0
def rotate_stream(st, event_latitude, event_longitude,
                  station_latitude=None, station_longitude=None,
                  inventory=None, mode="ALL"):
    """
    Rotate a stream to radial and transverse components based on the
    station information and event information

    :param st: input stream
    :type st: obspy.Stream
    :param event_latitude: event latitude
    :type event_latitude: float
    :param event_longitude: event longitude
    :type event_longitude: float
    :param station_latitude: station latitude. If not provided, extract
        information from inventory
    :type station_latitude: float
    :param station_longitude: station longitude. If not provided, extrace
        information from inventory
    :type station_longitude: float
    :param inv: station inventory information. If you want to rotate
    "12" components, you need to provide inventory since only station
    and station_longitude is not enough.
    :type inv: obspy.Inventory
    :param mode: rotation mode, could be one of:
        1) "NE": rotate only North and East channel to RT
        2) "12": rotate only 1 and 2 channel, like "BH1" and "BH2" to RT
        3) "all": rotate all components to RT
    :return: rotated stream(obspy.Stream)
    """

    if station_longitude is None or station_latitude is None:
        station_latitude = float(inventory[0][0].latitude)
        station_longitude = float(inventory[0][0].longitude)

    mode = mode.upper()
    if mode not in ["NE", "ALL", "12"]:
        raise ValueError("rotate_stream supports mode: 1) 12; 2) NE; 3) ALL")
    if mode == "12" and inventory is None:
        raise ValueError("Mode '12' required inventory(stationxml) "
                         "information provided")

    _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude,
                                event_latitude, event_longitude)

    components = [tr.stats.channel[-1] for tr in st]

    if mode in ["NE", "ALL"]:
        if "N" in components and "E" in components:
            try:
                st.rotate(method="NE->RT", back_azimuth=baz)
            except Exception as e:
                print e

    if mode in ["12", "ALL"]:
        if "1" in components and "2" in components:
            try:
                rotate_12_RT_func(st, inventory, back_azimuth=baz)
            except Exception as e:
                print e
Esempio n. 10
0
def distance(lat1, lon1, lat2, lon2):
    from obspy.core.util.geodetics import gps2DistAzimuth

    rngm, az, baz = gps2DistAzimuth(lat1, lon1, lat2, lon2)

    rngkm = rngm / 1000.

    return rngkm, az, baz
Esempio n. 11
0
File: rfstream.py Progetto: seism/rf
def rfstats(stats=None, event=None, station=None, stream=None,
            phase='P', dist_range=None):
    """
    Calculate ray specific values like slowness for given event and station.

    :param stats: stats object with event and/or station attributes. Can be
        None if both event and station are given.
    :param event: ObsPy :class:`~obspy.core.event.Event` object
    :param station: station object with attributes latitude, longitude and
        elevation
    :param stream: If a stream is given, stats has to be None. In this case
        rfstats will be called for every stats object in the stream.
    :param phase: string with phase to look for in result of
        :func:`~obspy.taup.taup.getTravelTimes`. Usually this will be 'P' or
        'S' for P and S receiver functions, respectively.
    :type dist_range: tuple of length 2
    :param dist_range: if epicentral of event is not in this intervall, None
        is returned by this function,\n
        if phase == 'P' defaults to (30, 90),\n
        if phase == 'S' defaults to (50, 85)

    :return: ``stats`` object with event and station attributes, distance,
        back_azimuth, inclination, onset and slowness or None if epicentral
        distance is not in the given intervall
    """
    if stream is not None:
        assert stats is None
        for tr in stream:
            rfstats(tr.stats, event, station, None, phase, dist_range)
        return
    phase = phase.upper()
    if dist_range is None and phase in 'PS':
        dist_range = (30, 90) if phase == 'P' else (50, 85)
    if stats is None:
        stats = AttribDict({})
    stats.update(obj2stats(event=event, station=station))
    dist, baz, _ = gps2DistAzimuth(stats.station_latitude,
                                   stats.station_longitude,
                                   stats.event_latitude,
                                   stats.event_longitude)
    dist = kilometer2degrees(dist / 1000)
    if dist_range and not dist_range[0] <= dist <= dist_range[1]:
        return
    tts = getTravelTimes(dist, stats.event_depth)
    tts2 = getTravelTimes(dist, 0)
    tts = [tt for tt in tts if tt['phase_name'] == phase]
    tts2 = [tt for tt in tts2 if tt['phase_name'] == phase]
    if len(tts) == 0 or len(tts2) == 0:
        raise Exception('Taup does not return phase %s at event distance %s' %
                        (phase, dist))
    onset = stats.event_time + tts[0]['time']
    inc = tts2[0]['take-off angle']  # approximation
    v = 5.8 if 'P' in phase else 3.36  # iasp91
    slowness = 6371. * sin(pi / 180. * inc) / v / 180 * pi
    stats.update({'distance': dist, 'back_azimuth': baz, 'inclination': inc,
                  'onset': onset, 'slowness': slowness})
    return stats
Esempio n. 12
0
 def test_issue_375(self):
     """
     Test for #375.
     """
     if not HAS_GEOGRAPHICLIB:
         return
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 + 1)
     self.assertEqual(round(azim, 0), 32)
     self.assertEqual(round(bazim, 0), 213)
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 - 1)
     self.assertEqual(round(azim, 0), 328)
     self.assertEqual(round(bazim, 0), 147)
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 + 1)
     self.assertEqual(round(azim, 0), 147)
     self.assertEqual(round(bazim, 0), 327)
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 - 1)
     self.assertEqual(round(azim, 0), 213)
     self.assertEqual(round(bazim, 0), 33)
Esempio n. 13
0
 def test_issue_375(self):
     """
     Test for #375.
     """
     if not HAS_GEOGRAPHICLIB:
         return
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 + 1)
     self.assertEqual(round(azim, 0), 32)
     self.assertEqual(round(bazim, 0), 213)
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 + 1, 10 - 1)
     self.assertEqual(round(azim, 0), 328)
     self.assertEqual(round(bazim, 0), 147)
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 + 1)
     self.assertEqual(round(azim, 0), 147)
     self.assertEqual(round(bazim, 0), 327)
     dist, azim, bazim = gps2DistAzimuth(50, 10, 50 - 1, 10 - 1)
     self.assertEqual(round(azim, 0), 213)
     self.assertEqual(round(bazim, 0), 33)
Esempio n. 14
0
def rotate_subs(st, stationxmldir, event_loc):

    # event info
    event_latitude = event_loc[0]
    event_longitude = event_loc[1]

    # station info
    nw = st[0].stats.network
    sta = st[0].stats.station
    stationxmlfile = os.path.join(stationxmldir, "%s.%s.xml" % (nw, sta))
    inv = read_inventory(stationxmlfile)
    station_latitude = float(inv[0][0].latitude)
    station_longitude = float(inv[0][0].longitude)
    _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude, event_latitude, event_longitude)

    components = [tr.stats.channel[-1] for tr in st]
    print "components:", components
    if "N" in components and "E" in components:
        _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude, event_latitude, event_longitude)
        st.rotate(method="NE->RT", back_azimuth=baz)
Esempio n. 15
0
def az3(sfile):
	azDic = {}
	evtlat,evtlon = evcor(sfile) #Obteniendo las coordenadas del evento del sfile en decimal
	print evtlat, evtlon
	infile = open(sfile,'rU') #Entrando al sfile
	for line in infile:

		if line[9:11] == 'ES':
			#print 'Dentro del if'
			station_name = line[1:6].split(' ')[0]
			Baz = gps2DistAzimuth(lat1=stacor('corstations.txt')[station_name][0], lon1=stacor('corstations.txt')[station_name][1], lat2=evtlat, lon2=evtlon)
			azDic[station_name] = Baz[1]
	return azDic
Esempio n. 16
0
def plot_transect(path,N,tsunlims,dlims,dt,xyannot):
    '''
    Plot snapshots along a transect
    '''
    from obspy.core.util.geodetics import gps2DistAzimuth
    from string import rjust
    from numpy import genfromtxt,zeros
    from matplotlib import pyplot as plt
    import matplotlib
    
    font = {'family' : 'normal','size'   : 14}

    matplotlib.rc('font', **font)
    trench_index=395 #Where is trench
    cut_index=160 #Where is land
    trench_index=trench_index-cut_index
    fig, axarr = plt.subplots(N, 1) 
    for k in range(N):
        time=k*dt
        trackname='AA.f'+rjust(str(k+1),4,'0')+'.track'
        t=genfromtxt(path+trackname)
        t=t[cut_index:,:]
        lon1=t[trench_index,0]
        lat1=t[trench_index,1]
        d=zeros(len(t))
        for n in range(len(t)):
            d[n],Az,BAz=gps2DistAzimuth(lat1,lon1,t[n,1],t[n,0])
        d=d/1000
        d[0:trench_index]=-d[0:trench_index]
        tstring=str(time)+'s'
        #Plot
        ax=axarr[k]
        ax.plot(d,t[:,2],'r',lw=2)
        ax.set_ylim(tsunlims)
        ax.set_xlim(dlims)
        ax.grid(which='both')
        ax.yaxis.set_ticklabels(['',0,'',10,'',20,''])
        if k!=N-1:
            ax.xaxis.set_ticklabels([])
        ax.annotate(tstring,xy=xyannot,fontsize=14)
        if k==N-1:
            ax.xaxis.set_label('Distance from trench (km)')
            print t[0,0]
            print t[-1,0]
            print t[0,1]
            print t[-1,1]
    plt.subplots_adjust(left=0.2, bottom=0.1, right=0.8, top=0.9, wspace=0, hspace=0)
        
        
    
    
Esempio n. 17
0
def plot_transect(path, N, tsunlims, dlims, dt, xyannot):
    '''
    Plot snapshots along a transect
    '''
    from obspy.core.util.geodetics import gps2DistAzimuth
    from numpy import genfromtxt, zeros
    from matplotlib import pyplot as plt
    import matplotlib

    font = {'family': 'normal', 'size': 14}

    matplotlib.rc('font', **font)
    trench_index = 395  #Where is trench
    cut_index = 160  #Where is land
    trench_index = trench_index - cut_index
    fig, axarr = plt.subplots(N, 1)
    for k in range(N):
        time = k * dt
        trackname = 'AA.f' + str(k + 1).rjust(4, '0') + '.track'
        t = genfromtxt(path + trackname)
        t = t[cut_index:, :]
        lon1 = t[trench_index, 0]
        lat1 = t[trench_index, 1]
        d = zeros(len(t))
        for n in range(len(t)):
            d[n], Az, BAz = gps2DistAzimuth(lat1, lon1, t[n, 1], t[n, 0])
        d = d / 1000
        d[0:trench_index] = -d[0:trench_index]
        tstring = str(time) + 's'
        #Plot
        ax = axarr[k]
        ax.plot(d, t[:, 2], 'r', lw=2)
        ax.set_ylim(tsunlims)
        ax.set_xlim(dlims)
        ax.grid(which='both')
        ax.yaxis.set_ticklabels(['', 0, '', 10, '', 20, ''])
        if k != N - 1:
            ax.xaxis.set_ticklabels([])
        ax.annotate(tstring, xy=xyannot, fontsize=14)
        if k == N - 1:
            ax.xaxis.set_label('Distance from trench (km)')
            print(t[0, 0])
            print(t[-1, 0])
            print(t[0, 1])
            print(t[-1, 1])
    plt.subplots_adjust(left=0.2,
                        bottom=0.1,
                        right=0.8,
                        top=0.9,
                        wspace=0,
                        hspace=0)
def calculate_local_magnitude(eventLat, eventLon, sta_lat, sta_lon, ampl):
    #print "Try"
    epi_dist, az, baz = gps2DistAzimuth(eventLat, eventLon, float(sta_lat), float(sta_lon))
    epi_dist = epi_dist / 1000
    #print "Azi dist", epi_dist
    if epi_dist > 60:
        a = 0.0037
        b = 3.02
    else:
        a = 0.018
        b = 2.17
    ml = log10(ampl * 1000) + a * epi_dist + b
    #print 'magnitude', ml
    return ml
Esempio n. 19
0
def calculate_baz(elat, elon, slat, slon):
    """
    Calculate back azimuth

    :param elat: event latitude
    :param elon: event longitude
    :param slat: station latitude
    :param slon: station longitude
    :return: back azimuth
    """

    _, _, baz = gps2DistAzimuth(elat, elon, slat, slon)

    return baz
Esempio n. 20
0
def calculate_baz(elat, elon, slat, slon):
    """
    Calculate back azimuth

    :param elat: event latitude
    :param elon: event longitude
    :param slat: station latitude
    :param slon: station longitude
    :return: back azimuth
    """

    _, baz, _ = gps2DistAzimuth(elat, elon, slat, slon)

    return baz
Esempio n. 21
0
    def get_location_info(self, cmtsource):
        """
        calculating azimuth and distance, and then store it

        :param cmtsource: cmt source
        :return:
        """
        self.event_latitude = cmtsource.latitude
        self.event_longitude = cmtsource.longitude
        # calculate location
        dist_in_m, az, baz = gps2DistAzimuth(
            self.event_latitude, self.event_longitude,
            self.latitude, self.longitude)
        self.dist_in_km = dist_in_m / 1000.0
        self.azimuth = az
Esempio n. 22
0
def inrange(center_lat, center_lon, event_lat, event_lon, dist_range):
    """
    Checks if event location is inside the range (in km) from the
    center location defined by the user
    """

    dist = obspy_geo.gps2DistAzimuth(center_lat, center_lon, event_lat,
                                     event_lon)

    dist = float(dist[0] / 1000.0)

    if dist <= dist_range:
        return True
    else:
        return False
Esempio n. 23
0
 def test_gps2DistAzimuthWithGeographiclib(self):
     """
     Testing gps2DistAzimuth function using the module geographiclib.
     """
     # nearly antipodal points
     result = gps2DistAzimuth(15.26804251, 2.93007342, -14.80522806,
                              -177.2299081)
     self.assertAlmostEqual(result[0], 19951425.048688546)
     self.assertAlmostEqual(result[1], 8.65553241932755)
     self.assertAlmostEqual(result[2], 351.36325485132306)
     # out of bounds
     self.assertRaises(ValueError, gps2DistAzimuth, 91, 0, 0, 0)
     self.assertRaises(ValueError, gps2DistAzimuth, -91, 0, 0, 0)
     self.assertRaises(ValueError, gps2DistAzimuth, 0, 0, 91, 0)
     self.assertRaises(ValueError, gps2DistAzimuth, 0, 0, -91, 0)
Esempio n. 24
0
def calculate_local_magnitude(eventLat, eventLon, sta_lat, sta_lon, ampl):
    #print "Try"
    epi_dist, az, baz = gps2DistAzimuth(eventLat, eventLon, float(sta_lat),
                                        float(sta_lon))
    epi_dist = epi_dist / 1000
    #print "Azi dist", epi_dist
    if epi_dist > 60:
        a = 0.0037
        b = 3.02
    else:
        a = 0.018
        b = 2.17
    ml = log10(ampl * 1000) + a * epi_dist + b
    #print 'magnitude', ml
    return ml
Esempio n. 25
0
 def test_gps2DistAzimuthWithGeographiclib(self):
     """
     Testing gps2DistAzimuth function using the module geographiclib.
     """
     # nearly antipodal points
     result = gps2DistAzimuth(15.26804251, 2.93007342, -14.80522806,
                              -177.2299081)
     self.assertAlmostEqual(result[0], 19951425.048688546)
     self.assertAlmostEqual(result[1], 8.65553241932755)
     self.assertAlmostEqual(result[2], 351.36325485132306)
     # out of bounds
     self.assertRaises(ValueError, gps2DistAzimuth, 91, 0, 0, 0)
     self.assertRaises(ValueError, gps2DistAzimuth, -91, 0, 0, 0)
     self.assertRaises(ValueError, gps2DistAzimuth, 0, 0, 91, 0)
     self.assertRaises(ValueError, gps2DistAzimuth, 0, 0, -91, 0)
Esempio n. 26
0
    def process_function(st, inv):
        st.detrend("linear")
        st.detrend("demean")
        st.taper(max_percentage=0.05, type="hann")

        # Perform a frequency domain taper like during the response removal
        # just without an actual response...
        for tr in st:
            data = tr.data.astype(np.float64)

            # smart calculation of nfft dodging large primes
            from obspy.signal.util import _npts2nfft
            nfft = _npts2nfft(len(data))

            fy = 1.0 / (tr.stats.delta * 2.0)
            freqs = np.linspace(0, fy, nfft // 2 + 1)

            # Transform data to Frequency domain
            data = np.fft.rfft(data, n=nfft)
            data *= c_sac_taper(freqs, flimit=pre_filt)
            data[-1] = abs(data[-1]) + 0.0j
            # transform data back into the time domain
            data = np.fft.irfft(data)[0:len(data)]
            # assign processed data and store processing information
            tr.data = data

        st.detrend("linear")
        st.detrend("demean")
        st.taper(max_percentage=0.05, type="hann")

        st.interpolate(sampling_rate=sampling_rate,
                       starttime=starttime,
                       npts=npts)

        components = [tr.stats.channel[-1] for tr in st]
        if "N" in components and "E" in components:
            station_latitude = inv[0][0].latitude
            station_longitude = inv[0][0].longitude
            _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude,
                                        event_latitude, event_longitude)

            st.rotate(method="NE->RT", back_azimuth=baz)

        # Convert to single precision to save space.
        for tr in st:
            tr.data = np.require(tr.data, dtype="float32")

        return st
    def process_function(st, inv):
        st.detrend("linear")
        st.detrend("demean")
        st.taper(max_percentage=0.05, type="hann")

        # Perform a frequency domain taper like during the response removal
        # just without an actual response...
        for tr in st:
            data = tr.data.astype(np.float64)

            # smart calculation of nfft dodging large primes
            from obspy.signal.util import _npts2nfft
            nfft = _npts2nfft(len(data))

            fy = 1.0 / (tr.stats.delta * 2.0)
            freqs = np.linspace(0, fy, nfft // 2 + 1)

            # Transform data to Frequency domain
            data = np.fft.rfft(data, n=nfft)
            data *= c_sac_taper(freqs, flimit=pre_filt)
            data[-1] = abs(data[-1]) + 0.0j
            # transform data back into the time domain
            data = np.fft.irfft(data)[0:len(data)]
            # assign processed data and store processing information
            tr.data = data

        st.detrend("linear")
        st.detrend("demean")
        st.taper(max_percentage=0.05, type="hann")

        st.interpolate(sampling_rate=sampling_rate, starttime=starttime,
                       npts=npts)

        components = [tr.stats.channel[-1] for tr in st]
        if "N" in components and "E" in components:
            station_latitude = inv[0][0].latitude
            station_longitude = inv[0][0].longitude
            _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude,
                                        event_latitude, event_longitude)

            st.rotate(method="NE->RT", back_azimuth=baz)

        # Convert to single precision to save space.
        for tr in st:
            tr.data = np.require(tr.data, dtype="float32")

        return st
Esempio n. 28
0
def rotate_one_station_stream(st,
                              event_latitude,
                              event_longitude,
                              station_latitude=None,
                              station_longitude=None,
                              inventory=None,
                              mode="ALL->RT"):

    mode = mode.upper()
    mode_options = ["NE->RT", "ALL->RT", "12->RT", "RT->NE"]
    if mode not in mode_options:
        raise ValueError("rotate_stream mode(%s) should be within %s" %
                         (mode, mode_options))

    if station_latitude is None or station_longitude is None:
        nw = st[0].stats.network
        station = st[0].stats.station
        _inv = inventory.select(network=nw, station=station)
        try:
            station_latitude = float(_inv[0][0].latitude)
            station_longitude = float(_inv[0][0].longitude)
        except Exception as err:
            print("Error extracting station('%s.%s') info:%s" %
                  (nw, station, err))
            return

    _, _, baz = gps2DistAzimuth(event_latitude, event_longitude,
                                station_latitude, station_longitude)

    components = [tr.stats.channel[-1] for tr in st]

    if mode in ["NE->RT", "ALL->RT"]:
        if "N" in components and "E" in components:
            try:
                st.rotate(method="NE->RT", back_azimuth=baz)
            except Exception as e:
                print("Error rotating NE->RT:%s" % e)

    if mode in ["12->RT", "ALL->RT"]:
        if "1" in components and "2" in components:
            try:
                rotate_12_RT_func(st, inventory, back_azimuth=baz)
            except Exception as e:
                print("Error rotating 12->RT:%s" % e)

    if mode in ["RT->NE"]:
        st.rotate(method="RT->NE", back_azimuth=baz)
Esempio n. 29
0
 def getMatchingEvent(self, xmldata, utctime, lat, lon, timewindow,
                      distwindow):
     root = minidom.parseString(xmldata)
     table = root.getElementsByTagName('table')[0]
     events = []
     matchingEvent = None
     for tr in table.childNodes:
         if tr.nodeName != 'tr':
             continue
         #now we're in an event
         colidx = 0
         event = {}
         for td in tr.childNodes:
             if td.nodeName != 'td':
                 continue
             if colidx == 1:
                 anchor = td.getElementsByTagName('a')[0]
                 event['href'] = anchor.getAttribute('href')
                 event['id'] = anchor.firstChild.data
             if colidx == 2:
                 datestr = td.firstChild.data
             if colidx == 3:
                 timestr = td.firstChild.data[0:8]
                 event['time'] = datetime.strptime(datestr + ' ' + timestr,
                                                   TIMEFMT)
             if colidx == 4:
                 event['lat'] = float(td.firstChild.data)
             if colidx == 5:
                 event['lon'] = float(td.firstChild.data)
             if colidx == 7:
                 event['mag'] = float(td.firstChild.data)
                 break
             colidx += 1
         if event['time'] > utctime:
             dt = event['time'] - utctime
         else:
             dt = utctime - event['time']
         dtsecs = dt.days * 86400 + dt.seconds
         dd, az1, az2 = gps2DistAzimuth(lat, lon, event['lat'],
                                        event['lon'])
         dd = dd / 1000.0
         if dtsecs < timewindow and dd < distwindow:
             print 'The most likely matching event is %s' % event['id']
             matchingEvent = event.copy()
             break
     return matchingEvent
Esempio n. 30
0
    def get_station_info(self, datalist):
        """
        Using the event location and station information to
        calculate azimuth and distance
        !!! Obsolete, not used any more !!!

        :param datalist: data dictionary(referred to pycmt3d.Window.datalist)
        :return:
        """
        # this might be related to datafile type(sac, mseed or asdf)
        event_lat = self.cmtsource.latitude
        event_lon = self.cmtsource.longitude
        # station location from synthetic file
        sta_lat = datalist['synt'].stats.sac['stla']
        sta_lon = datalist['synt'].stats.sac['stlo']
        dist_in_m, az, baz = \
            gps2DistAzimuth(event_lat, event_lon, sta_lat, sta_lon)
        return [dist_in_m / 1000.0, az]
Esempio n. 31
0
def calculateDistAzm(station_list, origin):
    """
    Calculates the distance and the azimuth between stream and origin
    stream_list = list of objects of class stream
    origin = object of class origin
    """

    for station in station_list:
        _result = obspy_geo.gps2DistAzimuth(origin.latitude, origin.longitude,
                                            station.latitude,
                                            station.longitude)

        if _result:
            station.distance_by_origin = float(_result[0] / 1000.0)
            station.azimuth_by_origin = _result[1]

    # removes stations with no streams
    return station_list
Esempio n. 32
0
def rotate_one_station_stream(st, event_latitude, event_longitude,
                              station_latitude=None, station_longitude=None,
                              inventory=None, mode="ALL->RT"):

    mode = mode.upper()
    mode_options = ["NE->RT", "ALL->RT", "12->RT", "RT->NE"]
    if mode not in mode_options:
        raise ValueError("rotate_stream mode(%s) should be within %s"
                         % (mode, mode_options))

    if station_latitude is None or station_longitude is None:
        nw = st[0].stats.network
        station = st[0].stats.station
        _inv = inventory.select(network=nw, station=station)
        try:
            station_latitude = float(_inv[0][0].latitude)
            station_longitude = float(_inv[0][0].longitude)
        except Exception as err:
            print("Error extracting station('%s.%s') info:%s"
                  % (nw, station, err))
            return

    _, _, baz = gps2DistAzimuth(event_latitude, event_longitude,
                                station_latitude, station_longitude)

    components = [tr.stats.channel[-1] for tr in st]

    if mode in ["NE->RT", "ALL->RT"]:
        if "N" in components and "E" in components:
            try:
                st.rotate(method="NE->RT", back_azimuth=baz)
            except Exception as e:
                print("Error rotating NE->RT:%s" % e)

    if mode in ["12->RT", "ALL->RT"]:
        if "1" in components and "2" in components:
            try:
                rotate_12_RT_func(st, inventory, back_azimuth=baz)
            except Exception as e:
                print("Error rotating 12->RT:%s" % e)

    if mode in ["RT->NE"]:
        st.rotate(method="RT->NE", back_azimuth=baz)
Esempio n. 33
0
 def getMatchingEvent(self,xmldata,utctime,lat,lon,timewindow,distwindow):
     root = minidom.parseString(xmldata)
     table = root.getElementsByTagName('table')[0]
     events = []
     matchingEvent = None
     for tr in table.childNodes:
         if tr.nodeName != 'tr':
             continue
         #now we're in an event
         colidx = 0
         event = {}
         for td in tr.childNodes:
             if td.nodeName != 'td':
                 continue
             if colidx == 1:
                 anchor = td.getElementsByTagName('a')[0]
                 event['href'] = anchor.getAttribute('href')
                 event['id'] = anchor.firstChild.data
             if colidx == 2:
                 datestr = td.firstChild.data
             if colidx == 3:
                 timestr = td.firstChild.data[0:8]
                 event['time'] = datetime.strptime(datestr + ' '+timestr,TIMEFMT)
             if colidx == 4:
                 event['lat'] = float(td.firstChild.data)
             if colidx == 5:
                 event['lon'] = float(td.firstChild.data)
             if colidx == 7:
                 event['mag'] = float(td.firstChild.data)
                 break
             colidx += 1
         if event['time'] > utctime:
             dt = event['time'] - utctime
         else:
             dt = utctime - event['time']
         dtsecs = dt.days*86400 + dt.seconds
         dd,az1,az2 = gps2DistAzimuth(lat,lon,event['lat'],event['lon'])
         dd = dd/1000.0
         if dtsecs < timewindow and dd < distwindow:
             print 'The most likely matching event is %s' % event['id']
             matchingEvent = event.copy()
             break
     return matchingEvent
Esempio n. 34
0
File: main.py Progetto: preinh/RF
def event2stats(lat, lon, event, phase='P', dist_range=(30, 90)):
    phase = phase.upper()
    ori = event.origins[0]
    dist, baz, _ = gps2DistAzimuth(lat, lon,
                                   ori.latitude, ori.longitude)
    dist = kilometer2degrees(dist / 1000)
    if not dist_range[0] <= dist <= dist_range[1]:
        return
    tts = getTravelTimes(dist, ori.depth)
    tts2 = getTravelTimes(dist, 0)
    tts = [tt for tt in tts if tt['phase_name'] == phase]
    tts2 = [tt for tt in tts2 if tt['phase_name'] == phase]
    if len(tts) == 0 or len(tts2) == 0:
        raise Exception('Taup does not return phase %s at event distance %s' %
                        (phase, dist))
    onset = event.origins[0].time + tts[0]['time']
    inc = tts2[0]['take-off angle']  # approximation
    return AttribDict({'dist':dist, 'back_azimuth':baz, 'inclination': inc,
                       'onset':onset})
Esempio n. 35
0
 def checkCatalog(self,time,lat,lon,timewindow,distwindow):
     stime = time - timedelta(seconds=NZCATWINDOW)
     etime = time + timedelta(seconds=NZCATWINDOW)
     url = CATBASE.replace('[START]',stime.strftime(TIMEFMT))
     url = url.replace('[END]',etime.strftime(TIMEFMT))
     try:
         fh = urllib.request.urlopen(url)
         data = fh.read().decode('utf-8')
         fh.close()
         lines = data.split('\n')
         vectors = []
         eidlist = []
         etimelist = []
         for line in lines[1:]:
             if not len(line.strip()):
                 break
             #time is column 2, longitude is column 4, latitude is column 5
             parts = line.split(',')
             eid = parts[0]
             etime = datetime.strptime(parts[2][0:19],TIMEFMT)
             elat = float(parts[5])
             elon = float(parts[4])
             if etime > time:
                 dt = etime - time
             else:
                 dt = time - etime
             nsecs = dt.days*86400 + dt.seconds
             dd,az1,az2 = gps2DistAzimuth(lat,lon,elat,elon)
             dd = dd/1000.0
             if nsecs <= timewindow and dd < distwindow:
                 vectors.append(np.sqrt(nsecs**2+dd**2))
                 eidlist.append(eid)
                 etimelist.append(etime)
         if len(vectors):
             idx = vectors.index(min(vectors))
             return (eidlist[idx],etimelist[idx])
     except Exception as msg:
         raise Exception('Could not access the GeoNet website - got error "%s"' % str(msg))
     return (None,None)
Esempio n. 36
0
    def plot_all(self, directory, sf=1e5, component='x'):
        import seismograms as s
        import matplotlib.pylab as plt
        from obspy.core.util.geodetics import gps2DistAzimuth
        from obspy.core.util.geodetics import kilometer2degrees

        for i in range(0, self.n_recs):
            a = s.ses3d_seismogram()
            a.read(directory, self.recs[i])

            #determine epicentral distance
            dist_az = gps2DistAzimuth((90.0 - a.rx), a.ry, (90.0 - a.sx), a.sy)
            back_az = dist_az[1]
            delta_deg = kilometer2degrees(dist_az[0] / 1000.0)

            if (component == 'x'):
                plt.plot(a.trace_x * sf + delta_deg, a.t, 'k')
            elif (component == 'y'):
                plt.plot(a.trace_y * sf + delta_deg, a.t, 'k')
            elif (component == 'z'):
                plt.plot(a.trace_z * sf + delta_deg, a.t, 'k')

        plt.show()
Esempio n. 37
0
def write2sac(d, header, evla, evlo, evdp, mag, output):
    sacio = SacIO()
    sacio.fromarray(d)
    # set the date to today
    sacio.SetHvalue('nzyear',header['nzyear'])
    sacio.SetHvalue('nzjday',header['nzjday'])
    sacio.SetHvalue('delta',0.02)
    sacio.SetHvalue('nzhour',header['nzhour'])
    sacio.SetHvalue('nzmin',header['nzmin'])
    sacio.SetHvalue('nzsec',header['nzsec'])
    sacio.SetHvalue('nzmsec',header['nzmsec'])
    sacio.SetHvalue('kstnm',header['stnm'])
    sacio.SetHvalue('stla',header['stla'])
    sacio.SetHvalue('stlo',header['stlo'])
    sacio.SetHvalue('kcmpnm',header['comp'])
    sacio.SetHvalue('evla',evla)
    sacio.SetHvalue('evlo',evlo)
    sacio.SetHvalue('evdp',evdp)
    sacio.SetHvalue('mag',mag)
    
    #dist = sacio.GetHvalue('dist')
    #print dist
    dist = gps2DistAzimuth(stla, stlo, evla, evlo)[0] /1000.
    sacio.SetHvalue('dist',dist)
    
    #sacio.SetHvalue('knetwk','phones')
    #sacio.SetHvalue('kstnm',phone)
    #sacio.SetHvalue('kcmpnm',comp)
    #sacio.SetHvalue('kevnm',loc)
    #sacio.SetHvalue('kuser0',test + ' test')
    #sacio.SetHvalue('kuser0',version)
    #sacio.SetHvalue('kuser1',brand)
    #set the type of the dependent variable as acceleration nm/sec/sec
    #sacio.SetHvalue('idep',8)
                    
    sacio.WriteSacBinary(output)
Esempio n. 38
0
   def plot_all(self,directory,sf=1e5,component='x'):
      import seismograms as s   
      import matplotlib.pylab as plt
      from obspy.core.util.geodetics import gps2DistAzimuth
      from obspy.core.util.geodetics import kilometer2degrees


      for i in range(0,self.n_recs):
         a = s.ses3d_seismogram()
         a.read(directory,self.recs[i])

         #determine epicentral distance
         dist_az   = gps2DistAzimuth((90.0-a.rx),a.ry,(90.0-a.sx),a.sy)
         back_az   = dist_az[1]
         delta_deg = kilometer2degrees(dist_az[0]/1000.0)

         if (component == 'x'):
            plt.plot(a.trace_x*sf + delta_deg, a.t,'k')
         elif (component == 'y'):
            plt.plot(a.trace_y*sf + delta_deg, a.t,'k')
         elif (component == 'z'):
            plt.plot(a.trace_z*sf + delta_deg, a.t,'k')

      plt.show()
Esempio n. 39
0
def write2sac(d, header, evla, evlo, evdp, mag, output):
    sacio = SacIO()
    sacio.fromarray(d)
    # set the date to today
    sacio.SetHvalue('nzyear', header['nzyear'])
    sacio.SetHvalue('nzjday', header['nzjday'])
    sacio.SetHvalue('delta', 0.02)
    sacio.SetHvalue('nzhour', header['nzhour'])
    sacio.SetHvalue('nzmin', header['nzmin'])
    sacio.SetHvalue('nzsec', header['nzsec'])
    sacio.SetHvalue('nzmsec', header['nzmsec'])
    sacio.SetHvalue('kstnm', header['stnm'])
    sacio.SetHvalue('stla', header['stla'])
    sacio.SetHvalue('stlo', header['stlo'])
    sacio.SetHvalue('kcmpnm', header['comp'])
    sacio.SetHvalue('evla', evla)
    sacio.SetHvalue('evlo', evlo)
    sacio.SetHvalue('evdp', evdp)
    sacio.SetHvalue('mag', mag)

    #dist = sacio.GetHvalue('dist')
    #print dist
    dist = gps2DistAzimuth(stla, stlo, evla, evlo)[0] / 1000.
    sacio.SetHvalue('dist', dist)

    #sacio.SetHvalue('knetwk','phones')
    #sacio.SetHvalue('kstnm',phone)
    #sacio.SetHvalue('kcmpnm',comp)
    #sacio.SetHvalue('kevnm',loc)
    #sacio.SetHvalue('kuser0',test + ' test')
    #sacio.SetHvalue('kuser0',version)
    #sacio.SetHvalue('kuser1',brand)
    #set the type of the dependent variable as acceleration nm/sec/sec
    #sacio.SetHvalue('idep',8)

    sacio.WriteSacBinary(output)
Esempio n. 40
0
def main(args,config):
    eventid = args.eventID
    shakehome = config.get('SHAKEMAP','shakehome')
    xmlfile = os.path.join(shakehome,'data',eventid,'input',args.dataFile)
    gridfile = os.path.join(shakehome,'data',eventid,'output','grid.xml')
    #list of grid.xml variable names and corresponding data file variable names
    variables = [('PGA','acc'),('PGV','vel'),('PSA03','psa03'),('PSA10','psa10'),('PSA30','psa30')]

    shakemap = ShakeGrid(gridfile,variable='MMI') #doesn't matter
    gdict = shakemap.getGeoDict()
    atts = shakemap.getAttributes()
    location = atts['event']['event_description']
    etime = atts['event']['event_timestamp']
    epilat = atts['event']['lat']
    epilon = atts['event']['lon']
    nrows = gdict['nrows']
    ncols = gdict['ncols']
    
    root = minidom.parse(xmlfile)
    f = plt.figure(figsize=(8.5,11))
    pnum = 1
    pgaobs = []
    pgaexp = []
    pgadist = []
    for vartuple in variables:
        gridvar,stationvar = vartuple
        shakemap = ShakeGrid(gridfile,variable=gridvar)
        
        stations = root.getElementsByTagName('station')
        observed = []
        expected = []
        for i in range(0,len(stations)):
            station = stations[i]
            lat = float(station.getAttribute('lat'))
            lon = float(station.getAttribute('lon'))
            row,col = shakemap.getRowCol(lat,lon)
            if row < 0 or row > nrows or col < 0 or col > ncols:
                continue
            pgael = station.getElementsByTagName('comp')[0].getElementsByTagName(stationvar)[0]
            pga = float(pgael.getAttribute('value'))
            gridpga = shakemap.getValue(lat,lon)
            observed.append(pga)
            expected.append(gridpga)
            if gridvar == 'PGA':
                pgaobs.append(pga)
                pgaexp.append(gridpga)
                distance,az1,az2 = gps2DistAzimuth(epilat,epilon,lat,lon)
                pgadist.append(distance/1000.0)

        observed = np.array(observed)
        expected = np.array(expected)
        xmax = observed.max()
        ymax = expected.max()
        dmax = max(xmax,ymax) * 1.05
        v = [0,dmax,0,dmax]
        plt.subplot(3,2,pnum)
        plt.plot(observed,expected,'b.')
        plt.xlabel('Observed %s' % gridvar)
        plt.ylabel('Modeled %s' % gridvar)
        plt.axis(v)
        pnum += 1

    #Add in one final plot - pga differences vs distance, just to see if that's a factor
    pgaobs = np.array(pgaobs)
    pgaexp = np.array(pgaexp)
    pgadist = np.array(pgadist)
    pgadiff = np.power((pgaobs-pgaexp),2)
    mdiff = np.mean(pgadiff)
    stddiff = np.std(pgadiff)
    ymax = mdiff + 2*stddiff
    plt.subplot(3,2,6)
    plt.plot(pgadist,pgadiff,'b.')
    plt.ylabel('pga diff (squared)')
    plt.xlabel('Distance (km)')
    plt.axis([0,pgadist.max(),0,ymax])
    f.suptitle('Event %s %s - %s' % (eventid,etime.strftime('%Y-%m-%d %H:%M:%S'),location))
    plt.savefig('%s_qa.pdf' % eventid)
Esempio n. 41
0
 xi=linspace(Plon[kP][0],Plon[kP][1],1000)
 yi=interp(xi, array([Plon[kP][0],Plon[kP][1]]), array([Plat[kP][0],Plat[kP][1]]))
 savetxt(table,c_[xi,yi],fmt='%.6f\t%.6f')
 
 #run gmt slicing
 run='/Users/dmelgar/code/GMT/coquimbo/slice_slip.gmt'
 run=split(run)
 p=subprocess.Popen(run)
 p.communicate()
 
 #get the slab
 slab=genfromtxt('/Users/dmelgar/code/GMT/coquimbo/slab.txt')
 distance=zeros(len(slab))
 #Convert to distance
 for k in range(len(slab)):
     distance[k],az,baz=gps2DistAzimuth(slab[0,1],slab[0,0],slab[k,1],slab[k,0])
 distance=distance/1000
 
 
 #Get the topo/bathy
 topo=genfromtxt('/Users/dmelgar/code/GMT/coquimbo/topo.txt')
 distance_topo=zeros(len(topo))
 #Convert to distance
 for k in range(len(topo)):
     distance_topo[k],az,baz=gps2DistAzimuth(slab[0,1],slab[0,0],topo[k,1],topo[k,0])
     if az>baz:
         distance_topo[k]=-distance_topo[k]
 distance_topo=distance_topo/1000
 topo=topo[:,2]/1000
 
 #get the slip
Esempio n. 42
0
paz_wa = {
    'sensitivity': 2800,
    'zeros': [0j],
    'gain': 1,
    'poles': [-6.2832 - 4.7124j, -6.2832 + 4.7124j]
}

st.simulate(paz_remove=paz_le3d5s, paz_simulate=paz_wa, water_level=10)

t = UTCDateTime("2012-04-03T02:45:03")
st.trim(t, t + 50)

tr_n = st.select(component="N")[0]
ampl_n = max(abs(tr_n.data))
tr_e = st.select(component="E")[0]
ampl_e = max(abs(tr_e.data))
ampl = max(ampl_n, ampl_e)

sta_lat = 46.38703
sta_lon = 7.62714
event_lat = 46.218
event_lon = 7.706

epi_dist, az, baz = gps2DistAzimuth(event_lat, event_lon, sta_lat, sta_lon)
epi_dist = epi_dist / 1000

a = 0.018
b = 2.17
ml = log10(ampl * 1000) + a * epi_dist + b
print ml
Esempio n. 43
0
fout = '/Users/dmelgar/Lefkada2015/scripts/total_up.dtopo'

dt = 1.0
vs = 3300.
epi = array([20.6002, 38.6655])

#load data
d = genfromtxt(f)
lonlat = d[:, 0:2]  #lon and lat
d = d[:, 2]  #Actual displacememnt
#Compute distance from hypocenter to all points
dist = zeros(len(d))
for k in range(len(d)):
    if k % 100 == 0:
        print str(k) + '/' + str(len(d))
    dist[k], az, baz = gps2DistAzimuth(epi[1], epi[0], lonlat[k, 1], lonlat[k,
                                                                            0])
#Form full length dtopo vector
tmax = dist.max() / vs
tvec = arange(0, tmax + dt, dt)
t = array([])
#Form time vectopr
for k in range(len(tvec)):
    t = r_[t, ones(len(d)) * tvec[k]]
#Form coordinate and dispalcememnt vector
dout = array([])
for k in range(len(tvec)):
    dmax = tvec[k] * vs
    print dmax
    i = where(dist < dmax)[0]
    mask = zeros(len(d))
    mask[i] = 1
Esempio n. 44
0
from numpy import genfromtxt, zeros, sin, cos, deg2rad
from mpl_toolkits.mplot3d import Axes3D
from obspy.core.util.geodetics import gps2DistAzimuth

a = genfromtxt('/Users/dmelgar/Lefkada2015/afters/aftershocks_NOA.txt')
f = genfromtxt(
    '/Users/dmelgar/Slip_inv/Lefkada70/data/model_info/lefkada65.fault')

lon = a[:, 5]
lat = a[:, 4]
depth = -a[:, 6]
hypo = [20.6002, 38.6655]
x = zeros(len(lon))
y = zeros(len(lon))
for k in range(len(lon)):
    dist, az, baz = gps2DistAzimuth(lat[k], lon[k], hypo[1], hypo[0])
    x[k] = dist * sin(deg2rad(baz)) / 1000
    y[k] = dist * cos(deg2rad(baz)) / 1000

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(lon, lat, depth)
ax.set_xlabel('lon')
ax.set_ylabel('lat')
ax.set_zlabel('depth (km)')
ax.view_init(azim=-90, elev=90.)
ax.scatter(f[:, 1], f[:, 2], -f[:, 3], c='r', s=100)
ax.set_zlim([0, -20])
ax.set_xlim([20, 21])
ax.set_ylim([38, 39])
Esempio n. 45
0
    st+=read(path+sta[k]+'.HNN.sac')
    st2+=read(path+sta[k]+'.HNE.sac')
    st3+=read(path+sta[k]+'.HNE.sac')
    if st[k].data.max>max_ampl:
        max_ampl=st[k].data.max()
    st[k].trim(starttime=time_epi,endtime=time_epi+timedelta(seconds=200))
    st[k].data=st[k].data-mean(st[k].data[0:50])
    st2[k].trim(starttime=time_epi,endtime=time_epi+timedelta(seconds=200))
    st2[k].data=st2[k].data-mean(st2[k].data[0:50])
    st3[k].trim(starttime=time_epi,endtime=time_epi+timedelta(seconds=200))
    st3[k].data=st3[k].data-mean(st3[k].data[0:50])
    #Get PGA
    aabs=max((st[k].data**2+st2[k].data**2+st3[k].data**2)**0.5)/9.81*100
    print sta[k]+', PGA = '+str(aabs)+'%g'
    #st[k].data=lowpass(st[k].data,corner,1./st[k].stats.delta,2)
    d[k],az,baz=gps2DistAzimuth(epicenter[1],epicenter[0],lonlat[k,1],lonlat[k,0])
    d[k]=d[k]/1000
    if lonlat[k,1]<epicenter[1]: #It south
        d[k]=-d[k]
 
#Write to file
tout=array([])
aout=array([])
f=open(outfile,'w')
for k in range(len(sta)):
    t=st[k].times()
    t=(t*t_adjust)+lonlat[k,0]
    offset=lonlat[k,1]
    a=((st[k].data/1.0)/ampl_adjust)+offset
    f.write('>\n')
    for kdat in range(len(t)):
Esempio n. 46
0
def main(argv=sys.argv): 
    
    #Earth's parameters 
    #~ beta = 4.e3 #m/s 
    #~ rho = 3.e3 #kg/m^3 
    #~ mu = rho*beta*beta
    
    PLotSt = ["IU.TRQA.00.LHZ",
             "IU.LVC.00.LHZ",
             "II.NNA.00.LHZ",
              "IU.RAR.00.LHZ"]
             
             
    #PlotSubf = [143, 133, 123, 113, 103, 93,
     #           83, 73, 63, 53]
    PlotSubf = [6,3]

    
    
    #Set rup_vel = 0 to have a point source solution
    RupVel = 2.1 #Chilean eq from Lay et al
    t_h     = 10. # Half duration for each sf  
    noiselevel = 0.0# L1 norm level of noise
    mu =40e9
    #W-Phase filter 
    corners = 4.
    fmin = 0.001
    fmax = 0.005
    
    ### Data from Chilean 2010 EQ (Same as W phase inv.) 
    strike = 18.
    dip    = 18.
    rake   = 104. # 109.
    
    rakeA = rake + 45.
    rakeB = rake - 45.
    
    
    ### Fault's grid parameters
    nsx   = 21 #Number of sf along strike
    nsy   = 11 #Number of sf along dip
    flen  = 600. #Fault's longitude [km] along strike
    fwid  = 300. #Fault's longitude [km] along dip
    direc = 0    #Directivity 0 = bilateral
    Min_h = 10.  #Min depth of the fault
    
    
    ### Derivated parameters:
    nsf = nsx*nsy
    sflen = flen/float(nsx)         
    sfwid = fwid/float(nsy)
    swp = [1, 0, 2] # useful to swap (lat,lon, depth)  
    mindist = flen*fwid # minimun dist to the hypcen (initializing)
    
    ###Chessboard
    #weight = np.load("RealSol.npy") 
    weight = np.zeros(nsf)
    weight[::2] = 1 
    #weight[::2] = 1 
    #~ weight[10]=15
    #~ weight[5001]=10
    #~ weight[3201]=2
    
    
    
    ## Setting dirs and reading files.
    GFdir = "/home/roberto/data/GFS/"
    workdir = os.path.abspath(".")+"/"
    datadir = workdir + "DATA/"
    tracesfilename = workdir + "goodtraces.dat"
    tracesdir = workdir + "WPtraces/"
    
    try:
        reqfilename    = glob.glob(workdir + '*.syn.req')[0]
    except IndexError:   
        print "There is not *.syn.req file in the dir"
        sys.exit()
    
    basename = reqfilename.split("/")[-1][:-4]
    
    if not os.path.exists(tracesfilename): 
        print tracesfilename, "does not exist."
        exit()
    
    if not os.path.exists(datadir):
            os.makedirs(datadir)
    
    if not os.path.exists(tracesdir):
            os.makedirs(tracesdir)
 
    tracesfile = open(tracesfilename)    
    reqfile =  open(reqfilename)    
    
    trlist = readtraces(tracesfile)
    eqdata = readreq(reqfile)    

    tracesfile.close()
    reqfile.close()   
    
    ####Hypocentre from
    ### http://earthquake.usgs.gov/earthquakes/eqinthenews/2010/us2010tfan/    
    cmteplat = -35.91#-35.85#-36.03#-35.83
    cmteplon = -72.73#-72.72#-72.83# -72.67
    cmtepdepth= 35.
    eq_hyp = (cmteplat,cmteplon,cmtepdepth)
    
    
      ############
    

    # Defining the sf system
    grid, sblt = fault_grid('CL-2010',cmteplat,cmteplon,
                            cmtepdepth, direc,
                            Min_h, strike, dip, rake, flen,fwid ,nsx,nsy,
                            Verbose=False,ffi_io=True,gmt_io=True)
    
    print ('CL-2010',cmteplat,cmteplon,
                            cmtepdepth, direc,
                            Min_h, strike, dip, rake, flen,fwid ,nsx,nsy)
    print grid[0][1]
    #sys.exit()
    #This calculation is inside of the loop
    #~ NP = [strike, dip, rake]
    #~ M = np.array(NodalPlanetoMT(NP))  
    #~ Mp = np.sum(M**2)/np.sqrt(2)    
     
    #############################################################################
    ######Determining the sf closest to the hypocentre:    
    min_Dist_hyp_subf = flen *fwid
    for subf in range(nsf):
        sblat   = grid[subf][1]
        sblon   = grid[subf][0]
        sbdepth = grid[subf][2]              
        sf_hyp =  (sblat,sblon, sbdepth)        
        Dist_hyp_subf = hypo2dist(eq_hyp,sf_hyp)
        if Dist_hyp_subf < min_Dist_hyp_subf:
            min_Dist_hyp_subf = Dist_hyp_subf
            min_sb_hyp = sf_hyp
            hyp_subf = subf
    ####Determining trimming times:    
    test_tr = read(GFdir + "H003.5/PP/GF.0001.SY.LHZ.SAC")[0]
    t0 = test_tr.stats.starttime
    TrimmingTimes = {}   # Min. Distace from the fault to each station. 
    A =0
    for trid in trlist:     
        metafile = workdir + "DATA/" + "META." + trid + ".xml"
        META = DU.getMetadataFromXML(metafile)[trid]
        stlat = META['latitude']
        stlon = META['longitude'] 
        dist =   locations2degrees(min_sb_hyp[0],min_sb_hyp[1],\
                                   stlat,stlon) 
        parrivaltime = getTravelTimes(dist,min_sb_hyp[2])[0]['time']        
        ta = t0 + parrivaltime
        tb = ta + round(15.*dist) 
        TrimmingTimes[trid] = (ta, tb)
        
    
    ###########################

      
    
    DIST = []
    # Ordering the stations in terms of distance
    for trid in trlist: 
        metafile = workdir + "DATA/" + "META." + trid + ".xml"
        META = DU.getMetadataFromXML(metafile)[trid]
        lat = META['latitude']
        lon = META['longitude']
        trdist = locations2degrees(cmteplat,
                                   cmteplon,lat,lon) 
        DIST.append(trdist)   

    DistIndex = lstargsort(DIST)
    trlist = [trlist[i] for i in DistIndex]
  
    stdistribution = StDistandAzi(trlist, eq_hyp , workdir + "DATA/")
    StDistributionPlot(stdistribution)
    #exit()
    #Main loop
   

 

        
    for subf in range(nsf):
        print subf
        sflat   = grid[subf][1]
        sflon   = grid[subf][0]           
        sfdepth = grid[subf][2]
        #~ strike = grid[subf][3] #+ 360.
        #~ dip    = grid[subf][4]
        #~ rake   = grid[subf][5] #     
        NP = [strike, dip, rake]  
        NPA = [strike, dip, rakeA]
        NPB = [strike, dip, rakeB]        


        
        M = np.array(NodalPlanetoMT(NP))   
        MA = np.array(NodalPlanetoMT(NPA)) 
        MB = np.array(NodalPlanetoMT(NPB)) 
        #Time delay is calculated as the time in which 
        #the rupture reach the subfault
            
        sf_hyp = (sflat, sflon, sfdepth) 
        Dist_ep_subf = hypo2dist(eq_hyp,sf_hyp)
        
        if Dist_ep_subf < mindist:
            mindist = Dist_ep_subf
            minsubf = subf
        
                
        if RupVel == 0:
            t_d = eqdata['time_shift']
        else:
            t_d = round(Dist_ep_subf/RupVel) #-59.
       
        print sflat, sflon, sfdepth
        # Looking for the best depth dir:
        depth = []
        depthdir = []
        for file in os.listdir(GFdir):
            if file[-2:] == ".5":
                depthdir.append(file)
                depth.append(float(file[1:-2]))            
        BestDirIndex = np.argsort(abs(sfdepth\
                                  - np.array(depth)))[0]      
        hdir = GFdir + depthdir[BestDirIndex] + "/"     
        
        ###

        SYN = np.array([])
        SYNA = np.array([])
        SYNB = np.array([])
        for trid in trlist:     
            
            metafile = workdir + "DATA/" + "META." + trid + ".xml"
            META = DU.getMetadataFromXML(metafile)[trid]
            lat = META['latitude']
            lon = META['longitude']  
            
            #Subfault loop               
            #GFs Selection:
            ##Change to folloing loop
            
            dist = locations2degrees(sflat,sflon,lat,lon)                                
            azi =  -np.pi/180.*gps2DistAzimuth(lat,lon,
                       sflat,sflon)[2] 
            trPPsy,  trRRsy, trRTsy,  trTTsy = \
                                       GFSelectZ(hdir,dist)          
            
            
 
            
            trROT =  MTrotationZ(azi, trPPsy,  trRRsy, trRTsy,  trTTsy) 
            orig = trROT[0].stats.starttime  
            dt = trROT[0].stats.delta                       

            trianglen = 2.*int(t_h/dt)-1.
            FirstValid = int(trianglen/2.) + 1 # to delete
            window = triang(trianglen)
            window /= np.sum(window)
            #window = np.array([1.])
            
      
            
            
            parrivaltime = getTravelTimes(dist,sfdepth)[0]['time']
            
            t1 = TrimmingTimes[trid][0] - t_d
            t2 = TrimmingTimes[trid][1] - t_d
            
            
            
            for trR in trROT:
                trR.data *= 10.**-21 ## To get M in Nm                   
                trR.data -= trR.data[0]
                AUX1 = len(trR)
                trR.data = convolve(trR.data,window,mode='valid') 
                AUX2 = len(trR)
                mean = np.mean(np.hstack((trR.data[0]*np.ones(FirstValid),\
                               trR.data[:60./trR.stats.delta*1.-FirstValid+1])))
                #mean = np.mean(trR.data[:60])
                trR.data -= mean      
                trR.data = bp.bandpassfilter(trR.data,len(trR), trR.stats.delta,\
                                             corners , 1 , fmin, fmax)  
                t_l = dt*0.5*(AUX1 - AUX2)                             
                trR.trim(t1-t_l,t2-t_l, pad=True, fill_value=trR.data[0])  #We lost t_h due to the convolution        
            


                   
            #~ for trR in trROT:
                #~ trR.data *= 10.**-23 ## To get M in Nm                   
                #~ trR.data -= trR.data[0]
 
                #~ trR.data = convolve(trR.data,window,mode='same') 

                #~ #mean = np.mean(np.hstack((trR.data[0]*np.ones(FirstValid),\
                               #~ #trR.data[:60./trR.stats.delta*1.-FirstValid+1])))
                #~ mean = np.mean(trR.data[:60])
                #~ trR.data -= mean      
                #~ trR.data = bp.bandpassfilter(trR.data,len(trR), trR.stats.delta,\
                                             #~ corners , 1 , fmin, fmax)  
                            
                #~ trR.trim(t1,t2,pad=True, fill_value=trR.data[0])     
           
            trROT = np.array(trROT)  
            syn  =  np.dot(trROT.T,M) 
            synA =  np.dot(trROT.T,MA)
            synB =  np.dot(trROT.T,MB)
            
            SYN = np.append(SYN,syn)  
            SYNA = np.append(SYNA,synA)
            SYNB = np.append(SYNB,synB)
            
            
        print np.shape(A), np.shape(np.array([SYN]))    
        if subf == 0: 
            A = np.array([SYN])
            AA = np.array([SYNA])
            AB = np.array([SYNB])
        else:
            A = np.append(A,np.array([SYN]),0)    
            AA = np.append(AA,np.array([SYNA]),0)
            AB = np.append(AB,np.array([SYNB]),0)
            
            
            
    AC = np.vstack((AA,AB))
    print np.shape(AC)
    print np.shape(weight)
    B = np.dot(A.T,weight)
    stsyn = Stream()
    n = 0
    Ntraces= {}
    for trid in trlist: 
        spid = trid.split(".")        
        print trid
        NMIN = 1. + (TrimmingTimes[trid][1] - TrimmingTimes[trid][0]) / dt
        Ntraces[trid] = (n,NMIN + n)
        trsyn = Trace(B[n:NMIN+n])   
        n += NMIN        
        trsyn.stats.network = spid[0]
        trsyn.stats.station = spid[1]
        trsyn.stats.location = spid[2]
        trsyn.stats.channel = spid[3] 
        trsyn = AddNoise(trsyn,level = noiselevel)
        #trsyn.stats.starttime = 
        stsyn.append(trsyn)
        
       
    stsyn.write(workdir+"WPtraces/" + basename + ".decov.trim.mseed",
                 format="MSEED")           
                
    #####################################################    
    # Plotting:
    #####################################################
    #we are going to reflect the y axis later, so:
    print minsubf
    hypsbloc = [minsubf / nsy , -(minsubf % nsy) - 2]

    #Creating the strike and dip axis:
    StrikeAx= np.linspace(0,flen,nsx+1)
    DipAx= np.linspace(0,fwid,nsy+1)
    DepthAx = DipAx*np.sin(np.pi/180.*dip) + Min_h    
    hlstrike = StrikeAx[hypsbloc[0]] + sflen*0.5
        
    hldip = DipAx[hypsbloc[1]] + sfwid*0.5 
    hldepth = DepthAx[hypsbloc[1]] + sfwid*0.5*np.sin(np.pi/180.*dip)
       
    StrikeAx = StrikeAx - hlstrike
    DipAx =     DipAx   - hldip
 

    
    XX, YY = np.meshgrid(StrikeAx, DepthAx)
    XX, ZZ = np.meshgrid(StrikeAx, DipAx )

   
    sbarea = sflen*sfwid
    
    SLIPS = weight.reshape(nsx,nsy).T#[::-1,:]
    SLIPS /= mu*1.e6*sbarea
    
    ######Plot:#####################
    plt.figure()
    ax = host_subplot(111)
    im = ax.pcolor(XX, YY, SLIPS, cmap="jet")    
    ax.set_ylabel('Depth [km]')       
    ax.set_ylim(DepthAx[-1],DepthAx[0])  
    
    # Creating a twin plot 
    ax2 = ax.twinx()
    #im2 = ax2.pcolor(XX, ZZ, SLIPS[::-1,:], cmap="Greys") 
    im2 = ax2.pcolor(XX, ZZ, SLIPS[::-1,:], cmap="jet")    
    
    ax2.set_ylabel('Distance along the dip [km]')
    ax2.set_xlabel('Distance along the strike [km]')    
    ax2.set_ylim(DipAx[0],DipAx[-1])
    ax2.set_xlim(StrikeAx[0],StrikeAx[-1])       
                         
                         
    ax.axis["bottom"].major_ticklabels.set_visible(False) 
    ax2.axis["bottom"].major_ticklabels.set_visible(False)
    ax2.axis["top"].set_visible(True)
    ax2.axis["top"].label.set_visible(True)
    
    
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("bottom", size="5%", pad=0.1)
    cb = plt.colorbar(im, cax=cax, orientation="horizontal")
    cb.set_label("Slip [m]") 
    ax2.plot([0], [0], '*', ms=225./(nsy+4))
    ax2.set_xticks(ax2.get_xticks()[1:-1])
    #ax.set_yticks(ax.get_yticks()[1:])
    #ax2.set_yticks(ax2.get_yticks()[:-1])
    

    
    #########Plotting the selected traces:
    nsp = len(PLotSt) * len(PlotSubf)
    plt.figure(figsize=(13,11))
    plt.title("Synthetics for rake = " + str(round(rake)))
    mindis = []
    maxdis = []
    for i, trid in enumerate(PLotSt):   
        x = np.arange(0,Ntraces[trid][1]-Ntraces[trid][0],
                      dt)
        for j, subf in enumerate(PlotSubf):
            y = A[subf, Ntraces[trid][0]:Ntraces[trid][1]]
            if j == 0:
                yy = y
            else:
                yy = np.vstack((yy,y))        
        maxdis.append(np.max(yy))
        mindis.append(np.min(yy))
        
    

    for i, trid in enumerate(PLotSt):   
        x = np.arange(0,Ntraces[trid][1]-Ntraces[trid][0],
                      dt)

        for j, subf in enumerate(PlotSubf):
            y = A[subf, Ntraces[trid][0]:Ntraces[trid][1]]
            plt.subplot2grid((len(PlotSubf), len(PLotSt)),
                              (j, i))                                
            plt.plot(x,y, linewidth=2.5)
            if j == 0:
                plt.title(trid)
            fig = plt.gca()            
            fig.axes.get_yaxis().set_ticks([])
            fig.set_ylabel(str(subf),rotation=0)
            fig.set_xlim((x[0],x[-1]))
            fig.set_ylim((mindis[i],maxdis[i]))
            if subf != PlotSubf[-1]:
                fig.axes.get_xaxis().set_ticks([])

    
    plt.show()
Esempio n. 47
0
        except:
            pass
    if not line:
        break

#Compute distances
i = where((pbo_lat < 42) & (pbo_lat > 35))[0]
pbo_lon = pbo_lon[i]
pbo_lat = pbo_lat[i]

f1 = open(fout1, 'w')
f2 = open(fout2, 'w')
for kpbo in range(len(pbo_lon)):
    print kpbo
    for kseis in range(len(sm_lon)):
        d, az, baz = gps2DistAzimuth(pbo_lat[kpbo], pbo_lon[kpbo],
                                     sm_lat[kseis], sm_lon[kseis])
        if d < dist_filter:
            print 'Found collocation! ' + pbo_sta[i[kpbo]] + ' and ' + sm_sta[
                kseis] + ' are ' + str(d) + 'm apart'
            out = '%s\t%12.6f\t%12.6f\t%s\t%12.6f\t%12.6f\t%7.1f\n' % (
                pbo_sta[i[kpbo]], pbo_lon[kpbo], pbo_lat[kpbo], sm_sta[kseis],
                sm_lon[kseis], sm_lat[kseis], d)
            f1.write(out)
    for kseis in range(len(bb_sm_lon)):
        d, az, baz = gps2DistAzimuth(pbo_lat[kpbo], pbo_lon[kpbo],
                                     bb_sm_lat[kseis], bb_sm_lon[kseis])
        if d < dist_filter:
            print 'Found collocation! ' + pbo_sta[
                i[kpbo]] + ' and ' + bb_sm_sta[kseis] + ' are ' + str(
                    d) + 'm apart'
            out = '%s\t%12.6f\t%12.6f\t%s\t%12.6f\t%12.6f\t%7.1f\n' % (
Esempio n. 48
0
def tr2assoc(tr, pickmap=None):
    """
    Takes a sac header dictionary, and produces a list of up to 10 
    Assoc instances. Header->phase mappings follow SAC2000, i.e.:

    * t0: P
    * t1: Pn
    * t2: Pg
    * t3: S
    * t4: Sn
    * t5: Sg
    * t6: Lg
    * t7: LR
    * t8: Rg
    * t9: pP

    An alternate mapping for some or all picks can be supplied, however, 
    as a dictionary of strings in the above form.  
    
    Note: arid values will not be filled in, so do:
    >>> for assoc in kbio.tables['assoc']:
            assoc.arid = lastarid+1
            lastarid += 1

    """
    pick2phase = {'t0': 'P', 't1': 'Pn', 't2': 'Pg', 't3': 'S',
    't4': 'Sn', 't5': 'Sg', 't6': 'Lg', 't7': 'LR', 't8': 'Rg',
    't9': 'pP'} 

    #overwrite defaults with supplied map
    if pickmap:
        pick2phase.update(pickmap)

    #geographic relations
    # obspy.read tries to calculate these values if lcalca is True and needed
    #header info is there, so we only need to try to if lcalca is False.
    #XXX: I just calculate it if no values are currently filled in.
    assocdict = {}
    try:
        assocdict.update(_map_header({'az': 'esaz', 'baz': 'seaz', 
                                      'gcarc': 'delta'}, tr.stats.sac, 
                                      SACDEFAULT))
    except AttributeError:
        # no tr.stats.sac
        pass

    #overwrite if any are None
    if not assocdict:
        try:
            delta = geod.locations2degrees(tr.stats.sac.stla, tr.stats.sac.stlo, 
                                           tr.stats.sac.evla, tr.stats.sac.evlo)
            m, seaz, esaz = geod.gps2DistAzimuth(tr.stats.sac.stla, 
                tr.stats.sac.stlo, tr.stats.sac.evla, tr.stats.sac.evlo)
            assocdict['esaz'] = esaz
            assocdict['seaz'] = seaz
            assocdict['delta'] = delta
        except (AttributeError, TypeError):
            #some sac header values are None
            pass

    if tr.stats.station:
        assocdict['sta'] = tr.stats.station

    assocdict.update(_map_header({'norid': 'orid'}, tr.stats.sac, SACDEFAULT))

    #now, do the phase arrival mappings
    #for each pick in hdr, make a separate dictionary containing assocdict plus
    #the new phase info.
    assocs = []
    for key in pick2phase:
        kkey = 'k' + key
        #if there's a value in t[0-9]
        if tr.stats.sac[key] != SACDEFAULT[key]:
            #if the phase name kt[0-9] is null
            if tr.stats.sac[kkey] == SACDEFAULT[kkey]:
                #take it from the map
                iassoc = {'phase': pick2phase[key]}
            else:
                #take it directly
                iassoc = {'phase': tr.stats.sac[kkey]}

            iassoc.update(assocdict)
            assocs.append(iassoc)

    return [Assoc(**assoc) for assoc in assocs]
Esempio n. 49
0
def main(args, config):
    eventid = args.eventID
    shakehome = config.get('SHAKEMAP', 'shakehome')
    xmlfile = os.path.join(shakehome, 'data', eventid, 'input', args.dataFile)
    gridfile = os.path.join(shakehome, 'data', eventid, 'output', 'grid.xml')
    #list of grid.xml variable names and corresponding data file variable names
    variables = [('PGA', 'acc'), ('PGV', 'vel'), ('PSA03', 'psa03'),
                 ('PSA10', 'psa10'), ('PSA30', 'psa30')]

    shakemap = ShakeGrid(gridfile, variable='MMI')  #doesn't matter
    gdict = shakemap.getGeoDict()
    atts = shakemap.getAttributes()
    location = atts['event']['event_description']
    etime = atts['event']['event_timestamp']
    epilat = atts['event']['lat']
    epilon = atts['event']['lon']
    nrows = gdict['nrows']
    ncols = gdict['ncols']

    root = minidom.parse(xmlfile)
    f = plt.figure(figsize=(8.5, 11))
    pnum = 1
    pgaobs = []
    pgaexp = []
    pgadist = []
    for vartuple in variables:
        gridvar, stationvar = vartuple
        shakemap = ShakeGrid(gridfile, variable=gridvar)

        stations = root.getElementsByTagName('station')
        observed = []
        expected = []
        for i in range(0, len(stations)):
            station = stations[i]
            lat = float(station.getAttribute('lat'))
            lon = float(station.getAttribute('lon'))
            row, col = shakemap.getRowCol(lat, lon)
            if row < 0 or row > nrows or col < 0 or col > ncols:
                continue
            pgael = station.getElementsByTagName(
                'comp')[0].getElementsByTagName(stationvar)[0]
            pga = float(pgael.getAttribute('value'))
            gridpga = shakemap.getValue(lat, lon)
            observed.append(pga)
            expected.append(gridpga)
            if gridvar == 'PGA':
                pgaobs.append(pga)
                pgaexp.append(gridpga)
                distance, az1, az2 = gps2DistAzimuth(epilat, epilon, lat, lon)
                pgadist.append(distance / 1000.0)

        observed = np.array(observed)
        expected = np.array(expected)
        xmax = observed.max()
        ymax = expected.max()
        dmax = max(xmax, ymax) * 1.05
        v = [0, dmax, 0, dmax]
        plt.subplot(3, 2, pnum)
        plt.plot(observed, expected, 'b.')
        plt.xlabel('Observed %s' % gridvar)
        plt.ylabel('Modeled %s' % gridvar)
        plt.axis(v)
        pnum += 1

    #Add in one final plot - pga differences vs distance, just to see if that's a factor
    pgaobs = np.array(pgaobs)
    pgaexp = np.array(pgaexp)
    pgadist = np.array(pgadist)
    pgadiff = np.power((pgaobs - pgaexp), 2)
    mdiff = np.mean(pgadiff)
    stddiff = np.std(pgadiff)
    ymax = mdiff + 2 * stddiff
    plt.subplot(3, 2, 6)
    plt.plot(pgadist, pgadiff, 'b.')
    plt.ylabel('pga diff (squared)')
    plt.xlabel('Distance (km)')
    plt.axis([0, pgadist.max(), 0, ymax])
    f.suptitle('Event %s %s - %s' %
               (eventid, etime.strftime('%Y-%m-%d %H:%M:%S'), location))
    plt.savefig('%s_qa.pdf' % eventid)
Esempio n. 50
0
paz_wa = {'sensitivity': 2800, 'zeros': [0j], 'gain': 1,
          'poles': [-6.2832-4.7124j, -6.2832+4.7124j]}

client = Client(user="******")
t = st[0].stats.starttime
paz_le3d5s = client.getPAZ("CH", "LKBD", "", "EHZ", t)

st.simulate(paz_remove=paz_le3d5s, paz_simulate=paz_wa, water_level=10)

t = UTCDateTime("2012-04-03T02:45:03")
st.trim(t, t + 50)

tr_n = st.select(component="N")[0]
ampl_n = max(abs(tr_n.data))
tr_e = st.select(component="E")[0]
ampl_e = max(abs(tr_e.data))
ampl = max(ampl_n, ampl_e)

sta_lat = 46.38703
sta_lon = 7.62714
event_lat = 46.218
event_lon = 7.706

epi_dist, az, baz = gps2DistAzimuth(event_lat, event_lon, sta_lat, sta_lon)
epi_dist = epi_dist / 1000

a = 0.018
b = 2.17
ml = log10(ampl * 1000) + a * epi_dist + b
print ml
Esempio n. 51
0
def distaz_query(records, deg=None, km=None, swath=None):
    """ 
    Out-of-database subset based on distances and/or azimuths.
    
    Parameters
    ----------
    records : iterable of objects with lat, lon attribute floats
        Target of the subset.
    deg : list or tuple of numbers, optional
        (centerlat, centerlon, minr, maxr)
        minr, maxr in degrees or None for unconstrained.
    km : list or tuple of numbers, optional
        (centerlat, centerlon, minr, maxr)
        minr, maxr in km or None for unconstrained.
    swath : list or tuple of numbers, optional
        (lat, lon, azimuth, tolerance)
        Azimuth (from North) +/-tolerance from lat,lon point in degrees.

    Returns
    -------
    list
        Subset of supplied records.

    """
    #initial True array to propagate through multiple logical AND comparisons
    mask0 = np.ones(len(records), dtype=np.bool)

    if deg:
        dgen = (geod.locations2degrees(irec.lat, irec.lon, deg[0], deg[1]) \
                for irec in records)
        degrees = np.fromiter(dgen, dtype=float)
        if deg[2] is not None:
            mask0 = np.logical_and(mask0, deg[2] <= degrees)
        if deg[3] is not None:
            mask0 = np.logical_and(mask0, deg[3] >= degrees)

        #mask0 = np.logical_and(mask0, mask)

    if km:
        #???: this may be backwards
        mgen = (geod.gps2DistAzimuth(irec.lat, irec.lon, km[0], km[1])[0] \
                  for irec in records)
        kilometers = np.fromiter(mgen, dtype=float)/1e3
        #meters, azs, bazs = zip(*valgen)
        #kilometers = np.array(meters)/1e3
        if km[2] is not None:
            mask0 = np.logical_and(mask0, km[2] <= kilometers)
        if km[3] is not None:
            mask0 = np.logical_and(mask0, km[3] >= kilometers)

        #mask0 = np.logical_and(mask0, mask)

    if swath is not None:
        minaz = swath[2] - swath[3]
        maxaz = swath[2] + swath[3]
        #???: this may be backwards
        azgen = (geod.gps2DistAzimuth(irec.lat, irec.lon, km[0], km[1])[1] \
                 for irec in records)
        azimuths = np.fromiter(azgen, dtype=float)
        mask0 = np.logical_and(mask0, azimuths >= minaz)
        mask0 = np.logical_and(mask0, azimuths <= maxaz)

    #idx = np.nonzero(np.atleast_1d(mask0))[0] ???
    idx = np.nonzero(mask0)[0]
    recs = [records[i] for i in idx]

    return recs
Esempio n. 52
0
 station_coords=genfromtxt(path+'station_info/melinka.sta',usecols=[1,2])
 #Now loop over station data at each epoch
 for ksta in range(len(stanames)):
     print '... fetching PGD for '+stanames[ksta]
     try:
         n=read(data_path+'/'+stanames[ksta]+'.LXN.sac')
         e=read(data_path+'/'+stanames[ksta]+'.LXE.sac')
         u=read(data_path+'/'+stanames[ksta]+'.LXZ.sac')
         if n[0].stats.npts>0:
             #Trim to times of interest
             n.trim(starttime=hypo_time,endtime=hypo_time+tmax,pad=True)
             e.trim(starttime=hypo_time,endtime=hypo_time+tmax,pad=True)
             u.trim(starttime=hypo_time,endtime=hypo_time+tmax,pad=True)
             #Remove mean of first ten seconds
             #Get station-event distance
             d,az,baz=gps2DistAzimuth(station_coords[ksta,1],station_coords[ksta,0],hypo[1],hypo[0])
             hypo_dist=((d/1000)**2+hypo[2]**2)**0.5
             #Now get PGD at that site
             pgd_all_out=0
             pgd_nov_out=0
             time_to_all=0
             time_to_nov=0
             f=open(path+'PGD/Melinka2016/'+stanames[ksta]+'.pgd','w')
             f.write('# Seconds after OT , no horiz PGD [m] , all PGD [m] , seconds to horiz , seconds to all , hypo_dist [km]\n')
             for kt in range(len(n[0].times())):
                 #print kt
                 pgd_all=(n[0].data[kt]**2+e[0].data[kt]**2+u[0].data[kt]**2)**0.5
                 pgd_nov=(n[0].data[kt]**2+e[0].data[kt]**2)**0.5
                 if pgd_all>pgd_all_out:
                     pgd_all_out=pgd_all
                     time_to_all=kt
Esempio n. 53
0
def process_synt(datadir, station, event = None, stationxml_dir = None, period_band = None, npts=None,
                sampling_rate=None, output_dir=None, suffix=None):

    # ensemble the stream
    #station_list = generate_station_list(datadir)
    #for station in station_list:
    zdatafile = station[0] + "." + station[1] + ".MXZ.sem.sac"
    ndatafile = station[0] + "." + station[1] + ".MXN.sem.sac"
    edatafile = station[0] + "." + station[1] + ".MXE.sem.sac"
    zpath = os.path.join(datadir, zdatafile)
    npath = os.path.join(datadir, ndatafile)
    epath = os.path.join(datadir, edatafile)
    st = read(zpath)
    st2 = read(npath)
    st3 = read(epath)
    #print st
    #print st2
    st.append(st2[0])
    st.append(st3[0])

    #print "\nProcessing file: %s" %filename
    # interpolation value
    #npts = 3630
    #sampling_rate = 1.0  # Hz
    min_period = period_band[0]
    max_period = period_band[1]
    f2 = 1.0 / max_period
    f3 = 1.0 / min_period
    f1 = 0.8 * f2
    f4 = 1.2 * f3
    pre_filt = (f1, f2, f3, f4)

    # fetch event information
    event_name = get_event_name(event)
    short_event_name = adjust_event_name(event_name)

    origin = event.preferred_origin() or event.origins[0]
    event_latitude = origin.latitude
    event_longitude = origin.longitude
    event_time = origin.time
    event_depth = origin.depth
    starttime = event_time
    print "event_time:",event_time

    #output_path = os.path.join(output_dir, short_event_name)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    nrecords = len(st)
    # processing
    for i, tr in enumerate(st):
        #get component name
        cmpname = tr.stats.channel
        #print tr.stats
        #tr.interpolate(sampling_rate=sampling_rate, starttime=starttime,
        #                npts=npts)
        #tr.decimate(4, strict_length=False,no_filter=True)
        print "Processing %d of total %d" %(i+1, nrecords)
        print "Detrend, Demean and Taper..."
        tr.detrend("linear")
        tr.detrend("demean")
        tr.taper(max_percentage=0.05, type="hann")
        #print "response show:"
        #print tr.stats.response


        # Perform a frequency domain taper like during the response removal
        # just without an actual response...
        #for tr in st:
        print "Filtering..."
        data = tr.data.astype(np.float64)

        # smart calculation of nfft dodging large primes
        from obspy.signal.util import _npts2nfft
        nfft = _npts2nfft(len(data))

        fy = 1.0 / (tr.stats.delta * 2.0)
        freqs = np.linspace(0, fy, nfft // 2 + 1)

        # Transform data to Frequency domain
        data = np.fft.rfft(data, n=nfft)
        data *= c_sac_taper(freqs, flimit=pre_filt)
        data[-1] = abs(data[-1]) + 0.0j
        # transform data back into the time domain
        data = np.fft.irfft(data)[0:len(data)]
        # assign processed data and store processing information
        tr.data = data

        print "Detrend, Demean and Taper again..."
        tr.detrend("linear")
        tr.detrend("demean")
        tr.taper(max_percentage=0.05, type="hann")
        print "Interpolate..."
        try:
            tr.interpolate(sampling_rate=sampling_rate, starttime=starttime,
                           npts=npts)
        except:
            print "Error"
            return

    # rotate
    station_latitude = st[0].stats.sac['stla']
    station_longitude = st[0].stats.sac['stlo']
    event_latitude = st[0].stats.sac['evla']
    event_longitude = st[0].stats.sac['evlo']
    #print station_latitude, station_longitude
    #print station_latitude, station_longitude
    _, baz, _ = gps2DistAzimuth(station_latitude, station_longitude,
                                    event_latitude, event_longitude)
    print st
    st.rotate(method="NE->RT", back_azimuth=baz)
    # write out
    print st
    for tr in st:
        comp = tr.stats.channel
        outfn = station[0] + "." + station[1] + "." + comp + ".sac"
        if suffix is not None and suffix != "":
            outfn = outfn + "." + suffix
        outpath = os.path.join(output_dir, outfn)
        print "file saved:", outpath
        tr.stats.sac['b'] = 0
        tr.stats.sac['iztype'] = 9
        tr.write(outpath, format="SAC")
Esempio n. 54
0
    def update(self, force=False):

        try:
            self._plot_receiver()
            self._plot_event()
        except AttributeError:
            return

        if (not bool(self.ui.auto_update_check_box.checkState()) and
                self.ui.finsource_tab.currentIndex() == 1 and not force and
                self.st_copy is None):
            return

        components = ["z", "n", "e"]
        components_map = {0: ("Z", "N", "E"),
                          1: ("Z", "R", "T")}

        components_choice = int(self.ui.components_combo.currentIndex())

        label_map = {0: {"z": "vertical", "n": "north", "e": "east"},
                     1: {"z": "vertical", "n": "radial", "e": "transverse"}}

        for component in components:
            p = getattr(self.ui, "%s_graph" % component)
            p.setTitle(label_map[components_choice][component].capitalize() +
                       " component")

        if self.ui.finsource_tab.currentIndex() == 0:
            src_latitude = self.source.latitude
            src_longitude = self.source.longitude
            src_depth_in_m = self.source.depth_in_m
        else:
            src_latitude = self.finite_source.hypocenter_latitude
            src_longitude = self.finite_source.hypocenter_longitude
            src_depth_in_m = self.finite_source.hypocenter_depth_in_m

        rec = self.receiver
        try:
            # Grab resampling settings from the UI.
            if bool(self.ui.resample_check_box.checkState()):
                dt = float(self.ui.resample_factor.value())
                dt = self.instaseis_db.info.dt / dt
            else:
                dt = None
            if self.ui.finsource_tab.currentIndex() == 0:
                st = self.instaseis_db.get_seismograms(
                    source=self.source, receiver=self.receiver, dt=dt,
                    components=components_map[components_choice])
            elif (not bool(self.ui.auto_update_check_box.checkState()) and
                    self.ui.finsource_tab.currentIndex() == 1 and
                    not force):
                st = self.st_copy.copy()
            else:
                prog_diag = QtGui.QProgressDialog(
                    "Calculating", "Cancel", 0, len(self.finite_source), self)
                prog_diag.setWindowModality(QtCore.Qt.WindowModal)
                prog_diag.setMinimumDuration(0)

                def get_prog_fct():
                    def set_value(value, count):
                        prog_diag.setValue(value)
                        if prog_diag.wasCanceled():
                            return True
                    return set_value

                prog_diag.setValue(0)
                st = self.instaseis_db.get_seismograms_finite_source(
                    sources=self.finite_source, receiver=self.receiver, dt=dt,
                    components=('Z', 'N', 'E'),
                    progress_callback=get_prog_fct())
                prog_diag.setValue(len(self.finite_source))
                if not st:
                    return

                baz = geodetics.gps2DistAzimuth(
                    self.finite_source.CMT.latitude,
                    self.finite_source.CMT.longitude,
                    rec.latitude, rec.longitude)[2]
                self.st_copy = st.copy()
                st.rotate('NE->RT', baz)
                st += self.st_copy
                self.st_copy = st.copy()

            if self.ui.finsource_tab.currentIndex() == 1 \
                    and bool(self.ui.plot_CMT_check_box.checkState()):
                st_cmt = self.instaseis_db.get_seismograms(
                    source=self.finite_source.CMT, receiver=self.receiver,
                    dt=dt, components=components_map[components_choice],
                    reconvolve_stf=True)
            else:
                st_cmt = None

            # check filter values from the UI
            zp = bool(self.ui.zero_phase_check_box.checkState())
            if bool(self.ui.lowpass_check_box.checkState()):
                try:
                    freq = 1.0 / float(self.ui.lowpass_period.value())
                    st.filter('lowpass', freq=freq, zerophase=zp)
                    if st_cmt is not None:
                        st_cmt.filter('lowpass', freq=freq, zerophase=zp)
                except ZeroDivisionError:
                    # this happens when typing in the lowpass_period box
                    pass

            if bool(self.ui.highpass_check_box.checkState()):
                try:
                    freq = 1.0 / float(self.ui.highpass_period.value())
                    st.filter('highpass', freq=freq, zerophase=zp)
                    if st_cmt is not None:
                        st_cmt.filter('highpass', freq=freq, zerophase=zp)
                except ZeroDivisionError:
                    # this happens when typing in the highpass_period box
                    pass

        except AttributeError:
            return

        if bool(self.ui.tt_times.checkState()):
            great_circle_distance = geodetics.locations2degrees(
                src_latitude, src_longitude,
                rec.latitude, rec.longitude)
            self.tts = tau_model.get_travel_times(
                source_depth_in_km=src_depth_in_m / 1000.0,
                distance_in_degree=great_circle_distance)

        for ic, component in enumerate(components):
            plot_widget = getattr(self.ui, "%s_graph" % component.lower())
            plot_widget.clear()
            tr = st.select(component=components_map[components_choice][ic])[0]
            times = tr.times()
            plot_widget.plot(times, tr.data, pen="k")
            plot_widget.ptp = tr.data.ptp()
            if st_cmt is not None:
                tr = st_cmt.select(
                    component=components_map[components_choice][ic])[0]
                times = tr.times()
                plot_widget.plot(times, tr.data, pen="r")

            if bool(self.ui.tt_times.checkState()):
                tts = []
                for tt in self.tts:
                    if tt.time >= times[-1]:
                        continue
                    tts.append(tt)
                    if tt.name[0].lower() == "p":
                        pen = "#008c2866"
                    else:
                        pen = "#95000066"
                    plot_widget.addLine(x=tt.time, pen=pen, z=-10)
                self.tts = tts
        self.set_info()
Esempio n. 55
0
def vespagram(stream, ev, inv, method, frqlow, frqhigh, baz, scale, nthroot=4,
              filter=True, static3D=False, vel_corr=4.8, sl=(0.0, 10.0, 0.5),
              align=False, align_phase=['P', 'Pdiff'], plot_trace=True):
    """
    vespagram wrapper routine for MESS 2014.

    :param stream: Waveforms for the array processing.
    :type stream: :class:`obspy.core.stream.Stream`
    :param inventory: Station metadata for waveforms
    :type inventory: :class:`obspy.station.inventory.Inventory`
    :param method: Method used for the array analysis
        (one of "DLS": Delay and Sum, "PWS": Phase Weighted Stack).
    :type method: str
    :param frqlow: Low corner of frequency range for array analysis
    :type frqlow: float
    :param frqhigh: High corner of frequency range for array analysis
    :type frqhigh: float
    :param baz: pre-defined (theoretical or calculated) backazimuth used for calculation
    :type baz_plot: float
    :param scale: scale for plotting
    :type scale: float
    :param nthroot: estimating the nthroot for calculation of the beam
    :type nthroot: int
    :param filter: Whether to bandpass data to selected frequency range
    :type filter: bool
    :param static3D: static correction of topography using `vel_corr` as
        velocity (slow!)
    :type static3D: bool
    :param vel_corr: Correction velocity for static topography correction in
        km/s.
    :type vel_corr: float
    :param sl: Min/Max and stepwidthslowness for analysis
    :type sl: (float, float,float)
    :param align: whether to align the vespagram to a certain phase
    :type align: bool
    :param align_phase: phase to be aligned with (might be a list if simulateneous arivials are expected (P,PcP,Pdif)
    :type align: str
    :param plot_trace: if True plot the vespagram as wiggle plot, if False as density map
    :type align: bool
    """

    starttime = max([tr.stats.starttime for tr in stream])
    endtime = min([tr.stats.endtime for tr in stream])
    stream.trim(starttime, endtime)

    org = ev.preferred_origin() or ev.origins[0]
    ev_lat = org.latitude
    ev_lon = org.longitude
    ev_depth = org.depth/1000.  # in km
    ev_otime = org.time

    sll, slm, sls = sl
    sll /= KM_PER_DEG
    slm /= KM_PER_DEG
    sls /= KM_PER_DEG
    center_lon = 0.
    center_lat = 0.
    center_elv = 0.
    seismo = stream
    seismo.attach_response(inv)
    seismo.merge()
    sz = Stream()
    i = 0
    for tr in seismo:
        for station in inv[0].stations:
            if tr.stats.station == station.code:
                tr.stats.coordinates = \
                    AttribDict({'latitude': station.latitude,
                                'longitude': station.longitude,
                                'elevation': station.elevation})
                center_lon += station.longitude
                center_lat += station.latitude
                center_elv += station.elevation
                i += 1
        sz.append(tr)

    center_lon /= float(i)
    center_lat /= float(i)
    center_elv /= float(i)

    starttime = max([tr.stats.starttime for tr in stream])
    stt = starttime
    endtime = min([tr.stats.endtime for tr in stream])
    e = endtime
    stream.trim(starttime, endtime)

    #nut = 0
    max_amp = 0.
    sz.trim(stt, e)
    sz.detrend('simple')

    print sz
    fl, fh = frqlow, frqhigh
    if filter:
        sz.filter('bandpass', freqmin=fl, freqmax=fh, zerophase=True)

    if align:
        deg = []
        shift = []
        res = gps2DistAzimuth(center_lat, center_lon, ev_lat, ev_lon)
        deg.append(kilometer2degrees(res[0]/1000.))
        tt = getTravelTimes(deg[0], ev_depth, model='ak135')
        for item in tt:
            phase = item['phase_name']
            if phase in align_phase:
                try:
                    travel = item['time']
                    travel = ev_otime.timestamp + travel
                    dtime = travel - stt.timestamp
                    shift.append(dtime)
                except:
                    break
        for i, tr in enumerate(sz):
            res = gps2DistAzimuth(tr.stats.coordinates['latitude'],
                                  tr.stats.coordinates['longitude'],
                                  ev_lat, ev_lon)
            deg.append(kilometer2degrees(res[0]/1000.))
            tt = getTravelTimes(deg[i+1], ev_depth, model='ak135')
            for item in tt:
                phase = item['phase_name']
                if phase in align_phase:
                    try:
                        travel = item['time']
                        travel = ev_otime.timestamp + travel
                        dtime = travel - stt.timestamp
                        shift.append(dtime)
                    except:
                        break
        shift = np.asarray(shift)
        shift -= shift[0]
        AA.shifttrace_freq(sz, -shift)

    baz += 180.
    nbeam = int((slm - sll)/sls + 0.5) + 1
    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll=sll, slm=slm, sls=sls, baz=baz, stime=stt, method=method,
        nthroot=nthroot, etime=e, correct_3dplane=False, static_3D=static3D,
        vel_cor=vel_corr)

    start = UTCDateTime()
    slow, beams, max_beam, beam_max = AA.vespagram_baz(sz, **kwargs)
    print "Total time in routine: %f\n" % (UTCDateTime() - start)

    df = sz[0].stats.sampling_rate
    # Plot the seismograms
    npts = len(beams[0])
    print npts
    T = np.arange(0, npts/df, 1/df)
    sll *= KM_PER_DEG
    slm *= KM_PER_DEG
    sls *= KM_PER_DEG
    slow = np.arange(sll, slm, sls)
    max_amp = np.max(beams[:, :])
    #min_amp = np.min(beams[:, :])
    scale *= sls

    fig = plt.figure(figsize=(12, 8))

    if plot_trace:
        ax1 = fig.add_axes([0.1, 0.1, 0.85, 0.85])
        for i in xrange(nbeam):
            if i == max_beam:
                ax1.plot(T, sll + scale*beams[i]/max_amp + i*sls, 'r',
                         zorder=1)
            else:
                ax1.plot(T, sll + scale*beams[i]/max_amp + i*sls, 'k',
                         zorder=-1)
        ax1.set_xlabel('Time [s]')
        ax1.set_ylabel('slowness [s/deg]')
        ax1.set_xlim(T[0], T[-1])
        data_minmax = ax1.yaxis.get_data_interval()
        minmax = [min(slow[0], data_minmax[0]), max(slow[-1], data_minmax[1])]
        ax1.set_ylim(*minmax)
    #####
    else:
        #step = (max_amp - min_amp)/100.
        #level = np.arange(min_amp, max_amp, step)
        #beams = beams.transpose()
        #cmap = cm.hot_r
        cmap = cm.rainbow

        ax1 = fig.add_axes([0.1, 0.1, 0.85, 0.85])
        #ax1.contour(slow,T,beams,level)
        #extent = (slow[0], slow[-1], \
        #               T[0], T[-1])
        extent = (T[0], T[-1], slow[0] - sls * 0.5, slow[-1] + sls * 0.5)

        ax1.set_ylabel('slowness [s/deg]')
        ax1.set_xlabel('T [s]')
        beams = np.flipud(beams)
        ax1.imshow(beams, cmap=cmap, interpolation="nearest",
                   extent=extent, aspect='auto')

    ####
    result = "BAZ: %.2f Time %s" % (baz-180., stt)
    ax1.set_title(result)

    plt.show()
    return slow, beams, max_beam, beam_max
Esempio n. 56
0
def hilbert(params, segment):
    """@calculates hilbert transform for given segment.

    @param params
        seismon params dictionary
    @param segment
        [start,end] gps

    """

    from obspy.core.util.geodetics import gps2DistAzimuth

    ifo = seismon.utils.getIfo(params)
    ifolat, ifolon = seismon.utils.getLatLon(params)

    gpsStart = segment[0]
    gpsEnd = segment[1]

    # set the times
    duration = np.ceil(gpsEnd - gpsStart)

    dataAll = []
    print("Loading data...")

    for channel in params["channels"]:
        # make timeseries
        dataFull = seismon.utils.retrieve_timeseries(params, channel, segment)
        if dataFull == []:
            continue

        dataFull = dataFull / channel.calibration
        indexes = np.where(np.isnan(dataFull.data))[0]
        meanSamples = np.mean(
            np.ma.masked_array(dataFull.data, np.isnan(dataFull.data)))
        for index in indexes:
            dataFull[index] = meanSamples
        dataFull -= np.mean(dataFull.data)

        if np.mean(dataFull.data) == 0.0:
            print("data only zeroes... continuing\n")
            continue
        if len(dataFull.data) < 2 * channel.samplef:
            print("timeseries too short for analysis... continuing\n")
            continue

        #cutoff = 0.01
        #dataFull = dataFull.lowpass(cutoff, amplitude=0.9, order=3, method='scipy')

        dataAll.append(dataFull)

    if len(dataAll) == 0:
        print("No data... returning")
        return

    if params["doEarthquakes"]:
        earthquakesDirectory = os.path.join(params["path"], "earthquakes")
        earthquakesXMLFile = os.path.join(earthquakesDirectory,
                                          "earthquakes.xml")
        attributeDics = seismon.utils.read_eqmons(earthquakesXMLFile)

    else:
        attributeDics = []

    print("Performing Hilbert transform")
    for attributeDic in attributeDics:

        if params["ifo"] == "IRIS":
            attributeDic = seismon.eqmon.ifotraveltimes(
                attributeDic, "IRIS", channel.latitude, channel.longitude)
            traveltimes = attributeDic["traveltimes"]["IRIS"]
        else:
            traveltimes = attributeDic["traveltimes"][ifo]

        doTilt = 0
        for dataFull in dataAll:
            if "_X_" in dataFull.channel.name or "E" == dataFull.channel.name[
                    -1]:
                tsx = dataFull.data
            if "_Y_" in dataFull.channel.name or "N" == dataFull.channel.name[
                    -1]:
                tsy = dataFull.data
            if "_Z_" in dataFull.channel.name:
                tsz = dataFull.data
            if "_RY_" in dataFull.channel.name:
                tttilt = np.array(dataFull.times)
                tstilt = dataFull.data
                doTilt = 1

        tt = np.array(dataAll[0].times)
        fs = 1.0 / (tt[1] - tt[0])

        if doTilt:
            tstilt = np.interp(tt, tttilt, tstilt)

        Ptime = max(traveltimes["Ptimes"])
        Stime = max(traveltimes["Stimes"])
        Rtwotime = max(traveltimes["Rtwotimes"])
        RthreePointFivetime = max(traveltimes["RthreePointFivetimes"])
        Rfivetime = max(traveltimes["Rfivetimes"])
        distance = max(traveltimes["Distances"])

        indexes = np.intersect1d(
            np.where(tt >= Rfivetime)[0],
            np.where(tt <= Rtwotime)[0])
        indexes = np.intersect1d(
            np.where(tt >= tt[0])[0],
            np.where(tt <= tt[-1])[0])

        if len(indexes) == 0:
            continue

        indexMin = np.min(indexes)
        indexMax = np.max(indexes)
        tt = tt[indexes]
        tsx = tsx[indexes]
        tsy = tsy[indexes]
        tsz = tsz[indexes]

        if doTilt:
            tstilt = tstilt[indexes]

            cutoff_high = 0.01  # 10 MHz
            cutoff_low = 0.3
            n = 3
            worN = 16384
            B_low, A_low = scipy.signal.butter(n,
                                               cutoff_low / (fs / 2.0),
                                               btype='lowpass')
            #w_low, h_low = scipy.signal.freqz(B_low,A_low)
            w_low, h_low = scipy.signal.freqz(B_low, A_low, worN=worN)
            B_high, A_high = scipy.signal.butter(n,
                                                 cutoff_high / (fs / 2.0),
                                                 btype='highpass')
            w_high, h_high = scipy.signal.freqz(B_high, A_high, worN=worN)

            dataLowpass = scipy.signal.lfilter(B_low, A_low, tstilt,
                                               axis=0).view(dataFull.__class__)
            dataHighpass = scipy.signal.lfilter(
                B_high, A_high, tstilt, axis=0).view(dataFull.__class__)

            dataTilt = dataHighpass.view(dataHighpass.__class__)
            #dataTilt = tstilt.view(tstilt.__class__)
            dataTilt = gwpy.timeseries.TimeSeries(dataTilt)
            dataTilt.sample_rate = dataFull.sample_rate
            dataTilt.epoch = Rfivetime

        tszhilbert = scipy.signal.hilbert(tsz).imag
        tszhilbert = -tszhilbert

        dataHilbert = tszhilbert.view(tsz.__class__)
        dataHilbert = gwpy.timeseries.TimeSeries(dataHilbert)
        dataHilbert.sample_rate = dataFull.sample_rate
        dataHilbert.epoch = Rfivetime

        distance, fwd, back = gps2DistAzimuth(attributeDic["Latitude"],
                                              attributeDic["Longitude"],
                                              ifolat, ifolon)
        xazimuth, yazimuth = seismon.utils.getAzimuth(params)

        angle1 = fwd
        rot1 = np.array([[np.cos(angle1), -np.sin(angle1)],
                         [np.sin(angle1), np.cos(angle1)]])
        angle2 = xazimuth * (np.pi / 180.0)
        rot2 = np.array([[np.cos(angle2), -np.sin(angle2)],
                         [np.sin(angle2), np.cos(angle2)]])

        angleEQ = np.mod(angle1 + angle2, 2 * np.pi)
        rot = np.array([[np.cos(angleEQ), -np.sin(angleEQ)],
                        [np.sin(angleEQ), np.cos(angleEQ)]])

        twodarray = np.vstack([tsx, tsy])
        z = rot.dot(twodarray)
        tsxy = np.sum(z.T, axis=1)

        dataXY = tsxy.view(tsz.__class__)
        dataXY = gwpy.timeseries.TimeSeries(tsxy)
        dataXY.sample_rate = dataFull.sample_rate
        dataXY.epoch = Rfivetime

        dataHilbert = dataHilbert.resample(16)
        dataXY = dataXY.resample(16)

        if doTilt:
            dataTilt = dataTilt.resample(16)

        if params["doPlots"]:

            plotDirectory = params["path"] + "/Hilbert"
            seismon.utils.mkdir(plotDirectory)

            dataHilbert *= 1e6
            dataXY *= 1e6

            pngFile = os.path.join(plotDirectory,
                                   "%s.png" % (attributeDic["eventName"]))
            plot = gwpy.plotter.TimeSeriesPlot(figsize=[14, 8])

            kwargs = {"linestyle": "-", "color": "b"}
            plot.add_timeseries(dataHilbert, label="Hilbert", **kwargs)
            kwargs = {"linestyle": "-", "color": "g"}
            plot.add_timeseries(dataXY, label="XY", **kwargs)
            plot.ylabel = r"Velocity [$\mu$m/s]"
            plot.add_legend(loc=1, prop={'size': 10})

            plot.save(pngFile)
            plot.close()

        dataHilbert = tszhilbert.view(tsz.__class__)
        dataHilbert = gwpy.timeseries.TimeSeries(dataHilbert)
        dataHilbert.sample_rate = dataFull.sample_rate
        dataHilbert.epoch = Rfivetime
        dataHilbert = dataHilbert.resample(16)

        angles = np.linspace(0, 2 * np.pi, 10)
        xcorrs = []
        for angle in angles:
            rot = np.array([[np.cos(angle), -np.sin(angle)],
                            [np.sin(angle), np.cos(angle)]])

            twodarray = np.vstack([tsx, tsy])
            z = rot.dot(twodarray)
            tsxy = np.sum(z.T, axis=1)

            dataXY = tsxy.view(tsz.__class__)
            dataXY = gwpy.timeseries.TimeSeries(tsxy)
            dataXY.sample_rate = dataFull.sample_rate
            dataXY.epoch = Rfivetime
            dataXY = dataXY.resample(16)

            xcorr, lags = seismon.utils.xcorr(dataHilbert.data,
                                              dataXY.data,
                                              maxlags=1)
            xcorrs.append(xcorr[1])
        xcorrs = np.array(xcorrs)

        angleMax = angles[np.argmax(xcorrs)]
        rot = np.array([[np.cos(angleMax), -np.sin(angleMax)],
                        [np.sin(angleMax), np.cos(angleMax)]])

        twodarray = np.vstack([tsx, tsy])
        z = rot.dot(twodarray)
        tsxy = np.sum(z.T, axis=1)

        dataXY = tsxy.view(tsz.__class__)
        dataXY = gwpy.timeseries.TimeSeries(tsxy)
        dataXY.sample_rate = dataFull.sample_rate
        dataXY.epoch = Rfivetime
        dataXY = dataXY.resample(16)

        if params["doPlots"]:

            plotDirectory = params["path"] + "/Hilbert"
            seismon.utils.mkdir(plotDirectory)

            dataHilbert *= 1e6
            dataXY *= 1e6

            if doTilt:
                dataTilt *= 1e6 * (9.81) / (2 * np.pi * 0.01)

            pngFile = os.path.join(plotDirectory,
                                   "%s-max.png" % (attributeDic["eventName"]))
            plot = gwpy.plotter.TimeSeriesPlot(figsize=[14, 8])

            kwargs = {"linestyle": "-", "color": "b"}
            plot.add_timeseries(dataHilbert, label="Hilbert", **kwargs)
            kwargs = {"linestyle": "-", "color": "g"}
            plot.add_timeseries(dataXY, label="XY", **kwargs)
            plot.ylabel = r"Velocity [$\mu$m/s]"
            plot.add_legend(loc=1, prop={'size': 10})

            plot.save(pngFile)
            plot.close()

            pngFile = os.path.join(plotDirectory,
                                   "%s-rot.png" % (attributeDic["eventName"]))
            plot = gwpy.plotter.Plot(figsize=[14, 8])

            kwargs = {"linestyle": "-", "color": "b"}
            plot.add_line(angles, xcorrs, label="Xcorrs", **kwargs)
            ylim = [plot.ylim[0], plot.ylim[1]]
            kwargs = {"linestyle": "--", "color": "r"}
            plot.add_line([angleEQ, angleEQ], ylim, label="EQ", **kwargs)
            plot.ylabel = r"XCorr"
            plot.xlabel = r"Angle [rad]"
            plot.add_legend(loc=1, prop={'size': 10})

            plot.save(pngFile)
            plot.close()

        dataHilbert = dataHilbert.resample(1.0)
        dataXY = dataXY.resample(1.0)

        if doTilt:
            dataTilt = dataTilt.resample(1.0)

        dataHilbertAbs = np.absolute(dataHilbert)
        dataXYAbs = np.absolute(dataXY)
        dataRatio = dataXYAbs / dataHilbertAbs

        meanValue = np.median(np.absolute(dataRatio))
        dataXYScale = dataXY / meanValue

        dataXYScale = gwpy.timeseries.TimeSeries(dataXYScale)
        dataXYScale.sample_rate = dataXY.sample_rate
        dataXYScale.epoch = dataXY.epoch

        if params["doPlots"]:

            plotDirectory = params["path"] + "/Hilbert"
            seismon.utils.mkdir(plotDirectory)

            pngFile = os.path.join(
                plotDirectory, "%s-max-abs.png" % (attributeDic["eventName"]))
            plot = gwpy.plotter.TimeSeriesPlot(figsize=[14, 8])

            kwargs = {"linestyle": "-", "color": "b"}
            plot.add_timeseries(dataHilbertAbs, label="Hilbert", **kwargs)
            kwargs = {"linestyle": "-", "color": "g"}
            plot.add_timeseries(dataXYAbs, label="XY", **kwargs)
            plot.ylabel = r"Velocity [$\mu$m/s]"
            plot.add_legend(loc=1, prop={'size': 10})

            plot.save(pngFile)
            plot.close()

            pngFile = os.path.join(
                plotDirectory,
                "%s-max-scale.png" % (attributeDic["eventName"]))
            plot = gwpy.plotter.TimeSeriesPlot(figsize=[14, 8])

            kwargs = {"linestyle": "-", "color": "b"}
            plot.add_timeseries(dataHilbert, label="Hilbert", **kwargs)
            kwargs = {"linestyle": "-", "color": "g"}
            plot.add_timeseries(dataXYScale, label="XY Scaled", **kwargs)
            plot.ylabel = r"Velocity [$\mu$m/s]"
            plot.add_legend(loc=1, prop={'size': 10})

            plot.save(pngFile)
            plot.close()

            pngFile = os.path.join(
                plotDirectory, "%s-ratio.png" % (attributeDic["eventName"]))
            plot = gwpy.plotter.TimeSeriesPlot(figsize=[14, 8])

            kwargs = {"linestyle": "-", "color": "k"}
            plot.add_timeseries(np.absolute(dataRatio),
                                label="Ratio",
                                **kwargs)
            plot.ylabel = r"Ratio [XY / Hilbert(Z)]"

            xlim = [plot.xlim[0], plot.xlim[1]]
            kwargs = {"linestyle": "-", "color": "r"}
            plot.add_line(xlim, [0.78, 0.78], label="PREM", **kwargs)

            plot.title = "Median Ratio: %.3f" % (meanValue)

            #plot.ylim = [0,100]

            plot.axes[0].set_yscale("log")
            plot.add_legend(loc=1, prop={'size': 10})

            plot.save(pngFile)
            plot.close()

            if doTilt:
                pngFile = os.path.join(
                    plotDirectory,
                    "%s-max-scale-tilt.png" % (attributeDic["eventName"]))
                plot = gwpy.plotter.TimeSeriesPlot(figsize=[14, 8])

                kwargs = {"linestyle": "-", "color": "b"}
                plot.add_timeseries(dataHilbert, label="Hilbert", **kwargs)
                kwargs = {"linestyle": "-", "color": "g"}
                plot.add_timeseries(dataXYScale, label="XY Scaled", **kwargs)
                kwargs = {"linestyle": "-", "color": "k"}
                plot.add_timeseries(dataTilt, label="Tiltmeter", **kwargs)
                plot.ylabel = r"Velocity [$\mu$m/s]"
                plot.add_legend(loc=1, prop={'size': 10})

                plot.save(pngFile)
                plot.close()
Esempio n. 57
0
kkn4_Re = R[:, 1]
kkn4_Ru = R[:, 2]
R = genfromtxt(u'/Users/dmelgar/Nepal2015/Response_Spectra/NAST.vel.resp',
               usecols=[1, 2, 3])
nast_Rn = R[:, 0]
nast_Re = R[:, 1]
nast_Ru = R[:, 2]
R = genfromtxt(u'/Users/dmelgar/Nepal2015/Response_Spectra/KATNP.vel.resp',
               usecols=[1, 2, 3])
katnp_Rn = R[:, 0]
katnp_Re = R[:, 1]
katnp_Ru = R[:, 2]

#Get distances
[d_nast, a, b] = gps2DistAzimuth(nast_n[0].stats['sac']['stla'],
                                 nast_n[0].stats['sac']['stlo'], epicenter[1],
                                 epicenter[0])
d_nast = int(d_nast / 1000)
[d_kkn4, a, b] = gps2DistAzimuth(kkn4_n[0].stats['sac']['stla'],
                                 kkn4_n[0].stats['sac']['stlo'], epicenter[1],
                                 epicenter[0])
d_kkn4 = int(d_kkn4 / 1000)
[d_katnp, a, b] = gps2DistAzimuth(katnp_n[0].stats['sac']['stla'],
                                  katnp_n[0].stats['sac']['stlo'],
                                  epicenter[1], epicenter[0])
d_katnp = int(d_katnp / 1000)

kkn4_n.trim(starttime=time_epi)
kkn4_e.trim(starttime=time_epi)
kkn4_u.trim(starttime=time_epi)
nast_n.trim(starttime=time_epi)