core.py 8.6 KB
Newer Older
Sebastian Heimann's avatar
Sebastian Heimann committed
1
2
3
4
import sys
import os
import logging
import os.path as op
5
import shutil
Sebastian Heimann's avatar
Sebastian Heimann committed
6
7
8
9
10
11
12
13
14
15
16

import numpy as num

from pyrocko import pile, trace, util, io
from pyrocko.parstack import parstack

from lassie import common, plot, grid as gridmod

logger = logging.getLogger('lassie.core')


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def check_data_consistency(p, receivers):
    nslc_ids = p.nslc_ids.keys()
    nsl_ids = [nslc_id[:3] for nslc_id in nslc_ids]
    r_ids = [r.codes for r in receivers]

    r_not_in_p = []
    t_not_in_r = []
    for r in receivers:
        if r.codes[:3] not in nsl_ids:
            r_not_in_p.append(r.codes)

    for nsl_id in nsl_ids:
        if nsl_id not in r_ids:
            t_not_in_r.append(nsl_id)

    if len(r_not_in_p) != 0.:
        logger.warn('following receivers have no traces in data set:')
        for nsl_id in r_not_in_p:
            logger.warn(nsl_id)

    if len(t_not_in_r) != 0.:
        logger.warn('following traces have no associated receivers:')
        for nsl_id in t_not_in_r:
            logger.warn(nsl_id)



Sebastian Heimann's avatar
Sebastian Heimann committed
44
45
def scan(
        config,
46
47
        override_tmin=None,
        override_tmax=None,
Sebastian Heimann's avatar
Sebastian Heimann committed
48
49
50
        show_detections=False,
        show_movie=False,
        force=False,
Marius Kriegerowski's avatar
Marius Kriegerowski committed
51
52
        stop_after_first=False,
        nparallel=None):
Sebastian Heimann's avatar
Sebastian Heimann committed
53
54
55
56
57

    if config.detections_path:
        if op.exists(config.detections_path):
            if force:
                os.unlink(config.detections_path)
58
59
60
61
62
63
64
65
                if config.stackmax_path:
                    if op.exists(config.stackmax_path):
                        shutil.rmtree(config.stackmax_path)
                        os.mkdir(config.stackmax_path)

                else:
                    shutil.rmtree('stackmax')
                    os.mkdir('stackmax')
Sebastian Heimann's avatar
Sebastian Heimann committed
66
67
68
69
70
71
            else:
                raise common.LassieError(
                    'detections file already exists: %s' % config.detections_path)

        util.ensuredirs(config.detections_path)

72
73
74
75
76
77
78
79
80
81
82
83
    else:
        if config.stackmax_path:
            if op.exists(config.stackmax_path):
                if force:
                    shutil.rmtree(config.stackmax_path)
                else:
                    raise common.LassieError(
                    'stackmax directory already exists: %s' % config.stackmax_path)

            util.ensuredirs(config.stackmax_path)


Sebastian Heimann's avatar
Sebastian Heimann committed
84
85
86
87
88
    grid = config.get_grid()
    receivers = config.get_receivers()

    norm_map = gridmod.geometrical_normalization(grid, receivers)

89
90
    ifcs = config.image_function_contributions

Sebastian Heimann's avatar
Sebastian Heimann committed
91
92
    shift_tables = []
    tshift_maxs = []
93
    for ifc in ifcs:
Sebastian Heimann's avatar
Sebastian Heimann committed
94
95
96
97
98
99
100
        shift_tables.append(ifc.shifter.get_table(grid, receivers))
        tshift_maxs.append(shift_tables[-1].max())

    tshift_max = max(tshift_maxs) * 1.0

    tinc = tshift_max * 10

101
    tpad = max(ifc.get_tpad() for ifc in ifcs) + tshift_max
Sebastian Heimann's avatar
Sebastian Heimann committed
102

103
    fsmooth_min = min(ifc.get_fsmooth() for ifc in ifcs)
Sebastian Heimann's avatar
Sebastian Heimann committed
104
105
106
107
108
109
110

    blacklist = set(tuple(s.split('.')) for s in config.blacklist)

    station_index = dict(
        (rec.codes, i) for (i, rec) in enumerate(receivers)
        if rec.codes not in blacklist)

111
112
113
114
115
    for data_path in config.data_paths:
        if not op.exists(data_path):
            raise common.LassieError(
                'waveform data path does not exist: %s' % data_path)

Sebastian Heimann's avatar
Sebastian Heimann committed
116
    p = pile.make_pile(config.data_paths, fileformat='detect')
117
118
    if p.is_empty():
        raise common.LassieError('no usable waveforms found')
Sebastian Heimann's avatar
Sebastian Heimann committed
119

120
121
    check_data_consistency(p, receivers)

Sebastian Heimann's avatar
Sebastian Heimann committed
122
123
124
125
126
127
    ngridpoints = grid.size()

    idetection = 0

    station_weights = {}

128
129
    tmin = override_tmin or config.tmin
    tmax = override_tmax or config.tmax
Sebastian Heimann's avatar
Sebastian Heimann committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    for trs in p.chopper(
            tmin=tmin, tmax=tmax, tinc=tinc, tpad=tpad,
            want_incomplete=False,
            trace_selector=lambda tr: tr.nslc_id[:3] in station_index):

        if not trs:
            continue

        logger.info('processing time window %s - %s' % (
            util.time_to_str(trs[0].wmin),
            util.time_to_str(trs[0].wmax)))

        wmin = trs[0].wmin
        wmax = trs[0].wmax

        frames = None
        pdata = []
        trs_debug = []
        shift_maxs = []
149
        for iifc, ifc in enumerate(ifcs):
