-
Notifications
You must be signed in to change notification settings - Fork 7
/
mseed3.ts
1363 lines (1264 loc) · 35 KB
/
mseed3.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Philip Crotwell
* University of South Carolina, 2019
* https://www.seis.sc.edu
*/
import {FDSNSourceId} from "./fdsnsourceid";
import {isDef, UTC_OPTIONS} from "./util";
import {EncodedDataSegment, FLOAT, INTEGER, DOUBLE, STEIM1, STEIM2} from "./seedcodec";
import {SeismogramSegment} from "./seismogramsegment";
import {Seismogram} from "./seismogram";
import {
DataRecord,
R_TYPECODE,
D_TYPECODE,
Q_TYPECODE,
M_TYPECODE,
} from "./miniseed";
import {DateTime, Duration} from "luxon";
export type json_object = Record<string, unknown>;
export const MINISEED_THREE_MIME = "application/vnd.fdsn.mseed3";
/** const for unknown data version, 0 */
export const UNKNOWN_DATA_VERSION = 0;
/** const for offset to crc in record, 28 */
export const CRC_OFFSET = 28;
/** const for size of fixed header part of record, 40 */
export const FIXED_HEADER_SIZE = 40;
/** const for fdsn prefix for extra headers, FDSN */
export const FDSN_PREFIX = "FDSN";
/** const for little endian, true */
export const LITTLE_ENDIAN = true;
/** const for big endian, false */
export const BIG_ENDIAN = false;
export function toMSeed3(seis: Seismogram, extraHeaders?: Record<string, unknown>): Array<MSeed3Record> {
const out = new Array<MSeed3Record>(0);
if (!isDef(extraHeaders)) {
extraHeaders = {};
}
for (const seg of seis.segments) {
const header = new MSeed3Header();
let rawData;
let encoding = 0;
if (seg.isEncoded()) {
const encoded = seg.getEncoded();
if (encoded.length === 1) {
rawData = encoded[0].dataView;
encoding = encoded[0].compressionType;
} else {
const encodeTypeSet = new Set<number>();
encoded.forEach((cur) => {
encodeTypeSet.add(cur.compressionType);
});
const encodeTypes = Array.from(encodeTypeSet.values());
if (encodeTypes.length > 1) {
throw new Error(`more than one encoding type in seis segment: ${encodeTypes.length}`);
} else if (encodeTypes.length === 0) {
throw new Error(`zero encoding type in seis segment`);
} else if ( !encodeTypes[0]) {
throw new Error(`only encoding type is undef`);
}
encoding = encodeTypes[0];
if (! encoding) {
throw new Error(`encoding is undefined`);
}
if (INTEGER || FLOAT || DOUBLE) {
// safe to concat
const totSize = encoded.reduce((acc, cur) => acc+cur.dataView.byteLength, 0);
const combined = new Uint8Array(totSize);
encoded.reduce((offset, cur) => {
combined.set(new Uint8Array(cur.dataView.buffer, cur.dataView.byteOffset, cur.dataView.byteLength), offset);
return offset+cur.dataView.byteLength;
}, 0);
rawData = new DataView(combined.buffer);
if (encoding === STEIM1 || encoding === STEIM2) {
// careful as each encodeddata has first-last sample
// copy last sample from last block to first block to check value to start
rawData.setUint32(8, encoded[encoded.length-1].dataView.getUint32(8));
}
} else {
throw new Error(`Encoding type not steim 1 or 2 or primitive in seis segment: ${encoding}`);
}
}
} else {
rawData = new DataView(seg.y.buffer);
if (seg.y instanceof Float32Array) {
encoding = FLOAT;
} else if (seg.y instanceof Int32Array) {
encoding = INTEGER;
} else if (seg.y instanceof Float64Array) {
encoding = DOUBLE;
} else {
throw new Error("unable to save data of encoding: ");
}
}
header.setStart(seg.startTime);
header.encoding = encoding;
if (seg.sampleRate > 0.001) {
header.sampleRateOrPeriod = seg.sampleRate;
} else {
header.sampleRateOrPeriod = -1*seg.samplePeriod;
}
header.numSamples = seg.numPoints;
header.publicationVersion = UNKNOWN_DATA_VERSION;
const sid = seg.sourceId?seg.sourceId:FDSNSourceId.createUnknown(seg.sampleRate);
header.identifier = sid.toString();
header.identifierLength = header.identifier.length;
header.extraHeaders = extraHeaders;
header.dataLength = rawData.byteLength;
const record = new MSeed3Record(header, extraHeaders, rawData);
record.calcSize();
out.push(record);
}
return out;
}
/**
* parse arrayBuffer into an array of MSeed3Records.
*
* @param arrayBuffer bytes to extract miniseed3 records from
* @returns array of all miniseed3 records contained in the buffer
*/
export function parseMSeed3Records(
arrayBuffer: ArrayBuffer,
): Array<MSeed3Record> {
const dataRecords = [];
let offset = 0;
while (offset < arrayBuffer.byteLength) {
const dataView = new DataView(arrayBuffer, offset);
if (!(dataView.getUint8(0) === 77 && dataView.getUint8(1) === 83)) {
throw new Error(
`First byte must be M=77 S=83 at offset=${offset}, but was ${dataView.getUint8(
0,
)} ${dataView.getUint8(1)}`,
);
}
const dr = MSeed3Record.parseSingleDataRecord(dataView);
dataRecords.push(dr);
offset += dr.getSize();
}
return dataRecords;
}
/**
* Represents a MSEED3 Data Record, with header, extras and data.
*
* @param header miniseed3 fixed record header
* @param extraHeaders json compatible object with extra headers
* @param rawData waveform data, in correct compression for value in header
*/
export class MSeed3Record {
header: MSeed3Header;
extraHeaders: Record<string, unknown>;
rawData: DataView;
constructor(header: MSeed3Header, extraHeaders: Record<string, unknown>, rawData: DataView) {
this.header = header;
this.rawData = rawData;
this.extraHeaders = extraHeaders;
}
/**
* Parses an miniseed3 data record from a DataView.
*
* @param dataView bytes to parse
* @returns parsed record
*/
static parseSingleDataRecord(dataView: DataView): MSeed3Record {
const header = MSeed3Header.createFromDataView(dataView);
const ehoffset = header.getSize();
const dataoffset = header.getSize() + header.extraHeadersLength;
const extraDataView = new DataView(
dataView.buffer,
dataView.byteOffset + ehoffset,
header.extraHeadersLength,
);
const extraHeaders = parseExtraHeaders(extraDataView);
const sliceStart = dataView.byteOffset + dataoffset;
const rawData = new DataView(
dataView.buffer.slice(sliceStart, sliceStart + header.dataLength),
);
const xr = new MSeed3Record(header, extraHeaders, rawData);
return xr;
}
/**
* Calculates the byte size of the miniseed3 record to hold this data.
* This should be called if the size is needed after modification
* of the extraHeaders.
*
* @returns size in bytes
*/
calcSize(): number {
const json = JSON.stringify(this.extraHeaders);
if (json.length > 2) {
this.header.extraHeadersLength = json.length;
} else {
this.header.extraHeadersLength = 0;
}
return this.getSize();
}
/**
* Gets the byte size of the miniseed3 record to hold this data.
* Note that unless calcSize() has been called, this may not
* take into account modifications to the extra headers.
*
* @returns size in bytes
*/
getSize(): number {
return (
this.header.getSize() +
this.header.extraHeadersLength +
this.header.dataLength
);
}
/**
* Decompresses the data , if the compression
* type is known
*
* @returns decompressed data as a typed array, usually Int32Array or Float32Array
*/
decompress(): Int32Array | Float32Array | Float64Array {
return this.asEncodedDataSegment().decode();
}
/**
* Wraps data in an EncodedDataSegment for future decompression.
*
* @returns waveform data
*/
asEncodedDataSegment(): EncodedDataSegment {
let swapBytes = LITTLE_ENDIAN;
if (
this.header.encoding === 10 ||
this.header.encoding === 11 ||
this.header.encoding === 19
) {
// steim1, 2 and 3 are big endian
swapBytes = BIG_ENDIAN;
}
return new EncodedDataSegment(
this.header.encoding,
this.rawData,
this.header.numSamples,
swapBytes,
);
}
/**
* Just the header.identifier, included as codes() for compatiblility
* with parsed miniseed2 data records.
*
* @returns string identifier
*/
codes(): string {
return this.header.identifier;
}
/**
* Saves miniseed3 record into a DataView, recalculating crc.
*
* @param dataView DataView to save into, must be large enough to hold the record.
* @returns the number of bytes written to the DataView, can be used as offset
* for writting the next record.
*/
save(dataView: DataView): number {
const json = JSON.stringify(this.extraHeaders);
if (json.length > 2) {
this.header.extraHeadersLength = json.length;
} else {
this.header.extraHeadersLength = 0;
}
// don't write crc as we need to recalculate
let offset = this.header.save(dataView, 0, true);
if (json.length > 2) {
for (let i = 0; i < json.length; i++) {
// not ok for unicode?
dataView.setInt8(offset, json.charCodeAt(i));
offset++;
}
}
if (this.rawData !== null) {
for (let i = 0; i < this.rawData.byteLength; i++) {
dataView.setUint8(offset + i, this.rawData.getUint8(i));
}
offset += this.rawData.byteLength;
} else {
throw new Error("rawData is null");
}
const dvcrc = dataView.getUint32(CRC_OFFSET, true);
if (dvcrc !== 0) {
throw new Error(`CRC is not zero before calculate! ${dvcrc}`);
}
const crc = calculateCRC32C(dataView.buffer);
dataView.setUint32(CRC_OFFSET, crc, true);
return offset;
}
/**
* Calculates crc by saving to a DataView, which sets the crc header to zero
* and then calculates it based on the rest of the record.
*
* @returns crc pulled from saved miniseed3 record
*/
calcCrc(): number {
const size = this.calcSize();
const buff = new ArrayBuffer(size);
const dataView = new DataView(buff);
const offset = this.save(dataView);
if (offset !== size) {
throw new Error(`expect to write ${size} bytes but only ${offset}`);
}
const crc = dataView.getUint32(CRC_OFFSET, true);
return crc;
}
toString(): string {
const ehLines = JSON.stringify(this.extraHeaders,null,2).split('\n');
const indentLines = ehLines.join('\n ');
return `${this.header.toString()}\n extra headers: ${indentLines}`;
}
}
/**
* Fixed header of an MSeed3 data record.
*/
export class MSeed3Header {
recordIndicator: string;
formatVersion: number;
flags: number;
nanosecond: number;
year: number;
dayOfYear: number;
hour: number;
minute: number;
second: number;
encoding: number;
sampleRateOrPeriod: number;
numSamples: number;
crc: number;
publicationVersion: number;
identifierLength: number;
extraHeadersLength: number;
identifier: string;
extraHeaders: json_object;
dataLength: number;
constructor() {
// empty construction
this.recordIndicator = "MS";
this.formatVersion = 3;
this.flags = 0;
this.nanosecond = 0;
this.year = 1970;
this.dayOfYear = 1;
this.hour = 0;
this.minute = 0;
this.second = 0;
this.encoding = 3; // 32 bit ints
this.sampleRateOrPeriod = 1;
this.numSamples = 0;
this.crc = 0;
this.publicationVersion = UNKNOWN_DATA_VERSION;
this.identifierLength = 0;
this.extraHeadersLength = 2;
this.identifier = "";
this.extraHeaders = {};
this.dataLength = 0;
}
/**
* Parses an miniseed3 fixed header from a DataView.
*
* @param dataView bytes to parse
* @returns parsed header object
*/
static createFromDataView(dataView: DataView): MSeed3Header {
const header = new MSeed3Header();
header.recordIndicator = makeString(dataView, 0, 2);
if (header.recordIndicator !== "MS") {
throw new Error(
"First 2 bytes of record should be MS but found " +
header.recordIndicator,
);
}
header.formatVersion = dataView.getUint8(2);
if (header.formatVersion !== 3) {
throw new Error("Format Version should be 3, " + header.formatVersion);
}
header.flags = dataView.getUint8(3);
const headerLittleEndian = true;
header.nanosecond = dataView.getInt32(4, headerLittleEndian);
header.year = dataView.getInt16(8, headerLittleEndian);
if (checkByteSwap(header.year)) {
throw new Error("Looks like wrong byte order, year=" + header.year);
}
header.dayOfYear = dataView.getInt16(10, headerLittleEndian);
header.hour = dataView.getUint8(12);
header.minute = dataView.getUint8(13);
header.second = dataView.getUint8(14);
header.encoding = dataView.getUint8(15);
header.sampleRateOrPeriod = dataView.getFloat64(16, headerLittleEndian);
header.numSamples = dataView.getUint32(24, headerLittleEndian);
header.crc = dataView.getUint32(28, headerLittleEndian);
header.publicationVersion = dataView.getUint8(32);
header.identifierLength = dataView.getUint8(33);
header.extraHeadersLength = dataView.getUint16(34, headerLittleEndian);
header.dataLength = dataView.getUint32(36, headerLittleEndian);
header.identifier = makeString(dataView, 40, header.identifierLength);
return header;
}
get start() {
return this.startAsDateTime();
}
get end() {
return this.timeOfSample(this.numSamples - 1);
}
get sampleRate() {
if (this.sampleRateOrPeriod < 0) {
return -1 / this.sampleRateOrPeriod;
} else {
return this.sampleRateOrPeriod;
}
}
get samplePeriod() {
if (this.sampleRateOrPeriod <= 0) {
return -1 * this.sampleRateOrPeriod;
} else {
return 1 / this.sampleRateOrPeriod;
}
}
/**
* Calculates size of the fixed header including the variable
* length identifier, but without the extra headers.
*
* @returns size in bytes of fixed header
*/
getSize(): number {
return FIXED_HEADER_SIZE + this.identifier.length;
}
/**
* Text representation of the miniseed3 header. This is modeled after
* the output of mseed3-text from the mseed3-utils package from IRIS.
*
* @returns textual repersentation
*/
toString(): string {
/*
FDSN:CO_HODGE_00_L_H_Z, version 4, 477 bytes (format: 3)
start time: 2019-07-06T03:19:53.000000Z (187)
number of samples: 255
sample rate (Hz): 1
flags: [00000000] 8 bits
CRC: 0x8926FFDF
extra header length: 31 bytes
data payload length: 384 bytes
payload encoding: STEIM-2 integer compression (val: 11)
extra headers:
"FDSN": {
"Time": {
"Quality": 0
}
}
*/
let encode_name = "unknown";
if (this.encoding === 0) {
encode_name = "Text";
} else if (this.encoding === 11) {
encode_name = "STEIM-2 integer compression";
} else if (this.encoding === 10) {
encode_name = "STEIM-1 integer compression";
}
let bitFlagStr = '';
if (this.flags & 0x01) {
bitFlagStr = `${bitFlagStr}
[Bit 0] Calibration signals present`;
}
if (this.flags & 0x02) {
bitFlagStr = `${bitFlagStr}
[Bit 1] Time tag is questionable`;
}
if (this.flags & 0x04) {
bitFlagStr = `${bitFlagStr}
[Bit 2] Clock locked`;
}
if (this.flags & 0x08) {
bitFlagStr = `${bitFlagStr}
[Bit 3] Undefined bit set`;
}
if (this.flags & 0x10) {
bitFlagStr = `${bitFlagStr}
[Bit 4] Undefined bit set`;
}
if (this.flags & 0x20) {
bitFlagStr = `${bitFlagStr}
[Bit 5] Undefined bit set`;
}
if (this.flags & 0x40) {
bitFlagStr = `${bitFlagStr}
[Bit 6] Undefined bit set`;
}
if (this.flags & 0x80) {
bitFlagStr = `${bitFlagStr}
[Bit 7] Undefined bit set`;
}
return (
`${this.identifier}, version ${this.publicationVersion}, ${
this.getSize() + this.dataLength + this.extraHeadersLength
} bytes (format: ${this.formatVersion})\n` +
` start time: ${this.getStartFieldsAsISO()} (${padZeros(this.dayOfYear, 3)})\n` +
` number of samples: ${this.numSamples}\n` +
` sample rate (Hz): ${this.sampleRate}\n` +
` flags: [${(this.flags >>> 0).toString(2)
.padStart(8, "0")}] 8 bits${bitFlagStr}\n` +
` CRC: ${crcToHexString(this.crc)}\n` +
` extra header length: ${this.extraHeadersLength} bytes\n` +
` data payload length: ${this.dataLength} bytes\n` +
` payload encoding: ${encode_name} (val: ${this.encoding})`
);
}
/**
* Start time in the format output by mseed3-utils from IRIS. Format is
* yyyy,ooo,HH:mm:ss.SSSSSS
*
* @returns start time
*/
startFieldsInUtilFormat(): string {
return `${this.year},${padZeros(this.dayOfYear, 3)},`+
`${padZeros(this.hour, 2)}:${padZeros(this.minute, 2)}:${padZeros(this.second, 2)}.${padZeros(Math.floor(this.nanosecond/1000), 6)}`;
}
/**
* Converts start time header fields to ISO8601 time string. This will include
* factional seconds to nanosecond precision.
*
* @param trimMicroNano trim to microsecond precision if nanos are 000
* @returns iso start time
*/
getStartFieldsAsISO(trimMicroNano = true): string {
const d = this.startAsDateTime().set({ millisecond: 0 })
.toISO({includeOffset: false, suppressMilliseconds: true});
let fracSec = "";
if (trimMicroNano && this.nanosecond % 1000 === 0) {
// nanos end in 000 so just use micros
fracSec = padZeros(this.nanosecond/1000, 6);
} else {
fracSec = padZeros(this.nanosecond, 9);
}
return `${d}.${fracSec}Z`;
}
/**
* sets start time headers.
*
* @param starttime start as DateTime
*/
setStart(starttime: DateTime) {
this.nanosecond = starttime.millisecond*1000;
this.year = starttime.year;
this.dayOfYear = starttime.ordinal;
this.hour = starttime.hour;
this.minute = starttime.minute;
this.second = starttime.second;
}
/**
* Calculates time of the ith sample.
*
* @param i sample number
* @returns the time
*/
timeOfSample(i: number): DateTime {
return this.start
.plus(Duration.fromMillis((1000 * i) / this.sampleRate));
}
/**
* Writes to the given dataview.
*
* @param dataView write buffer
* @param offset offset within the buffer
* @param zeroCrc optionally zero out the crc field in order to recalculate
* @returns new offset after this record
*/
save(
dataView: DataView,
offset = 0,
zeroCrc = false,
): number {
dataView.setUint8(offset, this.recordIndicator.charCodeAt(0));
offset++;
dataView.setUint8(offset, this.recordIndicator.charCodeAt(1));
offset++;
dataView.setUint8(offset, this.formatVersion);
offset++;
dataView.setUint8(offset, this.flags);
offset++;
dataView.setUint32(offset, this.nanosecond, true);
offset += 4;
dataView.setUint16(offset, this.year, true);
offset += 2;
dataView.setUint16(offset, this.dayOfYear, true);
offset += 2;
dataView.setUint8(offset, this.hour);
offset++;
dataView.setUint8(offset, this.minute);
offset++;
dataView.setUint8(offset, this.second);
offset++;
dataView.setUint8(offset, this.encoding);
offset++;
dataView.setFloat64(offset, this.sampleRateOrPeriod, true);
offset += 8;
dataView.setUint32(offset, this.numSamples, true);
offset += 4;
if (zeroCrc) {
dataView.setUint32(offset, 0, true);
} else {
dataView.setUint32(offset, this.crc, true);
}
offset += 4;
dataView.setUint8(offset, this.publicationVersion);
offset++;
dataView.setUint8(offset, this.identifier.length);
offset++;
dataView.setUint16(offset, this.extraHeadersLength, true);
offset += 2;
dataView.setUint32(offset, this.dataLength, true);
offset += 4;
for (let i = 0; i < this.identifier.length; i++) {
// not ok for unicode?
dataView.setUint8(offset, this.identifier.charCodeAt(i));
offset++;
}
return offset;
}
/**
* Converts header start time to DateTime
*
* @returns start time as DateTime
*/
startAsDateTime(): DateTime {
return DateTime.fromObject({
year: this.year,
ordinal: this.dayOfYear,
hour: this.hour,
minute: this.minute,
second: this.second,
millisecond: Math.round(this.nanosecond / 1000000),
}, UTC_OPTIONS);
}
}
/**
* Parses extra headers as json.
*
* @param dataView json bytes as DataView
* @returns json object
*/
export function parseExtraHeaders(dataView: DataView): Record<string, unknown> {
if (dataView.byteLength === 0) {
return {};
}
const firstChar = dataView.getUint8(0);
if (firstChar === 123) {
// looks like json, '{' is ascii 123
const jsonStr = makeString(dataView, 0, dataView.byteLength);
const v: unknown = JSON.parse(jsonStr);
if (typeof v === 'object') {
return v as Record<string, unknown>;
} else {
throw new Error(`extra headers does not look like JSON object: ${jsonStr}"`);
}
} else {
throw new Error(
"do not understand extras with first char val: " +
firstChar +
" " +
(firstChar === 123),
);
}
}
/**
* Creates a string version of a number with zero prefix padding. For example
* padZeros(5, 3) is 005.
*
* @param val number to stringify
* @param len total length of string
* @returns zero padded string
*/
export function padZeros(val: number, len: number): string {
let out = "" + val;
while (out.length < len) {
out = "0" + out;
}
return out;
}
/**
* creates a string from bytes in a DataView.
*
* @param dataView data bytes
* @param offset offset to first byte to use
* @param length number of bytes to convert
* @returns string resulting from utf-8 conversion
*/
export function makeString(
dataView: DataView,
offset: number,
length: number,
): string {
const utf8decoder = new TextDecoder("utf-8");
const u8arr = new Uint8Array(
dataView.buffer,
dataView.byteOffset + offset,
length,
);
return utf8decoder.decode(u8arr).trim();
}
/**
* Sanity checks on year to see if a record might be in the wrong byte order.
* Checks year betwee 1960 and 2055.
*
* @param year year as number to test
* @returns true is byte order appears to be wrong, false if it seems ok
*/
function checkByteSwap(year: number) {
return year < 1960 || year > 2055;
}
/**
* Checks if two miniseed3 records are (nearly) contiguous.
*
* @param dr1 first record
* @param dr2 second record
* @param sampRatio tolerence expressed as ratio of sample period, default 1.5
* @returns true if contiguous
*/
export function areContiguous(
dr1: MSeed3Record,
dr2: MSeed3Record,
sampRatio = 1.5,
): boolean {
const h1 = dr1.header;
const h2 = dr2.header;
return (
h1.end < h2.start &&
h1.end.plus(Duration.fromMillis(1000*sampRatio / h1.sampleRate))
>= h2.start
);
}
/**
* Concatentates a sequence of MSeed3 Records into a single seismogram object.
* Assumes that they are all contiguous (no gaps or overlaps) and in order.
* Header values from the first MSeed3 Record are used.
*
* @param contig array of miniseed3 records
* @returns seismogram segment for the records
*/
export function createSeismogramSegment(
contig: Array<MSeed3Record>,
): SeismogramSegment {
const contigData = contig.map(dr => dr.asEncodedDataSegment());
const out = new SeismogramSegment(
contigData,
contig[0].header.sampleRate,
contig[0].header.start,
FDSNSourceId.parse(contig[0].header.identifier)
);
return out;
}
/**
* Merges miniseed3 records into a Seismogram object, each of
* which consists of SeismogramSegment objects
* containing the data as EncodedDataSegment objects. DataRecords are
* sorted by startTime.
* This assumes all data records are from the same channel, byChannel
* can be used first if multiple channels may be present. Gaps may be present.
*
* @param drList list of miniseed3 records to convert
* @returns the seismogram
*/
export function merge(drList: Array<MSeed3Record>): Seismogram {
return new Seismogram(mergeSegments(drList));
}
/**
* merges contiguous MSeed3Record into SeismogramSegments.
*
* @param drList array of data records
* @returns array of SeismogramSegments for contiguous data
*/
export function mergeSegments(drList: Array<MSeed3Record>): Array<SeismogramSegment> {
const out = [];
let currDR;
drList.sort(function (a, b) {
return a.header.start.valueOf() - b.header.start.valueOf();
});
let contig: Array<MSeed3Record> = [];
for (let i = 0; i < drList.length; i++) {
currDR = drList[i];
if (contig.length === 0) {
contig.push(currDR);
} else if (areContiguous(contig[contig.length - 1], currDR)) {
contig.push(currDR);
} else {
//found a gap
out.push(createSeismogramSegment(contig));
contig = [currDR];
}
}
if (contig.length > 0) {
// last segment
out.push(createSeismogramSegment(contig));
contig = [];
}
return out;
}
/**
* splits a list of data records by channel identifier, returning an object
* with each NSLC mapped to an array of data records.
*
* @param drList array of miniseed3 records
* @returns map of channel id to array of miniseed3 records, possibly not contiguous
*/
export function byChannel(
drList: Array<MSeed3Record>,
): Map<string, Array<MSeed3Record>> {
const out: Map<string, Array<MSeed3Record>> = new Map();
let key;
for (let i = 0; i < drList.length; i++) {
const currDR = drList[i];
key = currDR.codes();
let drArray = out.get(key);
if (!drArray) {
drArray = [currDR];
out.set(key, drArray);
} else {
drArray.push(currDR);
}
}
return out;
}
/**
* splits the records by channel and creates a single
* SeismogramSegment for each contiguous window from each channel.
*
* @param drList MSeed3Records array
* @returns Array of SeismogramSegment
*/
export function seismogramSegmentPerChannel(
drList: Array<MSeed3Record>,
): Array<SeismogramSegment> {
let out = new Array<SeismogramSegment>(0);
const byChannelMap = byChannel(drList);
byChannelMap.forEach(segments => out = out.concat(mergeSegments(segments)));
return out;
}
/**
* splits the MSeed3Records by channel and creates a single
* Seismogram for each channel.
*
* @param drList MSeed3Records array
* @returns Map of code to Seismogram
*/
export function seismogramPerChannel(
drList: Array<MSeed3Record>,
): Array<Seismogram> {
const out: Array<Seismogram> = [];
const byChannelMap = byChannel(drList);
byChannelMap.forEach(segments => out.push(merge(segments)));
return out;
}
/* MSeed2 to xSeed converstion */
/**
* Convert array of Miniseed2 DataRecords into an array of MSeed3Records.
*
* @param mseed2 array of DataRecords
* @returns array of MSeed3Records
*/
export function convertMS2toMSeed3(
mseed2: Array<DataRecord>,
): Array<MSeed3Record> {
const out = [];
for (let i = 0; i < mseed2.length; i++) {
out.push(convertMS2Record(mseed2[i]));
}
return out;
}
/**
* Converts a single miniseed2 DataRecord into a single MSeed3Record.
*
* @param ms2record Miniseed2 DataRecord to convert
* @returns MSeed3Record
*/
export function convertMS2Record(ms2record: DataRecord): MSeed3Record {
const xHeader = new MSeed3Header();
const xExtras: Record<string,unknown> = {};
const ms2H = ms2record.header;
xHeader.flags =
(ms2H.activityFlags & 1) * 2 +
(ms2H.ioClockFlags & 64) * 4 +
(ms2H.dataQualityFlags & 16) * 8;
xHeader.year = ms2H.startBTime.year;
xHeader.dayOfYear = ms2H.startBTime.jday;
xHeader.hour = ms2H.startBTime.hour;
xHeader.minute = ms2H.startBTime.min;
xHeader.second = ms2H.startBTime.sec;
xHeader.nanosecond =
ms2H.startBTime.tenthMilli * 100000 + ms2H.startBTime.microsecond * 1000;
xHeader.sampleRateOrPeriod =
ms2H.sampleRate >= 1 ? ms2H.sampleRate : -1.0 / ms2H.sampleRate;
xHeader.encoding = ms2record.header.encoding;
xHeader.publicationVersion = UNKNOWN_DATA_VERSION;
xHeader.dataLength = ms2record.data.byteLength;
xHeader.identifier =
FDSN_PREFIX +
":" +
ms2H.netCode +
SEP +
ms2H.staCode +
SEP +
(ms2H.locCode ? ms2H.locCode : "") +
SEP +
ms2H.chanCode;
xHeader.identifierLength = xHeader.identifier.length;
xHeader.numSamples = ms2H.numSamples;
xHeader.crc = 0;
if (ms2H.typeCode) {
if (ms2H.typeCode === R_TYPECODE) {
xHeader.publicationVersion = 1;
} else if (ms2H.typeCode === D_TYPECODE) {
xHeader.publicationVersion = 2;
} else if (ms2H.typeCode === Q_TYPECODE) {
xHeader.publicationVersion = 3;
} else if (ms2H.typeCode === M_TYPECODE) {
xHeader.publicationVersion = 4;
}
if (ms2H.typeCode !== D_TYPECODE) {