File size: 10,337 Bytes
42fdfd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""Small helpers for the SOVIS dataset (MIT licence). Dependencies: numpy (+ opencv-python for drawing).

Conventions used throughout SOVIS
  * Polar sonar image: shape (n_ranges, n_beams) uint8. Row i is at range i * range_resolution
    (metres, from the transducer). Column j is beam j at bearing bearings_deg[j]. Bearings
    increase left to right; negative = port (left in the camera image), positive = starboard.
  * Fan (Cartesian) image from polar_to_fan(): sonar at the bottom centre, forward is up and
    starboard is right, as seen from above.
  * Camera image: 1725x974 crop of the 1920x1080 Blueye frame (x in [0,1725), y in [51,1025)).
"""
import struct
from functools import lru_cache
from pathlib import Path

import numpy as np

_HERE = Path(__file__).resolve().parent


# ----------------------------------------------------------------------------------- raw pings
def decode_ping(message):
    """Decode one raw Oculus SimplePingResult2 message (the `oculus_message` bytes in raw_pings).

    Returns a dict with header fields, `bearings_deg` (n_beams,) and `image` (n_ranges, n_beams) uint8.
    The image section starts at `image_offset` (2048 in SOVIS), after the header and bearing table.
    """
    m = memoryview(message)
    oid, _, _, msg_id, version, _, _ = struct.unpack_from("<HHHHHIH", m, 0)
    if oid != 0x4F53 or msg_id != 0x23 or version != 2:
        raise ValueError("not an Oculus SimplePingResult2 message")
    master_mode, ping_rate, network_speed, gamma, flags = struct.unpack_from("<5B", m, 16)
    range_setting, gain, speed_of_sound_setting, salinity = struct.unpack_from("<4d", m, 21)
    ping_id, status = struct.unpack_from("<II", m, 89)
    (frequency, temperature, pressure, heading, pitch, roll, speed_of_sound_used,
     ping_start_time) = struct.unpack_from("<8d", m, 97)
    data_size, = struct.unpack_from("<B", m, 161)
    range_resolution, = struct.unpack_from("<d", m, 162)
    n_ranges, n_beams = struct.unpack_from("<HH", m, 170)
    image_offset, image_size, message_size = struct.unpack_from("<III", m, 190)
    if data_size != 0 or flags & 0x04:
        raise ValueError("only 8-bit images without per-row gain are handled (SOVIS uses these)")
    bearings = np.frombuffer(message, "<i2", count=n_beams, offset=202) / 100.0
    image = np.frombuffer(message, np.uint8, count=n_ranges * n_beams, offset=image_offset)
    return dict(master_mode=master_mode, ping_rate=ping_rate, gamma=gamma, flags=flags,
                range_setting_m=range_setting, gain_percent=gain, salinity=salinity, ping_id=ping_id,
                status=status, frequency_hz=frequency, temperature_c=temperature, pressure_bar=pressure,
                heading_deg=heading, pitch_deg=pitch, roll_deg=roll, speed_of_sound_used=speed_of_sound_used,
                ping_start_time=ping_start_time, range_resolution=range_resolution, n_ranges=n_ranges,
                n_beams=n_beams, image_offset=image_offset, message_size=message_size,
                bearings_deg=bearings, image=image.reshape(n_ranges, n_beams))


@lru_cache(maxsize=None)
def _bearing_table():
    return np.genfromtxt(_HERE.parent / "calibration" / "sonar_bearings.csv", delimiter=",", names=True)


def sonar_bearings(mode):
    """Bearing (deg) of each of the 256 beams for sonar_mode 1 (750 kHz) or 2 (1.2 MHz)."""
    return np.array(_bearing_table()[f"mode{mode}_deg"], dtype=np.float64)


# ----------------------------------------------------------------------------------- geometry
def fan_width(size, max_range_m, bearings_deg):
    """Width (pixels) of the fan image polar_to_fan() draws for these settings."""
    scale = (size - 1) / max_range_m
    return int(np.ceil(2 * max_range_m * np.sin(np.radians(np.abs(bearings_deg).max())) * scale)) + 1


def fan_xy(bearing_deg, range_m, size, width, max_range_m):
    """Pixel (x, y) in a polar_to_fan() image of a point at (bearing, range)."""
    scale = (size - 1) / max_range_m
    a = np.radians(bearing_deg)
    return (width - 1) / 2 + range_m * np.sin(a) * scale, size - 1 - range_m * np.cos(a) * scale


@lru_cache(maxsize=16)
def _fan_maps(bearings_bytes, range_resolution, n_ranges, size, max_range_m):
    bearings_deg = np.frombuffer(bearings_bytes, np.float64)
    width = fan_width(size, max_range_m, bearings_deg)
    scale = (size - 1) / max_range_m                        # pixels per metre
    ys, xs = np.mgrid[0:size, 0:width].astype(np.float32)
    east = (xs - (width - 1) / 2) / scale
    north = (size - 1 - ys) / scale
    r = np.hypot(east, north)
    theta = np.degrees(np.arctan2(east, north))
    map_y = (r / range_resolution).astype(np.float32)
    map_x = np.interp(theta, bearings_deg, np.arange(len(bearings_deg))).astype(np.float32)
    valid = (theta >= bearings_deg[0]) & (theta <= bearings_deg[-1]) & (map_y <= n_ranges - 1) & (r <= max_range_m)
    for a in (map_x, map_y, valid):
        a.setflags(write=False)                             # shared by every call with these settings
    return map_x, map_y, valid


def polar_to_fan(polar, bearings_deg, range_resolution, size=512, max_range_m=None):
    """Render a polar image as a top-down fan. Returns (fan uint8 (size, width), valid mask bool).

    The remap grids are cached per (bearings, resolution, n_ranges, size, max range)."""
    import cv2
    n_ranges = polar.shape[0]
    max_range_m = max_range_m or n_ranges * range_resolution
    map_x, map_y, valid = _fan_maps(np.asarray(bearings_deg, np.float64).tobytes(), float(range_resolution),
                                    n_ranges, size, float(max_range_m))
    fan = cv2.remap(np.ascontiguousarray(polar), map_x, map_y, cv2.INTER_LINEAR, borderValue=0)
    fan[~valid] = 0
    return fan, valid


def to_metric_grid(polar, range_resolution, max_range_m=7.0, bin_m=0.02):
    """Resample the range axis to fixed metric bins so pings with different settings batch together.

    Returns (grid float32 (n_bins, n_beams), valid bool (n_bins,)); bins beyond the ping's range are 0
    and marked invalid. The beam axis is left as is (use sonar_bearings() for the angles).
    """
    centres = (np.arange(int(round(max_range_m / bin_m))) + 0.5) * bin_m
    src = centres / range_resolution
    valid = src <= polar.shape[0] - 1
    idx = np.clip(src, 0, polar.shape[0] - 1)
    i0 = np.floor(idx).astype(int)
    i1 = np.minimum(i0 + 1, polar.shape[0] - 1)
    w = (idx - i0).astype(np.float32)[:, None]
    p = polar.astype(np.float32)
    grid = (1 - w) * p[i0] + w * p[i1]
    grid[~valid] = 0
    return grid, valid


def camera_x_to_bearing(x, hfov_deg=80.0, cx=920.0, k=0.1):
    """Approximate sonar bearing (deg) of a camera column x (pixels in the 1725-wide crop).

    The model from the SOVIS annotation tool is theta = hfov/2 * xn * (1 + k (1 - xn^2)), with
    xn = (x - cx) / cx. The defaults were fitted to the 306 fish correspondences (median residual
    ~1.6 deg). It ignores the camera-sonar baseline (parallax) and the camera tilt, so treat it as a
    horizontal guide rather than a calibration.
    """
    xn = (np.asarray(x, dtype=np.float64) - cx) / cx
    return hfov_deg / 2 * xn * (1 + k * (1 - xn ** 2))


# Sonar acoustic centre (S, centre of the transducer face) in the body frame C: origin at the camera's
# optical centre, x forward, y starboard, z down (metres). See README "Sensor frames".
SONAR_IN_CAMERA_M = (0.01, 0.0, 0.37)


def sonar_to_camera(bearing_deg, range_m, camera_tilt_deg, elevation_deg=0.0, sonar_tilt_deg=0.0):
    """Sonar return -> OpenCV camera coordinates (x right, y down, z forward; metres).

    A return is known by bearing and range only; its elevation lies somewhere within the vertical
    aperture (about +-10 deg at 750 kHz, +-6 deg at 1.2 MHz; positive up). camera_tilt_deg and
    sonar_tilt_deg are positive up. Project with your own intrinsics, e.g. u = fx * x / z + cx.
    """
    b, e = np.radians(bearing_deg), np.radians(np.asarray(elevation_deg) + sonar_tilt_deg)
    t = np.radians(camera_tilt_deg)
    r = np.asarray(range_m, dtype=np.float64)
    x = r * np.cos(e) * np.cos(b) + SONAR_IN_CAMERA_M[0]          # body frame C
    y = r * np.cos(e) * np.sin(b) + SONAR_IN_CAMERA_M[1]
    z = -r * np.sin(e) + SONAR_IN_CAMERA_M[2]
    forward = np.cos(t) * x - np.sin(t) * z                         # into the tilted camera
    down = np.sin(t) * x + np.cos(t) * z
    return np.stack(np.broadcast_arrays(y, down, forward), axis=-1)


# ----------------------------------------------------------------------------------- physics
def seawater_sound_speed(temperature_c, depth_m, salinity_psu=33.0):
    """Mackenzie (1981) sound speed in sea water (m/s)."""
    T, D, S = temperature_c, depth_m, salinity_psu
    return (1448.96 + 4.591 * T - 5.304e-2 * T ** 2 + 2.374e-4 * T ** 3 + 1.340 * (S - 35)
            + 1.630e-2 * D + 1.675e-7 * D ** 2 - 1.025e-2 * T * (S - 35) - 7.139e-13 * T * D ** 3)


def range_scale(speed_of_sound_used, temperature_c, depth_m, salinity_psu=33.0):
    """Factor to multiply SOVIS sonar ranges by to correct for the sonar's salinity=0 setting.

    The Oculus was configured with salinity 0, so it converted echo time to range with a
    fresh-water sound speed (`sonar_speed_of_sound_mps`, ~1465 m/s). In the fjord the true speed
    is ~1490-1505 m/s, so true ranges are ~2-3 % longer than the stored rows suggest.
    """
    return seawater_sound_speed(temperature_c, depth_m, salinity_psu) / speed_of_sound_used


# ----------------------------------------------------------------------------------- batching
def collate_metric(batch, max_range_m=7.0, bin_m=0.02):
    """torch DataLoader collate_fn for SOVIS rows decoded with `with_format("numpy")` or PIL.

    Stacks camera images as uint8 (B, H, W, 3) and sonar as float32 metric grids (B, n_bins, 256)
    with a validity mask (B, n_bins).
    """
    import torch
    cams, grids, masks = [], [], []
    for row in batch:
        cams.append(np.asarray(row["camera"]))
        g, v = to_metric_grid(np.asarray(row["sonar"]), row["sonar_range_resolution_m"], max_range_m, bin_m)
        grids.append(g); masks.append(v)
    return {"camera": torch.from_numpy(np.stack(cams)), "sonar": torch.from_numpy(np.stack(grids)),
            "sonar_valid": torch.from_numpy(np.stack(masks)),
            "frame_id": [row["frame_id"] for row in batch]}