examples/a121/algo/obstacle/detector.py

examples/a121/algo/obstacle/detector.py#

  1# Copyright (c) Acconeer AB, 2023-2026
  2# All rights reserved
  3
  4from __future__ import annotations
  5
  6import numpy as np
  7
  8# Added here to force pyqtgraph to choose PySide
  9# import PySide6  # noqa: F401
 10# from PySide6.QtWidgets import QLabel, QPushButton, QVBoxLayout, QWidget
 11from PySide6.QtGui import QTransform
 12
 13import pyqtgraph as pg
 14
 15import acconeer.exptool as et
 16from acconeer.exptool import a121
 17from acconeer.exptool.a121.algo.obstacle import Detector, DetectorConfig, DetectorResult
 18
 19
 20SENSOR_IDS = [2, 3]
 21
 22
 23def main():
 24    args = a121.ExampleArgumentParser().parse_args()
 25    et.utils.config_logging(args)
 26
 27    client = a121.Client.open(**a121.get_client_args(args))
 28
 29    # Creating a list of subsweep configurations.
 30    subsweep_configurations = [
 31        a121.SubsweepConfig(
 32            start_point=24,  # ~6 cm
 33            num_points=96,
 34            step_length=1,
 35            profile=a121.Profile.PROFILE_1,
 36            hwaas=4,
 37        ),
 38        a121.SubsweepConfig(
 39            start_point=96,  # ~24 cm
 40            num_points=48,
 41            step_length=4,
 42            profile=a121.Profile.PROFILE_3,
 43            hwaas=16,
 44        ),
 45        a121.SubsweepConfig(
 46            start_point=300,  # ~75 cm
 47            num_points=48,
 48            step_length=4,
 49            profile=a121.Profile.PROFILE_3,
 50            hwaas=2,
 51        ),
 52    ]
 53
 54    # Configure the detector using multiple subsweeps
 55    detector_config = DetectorConfig(
 56        num_mean_threshold=1.5,
 57        num_std_threshold=4,
 58        subsweep_configurations=subsweep_configurations,
 59    )
 60
 61    detector = Detector(client=client, sensor_ids=SENSOR_IDS, detector_config=detector_config)
 62
 63    detector.calibrate_detector()
 64    detector.start()
 65
 66    pg_updater = PGUpdater(
 67        num_sensors=len(SENSOR_IDS),
 68        num_subsweeps=len(subsweep_configurations),
 69    )
 70
 71    pg_process = et.PGProcess(pg_updater)
 72    pg_process.start()
 73
 74    interrupt_handler = et.utils.ExampleInterruptHandler()
 75
 76    while not interrupt_handler.got_signal:
 77        # v_current = get_speed_from_some_Robot_API(), e.g ROS?
 78        # detector.update_robot_speed(v_current)
 79
 80        detector_result = detector.get_next()
 81
 82        try:
 83            pg_process.put_data(detector_result)
 84        except et.PGProccessDiedException:
 85            break
 86
 87    detector.stop()
 88
 89    print("Disconnecting...")
 90    client.close()
 91
 92
 93PLOT_HISTORY_FRAMES = 50
 94PLOT_THRESHOLDS = True
 95
 96
 97class PGUpdater:
 98    def __init__(self, num_sensors, num_subsweeps):
 99        self.num_sensors = num_sensors
