spectra-flight 0.2.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.
Files changed (106) hide show
  1. spectra_flight/__init__.py +3 -0
  2. spectra_flight/app/__init__.py +1 -0
  3. spectra_flight/app/__main__.py +43 -0
  4. spectra_flight/app/findings_panel.py +259 -0
  5. spectra_flight/app/main_window.py +361 -0
  6. spectra_flight/app/plot_panel.py +298 -0
  7. spectra_flight/app/px4_handoff.py +57 -0
  8. spectra_flight/app/signal_browser.py +183 -0
  9. spectra_flight/app/spectra_loader.py +83 -0
  10. spectra_flight/app/timeline.py +376 -0
  11. spectra_flight/app/vehicle_form.py +597 -0
  12. spectra_flight/app/window_docks.py +85 -0
  13. spectra_flight/app/window_model.py +56 -0
  14. spectra_flight/app/window_tasks.py +141 -0
  15. spectra_flight/app/window_vehicle.py +145 -0
  16. spectra_flight/app/worker.py +383 -0
  17. spectra_flight/cli.py +1006 -0
  18. spectra_flight/engine/__init__.py +1 -0
  19. spectra_flight/engine/analyzers/__init__.py +41 -0
  20. spectra_flight/engine/analyzers/_common.py +50 -0
  21. spectra_flight/engine/analyzers/base.py +280 -0
  22. spectra_flight/engine/analyzers/commands/__init__.py +13 -0
  23. spectra_flight/engine/analyzers/commands/_shared.py +59 -0
  24. spectra_flight/engine/analyzers/commands/acks.py +199 -0
  25. spectra_flight/engine/analyzers/commands/limits.py +305 -0
  26. spectra_flight/engine/analyzers/commands/modes.py +97 -0
  27. spectra_flight/engine/analyzers/commands/offboard.py +112 -0
  28. spectra_flight/engine/analyzers/commands/response.py +166 -0
  29. spectra_flight/engine/analyzers/crash/__init__.py +348 -0
  30. spectra_flight/engine/analyzers/crash/model_gap.py +493 -0
  31. spectra_flight/engine/analyzers/crash/onset.py +553 -0
  32. spectra_flight/engine/analyzers/crash/suspects.py +1615 -0
  33. spectra_flight/engine/analyzers/crash/timeline.py +168 -0
  34. spectra_flight/engine/analyzers/drag/__init__.py +549 -0
  35. spectra_flight/engine/analyzers/drag/fit.py +494 -0
  36. spectra_flight/engine/analyzers/drag/fixed_wing.py +596 -0
  37. spectra_flight/engine/analyzers/drag/grade.py +144 -0
  38. spectra_flight/engine/analyzers/drag/limits.py +54 -0
  39. spectra_flight/engine/analyzers/drag/power.py +757 -0
  40. spectra_flight/engine/analyzers/drag/samples.py +249 -0
  41. spectra_flight/engine/analyzers/drag/tilt.py +91 -0
  42. spectra_flight/engine/analyzers/drag/vertical.py +685 -0
  43. spectra_flight/engine/analyzers/model/__init__.py +719 -0
  44. spectra_flight/engine/analyzers/model/build.py +1288 -0
  45. spectra_flight/engine/analyzers/model/fit.py +1143 -0
  46. spectra_flight/engine/analyzers/model/fixed_wing.py +1393 -0
  47. spectra_flight/engine/analyzers/model/grade.py +232 -0
  48. spectra_flight/engine/analyzers/model/samples.py +330 -0
  49. spectra_flight/engine/analyzers/summary/__init__.py +108 -0
  50. spectra_flight/engine/analyzers/summary/events.py +85 -0
  51. spectra_flight/engine/analyzers/summary/flight.py +363 -0
  52. spectra_flight/engine/analyzers/summary/health.py +325 -0
  53. spectra_flight/engine/analyzers/tuning/__init__.py +11 -0
  54. spectra_flight/engine/analyzers/tuning/attitude.py +143 -0
  55. spectra_flight/engine/analyzers/tuning/limits.py +297 -0
  56. spectra_flight/engine/analyzers/tuning/loops.py +403 -0
  57. spectra_flight/engine/analyzers/tuning/noise.py +298 -0
  58. spectra_flight/engine/analyzers/tuning/oscillation.py +245 -0
  59. spectra_flight/engine/analyzers/tuning/spectrum.py +203 -0
  60. spectra_flight/engine/analyzers/tuning/step.py +307 -0
  61. spectra_flight/engine/analyzers/tuning/step_response.py +898 -0
  62. spectra_flight/engine/analyzers/tuning/tecs.py +186 -0
  63. spectra_flight/engine/analyzers/tuning/tracking.py +211 -0
  64. spectra_flight/engine/analyzers/validation/__init__.py +384 -0
  65. spectra_flight/engine/analyzers/vtol/__init__.py +29 -0
  66. spectra_flight/engine/analyzers/vtol/frames.py +202 -0
  67. spectra_flight/engine/analyzers/vtol/runner.py +294 -0
  68. spectra_flight/engine/analyzers/vtol/transition.py +564 -0
  69. spectra_flight/engine/check_selection.py +323 -0
  70. spectra_flight/engine/checks.py +379 -0
  71. spectra_flight/engine/checks_default.yaml +148 -0
  72. spectra_flight/engine/checks_fixed_wing.yaml +134 -0
  73. spectra_flight/engine/checks_vtol.yaml +225 -0
  74. spectra_flight/engine/compare.py +830 -0
  75. spectra_flight/engine/diff.py +518 -0
  76. spectra_flight/engine/export/__init__.py +290 -0
  77. spectra_flight/engine/export/curve.py +70 -0
  78. spectra_flight/engine/export/fw_physical.py +282 -0
  79. spectra_flight/engine/export/gazebo.py +1309 -0
  80. spectra_flight/engine/export/gazebo_template.sdf +92 -0
  81. spectra_flight/engine/export/matlab.py +887 -0
  82. spectra_flight/engine/export/physical.py +236 -0
  83. spectra_flight/engine/export/sih.py +435 -0
  84. spectra_flight/engine/export/vtol_physical.py +330 -0
  85. spectra_flight/engine/fifo.py +85 -0
  86. spectra_flight/engine/filters.py +25 -0
  87. spectra_flight/engine/formatting.py +72 -0
  88. spectra_flight/engine/model_file.py +684 -0
  89. spectra_flight/engine/pipeline.py +228 -0
  90. spectra_flight/engine/reader.py +176 -0
  91. spectra_flight/engine/replay.py +690 -0
  92. spectra_flight/engine/report.py +954 -0
  93. spectra_flight/engine/results.py +320 -0
  94. spectra_flight/engine/rotors.py +153 -0
  95. spectra_flight/engine/segments.py +241 -0
  96. spectra_flight/engine/signals.py +101 -0
  97. spectra_flight/engine/topic_map.py +388 -0
  98. spectra_flight/engine/validation.py +1683 -0
  99. spectra_flight/engine/validation_file.py +198 -0
  100. spectra_flight/engine/vehicle.py +176 -0
  101. spectra_flight/engine/vehicle_file.py +248 -0
  102. spectra_flight-0.2.0.dist-info/METADATA +186 -0
  103. spectra_flight-0.2.0.dist-info/RECORD +106 -0
  104. spectra_flight-0.2.0.dist-info/WHEEL +4 -0
  105. spectra_flight-0.2.0.dist-info/entry_points.txt +8 -0
  106. spectra_flight-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3 @@
