Esempio n. 1
0
    def call(self):
        fn = self.input_filename()
        with open(fn) as f:
            read_data = f.readlines()

        allaz = {}
        for i, line in enumerate(read_data):
            fields = string.split(line)
            k = string.lower(fields[0])
            if not k == '#':
                allaz[k] = float(fields[1])

        p = self.get_pile()

        key = lambda tr: (tr.network, tr.station)

        tmin, tmax = self.get_selected_time_range(fallback=True)
        for traces in p.chopper_grouped(tmin=tmin, tmax=tmax, gather=key):
            if not traces:
                continue

            # rotate all stations except d05
            if self.d05_included(traces):
                continue

            if self.want_pre_rotate(traces):
                az = -1 * allaz[traces[0].station]
                rotated = trace.rotate(traces, az, ('E', 'N'), ('EX', 'NY'))
                print 'using pre-rotated traces\n%s %s ' % tuple(rotated)
                rot_from = ('NY', 'EX')
                rot_to = ('NN', 'EN')
            else:
                rotated = [
                    tr.copy() for tr in traces if tr.channel[-1] in '34'
                ]
                for tr in rotated:
                    tr.set_channel(tr.channel.upper())

                print 'using UN-pre-rotated traces\n%s %s ' % tuple(rotated)
                rot_from = ('HH4', 'HH3')
                rot_to = ('N', 'E')

            az = allaz[traces[0].station]

            n_new, e_new = trace.rotate(rotated, az, rot_from, rot_to)
            n_new.set_codes(station=traces[0].station)
            e_new.set_codes(station=traces[0].station)
            self.add_traces([n_new, e_new])
def RotateAllTraces(degrange, Traces):
    '''
    :param degrange:    list of degree values to rotate
    :param Traces:      list of Traces to rotate
    :return:            dict containing degrees as keys and 
                                        rotatedTraces
    '''
    rotTrac={}
    for deg in degrange:
        rotatedTraces = trace.rotate(Traces, deg, ['n', 'e'], ['p1rot', 'p2rot']) 
        rotTrac[deg] = rotatedTraces
    return rotTrac
Esempio n. 3
0
    def testRotation(self):
        s2 = math.sqrt(2.)
        ndata = num.array([s2, s2], dtype=num.float)
        edata = num.array([s2, 0.], dtype=num.float)
        dt = 1.0
        n = trace.Trace(deltat=dt, ydata=ndata, tmin=100, channel='N')
        e = trace.Trace(deltat=dt, ydata=edata, tmin=100, channel='E')
        rotated = trace.rotate([n, e], 45., ['N', 'E'], ['R', 'T'])
        for tr in rotated:
            if tr.channel == 'R':
                r = tr
            if tr.channel == 'T':
                t = tr

        assert numeq(r.get_ydata(), [2., 1.], 1.0e-6)
        assert numeq(t.get_ydata(), [0., -1], 1.0e-6)
Esempio n. 4
0
 def testRotation(self):
     s2 = math.sqrt(2.)
     ndata = num.array([s2,s2], dtype=num.float)
     edata = num.array([s2,0.], dtype=num.float)
     dt = 1.0
     n = trace.Trace(deltat=dt, ydata=ndata, tmin=100, channel='N')
     e = trace.Trace(deltat=dt, ydata=edata, tmin=100, channel='E')
     rotated = trace.rotate([n,e], 45., ['N','E'], ['R','T'])
     for tr in rotated:
         if tr.channel == 'R':
             r = tr
         if tr.channel == 'T':
             t = tr
     
     assert numeq(r.get_ydata(), [2.,1.], 1.0e-6)
     assert numeq(t.get_ydata(), [ 0., -1 ], 1.0e-6)