100        self.num_subsweeps = num_subsweeps
101        self.obst_vel_ys = num_sensors * [np.nan * np.ones(PLOT_HISTORY_FRAMES)]
102        self.obst_dist_ys = num_sensors * [np.nan * np.ones(PLOT_HISTORY_FRAMES)]
103        self.obst_bil_ys = np.nan * np.ones(PLOT_HISTORY_FRAMES)
104        self.hist_x = np.linspace(-100, 0, PLOT_HISTORY_FRAMES)
105
106    def setup(self, win: pg.GraphicsLayout):
107        self.fftmap_plots: list[pg.PlotItem] = []
108        self.fftmap_images: list[pg.ImageItem] = []
109        self.range_hist_curves: list[pg.PlotDataItem] = []
110        self.angle_hist_curves: list[pg.PlotDataItem] = []
111
112        if PLOT_THRESHOLDS:
113            self.bin0_curves: list[pg.PlotDataItem] = []
114            self.bin0_threshold_curves: list[pg.PlotDataItem] = []
115            self.other_bins_curves: list[pg.PlotDataItem] = []
116            self.other_bins_threshold_curves: list[pg.PlotDataItem] = []
117
118        row_offset = 2 if PLOT_THRESHOLDS else 0
119
120        for i_s in range(self.num_sensors):
121            for i_ss in range(self.num_subsweeps):
122                col = i_s * self.num_subsweeps + i_ss
123                p = win.addPlot(
124                    row=0, col=col, title=f"FFT Map, sensor {SENSOR_IDS[i_s]}, subsweep {i_ss}"
125                )
126                im = pg.ImageItem(autoDownsample=True)
127                im.setLookupTable(et.utils.pg_mpl_cmap("viridis"))
128                self.fftmap_images.append(im)
129
130                p.setLabel("bottom", "Distance (cm)")
131                p.setLabel("left", "Velocity (cm/s)")
132                p.addItem(im)
133
134                self.fftmap_plots.append(p)
135
136            if PLOT_THRESHOLDS:
137                self.bin0 = pg.PlotItem(title="Zeroth velocity/angle bin")
138                self.bin0.showGrid(x=True, y=True)
139                self.bin0.setLabel("bottom", "Range (cm)")
140                self.bin0.setLabel("left", "Amplitude")
141                self.bin0.addLegend()
142
143                pen = et.utils.pg_pen_cycler(0)
144                brush = et.utils.pg_brush_cycler(0)
145                symbol_kw = {
146                    "symbol": "o",
147                    "symbolSize": 1,
148                    "symbolBrush": brush,
149                    "symbolPen": "k",
150                }
151                feat_kw = {"pen": pen, **symbol_kw}
152                self.bin0_curves += [self.bin0.plot(**feat_kw) for _ in range(self.num_subsweeps)]
153
154                pen = et.utils.pg_pen_cycler(1)
155                brush = et.utils.pg_brush_cycler(1)
156                symbol_kw = {
157                    "symbol": "o",
158                    "symbolSize": 1,
159                    "symbolBrush": brush,
160                    "symbolPen": "k",
161                }
162                feat_kw = {"pen": pen, **symbol_kw}
163                self.bin0_threshold_curves += [
164                    self.bin0.plot(**feat_kw) for _ in range(self.num_subsweeps)
165                ]
166
167                bin0_plot_legend = pg.LegendItem(offset=(0.0, 0.5))
168                bin0_plot_legend.setParentItem(self.bin0)
169                bin0_plot_legend.addItem(self.bin0_curves[0], "Sweep")
170                bin0_plot_legend.addItem(self.bin0_threshold_curves[0], "Threshold")
171
172                sublayout = win.addLayout(
173                    row=1,
174                    col=i_s * self.num_subsweeps,
175                    colspan=self.num_subsweeps,
176                )
177                sublayout.layout.setColumnStretchFactor(0, self.num_subsweeps)
178                sublayout.addItem(self.bin0, row=0, col=0)
179
180                self.other_bins = pg.PlotItem(title="Other velocity/angle bins")
181                self.other_bins.showGrid(x=True, y=True)
182                self.other_bins.setLabel("bottom", "Range (cm)")
183                self.other_bins.setLabel("left", "Amplitude")
184                self.other_bins.addLegend()
185
186                pen = et.utils.pg_pen_cycler(0)
187                brush = et.utils.pg_brush_cycler(0)
188                symbol_kw = {
189                    "symbol": "o",
190                    "symbolSize": 1,
191                    "symbolBrush": brush,
192                    "symbolPen": "k",
193                }
194                feat_kw = {"pen": pen, **symbol_kw}
195                self.other_bins_curves += [
196                    self.other_bins.plot(**feat_kw) for _ in range(self.num_subsweeps)
197                ]
198
199                pen = et.utils.pg_pen_cycler(1)
200                brush = et.utils.pg_brush_cycler(1)
201                symbol_kw = {
202                    "symbol": "o",
203                    "symbolSize": 1,
204                    "symbolBrush": brush,
205                    "symbolPen": "k",
206                }
207                feat_kw = {"pen": pen, **symbol_kw}
208                self.other_bins_threshold_curves += [
209                    self.other_bins.plot(**feat_kw) for _ in range(self.num_subsweeps)
210                ]
211
212                other_bins_plot_legend = pg.LegendItem(offset=(0.0, 0.5))
213                other_bins_plot_legend.setParentItem(self.other_bins)
214                other_bins_plot_legend.addItem(self.other_bins_curves[0], "Max Sweep")
215                other_bins_plot_legend.addItem(self.other_bins_threshold_curves[0], "Threshold")
216
217                sublayout = win.addLayout(
218                    row=2,
219                    col=i_s * self.num_subsweeps,
220                    colspan=self.num_subsweeps,
221                )
222                sublayout.layout.setColumnStretchFactor(0, self.num_subsweeps)
223                sublayout.addItem(self.other_bins, row=0, col=0)
224
225            self.angle_hist = pg.PlotItem(title="Angle/velocity history")
226            self.angle_hist.showGrid(x=True, y=True)
227            self.angle_hist.setLabel("bottom", "Time (frames)")
228            self.angle_hist.setLabel("left", "velocity (cm/s)")
229            self.angle_hist.setXRange(-100, 0)
230            self.angle_hist.addLegend()
231            self.angle_hist_curves.append(self.angle_hist.plot(symbolSize=5, symbol="o"))
232
233            sublayout = win.addLayout(
234                row=1 + row_offset,
235                col=i_s * self.num_subsweeps,
236                colspan=self.num_subsweeps,
237            )
238
239            sublayout.layout.setColumnStretchFactor(0, self.num_subsweeps)
240            sublayout.addItem(self.angle_hist, row=0, col=0)
241
242            self.range_hist = pg.PlotItem(title="Range history")
243            self.range_hist.showGrid(x=True, y=True)
244            self.range_hist.setLabel("bottom", "Time (frames)")
245            self.range_hist.setLabel("left", "Range (cm)")
246            self.range_hist.setXRange(-100, 0)
247            self.range_hist.addLegend()
248            self.range_hist_curves.append(self.range_hist.plot(symbolSize=5, symbol="o"))
249
250            sublayout = win.addLayout(
251                row=2 + row_offset,
252                col=i_s * self.num_subsweeps,
253                colspan=self.num_subsweeps,
254            )
255
256            sublayout.layout.setColumnStretchFactor(0, self.num_subsweeps)
257            sublayout.addItem(self.range_hist, row=0, col=0)
258
259    def update(self, detector_result: DetectorResult):
260        for i_s in range(self.num_sensors):
261            pr = detector_result.processor_results[SENSOR_IDS[i_s]]
262
263            for i_ss in range(self.num_subsweeps):
264                curve_idx = self.num_subsweeps * i_s + i_ss
265
266                fftmap = pr.subsweeps_extra_results[i_ss].fft_map
267                fftmap_threshold = pr.subsweeps_extra_results[i_ss].fft_map_threshold
268
269                # fftmap = 10*np.log10(fftmap)  # to dB
270
271                spf = fftmap.shape[0]
272                r = 100 * pr.subsweeps_extra_results[i_ss].r
273
274                transform = QTransform()
275                transform.translate(
276                    r[0], -100 * pr.extra_result.dv * spf / 2 - 0.5 * 100 * pr.extra_result.dv
277                )
278                transform.scale(r[1] - r[0], 100 * pr.extra_result.dv)
279
280                self.fftmap_images[curve_idx].setTransform(transform)
281
282                self.fftmap_images[curve_idx].updateImage(
283                    np.fft.fftshift(fftmap, 0).T,
284                    levels=(0, 1.05 * np.max(fftmap)),
285                )
286
287                if PLOT_THRESHOLDS:
288                    bin0 = fftmap[0, :]
289                    threshold_bin0 = fftmap_threshold[0, :]
290
291                    max_other_bins = np.max(fftmap[1:, :], axis=0)
292                    threshold_other_bins = fftmap_threshold[1, :]
293
294                    self.bin0_curves[curve_idx].setData(r, bin0)
295                    self.bin0_threshold_curves[curve_idx].setData(r, threshold_bin0)
296                    self.other_bins_curves[curve_idx].setData(r, max_other_bins)
297                    self.other_bins_threshold_curves[curve_idx].setData(r, threshold_other_bins)
298
299            v = pr.targets[0].velocity if pr.targets else np.nan
300
301            self.obst_vel_ys[i_s] = np.roll(self.obst_vel_ys[i_s], -1)
302            self.obst_vel_ys[i_s][-1] = 100 * v  # m/s -> cm/s
303
304            if np.isnan(self.obst_vel_ys[i_s]).all():
305                self.angle_hist_curves[i_s].setVisible(False)
306            else:
307                self.angle_hist_curves[i_s].setVisible(True)
308                self.angle_hist_curves[i_s].setData(
309                    self.hist_x, self.obst_vel_ys[i_s], connect="finite"
310                )
311
312            # TODO: should be known earlier
313            # r_min = min([er.r[0] for er in pr.subsweeps_extra_results])
314            # r_max = min([er.r[-1] for er in pr.subsweeps_extra_results])
315            # self.range_hist.setYRange(100*r_min, 100*r_max)
316
317            r_targets = pr.targets[0].distance if pr.targets else np.nan
318
319            self.obst_dist_ys[i_s] = np.roll(self.obst_dist_ys[i_s], -1)
320            self.obst_dist_ys[i_s][-1] = 100 * r_targets  # m -> cm
321
322            # print(f'{i_s}: r = {r_targets}, v = {v}')
323
324            if np.isnan(self.obst_dist_ys[i_s]).all():
325                self.range_hist_curves[i_s].setVisible(False)
326            else:
327                self.range_hist_curves[i_s].setVisible(True)
328                self.range_hist_curves[i_s].setData(
329                    self.hist_x, self.obst_dist_ys[i_s], connect="finite"
330                )
331
332
333if __name__ == "__main__":
334    main()

View this example on GitHub: acconeer/acconeer-python-exploration