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.
@@ -0,0 +1,72 @@
1
+ import math
2
+ import pandas as pd
3
+ import re
4
+ from datetime import datetime
5
+
6
+ class SoundVelocityProfileSection:
7
+ def __init__(self,timestamp,longitude,latitude):
8
+ self.longitude = longitude
9
+ self.latitude = latitude
10
+ self.timestamp = timestamp
11
+ self.values = pd.DataFrame(columns=["depth","sound_speed"])
12
+
13
+ def get_values(self):
14
+ return self.values
15
+
16
+ def get_position(self):
17
+ return (self.longitude,self.latitude)
18
+
19
+ def get_timestamp(self):
20
+ return self.timestamp
21
+
22
+ def add(self,depth,sound_speed):
23
+ self.values.loc[len(self.values)] = [depth,sound_speed]
24
+
25
+ class SoundVelocityProfile:
26
+ def __init__(self):
27
+ self.sections = []
28
+ self.name = ""
29
+
30
+ def dms2dd(self,dms_string):
31
+ degrees,minutes,seconds = re.split("[:]",dms_string)
32
+ dd = abs(float(degrees)) + (float(minutes)/60.0) + (float(seconds)/(60.0*60.0))
33
+ return dd if float(degrees) > 0 else -1 * dd
34
+
35
+ def read(self,filename):
36
+ with open(filename) as f:
37
+ line_count = 0
38
+
39
+ for line in f:
40
+ if line_count == 0:
41
+ if not line.startswith("[SVP_VERSION_2]"):
42
+ raise Exception("Unsupported SVP file version: only version 2 is supported")
43
+ elif line_count == 1:
44
+ name=line
45
+ else:
46
+ tokens = line.split()
47
+
48
+ if tokens[0]=="Section":
49
+ timestamp = datetime.strptime(tokens[1] + " " + tokens[2],"%Y-%j %H:%M:%S")
50
+ try:
51
+ latitude = self.dms2dd(tokens[3])
52
+ except Exception as e:
53
+ print(f"{e}")
54
+ latitude = math.nan
55
+ try:
56
+ longitude = self.dms2dd(tokens[4])
57
+ except Exception as e:
58
+ longitude = math.nan
59
+
60
+ #new section
61
+ new_section = SoundVelocityProfileSection(timestamp,longitude,latitude)
62
+ self.sections.append(new_section)
63
+ else:
64
+ depth = float(tokens[0])
65
+ sound_speed = float(tokens[1])
66
+
67
+ self.sections[len(self.sections)-1].add(depth,sound_speed)
68
+
69
+ line_count = line_count + 1
70
+ def get_sections(self):
71
+ return self.sections
72
+
mbes/Viewer.py ADDED
@@ -0,0 +1,48 @@
1
+ import open3d as o3d
2
+ import sys
3
+ import numpy as np
4
+
5
+ from mbes.MbesReader import MbesReader
6
+
7
+ print(o3d.__version__)
8
+
9
+ if len(sys.argv) != 2:
10
+ sys.exit("Usage: Viewer.py xyz_file\n")
11
+
12
+ # Read file data
13
+ filename = sys.argv[1]
14
+
15
+ sys.stderr.write(f"[+] Reading MBES data from {filename}\n")
16
+ r = MbesReader()
17
+ pings = r.read(filename)
18
+
19
+ if len(pings) == 0:
20
+ sys.exit(f"*** Error: Could not read pings from {filename}.\n")
21
+
22
+ # Display point cloud
23
+ points = np.vstack(pings).astype(np.float64)
24
+
25
+ origin = np.floor(points[0, :3])
26
+ #origin[2] = 0.0 # Z is already small; leaving it unshifted keeps depths readable
27
+ points[:, :3] -= origin
28
+
29
+ point_cloud = o3d.geometry.PointCloud()
30
+ point_cloud.points = o3d.utility.Vector3dVector(points)
31
+
32
+ if point_cloud.is_empty():
33
+ sys.exit(f"*** Error: no points could be read from {filename}.\nMake sure each line contains space-separated 'x y z' values.")
34
+
35
+ # Create viz window
36
+ vis = o3d.visualization.Visualizer()
37
+ if not vis.create_window(window_name=f"MBES - {filename}", width=1280, height=800): sys.exit("Error: could not create a window (is a display available?)")
38
+
39
+ opt = vis.get_render_option()
40
+ opt.background_color = [0.05, 0.05, 0.05] # Dark background makes the point cloud pop
41
+ opt.point_size = 2
42
+
43
+ # Add XYZ point cloud
44
+ vis.add_geometry(point_cloud)
45
+
46
+ vis.run()
47
+ vis.destroy_window()
48
+
mbes/XtfReader.py ADDED
@@ -0,0 +1,532 @@
1
+ import struct
2
+ import mmap
3
+ import sys
4
+ import math
5
+ import datetime
6
+ import statistics
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 Triton Imaging "eXtended Triton Format (XTF) Rev. 41" (September 2016). XTF values are little
15
+ # endian (2.5) with 1 byte packing (2.2.1). Reson 7125 bathymetry is stored as a raw 7027 record (appendix 1), whose
16
+ # layout is from the Teledyne RESON "7k Data Format, Volume I" version 2.41, which appendix 1 refers to.
17
+ #
18
+ # Two misprints in the XTF document: Table E gives HeaderType at offset 1 and SubChannelNumber at 2, and Table H gives
19
+ # ReservedSpace2 at 245. Every packet starts with the same 14 bytes (magic 0, type 2, subchannel 3, size 10), and the
20
+ # stated 64 and 256 byte totals only work out with ReservedSpace2 at 250, so those are used here.
21
+
22
+ FILE_FORMAT = 123 # Table C: FileFormat
23
+ MAGIC_NUMBER = 0xFACE
24
+ MAGIC_BYTES = struct.pack("<H", MAGIC_NUMBER)
25
+ FILE_HEADER_BLOCK = 1024 # the file header grows in 1024 byte increments for more than six channels (2.4.1)
26
+ NAV_UNITS_LATLONG = 3 # Table C: NavUnits, 0 = meters (projected), 3 = lat/long
27
+ TYPE_BATHYMETRY = 3 # Table D: TypeOfChannel
28
+
29
+ FILE_HEADER = struct.Struct("<BB8s8s16sH64s64sHHHBBHBBHf12s10si12f") # Table C up to the CHANINFO array, 256 bytes
30
+ CHANINFO = struct.Struct("<BBHHHI16s11fHB53s") # Table D, 128 bytes
31
+ PACKET_HEADER = struct.Struct("<HBBHHHI") # common start of all packets: magic, type, subchannel, channels, reserved, size
32
+ PING_HEADER = struct.Struct("<HBBHHHIHBBBBBBHIIffI21fddHHBBBBffddHHHH10fIfIBBBBhhBIB6s") # Table H, 256 bytes
33
+ ATTITUDE = struct.Struct("<HBBHHHIIIIIffffIfHBBBBBHB") # Table E, 64 bytes
34
+ NAVIGATION = struct.Struct("<HB7sIHBBBBBIIIdddB6s") # 3.1.18, 64 bytes
35
+ POS_RAW_NAVIGATION = struct.Struct("<HBBHHHIHBBBBBHdddffffB") # Table P, 64 bytes
36
+ Q_MULTIBEAM_ENTRY = struct.Struct("<ididdddffff") # Table S (XTFQPSMBEENTRY), 64 bytes
37
+
38
+ # Reson 7k structures (7k DFD tables 5, 66 and 67)
39
+ DRF_7K = struct.Struct("<HHIIIIHHfBBHIIHHIHHIII") # Data Record Frame, 64 bytes
40
+ SYNC_PATTERN_7K = 0x0000FFFF
41
+ RAW_DETECTION_7027 = struct.Struct("<QIHIIBIff16I")
42
+ DETECTION_7027 = struct.Struct("<HffIIff") # may be shorter (older) or longer (newer): step by the RTH data field size
43
+ DETECTION_7027_MIN = struct.calcsize("<Hff") # beam descriptor, detection point and rx angle are required
44
+ RECORD_7006 = 7006
45
+ RECORD_7027 = 7027
46
+ UNCERTAINTY_METHOD_MASK = 0x0F # 7027 RTH flags bits 0-3, 0 = uncertainty not calculated
47
+ DETECTION_PRIORITY_SHIFT = 9 # 7027 detection flags bits 9-12, multi-detect priority, 0 = highest
48
+ DETECTION_PRIORITY_MASK = 0x0F
49
+
50
+ # Header types (Table H and sections 3.1.13-3.1.19)
51
+ HEADER_SONAR = 0
52
+ HEADER_BATHY = 2
53
+ HEADER_ATTITUDE = 3
54
+ HEADER_Q_SINGLEBEAM = 26
55
+ HEADER_Q_MULTITX = 27
56
+ HEADER_Q_MULTIBEAM = 28
57
+ HEADER_NAVIGATION = 42
58
+ HEADER_7125 = 61
59
+ HEADER_POS_RAW_NAVIGATION = 107
60
+
61
+ HEADER_NAMES = {0: "sonar", 1: "notes", 2: "bathy", 3: "attitude", 4: "forward look", 5: "ELAC", 6: "raw serial",
62
+ 7: "embedded header", 8: "hidden sonar", 9: "Seaview processed bathy", 10: "Seaview depths",
63
+ 11: "high speed sensor", 12: "echo strength", 13: "georec", 14: "Klein raw bathy",
64
+ 15: "high speed sensor 2", 16: "ELAC XSE", 17: "bathy XYZA", 18: "K5000 bathy IQ", 19: "bathy snippet",
65
+ 20: "GPS", 21: "GPS statistics", 22: "single beam", 23: "gyro", 24: "Trackpoint", 25: "multibeam",
66
+ 26: "QPS single beam", 27: "QPS multi-transducer", 28: "QPS multibeam", 42: "navigation", 50: "time",
67
+ 60: "Benthos CAATI SARA", 61: "Reson 7125", 62: "Reson 7125 snippet", 65: "QINSy R2Sonic bathy",
68
+ 66: "QINSy R2Sonic FTS", 68: "R2Sonic bathy", 69: "R2Sonic FTS", 70: "CODA Echoscope data",
69
+ 71: "CODA Echoscope config", 72: "CODA Echoscope image", 73: "Edgetech 4600", 75: "Klein bathy",
70
+ 78: "Reson 7018 water column", 79: "R2Sonic water column", 84: "gyro (source time)",
71
+ 100: "Reson position", 102: "bathy proc", 103: "attitude proc", 104: "single beam proc",
72
+ 105: "aux proc", 106: "Klein 3000 data page", 107: "POS raw navigation", 108: "Klein V4 data page",
73
+ 199: "custom", 200: "user defined"}
74
+ KNOWN_HEADER_TYPES = set(HEADER_NAMES) | {67, 76}
75
+
76
+ # Packets that start with an XTFPINGHEADER/XTFBATHHEADER (Table H, sections 3.1.11-3.1.16, appendices 1-3).
77
+ # The ping header navigation of bathymetry packets is preferred: in a file with a towed sidescan as well,
78
+ # sonar ping headers may carry the towfish position.
79
+ SONAR_PING_HEADERS = {0, 4, 8, 12, 60}
80
+ BATHY_PING_HEADERS = {2, 19, 27, 28, 61, 62, 65, 66, 68, 69, 75, 78, 79}
81
+ # Bathymetry whose payload is a vendor format not documented in the XTF document, reported when there are no pings
82
+ UNDECODED_BATHY = {2, 5, 14, 16, 17, 18, 22, 25, 26, 27, 65, 68, 75}
83
+
84
+ EPOCH = datetime.datetime(1970, 1, 1)
85
+ DAY_MICROSECONDS = 86400000000
86
+
87
+ def epoch_microseconds_from(year, month, day, hour, minute, second, microseconds):
88
+ """Calendar time to microseconds since 1970-01-01. Returns None when the fields are not a valid time."""
89
+ try:
90
+ t = datetime.datetime(year, month, day, hour, minute, second)
91
+ except ValueError:
92
+ return None
93
+ return int((t - EPOCH).total_seconds()) * 1000000 + microseconds
94
+
95
+ def epoch_microseconds_from_7ktime(year, day, seconds, hours, minutes):
96
+ """7KTIME (7k DFD Table 3: year, day of year 1-366, seconds, hours, minutes) to microseconds since 1970-01-01."""
97
+ if not (1 <= day <= 366 and hours <= 23 and minutes <= 59 and 0.0 <= seconds < 61.0):
98
+ return None
99
+ try:
100
+ days = (datetime.date(year, 1, 1) - EPOCH.date()).days + day - 1
101
+ except ValueError:
102
+ return None
103
+ return ((days * 24 + hours) * 60 + minutes) * 60000000 + int(round(seconds * 1e6))
104
+
105
+ def full_sound_velocity(soundVelocity):
106
+ """Table H SoundVelocity: "Isis uses 750 (one way), some XTF files use 1500" (appendix 2: "SoundVelocity (half)")."""
107
+ if not soundVelocity > 0.0:
108
+ return math.nan
109
+ return 2.0 * soundVelocity if soundVelocity < 1000.0 else soundVelocity
110
+
111
+ def geographic(latitude_deg, longitude_deg):
112
+ return abs(latitude_deg) <= 90.0 and abs(longitude_deg) <= 180.0
113
+
114
+ class XtfReader(BaseReader):
115
+ def __init__(self):
116
+ super().__init__()
117
+ self.include_extra_detections = False #Reson 7027 multi-detect: lower priority detections in the same beam
118
+ self.positions = []
119
+ self.attitudes = []
120
+ self.pings = []
121
+ self.file_header = {} #parsed XTFFILEHEADER, e.g. file_header["NavUnits"]
122
+ self.channels = [] #parsed CHANINFO structures
123
+
124
+ def lever_arm(self):
125
+ """Bathymetry sonar position re. vessel reference point (VCS: x fwd, y stbd, z down), from the first bathymetry
126
+ CHANINFO. XTF offsets have X to starboard, Y forward and Z down (Table D), so (x, y, z) = (Y, X, Z)."""
127
+ for channel in self.channels:
128
+ if channel["TypeOfChannel"] == TYPE_BATHYMETRY:
129
+ return np.array([channel["OffsetY"], channel["OffsetX"], channel["OffsetZ"]])
130
+ return np.zeros(3)
131
+
132
+ def position_lever_arm(self):
133
+ """Navigation system position re. vessel reference point (VCS), from the file header NavOffset. Raw navigation
134
+ packets (types 42 and 107) are the positions of that navigation system."""
135
+ h = self.file_header
136
+ if not h:
137
+ return np.zeros(3)
138
+ return np.array([h["NavOffsetY"], h["NavOffsetX"], h["NavOffsetZ"]])
139
+
140
+ def _read_file_header(self, buffer):
141
+ """XTFFILEHEADER and its CHANINFO structures (Tables C and D). Returns the offset of the first packet."""
142
+ if len(buffer) < FILE_HEADER_BLOCK:
143
+ raise ValueError("File shorter than an XTF file header")
144
+ (FileFormat, SystemType, RecordingProgramName, RecordingProgramVersion, SonarName, SonarType, NoteString, ThisFileName,
145
+ NavUnits, NumberOfSonarChannels, NumberOfBathymetryChannels, NumberOfSnippetChannels, NumberOfForwardLookArrays,
146
+ NumberOfEchoStrengthChannels, NumberOfInterferometryChannels, Reserved1, Reserved2, ReferencePointHeight,
147
+ ProjectionType, SpheriodType, NavigationLatency, OriginY, OriginX, NavOffsetY, NavOffsetX, NavOffsetZ, NavOffsetYaw,
148
+ MRUOffsetY, MRUOffsetX, MRUOffsetZ, MRUOffsetYaw, MRUOffsetPitch, MRUOffsetRoll) = FILE_HEADER.unpack_from(buffer, 0)
149
+ if FileFormat != FILE_FORMAT:
150
+ raise ValueError(f"FileFormat is {FileFormat}, not {FILE_FORMAT}: not an XTF file")
151
+
152
+ text = lambda b: b.split(b"\0")[0].decode("ascii", "replace")
153
+ self.file_header = {
154
+ "RecordingProgramName": text(RecordingProgramName), "RecordingProgramVersion": text(RecordingProgramVersion),
155
+ "SonarName": text(SonarName), "SonarType": SonarType, "NoteString": text(NoteString), "ThisFileName": text(ThisFileName),
156
+ "NavUnits": NavUnits, "NumberOfSonarChannels": NumberOfSonarChannels, "NumberOfBathymetryChannels": NumberOfBathymetryChannels,
157
+ "ReferencePointHeight": ReferencePointHeight, "NavigationLatency": NavigationLatency,
158
+ "NavOffsetY": NavOffsetY, "NavOffsetX": NavOffsetX, "NavOffsetZ": NavOffsetZ, "NavOffsetYaw": NavOffsetYaw,
159
+ "MRUOffsetY": MRUOffsetY, "MRUOffsetX": MRUOffsetX, "MRUOffsetZ": MRUOffsetZ,
160
+ "MRUOffsetYaw": MRUOffsetYaw, "MRUOffsetPitch": MRUOffsetPitch, "MRUOffsetRoll": MRUOffsetRoll}
161
+
162
+ # Sonar CHANINFOs come first, then bathymetry (2.3). The header is 1024 bytes, growing by 1024 when needed
163
+ numChannels = NumberOfSonarChannels + NumberOfBathymetryChannels
164
+ header_size = max(FILE_HEADER_BLOCK, -(-(FILE_HEADER.size + numChannels * CHANINFO.size) // FILE_HEADER_BLOCK) * FILE_HEADER_BLOCK)
165
+ self.channels = []
166
+ for i in range(min(numChannels, (min(header_size, len(buffer)) - FILE_HEADER.size) // CHANINFO.size)):
167
+ (TypeOfChannel, SubChannelNumber, CorrectionFlags, UniPolar, BytesPerSample, Reserved, ChannelName, VoltScale, Frequency,
168
+ HorizBeamAngle, TiltAngle, BeamWidth, OffsetX, OffsetY, OffsetZ, OffsetYaw, OffsetPitch, OffsetRoll, BeamsPerArray,
169
+ SampleFormat, ReservedArea2) = CHANINFO.unpack_from(buffer, FILE_HEADER.size + i * CHANINFO.size)
170
+ self.channels.append({
171
+ "TypeOfChannel": TypeOfChannel, "SubChannelNumber": SubChannelNumber, "ChannelName": text(ChannelName),
172
+ "BytesPerSample": BytesPerSample, "Frequency": Frequency, "OffsetX": OffsetX, "OffsetY": OffsetY, "OffsetZ": OffsetZ,
173
+ "OffsetYaw": OffsetYaw, "OffsetPitch": OffsetPitch, "OffsetRoll": OffsetRoll})
174
+
175
+ # Some writers count channels differently: if no packet starts where expected, look at the next 1024 blocks
176
+ for start in range(header_size, min(len(buffer), header_size + 16 * FILE_HEADER_BLOCK), FILE_HEADER_BLOCK):
177
+ if buffer[start : start + 2] == MAGIC_BYTES:
178
+ if start != header_size:
179
+ sys.stderr.write(f"File header is {start} bytes, not the {header_size} expected from its channel counts\n")
180
+ return start
181
+ return header_size
182
+
183
+ def read(self,filename):
184
+ self.positions = []
185
+ self.attitudes = []
186
+ self.pings = []
187
+
188
+ # Repeated problems are reported once, with a count, at the end
189
+ warnings = {}
190
+ def warn(message):
191
+ warnings[message] = warnings.get(message, 0) + 1
192
+
193
+ attitude_packets = [] # (epoch_us, roll_rad, pitch_rad, heading_rad) from attitude packets with an absolute time
194
+ attitude_tagged = [] # (TimeTag_ms, roll_rad, pitch_rad, heading_rad) from attitude packets with only a time tag
195
+ attitude_tags = [] # (AttitudeTimeTag_ms, ping epoch_us) from ping headers, to time the tagged attitude
196
+ navigation = [] # (epoch_us, latitude_rad, longitude_rad, height_m) from type 42
197
+ pos_raw = [] # idem from type 107
198
+ pos_raw_attitude = [] # (epoch_us, roll_rad, pitch_rad, heading_rad) from type 107
199
+ header_positions = {True: {}, False: {}} # per bathy/sonar ping headers: fix epoch_us -> (latitude_deg, longitude_deg)
200
+ header_attitudes = {True: {}, False: {}} # per bathy/sonar ping headers: ping epoch_us -> (roll, pitch, heading) in degrees
201
+ ping_packets = [] # bathymetry packets turned into Pings after the first pass
202
+ undecoded_bathy = {} # header type -> count
203
+ count_7006 = 0
204
+
205
+ with open(filename, "rb") as file, mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as buffer:
206
+ file_size = len(buffer)
207
+ offset = self._read_file_header(buffer)
208
+ nav_latlong = self.file_header["NavUnits"] == NAV_UNITS_LATLONG
209
+
210
+ def valid_packet_at(start):
211
+ """A packet that starts with the magic number and is followed by the end of file or another packet."""
212
+ if start + PACKET_HEADER.size > file_size or buffer[start : start + 2] != MAGIC_BYTES:
213
+ return False
214
+ (numBytes,) = struct.unpack_from("<I", buffer, start + 10)
215
+ end = start + numBytes
216
+ return numBytes >= PACKET_HEADER.size and (end == file_size or (end + 2 <= file_size and buffer[end : end + 2] == MAGIC_BYTES))
217
+
218
+ # Read file one packet at the time
219
+ invalid_since = None # start of a corrupted region while searching for the next packet
220
+ while offset + PACKET_HEADER.size <= file_size:
221
+ packet_start = offset
222
+
223
+ # Read the start common to all packets
224
+ (MagicNumber, HeaderType, SubChannelNumber, NumChansToFollow, Reserved1a, Reserved1b, NumBytesThisRecord) = PACKET_HEADER.unpack_from(buffer, packet_start)
225
+ packet_end = packet_start + NumBytesThisRecord
226
+
227
+ # The magic number "can be used to align the data stream to the start of a packet" (3.1.3)
228
+ if MagicNumber != MAGIC_NUMBER or NumBytesThisRecord < PACKET_HEADER.size or packet_end > file_size:
229
+ if invalid_since is None:
230
+ invalid_since = packet_start
231
+ if MagicNumber == MAGIC_NUMBER and packet_end > file_size:
232
+ sys.stderr.write(f"Packet at offset {packet_start} ({NumBytesThisRecord} bytes) extends past the end of the file ({file_size - packet_start} bytes left)\n")
233
+ else:
234
+ sys.stderr.write(f"Invalid packet at offset {packet_start}, searching for the next magic number\n")
235
+ candidate = buffer.find(MAGIC_BYTES, packet_start + 1)
236
+ while candidate >= 0 and not valid_packet_at(candidate):
237
+ candidate = buffer.find(MAGIC_BYTES, candidate + 1)
238
+ if candidate < 0:
239
+ break
240
+ offset = candidate
241
+ continue
242
+ if invalid_since is not None:
243
+ sys.stderr.write(f"Resynchronised at offset {packet_start}, skipped {packet_start - invalid_since} bytes\n")
244
+ invalid_since = None
245
+
246
+ offset = packet_end
247
+ type_name = HEADER_NAMES.get(HeaderType, str(HeaderType))
248
+
249
+ if HeaderType in SONAR_PING_HEADERS or HeaderType in BATHY_PING_HEADERS:
250
+ #XTFPINGHEADER / XTFBATHHEADER Sonar and bathymetry packets
251
+ if NumBytesThisRecord < PING_HEADER.size:
252
+ warn(f"Packet type {HeaderType} ({type_name}) shorter than a ping header, skipped")
253
+ continue
254
+ (MagicNumber, HeaderType, SubChannelNumber, NumChansToFollow, Reserved1a, Reserved1b, NumBytesThisRecord,
255
+ Year, Month, Day, Hour, Minute, Second, HSeconds, JulianDay, EventNumber, PingNumber, SoundVelocity, OceanTide, Reserved2,
256
+ ConductivityFreq, TemperatureFreq, PressureFreq, PressureTemp, Conductivity, WaterTemperature, Pressure, ComputedSoundVelocity,
257
+ MagX, MagY, MagZ, AuxVal1, AuxVal2, AuxVal3, AuxVal4, AuxVal5, AuxVal6, SpeedLog, Turbidity, ShipSpeed, ShipGyro,
258
+ ShipYcoordinate, ShipXcoordinate, ShipAltitude, ShipDepth, FixTimeHour, FixTimeMinute, FixTimeSecond, FixTimeHsecond,
259
+ SensorSpeed, KP, SensorYcoordinate, SensorXcoordinate, SonarStatus, RangeToFish, BearingToFish, CableOut,
260
+ Layback, CableTension, SensorDepth, SensorPrimaryAltitude, SensorAuxAltitude, SensorPitch, SensorRoll, SensorHeading, Heave, Yaw,
261
+ AttitudeTimeTag, DOT, NavFixMilliseconds, ComputerClockHour, ComputerClockMinute, ComputerClockSecond, ComputerClockHsec,
262
+ FishPositionDeltaX, FishPositionDeltaY, FishPositionErrorCode, OptionalOffset, CableOutHundredths, ReservedSpace2) = PING_HEADER.unpack_from(buffer, packet_start)
263
+
264
+ # Ping time, in hundredths of seconds
265
+ ping_epoch = epoch_microseconds_from(Year, Month, Day, Hour, Minute, Second, HSeconds * 10000)
266
+ if ping_epoch is None:
267
+ warn(f"Packet type {HeaderType} ({type_name}) with an invalid ping time, skipped")
268
+ continue
269
+
270
+ # Attitude packets without an absolute time are timed with this millisecond tag (Table H AttitudeTimeTag)
271
+ if AttitudeTimeTag:
272
+ attitude_tags.append((AttitudeTimeTag, ping_epoch))
273
+
274
+ # Most recent navigation, timed by its fix time (already corrected for NavigationLatency)
275
+ bathy = HeaderType in BATHY_PING_HEADERS
276
+ latitude, longitude = (SensorYcoordinate, SensorXcoordinate) if (SensorYcoordinate or SensorXcoordinate) else (ShipYcoordinate, ShipXcoordinate)
277
+ if latitude or longitude:
278
+ fix_epoch = ping_epoch
279
+ if FixTimeHour or FixTimeMinute or FixTimeSecond or FixTimeHsecond:
280
+ fix_epoch = epoch_microseconds_from(Year, Month, Day, FixTimeHour, FixTimeMinute, FixTimeSecond, FixTimeHsecond * 10000)
281
+ if fix_epoch is None:
282
+ fix_epoch = ping_epoch
283
+ elif fix_epoch - ping_epoch > DAY_MICROSECONDS // 2:
284
+ fix_epoch -= DAY_MICROSECONDS # fix before midnight, ping after
285
+ elif ping_epoch - fix_epoch > DAY_MICROSECONDS // 2:
286
+ fix_epoch += DAY_MICROSECONDS
287
+ header_positions[bathy].setdefault(fix_epoch, (latitude, longitude))
288
+
289
+ # Attitude "received closest in time to this sonar or bathymetry update"
290
+ if SensorPitch or SensorRoll or SensorHeading:
291
+ header_attitudes[bathy].setdefault(ping_epoch, (SensorRoll, SensorPitch, SensorHeading))
292
+
293
+ if HeaderType == HEADER_Q_MULTIBEAM:
294
+ #28 XTFBATHHEADER followed by NumChansToFollow XTFQPSMBEENTRY (3.1.16)
295
+ entries_start = packet_start + PING_HEADER.size
296
+ if entries_start + NumChansToFollow * Q_MULTIBEAM_ENTRY.size > packet_end:
297
+ warn("QPS multibeam packet too short for its number of beams, skipped")
298
+ continue
299
+ ping_packets.append((HEADER_Q_MULTIBEAM, ping_epoch, full_sound_velocity(SoundVelocity), entries_start, NumChansToFollow))
300
+
301
+ elif HeaderType == HEADER_7125:
302
+ #61 Reson 7125 bathymetry: a 7k Data Record Frame and the 7027 or 7006 record (appendix 1)
303
+ drf_start = packet_start + PING_HEADER.size
304
+ if drf_start + DRF_7K.size > packet_end:
305
+ warn("Reson 7125 packet too short for a 7k record frame, skipped")
306
+ continue
307
+ (ProtocolVersion, RthOffset, SyncPattern, RecordSize, OptionalDataOffset, OptionalDataIdentifier,
308
+ Year7k, Day7k, Seconds7k, Hours7k, Minutes7k, RecordVersion, RecordTypeIdentifier, DeviceIdentifier,
309
+ Reserved7k0, SystemEnumerator, Reserved7k1, Flags7k, Reserved7k2, Reserved7k3, TotalRecords, FragmentNumber) = DRF_7K.unpack_from(buffer, drf_start)
310
+ if SyncPattern != SYNC_PATTERN_7K:
311
+ warn("Reson 7125 packet without a valid 7k record frame, skipped")
312
+ continue
313
+
314
+ # "To distinguish the difference examine the DRF ... and note the value of the RecordTypeID field"
315
+ if RecordTypeIdentifier == RECORD_7006:
316
+ count_7006 += 1
317
+ continue
318
+ if RecordTypeIdentifier != RECORD_7027:
319
+ warn(f"Reson 7125 packet with 7k record {RecordTypeIdentifier}, skipped")
320
+ continue
321
+
322
+ rth_start = drf_start + 4 + RthOffset # the DRF offset counts from the sync pattern
323
+ if rth_start + RAW_DETECTION_7027.size > packet_end:
324
+ warn("Reson 7027 record too short, skipped")
325
+ continue
326
+ (SonarId, PingNumber7k, MultiPingSequence, NumDetections, DataFieldSize, DetectionAlgorithm, DetectionFlags, SamplingRate_Hz, TxAngle_rad, *Reserved7027) = RAW_DETECTION_7027.unpack_from(buffer, rth_start)
327
+ if DataFieldSize < DETECTION_7027_MIN or rth_start + RAW_DETECTION_7027.size + NumDetections * DataFieldSize > packet_end or not SamplingRate_Hz > 0.0:
328
+ warn("Reson 7027 record with invalid detection sizes or sampling rate, skipped")
329
+ continue
330
+
331
+ # The 7k time of the ping (microseconds) is more precise than the ping header time (hundredths)
332
+ epoch_7k = epoch_microseconds_from_7ktime(Year7k, Day7k, Seconds7k, Hours7k, Minutes7k)
333
+ ping_packets.append((HEADER_7125, epoch_7k if epoch_7k is not None else ping_epoch, full_sound_velocity(SoundVelocity),
334
+ rth_start + RAW_DETECTION_7027.size, NumDetections, DataFieldSize, DetectionFlags, SamplingRate_Hz, TxAngle_rad))
335
+
336
+ elif HeaderType in UNDECODED_BATHY:
337
+ undecoded_bathy[HeaderType] = undecoded_bathy.get(HeaderType, 0) + 1
338
+
339
+ elif HeaderType == HEADER_ATTITUDE:
340
+ #3 XTFATTITUDEDATA
341
+ if NumBytesThisRecord < ATTITUDE.size:
342
+ warn("Attitude packet too short, skipped")
343
+ continue
344
+ (MagicNumber, HeaderType, SubChannelNumber, NumChansToFollow, Reserved1a, Reserved1b, NumBytesThisRecord, Reserved2a, Reserved2b,
345
+ EpochMicroseconds, SourceEpoch, Pitch, Roll, Heave, Yaw, TimeTag, Heading, Year, Month, Day, Hour, Minutes, Seconds, Milliseconds, Reserved3) = ATTITUDE.unpack_from(buffer, packet_start)
346
+
347
+ # Positive roll is to starboard (port up) and positive pitch nose up, as in KMALL
348
+ sample = (math.radians(Roll), math.radians(Pitch), math.radians(Heading))
349
+ if SourceEpoch and EpochMicroseconds <= 999999:
350
+ attitude_packets.append((SourceEpoch * 1000000 + EpochMicroseconds,) + sample)
351
+ continue
352
+ epoch_microseconds = epoch_microseconds_from(Year, Month, Day, Hour, Minutes, Seconds, Milliseconds * 1000) if Year and Milliseconds <= 999 else None
353
+ if epoch_microseconds is not None:
354
+ attitude_packets.append((epoch_microseconds,) + sample)
355
+ elif TimeTag:
356
+ attitude_tagged.append((TimeTag,) + sample)
357
+ else:
358
+ warn("Attitude packet without any time, skipped")
359
+
360
+ elif HeaderType == HEADER_NAVIGATION:
361
+ #42 XTFHEADERNAVIGATION, source time-stamped navigation
362
+ if NumBytesThisRecord < NAVIGATION.size:
363
+ warn("Navigation packet too short, skipped")
364
+ continue
365
+ (MagicNumber, HeaderType, Reserved, NumBytesThisRecord, Year, Month, Day, Hour, Minute, Second, Microseconds, SourceEpoch, TimeTag,
366
+ RawYcoordinate, RawXcoordinate, RawAltitude, TimeFlag, Reserved1) = NAVIGATION.unpack_from(buffer, packet_start)
367
+
368
+ # Appendix 3: SourceEpoch and the microseconds must be set; otherwise fall back on the source date and time
369
+ if Microseconds > 999999:
370
+ epoch_microseconds = None
371
+ elif SourceEpoch:
372
+ epoch_microseconds = SourceEpoch * 1000000 + Microseconds
373
+ else:
374
+ epoch_microseconds = epoch_microseconds_from(Year, Month, Day, Hour, Minute, Second, Microseconds)
375
+ if epoch_microseconds is None:
376
+ warn("Navigation packet without a valid source time, skipped")
377
+ continue
378
+
379
+ # "Raw position from POSMV or other time stamped navigation source": taken as degrees when in range
380
+ if not geographic(RawYcoordinate, RawXcoordinate):
381
+ warn("Navigation packet with a position that is not lat/long, skipped")
382
+ continue
383
+ navigation.append((epoch_microseconds, math.radians(RawYcoordinate), math.radians(RawXcoordinate), RawAltitude))
384
+
385
+ elif HeaderType == HEADER_POS_RAW_NAVIGATION:
386
+ #107 XTFPOSRAWNAVIGATION
387
+ if NumBytesThisRecord < POS_RAW_NAVIGATION.size:
388
+ warn("POS raw navigation packet too short, skipped")
389
+ continue
390
+ (MagicNumber, HeaderType, SubChannelNumber, NumChansToFollow, Reserved1a, Reserved1b, NumBytesThisRecord,
391
+ Year, Month, Day, Hour, Minutes, Seconds, MicroSeconds, RawYcoordinate, RawXcoordinate, RawAltitude,
392
+ Pitch, Roll, Heave, Heading, Reserved2) = POS_RAW_NAVIGATION.unpack_from(buffer, packet_start)
393
+
394
+ # MicroSeconds is actually 0-9999, tenths of milliseconds
395
+ epoch_microseconds = epoch_microseconds_from(Year, Month, Day, Hour, Minutes, Seconds, MicroSeconds * 100) if MicroSeconds <= 9999 else None
396
+ if epoch_microseconds is None:
397
+ warn("POS raw navigation packet without a valid time, skipped")
398
+ continue
399
+ if geographic(RawYcoordinate, RawXcoordinate) and (RawYcoordinate or RawXcoordinate):
400
+ pos_raw.append((epoch_microseconds, math.radians(RawYcoordinate), math.radians(RawXcoordinate), RawAltitude))
401
+ if Pitch or Roll or Heading:
402
+ pos_raw_attitude.append((epoch_microseconds, math.radians(Roll), math.radians(Pitch), math.radians(Heading)))
403
+
404
+ elif HeaderType in KNOWN_HEADER_TYPES:
405
+ # Known packets that are not used (yet)
406
+ pass
407
+ else:
408
+ warn(f"Unknown packet type {HeaderType}")
409
+
410
+ if invalid_since is not None:
411
+ sys.stderr.write(f"No valid packet found after offset {invalid_since}, stopping\n")
412
+ elif offset < file_size:
413
+ sys.stderr.write(f"Truncated packet at offset {offset} ({file_size - offset} bytes left), stopping\n")
414
+
415
+ # Bathymetry is read from the mapped file, so this happens before it is closed
416
+ self._make_pings(buffer, ping_packets)
417
+
418
+ if not self.pings:
419
+ if count_7006:
420
+ warn("Reson 7125 bathymetry is in the older 7006 record (needs the appended 7004 beam geometry), which is not read: no pings")
421
+ if undecoded_bathy:
422
+ names = ", ".join(f"{HEADER_NAMES[t]} ({t})" for t in sorted(undecoded_bathy))
423
+ warn(f"Bathymetry packets whose payload is a vendor format not documented in the XTF format, not read: {names}")
424
+
425
+ self._make_positions(navigation, pos_raw, header_positions, nav_latlong, warn)
426
+ self._make_attitudes(attitude_packets, attitude_tagged, attitude_tags, pos_raw_attitude, header_attitudes, warn)
427
+
428
+ for message, count in warnings.items():
429
+ sys.stderr.write(f"{message}" + (f" ({count}x)" if count > 1 else "") + "\n")
430
+
431
+ @staticmethod
432
+ def _read_detection_7027(buffer, offset, size):
433
+ """One 7027 detection. Older, shorter versions are padded with zeros (like the C++ example in 7k DFD appendix E)."""
434
+ if size >= DETECTION_7027.size:
435
+ return DETECTION_7027.unpack_from(buffer, offset)
436
+ return DETECTION_7027.unpack(bytes(buffer[offset : offset + size]) + bytes(DETECTION_7027.size - size))
437
+
438
+ def _rx_angle_sign_7027(self, buffer, ping_packets):
439
+ """Beam zero is the first beam on the port side (7k DFD 2.5) and the 7k frame has X to starboard, so the rx angle
440
+ should increase with the beam number. Check that against the data over the first and last detection of each ping."""
441
+ votes = 0
442
+ for packet in ping_packets:
443
+ if packet[0] != HEADER_7125 or packet[4] < 2:
444
+ continue
445
+ (kind, epoch_microseconds, surface_sound_speed, data_start, numDetections, dataFieldSize, detectionFlags, samplingRate_Hz, txAngle_rad) = packet
446
+ (firstBeam, _, firstRxAngle, *_) = self._read_detection_7027(buffer, data_start, dataFieldSize)
447
+ (lastBeam, _, lastRxAngle, *_) = self._read_detection_7027(buffer, data_start + (numDetections - 1) * dataFieldSize, dataFieldSize)
448
+ trend = (lastBeam - firstBeam) * (lastRxAngle - firstRxAngle)
449
+ votes += (trend > 0) - (trend < 0)
450
+ if votes < 0:
451
+ sys.stderr.write("Reson rx angles decrease with the beam number (positive to port): flipping their sign so beam_angle is positive to starboard\n")
452
+ return -1.0
453
+ return 1.0
454
+
455
+ def _make_pings(self, buffer, ping_packets):
456
+ rx_angle_sign = self._rx_angle_sign_7027(buffer, ping_packets)
457
+
458
+ for packet in ping_packets:
459
+ if packet[0] == HEADER_Q_MULTIBEAM:
460
+ (kind, ping_epoch, surface_sound_speed, entries_start, numBeams) = packet
461
+ for i in range(numBeams):
462
+ (Id, Intensity, Quality, TwoWayTravelTime, DeltaTime, BeamAngle, TiltAngle, Reserved0, Reserved1, Reserved2, Reserved3) = Q_MULTIBEAM_ENTRY.unpack_from(buffer, entries_start + i * Q_MULTIBEAM_ENTRY.size)
463
+ if not TwoWayTravelTime > 0.0:
464
+ continue # no detection
465
+
466
+ # The header time is the transmission time; DeltaTime gives the ping time per beam for profilers
467
+ epoch_microseconds = ping_epoch + int(round(DeltaTime * 1e6))
468
+
469
+ # The QPS quality has no documented scale, so it is not comparable to the KMALL quality factor
470
+ quality = math.nan
471
+
472
+ # "Beam Angle convention, Negative to port side, nadir beam 0degs, positive to starboard side", so no flip.
473
+ # "Tilt angle convention positive forward"
474
+ ping = Ping(epoch_microseconds,Id,quality,Intensity,surface_sound_speed,TwoWayTravelTime,math.radians(TiltAngle),math.radians(BeamAngle))
475
+ self.pings.append(ping)
476
+ continue
477
+
478
+ (kind, epoch_microseconds, surface_sound_speed, data_start, numDetections, dataFieldSize, detectionFlags, samplingRate_Hz, txAngle_rad) = packet
479
+ uncertainty_available = (detectionFlags & UNCERTAINTY_METHOD_MASK) != 0
480
+ for i in range(numDetections):
481
+ (beamDescriptor, detectionPoint, rxAngle_rad, flags, detectionQuality, uncertainty, signalStrength) = self._read_detection_7027(buffer, data_start + i * dataFieldSize, dataFieldSize)
482
+
483
+ # Multi-detect gives up to five detections per beam; priority 0 is the main one
484
+ if (flags >> DETECTION_PRIORITY_SHIFT) & DETECTION_PRIORITY_MASK and not self.include_extra_detections:
485
+ continue
486
+
487
+ # Fractional sample number with the zero sample at the transmit time (7k DFD appendix F)
488
+ twoWayTravelTime_sec = detectionPoint / samplingRate_Hz
489
+
490
+ # The uncertainty is an error normalised to the detection point; in % like the KMALL quality factor
491
+ quality = 100.0 * uncertainty if uncertainty_available else math.nan
492
+
493
+ ping = Ping(epoch_microseconds,beamDescriptor,quality,signalStrength,surface_sound_speed,twoWayTravelTime_sec,txAngle_rad,rx_angle_sign * rxAngle_rad)
494
+ self.pings.append(ping)
495
+
496
+ def _make_positions(self, navigation, pos_raw, header_positions, nav_latlong, warn):
497
+ # One source only, so positions from two systems never get interleaved: source time-stamped navigation first,
498
+ # then POS raw navigation, then the most recent fix copied into the ping headers
499
+ samples = navigation or pos_raw
500
+ if not samples:
501
+ header = header_positions[True] or header_positions[False]
502
+ if header and not nav_latlong:
503
+ warn("Ping header navigation is in projected meters (NavUnits 0) and XTF does not record the projection: no positions")
504
+ elif header:
505
+ samples = [(epoch_microseconds, math.radians(latitude), math.radians(longitude), math.nan)
506
+ for epoch_microseconds, (latitude, longitude) in header.items() if geographic(latitude, longitude)]
507
+
508
+ # Packets are written asynchronously (2.2), so sort
509
+ for (epoch_microseconds, latitude_rad, longitude_rad, height_m) in sorted(samples):
510
+ position = Position(epoch_microseconds, latitude_rad, longitude_rad, height_m)
511
+ self.positions.append(position)
512
+
513
+ def _make_attitudes(self, attitude_packets, attitude_tagged, attitude_tags, pos_raw_attitude, header_attitudes, warn):
514
+ # Attitude packets with only a millisecond TimeTag are timed with the AttitudeTimeTag of the ping headers:
515
+ # the offset between that clock and the ping times
516
+ if attitude_tagged:
517
+ if attitude_tags:
518
+ offset = statistics.median(ping_epoch - tag * 1000 for (tag, ping_epoch) in attitude_tags)
519
+ attitude_packets = attitude_packets + [(int(tag * 1000 + offset), roll, pitch, heading) for (tag, roll, pitch, heading) in attitude_tagged]
520
+ else:
521
+ warn("Attitude packets with only a time tag and no ping header AttitudeTimeTag to time them, skipped")
522
+
523
+ # The high rate attitude packets first, then POS raw navigation, then the ping headers' attitude
524
+ samples = attitude_packets or pos_raw_attitude
525
+ if not samples:
526
+ header = header_attitudes[True] or header_attitudes[False]
527
+ samples = [(epoch_microseconds, math.radians(roll), math.radians(pitch), math.radians(heading))
528
+ for epoch_microseconds, (roll, pitch, heading) in header.items()]
529
+
530
+ for (epoch_microseconds, roll_rad, pitch_rad, heading_rad) in sorted(samples):
531
+ attitude = Attitude(epoch_microseconds, roll_rad, pitch_rad, heading_rad)
532
+ self.attitudes.append(attitude)
mbes/__init__.py ADDED
File without changes
mbes/core.py ADDED
@@ -0,0 +1,17 @@
1
+ import os
2
+ import sys
3
+ import pandas as pd
4
+
5
+ from mbes.MbesReader import MbesReader
6
+
7
+ if __name__ == "__main__":
8
+ if len(sys.argv) != 2:
9
+ sys.stderr.write("Usage: MbesReader.py sonar_file\n")
10
+ sys.exit(1)
11
+
12
+ r = MbesReader()
13
+ pings = r.read(sys.argv[1])
14
+
15
+ for p in pings:
16
+ print(f"{p[0]} {p[1]} {p[2]}")
17
+