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.
mbes/Georeferencing.py ADDED
@@ -0,0 +1,46 @@
1
+ import math
2
+ import numpy as np
3
+ from mbes.Position import Position
4
+ from mbes.Attitude import Attitude
5
+ from mbes.Ping import Ping
6
+ from mbes.SoundVelocityProfile import SoundVelocityProfile
7
+
8
+ class Georeferencing:
9
+
10
+ # Convert WGS84 lat/lon to ECEF
11
+ @staticmethod
12
+ def llh2ecef(p: Position):
13
+ return np.array([
14
+ (6378137.0 / (math.sqrt(1 - (0.081819190842622 ** 2) * (math.sin(p.latitude) ** 2))) + p.ellipsoidal_height) * math.cos(p.latitude) * math.cos(p.longitude),
15
+ (6378137.0 / (math.sqrt(1 - (0.081819190842622 ** 2) * (math.sin(p.latitude) ** 2))) + p.ellipsoidal_height) * math.cos(p.latitude) * math.sin(p.longitude),
16
+ (6378137.0 / (math.sqrt(1 - (0.081819190842622 ** 2) * (math.sin(p.latitude) ** 2))) * (1 - (0.081819190842622 **2)) + p.ellipsoidal_height) * math.sin(p.latitude)
17
+ ])
18
+
19
+ # Computes the position of a sonar sounding in the ECEF frame
20
+ @staticmethod
21
+ def compute_ecef(p: Position, a: Attitude,d: Ping, svp: SoundVelocityProfile, offset: np.array, boresight: np.array):
22
+ # Compute frame conversion matrix between local (NED) and terrestrial (ECEF) frames
23
+ ned_2_ecef = np.array([
24
+ [-math.cos(p.longitude)*math.sin(p.latitude),-math.sin(p.longitude),-math.cos(p.latitude)*math.cos(p.longitude)],
25
+ [-math.sin(p.latitude)*math.sin(p.longitude),math.cos(p.longitude),-math.cos(p.latitude)*math.sin(p.longitude)],
26
+ [math.cos(p.latitude),0,-math.sin(p.latitude)]
27
+ ])
28
+
29
+ # Compute motion compensation matrix
30
+ imu_2_ned = np.array([
31
+ [math.cos(a.heading)*math.cos(a.pitch), math.cos(a.heading)*math.sin(a.pitch)*math.sin(a.roll)-math.cos(a.roll)*math.sin(a.heading), math.cos(a.heading)*math.cos(a.roll)*math.sin(a.pitch)+math.sin(a.roll)*math.sin(a.heading)],
32
+ [math.cos(a.pitch)*math.sin(a.heading), math.cos(a.heading)*math.cos(a.roll)+math.sin(a.pitch)*math.sin(a.roll)*math.sin(a.heading), math.sin(a.heading)*math.cos(a.roll)*math.sin(a.pitch)-math.cos(a.heading)*math.sin(a.roll)],
33
+ [-math.sin(a.pitch), math.cos(a.pitch) * math.sin(a.roll), math.cos(a.roll) * math.cos(a.pitch)]
34
+ ]);
35
+
36
+ # Sum the position, offset and depth vectors in the same frame (ECEF)
37
+ sound_speed = d.surface_sound_speed if d.surface_sound_speed > 0 else 1500.0
38
+ distance = d.two_way_travel_time * sound_speed / 2 #TODO: raytrace with SSS + SVP
39
+
40
+ sx = math.sin(d.tilt_angle)
41
+ sy = math.sin(d.beam_angle)
42
+ sz = math.sqrt(max(0.0, 1.0 - sx*sx - sy*sy))
43
+ ping = distance * np.array([sx, sy, sz])
44
+
45
+ #TODO: handle boresight
46
+ return Georeferencing.llh2ecef(p) + np.matmul(np.matmul(ned_2_ecef,imu_2_ned) , (np.array([offset[0],offset[1],offset[2]]) + ping));
mbes/Interpolator.py ADDED
@@ -0,0 +1,50 @@
1
+ import math
2
+
3
+ from mbes.Position import Position
4
+ from mbes.Attitude import Attitude
5
+
6
+ class InterpolationError(Exception):
7
+ pass
8
+
9
+ class Interpolator:
10
+ @staticmethod
11
+ def interpolate_position(p1: Position, p2: Position, timestamp: int) -> Position:
12
+ lat = Interpolator.linear_interpolation_by_time(p1.latitude, p2.latitude, timestamp, p1.timestamp, p2.timestamp)
13
+ lon = Interpolator.linear_angle_interpolation_by_time(p1.longitude, p2.longitude, timestamp, p1.timestamp, p2.timestamp)
14
+ alt = Interpolator.linear_interpolation_by_time(p1.ellipsoidal_height, p2.ellipsoidal_height, timestamp, p1.timestamp, p2.timestamp)
15
+
16
+ return Position(timestamp, lat, lon, alt)
17
+
18
+ @staticmethod
19
+ def interpolate_attitude(a1: Attitude, a2: Attitude, timestamp: int) -> Attitude:
20
+ roll = Interpolator.linear_angle_interpolation_by_time(a1.roll, a2.roll, timestamp, a1.timestamp, a2.timestamp)
21
+ pitch = Interpolator.linear_angle_interpolation_by_time(a1.pitch, a2.pitch, timestamp, a1.timestamp, a2.timestamp)
22
+ heading = Interpolator.linear_angle_interpolation_by_time(a1.heading, a2.heading, timestamp, a1.timestamp, a2.timestamp) % (2 * math.pi)
23
+
24
+ return Attitude(timestamp, roll, pitch, heading)
25
+
26
+ @staticmethod
27
+ def linear_interpolation_by_time(y1: float, y2: float, x: int, x1: int, x2: int) -> float:
28
+ """Linear interpolation of a scalar value between (x1, y1) and (x2, y2)."""
29
+ Interpolator.check_timestamps(x, x1, x2)
30
+ return y1 + (y2 - y1) * (x - x1) / (x2 - x1)
31
+
32
+ @staticmethod
33
+ def check_timestamps(x: int, x1: int, x2: int) -> None:
34
+ if x1 == x2:
35
+ raise InterpolationError("The two timestamps are the same")
36
+ if x1 > x2:
37
+ raise InterpolationError("The first timestamp is higher than the second timestamp")
38
+ if not (x1 <= x <= x2):
39
+ raise InterpolationError("The interpolation timestamp is outside the interval (extrapolation)")
40
+
41
+ @staticmethod
42
+ def linear_angle_interpolation_by_time(psi1: float, psi2: float, t: int, t1: int, t2: int) -> float:
43
+ """Linear interpolation of an angle in RADIANS along the shortest arc.
44
+ The result is not wrapped, so a small negative roll/pitch stays a small negative number."""
45
+ Interpolator.check_timestamps(t, t1, t2)
46
+
47
+ delta = (t - t1) / (t2 - t1)
48
+ dpsi = math.remainder(psi2 - psi1, 2 * math.pi) # shortest signed difference, in [-pi, pi]
49
+
50
+ return psi1 + dpsi * delta
mbes/KmallReader.py ADDED
@@ -0,0 +1,213 @@
1
+ import struct
2
+ import mmap
3
+ import sys
4
+ import math
5
+ import numpy as np
6
+
7
+ from mbes.BaseReader import BaseReader
8
+ from mbes.Ping import Ping
9
+ from mbes.Attitude import Attitude
10
+ from mbes.Position import Position
11
+
12
+ # "Unavailable" markers from EMdgmFormat.h
13
+ UNAVAILABLE_LATITUDE = 200.0
14
+ UNAVAILABLE_LONGITUDE = 200.0
15
+
16
+ # Bit 0 of the sensor status fields: 1 = sensor is chosen as active
17
+ SENSOR_ACTIVE = 0x01
18
+
19
+ # MRZ sounding detectionType values
20
+ DETECTION_NORMAL = 0
21
+ DETECTION_EXTRA = 1
22
+ DETECTION_REJECTED = 2
23
+
24
+ class KmallReader(BaseReader):
25
+ def __init__(self):
26
+ self.use_realtime_approximation = False #The MRZ datagram contains a position and XYZ estimate to be used in real-time.
27
+ self.include_extra_detections = False #detectionType 1 (water-column targets etc.), not seabed
28
+ self.positions = []
29
+ self.attitudes = []
30
+ self.pings = []
31
+ self.installation = {} #parsed #IIP, e.g. installation["TRAI_RX1"]["X"]
32
+
33
+ def lever_arm(self):
34
+ """Sonar position re. vessel reference point (VCS: x fwd, y stbd, z down), from #IIP.
35
+ Along-track from the TX array, across-track and vertical from the RX array (Mills cross)."""
36
+ tx = self.installation.get("TRAI_TX1")
37
+ rx = self.installation.get("TRAI_RX1")
38
+ if not tx or not rx:
39
+ return np.zeros(3)
40
+ return np.array([float(tx["X"]), float(rx["Y"]), float(rx["Z"])])
41
+
42
+ def read(self,filename):
43
+ self.positions = []
44
+ self.attitudes = []
45
+ self.pings = []
46
+ self.installation = {}
47
+
48
+ with open(filename, "rb") as file, mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as buffer:
49
+ # Read file one datagram at the time
50
+ datagram_header_format = "<I4sBBHII"
51
+ datagram_header_size = struct.calcsize(datagram_header_format)
52
+ offset = 0
53
+ file_size = len(buffer)
54
+
55
+ while offset + datagram_header_size <= file_size:
56
+ datagram_start = offset
57
+
58
+ # Read datagram header
59
+ (datagram_size, datagram_type, datagram_version, system_id, echosounder_id, time_sec, time_nanosec) = struct.unpack_from(datagram_header_format, buffer,offset)
60
+
61
+ # Every datagram is header + body + a trailing uint32 copy of its size
62
+ if datagram_size < datagram_header_size + 4:
63
+ raise ValueError(f"Invalid datagram size {datagram_size} bytes at offset {datagram_start}")
64
+ if datagram_start + datagram_size > file_size:
65
+ sys.stderr.write(f"Truncated datagram at offset {datagram_start} ({datagram_size} bytes, {file_size - datagram_start} left), stopping\n")
66
+ break
67
+ (trailing_size,) = struct.unpack_from("<I", buffer, datagram_start + datagram_size - 4)
68
+ if trailing_size != datagram_size:
69
+ raise ValueError(f"Datagram at offset {datagram_start}: size {datagram_size} != trailing size {trailing_size}")
70
+
71
+ offset += datagram_header_size
72
+
73
+ datagram_type = datagram_type.decode("ascii")
74
+
75
+ if datagram_type == "#IIP":
76
+ #IIP EMdgmIIP_def Installation parameters and sensor setup.
77
+ (numBytesCmnPart, info, status) = struct.unpack_from("<HHH", buffer, offset)
78
+ text = bytes(buffer[offset + 6 : datagram_start + datagram_size - 4]).split(b"\0")[0].decode("ascii", "replace")
79
+ for line in text.replace(",", "\n").splitlines():
80
+ name, sep, values = line.partition(":")
81
+ if sep and "=" in values:
82
+ self.installation[name.strip()] = dict(kv.split("=", 1) for kv in values.split(";") if "=" in kv)
83
+ elif datagram_type == "#IOP":
84
+ #IOP EMdgmIOP_def Runtime parameters as chosen by operator.
85
+ pass
86
+ elif datagram_type == "#MRZ":
87
+ #MRZ EMdgmMRZ_def Multibeam (M) raw range (R) and depth(Z) datagram
88
+ ping_offset = offset
89
+
90
+ # Partitions
91
+ partition_format = "<HH"
92
+ (numOfDgms, dgmNum) = struct.unpack_from(partition_format, buffer, offset)
93
+ ping_offset += struct.calcsize(partition_format)
94
+
95
+ #MBody
96
+ (numBytesCmnPart, pingCnt, rxFansPerPing, rxFanIndex,swathsPerPing, swathAlongPosition, txTransducerInd, rxTransducerInd, numRxTransducers, algorithmType) = struct.unpack_from("<HHBBBBBBBB",buffer,ping_offset)
97
+ ping_offset += numBytesCmnPart
98
+
99
+ #Ping Info
100
+ pinginfo_format = "<HHfBBBBBBH11fhhBBHIfffHHfHH6fBBBBddf"
101
+ (numBytesInfoData, padding0, pingRate_Hz, beamSpacing, depthMode, subDepthMode, distanceBtwSwath, detectionMode, pulseForm, padding1, frequencyMode_Hz, freqRangeLowLim_Hz, freqRangeHighLim_Hz, maxTotalTxPulseLength_sec, maxEffTxPulseLength_sec, maxEffTxBandWidth_Hz, absCoeff_dBPerkm, portSectorEdge_deg, starbSectorEdge_deg, portMeanCov_deg, starbMeanCov_deg, portMeanCov_m, starbMeanCov_m, modeAndStabilisation, runtimeFilter1, runtimeFilter2, pipeTrackingStatus, transmitArraySizeUsed_deg, receiveArraySizeUsed_deg, transmitPower_dB, SLrampUpTimeRemaining, padding2, yawAngle_deg, numTxSectors, numBytesPerTxSector, headingVessel_deg, soundSpeedAtTxDepth_mPerSec, txTransducerDepth_m, z_waterLevelReRefPoint_m, x_kmallToall_m, y_kmallToall_m, latLongInfo, posSensorStatus, attitudeSensorStatus, padding3, latitude_deg, longitude_deg, ellipsoidHeightReRefPoint_m) = struct.unpack_from(pinginfo_format,buffer,ping_offset)
102
+
103
+ #If the ping contains extended data (MRZ version >= 1), it follows the base struct
104
+ pinginfo_ext_format = "<fBBH"
105
+ base = struct.calcsize(pinginfo_format)
106
+ if numBytesInfoData >= base + struct.calcsize(pinginfo_ext_format):
107
+ (bsCorrectionOffset_dB,lambertsLawApplied,iceWindow,activeModes) = struct.unpack_from(pinginfo_ext_format, buffer, ping_offset + base)
108
+ ping_offset += numBytesInfoData
109
+
110
+ #TX Sectors
111
+ sectors = {}
112
+ txsector_format = "<BBBBfffffffBBH"
113
+ txsector_ext_format = "<fff"
114
+ base = struct.calcsize(txsector_format)
115
+
116
+ for _ in range(numTxSectors):
117
+ (txSectorNumb,txArrNumber,txSubArray,padding0,sectorTransmitDelay_sec,tiltAngleReTx_deg,txNominalSourceLevel_dB,txFocusRange_m,centreFreq_Hz,signalBandWidth_Hz,totalSignalLength_sec,pulseShading,signalWaveForm,padding1) = struct.unpack_from(txsector_format, buffer, ping_offset)
118
+ if numBytesPerTxSector >= base + struct.calcsize(txsector_ext_format):
119
+ (highVoltageLevel_dB, sectorTrackingCorr_dB, effectiveSignalLength_sec) = struct.unpack_from(txsector_ext_format,buffer,ping_offset + base)
120
+ sectors[txSectorNumb] = [txArrNumber,txSubArray,padding0,sectorTransmitDelay_sec,tiltAngleReTx_deg,txNominalSourceLevel_dB,txFocusRange_m,centreFreq_Hz,signalBandWidth_Hz,totalSignalLength_sec,pulseShading,signalWaveForm,padding1]
121
+ ping_offset += numBytesPerTxSector
122
+
123
+ #RX Info
124
+ (numBytesRxInfo,numSoundingsMaxMain,numSoundingsValidMain,numBytesPerSounding,WCSampleRate,seabedImageSampleRate,BSnormal_dB,BSoblique_dB,extraDetectionAlarmFlag,numExtraDetections,numExtraDetectionClasses,numBytesPerClass) = struct.unpack_from("<HHHHffffHHHH",buffer,ping_offset)
125
+ ping_offset += numBytesRxInfo
126
+
127
+ # Extra detection classes
128
+ for _ in range(numExtraDetectionClasses):
129
+ (numExtraDetInClass, padding, alarmFlag) = struct.unpack_from("<HbB", buffer, ping_offset)
130
+ ping_offset += numBytesPerClass
131
+
132
+ # Header time = time of first TX pulse in the ping
133
+ epoch_microseconds = time_sec * 1000000 + (time_nanosec // 1000)
134
+
135
+ # Soundings
136
+ samples_count = 0
137
+ for _ in range(numSoundingsMaxMain + numExtraDetections):
138
+ (soundingIndex,txSectorNumb,detectionType,detectionMethod,rejectionInfo1,rejectionInfo2,postProcessingInfo,detectionClass,detectionConfidenceLevel,padding,rangeFactor,qualityFactor,detectionUncertaintyVer_m,detectionUncertaintyHor_m,detectionWindowLength_sec,echoLength_sec,WCBeamNumb,WCrange_samples,WCNomBeamAngleAcross_deg,meanAbsCoeff_dBPerkm,reflectivity1_dB,reflectivity2_dB,receiverSensitivityApplied_dB,sourceLevelApplied_dB,BScalibration_dB,TVG_dB,beamAngleReRx_deg,beamAngleCorrection_deg,twoWayTravelTime_sec,twoWayTravelTimeCorrection_sec,deltaLatitude_deg,deltaLongitude_deg,z_reRefPoint_m,y_reRefPoint_m,x_reRefPoint_m,beamIncAngleAdj_deg,realTimeCleanInfo,SIstartRange_samples,SIcentreSample,SInumSamples) = struct.unpack_from("<HBBBBBBBBH6fHH18f4H",buffer,ping_offset)
139
+ samples_count += SInumSamples
140
+ ping_offset += numBytesPerSounding
141
+
142
+ # detectionType 2 = rejected: the range is interpolated/extrapolated from neighbours, not measured
143
+ if detectionType == DETECTION_REJECTED:
144
+ continue
145
+ if detectionType == DETECTION_EXTRA and not self.include_extra_detections:
146
+ continue
147
+
148
+ if self.use_realtime_approximation:
149
+ latitude = latitude_deg + deltaLatitude_deg
150
+ longitude = longitude_deg + deltaLongitude_deg
151
+ position = Position(epoch_microseconds,math.radians(latitude),math.radians(longitude),ellipsoidHeightReRefPoint_m)
152
+ self.positions.append(position)
153
+
154
+ # beamAngleReRx_deg is positive towards PORT (the port-most beam has the largest positive
155
+ # angle and a negative y_reRefPoint_m). Ping.beam_angle follows the VCS (y = starboard),
156
+ # so flip the sign here.
157
+ intensity = 0 #TODO
158
+ surface_sound_speed = soundSpeedAtTxDepth_mPerSec
159
+ ping = Ping(epoch_microseconds,soundingIndex,qualityFactor,intensity,surface_sound_speed,twoWayTravelTime_sec,math.radians(sectors[txSectorNumb][4]),-math.radians(beamAngleReRx_deg))
160
+ self.pings.append(ping)
161
+
162
+ # Samples (seabed image), not used yet
163
+ ping_offset += 2 * samples_count
164
+
165
+ elif datagram_type == "#MWC":
166
+ #MWC EMdgmMWC_def Multibeam (M) water (W) column (C) datagram
167
+ pass
168
+ elif datagram_type == "#SPO":
169
+ #SPO EMdgmSPO_def Sensor (S) data for position (PO)
170
+ (numBytesCmnPart, sensorSystem, sensorStatus, padding) = struct.unpack_from("<HHHH", buffer, offset)
171
+ (timeFromSensor_sec, timeFromSensor_nanosec, posFixQuality_m, correctedLat_deg, correctedLong_deg, speedOverGround_mPerSec, courseOverGround_deg, ellipsoidHeightReRefPoint_m) = struct.unpack_from("<IIfddfff", buffer, offset + numBytesCmnPart)
172
+
173
+ # Header time, not timeFromSensor: GGA carries no date, and timeFromSensor is not a usable epoch in practice
174
+ epoch_microseconds = time_sec * 1000000 + (time_nanosec // 1000)
175
+
176
+ # Corrected data is only provided for the active sensor; inactive ones carry the UNAVAILABLE markers
177
+ active = sensorStatus & SENSOR_ACTIVE
178
+ available = correctedLat_deg != UNAVAILABLE_LATITUDE and correctedLong_deg != UNAVAILABLE_LONGITUDE
179
+
180
+ if not self.use_realtime_approximation and active and available:
181
+ position = Position(epoch_microseconds, math.radians(correctedLat_deg),math.radians(correctedLong_deg),ellipsoidHeightReRefPoint_m)
182
+ self.positions.append(position)
183
+
184
+ elif datagram_type == "#SKM":
185
+ #SKM EMdgmSKM_def Sensor (S) KM binary sensor format
186
+ skminfo_format = "<HBBHHHH"
187
+ #SKMInfo
188
+ (numBytesInfoPart, sensorSystem, sensorStatus, sensorInputFormat, numSamplesArray, numBytesPerSample, sensorDataContents) = struct.unpack_from(skminfo_format,buffer, offset)
189
+
190
+ # Only use the active attitude sensor, otherwise two IMUs get interleaved
191
+ if not (sensorStatus & SENSOR_ACTIVE):
192
+ offset = datagram_start + datagram_size
193
+ continue
194
+
195
+ attitude_offset = offset + numBytesInfoPart
196
+ for _ in range(numSamplesArray):
197
+ (dgmType, numBytesDgm, dgmVersion, timeFromSensor_sec, timeFromSensor_nanosec, status, latitude_deg, longitude_deg, ellipsoidHeight_m, roll_deg, pitch_deg, heading_deg, heave_m, rollRate, pitchRate, yawRate, velNorth, velEast, velDown, latitudeError_m, longitudeError_m, ellipsoidHeightError_m, rollError_deg, pitchError_deg, headingError_deg, heaveError_m, northAcceleration, eastAcceleration, downAcceleration) = struct.unpack_from("<4sHHIII2d21f",buffer, attitude_offset)
198
+ (delayedHeave_time_sec, delayedHeave_time_nanosec, delayedHeave_m) = struct.unpack_from("<IIf", buffer, attitude_offset + numBytesDgm)
199
+ attitude_offset += numBytesPerSample
200
+
201
+ # Each KMbinary sample carries its own timestamp; the SKM header time is only that of the first sample
202
+ epoch_microseconds = timeFromSensor_sec * 1000000 + (timeFromSensor_nanosec // 1000)
203
+
204
+ attitude = Attitude(epoch_microseconds, math.radians(roll_deg), math.radians(pitch_deg), math.radians(heading_deg))
205
+ self.attitudes.append(attitude)
206
+
207
+ elif datagram_type in ("#SVP", "#SVT", "#SCL", "#SDE", "#SHI", "#CPO", "#CHE", "#FCF", "#SPE", "#SPD", "#IBE", "#IBR", "#IBS"):
208
+ # Known datagrams that are not used (yet)
209
+ pass
210
+ else:
211
+ sys.stderr.write(f"Unknown datagram {datagram_type}\n")
212
+
213
+ offset = datagram_start + datagram_size
mbes/LeastSquares.py ADDED
@@ -0,0 +1,18 @@
1
+ import numpy as np
2
+
3
+ class LeastSquares:
4
+ @staticmethod
5
+ def fit(points):
6
+ """Least-squares line through ordered XYZ points.
7
+ Returns the start point and the total displacement vector (first -> last, along the line)."""
8
+ pts = np.asarray(points, dtype=np.float64)
9
+ centroid = pts.mean(axis=0)
10
+ _, _, vt = np.linalg.svd(pts - centroid, full_matrices=False)
11
+ direction = vt[0] # unit vector along the best-fit line
12
+
13
+ t = (pts - centroid) @ direction # each point's position along the line
14
+ if t[-1] < t[0]: # orient it from the first point to the last
15
+ direction, t = -direction, -t
16
+ start = centroid + t[0] * direction
17
+ end = centroid + t[-1] * direction
18
+ return start, end - start
mbes/MbesReader.py ADDED
@@ -0,0 +1,113 @@
1
+ import os
2
+ import sys
3
+ import pandas as pd
4
+ import numpy as np
5
+
6
+ from mbes.KmallReader import KmallReader
7
+ from mbes.S7kReader import S7kReader
8
+ from mbes.AllReader import AllReader
9
+ from mbes.XtfReader import XtfReader
10
+
11
+ from mbes.Interpolator import Interpolator, InterpolationError
12
+ from mbes.Georeferencing import Georeferencing
13
+
14
+ class MbesReader:
15
+
16
+ def read(self,filename, offset=None, boresight=np.identity(3)):
17
+ filename_components = os.path.splitext(filename)
18
+
19
+ reader = False;
20
+
21
+ if filename_components[1] =='.kmall':
22
+ reader = KmallReader()
23
+ elif filename_components[1] =='.s7k':
24
+ reader = S7kReader()
25
+ elif filename_components[1] =='.all':
26
+ reader = AllReader()
27
+ elif filename_components[1] =='.xtf':
28
+ reader = XtfReader()
29
+ else:
30
+ raise ValueError(f"Unknown file extension {filename_components[1]}\n")
31
+
32
+ # Read file
33
+ reader.read(filename)
34
+
35
+ sys.stderr.write(f"{len(reader.positions)} positions\n")
36
+ sys.stderr.write(f"{len(reader.attitudes)} attitudes\n")
37
+ sys.stderr.write(f"{len(reader.pings)} pings\n")
38
+
39
+ # Interpolate time-series
40
+ if not reader.positions or not reader.attitudes or not reader.pings:
41
+ # Not enough data to georeference
42
+ sys.stderr.write("Not enough data to georeference\n")
43
+ return []
44
+
45
+ # Sonar offset re. reference point: use the installation parameters unless given explicitly
46
+ if offset is None:
47
+ offset = reader.lever_arm() if hasattr(reader, "lever_arm") else np.zeros(3)
48
+ sys.stderr.write(f"Offset (x fwd, y stbd, z down): {offset}\n")
49
+
50
+ reader.positions.sort(key=lambda x: x.timestamp)
51
+ reader.attitudes.sort(key=lambda x: x.timestamp)
52
+ reader.pings.sort(key=lambda x: x.timestamp)
53
+
54
+ # Interpolate attitudes and positions around pings
55
+ attitude_index = 0
56
+ position_index = 0
57
+ n_att = len(reader.attitudes)
58
+ n_pos = len(reader.positions)
59
+
60
+
61
+ georeferenced_pings = []
62
+
63
+ for ping in reader.pings:
64
+ t = ping.timestamp
65
+
66
+ #print(f"Ping: {ping.timestamp} Position:{reader.positions[position_index].timestamp} Attitude: {reader.attitudes[attitude_index].timestamp}")
67
+
68
+ while attitude_index + 1 < n_att and reader.attitudes[attitude_index + 1].timestamp < t:
69
+ attitude_index += 1
70
+
71
+ # No more attitudes available
72
+ if attitude_index >= n_att - 1:
73
+ #sys.stderr.write("No more attitudes\n")
74
+ break
75
+
76
+ while position_index + 1 < n_pos and reader.positions[position_index + 1].timestamp < t:
77
+ position_index += 1
78
+
79
+ # No more positions available
80
+ if position_index >= n_pos - 1:
81
+ #sys.stderr.write("No more positions\n")
82
+ break
83
+
84
+ # No position or attitude earlier than the ping, so discard it
85
+ if reader.positions[position_index].timestamp > t or reader.attitudes[attitude_index].timestamp > t:
86
+ #print(f"rejecting ping {ping.id} {t} {reader.positions[position_index].timestamp} {reader.attitudes[attitude_index].timestamp}", file=sys.stderr)
87
+ continue
88
+
89
+ try:
90
+ interpolated_attitude = Interpolator.interpolate_attitude(reader.attitudes[attitude_index], reader.attitudes[attitude_index + 1], t)
91
+ interpolated_position = Interpolator.interpolate_position(reader.positions[position_index], reader.positions[position_index + 1], t)
92
+ except InterpolationError as e:
93
+ sys.stderr.write(f"Skipping sounding {ping.id} at {t}: {e}\n")
94
+ continue
95
+
96
+ #svp = self.svp_strategy.choose_svp(interpolated_position, ping)
97
+ svp = False #TODO
98
+ georeferenced_pings.append(Georeferencing.compute_ecef(interpolated_position, interpolated_attitude,ping, svp, offset, boresight))
99
+
100
+ # return XYZ data
101
+ return georeferenced_pings
102
+
103
+ if __name__ == "__main__":
104
+ if len(sys.argv) != 2:
105
+ sys.stderr.write("Usage: MbesReader.py sonar_file\n")
106
+ sys.exit(1)
107
+
108
+ r = MbesReader()
109
+ pings = r.read(sys.argv[1])
110
+
111
+ for p in pings:
112
+ print(f"{p[0]} {p[1]} {p[2]}")
113
+
mbes/Ping.py ADDED
@@ -0,0 +1,12 @@
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class Ping:
5
+ timestamp: int # microseconds since Unix epoch
6
+ id: int
7
+ quality: int
8
+ intensity: int
9
+ surface_sound_speed: float
10
+ two_way_travel_time: float
11
+ tilt_angle: float
12
+ beam_angle: float
mbes/Position.py ADDED
@@ -0,0 +1,13 @@
1
+ from dataclasses import dataclass
2
+
3
+ @dataclass
4
+ class Position:
5
+ timestamp: int # microseconds since Unix epoch
6
+ latitude: float # radians
7
+ longitude: float # radians
8
+ ellipsoidal_height: float # meters
9
+
10
+ def __str__(self) -> str:
11
+ return f"{self.latitude} {self.longitude} {self.ellipsoidal_height}"
12
+
13
+