Example #1
0
def stack(st, stats=None, kw_stack={}, kw_snr={}):
    """
    Stack traces in stream.
    """
    if st.count() == 0:
        logger.error('No traces!')
        return st
    elif st.count() == 1:
        return st

    # Find lap
    if kw_stack.get('sort', False):
        st.sort(keys=['endtime'])
        st.trim(
            starttime=st[0].stats.starttime,
            endtime=st[0].stats.endtime,
            pad=True,
            fill_value=0,
        )

    sk = Trace()
    data = _data_stack(st, **kw_stack, **kw_snr)
    if data is None:
        return
    else:
        sk.data = data
        sk.stats = _hdr_stack(st, stats, **kw_stack, **kw_snr)

        key_snr = kw_stack.get('snr', 'user2')
        weight = kw_stack.get('weight', 'None').lower()
        if 'none' not in weight:
            sk.stats.sac[key_snr] = snr(sk, **kw_snr)

        return sk
Example #2
0
def rand_stack(st, stats=None, kw_stack={}, kw_snr={}):
    nsub = kw_stack.get('nsub', 4)
    key_nsrc = kw_stack.get('key_nsrc', 'user0')

    ntr = st.count()
    if ntr < 2:
        return st

    sk = Trace()
    sk.stats = _hdr_stack(st, stats, **kw_stack, **kw_snr)

    if ntr <= nsub:
        for tr in st:
            yield tr
    else:
        ind = np.arange(ntr)
        np.random.shuffle(ind)
        for sub in np.array_split(ind, nsub):
            data = 0
            for i in sub:
                data += st[i].data
            n = sub.size
            data /= n
            sk.stats.sac[key_nsrc] = n
            sk.data = data
            yield sk

    return
Example #3
0
def sym_xc(xc, noeven=False):
    """
    Symmetrize a cross-correlation.
    """
    pair = f'{xc.stats.sac.kevnm.split()[0]}-{xc.stats.station}'
    if not _is_sym(xc):
        logger.debug(f'Asymmetric {pair}')
        end = min(abs(xc.stats.sac.b), xc.stats.sac.e)
        xc = sliced(xc, -end, end)
    if _even_npts(xc) and noeven:
        logger.error(f'Even npts to symmexcize {pair}')
    else:
        sym = Trace()
        sym.data = _data_sym(xc.data)
        sym.stats = _hd_sym(xc.stats, npts=sym.data.size)
        return sym
Example #4
0
    def get_stream(self,
                   processed_path,
                   kstnm,
                   kinst,
                   force_without_loc=False):
        # Check if an interpolated station location exists
        if self.station_loc is None and not force_without_loc:
            return

        # Save data into a Stream object
        trace = Trace()
        trace.stats = self.obspy_trace_stats
        trace.data = self.processed_data

        stream = Stream(traces=[trace])

        return stream
Example #5
0
    def to_sac_and_mseed(self, export_path, station_number, force_without_loc):
        # Check if file exist
        export_path_sac = export_path + self.get_export_file_name() + ".sac"
        export_path_msd = export_path + self.get_export_file_name() + ".mseed"
        #export_path_wav = export_path + self.get_export_file_name() + ".wav"
        if os.path.exists(export_path_sac) and os.path.exists(export_path_msd):
            return

        # Check if the station location have been calculated
        if self.station_loc is None and not force_without_loc:
            print self.get_export_file_name() + ": Skip sac/mseed generation, wait the next ascent to compute location"
            return

        # Fill header info
        stats = Stats()
        stats.sampling_rate = self.decimated_fs
        stats.network = "MH"
        stats.station = station_number
        stats.starttime = self.date

        stats.sac = dict()
        if not force_without_loc:
            stats.sac["stla"] = self.station_loc.latitude
            stats.sac["stlo"] = self.station_loc.longitude
        stats.sac["stdp"] = self.depth
        stats.sac["user0"] = self.snr
        stats.sac["user1"] = self.criterion
        stats.sac["iztype"] = 9  # 9 == IB in sac format

        # Save data into a Stream object
        trace = Trace()
        trace.stats = stats
        trace.data = self.data
        stream = Stream(traces=[trace])

        # Save stream object
        print export_path_sac
        stream.write(export_path_sac, format='SAC')
        print export_path_msd
        stream.write(export_path_msd, format='MSEED')
