hydrography 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hydrography-0.1.0.dist-info/METADATA +24 -0
- hydrography-0.1.0.dist-info/RECORD +22 -0
- hydrography-0.1.0.dist-info/WHEEL +5 -0
- hydrography-0.1.0.dist-info/licenses/LICENSE +7 -0
- hydrography-0.1.0.dist-info/top_level.txt +1 -0
- mbes/AllReader.py +551 -0
- mbes/Attitude.py +9 -0
- mbes/BaseReader.py +11 -0
- mbes/Georeferencing.py +46 -0
- mbes/Interpolator.py +50 -0
- mbes/KmallReader.py +213 -0
- mbes/LeastSquares.py +18 -0
- mbes/MbesReader.py +113 -0
- mbes/Ping.py +12 -0
- mbes/Position.py +13 -0
- mbes/S7kReader.py +462 -0
- mbes/SbetReader.py +197 -0
- mbes/SoundVelocityProfile.py +72 -0
- mbes/Viewer.py +48 -0
- mbes/XtfReader.py +532 -0
- mbes/__init__.py +0 -0
- mbes/core.py +17 -0
mbes/S7kReader.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
import struct
|
|
2
|
+
import mmap
|
|
3
|
+
import sys
|
|
4
|
+
import math
|
|
5
|
+
import datetime
|
|
6
|
+
import numpy as np
|
|
7
|
+
|
|
8
|
+
from mbes.BaseReader import BaseReader
|
|
9
|
+
from mbes.Ping import Ping
|
|
10
|
+
from mbes.Attitude import Attitude
|
|
11
|
+
from mbes.Position import Position
|
|
12
|
+
|
|
13
|
+
# References are to the Teledyne RESON "7k Data Format, Volume I", DFD 12713 version 2.41.
|
|
14
|
+
# All data is little endian with single byte alignment (2.6). Distances in metres, angles in radians (2.2).
|
|
15
|
+
|
|
16
|
+
# Data Record Frame (DRF), Table 5. The 7KTIME (Table 3) is inlined as HHfBB.
|
|
17
|
+
DRF = struct.Struct("<HHIIIIHHfBBHIIHHIHHIII") # 64 bytes
|
|
18
|
+
CHECKSUM = struct.Struct("<I")
|
|
19
|
+
SYNC_PATTERN = 0x0000FFFF
|
|
20
|
+
SYNC_BYTES = struct.pack("<I", SYNC_PATTERN)
|
|
21
|
+
SYNC_OFFSET = 4 # the DRF "Offset" field (to the Record Type Header) counts from the sync pattern
|
|
22
|
+
PROTOCOL_VERSION = 5 # Table 4: only version 5 is in use
|
|
23
|
+
DRF_FLAG_CHECKSUM = 0x0001 # DRF flags bit 0: checksum is valid
|
|
24
|
+
|
|
25
|
+
# Record Type Headers (RTH) and Record Data (RD)
|
|
26
|
+
POSITION_1003 = struct.Struct("<IfdddBBBB") # Table 12. A trailing "Number of satellites" (u8) is optional
|
|
27
|
+
ROLL_PITCH_HEAVE_1012 = struct.Struct("<fff") # Table 25
|
|
28
|
+
HEADING_1013 = struct.Struct("<f") # Table 26
|
|
29
|
+
NAVIGATION_1015 = struct.Struct("<Bdd6f") # Table 29
|
|
30
|
+
ATTITUDE_1016 = struct.Struct("<B") # Table 30
|
|
31
|
+
ATTITUDE_SAMPLE_1016 = struct.Struct("<H4f") # Table 31
|
|
32
|
+
INSTALLATION_1020 = struct.Struct("<5I4f3f3f4f3f3ff3fI") # Table 33, without the trailing 44 reserved bytes
|
|
33
|
+
SONAR_SETTINGS_7000 = struct.Struct("<QIH4fIIfHH5fII5fIfIIIfIf4f3fH") # Table 36
|
|
34
|
+
RAW_DETECTION_7027 = struct.Struct("<QIHIIBIff16I") # Table 66
|
|
35
|
+
DETECTION_7027 = struct.Struct("<HffIIff") # Table 67, may be shorter (older) or longer (newer) in a file
|
|
36
|
+
DETECTION_7027_MIN = struct.calcsize("<Hff") # beam descriptor, detection point and rx angle are required
|
|
37
|
+
INSTALLATION_7030 = struct.Struct("<fH128sH128sH128sH128s6f6f6fH3fHf") # Table 71
|
|
38
|
+
|
|
39
|
+
# Record type identifiers (Table 7)
|
|
40
|
+
RECORD_POSITION = 1003
|
|
41
|
+
RECORD_ROLL_PITCH_HEAVE = 1012
|
|
42
|
+
RECORD_HEADING = 1013
|
|
43
|
+
RECORD_NAVIGATION = 1015
|
|
44
|
+
RECORD_ATTITUDE = 1016
|
|
45
|
+
RECORD_INSTALLATION_IDENTIFIERS = 1020
|
|
46
|
+
RECORD_SONAR_SETTINGS = 7000
|
|
47
|
+
RECORD_BATHYMETRIC_DATA = 7006
|
|
48
|
+
RECORD_RAW_DETECTION_DATA = 7027
|
|
49
|
+
RECORD_INSTALLATION_PARAMETERS = 7030
|
|
50
|
+
|
|
51
|
+
PARSED_RECORDS = {RECORD_POSITION, RECORD_ROLL_PITCH_HEAVE, RECORD_HEADING, RECORD_NAVIGATION, RECORD_ATTITUDE,
|
|
52
|
+
RECORD_INSTALLATION_IDENTIFIERS, RECORD_SONAR_SETTINGS, RECORD_RAW_DETECTION_DATA, RECORD_INSTALLATION_PARAMETERS}
|
|
53
|
+
TIMED_RECORDS = {RECORD_POSITION, RECORD_ROLL_PITCH_HEAVE, RECORD_HEADING, RECORD_NAVIGATION, RECORD_ATTITUDE, RECORD_RAW_DETECTION_DATA}
|
|
54
|
+
|
|
55
|
+
# Known records (Table 7, chapter 12) that are not used (yet)
|
|
56
|
+
KNOWN_UNUSED_RECORDS = (
|
|
57
|
+
{1000, 1001, 1002, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1014, 1017, 1022, 1050, 1200, 2004, 5835, 5836}
|
|
58
|
+
| set(range(1500, 1600))
|
|
59
|
+
| {7001, 7002, 7003, 7004, 7005, 7007, 7008, 7009, 7010, 7011, 7012, 7016, 7017, 7018, 7019, 7021, 7022, 7023, 7024,
|
|
60
|
+
7026, 7028, 7031, 7037, 7038, 7040, 7041, 7042, 7048, 7050, 7051, 7052, 7053, 7055, 7057, 7058, 7059, 7060, 7068}
|
|
61
|
+
| {7200, 7300, 7310, 7311, 7312} | set(range(7400, 7500))
|
|
62
|
+
| {7500, 7501, 7502, 7503, 7504, 7505, 7510, 7511, 7515, 7610, 7611, 7612, 7613}
|
|
63
|
+
| set(range(7900, 8000)) | {8012, 8100} | set(range(11000, 11300)) | set(range(81000, 88000))
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# 1003 Position
|
|
67
|
+
DATUM_WGS84 = 0
|
|
68
|
+
POSITION_TYPE_GEOGRAPHIC = 0
|
|
69
|
+
|
|
70
|
+
# 7027 RTH flags bits 0-3: uncertainty method, 0 = not calculated
|
|
71
|
+
UNCERTAINTY_METHOD_MASK = 0x0F
|
|
72
|
+
|
|
73
|
+
# 7027 detection flags bits 9-12: detection priority within the same beam (multi-detect only), 0 = highest
|
|
74
|
+
DETECTION_PRIORITY_SHIFT = 9
|
|
75
|
+
DETECTION_PRIORITY_MASK = 0x0F
|
|
76
|
+
|
|
77
|
+
EPOCH_ORDINAL = datetime.date(1970, 1, 1).toordinal()
|
|
78
|
+
|
|
79
|
+
def epoch_microseconds_from_7ktime(year, day, seconds, hours, minutes):
|
|
80
|
+
"""7KTIME (Table 3: UTC year, day of year 1-366, seconds, hours, minutes) to microseconds since 1970-01-01.
|
|
81
|
+
Returns None if no time is available (all fields zero, 2.7) or the fields are invalid."""
|
|
82
|
+
if not (1 <= day <= 366 and hours <= 23 and minutes <= 59 and 0.0 <= seconds < 61.0):
|
|
83
|
+
return None
|
|
84
|
+
try:
|
|
85
|
+
days = datetime.date(year, 1, 1).toordinal() - EPOCH_ORDINAL + day - 1
|
|
86
|
+
except ValueError:
|
|
87
|
+
return None
|
|
88
|
+
return ((days * 24 + hours) * 60 + minutes) * 60000000 + int(round(seconds * 1e6))
|
|
89
|
+
|
|
90
|
+
def checksum(buffer, start, end):
|
|
91
|
+
"""DRF checksum: unsigned 32-bit sum of all bytes from the protocol version field to the end of the data section."""
|
|
92
|
+
return int(np.frombuffer(buffer, dtype=np.uint8, count=end - start, offset=start).sum(dtype=np.uint64)) & 0xFFFFFFFF
|
|
93
|
+
|
|
94
|
+
def largest_stream(streams):
|
|
95
|
+
"""Samples of the (device identifier, system enumerator) stream with the most samples, so two sensors never get interleaved."""
|
|
96
|
+
return max(streams.values(), key=len) if streams else []
|
|
97
|
+
|
|
98
|
+
class S7kReader(BaseReader):
|
|
99
|
+
def __init__(self):
|
|
100
|
+
super().__init__()
|
|
101
|
+
self.include_extra_detections = False #Multi-detect: lower priority detections in the same beam (priority > 0)
|
|
102
|
+
self.verify_checksums = True #Skip parsed records whose DRF checksum (when flagged as valid) does not match
|
|
103
|
+
self.positions = []
|
|
104
|
+
self.attitudes = []
|
|
105
|
+
self.pings = []
|
|
106
|
+
self.installation = {} #parsed 1020 and 7030, e.g. installation["7030"]["receiveArrayX_m"]
|
|
107
|
+
|
|
108
|
+
def lever_arm(self):
|
|
109
|
+
"""Sonar reference point re. vessel reference point, in the VCS used by KmallReader (x fwd, y stbd, z down).
|
|
110
|
+
The 7k frame is X starboard, Y forward, Z up (2.2), so (x, y, z) = (Y, X, -Z).
|
|
111
|
+
From 7030 (written by third party software such as Teledyne PDS): along-track from the TX array, across-track
|
|
112
|
+
and vertical from the RX array, as the sonar reference point is defined (2.4). Otherwise the VRP to SRP offset from 1020."""
|
|
113
|
+
parameters = self.installation.get("7030")
|
|
114
|
+
if parameters:
|
|
115
|
+
return np.array([parameters["transmitArrayY_m"], parameters["receiveArrayX_m"], -parameters["receiveArrayZ_m"]])
|
|
116
|
+
identifiers = self.installation.get("1020")
|
|
117
|
+
if identifiers:
|
|
118
|
+
return np.array([identifiers["vrpToSrpY_m"], identifiers["vrpToSrpX_m"], -identifiers["vrpToSrpZ_m"]])
|
|
119
|
+
return np.zeros(3)
|
|
120
|
+
|
|
121
|
+
def read(self,filename):
|
|
122
|
+
self.positions = []
|
|
123
|
+
self.attitudes = []
|
|
124
|
+
self.pings = []
|
|
125
|
+
self.installation = {}
|
|
126
|
+
|
|
127
|
+
# Repeated problems are reported once, with a count, at the end
|
|
128
|
+
warnings = {}
|
|
129
|
+
def warn(message):
|
|
130
|
+
warnings[message] = warnings.get(message, 0) + 1
|
|
131
|
+
|
|
132
|
+
# Sensor samples per stream, keyed by (device identifier, system enumerator)
|
|
133
|
+
positions_1003 = {} # (epoch_us, latitude_rad, longitude_rad, height_m)
|
|
134
|
+
navigation_1015 = {} # (epoch_us, latitude_rad, longitude_rad, height_m, heading_rad)
|
|
135
|
+
rph_1012 = {} # (epoch_us, roll_rad, pitch_rad)
|
|
136
|
+
heading_1013 = {} # (epoch_us, heading_rad)
|
|
137
|
+
attitude_1016 = {} # (epoch_us, roll_rad, pitch_rad, heading_rad)
|
|
138
|
+
|
|
139
|
+
# 7027 carries no sound velocity: take it from the 7000 of the same ping, which may come before or after it
|
|
140
|
+
sound_velocity_7000 = {} # (device, enumerator, ping number, multi-ping sequence) -> sound velocity
|
|
141
|
+
latest_sound_velocity = {} # (device, enumerator) -> last 7000 sound velocity seen, fallback
|
|
142
|
+
detections_7027 = [] # located in the first pass, turned into Pings in the second
|
|
143
|
+
count_7006 = 0
|
|
144
|
+
|
|
145
|
+
with open(filename, "rb") as file, mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as buffer:
|
|
146
|
+
file_size = len(buffer)
|
|
147
|
+
offset = 0
|
|
148
|
+
invalid_since = None # start of a corrupted region while searching for the next sync pattern
|
|
149
|
+
|
|
150
|
+
# Read file one record at the time
|
|
151
|
+
while offset + DRF.size + CHECKSUM.size <= file_size:
|
|
152
|
+
record_start = offset
|
|
153
|
+
|
|
154
|
+
# Read Data Record Frame
|
|
155
|
+
(protocolVersion, rthOffset, syncPattern, recordSize, optionalDataOffset, optionalDataIdentifier,
|
|
156
|
+
year, day, seconds, hours, minutes,
|
|
157
|
+
recordVersion, recordTypeIdentifier, deviceIdentifier, reserved0, systemEnumerator, reserved1,
|
|
158
|
+
flags, reserved2, reserved3, totalRecordsInFragmentedSet, fragmentNumber) = DRF.unpack_from(buffer, offset)
|
|
159
|
+
|
|
160
|
+
record_end = record_start + recordSize
|
|
161
|
+
rth_start = record_start + SYNC_OFFSET + rthOffset
|
|
162
|
+
body_end = record_end - CHECKSUM.size
|
|
163
|
+
|
|
164
|
+
# The sync pattern combined with the checksum allows recovery from corruption (chapter 6)
|
|
165
|
+
valid_frame = (syncPattern == SYNC_PATTERN and recordSize >= DRF.size + CHECKSUM.size and
|
|
166
|
+
record_start + DRF.size <= rth_start <= body_end and record_end <= file_size)
|
|
167
|
+
if not valid_frame:
|
|
168
|
+
if invalid_since is None:
|
|
169
|
+
invalid_since = record_start
|
|
170
|
+
if syncPattern == SYNC_PATTERN and record_end > file_size:
|
|
171
|
+
sys.stderr.write(f"Record at offset {record_start} ({recordSize} bytes) extends past the end of the file ({file_size - record_start} bytes left)\n")
|
|
172
|
+
else:
|
|
173
|
+
sys.stderr.write(f"Invalid record frame at offset {record_start}, searching for the next sync pattern\n")
|
|
174
|
+
next_sync = buffer.find(SYNC_BYTES, record_start + SYNC_OFFSET + 1)
|
|
175
|
+
if next_sync < 0:
|
|
176
|
+
break
|
|
177
|
+
offset = next_sync - SYNC_OFFSET
|
|
178
|
+
continue
|
|
179
|
+
if invalid_since is not None:
|
|
180
|
+
sys.stderr.write(f"Resynchronised at offset {record_start}, skipped {record_start - invalid_since} bytes\n")
|
|
181
|
+
invalid_since = None
|
|
182
|
+
|
|
183
|
+
offset = record_end
|
|
184
|
+
|
|
185
|
+
if protocolVersion != PROTOCOL_VERSION:
|
|
186
|
+
warn(f"Protocol version {protocolVersion} (expected {PROTOCOL_VERSION}), parsed as version {PROTOCOL_VERSION}")
|
|
187
|
+
|
|
188
|
+
# The optional data (if any) follows the record data
|
|
189
|
+
if optionalDataOffset and rth_start <= record_start + optionalDataOffset <= body_end:
|
|
190
|
+
body_end = record_start + optionalDataOffset
|
|
191
|
+
body_size = body_end - rth_start
|
|
192
|
+
|
|
193
|
+
if recordTypeIdentifier in PARSED_RECORDS:
|
|
194
|
+
if self.verify_checksums and flags & DRF_FLAG_CHECKSUM:
|
|
195
|
+
(recordChecksum,) = CHECKSUM.unpack_from(buffer, record_end - CHECKSUM.size)
|
|
196
|
+
if checksum(buffer, record_start, record_end - CHECKSUM.size) != recordChecksum:
|
|
197
|
+
warn(f"Checksum mismatch, record {recordTypeIdentifier} skipped")
|
|
198
|
+
continue
|
|
199
|
+
|
|
200
|
+
# Time at which the data was generated (chapter 9); for ping records when the transmitter finishes the ping
|
|
201
|
+
epoch_microseconds = epoch_microseconds_from_7ktime(year, day, seconds, hours, minutes)
|
|
202
|
+
if epoch_microseconds is None and recordTypeIdentifier in TIMED_RECORDS:
|
|
203
|
+
warn(f"No valid time, record {recordTypeIdentifier} skipped")
|
|
204
|
+
continue
|
|
205
|
+
|
|
206
|
+
stream = (deviceIdentifier, systemEnumerator)
|
|
207
|
+
|
|
208
|
+
if recordTypeIdentifier == RECORD_POSITION:
|
|
209
|
+
#1003 Position
|
|
210
|
+
if body_size < POSITION_1003.size:
|
|
211
|
+
warn("Record 1003 too short, skipped")
|
|
212
|
+
continue
|
|
213
|
+
(datumIdentifier, latency_sec, latitude_rad, longitude_rad, height_m, positionTypeFlag, utmZone, qualityFlag, positioningMethod) = POSITION_1003.unpack_from(buffer, rth_start)
|
|
214
|
+
|
|
215
|
+
# Position only takes geographic WGS84 coordinates. The latency is not applied: positions use the time in the message (chapter 9)
|
|
216
|
+
if positionTypeFlag != POSITION_TYPE_GEOGRAPHIC or datumIdentifier != DATUM_WGS84:
|
|
217
|
+
warn("Record 1003 in grid coordinates or a non-WGS84 datum, skipped")
|
|
218
|
+
continue
|
|
219
|
+
positions_1003.setdefault(stream, []).append((epoch_microseconds, latitude_rad, longitude_rad, height_m))
|
|
220
|
+
|
|
221
|
+
elif recordTypeIdentifier == RECORD_ROLL_PITCH_HEAVE:
|
|
222
|
+
#1012 Roll Pitch Heave
|
|
223
|
+
if body_size < ROLL_PITCH_HEAVE_1012.size:
|
|
224
|
+
warn("Record 1012 too short, skipped")
|
|
225
|
+
continue
|
|
226
|
+
(roll_rad, pitch_rad, heave_m) = ROLL_PITCH_HEAVE_1012.unpack_from(buffer, rth_start)
|
|
227
|
+
rph_1012.setdefault(stream, []).append((epoch_microseconds, roll_rad, pitch_rad))
|
|
228
|
+
|
|
229
|
+
elif recordTypeIdentifier == RECORD_HEADING:
|
|
230
|
+
#1013 Heading
|
|
231
|
+
if body_size < HEADING_1013.size:
|
|
232
|
+
warn("Record 1013 too short, skipped")
|
|
233
|
+
continue
|
|
234
|
+
(heading_rad,) = HEADING_1013.unpack_from(buffer, rth_start)
|
|
235
|
+
heading_1013.setdefault(stream, []).append((epoch_microseconds, heading_rad))
|
|
236
|
+
|
|
237
|
+
elif recordTypeIdentifier == RECORD_NAVIGATION:
|
|
238
|
+
#1015 Navigation, at the vessel reference point
|
|
239
|
+
if body_size < NAVIGATION_1015.size:
|
|
240
|
+
warn("Record 1015 too short, skipped")
|
|
241
|
+
continue
|
|
242
|
+
(verticalReference, latitude_rad, longitude_rad, horizontalPositionAccuracy_m, vesselHeight_m, heightAccuracy_m, speedOverGround_mPerSec, courseOverGround_rad, heading_rad) = NAVIGATION_1015.unpack_from(buffer, rth_start)
|
|
243
|
+
navigation_1015.setdefault(stream, []).append((epoch_microseconds, latitude_rad, longitude_rad, vesselHeight_m, heading_rad))
|
|
244
|
+
|
|
245
|
+
elif recordTypeIdentifier == RECORD_ATTITUDE:
|
|
246
|
+
#1016 Attitude, at the motion sensor rate
|
|
247
|
+
if body_size < ATTITUDE_1016.size:
|
|
248
|
+
warn("Record 1016 too short, skipped")
|
|
249
|
+
continue
|
|
250
|
+
(numberOfDataSets,) = ATTITUDE_1016.unpack_from(buffer, rth_start)
|
|
251
|
+
if ATTITUDE_1016.size + numberOfDataSets * ATTITUDE_SAMPLE_1016.size > body_size:
|
|
252
|
+
warn("Record 1016 too short for its number of data sets, skipped")
|
|
253
|
+
continue
|
|
254
|
+
|
|
255
|
+
samples = attitude_1016.setdefault(stream, [])
|
|
256
|
+
attitude_offset = rth_start + ATTITUDE_1016.size
|
|
257
|
+
for _ in range(numberOfDataSets):
|
|
258
|
+
(timeDifference_ms, roll_rad, pitch_rad, heave_m, heading_rad) = ATTITUDE_SAMPLE_1016.unpack_from(buffer, attitude_offset)
|
|
259
|
+
attitude_offset += ATTITUDE_SAMPLE_1016.size
|
|
260
|
+
|
|
261
|
+
# Each data set is timed relative to the record timestamp
|
|
262
|
+
samples.append((epoch_microseconds + timeDifference_ms * 1000, roll_rad, pitch_rad, heading_rad))
|
|
263
|
+
|
|
264
|
+
elif recordTypeIdentifier == RECORD_INSTALLATION_IDENTIFIERS:
|
|
265
|
+
#1020 Sonar Installation Identifiers
|
|
266
|
+
if body_size < INSTALLATION_1020.size:
|
|
267
|
+
warn("Record 1020 too short, skipped")
|
|
268
|
+
continue
|
|
269
|
+
(systemIdentificationNumber, transmitterIdentificationNumber, receiverIdentificationNumber, standardConfigurationOptions, configurationFixedParameters,
|
|
270
|
+
txLength_m, txWidth_m, txHeight_m, txRadius_m, srpToTxX_m, srpToTxY_m, srpToTxZ_m, txRoll_rad, txPitch_rad, txYaw_rad,
|
|
271
|
+
rxLength_m, rxWidth_m, rxHeight_m, rxRadius_m, srpToRxX_m, srpToRxY_m, srpToRxZ_m, rxRoll_rad, rxPitch_rad, rxYaw_rad,
|
|
272
|
+
frequency_Hz, vrpToSrpX_m, vrpToSrpY_m, vrpToSrpZ_m, cableLength_m) = INSTALLATION_1020.unpack_from(buffer, rth_start)
|
|
273
|
+
self.installation["1020"] = {
|
|
274
|
+
"srpToTxX_m": srpToTxX_m, "srpToTxY_m": srpToTxY_m, "srpToTxZ_m": srpToTxZ_m,
|
|
275
|
+
"txRoll_rad": txRoll_rad, "txPitch_rad": txPitch_rad, "txYaw_rad": txYaw_rad,
|
|
276
|
+
"srpToRxX_m": srpToRxX_m, "srpToRxY_m": srpToRxY_m, "srpToRxZ_m": srpToRxZ_m,
|
|
277
|
+
"rxRoll_rad": rxRoll_rad, "rxPitch_rad": rxPitch_rad, "rxYaw_rad": rxYaw_rad,
|
|
278
|
+
"vrpToSrpX_m": vrpToSrpX_m, "vrpToSrpY_m": vrpToSrpY_m, "vrpToSrpZ_m": vrpToSrpZ_m,
|
|
279
|
+
"frequency_Hz": frequency_Hz}
|
|
280
|
+
|
|
281
|
+
elif recordTypeIdentifier == RECORD_INSTALLATION_PARAMETERS:
|
|
282
|
+
#7030 Sonar Installation Parameters, not generated by RESON sonars but by e.g. Teledyne PDS
|
|
283
|
+
if body_size < INSTALLATION_7030.size:
|
|
284
|
+
warn("Record 7030 too short, skipped")
|
|
285
|
+
continue
|
|
286
|
+
(frequency_Hz, firmwareVersionLength, firmwareVersion, softwareVersionLength, softwareVersion, software7kVersionLength, software7kVersion, recordProtocolLength, recordProtocolVersion,
|
|
287
|
+
transmitArrayX_m, transmitArrayY_m, transmitArrayZ_m, transmitArrayRoll_rad, transmitArrayPitch_rad, transmitArrayHeading_rad,
|
|
288
|
+
receiveArrayX_m, receiveArrayY_m, receiveArrayZ_m, receiveArrayRoll_rad, receiveArrayPitch_rad, receiveArrayHeading_rad,
|
|
289
|
+
motionSensorX_m, motionSensorY_m, motionSensorZ_m, motionSensorRollCalibration_rad, motionSensorPitchCalibration_rad, motionSensorHeadingCalibration_rad, motionSensorTimeDelay_sec,
|
|
290
|
+
positionSensorX_m, positionSensorY_m, positionSensorZ_m, positionSensorTimeDelay_sec, waterLineVerticalOffset_m) = INSTALLATION_7030.unpack_from(buffer, rth_start)
|
|
291
|
+
self.installation["7030"] = {
|
|
292
|
+
"transmitArrayX_m": transmitArrayX_m, "transmitArrayY_m": transmitArrayY_m, "transmitArrayZ_m": transmitArrayZ_m,
|
|
293
|
+
"transmitArrayRoll_rad": transmitArrayRoll_rad, "transmitArrayPitch_rad": transmitArrayPitch_rad, "transmitArrayHeading_rad": transmitArrayHeading_rad,
|
|
294
|
+
"receiveArrayX_m": receiveArrayX_m, "receiveArrayY_m": receiveArrayY_m, "receiveArrayZ_m": receiveArrayZ_m,
|
|
295
|
+
"receiveArrayRoll_rad": receiveArrayRoll_rad, "receiveArrayPitch_rad": receiveArrayPitch_rad, "receiveArrayHeading_rad": receiveArrayHeading_rad,
|
|
296
|
+
"motionSensorX_m": motionSensorX_m, "motionSensorY_m": motionSensorY_m, "motionSensorZ_m": motionSensorZ_m,
|
|
297
|
+
"motionSensorRollCalibration_rad": motionSensorRollCalibration_rad, "motionSensorPitchCalibration_rad": motionSensorPitchCalibration_rad,
|
|
298
|
+
"motionSensorHeadingCalibration_rad": motionSensorHeadingCalibration_rad, "motionSensorTimeDelay_sec": motionSensorTimeDelay_sec,
|
|
299
|
+
"positionSensorX_m": positionSensorX_m, "positionSensorY_m": positionSensorY_m, "positionSensorZ_m": positionSensorZ_m,
|
|
300
|
+
"positionSensorTimeDelay_sec": positionSensorTimeDelay_sec, "waterLineVerticalOffset_m": waterLineVerticalOffset_m,
|
|
301
|
+
"frequency_Hz": frequency_Hz}
|
|
302
|
+
|
|
303
|
+
elif recordTypeIdentifier == RECORD_SONAR_SETTINGS:
|
|
304
|
+
#7000 7k Sonar Settings, updated for each ping
|
|
305
|
+
if body_size < SONAR_SETTINGS_7000.size:
|
|
306
|
+
warn("Record 7000 too short, skipped")
|
|
307
|
+
continue
|
|
308
|
+
(sonarId, pingNumber, multiPingSequence, frequency_Hz, sampleRate_Hz, receiverBandwidth_Hz, txPulseWidth_sec, txPulseTypeIdentifier, txPulseEnvelopeIdentifier, txPulseEnvelopeParameter, txPulseMode, txPulseReserved,
|
|
309
|
+
maxPingRate, pingPeriod_sec, rangeSelection_m, powerSelection_dB, gainSelection_dB, controlFlags,
|
|
310
|
+
projectorIdentifier, projectorBeamSteeringAngleVertical_rad, projectorBeamSteeringAngleHorizontal_rad, projectorBeamWidthVertical_rad, projectorBeamWidthHorizontal_rad, projectorBeamFocalPoint_m, projectorBeamWeightingWindowType, projectorBeamWeightingWindowParameter,
|
|
311
|
+
transmitFlags, hydrophoneIdentifier, receiveBeamWeightingWindow, receiveBeamWeightingParameter, receiveFlags, receiveBeamWidth_rad,
|
|
312
|
+
rangeFilterMin_m, rangeFilterMax_m, depthFilterMin_m, depthFilterMax_m, absorption_dBPerkm, soundVelocity_mPerSec, spreading_dB, reserved) = SONAR_SETTINGS_7000.unpack_from(buffer, rth_start)
|
|
313
|
+
sound_velocity_7000[stream + (pingNumber, multiPingSequence)] = soundVelocity_mPerSec
|
|
314
|
+
latest_sound_velocity[stream] = soundVelocity_mPerSec
|
|
315
|
+
|
|
316
|
+
elif recordTypeIdentifier == RECORD_RAW_DETECTION_DATA:
|
|
317
|
+
#7027 7k RAW Detection Data
|
|
318
|
+
if body_size < RAW_DETECTION_7027.size:
|
|
319
|
+
warn("Record 7027 too short, skipped")
|
|
320
|
+
continue
|
|
321
|
+
(sonarId, pingNumber, multiPingSequence, numDetections, dataFieldSize, detectionAlgorithm, detectionFlags, samplingRate_Hz, txAngle_rad, *reserved) = RAW_DETECTION_7027.unpack_from(buffer, rth_start)
|
|
322
|
+
|
|
323
|
+
# The detection size is given by the RTH: older versions are shorter, newer ones have fields added at the end
|
|
324
|
+
if dataFieldSize < DETECTION_7027_MIN:
|
|
325
|
+
warn(f"Record 7027 with a detection size of {dataFieldSize} bytes, skipped")
|
|
326
|
+
continue
|
|
327
|
+
if RAW_DETECTION_7027.size + numDetections * dataFieldSize > body_size:
|
|
328
|
+
warn("Record 7027 too short for its number of detections, skipped")
|
|
329
|
+
continue
|
|
330
|
+
if not samplingRate_Hz > 0.0:
|
|
331
|
+
warn("Record 7027 without a valid sampling rate, skipped")
|
|
332
|
+
continue
|
|
333
|
+
|
|
334
|
+
detections_7027.append((epoch_microseconds, stream + (pingNumber, multiPingSequence), latest_sound_velocity.get(stream),
|
|
335
|
+
rth_start + RAW_DETECTION_7027.size, numDetections, dataFieldSize, detectionFlags, samplingRate_Hz, txAngle_rad))
|
|
336
|
+
|
|
337
|
+
elif recordTypeIdentifier == RECORD_BATHYMETRIC_DATA:
|
|
338
|
+
#7006 7k Bathymetric Data, deprecated and superseded by 7027
|
|
339
|
+
count_7006 += 1
|
|
340
|
+
elif recordTypeIdentifier in KNOWN_UNUSED_RECORDS:
|
|
341
|
+
# Known records that are not used (yet)
|
|
342
|
+
pass
|
|
343
|
+
else:
|
|
344
|
+
warn(f"Unknown record type {recordTypeIdentifier}")
|
|
345
|
+
|
|
346
|
+
if invalid_since is not None:
|
|
347
|
+
sys.stderr.write(f"No valid record found after offset {invalid_since}, stopping\n")
|
|
348
|
+
elif offset < file_size:
|
|
349
|
+
sys.stderr.write(f"Truncated record at offset {offset} ({file_size - offset} bytes left), stopping\n")
|
|
350
|
+
|
|
351
|
+
# Detections are read from the mapped file, so this happens before it is closed
|
|
352
|
+
self._make_pings(buffer, detections_7027, sound_velocity_7000, warn)
|
|
353
|
+
|
|
354
|
+
if not detections_7027 and count_7006:
|
|
355
|
+
warn("The file only has the deprecated 7006 bathymetry (superseded by 7027), which is not read: no pings")
|
|
356
|
+
|
|
357
|
+
self._make_positions(navigation_1015, positions_1003)
|
|
358
|
+
self._make_attitudes(attitude_1016, rph_1012, heading_1013, navigation_1015, warn)
|
|
359
|
+
|
|
360
|
+
for message, count in warnings.items():
|
|
361
|
+
sys.stderr.write(f"{message}" + (f" ({count}x)" if count > 1 else "") + "\n")
|
|
362
|
+
|
|
363
|
+
@staticmethod
|
|
364
|
+
def _read_detection(buffer, offset, size):
|
|
365
|
+
"""One 7027 detection. Older, shorter versions are padded with zeros (like the C++ example in appendix E)."""
|
|
366
|
+
if size >= DETECTION_7027.size:
|
|
367
|
+
return DETECTION_7027.unpack_from(buffer, offset)
|
|
368
|
+
return DETECTION_7027.unpack(bytes(buffer[offset : offset + size]) + bytes(DETECTION_7027.size - size))
|
|
369
|
+
|
|
370
|
+
def _rx_angle_sign(self, buffer, detections_7027):
|
|
371
|
+
"""Beam zero is the first beam on the port side of the array (2.5) and the 7k frame has X to starboard (2.4), so the
|
|
372
|
+
rx angle should increase with the beam number (figure 10-1). Ping.beam_angle is positive to starboard, like in
|
|
373
|
+
KmallReader. Check that against the data rather than trust it: vote over the first and last detection of each ping."""
|
|
374
|
+
votes = 0
|
|
375
|
+
for (epoch_microseconds, ping_key, fallback_sound_velocity, data_offset, numDetections, dataFieldSize, detectionFlags, samplingRate_Hz, txAngle_rad) in detections_7027:
|
|
376
|
+
if numDetections < 2:
|
|
377
|
+
continue
|
|
378
|
+
(firstBeam, _, firstRxAngle, *_) = self._read_detection(buffer, data_offset, dataFieldSize)
|
|
379
|
+
(lastBeam, _, lastRxAngle, *_) = self._read_detection(buffer, data_offset + (numDetections - 1) * dataFieldSize, dataFieldSize)
|
|
380
|
+
trend = (lastBeam - firstBeam) * (lastRxAngle - firstRxAngle)
|
|
381
|
+
votes += (trend > 0) - (trend < 0)
|
|
382
|
+
if votes < 0:
|
|
383
|
+
sys.stderr.write("Rx angles decrease with the beam number (positive to port): flipping their sign so beam_angle is positive to starboard\n")
|
|
384
|
+
return -1.0
|
|
385
|
+
return 1.0
|
|
386
|
+
|
|
387
|
+
def _make_pings(self, buffer, detections_7027, sound_velocity_7000, warn):
|
|
388
|
+
rx_angle_sign = self._rx_angle_sign(buffer, detections_7027)
|
|
389
|
+
|
|
390
|
+
for (epoch_microseconds, ping_key, fallback_sound_velocity, data_offset, numDetections, dataFieldSize, detectionFlags, samplingRate_Hz, txAngle_rad) in detections_7027:
|
|
391
|
+
# Sound velocity at the sonar from the 7000 of this ping (appendix F), else the last one seen before it
|
|
392
|
+
surface_sound_speed = sound_velocity_7000.get(ping_key, fallback_sound_velocity)
|
|
393
|
+
if surface_sound_speed is None:
|
|
394
|
+
warn("No 7000 sonar settings for a 7027 ping, surface sound speed set to NaN")
|
|
395
|
+
surface_sound_speed = math.nan
|
|
396
|
+
|
|
397
|
+
uncertainty_available = (detectionFlags & UNCERTAINTY_METHOD_MASK) != 0
|
|
398
|
+
|
|
399
|
+
for i in range(numDetections):
|
|
400
|
+
(beamDescriptor, detectionPoint, rxAngle_rad, flags, detectionQuality, uncertainty, signalStrength) = self._read_detection(buffer, data_offset + i * dataFieldSize, dataFieldSize)
|
|
401
|
+
|
|
402
|
+
# Multi-detect gives up to five detections per beam; priority 0 is the main one
|
|
403
|
+
priority = (flags >> DETECTION_PRIORITY_SHIFT) & DETECTION_PRIORITY_MASK
|
|
404
|
+
if priority and not self.include_extra_detections:
|
|
405
|
+
continue
|
|
406
|
+
|
|
407
|
+
# The detection point is a fractional sample number with the zero sample at the transmit time (appendix F)
|
|
408
|
+
twoWayTravelTime_sec = detectionPoint / samplingRate_Hz
|
|
409
|
+
|
|
410
|
+
# The uncertainty is an error normalised to the detection point, i.e. a fraction of the range. Expressed in %
|
|
411
|
+
# like the KMALL Ifremer quality factor. NaN when the sonar did not calculate it (RTH flags bits 0-3 = 0).
|
|
412
|
+
quality = 100.0 * uncertainty if uncertainty_available else math.nan
|
|
413
|
+
|
|
414
|
+
# Relative signal strength of the detection point, not calibrated
|
|
415
|
+
intensity = signalStrength
|
|
416
|
+
|
|
417
|
+
# Tx angle is the total applied steering, positive forward (2.2). The rx angle is relative to the receiver
|
|
418
|
+
# in the sonar reference frame and includes the steering applied for roll stabilisation (appendix F).
|
|
419
|
+
ping = Ping(epoch_microseconds,beamDescriptor,quality,intensity,surface_sound_speed,twoWayTravelTime_sec,txAngle_rad,rx_angle_sign * rxAngle_rad)
|
|
420
|
+
self.pings.append(ping)
|
|
421
|
+
|
|
422
|
+
def _make_positions(self, navigation_1015, positions_1003):
|
|
423
|
+
# 1015 is explicitly the position of the vessel reference point, so it is preferred over 1003. Log files are not
|
|
424
|
+
# guaranteed to be in chronological order (8.3), so samples are sorted.
|
|
425
|
+
navigation = largest_stream(navigation_1015)
|
|
426
|
+
if navigation:
|
|
427
|
+
samples = [(epoch_microseconds, latitude_rad, longitude_rad, height_m) for (epoch_microseconds, latitude_rad, longitude_rad, height_m, heading_rad) in navigation]
|
|
428
|
+
else:
|
|
429
|
+
samples = largest_stream(positions_1003)
|
|
430
|
+
|
|
431
|
+
for (epoch_microseconds, latitude_rad, longitude_rad, height_m) in sorted(samples):
|
|
432
|
+
position = Position(epoch_microseconds, latitude_rad, longitude_rad, height_m)
|
|
433
|
+
self.positions.append(position)
|
|
434
|
+
|
|
435
|
+
def _make_attitudes(self, attitude_1016, rph_1012, heading_1013, navigation_1015, warn):
|
|
436
|
+
# 1016 has complete, individually timed samples. Otherwise combine 1012 roll/pitch with the 1013 heading
|
|
437
|
+
# (or the 1015 navigation heading), interpolated to the roll/pitch times.
|
|
438
|
+
attitude = largest_stream(attitude_1016)
|
|
439
|
+
if attitude:
|
|
440
|
+
for (epoch_microseconds, roll_rad, pitch_rad, heading_rad) in sorted(attitude):
|
|
441
|
+
self.attitudes.append(Attitude(epoch_microseconds, roll_rad, pitch_rad, heading_rad))
|
|
442
|
+
return
|
|
443
|
+
|
|
444
|
+
rph = sorted(largest_stream(rph_1012))
|
|
445
|
+
if not rph:
|
|
446
|
+
return
|
|
447
|
+
|
|
448
|
+
headings = sorted(largest_stream(heading_1013))
|
|
449
|
+
if not headings:
|
|
450
|
+
headings = sorted((epoch_microseconds, heading_rad) for (epoch_microseconds, latitude_rad, longitude_rad, height_m, heading_rad) in largest_stream(navigation_1015))
|
|
451
|
+
if not headings:
|
|
452
|
+
warn("Roll and pitch (1012) without any heading (1013 or 1015): no attitudes")
|
|
453
|
+
return
|
|
454
|
+
|
|
455
|
+
heading_times = np.array([epoch_microseconds for (epoch_microseconds, heading_rad) in headings], dtype=np.float64)
|
|
456
|
+
heading_unwrapped = np.unwrap([heading_rad for (epoch_microseconds, heading_rad) in headings])
|
|
457
|
+
rph_times = np.array([epoch_microseconds for (epoch_microseconds, roll_rad, pitch_rad) in rph], dtype=np.float64)
|
|
458
|
+
rph_headings = np.mod(np.interp(rph_times, heading_times, heading_unwrapped), 2.0 * math.pi)
|
|
459
|
+
rph_headings[rph_headings >= 2.0 * math.pi] = 0.0 # np.mod can round a tiny negative value up to 2 pi
|
|
460
|
+
|
|
461
|
+
for (epoch_microseconds, roll_rad, pitch_rad), heading_rad in zip(rph, rph_headings.tolist()):
|
|
462
|
+
self.attitudes.append(Attitude(epoch_microseconds, roll_rad, pitch_rad, heading_rad))
|
mbes/SbetReader.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SbetReader.py - Reader for SBET (Smoothed Best Estimate of Trajectory) files.
|
|
3
|
+
|
|
4
|
+
An SBET file is a headerless binary file made of fixed-size records. Each
|
|
5
|
+
record is 17 little-endian float64 values (136 bytes):
|
|
6
|
+
|
|
7
|
+
idx field units
|
|
8
|
+
--- ----------- ------------------------------------
|
|
9
|
+
0 time s (GPS seconds of week)
|
|
10
|
+
1 lat rad
|
|
11
|
+
2 lon rad
|
|
12
|
+
3 alt m (ellipsoidal height)
|
|
13
|
+
4 x_vel m/s (wander frame)
|
|
14
|
+
5 y_vel m/s
|
|
15
|
+
6 z_vel m/s
|
|
16
|
+
7 roll rad
|
|
17
|
+
8 pitch rad
|
|
18
|
+
9 heading rad (platform heading)
|
|
19
|
+
10 wander rad (wander angle)
|
|
20
|
+
11 x_acc m/s^2 (body frame)
|
|
21
|
+
12 y_acc m/s^2
|
|
22
|
+
13 z_acc m/s^2
|
|
23
|
+
14 x_ang_rate rad/s (body frame)
|
|
24
|
+
15 y_ang_rate rad/s
|
|
25
|
+
16 z_ang_rate rad/s
|
|
26
|
+
|
|
27
|
+
Example
|
|
28
|
+
-------
|
|
29
|
+
>>> sbet = SbetReader("trajectory.out")
|
|
30
|
+
>>> arr = sbet.to_array() # (N, 17) float64 array
|
|
31
|
+
>>> rec = sbet.read(degrees=True) # structured array, angles in degrees
|
|
32
|
+
>>> rec["lat"], rec["lon"], rec["alt"]
|
|
33
|
+
>>> sbet["time"] # single column by name
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
from __future__ import annotations
|
|
37
|
+
|
|
38
|
+
import os
|
|
39
|
+
import warnings
|
|
40
|
+
from pathlib import Path
|
|
41
|
+
from typing import Iterator, Optional, Union
|
|
42
|
+
|
|
43
|
+
import numpy as np
|
|
44
|
+
import numpy.lib.recfunctions as rfn
|
|
45
|
+
|
|
46
|
+
PathLike = Union[str, os.PathLike]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class SbetReader:
|
|
50
|
+
"""Read a SBET file into NumPy arrays.
|
|
51
|
+
|
|
52
|
+
Parameters
|
|
53
|
+
----------
|
|
54
|
+
path : str or PathLike
|
|
55
|
+
Path to the SBET file (often ``sbet_*.out``).
|
|
56
|
+
memmap : bool, default False
|
|
57
|
+
If True, memory-map the file instead of loading it into RAM. Useful
|
|
58
|
+
for very large trajectories; data is read lazily from disk.
|
|
59
|
+
strict : bool, default True
|
|
60
|
+
If True, raise when the file size is not a multiple of the record
|
|
61
|
+
size. If False, warn and ignore the trailing partial record.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
FIELDS = (
|
|
65
|
+
"time", "lat", "lon", "alt",
|
|
66
|
+
"x_vel", "y_vel", "z_vel",
|
|
67
|
+
"roll", "pitch", "heading", "wander",
|
|
68
|
+
"x_acc", "y_acc", "z_acc",
|
|
69
|
+
"x_ang_rate", "y_ang_rate", "z_ang_rate",
|
|
70
|
+
)
|
|
71
|
+
ANGLE_FIELDS = ("lat", "lon", "roll", "pitch", "heading", "wander")
|
|
72
|
+
ANGULAR_RATE_FIELDS = ("x_ang_rate", "y_ang_rate", "z_ang_rate")
|
|
73
|
+
|
|
74
|
+
DTYPE = np.dtype([(name, "<f8") for name in FIELDS])
|
|
75
|
+
RECORD_SIZE = DTYPE.itemsize # 136 bytes
|
|
76
|
+
|
|
77
|
+
def __init__(self, path: PathLike, *, memmap: bool = False, strict: bool = True):
|
|
78
|
+
self.path = Path(path)
|
|
79
|
+
if not self.path.is_file():
|
|
80
|
+
raise FileNotFoundError(f"SBET file not found: {self.path}")
|
|
81
|
+
|
|
82
|
+
size = self.path.stat().st_size
|
|
83
|
+
self.n_records, remainder = divmod(size, self.RECORD_SIZE)
|
|
84
|
+
if remainder:
|
|
85
|
+
msg = (
|
|
86
|
+
f"{self.path.name}: size {size} bytes is not a multiple of "
|
|
87
|
+
f"{self.RECORD_SIZE}; {remainder} trailing bytes will be ignored."
|
|
88
|
+
)
|
|
89
|
+
if strict:
|
|
90
|
+
raise ValueError(msg)
|
|
91
|
+
warnings.warn(msg)
|
|
92
|
+
|
|
93
|
+
self._memmap = memmap
|
|
94
|
+
self._data: Optional[np.ndarray] = None
|
|
95
|
+
|
|
96
|
+
# ------------------------------------------------------------------ #
|
|
97
|
+
# Loading
|
|
98
|
+
# ------------------------------------------------------------------ #
|
|
99
|
+
@property
|
|
100
|
+
def data(self) -> np.ndarray:
|
|
101
|
+
"""Raw structured array (radians), loaded lazily on first access."""
|
|
102
|
+
if self._data is None:
|
|
103
|
+
self._data = self._load()
|
|
104
|
+
return self._data
|
|
105
|
+
|
|
106
|
+
def _load(self) -> np.ndarray:
|
|
107
|
+
if self.n_records == 0:
|
|
108
|
+
return np.empty(0, dtype=self.DTYPE)
|
|
109
|
+
if self._memmap:
|
|
110
|
+
return np.memmap(self.path, dtype=self.DTYPE, mode="r",
|
|
111
|
+
shape=(self.n_records,))
|
|
112
|
+
return np.fromfile(self.path, dtype=self.DTYPE, count=self.n_records)
|
|
113
|
+
|
|
114
|
+
# ------------------------------------------------------------------ #
|
|
115
|
+
# Public API
|
|
116
|
+
# ------------------------------------------------------------------ #
|
|
117
|
+
def read(
|
|
118
|
+
self,
|
|
119
|
+
*,
|
|
120
|
+
degrees: bool = False,
|
|
121
|
+
start_time: Optional[float] = None,
|
|
122
|
+
end_time: Optional[float] = None,
|
|
123
|
+
) -> np.ndarray:
|
|
124
|
+
"""Return the records as a structured array with named fields.
|
|
125
|
+
|
|
126
|
+
Parameters
|
|
127
|
+
----------
|
|
128
|
+
degrees : bool, default False
|
|
129
|
+
Convert lat, lon, roll, pitch, heading, wander (and angular
|
|
130
|
+
rates) from radians to degrees.
|
|
131
|
+
start_time, end_time : float, optional
|
|
132
|
+
Keep only records with ``start_time <= time <= end_time``.
|
|
133
|
+
"""
|
|
134
|
+
arr = self.data
|
|
135
|
+
|
|
136
|
+
if start_time is not None or end_time is not None:
|
|
137
|
+
t = arr["time"]
|
|
138
|
+
mask = np.ones(t.shape, dtype=bool)
|
|
139
|
+
if start_time is not None:
|
|
140
|
+
mask &= t >= start_time
|
|
141
|
+
if end_time is not None:
|
|
142
|
+
mask &= t <= end_time
|
|
143
|
+
arr = arr[mask] # boolean indexing always copies
|
|
144
|
+
|
|
145
|
+
if degrees:
|
|
146
|
+
arr = np.array(arr, copy=True) # never modify the cached/memmapped data
|
|
147
|
+
for name in self.ANGLE_FIELDS + self.ANGULAR_RATE_FIELDS:
|
|
148
|
+
arr[name] = np.degrees(arr[name])
|
|
149
|
+
|
|
150
|
+
return arr
|
|
151
|
+
|
|
152
|
+
def to_array(self, **kwargs) -> np.ndarray:
|
|
153
|
+
"""Return the records as a plain ``(N, 17)`` float64 array.
|
|
154
|
+
|
|
155
|
+
Columns follow the order in :attr:`FIELDS`. Accepts the same keyword
|
|
156
|
+
arguments as :meth:`read`.
|
|
157
|
+
"""
|
|
158
|
+
return rfn.structured_to_unstructured(self.read(**kwargs))
|
|
159
|
+
|
|
160
|
+
def iter_chunks(self, chunk_size: int = 100_000) -> Iterator[np.ndarray]:
|
|
161
|
+
"""Yield structured-array chunks without loading the whole file."""
|
|
162
|
+
if chunk_size <= 0:
|
|
163
|
+
raise ValueError("chunk_size must be positive")
|
|
164
|
+
with open(self.path, "rb") as f:
|
|
165
|
+
remaining = self.n_records
|
|
166
|
+
while remaining > 0:
|
|
167
|
+
count = min(chunk_size, remaining)
|
|
168
|
+
yield np.fromfile(f, dtype=self.DTYPE, count=count)
|
|
169
|
+
remaining -= count
|
|
170
|
+
|
|
171
|
+
def to_dataframe(self, **kwargs):
|
|
172
|
+
"""Return the records as a pandas DataFrame (requires pandas)."""
|
|
173
|
+
import pandas as pd
|
|
174
|
+
return pd.DataFrame(self.read(**kwargs))
|
|
175
|
+
|
|
176
|
+
# ------------------------------------------------------------------ #
|
|
177
|
+
# Convenience
|
|
178
|
+
# ------------------------------------------------------------------ #
|
|
179
|
+
@property
|
|
180
|
+
def time_span(self) -> tuple[float, float]:
|
|
181
|
+
"""(first_time, last_time) in seconds; (nan, nan) if empty."""
|
|
182
|
+
if self.n_records == 0:
|
|
183
|
+
return (float("nan"), float("nan"))
|
|
184
|
+
t = self.data["time"]
|
|
185
|
+
return float(t[0]), float(t[-1])
|
|
186
|
+
|
|
187
|
+
def __len__(self) -> int:
|
|
188
|
+
return self.n_records
|
|
189
|
+
|
|
190
|
+
def __getitem__(self, key):
|
|
191
|
+
"""``sbet["lat"]`` returns a column; ints/slices return records."""
|
|
192
|
+
if isinstance(key, str) and key not in self.FIELDS:
|
|
193
|
+
raise KeyError(f"Unknown field {key!r}. Valid fields: {self.FIELDS}")
|
|
194
|
+
return self.data[key]
|
|
195
|
+
|
|
196
|
+
def __repr__(self) -> str:
|
|
197
|
+
return f"{type(self).__name__}(path={str(self.path)!r}, n_records={self.n_records})"
|