-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathspectraplot.ts
446 lines (391 loc) · 12 KB
/
spectraplot.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
* Philip Crotwell
* University of South Carolina, 2019
* https://www.seis.sc.edu
*/
import {FFTResult} from "./fft";
import {COLOR_CSS_ID} from "./seismograph";
import {SeismographConfig} from "./seismographconfig";
import {SeismogramDisplayData} from "./seismogram";
import {addStyleToElement} from './spelement';
import {Complex} from "./oregondsputil";
import {SVG_NS} from "./util";
import {extent as d3extent} from "d3-array";
import {select as d3select} from "d3-selection";
import {
scaleLinear as d3scaleLinear,
ScaleContinuousNumeric as d3ScaleContinuousNumeric,
scaleLog as d3scaleLog,
} from "d3-scale";
import {line as d3line } from "d3-shape";
import {
axisLeft as d3axisLeft ,
axisBottom as d3axisBottom,
} from "d3-axis";
import { G_DATA_SELECTOR, AUTO_COLOR_SELECTOR} from "./cssutil";
import {drawAxisLabels} from "./axisutil";
export const SPECTRA_ELEMENT = 'sp-spectra';
/**
* Similar to FFTResult, but used for plotting non-fft generated data.
* This allows the frequencies to be, for example, evenly distrubuted
* in log instead of linearly for plotting PolesZeros stages.
*/
export class FreqAmp {
freq: Float32Array;
values: Array<InstanceType<typeof Complex>>;
/** optional units of the original data for display purposes. */
inputUnits: string;
seismogramDisplayData: null | SeismogramDisplayData;
constructor(freq: Float32Array, values: Array<InstanceType<typeof Complex>>) {
this.freq = freq;
this.values = values;
this.inputUnits = ""; // leave blank unless set manually
this.seismogramDisplayData = null;
if (freq.length !== values.length) {
throw new Error(`Frequencies and complex values must have same length: ${freq.length} ${values.length}`);
}
}
frequencies(): Float32Array {
return this.freq;
}
amplitudes(): Float32Array {
const out = new Float32Array(this.values.length);
this.values.forEach((c,i) => out[i] = c.abs());
return out;
}
phases(): Float32Array {
const out = new Float32Array(this.values.length);
this.values.forEach((c,i) => out[i] = c.angle());
return out;
}
get numFrequencies(): number {
return this.freq.length;
}
get minFrequency(): number {
return this.fundamentalFrequency;
}
get maxFrequency(): number {
return this.freq[this.freq.length - 1];
}
// for compatibility with FFTResult
get fundamentalFrequency(): number {
return this.freq[0];
}
}
/**
* Defualt CSS for styling fft plots.
*/
export const spectra_plot_css = `
:host {
display: block
}
div.wrapper {
height: 100%;
min-height: 100px;
}
path.fftpath {
stroke: skyblue;
fill: none;
stroke-width: 1px;
}
svg.spectra_plot {
height: 100%;
width: 100%;
min-height: 100px;
display: block;
}
svg.spectra_plot text.title {
font-size: larger;
font-weight: bold;
fill: black;
color: black;
}
svg.spectra_plot text.sublabel {
font-size: smaller;
}
/* links in svg */
svg.spectra_plot text a {
fill: #0000EE;
text-decoration: underline;
}
`;
export const AMPLITUDE = "amplitude";
export const PHASE = "phase";
export const LOGFREQ = "logfreq";
export const KIND = "kind";
/**
* A amplitude or phase plot of fft data. The 'kind' attribute controls whether
* 'amplitude' or 'phase' is plotted and the 'logfreq' attribute controls
* whether frequency, x axis, is linear or log.
* Setting the seismogramConfig changes
* the plot configuration, althought not all values are used.
* The data as an array of FFTResult or FreqAmp
* sets the data to be plotted.
* Amplitude is plotted with y axis log, phase is y axis linear.
*
*/
export class SpectraPlot extends HTMLElement {
_seismographConfig: SeismographConfig;
_fftResults: Array<FFTResult | FreqAmp>;
constructor(fftResults?: Array<FFTResult | FreqAmp>, seismographConfig?: SeismographConfig) {
super();
if (seismographConfig) {
this._seismographConfig = seismographConfig;
} else {
this._seismographConfig = new SeismographConfig();
}
if (fftResults) {
this._fftResults = fftResults;
} else {
this._fftResults = [];
}
const wrapper = document.createElement('div');
wrapper.setAttribute("class", "wrapper");
addStyleToElement(this, spectra_plot_css);
const lineColorsCSS = this.seismographConfig.createCSSForLineColors();
addStyleToElement(this, lineColorsCSS, COLOR_CSS_ID);
this.shadowRoot?.appendChild(wrapper);
}
get fftResults() {
return this._fftResults;
}
set fftResults(fftResults: Array<FFTResult | FreqAmp>) {
this._fftResults = fftResults;
this.draw();
}
get seismographConfig() {
return this._seismographConfig;
}
set seismographConfig(seismographConfig: SeismographConfig) {
this._seismographConfig = seismographConfig;
this.draw();
}
get kind(): string {
let k = this.hasAttribute(KIND) ? this.getAttribute(KIND) : AMPLITUDE;
// typescript null
if (!k) { k = AMPLITUDE;}
return k;
}
set kind(val: string) {
this.setAttribute(KIND, val);
}
get logfreq(): boolean {
if ( ! this.hasAttribute(LOGFREQ) ) { return true;}
const b = this.getAttribute(LOGFREQ);
if (b && b.toLowerCase()==="true") {return true;}
return false;
}
set logfreq(val: boolean) {
this.setAttribute(LOGFREQ, `${val}`);
}
connectedCallback() {
this.draw();
}
static get observedAttributes() { return [LOGFREQ, KIND]; }
attributeChangedCallback(name: string, oldValue: any, newValue: any) {
this.draw();
}
draw() {
if ( ! this.isConnected) { return; }
const ampPhaseList = [];
let maxFFTAmpLen = 0;
const extentFFTData: Array<number> = [];
const freqMinMax: Array<number> = [];
if (this.kind === PHASE) {
extentFFTData.push(-Math.PI);
extentFFTData.push(Math.PI);
if (this.seismographConfig.ySublabelIsUnits) {
this.seismographConfig.ySublabelIsUnits = false;
this.seismographConfig.ySublabel = "Radian";
}
} else {
if (this.seismographConfig.ySublabelIsUnits) {
this.seismographConfig.ySublabelIsUnits = false;
this.seismographConfig.ySublabel = "";
}
}
for (const fftA of this.fftResults) {
if (this.logfreq === true) {
freqMinMax.push(fftA.fundamentalFrequency); // min freq
} else {
freqMinMax.push(0);
}
freqMinMax.push(fftA.maxFrequency); // max freq
let ap: FFTResult | FreqAmp;
if (fftA instanceof FFTResult || fftA instanceof FreqAmp) {
ap = fftA;
} else {
throw new Error("fftResults must be array of FFTResult");
}
ampPhaseList.push(ap);
if (maxFFTAmpLen < ap.numFrequencies) {
maxFFTAmpLen = ap.numFrequencies;
}
let ampSlice: Float32Array;
if (this.kind === AMPLITUDE) {
ampSlice = ap.amplitudes();
} else if (this.kind === PHASE) {
ampSlice = ap.phases();
} else {
throw new Error(`Unknown plot kind=${this.kind}`);
}
if (this.kind === AMPLITUDE) {
// don't plot zero freq amp
ampSlice = ampSlice.slice(1);
}
const currExtent = d3extent(ampSlice);
if (this.kind === AMPLITUDE && currExtent[0] === 0) {
// replace zero with smallest non-zero / 10 for log amp plot
currExtent[0] =
0.1 *
ampSlice.reduce(function(acc: number, curr: number): number {
if (curr > 0 && curr < acc) {
return curr;
} else {
return acc;
}
}, 1e-9);
}
if (currExtent[0]) { extentFFTData.push(currExtent[0]); }
if (currExtent[1]) { extentFFTData.push(currExtent[1]); }
}
if (freqMinMax.length < 2) {
freqMinMax.push(0.1);
freqMinMax.push(10.0);
}
if (extentFFTData.length < 2 ) {
extentFFTData.push(0.1);
extentFFTData.push(1);
}
const wrapper = (this.shadowRoot?.querySelector('div') as HTMLDivElement);
while (wrapper.lastChild) {
wrapper.removeChild(wrapper.lastChild);
}
const svg_element = document.createElementNS(SVG_NS,"svg");
wrapper.appendChild(svg_element);
const svg = d3select(svg_element);
svg.classed("spectra_plot", true).classed(AUTO_COLOR_SELECTOR, true);
const rect = svg_element.getBoundingClientRect();
const width =
+rect.width -
this.seismographConfig.margin.left -
this.seismographConfig.margin.right;
const height =
+rect.height -
this.seismographConfig.margin.top -
this.seismographConfig.margin.bottom;
const g = svg
.append("g")
.attr(
"transform",
"translate(" +
this.seismographConfig.margin.left +
"," +
this.seismographConfig.margin.top +
")",
);
let xScale: d3ScaleContinuousNumeric<number, number, never>;
if (this.logfreq) {
xScale = d3scaleLog().rangeRound([0, width]);
} else {
xScale = d3scaleLinear().rangeRound([0, width]);
}
const freqMin = freqMinMax.reduce((acc, cur) => Math.min(acc, cur));
const freqMax = freqMinMax.reduce((acc, cur) => Math.max(acc, cur));
xScale.domain([freqMin, freqMax]);
let fftMin = extentFFTData.reduce((acc, cur) => Math.min(acc, cur), Number.MAX_VALUE);
let fftMax = extentFFTData.reduce((acc, cur) => Math.max(acc, cur), -1.0);
if ((fftMax - fftMin) / fftMax < .1) {
// min and max are close, expand range a bit
fftMin = fftMin*0.1;
fftMax = fftMax*2;
}
let yScale: d3ScaleContinuousNumeric<number, number, never>;
if (this.kind === AMPLITUDE) {
yScale = d3scaleLog().rangeRound([height, 0]);
yScale.domain([fftMin, fftMax]);
if (yScale.domain()[0] === yScale.domain()[1]) {
yScale.domain([
yScale.domain()[0] / 2,
yScale.domain()[1] * 2,
]);
}
} else {
yScale = d3scaleLinear().rangeRound([height, 0]);
yScale.domain([fftMin, fftMax]);
if (yScale.domain()[0] === yScale.domain()[1]) {
yScale.domain([
yScale.domain()[0] - 1,
yScale.domain()[1] + 1,
]);
}
}
const xAxis = d3axisBottom(xScale);
g.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
const yAxis = d3axisLeft(yScale);
g.append("g").call(yAxis);
this.seismographConfig.yLabel = "Amplitude";
if (this.kind === PHASE) {
this.seismographConfig.yLabel = "Phase";
}
this.seismographConfig.xLabel = "Frequency";
this.seismographConfig.xSublabel = "Hz";
if (this.seismographConfig.ySublabelIsUnits) {
if (this.kind === PHASE) {
this.seismographConfig.ySublabel = "radian";
} else {
this.seismographConfig.ySublabel = "";
for (const ap of ampPhaseList) {
this.seismographConfig.ySublabel += ap.inputUnits;
}
}
}
const pathg = g.append("g").classed(G_DATA_SELECTOR, true);
for (const ap of ampPhaseList) {
let ampSlice;
if (this.kind === AMPLITUDE) {
ampSlice = ap.amplitudes();
} else if (this.kind === PHASE) {
ampSlice = ap.phases();
} else {
throw new Error(`Unknown plot kind=${this.kind}`);
}
let freqSlice = ap.frequencies();
if (this.logfreq) {
freqSlice = freqSlice.slice(1);
ampSlice = ampSlice.slice(1);
}
const line = d3line<number>();
line.x(function (d: number, i: number) {
return xScale(freqSlice[i]);
});
line.y(function (d: number) {
if (d !== 0.0 && !isNaN(d)) {
return yScale(d);
} else {
return yScale.range()[0];
}
});
pathg
.append("g")
.append("path")
.classed("fftpath", true)
.datum(ampSlice)
.attr("d", line);
}
const handlebarInput = {
seisDataList: this.fftResults.map(f => f.seismogramDisplayData),
seisConfig: this.seismographConfig,
};
drawAxisLabels(
svg_element,
this.seismographConfig,
height,
width,
handlebarInput,
);
}
}
customElements.define(SPECTRA_ELEMENT, SpectraPlot);