Example #6
0
def invert_raw():
    ######################################
    # Binary
    ######################################
    if mode == "Binary":
        catch_files = []
        files = glob.glob(file_path + "*")
        for file in files:
            catch = re.findall(
                ".*[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}_[0-9]{2}_[0-9]{2}\.[0-9]{6}",
                file)
            if len(catch) > 0:
                catch_files.append(file)

        ######################################
        # Freq file
        ######################################
        freq_file = glob.glob(file_path + "*_freq")
        if len(freq_file) > 1:
            print "warning : more than one freq file in folder"
        if len(freq_file) == 0:
            print "warning no freq file discovered use :" + str(sampling_freq)
        else:
            content = "40.000000"
            with open(freq_file[0], "r") as f:
                content = f.read()
            sampling_freq = float(content)
            print "Sampling used : " + str(sampling_freq)
        files_nb = len(catch_files)
        file_offset = 1
        for catch_file in catch_files:
            print catch_file
            print "File nb : " + str(file_offset) + "/" + str(files_nb)
            date = UTCDateTime(
                re.findall(
                    ".*([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}_[0-9]{2}_[0-9]{2}\.[0-9]{6})",
                    catch_file)[0])
            rawdata = numpy.fromfile(catch_file, numpy.int32)
            ######################################
            # Plot plotly file
            ######################################
            # Add acoustic values to the graph
            #data_line = graph.Scattergl(x=[date + i/sampling_freq for i in range(0,len(rawdata))],
            #                          y=rawdata,
            #                          name="counts",
            #                          line=dict(color='blue', width=2),
            #                          mode='lines')

            #plotlydata = [data_line]

            #layout = graph.Layout(title="Plot",
            #                      xaxis=dict(title='Date', titlefont=dict(size=18)),
            #                      yaxis=dict(title='Counts', titlefont=dict(size=18)),
            #                      hovermode='closest'
            #                      )

            #plotly.plot({'data': plotlydata, 'layout': layout},
            #            filename=catch_file + ".html",
            #            auto_open=False)

            ######################################
            # Create SAC file
            ######################################

            # Fill header info
            stats = Stats()
            stats.sampling_rate = sampling_freq
            stats.network = "test"
            stats.station = 0
            stats.starttime = date
            stats.sac = dict()

            # Save data into a Stream object
            trace = Trace()
            trace.stats = stats
            trace.data = rawdata
            stream = Stream(traces=[trace])

            # Save stream object
            stream.write(catch_file + ".sac", format='SAC')
            stream.write(catch_file + ".mseed", format='MSEED')
            file_offset = file_offset + 1
    else:
        ######################################
        # Text
        ######################################
        #filename = "tool_invert_raw/1553771378.490936"
        #date = UTCDateTime(1553771378.490936)
        # text
        #f = open(filename, 'r')
        #rawdata = numpy.array(f.read().rstrip('\n').split('\n'))
        #f.close()
        # binary
        ######################################
        # Plot plotly file
        ######################################

        # Add acoustic values to the graph
        data_line = graph.Scattergl(
            x=[date + i / sampling_freq for i in range(0, len(rawdata))],
            y=rawdata,
            name="counts",
            line=dict(color='blue', width=2),
            mode='lines')

        plotlydata = [data_line]

        layout = graph.Layout(title="Plot",
                              xaxis=dict(title='Date',
                                         titlefont=dict(size=18)),
                              yaxis=dict(title='Counts',
                                         titlefont=dict(size=18)),
                              hovermode='closest')

        plotly.plot({
            'data': plotlydata,
            'layout': layout
        },
                    filename=filename + ".html",
                    auto_open=False)

        ######################################
        # Create SAC file
        ######################################

        # Fill header info
        stats = Stats()
        stats.sampling_rate = sampling_freq
        stats.network = "test"
        stats.station = 0
        stats.starttime = date
        stats.sac = dict()

        # Save data into a Stream object
        trace = Trace()
        trace.stats = stats
        trace.data = rawdata
        stream = Stream(traces=[trace])

        # Save stream object
        stream.write(filename + ".sac", format='SAC')
Example #7
0
        # store stats
        stationname = sta + '%04d' % i
        channelnameN = cha + '%s' % 'N'
        channelnameE = cha + '%s' % 'E'

        # for NS components
        statsN = Stats()
        statsN.sampling_rate = 1.0 / sampling_rate_x
        statsN.delta = sampling_rate_x
        statsN.starttime = starttime
        statsN.npts = len(traceN.data)
        statsN.network = net
        statsN.station = stationname
        statsN.location = ''
        statsN.channel = channelnameN
        traceN.stats = statsN
        traceN.stats.sac = obspy.core.AttribDict()
        traceN.stats.sac.back_azimuth = plottheta  # use this as azimuth of station

        #---applying filters---#
        traceN.filter('bandpass', freqmin=freqmin, freqmax=freqmax)
        tN = traceN.stats.starttime
        traceN.trim(starttime=tN, endtime=tN + trim_end_time)
        traceN.taper(0.05, side='right')

        #----------------------#
        stemp += Stream(traceN)
        # for EW components
        statsE = Stats()
        statsE.sampling_rate = 1.0 / sampling_rate_z
        statsE.delta = sampling_rate_z