1
+ """spectra-flight: PX4 flight log analysis engine and app."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1 @@
1
+ """The PySide6 app. The engine never imports this package."""
@@ -0,0 +1,43 @@
1
+ """Entry point of `spectra-flight-app [LOG]`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections.abc import Sequence
8
+
9
+ from PySide6.QtCore import QCoreApplication, QThreadPool
10
+ from PySide6.QtWidgets import QApplication, QMessageBox
11
+
12
+ from spectra_flight.app.spectra_loader import SpectraNotFound, load_spectra
13
+
14
+ EXIT_SPECTRA_MISSING = 3
15
+
16
+
17
+ def main(argv: Sequence[str] | None = None) -> int:
18
+ args = argparse.ArgumentParser(prog="spectra-flight-app", description="PX4 flight log viewer")
19
+ args.add_argument("log", nargs="?", help="a .ulg file to open")
20
+ options = args.parse_args(None if argv is None else list(argv))
21
+
22
+ app = QApplication.instance() or QApplication(sys.argv[:1])
23
+ QCoreApplication.setOrganizationName("spectra-flight")
24
+ QCoreApplication.setApplicationName("spectra-flight")
25
+ try:
26
+ load_spectra()
27
+ except SpectraNotFound as exc:
28
+ QMessageBox.critical(None, "Spectra not found", str(exc))
29
+ return EXIT_SPECTRA_MISSING
30
+
31
+ from spectra_flight.app.main_window import MainWindow
32
+
33
+ window = MainWindow()
34
+ window.show()
35
+ if options.log:
36
+ window.open_log(options.log)
37
+ code = app.exec()
38
+ QThreadPool.globalInstance().waitForDone(5000) # no pool thread may outlive the window
39
+ return code
40
+
41
+
42
+ if __name__ == "__main__":
43
+ sys.exit(main())
@@ -0,0 +1,259 @@
1
+ """FindingsPanel: the summary block and the findings tree, grouped by job."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from PySide6.QtCore import QModelIndex, Qt
6
+ from PySide6.QtCore import Signal as QtSignal
7
+ from PySide6.QtGui import QColor, QIcon, QPixmap, QResizeEvent, QStandardItem, QStandardItemModel
8
+ from PySide6.QtWidgets import (
9
+ QAbstractItemView,
10
+ QFormLayout,
11
+ QGroupBox,
12
+ QLabel,
13
+ QScrollArea,
14
+ QSizePolicy,
15
+ QTreeView,
16
+ QVBoxLayout,
17
+ QWidget,
18
+ )
19
+
20
+ from spectra_flight.engine.formatting import entry_text, limit_text, value_text
21
+ from spectra_flight.engine.results import JOBS, LEVELS, Finding, Results
22
+
23
+ COLUMNS = ("Finding", "Level", "Value", "Limit")
24
+ _LEVEL_COLORS = {"fail": "#c62828", "warning": "#e08a00", "info": "#1565c0", "pass": "#2e7d32"}
25
+ NOT_APPLICABLE = "Not applicable"
26
+ _MARKER_SIZE = 10
27
+ _SUMMARY_SHARE = 3 # the summary block takes at most 1/_SUMMARY_SHARE of the panel's height
28
+ _SUMMARY_MIN_HEIGHT = 72
29
+ TUNING_GROUPS = {
30
+ "hover": "Hover",
31
+ "cruise": "Cruise",
32
+ "transition": "Transition",
33
+ "rate": "Rate",
34
+ "attitude": "Attitude",
35
+ "velocity": "Velocity",
36
+ "position": "Position",
37
+ "tecs": "TECS",
38
+ "oscillation": "Oscillation",
39
+ "limits": "Limits",
40
+ "noise": "Noise",
41
+ }
42
+
43
+ # Within a tuning group the axes read in their natural order, then anything else (motors,
44
+ # torque); the engine's id order is alphabetical (pitch, roll, yaw).
45
+ AXIS_ORDER = ("roll", "pitch", "yaw", "north", "east", "down")
46
+
47
+
48
+ def _axis_rank(f: Finding) -> int:
49
+ for part in f.id.split(".")[2:]:
50
+ if part in AXIS_ORDER:
51
+ return AXIS_ORDER.index(part)
52
+ return len(AXIS_ORDER)
53
+
54
+
55
+ class FindingsPanel(QWidget):
56
+ """Summary form above a tree: jobs, each with its findings, failures first."""
57
+
58
+ finding_selected = QtSignal(object) # Finding
59
+
60
+ def __init__(self, parent: QWidget | None = None) -> None:
61
+ super().__init__(parent)
62
+ self._icons: dict[str, QIcon] = {}
63
+ self._items: dict[str, QStandardItem] = {} # finding id -> its first-column item
64
+
65
+ self._summary_box = QGroupBox("Summary")
66
+ self._summary_form = QFormLayout(self._summary_box)
67
+ self._summary_form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
68
+ self._summary_form.setRowWrapPolicy(QFormLayout.RowWrapPolicy.DontWrapRows)
69
+ # Many rows, so the block scrolls inside a capped height (see resizeEvent) and the
70
+ # findings tree keeps the rest of the panel.
71
+ self._summary_scroll = QScrollArea()
72
+ self._summary_scroll.setWidgetResizable(True)
73
+ self._summary_scroll.setFrameShape(QScrollArea.Shape.NoFrame)
74
+ self._summary_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
75
+ self._summary_scroll.setSizeAdjustPolicy(QScrollArea.SizeAdjustPolicy.AdjustToContents)
76
+ self._summary_scroll.setWidget(self._summary_box)
77
+ self._summary_scroll.hide()
78
+
79
+ self._model = QStandardItemModel(self)
80
+ self._model.setHorizontalHeaderLabels(list(COLUMNS))
81
+ self.tree = QTreeView()
82
+ self.tree.setModel(self._model)
83
+ self.tree.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
84
+ self.tree.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
85
+ self.tree.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
86
+ self.tree.setUniformRowHeights(True)
87
+ self.tree.setAlternatingRowColors(True)
88
+ self.tree.setTextElideMode(Qt.TextElideMode.ElideRight)
89
+ self.tree.selectionModel().currentChanged.connect(self._on_current_changed)
90
+
91
+ layout = QVBoxLayout(self)
92
+ layout.setContentsMargins(0, 0, 0, 0)
93
+ layout.addWidget(self._summary_scroll)
94
+ layout.addWidget(self.tree, 1)
95
+
96
+ def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802
97
+ super().resizeEvent(event)
98
+ self._summary_scroll.setMaximumHeight(
99
+ max(_SUMMARY_MIN_HEIGHT, self.height() // _SUMMARY_SHARE)
100
+ )
101
+
102
+ # ── Public API ───────────────────────────────────────────────────────
103
+
104
+ def set_results(self, results: Results) -> None:
105
+ self.clear()
106
+ self._fill_summary(results)
107
+ for job in JOBS:
108
+ found = [f for f in results.findings if f.job == job]
109
+ if not found:
110
+ continue
111
+ if job == "crash":
112
+ ranks = {
113
+ s["key"]: int(s["rank"])
114
+ for s in (results.crash or {}).get("suspects", ())
115
+ }
116
+
117
+ def _crash_key(f: Finding, ranks: dict[str, int] = ranks) -> tuple[int, str]:
118
+ if f.id in ("crash.status", "crash.onset"):
119
+ return (0, f.id)
120
+ if f.id.startswith("crash.suspect."):
121
+ return (ranks.get(f.id.removeprefix("crash.suspect."), 50), f.id)
122
+ if f.id == "crash.timeline":
123
+ return (100, f.id)
124
+ if f.id == "crash.ruled_out":
125
+ return (110, f.id)
126
+ return (120, f.id)
127
+
128
+ found.sort(key=_crash_key)
129
+ worst = min(found, key=lambda f: LEVELS.index(f.level)).level
130
+ else:
131
+ found.sort(key=lambda f: LEVELS.index(f.level)) # stable: failures first
132
+ worst = found[0].level
133
+ group = self._row(job.capitalize(), worst)
134
+ if job == "tuning":
135
+ self._fill_tuning(group[0], found)
136
+ else:
137
+ for f in found:
138
+ group[0].appendRow(self._finding_row(f))
139
+ self._model.appendRow(group)
140
+ if results.not_applicable:
141
+ group = self._row(NOT_APPLICABLE)
142
+ for item in results.not_applicable:
143
+ reason = item.get("reason", "")
144
+ row = self._row(f"{item['analyzer']}: {reason}", tooltip=reason)
145
+ group[0].appendRow(row)
146
+ self._model.appendRow(group)
147
+ self.tree.expandAll()
148
+ for column in range(len(COLUMNS)):
149
+ self.tree.resizeColumnToContents(column)
150
+
151
+ def first_needing_attention(self) -> Finding | None:
152
+ """First failure in display order, else the first warning; None when there is neither."""
153
+ findings: list[Finding] = []
154
+
155
+ def walk(parent: QModelIndex) -> None:
156
+ for r in range(self._model.rowCount(parent)):
157
+ index = self._model.index(r, 0, parent)
158
+ data = index.data(Qt.ItemDataRole.UserRole)
159
+ if isinstance(data, Finding):
160
+ findings.append(data)
161
+ walk(index)
162
+
163
+ walk(QModelIndex())
164
+ for level in ("fail", "warning"):
165
+ for f in findings:
166
+ if f.level == level:
167
+ return f
168
+ return None
169
+
170
+ def clear(self) -> None:
171
+ self._model.removeRows(0, self._model.rowCount())
172
+ self._items.clear()
173
+ while self._summary_form.rowCount():
174
+ self._summary_form.removeRow(0)
175
+ self._summary_scroll.hide()
176
+
177
+ def select_finding(self, finding_id: str) -> bool:
178
+ """Select a finding by id (emits finding_selected); False when there is no such id."""
179
+ item = self._items.get(finding_id)
180
+ if item is None:
181
+ return False
182
+ self.tree.setCurrentIndex(item.index())
183
+ return True
184
+
185
+ # ── Building ─────────────────────────────────────────────────────────
186
+
187
+ def _finding_row(self, f: Finding) -> list[QStandardItem]:
188
+ row = self._row(f.title, f.level, value_text(f), limit_text(f), f.detail)
189
+ row[0].setData(f, Qt.ItemDataRole.UserRole)
190
+ self._items[f.id] = row[0]
191
+ return row
192
+
193
+ def _fill_tuning(self, job_item: QStandardItem, found: list[Finding]) -> None:
194
+ """Tuning findings under one group per loop (the id's second part), then loose ones."""
195
+ by_part: dict[str, list[Finding]] = {}
196
+ loose: list[Finding] = []
197
+ for f in found: # already failures first
198
+ parts = f.id.split(".")
199
+ if len(parts) > 2:
200
+ by_part.setdefault(parts[1], []).append(f)
201
+ else:
202
+ loose.append(f)
203
+ known = [p for p in TUNING_GROUPS if p in by_part]
204
+ others = sorted(p for p in by_part if p not in TUNING_GROUPS)
205
+ for part in known + others:
206
+ # failures first, then axes in natural order; stable, so ids order the rest
207
+ members = sorted(by_part[part], key=lambda f: (LEVELS.index(f.level), _axis_rank(f)))
208
+ title = TUNING_GROUPS.get(part, part.capitalize())
209
+ group = self._row(title, members[0].level)
210
+ for f in members:
211
+ group[0].appendRow(self._finding_row(f))
212
+ job_item.appendRow(group)
213
+ for f in loose:
214
+ job_item.appendRow(self._finding_row(f))
215
+
216
+ def _fill_summary(self, results: Results) -> None:
217
+ for entry in results.summary.values():
218
+ value = QLabel(entry_text(entry))
219
+ value.setWordWrap(True) # a long "not checked" list wraps instead of widening the panel
220
+ value.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred)
221
+ value.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
222
+ self._summary_form.addRow(f"{entry['label']}:", value)
223
+ self._summary_scroll.setVisible(bool(results.summary))
224
+
225
+ def _marker(self, level: str) -> QIcon:
226
+ icon = self._icons.get(level)
227
+ if icon is None:
228
+ pixmap = QPixmap(_MARKER_SIZE, _MARKER_SIZE)
229
+ pixmap.fill(QColor(_LEVEL_COLORS[level]))
230
+ icon = self._icons[level] = QIcon(pixmap)
231
+ return icon
232
+
233
+ def _row(
234
+ self,
235
+ title: str,
236
+ level: str | None = None,
237
+ value: str = "",
238
+ limit: str = "",
239
+ tooltip: str = "",
240
+ ) -> list[QStandardItem]:
241
+ """One tree row; the level word sits next to its colored marker, never color alone."""
242
+ cells = [QStandardItem(title), QStandardItem(level or ""), QStandardItem(value)]
243
+ cells.append(QStandardItem(limit))
244
+ if level is not None:
245
+ cells[1].setIcon(self._marker(level))
246
+ for cell in cells:
247
+ cell.setEditable(False)
248
+ if tooltip:
249
+ cell.setToolTip(tooltip)
250
+ return cells
251
+
252
+ # ── Selection ────────────────────────────────────────────────────────
253
+
254
+ def _on_current_changed(self, current: QModelIndex, _previous: QModelIndex) -> None:
255
+ if not current.isValid():
256
+ return
257
+ finding = current.siblingAtColumn(0).data(Qt.ItemDataRole.UserRole)
258
+ if isinstance(finding, Finding):
259
+ self.finding_selected.emit(finding)
@@ -0,0 +1,361 @@
1
+ """MainWindow: findings on the left, the plots in the center, progress in the status bar."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import replace
6
+ from pathlib import Path
7
+
8
+ from PySide6.QtCore import QSettings, Qt
9
+ from PySide6.QtCore import Signal as QtSignal
10
+ from PySide6.QtGui import QAction, QDragEnterEvent, QDropEvent, QKeySequence
11
+ from PySide6.QtWidgets import (
12
+ QApplication,
13
+ QFileDialog,
14
+ QLabel,
15
+ QMainWindow,
16
+ QProgressBar,
17
+ QSplitter,
18
+ QStackedWidget,
19
+ QWidget,
20
+ )
21
+
22
+ from spectra_flight.app.findings_panel import FindingsPanel
23
+ from spectra_flight.app.plot_panel import PlotView
24
+ from spectra_flight.app.window_docks import DocksMixin
25
+ from spectra_flight.app.window_model import ModelMixin
26
+ from spectra_flight.app.window_tasks import TasksMixin
27
+ from spectra_flight.app.window_vehicle import VehicleMixin, vehicle_status
28
+ from spectra_flight.app.worker import AnalysisWorker
29
+ from spectra_flight.engine.results import (
30
+ Finding,
31
+ PlotPanel,
32
+ PlotSpec,
33
+ Results,
34
+ read_derived,
35
+ read_results,
36
+ )
37
+ from spectra_flight.engine.signals import FlightLog, Signal, parse_ref
38
+
39
+ _CHECKS_KEY = "checks_file" # QSettings: the chosen check file, "" for the built-in checks
40
+ _HINT = "Open a PX4 log with File > Open (Ctrl+O), or drop a .ulg file here."
41
+
42
+
43
+ class MainWindow(DocksMixin, TasksMixin, VehicleMixin, ModelMixin, QMainWindow):
44
+ """Open a log, list its findings, show a finding's plots at its time window.
45
+
46
+ Attributes for the docks and tools built on top of this window: `plot_view`,
47
+ `findings_panel`, `results` and `log` (None until a log is loaded). `results_loaded`
48
+ fires after the results of a log are shown; `plot_shown` after a plot is drawn.
49
+ """
50
+
51
+ results_loaded = QtSignal(object) # Results
52
+ plot_shown = QtSignal(object) # PlotSpec
53
+
54
+ def __init__(self, cache_root: Path | None = None, parent: QWidget | None = None) -> None:
55
+ super().__init__(parent)
56
+ self._cache_root = Path(cache_root) if cache_root is not None else None
57
+ self.results: Results | None = None
58
+ self.log: FlightLog | None = None
59
+ self._derived: dict[str, Signal] = {}
60
+ self._worker: AnalysisWorker | None = None
61
+ self._log_path: Path | None = None
62
+ stored = QSettings().value(_CHECKS_KEY, "", str)
63
+ self._checks_path: Path | None = Path(stored) if stored else None
64
+ self._init_vehicle()
65
+ self._init_model()
66
+ self._tasks: dict[int, tuple] = {} # tag -> (task, on_done, on_failed, on_finish)
67
+ self._task_counter = 0
68
+ self._open_generation = 0
69
+ self._plot_request = 0
70
+ self._busy_count = 0
71
+ self._closed = False
72
+
73
+ self.findings_panel = FindingsPanel()
74
+ self.plot_view = PlotView(self.resolve_signal)
75
+ self._message = QLabel(_HINT)
76
+ self._message.setAlignment(Qt.AlignmentFlag.AlignCenter)
77
+ self._message.setWordWrap(True)
78
+ self._message.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
79
+ self._center = QStackedWidget()
80
+ self._center.addWidget(self.plot_view)
81
+ self._center.addWidget(self._message)
82
+ self._center.setCurrentWidget(self._message)
83
+
84
+ self.splitter = QSplitter(Qt.Orientation.Horizontal)
85
+ self.splitter.addWidget(self.findings_panel)
86
+ self.splitter.addWidget(self._center)
87
+ self.splitter.setStretchFactor(1, 1)
88
+ self.splitter.setSizes([560, 840])
89
+ self.setCentralWidget(self.splitter)
90
+
91
+ self._progress = QProgressBar()
92
+ self._progress.setRange(0, 100)
93
+ self._progress.setMaximumWidth(220)
94
+ self._progress.hide()
95
+ self.statusBar().addPermanentWidget(self._progress)
96
+
97
+ self._build_menus()
98
+ self._build_docks()
99
+ self._wire_docks()
100
+ self.findings_panel.finding_selected.connect(self.show_finding)
101
+ self.setAcceptDrops(True)
102
+ self.setWindowTitle("spectra-flight")
103
+ self.resize(1280, 800)
104
+
105
+ def _build_menus(self) -> None:
106
+ """All menus in one place; later features add their entries here."""
107
+ file_menu = self.menuBar().addMenu("&File")
108
+ self.open_action = QAction("&Open...", self)
109
+ self.open_action.setShortcut(QKeySequence.StandardKey.Open)
110
+ self.open_action.triggered.connect(self._choose_log)
111
+ file_menu.addAction(self.open_action)
112
+ self.reanalyse_action = QAction("&Re-analyse", self)
113
+ self.reanalyse_action.setShortcut(QKeySequence("F5"))
114
+ self.reanalyse_action.setEnabled(False) # until a log has been opened
115
+ self.reanalyse_action.triggered.connect(self.reanalyse)
116
+ file_menu.addAction(self.reanalyse_action)
117
+ file_menu.addSeparator()
118
+ self.checks_action = QAction("&Checks file...", self)
119
+ self.checks_action.triggered.connect(self._choose_checks)
120
+ file_menu.addAction(self.checks_action)
121
+ self.default_checks_action = QAction("Use &default checks", self)
122
+ self.default_checks_action.setEnabled(self._checks_path is not None)
123
+ self.default_checks_action.triggered.connect(lambda: self.set_checks_file(None))
124
+ file_menu.addAction(self.default_checks_action)
125
+ file_menu.addSeparator()
126
+ self._build_vehicle_menu(file_menu)
127
+ self._build_model_menu(file_menu)
128
+ file_menu.addSeparator()
129
+ quit_action = QAction("&Quit", self)
130
+ quit_action.setShortcut(QKeySequence.StandardKey.Quit)
131
+ quit_action.triggered.connect(self.close)
132
+ file_menu.addAction(quit_action)
133
+
134
+ view_menu = self.menuBar().addMenu("&View")
135
+ self.whole_flight_action = QAction("&Whole flight", self)
136
+ # Ctrl+Home, not plain Home: Home must keep moving to the first row in the findings tree.
137
+ self.whole_flight_action.setShortcut(QKeySequence("Ctrl+Home"))
138
+ self.whole_flight_action.triggered.connect(self.plot_view.fit_all)
139
+ view_menu.addAction(self.whole_flight_action)
140
+
141
+ # ── Opening a log ────────────────────────────────────────────────────
142
+
143
+ def _choose_log(self) -> None:
144
+ name, _ = QFileDialog.getOpenFileName(
145
+ self, "Open PX4 log", "", "PX4 logs (*.ulg);;All files (*)"
146
+ )
147
+ if name:
148
+ self.open_log(name)
149
+
150
+ def _choose_checks(self) -> None:
151
+ start = str(self._checks_path.parent) if self._checks_path is not None else ""
152
+ name, _ = QFileDialog.getOpenFileName(
153
+ self, "Choose a checks file", start, "Check files (*.yaml *.yml);;All files (*)"
154
+ )
155
+ if name:
156
+ self.set_checks_file(name)
157
+
158
+ @property
159
+ def checks_file(self) -> Path | None:
160
+ """The check file the analysis runs with; None for the built-in checks."""
161
+ return self._checks_path
162
+
163
+ def set_checks_file(self, path: str | Path | None) -> None:
164
+ """Use a check file (None: the built-in checks) from now on, remember it, and analyse
165
+ the open log with it. Results are cached per check file, so going back is quick."""
166
+ self._checks_path = Path(path) if path is not None else None
167
+ QSettings().setValue(_CHECKS_KEY, str(self._checks_path or ""))
168
+ self.default_checks_action.setEnabled(self._checks_path is not None)
169
+ if self._log_path is not None:
170
+ self.open_log(self._log_path)
171
+
172
+ def reanalyse(self) -> None:
173
+ """Analyse the open log again, ignoring its cached results."""
174
+ if self._log_path is not None:
175
+ self.open_log(self._log_path, use_cache=False)
176
+
177
+ def open_log(self, path: str | Path, use_cache: bool = True) -> None:
178
+ """Analyse a log in the background (or reuse its cached results), then show it."""
179
+ path = Path(path)
180
+ self._log_path = path
181
+ self.reanalyse_action.setEnabled(True)
182
+ self.mass_action.setEnabled(True)
183
+ self._open_generation += 1
184
+ generation = self._open_generation
185
+ self._stop_worker()
186
+ self.setWindowTitle(f"{path.name} - spectra-flight")
187
+ self._reset_views()
188
+ self.statusBar().showMessage(f"Analysing {path.name}...")
189
+ self._progress.setValue(0)
190
+ self._progress.show()
191
+
192
+ worker = AnalysisWorker(
193
+ self._cache_root,
194
+ self,
195
+ checks=self._checks_path,
196
+ vehicle=self._vehicle_path,
197
+ mass_kg=self.log_mass(path),
198
+ model=self._model_path,
199
+ )
200
+ self._worker = worker
201
+ worker.progress.connect(self._on_progress)
202
+ worker.finished.connect(lambda found, g=generation: self._on_analysed(g, path, found))
203
+ worker.failed.connect(lambda text, g=generation: self._on_failed(g, text))
204
+ worker.start(path, use_cache)
205
+
206
+ def _stop_worker(self) -> None:
207
+ if self._worker is not None:
208
+ self._worker.cancel()
209
+ self._worker.deleteLater()
210
+ self._worker = None
211
+
212
+ def _on_progress(self, stage: str, fraction: float) -> None:
213
+ self._progress.setValue(round(fraction * 100))
214
+ self.statusBar().showMessage(f"Analysing: {stage}")
215
+
216
+ def _on_log_loaded(self, generation: int, json_path: Path, log: FlightLog) -> None:
217
+ if generation != self._open_generation:
218
+ return
219
+ try:
220
+ self.load_results(json_path, log)
221
+ except (OSError, ValueError, KeyError) as exc:
222
+ self._on_failed(generation, f"The results file could not be read: {exc}")
223
+
224
+ def _on_failed(self, generation: int, text: str) -> None:
225
+ if generation != self._open_generation:
226
+ return
227
+ self._progress.hide()
228
+ self._reset_views()
229
+ self.statusBar().showMessage("Analysis failed")
230
+ self._show_message(f"The log could not be analysed.\n\n{text}")
231
+
232
+ def load_results(self, json_path: str | Path, log: FlightLog) -> None:
233
+ """Show a results file together with the log it was made from (also used by tests)."""
234
+ results = read_results(json_path)
235
+ derived = read_derived(json_path)
236
+ self._plot_request += 1
237
+ self.results, self.log, self._derived = results, log, derived
238
+ self.plot_view.clear()
239
+ self.findings_panel.set_results(results)
240
+ self._progress.hide()
241
+ name = Path(results.log.get("path") or "").name
242
+ if name:
243
+ self.setWindowTitle(f"{name} - spectra-flight")
244
+ checks = (results.checks or {}).get("file", "")
245
+ with_checks = f", checks: {Path(checks).name}" if checks not in ("", "default") else ""
246
+ self.statusBar().showMessage(
247
+ f"{len(results.findings)} findings{with_checks}{vehicle_status(results)}"
248
+ )
249
+ self._show_message("Select a finding to see its plots.")
250
+ self.results_loaded.emit(results)
251
+ first = self.findings_panel.first_needing_attention()
252
+ if first is not None:
253
+ self.findings_panel.select_finding(first.id)
254
+
255
+ def _reset_views(self) -> None:
256
+ self._plot_request += 1
257
+ self.results, self.log, self._derived = None, None, {}
258
+ self.plot_view.clear()
259
+ self.findings_panel.clear()
260
+ self.timeline.clear()
261
+ self.signal_browser.set_log(None)
262
+ self._update_px4_action()
263
+
264
+ def _show_message(self, text: str) -> None:
265
+ self._message.setText(text)
266
+ self._center.setCurrentWidget(self._message)
267
+
268
+ # ── Signals and lazy topic loading ───────────────────────────────────
269
+
270
+ def resolve_signal(self, ref: str) -> Signal:
271
+ """The resolver for the plot view; never loads (see run_with_topics). KeyError if absent."""
272
+ try:
273
+ kind, _topic, _multi_id, _field = parse_ref(ref)
274
+ except ValueError as exc:
275
+ raise KeyError(ref) from exc
276
+ if kind == "derived":
277
+ return self._derived[ref]
278
+ if self.log is None:
279
+ raise KeyError(ref)
280
+ return self.log.signal(ref)
281
+
282
+ # ── Showing a finding ────────────────────────────────────────────────
283
+
284
+ def _signals_unit(self, refs: list[str]) -> str:
285
+ """The unit every one of the signals carries, "" when they differ or one is unknown
286
+ (a log field has none; a topic not loaded yet cannot be asked)."""
287
+ units = set()
288
+ for ref in refs:
289
+ try:
290
+ units.add(self.resolve_signal(ref).unit)
291
+ except KeyError:
292
+ units.add("")
293
+ return units.pop() if len(units) == 1 else ""
294
+
295
+ def spec_for(self, finding: Finding) -> PlotSpec | None:
296
+ """The finding's plot zoomed to its window, or its signals in one panel; None if neither.
297
+ The one panel is labelled with the signals' own unit, not the finding's: a step
298
+ finding without a curve has the unit "%" over signals in rad/s, m/s or m."""
299
+ assert self.results is not None
300
+ spec = next((p for p in self.results.plots if p.id == finding.plot), None)
301
+ if spec is None and finding.signals:
302
+ unit = self._signals_unit(finding.signals)
303
+ spec = PlotSpec(
304
+ id=f"finding:{finding.id}",
305
+ job=finding.job,
306
+ title=finding.title,
307
+ panels=[PlotPanel(f"[{unit}]" if unit else "", list(finding.signals))],
308
+ )
309
+ if spec is None:
310
+ return None
311
+ return replace(spec, window=finding.window or spec.window)
312
+
313
+ def show_finding(self, finding: Finding) -> None:
314
+ if self.results is None:
315
+ return
316
+ spec = self.spec_for(finding)
317
+ if spec is None:
318
+ self.statusBar().showMessage(f"{finding.title}: no plot for this finding")
319
+ return
320
+ self._plot_request += 1
321
+ request = self._plot_request
322
+ refs = [s for panel in spec.panels for s in panel.signals]
323
+
324
+ def draw() -> None:
325
+ if request != self._plot_request:
326
+ return # another finding was selected while the topics loaded
327
+ self._center.setCurrentWidget(self.plot_view)
328
+ self.plot_view.show_plot(spec, highlight=finding.window)
329
+ self.statusBar().showMessage(finding.detail or finding.title)
330
+ self.plot_shown.emit(spec)
331
+
332
+ self.run_with_topics(refs, draw)
333
+
334
+ # ── Drag and drop, closing ───────────────────────────────────────────
335
+
336
+ @staticmethod
337
+ def _dropped_log(event: QDragEnterEvent | QDropEvent) -> Path | None:
338
+ for url in event.mimeData().urls():
339
+ path = Path(url.toLocalFile())
340
+ if url.isLocalFile() and path.suffix.lower() == ".ulg":
341
+ return path
342
+ return None
343
+
344
+ def dragEnterEvent(self, event: QDragEnterEvent) -> None: # noqa: N802
345
+ if self._dropped_log(event) is not None:
346
+ event.acceptProposedAction()
347
+
348
+ def dropEvent(self, event: QDropEvent) -> None: # noqa: N802
349
+ path = self._dropped_log(event)
350
+ if path is not None:
351
+ event.acceptProposedAction()
352
+ self.open_log(path)
353
+
354
+ def closeEvent(self, event) -> None: # noqa: ANN001, N802
355
+ self._closed = True # results of tasks still running are ignored from now on
356
+ self._open_generation += 1
357
+ self._stop_worker()
358
+ if self._busy_count > 0:
359
+ QApplication.restoreOverrideCursor()
360
+ self._busy_count = 0
361
+ super().closeEvent(event)