-
Notifications
You must be signed in to change notification settings - Fork 7
/
filter.ts
350 lines (320 loc) · 9.62 KB
/
filter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
* Philip Crotwell
* University of South Carolina, 2019
* http://www.seis.sc.edu
*/
import {Duration} from "luxon";
import {Seismogram} from "./seismogram";
import {InstrumentSensitivity} from "./stationxml";
import {
Butterworth,
ChebyshevI,
ChebyshevII,
PassbandType,
IIRFilter,
CenteredHilbertTransform,
LOWPASS, BANDPASS, HIGHPASS
} from "./oregondsputil";
import {isDef} from "./util";
/**
* Constant for bandpass OregonDSP filter creation.
*/
export const BAND_PASS = 'BANDPASS';
/**
* Constant for lowpass OregonDSP filter creation.
*/
export const LOW_PASS = "LOWPASS";
/**
* Constant for highpass OregonDSP filter creation.
*/
export const HIGH_PASS = "HIGHPASS";
export function amplitude(real: number, imag: number): number {
return Math.hypot(real, imag);
}
/**
* Remove the mean from a seismogram. Subtract the mean from each data point.
*
* @param seis input seismogram
* @returns seismogram with mean of zero
*/
export function rMean(seis: Seismogram): Seismogram {
if (seis instanceof Seismogram) {
const meanVal = seis.mean();
const rmeanSeismogram = new Seismogram(
seis.segments.map(s => {
const demeanY = s.y.map(function (d) {
return d - meanVal;
});
const out = s.cloneWithNewData(demeanY);
return out;
}),
);
return rmeanSeismogram;
} else {
throw new Error("rMean arg not a Seismogram");
}
}
/**
* Apply the frequency independent overall gain to a seismogram. This does not
* do a full transfer using poles and zero, this only applies the scalar conversion
* factor to convert counts back to original real world units and update the units.
*
* @param seis the seismogram to correct
* @param instrumentSensitivity overall gain object, usually pulled from stationxml
* @returns new seismogram with original units, like m/s and gain applied.
*/
export function gainCorrect(
seis: Seismogram,
instrumentSensitivity: InstrumentSensitivity,
): Seismogram {
if (seis instanceof Seismogram) {
const gain = instrumentSensitivity.sensitivity;
const gainSeismogram = new Seismogram(
seis.segments.map(s => {
let gainY;
if (s.y instanceof Int32Array || s.y instanceof Float32Array) {
gainY = Float32Array.from(s.y);
} else {
gainY = Float64Array.from(s.y);
}
gainY = gainY.map(function (d) {
return d / gain;
});
const outS = s.cloneWithNewData(gainY);
outS.yUnit = instrumentSensitivity.inputUnits;
return outS;
}),
);
return gainSeismogram;
} else {
throw new Error(`Expected Seismogram but was ${typeof seis}`);
}
}
export type MinMaxMean = {
min: number;
max: number;
mean: number;
};
export function getPassband(type: string): (typeof LOWPASS | typeof BANDPASS | typeof HIGHPASS) {
if (type === LOW_PASS) {
return LOWPASS;
} else if (type === BAND_PASS) {
return PassbandType.BANDPASS;
} else if (type === HIGH_PASS) {
return PassbandType.HIGHPASS;
} else {
throw new Error(`unknown pass band: ${type}`);
}
}
/**
* Creates a Butterworth IIR filter using the OregonDSP library.
*
* @param numPoles number of poles
* @param passband type, use constants of BAND_PASS, LOW_PASS, HIGH_PASS
* @param lowFreqCorner low corner frequency
* @param highFreqCorner high corner frequency
* @param delta delta, period, of timeseries
* @returns Butterworth IIR filter
*/
export function createButterworth(
numPoles: number,
passband: string,
lowFreqCorner: number,
highFreqCorner: number,
delta: number,
): InstanceType<typeof Butterworth> {
const passbandtype = getPassband(passband);
return new Butterworth(
numPoles,
passbandtype,
lowFreqCorner,
highFreqCorner,
delta,
);
}
/**
* Creates a Chebyshev I IIR filter using the OregonDSP library.
*
* @param numPoles number of poles
* @param epsilon Chebyshev epsilon value
* @param passband type, use constants of BAND_PASS, LOW_PASS, HIGH_PASS
* @param lowFreqCorner low corner frequency
* @param highFreqCorner high corner frequency
* @param delta delta, period, of timeseries
* @returns Chebyshev I IIR filter
*/
export function createChebyshevI(
numPoles: number,
epsilon: number,
passband: string,
lowFreqCorner: number,
highFreqCorner: number,
delta: number,
): InstanceType<typeof ChebyshevI> {
const passbandtype = getPassband(passband);
return new ChebyshevI(
numPoles,
epsilon,
passbandtype,
lowFreqCorner,
highFreqCorner,
delta,
);
}
/**
* Creates a Chebyshev II IIR filter using the OregonDSP library.
*
* @param numPoles number of poles
* @param epsilon Chebyshev epsilon value
* @param passband type, use constants of BAND_PASS, LOW_PASS, HIGH_PASS
* @param lowFreqCorner low corner frequency
* @param highFreqCorner high corner frequency
* @param delta delta, period, of timeseries
* @returns Chebyshev II IIR filter
*/
export function createChebyshevII(
numPoles: number,
epsilon: number,
passband: string,
lowFreqCorner: number,
highFreqCorner: number,
delta: number,
): InstanceType<typeof ChebyshevII> {
const passbandtype = getPassband(passband);
return new ChebyshevII(
numPoles,
epsilon,
passbandtype,
lowFreqCorner,
highFreqCorner,
delta,
);
}
/**
* Applies the filter to the given seismogram.
*
* @param iirFilter filter to apply
* @param seis seismogram to apply filter to
* @returns filtered seismogram
*/
export function applyFilter(
iirFilter: InstanceType<typeof IIRFilter>,
seis: Seismogram,
): Seismogram {
// check delta and samplePeriod with 0.1% of each other
if (Math.abs(iirFilter.getDelta() - seis.samplePeriod)/seis.samplePeriod > 0.001) {
throw new Error(`Filter, delta=${iirFilter.getDelta()}, has different delta from seis, ${1/seis.sampleRate}`);
}
const filteredSegments = [];
for (let i = 0; i < seis.segments.length; i++) {
const outData = Float32Array.from(seis.segments[i].y);
iirFilter.filterInPlace(outData);
filteredSegments.push(seis.segments[i].cloneWithNewData(outData));
}
return new Seismogram(filteredSegments);
}
/**
* Calculates the envelope, y_i = sqrt( y_i * y_i + h_i * h_i)
* where h is the hilber transform of y. The default configuration
* for the hilbet transform is n=100, lowEdge=.05 and highEdge = 0.95
*
* @param seis seismogram to apply envelope to
* @returns seismogram cloned but with data as the envelope
*/
export function envelope(seis: Seismogram): Seismogram {
if (seis.isContiguous()) {
const seisY = seis.y;
const s = hilbert(seis);
const hilbertY = s.y;
let outY;
if (seis.y instanceof Int32Array || seis.y instanceof Float32Array) {
outY = new Float32Array(seisY.length);
} else {
outY = new Float64Array(seisY.length);
}
for (let n = 0; n < seisY.length; n++) {
outY[n] = Math.sqrt(hilbertY[n] * hilbertY[n] + seisY[n] * seisY[n]);
}
return seis.cloneWithNewData(outY);
} else {
throw new Error("Cannot take envelope of non-contiguous seismogram");
}
}
/**
* Calculates the hilbert transform using the OregonDSP library
* with default number of points, n=10 (to yield a 21 pt FIR transform)
* and default low and high edge of 0.05 and 0.95. Low and high edge are
* given normalized 0 to 1.
*
* Note this uses Float32Array, other array types will be converted,
* possibly losing precision.
*
* @param seis seismogram to calculate from
* @param n optional number of points in transform, default is 10
* @param lowEdge low edge of filter, normailized to 0-1, default is 0.05
* @param highEdge high edge of filter, normailized to 0-1, default is 0.95
* @returns hilbert transformed data
*/
export function hilbert(
seis: Seismogram,
n?: number,
lowEdge?: number,
highEdge?: number,
): Seismogram {
if (seis.isContiguous()) {
let seisY: Float32Array;
if (seis.y instanceof Float32Array){
seisY = seis.y;
} else {
seisY = Float32Array.from(seis.y);
}
if (!isDef(n)) {
n = 10;
}
if (!isDef(lowEdge)) {
lowEdge = 0.05;
}
if (!isDef(highEdge)) {
highEdge = 0.95;
}
const hilbert = new CenteredHilbertTransform(n, lowEdge, highEdge);
const coeff = hilbert.getCoefficients();
for (const c of coeff) {
if (Number.isNaN(c)) {
throw new Error(`Hilbert FIR coeff includes NaN: ${coeff.join()}`);
}
}
const hilbertY = hilbert.filter(seisY);
const s = seis.cloneWithNewData(hilbertY);
return s;
} else {
throw new Error("Cannot take hilbert of non-contiguous seismogram");
}
}
/**
* Differentiate a seismogram.
*
* @param seis input seismogram
* @returns differentiated seismogram
*/
export function differentiate(seis: Seismogram): Seismogram {
if (seis instanceof Seismogram) {
const diffSeismogram = new Seismogram(
seis.segments.map(s => {
const origY = s.y;
const sampRate = 1.0 * s.sampleRate; // same as 1/delta
const diffY = new Float32Array(origY.length - 1);
for (let i = 0; i < diffY.length; i++) {
diffY[i] = (origY[i + 1] - origY[i]) * sampRate;
}
const out = s.cloneWithNewData(diffY);
out.startTime = out.startTime.plus(Duration.fromMillis(1000 / out.sampleRate / 2));// second
out.yUnit = out.yUnit + "/s";
return out;
}),
);
return diffSeismogram;
} else {
throw new Error("diff arg not a Seismogram");
}
}