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
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hydrography
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A library to process multibeam echosounder files
|
|
5
|
+
Author-email: Guillaume Morissette <glabmoris@gmail.com>
|
|
6
|
+
Classifier: Programming Language :: Python :: 3
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.8
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# Hydrography library
|
|
15
|
+
|
|
16
|
+
Library to process echosounder data files into hydrographic data
|
|
17
|
+
|
|
18
|
+
## Build
|
|
19
|
+
To build the package, run the `python -m build` command from the top level directory
|
|
20
|
+
|
|
21
|
+
## Testing
|
|
22
|
+
To test the package, run the following command from the top level directory:
|
|
23
|
+
`python3 -m unittest tests/test_core.py`
|
|
24
|
+
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
hydrography-0.1.0.dist-info/licenses/LICENSE,sha256=zdFXnlmYx67bBihtJgzowcYnjBNv4CCezKEZh1yJqxM,1080
|
|
2
|
+
mbes/AllReader.py,sha256=n3HTTaQIQ_O1eIPuXBRJ-XOMkfaYC3uRHgy-hD_c_0s,29957
|
|
3
|
+
mbes/Attitude.py,sha256=TYZhJ2IbxO4KTwxws5pSvD9XYbL2djjXDgEWUCvFAis,188
|
|
4
|
+
mbes/BaseReader.py,sha256=nc0taF1MHmyei7sIIz7q_ewHv_WO1ePqRR3YRvAVR70,198
|
|
5
|
+
mbes/Georeferencing.py,sha256=vXpyUf8VxIeb_enWf0bD_m0xFjIkOynL_jNEjFia9tg,2585
|
|
6
|
+
mbes/Interpolator.py,sha256=PSA4UEpKjjwjv8el9unrFvgF5Mvw3HreXJeqxPZLdFg,2323
|
|
7
|
+
mbes/KmallReader.py,sha256=TlGSgCp0y3Kh0ELQVTMmXNtbufzRVuSwyZTbYvkEH6w,12418
|
|
8
|
+
mbes/LeastSquares.py,sha256=VwL0avXDO4Fbp21KHP9vpdjGSXWman2OyfVs99j_kGw,754
|
|
9
|
+
mbes/MbesReader.py,sha256=tFHpj_VpGE3ao9jelWD67ppuUkEWLOdSYsVXmfRxNR8,3746
|
|
10
|
+
mbes/Ping.py,sha256=Zdyja2j6pRX7Di7aR8O_UoU56RyjDztXfAysvXVqJxg,240
|
|
11
|
+
mbes/Position.py,sha256=c1J8dRJn767u7cr74VIuZbyPKSV1afHDs4DeMPjHH0I,306
|
|
12
|
+
mbes/S7kReader.py,sha256=OaqqID_xjBVeB03g9UxD6ftWRbIJSsjnXmJvX42mzIM,26717
|
|
13
|
+
mbes/SbetReader.py,sha256=bet3mmYg_1e033939Qk0rTjVC6jrj-cjgugJ5KgTmtk,7150
|
|
14
|
+
mbes/SoundVelocityProfile.py,sha256=Ndx-F4-AWgkzOMCEVtE9-aPE5YhEiDwfopTj4SoJrkE,1908
|
|
15
|
+
mbes/Viewer.py,sha256=wjux2MH8vyN18EvEBUHVZ2bc_vm1mZbN2vsYkY8HLls,1314
|
|
16
|
+
mbes/XtfReader.py,sha256=F2u3OFZBEKDDNQT1W4fvoP3gncBfXKIx3y9puLJWY-E,31659
|
|
17
|
+
mbes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
mbes/core.py,sha256=eri373MB-twAlZjx5ZUUMw_azEEI2JwENvb1cNl80rs,303
|
|
19
|
+
hydrography-0.1.0.dist-info/METADATA,sha256=48XJEozz3ucD9q-3Y37f8YWCkQ5xXQx0nW99wR4VBuk,739
|
|
20
|
+
hydrography-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
21
|
+
hydrography-0.1.0.dist-info/top_level.txt,sha256=q6_RD9Gs461jeeiziwkupywwEddjOgwPOBR9elsJ9mU,5
|
|
22
|
+
hydrography-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2025 Guillaume Morissette, Ocean Riot
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mbes
|
mbes/AllReader.py
ADDED
|
@@ -0,0 +1,551 @@
|
|
|
1
|
+
import struct
|
|
2
|
+
import mmap
|
|
3
|
+
import sys
|
|
4
|
+
import math
|
|
5
|
+
import datetime
|
|
6
|
+
from types import SimpleNamespace
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from mbes.BaseReader import BaseReader
|
|
10
|
+
from mbes.Ping import Ping
|
|
11
|
+
from mbes.Attitude import Attitude
|
|
12
|
+
from mbes.Position import Position
|
|
13
|
+
|
|
14
|
+
# References are to the Kongsberg "EM datagram formats" instruction manual, 850-160692/W (January 2018).
|
|
15
|
+
# Every datagram is: number of bytes (4U, not counting itself), STX, type, EM model, date, time, counter,
|
|
16
|
+
# serial number, data, ETX and a checksum (2U, sum of the bytes between STX and ETX). Appendix E says the length
|
|
17
|
+
# is written in two bytes, but the introduction and every datagram table give 4U, which is what is used here.
|
|
18
|
+
|
|
19
|
+
STX = 0x02
|
|
20
|
+
ETX = 0x03
|
|
21
|
+
STX_BYTE = bytes([STX])
|
|
22
|
+
TRAILER_SIZE = 3 # ETX + checksum
|
|
23
|
+
MIN_NUM_BYTES = 16 + TRAILER_SIZE # header after the length field, ETX and checksum
|
|
24
|
+
|
|
25
|
+
# Datagram types
|
|
26
|
+
DGM_RAW_RANGE_78 = ord("N") # Raw range and angle 78: EM 122, EM 302, EM 710, ME70 BO, EM 2040, EM 2040C
|
|
27
|
+
DGM_RAW_RANGE_F = ord("f") # Raw range and beam angle (f): EM 120, EM 300, EM 1002, EM 2000, EM 3000, EM 3002
|
|
28
|
+
DGM_EXTRA_DETECTIONS = ord("l") # EM 2040 and EM 2040C with Slim Processing Unit
|
|
29
|
+
DGM_POSITION = ord("P")
|
|
30
|
+
DGM_ATTITUDE = ord("A")
|
|
31
|
+
DGM_NETWORK_ATTITUDE = ord("n")
|
|
32
|
+
DGM_HEADING = ord("H")
|
|
33
|
+
DGM_INSTALLATION_START = ord("I")
|
|
34
|
+
DGM_INSTALLATION = {ord("I"), ord("i"), ord("r")} # start, stop and remote information
|
|
35
|
+
DGM_DEPTH_ONLY = {ord("D"), ord("X"), ord("F")} # processed depths, or EM 3000 raw ranges (F) that need the depth datagram
|
|
36
|
+
|
|
37
|
+
PARSED_DATAGRAMS = {DGM_RAW_RANGE_78, DGM_RAW_RANGE_F, DGM_EXTRA_DETECTIONS, DGM_POSITION, DGM_ATTITUDE,
|
|
38
|
+
DGM_NETWORK_ATTITUDE, DGM_HEADING} | DGM_INSTALLATION
|
|
39
|
+
|
|
40
|
+
# Output datagrams in the manual that are not used (yet)
|
|
41
|
+
KNOWN_UNUSED_DATAGRAMS = {ord(c) for c in "DXKFSYkOChETGUWRJ301B"}
|
|
42
|
+
|
|
43
|
+
# Detection info (Table 29 note 3): bit 7 set = invalid detection (interpolated, estimated, rejected or no detection)
|
|
44
|
+
DETECTION_INVALID = 0x80
|
|
45
|
+
|
|
46
|
+
# Position system descriptor (Table 39 note 2): 10xx xxxx or 11xx xxxx = the position system is active
|
|
47
|
+
POSITION_SYSTEM_ACTIVE = 0x80
|
|
48
|
+
INVALID_4S = 0x7FFFFFFF # "Invalid data are always identified by the highest positive number allowed in a field"
|
|
49
|
+
|
|
50
|
+
# Sensor system descriptor (Table 34 note 2, Table 35 note 1)
|
|
51
|
+
SENSOR_NUMBER_SHIFT = 4
|
|
52
|
+
SENSOR_NUMBER_MASK = 0x03
|
|
53
|
+
SENSOR_HEADING_ACTIVE = 0x01 # 1 = heading from the sensor is active
|
|
54
|
+
SENSOR_ROLL_INACTIVE = 0x02 # 0 = roll from the sensor is active
|
|
55
|
+
SENSOR_PITCH_INACTIVE = 0x04 # 0 = pitch from the sensor is active
|
|
56
|
+
SENSOR_NOT_USED = -1 # network attitude: function is not used
|
|
57
|
+
|
|
58
|
+
EPOCH_ORDINAL = datetime.date(1970, 1, 1).toordinal()
|
|
59
|
+
|
|
60
|
+
def epoch_microseconds_from(date, time_ms):
|
|
61
|
+
"""Datagram date (year*10000 + month*100 + day) and time since midnight (ms) to microseconds since 1970-01-01.
|
|
62
|
+
Returns None if invalid."""
|
|
63
|
+
if time_ms > 86399999:
|
|
64
|
+
return None
|
|
65
|
+
try:
|
|
66
|
+
days = datetime.date(date // 10000, date // 100 % 100, date % 100).toordinal() - EPOCH_ORDINAL
|
|
67
|
+
except ValueError:
|
|
68
|
+
return None
|
|
69
|
+
return days * 86400000000 + time_ms * 1000
|
|
70
|
+
|
|
71
|
+
def byte_sum(buffer, start, end):
|
|
72
|
+
"""Datagram checksum: sum of the bytes between STX and ETX, as a 16 bit unsigned number."""
|
|
73
|
+
return int(np.frombuffer(buffer, dtype=np.uint8, count=end - start, offset=start).sum(dtype=np.uint64)) & 0xFFFF
|
|
74
|
+
|
|
75
|
+
def datagram_formats(byte_order):
|
|
76
|
+
"""Datagram layouts in the byte order of the file. EM 3002, EM 710, EM 302, EM 122, EM 2040, EM 2040C and ME70BO
|
|
77
|
+
are little endian; the manual recommends checking the byte order (output datagrams introduction)."""
|
|
78
|
+
f = lambda fmt: struct.Struct(byte_order + fmt)
|
|
79
|
+
return SimpleNamespace(
|
|
80
|
+
length = f("I"),
|
|
81
|
+
header = f("IBBHIIHH"), # number of bytes, STX, type, EM model, date, time since midnight in ms, counter, serial number
|
|
82
|
+
checksum = f("H"),
|
|
83
|
+
raw_range_78 = f("HHHHfI"), # Table 29
|
|
84
|
+
tx_sector_78 = f("hHfffHBBf"),
|
|
85
|
+
rx_beam_78 = f("hBBHBbfhbB"),
|
|
86
|
+
raw_range_f = f("HHIiHHHH"), # Table 28
|
|
87
|
+
tx_sector_f = f("hHIIIHBB"),
|
|
88
|
+
rx_beam_f = f("hHBbBBhH"),
|
|
89
|
+
extra_detections = f("HHHHHHfffHHHHHH"), # Table 25
|
|
90
|
+
extra_detection = f("9fhbBHHHH"), # first fields of a detection, the size per detection is in the datagram
|
|
91
|
+
position = f("iiHHHHBB"), # Table 39
|
|
92
|
+
attitude = f("H"), # Table 34
|
|
93
|
+
attitude_entry = f("HHhhhH"),
|
|
94
|
+
network_attitude = f("HbB"), # Table 35
|
|
95
|
+
network_attitude_entry = f("HhhhHB"),
|
|
96
|
+
heading = f("H"), # Table 38
|
|
97
|
+
heading_entry = f("HH"),
|
|
98
|
+
installation = f("H"), # Table 45, secondary system serial number
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
def height_from_sentence(sentence):
|
|
102
|
+
"""Antenna height above the ellipsoid from the position input datagram as received (Table 39 note 3, without '$'):
|
|
103
|
+
GGA altitude + geoidal separation (as Kongsberg computes the height datagram, Table 1 note 2), or the GGK and
|
|
104
|
+
PTNL,GGK ellipsoidal height (EHT). NaN for other formats, such as Simrad 90."""
|
|
105
|
+
fields = sentence.decode("ascii", "replace").strip().lstrip("$").split("*")[0].split(",")
|
|
106
|
+
try:
|
|
107
|
+
if fields[0].endswith("GGA"):
|
|
108
|
+
separation = float(fields[11]) if fields[11].strip() else 0.0
|
|
109
|
+
return float(fields[9]) + separation
|
|
110
|
+
if fields[0].endswith("GGK") or fields[0] == "PTNL":
|
|
111
|
+
for field in fields:
|
|
112
|
+
if field.startswith("EHT"):
|
|
113
|
+
return float(field[3:])
|
|
114
|
+
except (IndexError, ValueError):
|
|
115
|
+
pass
|
|
116
|
+
return math.nan
|
|
117
|
+
|
|
118
|
+
class AllReader(BaseReader):
|
|
119
|
+
def __init__(self):
|
|
120
|
+
super().__init__()
|
|
121
|
+
self.include_extra_detections = False #Extra detections datagram (water column targets etc.), not seabed
|
|
122
|
+
self.verify_checksums = True #Skip parsed datagrams whose checksum does not match
|
|
123
|
+
self.positions = []
|
|
124
|
+
self.attitudes = []
|
|
125
|
+
self.pings = []
|
|
126
|
+
self.installation = {} #parsed installation parameters, e.g. installation["S1X"]
|
|
127
|
+
self.byte_order = "<"
|
|
128
|
+
|
|
129
|
+
def _installation_xyz(self, prefix):
|
|
130
|
+
p = self.installation
|
|
131
|
+
return [float(p.get(prefix + axis, 0.0) or 0.0) for axis in "XYZ"]
|
|
132
|
+
|
|
133
|
+
def lever_arm(self):
|
|
134
|
+
"""Sonar position re. vessel reference point (VCS: x fwd, y stbd, z down), from the installation datagram.
|
|
135
|
+
Along-track from the TX transducer, across-track and vertical from the RX transducer (Mills cross), as in
|
|
136
|
+
KmallReader. Which of S0-S3 is which depends on the system transducer configuration (Table 45 notes 19 and 26).
|
|
137
|
+
For sonar heads (EM 3002, EM 2040C/P/M) this is the centre of the head face; the arrays are offset from it
|
|
138
|
+
(appendices B-D)."""
|
|
139
|
+
if not self.installation:
|
|
140
|
+
return np.zeros(3)
|
|
141
|
+
stc = self.installation.get("STC")
|
|
142
|
+
if stc is None:
|
|
143
|
+
# Older datagrams have no STC: sonar head systems use S1 for (the first) head, others S1 = TX, S2 = RX
|
|
144
|
+
heads = int(self.installation.get("emModel", 0)) in (2000, 3000, 3002, 3020, 2045)
|
|
145
|
+
stc = 1 if heads else 0
|
|
146
|
+
stc = int(float(stc))
|
|
147
|
+
if stc in (1, 2, 5, 6, 9):
|
|
148
|
+
return np.array(self._installation_xyz("S1"))
|
|
149
|
+
tx = self._installation_xyz("S0" if stc == 4 else "S1")
|
|
150
|
+
rx = self._installation_xyz("S2")
|
|
151
|
+
return np.array([tx[0], rx[1], rx[2]])
|
|
152
|
+
|
|
153
|
+
def position_lever_arm(self):
|
|
154
|
+
"""Active position system (APS) location re. vessel reference point (VCS), from the installation datagram.
|
|
155
|
+
Unlike KMALL #SPO positions, which are referred to the vessel reference point, .all positions are those of the
|
|
156
|
+
positioning system: the XYZ 88 beam data are given re "the active positioning system's reference point"."""
|
|
157
|
+
if not self.installation:
|
|
158
|
+
return np.zeros(3)
|
|
159
|
+
position_system = int(float(self.installation.get("APS", 0) or 0)) + 1 # APS is the position system number - 1
|
|
160
|
+
return np.array(self._installation_xyz(f"P{position_system}"))
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def _detect_byte_order(buffer):
|
|
164
|
+
"""Pick the byte order in which the first datagram has a consistent length, STX and ETX, and a plausible date."""
|
|
165
|
+
candidates = []
|
|
166
|
+
for byte_order in ("<", ">"):
|
|
167
|
+
if len(buffer) < 4 + MIN_NUM_BYTES:
|
|
168
|
+
break
|
|
169
|
+
(numBytes, stx, datagramType, emModel, date, time_ms, counter, serialNumber) = struct.unpack_from(byte_order + "IBBHIIHH", buffer, 0)
|
|
170
|
+
end = 4 + numBytes
|
|
171
|
+
if stx == STX and numBytes >= MIN_NUM_BYTES and end <= len(buffer) and buffer[end - TRAILER_SIZE] == ETX:
|
|
172
|
+
candidates.append((epoch_microseconds_from(date, time_ms) is not None, byte_order))
|
|
173
|
+
if not candidates:
|
|
174
|
+
raise ValueError("No valid datagram at the start of the file: not a Kongsberg .all file?")
|
|
175
|
+
return max(candidates)[1]
|
|
176
|
+
|
|
177
|
+
def read(self,filename):
|
|
178
|
+
self.positions = []
|
|
179
|
+
self.attitudes = []
|
|
180
|
+
self.pings = []
|
|
181
|
+
self.installation = {}
|
|
182
|
+
|
|
183
|
+
# Repeated problems are reported once, with a count, at the end
|
|
184
|
+
warnings = {}
|
|
185
|
+
def warn(message):
|
|
186
|
+
warnings[message] = warnings.get(message, 0) + 1
|
|
187
|
+
|
|
188
|
+
attitude_streams = {} # (datagram type, sensor number) -> [(epoch_us, roll_rad, pitch_rad, heading_rad, roll_pitch_active, heading_active)]
|
|
189
|
+
headings = [] # (epoch_us, heading_rad) from active heading datagrams
|
|
190
|
+
positions = [] # (epoch_us, latitude_rad, longitude_rad, height_m)
|
|
191
|
+
ping_datagrams = [] # located in the first pass, turned into Pings in the second
|
|
192
|
+
extra_detections = {} # (serial number, ping counter) -> [(data start, ETX offset)]
|
|
193
|
+
depth_only_count = 0
|
|
194
|
+
|
|
195
|
+
with open(filename, "rb") as file, mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as buffer:
|
|
196
|
+
file_size = len(buffer)
|
|
197
|
+
self.byte_order = self._detect_byte_order(buffer)
|
|
198
|
+
fmt = datagram_formats(self.byte_order)
|
|
199
|
+
|
|
200
|
+
def datagram_size(start):
|
|
201
|
+
"""Size of a structurally valid datagram (including the length field) at start, else None."""
|
|
202
|
+
if start + fmt.header.size > file_size:
|
|
203
|
+
return None
|
|
204
|
+
(numBytes,) = fmt.length.unpack_from(buffer, start)
|
|
205
|
+
end = start + 4 + numBytes
|
|
206
|
+
if numBytes < MIN_NUM_BYTES or end > file_size or buffer[start + 4] != STX or buffer[end - TRAILER_SIZE] != ETX:
|
|
207
|
+
return None
|
|
208
|
+
return 4 + numBytes
|
|
209
|
+
|
|
210
|
+
def checksum_ok(start, size):
|
|
211
|
+
(checksum,) = fmt.checksum.unpack_from(buffer, start + size - 2)
|
|
212
|
+
return byte_sum(buffer, start + 5, start + size - TRAILER_SIZE) == checksum
|
|
213
|
+
|
|
214
|
+
# Read file one datagram at the time
|
|
215
|
+
offset = 0
|
|
216
|
+
invalid_since = None # start of a corrupted region while searching for the next valid datagram
|
|
217
|
+
while offset + 4 + MIN_NUM_BYTES <= file_size:
|
|
218
|
+
datagram_start = offset
|
|
219
|
+
size = datagram_size(datagram_start)
|
|
220
|
+
|
|
221
|
+
if size is None:
|
|
222
|
+
# Resynchronise on the next STX that starts a datagram with a valid length, ETX and checksum
|
|
223
|
+
if invalid_since is None:
|
|
224
|
+
invalid_since = datagram_start
|
|
225
|
+
(numBytes,) = fmt.length.unpack_from(buffer, datagram_start)
|
|
226
|
+
if buffer[datagram_start + 4] == STX and datagram_start + 4 + numBytes > file_size:
|
|
227
|
+
sys.stderr.write(f"Datagram at offset {datagram_start} ({4 + numBytes} bytes) extends past the end of the file ({file_size - datagram_start} bytes left)\n")
|
|
228
|
+
else:
|
|
229
|
+
sys.stderr.write(f"Invalid datagram at offset {datagram_start}, searching for the next valid one\n")
|
|
230
|
+
candidate = datagram_start
|
|
231
|
+
while True:
|
|
232
|
+
next_stx = buffer.find(STX_BYTE, candidate + 5)
|
|
233
|
+
if next_stx < 0:
|
|
234
|
+
break
|
|
235
|
+
candidate = next_stx - 4
|
|
236
|
+
candidate_size = datagram_size(candidate)
|
|
237
|
+
if candidate_size and checksum_ok(candidate, candidate_size):
|
|
238
|
+
break
|
|
239
|
+
if next_stx < 0:
|
|
240
|
+
break
|
|
241
|
+
offset = candidate
|
|
242
|
+
continue
|
|
243
|
+
if invalid_since is not None:
|
|
244
|
+
sys.stderr.write(f"Resynchronised at offset {datagram_start}, skipped {datagram_start - invalid_since} bytes\n")
|
|
245
|
+
invalid_since = None
|
|
246
|
+
|
|
247
|
+
offset = datagram_start + size
|
|
248
|
+
|
|
249
|
+
# Read datagram header
|
|
250
|
+
(numBytes, stx, datagramType, emModel, date, time_ms, counter, serialNumber) = fmt.header.unpack_from(buffer, datagram_start)
|
|
251
|
+
data_start = datagram_start + fmt.header.size
|
|
252
|
+
etx_offset = datagram_start + size - TRAILER_SIZE
|
|
253
|
+
type_name = chr(datagramType) if 32 <= datagramType < 127 else f"0x{datagramType:02X}"
|
|
254
|
+
|
|
255
|
+
if datagramType in PARSED_DATAGRAMS:
|
|
256
|
+
if self.verify_checksums and not checksum_ok(datagram_start, size):
|
|
257
|
+
warn(f"Checksum mismatch, datagram {type_name} skipped")
|
|
258
|
+
continue
|
|
259
|
+
|
|
260
|
+
epoch_microseconds = epoch_microseconds_from(date, time_ms)
|
|
261
|
+
if epoch_microseconds is None and datagramType in PARSED_DATAGRAMS:
|
|
262
|
+
warn(f"Invalid date or time, datagram {type_name} skipped")
|
|
263
|
+
continue
|
|
264
|
+
|
|
265
|
+
if datagramType in (DGM_RAW_RANGE_78, DGM_RAW_RANGE_F):
|
|
266
|
+
#N Raw range and angle 78, or f Raw range and beam angle (older systems)
|
|
267
|
+
ping_datagrams.append((datagramType, data_start, etx_offset, epoch_microseconds, serialNumber, counter))
|
|
268
|
+
|
|
269
|
+
elif datagramType == DGM_EXTRA_DETECTIONS:
|
|
270
|
+
#l Extra detections. Its TX sector tilt is in the raw range and angle 78 datagram of the same ping
|
|
271
|
+
if self.include_extra_detections:
|
|
272
|
+
extra_detections.setdefault((serialNumber, counter), []).append((data_start, etx_offset))
|
|
273
|
+
|
|
274
|
+
elif datagramType in DGM_INSTALLATION:
|
|
275
|
+
#I, i, r Installation parameters: ASCII "XXX=value," fields after the secondary serial number
|
|
276
|
+
if self.installation and datagramType != DGM_INSTALLATION_START:
|
|
277
|
+
continue # keep the start datagram; the stop (i) or remote (r) one only if there is nothing else
|
|
278
|
+
(secondarySerialNumber,) = fmt.installation.unpack_from(buffer, data_start)
|
|
279
|
+
text = bytes(buffer[data_start + fmt.installation.size : etx_offset]).split(b"\0")[0].decode("ascii", "replace")
|
|
280
|
+
installation = {"emModel": emModel, "systemSerialNumber": serialNumber, "secondarySystemSerialNumber": secondarySerialNumber}
|
|
281
|
+
for field in text.split(","):
|
|
282
|
+
name, sep, value = field.partition("=")
|
|
283
|
+
if sep:
|
|
284
|
+
installation[name.strip()] = value.strip()
|
|
285
|
+
if datagramType == DGM_INSTALLATION_START or not self.installation:
|
|
286
|
+
self.installation = installation
|
|
287
|
+
|
|
288
|
+
elif datagramType == DGM_POSITION:
|
|
289
|
+
#P Position
|
|
290
|
+
if data_start + fmt.position.size > etx_offset:
|
|
291
|
+
warn("Datagram P too short, skipped")
|
|
292
|
+
continue
|
|
293
|
+
(latitude, longitude, fixQuality_cm, speedOverGround_cmPerSec, courseOverGround_cdeg, heading_cdeg, positionSystemDescriptor, numBytesInput) = fmt.position.unpack_from(buffer, data_start)
|
|
294
|
+
|
|
295
|
+
# Only the active position system, otherwise two positioning systems get interleaved
|
|
296
|
+
if not positionSystemDescriptor & POSITION_SYSTEM_ACTIVE:
|
|
297
|
+
continue
|
|
298
|
+
if latitude == INVALID_4S or longitude == INVALID_4S:
|
|
299
|
+
continue
|
|
300
|
+
latitude_deg = latitude / 20000000.0
|
|
301
|
+
longitude_deg = longitude / 10000000.0
|
|
302
|
+
if abs(latitude_deg) > 90.0 or abs(longitude_deg) > 180.0:
|
|
303
|
+
warn("Datagram P with an out of range position, skipped")
|
|
304
|
+
continue
|
|
305
|
+
|
|
306
|
+
# The P datagram has no height: take it from the position input datagram as received
|
|
307
|
+
input_start = data_start + fmt.position.size
|
|
308
|
+
height_m = height_from_sentence(bytes(buffer[input_start : min(input_start + numBytesInput, etx_offset)]))
|
|
309
|
+
positions.append((epoch_microseconds, math.radians(latitude_deg), math.radians(longitude_deg), height_m))
|
|
310
|
+
|
|
311
|
+
elif datagramType == DGM_ATTITUDE:
|
|
312
|
+
#A Attitude, valid at the transmit transducer. Entries are timed re the datagram time
|
|
313
|
+
(numEntries,) = fmt.attitude.unpack_from(buffer, data_start)
|
|
314
|
+
entries_start = data_start + fmt.attitude.size
|
|
315
|
+
descriptor_offset = entries_start + numEntries * fmt.attitude_entry.size
|
|
316
|
+
if descriptor_offset + 1 > etx_offset:
|
|
317
|
+
warn("Datagram A too short for its number of entries, skipped")
|
|
318
|
+
continue
|
|
319
|
+
sensorSystemDescriptor = buffer[descriptor_offset]
|
|
320
|
+
sensor = (sensorSystemDescriptor >> SENSOR_NUMBER_SHIFT) & SENSOR_NUMBER_MASK
|
|
321
|
+
roll_pitch_active = not sensorSystemDescriptor & (SENSOR_ROLL_INACTIVE | SENSOR_PITCH_INACTIVE)
|
|
322
|
+
heading_active = bool(sensorSystemDescriptor & SENSOR_HEADING_ACTIVE)
|
|
323
|
+
|
|
324
|
+
samples = attitude_streams.setdefault((DGM_ATTITUDE, sensor), [])
|
|
325
|
+
for i in range(numEntries):
|
|
326
|
+
(time_since_start_ms, sensorStatus, roll_cdeg, pitch_cdeg, heave_cm, heading_cdeg) = fmt.attitude_entry.unpack_from(buffer, entries_start + i * fmt.attitude_entry.size)
|
|
327
|
+
# Values outside the valid range are non-valid data (EM attitude input format)
|
|
328
|
+
if abs(roll_cdeg) > 18000 or abs(pitch_cdeg) > 18000 or heading_cdeg > 35999:
|
|
329
|
+
continue
|
|
330
|
+
samples.append((epoch_microseconds + time_since_start_ms * 1000, math.radians(roll_cdeg * 0.01), math.radians(pitch_cdeg * 0.01), math.radians(heading_cdeg * 0.01), roll_pitch_active, heading_active))
|
|
331
|
+
|
|
332
|
+
elif datagramType == DGM_NETWORK_ATTITUDE:
|
|
333
|
+
#n Network attitude velocity 110
|
|
334
|
+
(numEntries, sensorSystemDescriptor, spare) = fmt.network_attitude.unpack_from(buffer, data_start)
|
|
335
|
+
used = sensorSystemDescriptor != SENSOR_NOT_USED
|
|
336
|
+
sensor = (sensorSystemDescriptor >> SENSOR_NUMBER_SHIFT) & SENSOR_NUMBER_MASK
|
|
337
|
+
roll_pitch_active = used and not sensorSystemDescriptor & (SENSOR_ROLL_INACTIVE | SENSOR_PITCH_INACTIVE)
|
|
338
|
+
heading_active = used and bool(sensorSystemDescriptor & SENSOR_HEADING_ACTIVE)
|
|
339
|
+
|
|
340
|
+
samples = attitude_streams.setdefault((DGM_NETWORK_ATTITUDE, sensor), [])
|
|
341
|
+
entry_offset = data_start + fmt.network_attitude.size
|
|
342
|
+
for _ in range(numEntries):
|
|
343
|
+
if entry_offset + fmt.network_attitude_entry.size > etx_offset:
|
|
344
|
+
warn("Datagram n too short for its number of entries, truncated")
|
|
345
|
+
break
|
|
346
|
+
(time_since_start_ms, roll_cdeg, pitch_cdeg, heave_cm, heading_cdeg, numBytesInput) = fmt.network_attitude_entry.unpack_from(buffer, entry_offset)
|
|
347
|
+
# Each entry carries the attitude input datagram as received
|
|
348
|
+
entry_offset += fmt.network_attitude_entry.size + numBytesInput
|
|
349
|
+
if abs(roll_cdeg) > 18000 or abs(pitch_cdeg) > 18000 or heading_cdeg > 35999:
|
|
350
|
+
continue
|
|
351
|
+
samples.append((epoch_microseconds + time_since_start_ms * 1000, math.radians(roll_cdeg * 0.01), math.radians(pitch_cdeg * 0.01), math.radians(heading_cdeg * 0.01), roll_pitch_active, heading_active))
|
|
352
|
+
|
|
353
|
+
elif datagramType == DGM_HEADING:
|
|
354
|
+
#H Heading, for when the motion sensor does not supply the active heading
|
|
355
|
+
(numEntries,) = fmt.heading.unpack_from(buffer, data_start)
|
|
356
|
+
entries_start = data_start + fmt.heading.size
|
|
357
|
+
indicator_offset = entries_start + numEntries * fmt.heading_entry.size
|
|
358
|
+
if indicator_offset + 1 > etx_offset:
|
|
359
|
+
warn("Datagram H too short for its number of entries, skipped")
|
|
360
|
+
continue
|
|
361
|
+
if buffer[indicator_offset] == 0:
|
|
362
|
+
continue # heading indicator: 0 = inactive
|
|
363
|
+
for i in range(numEntries):
|
|
364
|
+
(time_since_start_ms, heading_cdeg) = fmt.heading_entry.unpack_from(buffer, entries_start + i * fmt.heading_entry.size)
|
|
365
|
+
if heading_cdeg <= 35999:
|
|
366
|
+
headings.append((epoch_microseconds + time_since_start_ms * 1000, math.radians(heading_cdeg * 0.01)))
|
|
367
|
+
|
|
368
|
+
elif datagramType in KNOWN_UNUSED_DATAGRAMS:
|
|
369
|
+
# Known datagrams that are not used (yet)
|
|
370
|
+
if datagramType in DGM_DEPTH_ONLY:
|
|
371
|
+
depth_only_count += 1
|
|
372
|
+
else:
|
|
373
|
+
warn(f"Unknown datagram {type_name}")
|
|
374
|
+
|
|
375
|
+
if invalid_since is not None:
|
|
376
|
+
sys.stderr.write(f"No valid datagram found after offset {invalid_since}, stopping\n")
|
|
377
|
+
elif offset < file_size:
|
|
378
|
+
sys.stderr.write(f"Truncated datagram at offset {offset} ({file_size - offset} bytes left), stopping\n")
|
|
379
|
+
|
|
380
|
+
# Datagrams are read from the mapped file, so this happens before it is closed
|
|
381
|
+
self._make_pings(buffer, fmt, ping_datagrams, extra_detections, warn)
|
|
382
|
+
|
|
383
|
+
if not ping_datagrams and depth_only_count:
|
|
384
|
+
warn("No raw range and angle datagrams (N or f), only processed depths or EM 3000 F datagrams, which are not read: no pings")
|
|
385
|
+
|
|
386
|
+
# Datagram timestamps are not strictly sequential, motion data for example arrives grouped (appendix E)
|
|
387
|
+
for (epoch_microseconds, latitude_rad, longitude_rad, height_m) in sorted(positions):
|
|
388
|
+
position = Position(epoch_microseconds, latitude_rad, longitude_rad, height_m)
|
|
389
|
+
self.positions.append(position)
|
|
390
|
+
|
|
391
|
+
self._make_attitudes(attitude_streams, headings, warn)
|
|
392
|
+
|
|
393
|
+
for message, count in warnings.items():
|
|
394
|
+
sys.stderr.write(f"{message}" + (f" ({count}x)" if count > 1 else "") + "\n")
|
|
395
|
+
|
|
396
|
+
def _make_pings(self, buffer, fmt, ping_datagrams, extra_detections, warn):
|
|
397
|
+
for (datagramType, data_start, etx_offset, epoch_microseconds, serialNumber, pingCounter) in ping_datagrams:
|
|
398
|
+
if datagramType == DGM_RAW_RANGE_F:
|
|
399
|
+
self._pings_from_raw_range_f(buffer, fmt, data_start, etx_offset, epoch_microseconds, warn)
|
|
400
|
+
continue
|
|
401
|
+
|
|
402
|
+
sectors = self._pings_from_raw_range_78(buffer, fmt, data_start, etx_offset, epoch_microseconds, warn)
|
|
403
|
+
if sectors is None:
|
|
404
|
+
continue
|
|
405
|
+
|
|
406
|
+
# Extra detections follow the soundings of their ping, with sounding indices after them like in KMALL
|
|
407
|
+
(tilts_rad, numRxBeams) = sectors
|
|
408
|
+
for (extra_start, extra_etx) in extra_detections.pop((serialNumber, pingCounter), []):
|
|
409
|
+
self._pings_from_extra_detections(buffer, fmt, extra_start, extra_etx, epoch_microseconds, tilts_rad, numRxBeams, warn)
|
|
410
|
+
|
|
411
|
+
if extra_detections:
|
|
412
|
+
warn("Extra detections without a raw range and angle 78 datagram for their ping, skipped")
|
|
413
|
+
|
|
414
|
+
def _pings_from_raw_range_78(self, buffer, fmt, data_start, etx_offset, epoch_microseconds, warn):
|
|
415
|
+
"""Raw range and angle 78 (Table 29). Returns the TX sector tilts and the number of RX beams, None if invalid."""
|
|
416
|
+
(soundSpeed_dmPerSec, numTxSectors, numRxBeams, numValidDetections, samplingFrequency_Hz, dScale) = fmt.raw_range_78.unpack_from(buffer, data_start)
|
|
417
|
+
tx_start = data_start + fmt.raw_range_78.size
|
|
418
|
+
rx_start = tx_start + numTxSectors * fmt.tx_sector_78.size
|
|
419
|
+
if rx_start + numRxBeams * fmt.rx_beam_78.size > etx_offset:
|
|
420
|
+
warn("Datagram N too short for its number of sectors and beams, skipped")
|
|
421
|
+
return None
|
|
422
|
+
|
|
423
|
+
# TX sectors. The RX beams refer to a sector by its position in this loop: for the EM 2040 the
|
|
424
|
+
# "Transmit sector number / TX array index" field here is the TX array index, not the sector (appendix A)
|
|
425
|
+
tilts_rad = []
|
|
426
|
+
for i in range(numTxSectors):
|
|
427
|
+
(tiltAngle_cdeg, focusRange_dm, signalLength_sec, sectorTransmitDelay_sec, centreFrequency_Hz, meanAbsorptionCoeff_cdBPerkm, signalWaveformIdentifier, txArrayIndex, signalBandwidth_Hz) = fmt.tx_sector_78.unpack_from(buffer, tx_start + i * fmt.tx_sector_78.size)
|
|
428
|
+
# Tilt angle re TX array, positive forwards (Table 27 note 1)
|
|
429
|
+
tilts_rad.append(math.radians(tiltAngle_cdeg * 0.01))
|
|
430
|
+
|
|
431
|
+
surface_sound_speed = soundSpeed_dmPerSec * 0.1
|
|
432
|
+
|
|
433
|
+
# RX beams. All beams are included; the beam number is their index (output datagrams introduction)
|
|
434
|
+
for beam in range(numRxBeams):
|
|
435
|
+
(beamPointingAngle_cdeg, txSectorNumber, detectionInfo, detectionWindowLength, qualityFactor, dCorr, twoWayTravelTime_sec, reflectivity_ddB, realTimeCleaningInfo, spare) = fmt.rx_beam_78.unpack_from(buffer, rx_start + beam * fmt.rx_beam_78.size)
|
|
436
|
+
|
|
437
|
+
# Bit 7 set = invalid: the range is interpolated, estimated, a rejected candidate or missing, not measured
|
|
438
|
+
if detectionInfo & DETECTION_INVALID:
|
|
439
|
+
continue
|
|
440
|
+
if txSectorNumber >= numTxSectors:
|
|
441
|
+
warn("Datagram N beam with a transmit sector number beyond its sectors, skipped")
|
|
442
|
+
continue
|
|
443
|
+
|
|
444
|
+
# Quality factor = 2500*sd/dr (note 2), so the standard deviation in % of the range, like the KMALL quality factor in %
|
|
445
|
+
quality = qualityFactor / 25.0 if qualityFactor <= 254 else math.nan
|
|
446
|
+
intensity = reflectivity_ddB * 0.1 # BS in dB
|
|
447
|
+
|
|
448
|
+
# The beam pointing angle re RX array is positive to PORT (Table 27 note 1). Ping.beam_angle follows the VCS
|
|
449
|
+
# (y = starboard), so flip the sign here, as in KmallReader.
|
|
450
|
+
ping = Ping(epoch_microseconds,beam,quality,intensity,surface_sound_speed,twoWayTravelTime_sec,tilts_rad[txSectorNumber],-math.radians(beamPointingAngle_cdeg * 0.01))
|
|
451
|
+
self.pings.append(ping)
|
|
452
|
+
|
|
453
|
+
return (tilts_rad, numRxBeams)
|
|
454
|
+
|
|
455
|
+
def _pings_from_raw_range_f(self, buffer, fmt, data_start, etx_offset, epoch_microseconds, warn):
|
|
456
|
+
"""Raw range and beam angle (f) of older systems (Table 28). All beams in it are valid."""
|
|
457
|
+
(numTxSectors, numBeams, samplingFrequency_cHz, rovDepth_cm, soundSpeed_dmPerSec, maxNumBeams, spare1, spare2) = fmt.raw_range_f.unpack_from(buffer, data_start)
|
|
458
|
+
tx_start = data_start + fmt.raw_range_f.size
|
|
459
|
+
rx_start = tx_start + numTxSectors * fmt.tx_sector_f.size
|
|
460
|
+
if rx_start + numBeams * fmt.rx_beam_f.size > etx_offset:
|
|
461
|
+
warn("Datagram f too short for its number of sectors and beams, skipped")
|
|
462
|
+
return
|
|
463
|
+
if samplingFrequency_cHz == 0:
|
|
464
|
+
warn("Datagram f without a sampling frequency, skipped")
|
|
465
|
+
return
|
|
466
|
+
|
|
467
|
+
tilts_rad = {}
|
|
468
|
+
for i in range(numTxSectors):
|
|
469
|
+
(tiltAngle_cdeg, focusRange_dm, signalLength_us, transmitTimeOffset_us, centreFrequency_Hz, bandwidth_10Hz, signalWaveformIdentifier, txSectorNumber) = fmt.tx_sector_f.unpack_from(buffer, tx_start + i * fmt.tx_sector_f.size)
|
|
470
|
+
tilts_rad[txSectorNumber] = math.radians(tiltAngle_cdeg * 0.01)
|
|
471
|
+
|
|
472
|
+
surface_sound_speed = soundSpeed_dmPerSec * 0.1
|
|
473
|
+
|
|
474
|
+
for i in range(numBeams):
|
|
475
|
+
(beamPointingAngle_cdeg, range_quarterSamples, txSectorNumber, reflectivity_hdB, qualityFactor, detectionWindowLength, beamNumber, spare) = fmt.rx_beam_f.unpack_from(buffer, rx_start + i * fmt.rx_beam_f.size)
|
|
476
|
+
if txSectorNumber not in tilts_rad:
|
|
477
|
+
warn("Datagram f beam with an unknown transmit sector number, skipped")
|
|
478
|
+
continue
|
|
479
|
+
|
|
480
|
+
# Two way travel time = R / (4 * F / 100), with F the sampling frequency in 0.01 Hz (note 2)
|
|
481
|
+
twoWayTravelTime_sec = range_quarterSamples / (4.0 * samplingFrequency_cHz / 100.0)
|
|
482
|
+
|
|
483
|
+
# This quality factor is not defined as a standard deviation, so it is not comparable
|
|
484
|
+
quality = math.nan
|
|
485
|
+
intensity = reflectivity_hdB * 0.5 # BS in dB
|
|
486
|
+
|
|
487
|
+
ping = Ping(epoch_microseconds,beamNumber,quality,intensity,surface_sound_speed,twoWayTravelTime_sec,tilts_rad[txSectorNumber],-math.radians(beamPointingAngle_cdeg * 0.01))
|
|
488
|
+
self.pings.append(ping)
|
|
489
|
+
|
|
490
|
+
def _pings_from_extra_detections(self, buffer, fmt, data_start, etx_offset, epoch_microseconds, tilts_rad, numRxBeams, warn):
|
|
491
|
+
"""Extra detections (Table 25), timed and tilted like the raw range and angle 78 datagram of their ping."""
|
|
492
|
+
(datagramCounter, datagramVersion, swathCounter, swathIndex, heading_cdeg, soundVelocity_dmPerSec, depthOfReferencePoint_m, wcSampleRate, siSampleRate, rxTransducerIndex, numExtraDetections, numDetectionClasses, numBytesPerClass, numAlarmFlags, numBytesPerDetection) = fmt.extra_detections.unpack_from(buffer, data_start)
|
|
493
|
+
|
|
494
|
+
# Step by the sizes given in the datagram: Rev. T (June 2015) added data to the detections
|
|
495
|
+
if numBytesPerDetection < fmt.extra_detection.size:
|
|
496
|
+
warn(f"Datagram l with {numBytesPerDetection} bytes per detection, skipped")
|
|
497
|
+
return
|
|
498
|
+
detections_start = data_start + fmt.extra_detections.size + numDetectionClasses * numBytesPerClass
|
|
499
|
+
if detections_start + numExtraDetections * numBytesPerDetection > etx_offset:
|
|
500
|
+
warn("Datagram l too short for its number of detections, skipped")
|
|
501
|
+
return
|
|
502
|
+
|
|
503
|
+
surface_sound_speed = soundVelocity_dmPerSec * 0.1
|
|
504
|
+
|
|
505
|
+
for i in range(numExtraDetections):
|
|
506
|
+
(depth_m, across_m, along_m, deltaLatitude_deg, deltaLongitude_deg, beamPointingAngle_deg, appliedPointingAngleCorrection_deg, twoWayTravelTime_sec, appliedTwoWayTravelTimeCorrection_sec, bs_ddB, beamIncidenceAngleAdjustment_ddeg, detectionInfo, spare, txSectorNumber, detectionWindowLength, qualityFactorOld) = fmt.extra_detection.unpack_from(buffer, detections_start + i * numBytesPerDetection)
|
|
507
|
+
if detectionInfo & DETECTION_INVALID:
|
|
508
|
+
continue
|
|
509
|
+
# Same TX sector index as in the raw range and angle 78 datagram (note 1)
|
|
510
|
+
if txSectorNumber >= len(tilts_rad):
|
|
511
|
+
warn("Datagram l detection with a transmit sector number beyond the ping's sectors, skipped")
|
|
512
|
+
continue
|
|
513
|
+
|
|
514
|
+
quality = qualityFactorOld / 25.0 # assumed scaled like the 78 quality factor
|
|
515
|
+
intensity = bs_ddB * 0.1 # BS in dB
|
|
516
|
+
|
|
517
|
+
ping = Ping(epoch_microseconds,numRxBeams + i,quality,intensity,surface_sound_speed,twoWayTravelTime_sec,tilts_rad[txSectorNumber],-math.radians(beamPointingAngle_deg))
|
|
518
|
+
self.pings.append(ping)
|
|
519
|
+
|
|
520
|
+
def _make_attitudes(self, attitude_streams, headings, warn):
|
|
521
|
+
# Like KmallReader, only use the active attitude sensor, otherwise two sensors get interleaved. The sensor
|
|
522
|
+
# system descriptor of each datagram tells whether its roll and pitch are used in real time.
|
|
523
|
+
samples = [s for (datagramType, sensor), stream in attitude_streams.items() if datagramType == DGM_ATTITUDE for s in stream if s[4]]
|
|
524
|
+
if not samples:
|
|
525
|
+
samples = [s for (datagramType, sensor), stream in attitude_streams.items() if datagramType == DGM_NETWORK_ATTITUDE for s in stream if s[4]]
|
|
526
|
+
if not samples and attitude_streams:
|
|
527
|
+
samples = max(attitude_streams.values(), key=len)
|
|
528
|
+
if samples:
|
|
529
|
+
warn("No attitude datagram marked as the active roll/pitch sensor: using the sensor with the most samples")
|
|
530
|
+
if not samples:
|
|
531
|
+
return
|
|
532
|
+
samples.sort()
|
|
533
|
+
|
|
534
|
+
# The heading from the attitude sensor may not be the active one: then use the active heading, from another
|
|
535
|
+
# attitude sensor or the heading datagram, interpolated to the attitude times
|
|
536
|
+
heading_samples = sorted(headings + [(s[0], s[3]) for stream in attitude_streams.values() for s in stream if s[5]])
|
|
537
|
+
need_heading = [i for i, s in enumerate(samples) if not s[5]]
|
|
538
|
+
interpolated = {}
|
|
539
|
+
if need_heading and heading_samples:
|
|
540
|
+
heading_times = np.array([t for (t, h) in heading_samples], dtype=np.float64)
|
|
541
|
+
heading_unwrapped = np.unwrap([h for (t, h) in heading_samples])
|
|
542
|
+
times = np.array([samples[i][0] for i in need_heading], dtype=np.float64)
|
|
543
|
+
values = np.mod(np.interp(times, heading_times, heading_unwrapped), 2.0 * math.pi)
|
|
544
|
+
values[values >= 2.0 * math.pi] = 0.0 # np.mod can round a tiny negative value up to 2 pi
|
|
545
|
+
interpolated = dict(zip(need_heading, values.tolist()))
|
|
546
|
+
elif need_heading:
|
|
547
|
+
warn("The attitude sensor's heading is not marked active and there is no other active heading: using it anyway")
|
|
548
|
+
|
|
549
|
+
for i, (epoch_microseconds, roll_rad, pitch_rad, heading_rad, roll_pitch_active, heading_active) in enumerate(samples):
|
|
550
|
+
attitude = Attitude(epoch_microseconds, roll_rad, pitch_rad, interpolated.get(i, heading_rad))
|
|
551
|
+
self.attitudes.append(attitude)
|
mbes/Attitude.py
ADDED