Esempio n. 5
0
                
                if displacements:
                    if projections:
                        for project in projections:
                            matrix, in_channels, out_channels = project(out_station)
                            projected = trace.project(displacements, matrix, in_channels, out_channels)
                            displacements.extend(projected)
                            for tr in projected:
                                for ch in out_channels:
                                    if ch.name == tr.channel:
                                        out_station.add_channel(ch)
                    
                    if rotations:
                        for rotate in rotations:
                            angle, in_channels, out_channels  = rotate(out_station)
                            rotated = trace.rotate(displacements, angle, in_channels, out_channels)
                            displacements.extend(rotated)
                            for tr in rotated:
                                for ch in out_channels:
                                    if ch.name == tr.channel:
                                        out_station.add_channel(ch)
                        
                yield displacements
                
    def get_restitution(self, tr, allowed_methods):
        if 'integration' in allowed_methods:
            trace.IntegrationResponse()
        else:
            raise Exception('only "integration" restitution method is allowed')

Esempio n. 6
0
def prep_orient(datapath,
                st,
                loc,
                catalog,
                dir_ro,
                v_rayleigh,
                bp,
                dt_start,
                dt_stop,
                ccmin=0.80,
                plot_heatmap=False,
                plot_distr=False,
                debug=False):
    """
    Perform orientation analysis using Rayleigh waves, main function.

    time wdw: 20s before 4.0km/s arrival and 600 s afterwards
    (Stachnik et al. 2012)
    - compute radial component for back values of 0 to 360 deg
    - for each c-c of hilbert(R) with Z comp.
    - call plotting functions and/or write results to file

    :param datapath: path to rrd data
    :param st: current station (pyrocko station object)
    :param catalog: list of pyrocko events used for analysis
    :param dir_ro: output directory
    :param plot_heatmap: bool, optional
    :param plot_distr: bool, optional
    """
    logs = logging.getLogger('prep_orient')
    st_data_pile = pile.make_pile(datapath,
                                  regex='%s_%s_' % (st.network, st.station),
                                  show_progress=False)
    n_ev = len(catalog)

    if st_data_pile.tmin is not None and st_data_pile.tmax is not None:

        # calculate dist between all events and current station
        r_arr_by_ev = num.empty(n_ev)
        ev_lats = num.asarray([ev.lat for ev in catalog])
        ev_lons = num.asarray([ev.lon for ev in catalog])
        dists = distance_accurate50m_numpy(a_lats=ev_lats,
                                           a_lons=ev_lons,
                                           b_lats=st.lat,
                                           b_lons=st.lon,
                                           implementation='c')
        r_arr_by_ev = (dists / 1000.) / v_rayleigh
        cc_i_ev_vs_rota = num.empty((n_ev, 360))
        rot_angles = range(-180, 180, 1)
        for i_ev, ev in enumerate(catalog):
            arrT = ev.time + r_arr_by_ev[i_ev]

            start_twd1 = ev.time
            end_twd1 = arrT + 1800

            trZ = get_tr_by_cha(st_data_pile, start_twd1, end_twd1, loc, 'Z')
            trR = get_tr_by_cha(st_data_pile, start_twd1, end_twd1, loc, 'R')
            trT = get_tr_by_cha(st_data_pile, start_twd1, end_twd1, loc, 'T')

            start_twd2 = ev.time + r_arr_by_ev[i_ev] - dt_start
            end_twd2 = arrT + dt_stop

            if len(trZ) == 1 and len(trR) == 1 and len(trT) == 1:
                trZ = trZ[0]
                trR = trR[0]
                trT = trT[0]
                # debugging - window selection:
                if debug is True:
                    trace.snuffle([trZ, trR, trT],
                                  markers=[
                                      pm.Marker(nslc_ids=[
                                          trZ.nslc_id, trR.nslc_id, trT.nslc_id
                                      ],
                                                tmin=start_twd2,
                                                tmax=end_twd2),
                                      pm.Marker(nslc_ids=[
                                          trZ.nslc_id, trR.nslc_id, trT.nslc_id
                                      ],
                                                tmin=arrT,
                                                tmax=arrT + 3)
                                  ])

            else:
                cc_i_ev_vs_rota[i_ev, :] = num.nan
                continue

            try:
                trZ.bandpass(bp[0], bp[1], bp[2])
                trZ.chop(tmin=start_twd2, tmax=end_twd2)
            except trace.NoData:
                logs.warning('no data %s %s %s' % (trZ, trR, trT))
                continue

            for i_r, r in enumerate(rot_angles):
                print('rotation angle [deg]: %5d' % r, end='\r')
                rot_2, rot_3 = trace.rotate(traces=[trR, trT],
                                            azimuth=r,
                                            in_channels=['R', 'T'],
                                            out_channels=['2', '3'])
                rot_2_y = rot_2.ydata
                rot_2_hilb = num.imag(trace.hilbert(rot_2_y, len(rot_2_y)))
                rot_2_hilb_tr = trace.Trace(deltat=rot_2.deltat,
                                            ydata=rot_2_hilb,
                                            tmin=rot_2.tmin)
                # problem: rot_2 and rot_2_hilb look exactly the same!
                # --> no phase shift. why? should be num.imag!!!
                # trace.snuffle([rot_2, rot_2_hilb_tr])
                rot_2_hilb_tr.bandpass(bp[0], bp[1], bp[2])
                rot_2_hilb_tr.chop(tmin=start_twd2, tmax=end_twd2)

                # if st.station == 'RORO' and r == 0:
                #     trace.snuffle([rot_2_hilb_tr, trZ])
                # normalize traces
                trZ.ydata /= abs(max(trZ.ydata))
                rot_2_hilb_tr.ydata /= abs(max(rot_2_hilb_tr.ydata))

                c = trace.correlate(trZ,
                                    rot_2_hilb_tr,
                                    mode='valid',
                                    normalization='normal')

                t, coef = c.max()
                t2, coef2 = max_or_min(c)
                '''
                if st.station == 'MATE' and r == 0:
                    print(i_ev, ev.name, ev.depth)
                    print(r, t, coef, t2, coef2)
                    trace.snuffle([trZ, trR, rot_2_hilb_tr])
                '''
                cc_i_ev_vs_rota[i_ev, i_r] = coef
        '''
        if st.station == 'MATE':
            for i_ev in range(n_ev):
                print(num.argmax(cc_i_ev_vs_rota[i_ev,:]),
                      num.max(cc_i_ev_vs_rota[i_ev,:]))
        '''

        if plot_heatmap is True:
            fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 2))

            cax = ax.imshow(cc_i_ev_vs_rota,
                            interpolation='nearest',
                            vmin=-1.0,
                            vmax=1.0,
                            aspect='auto',
                            extent=[-180, 180, n_ev, 0],
                            cmap='binary')
            ax.set_ylabel('i_ev')
            ax.set_xlabel('Correction angle (deg)')
            ax.set_title('%s %s' % (st.network, st.station))
            cbar = fig.colorbar(cax,
                                ticks=[0, 0.5, 1.0],
                                orientation='horizontal',
                                fraction=0.05,
                                pad=0.5)
            cbar.ax.set_xticklabels(['0', '0.5', '1.0'])
            plt.tight_layout()
            # plt.show(fig)
            fig.savefig(
                os.path.join(
                    dir_ro, '%s_%s_%s_rot_cc_heatmap.png' %
                    (st.network, st.station, loc)))
            plt.close()

        if plot_distr is True:
            plot_ccdistr_each_event(cc_i_ev_vs_rota, catalog, rot_angles, st,
                                    loc, dir_ro)

        median_a, mean_a, std_a, switched, n_ev =\
            get_m_angle_switched(cc_i_ev_vs_rota, catalog, st, ccmin)

        dict_ev_angle = get_m_angle_all(cc_i_ev_vs_rota, catalog, st, ccmin)

        return median_a, mean_a, std_a, switched, dict_ev_angle, n_ev