Sebastian Heimann's avatar
Sebastian Heimann committed
150
151
152
153
154
155
156
157
            dataset = ifc.preprocess(trs, wmin, wmax, tshift_max)
            if not dataset:
                continue

            nstations_selected = len(dataset)

            nsls_selected, trs_selected = zip(*dataset)

158
            #trs_debug.extend(trs + list(trs_selected))
Sebastian Heimann's avatar
Sebastian Heimann committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201

            deltat_cf = trs_selected[0].deltat

            t0 = (wmin / deltat_cf) * deltat_cf

            istations_selected = num.array(
                [station_index[nsl] for nsl in nsls_selected], dtype=num.int)

            arrays = [tr.ydata.astype(num.float) for tr in trs_selected]

            offsets = num.array(
                [int(round((tr.tmin-t0) / deltat_cf)) for tr in trs_selected],
                dtype=num.int32)

            w = num.array(
                [station_weights.get(nsl, 1.0) for nsl in nsls_selected],
                dtype=num.float)


            weights = num.ones((ngridpoints, nstations_selected))
            weights *= w[num.newaxis, :]
            weights *= ifc.weight

            shift_table = shift_tables[iifc]

            shifts = -num.round(
                shift_table[:, istations_selected] /
                deltat_cf).astype(num.int32)

            pdata.append((list(trs_selected), shift_table, ifc))

            iwmin = int(round((wmin-t0) / deltat_cf))
            iwmax = int(round((wmax-t0) / deltat_cf))

            lengthout = iwmax - iwmin + 1

            shift_maxs.append(num.max(-shifts) * deltat_cf)

            frames, ioff = parstack(
                arrays, offsets, shifts, weights, 0,
                offsetout=iwmin,
                lengthout=lengthout,
                result=frames,
Marius Kriegerowski's avatar
Marius Kriegerowski committed
202
                nparallel=nparallel,
Sebastian Heimann's avatar
Sebastian Heimann committed
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
                impl='openmp')

        shift_max = max(shift_maxs)

        if config.sharpness_normalization:
            frame_maxs = frames.max(axis=0)
            frame_means = num.abs(frames).mean(axis=0)
            frames *= (frame_maxs / frame_means)[num.newaxis, :]
            frames *= norm_map[:, num.newaxis]

        frame_maxs = frames.max(axis=0)

        tmin_frames = t0 + ioff * deltat_cf

        tr_stackmax = trace.Trace(
            '', 'SMAX', '', '',
            tmin=tmin_frames,
            deltat=deltat_cf,
            ydata=frame_maxs)

223
        #trs_debug.append(tr_stackmax)
Sebastian Heimann's avatar
Sebastian Heimann committed
224
225
226
227
228

        # trace.snuffle(trs_debug)

        ydata_window = tr_stackmax.chop(wmin, wmax, inplace=False).get_ydata()

229
        logger.info('CF stats: min %g, max %g, median %g' % (
Sebastian Heimann's avatar
Sebastian Heimann committed
230
231
232
233
234
235
236
            num.min(ydata_window),
            num.max(ydata_window),
            num.median(ydata_window)))

        tpeaks, apeaks = tr_stackmax.peaks(
            config.detector_threshold, shift_max + 1.0/fsmooth_min)

237
238
239
240
241
        tr_stackmax_indx = tr_stackmax.copy(data=False)
        imaxs = num.argmax(frames, axis=0)
        tr_stackmax_indx.set_ydata(imaxs.astype(num.int32))
        tr_stackmax_indx.set_location('i')

Sebastian Heimann's avatar
Sebastian Heimann committed
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        for (tpeak, apeak) in zip(tpeaks, apeaks):
            if not (wmin <= tpeak and tpeak < wmax):
                continue

            logger.info('detection: %s %g' % (
                util.time_to_str(tpeak),
                apeak))

            iframe = int(round(((tpeak-t0) - ioff*deltat_cf) / deltat_cf))
            frame = frames[:, iframe]
            imax = num.argmax(frame)

            latpeak, lonpeak, xpeak, ypeak, zpeak = grid.index_to_location(imax)

            idetection += 1

            if config.detections_path:
                f = open(config.detections_path, 'a')
                f.write('%06i %s %g %g %g %g %g %g\n' % (
                    idetection,
                    util.time_to_str(tpeak, format='%Y-%m-%d %H:%M:%S.6FRAC'),
                    apeak,
                    latpeak, lonpeak, xpeak, ypeak, zpeak))

                f.close()

            if show_detections:
269
270
                fmin = min(ifc.fmin for ifc in ifcs)
                fmax = min(ifc.fmax for ifc in ifcs)
Sebastian Heimann's avatar
Sebastian Heimann committed
271
272
273
274
275
276
277
278
279
280
                plot.plot_detection(
                    grid, receivers, frames, tmin_frames,
                    deltat_cf, imax, iframe, fsmooth_min, xpeak, ypeak, zpeak,
                    tr_stackmax, tpeaks, apeaks, config.detector_threshold,
                    pdata, trs, fmin, fmax, idetection,
                    grid_station_shift_max=shift_max,
                    movie=show_movie)

            if stop_after_first:
                return
281

Sebastian Heimann's avatar
Sebastian Heimann committed
282
283
        tr_stackmax.chop(wmin, wmax)

284
285
286
287
        if config.stackmax_path:
            io.save([tr_stackmax, tr_stackmax_indx], os.path.join(config.stackmax_path, 'trace_%(tmin_ms)s.mseed'))
        else:
            io.save([tr_stackmax, tr_stackmax_indx], 'stackmax/trace_%(tmin_ms)s.mseed')
Sebastian Heimann's avatar
Sebastian Heimann committed
288
289
290
291

__all__ = [
    'scan',
]