|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# SPDX-License-Identifier: CECILL-2.1 |
| 3 | +""" |
| 4 | +A trace clipping detector based on kernel density estimation. |
| 5 | +
|
| 6 | +:copyright: |
| 7 | + 2023 Claudio Satriano <[email protected]> |
| 8 | +:license: |
| 9 | + CeCILL Free Software License Agreement v2.1 |
| 10 | + (http://www.cecill.info/licences.en.html) |
| 11 | +""" |
| 12 | +import numpy as np |
| 13 | +from scipy.stats import gaussian_kde |
| 14 | +from scipy.signal import find_peaks |
| 15 | + |
| 16 | + |
| 17 | +def is_clipped(trace, sensitivity, debug=False): |
| 18 | + """ |
| 19 | + Check if a trace is clipped, based on kernel density estimation. |
| 20 | +
|
| 21 | + Kernel density estimation is used to find the peaks of the histogram of |
| 22 | + the trace data points. The peaks are then weighted by their distance from |
| 23 | + the trace average (which should be the most common value). |
| 24 | + The peaks with the highest weight are then checked for prominence, |
| 25 | + which is a measure of how much higher the peak is than the surrounding |
| 26 | + data. The prominence threshold is determined by the sensitivity parameter. |
| 27 | + If more than one peak is found, the trace is considered clipped or |
| 28 | + distorted. |
| 29 | +
|
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + trace : obspy.core.trace.Trace |
| 33 | + Trace to check. |
| 34 | + sensitivity : int |
| 35 | + Sensitivity level, from 1 (least sensitive) to 5 (most sensitive). |
| 36 | + debug : bool |
| 37 | + If True, plot trace, samples histogram and kernel density. |
| 38 | +
|
| 39 | + Returns |
| 40 | + ------- |
| 41 | + bool |
| 42 | + True if trace is clipped, False otherwise. |
| 43 | + """ |
| 44 | + sensitivity = int(sensitivity) |
| 45 | + if sensitivity < 1 or sensitivity > 5: |
| 46 | + raise ValueError('sensitivity must be between 1 and 5') |
| 47 | + trace = trace.copy().detrend('demean') |
| 48 | + npts = len(trace.data) |
| 49 | + # Compute data histogram with a number of bins equal to 0.5% of data points |
| 50 | + nbins = int(npts*0.005) |
| 51 | + counts, bins = np.histogram(trace.data, bins=nbins) |
| 52 | + counts = counts/np.max(counts) |
| 53 | + # Compute gaussian kernel density |
| 54 | + kde = gaussian_kde(trace.data, bw_method=0.2) |
| 55 | + max_data = np.max(np.abs(trace.data))*1.2 |
| 56 | + density_points = np.linspace(-max_data, max_data, 100) |
| 57 | + density = kde.pdf(density_points) |
| 58 | + maxdensity = np.max(density) |
| 59 | + density /= maxdensity |
| 60 | + # Distance weight, parabolic, between 1 and 5 |
| 61 | + dist_weight = np.abs(density_points)**2 |
| 62 | + dist_weight *= 4/dist_weight.max() |
| 63 | + dist_weight += 1 |
| 64 | + density_weight = density*dist_weight |
| 65 | + # find peaks with minimum prominence based on clipping sensitivity |
| 66 | + min_prominence = [0.1, 0.05, 0.03, 0.02, 0.01] |
| 67 | + peaks, _ = find_peaks( |
| 68 | + density_weight, |
| 69 | + prominence=min_prominence[sensitivity-1] |
| 70 | + ) |
| 71 | + if debug: |
| 72 | + import matplotlib.pyplot as plt |
| 73 | + fig, ax = plt.subplots(1, 2, figsize=(15, 5), sharey=True) |
| 74 | + fig.suptitle(trace.id) |
| 75 | + ax[0].plot(trace.times(), trace.data) |
| 76 | + ax[0].set_ylim(-max_data, max_data) |
| 77 | + ax[0].set_xlabel('Time (s)') |
| 78 | + ax[0].set_ylabel('Amplitude') |
| 79 | + ax[1].hist( |
| 80 | + bins[:-1], bins=len(counts), weights=counts, |
| 81 | + orientation='horizontal') |
| 82 | + ax[1].plot(density, density_points, label='kernel density') |
| 83 | + ax[1].plot( |
| 84 | + density_weight, density_points, label='weighted\nkernel density') |
| 85 | + ax[1].scatter( |
| 86 | + density_weight[peaks], density_points[peaks], |
| 87 | + s=100, marker='x', color='red') |
| 88 | + ax[1].set_xlabel('Density') |
| 89 | + ax[1].legend() |
| 90 | + plt.show() |
| 91 | + # If more than one peak, then the signal is probably clipped or distorted |
| 92 | + if len(peaks) > 1: |
| 93 | + return True |
| 94 | + else: |
| 95 | + return False |
| 96 | + |
| 97 | + |
| 98 | +def main(): |
| 99 | + import argparse |
| 100 | + from obspy import read |
| 101 | + parser = argparse.ArgumentParser( |
| 102 | + description='Check if a trace is clipped, ' |
| 103 | + 'based on kernel density estimation of trace samples.') |
| 104 | + parser.add_argument( |
| 105 | + 'infile', type=str, |
| 106 | + help='Input file name in any ObsPy supported format') |
| 107 | + parser.add_argument( |
| 108 | + '-s', '--sensitivity', type=int, default=3, |
| 109 | + help='Sensitivity level, from 1 (least sensitive) ' |
| 110 | + 'to 5 (most sensitive)') |
| 111 | + parser.add_argument( |
| 112 | + '-d', '--debug', action='store_true', |
| 113 | + help='If set, plot trace, samples histogram and kernel density') |
| 114 | + args = parser.parse_args() |
| 115 | + st = read(args.infile) |
| 116 | + for tr in st: |
| 117 | + print(tr.id, is_clipped(tr, args.sensitivity, args.debug)) |
| 118 | + |
| 119 | + |
| 120 | +if __name__ == '__main__': |
| 121 | + import sys |
| 122 | + try: |
| 123 | + main() |
| 124 | + except Exception as msg: |
| 125 | + sys.exit(msg) |
| 126 | + except KeyboardInterrupt: |
| 127 | + sys.exit() |
0 commit comments