Skip to content

FilterReview: add auto fit for the first notch - #363

Open
j-w9 wants to merge 3 commits into
ArduPilot:mainfrom
j-w9:filter-auto-fit
Open

j-w9 wants to merge 3 commits into
ArduPilot:mainfrom
j-w9:filter-auto-fit

Conversation

@j-w9

@j-w9 j-w9 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Adds an "Auto fit" button to the first notch that sets it up from the log: ESC telemetry first, then throttle, with peak detection to verify the tracking and the noise floor setting the attenuation.

Method: the pre-filter spectrum of each FFT window in the analysis time is resampled against the tracked frequency and averaged. Noise that follows the motors adds up into peaks at multiples of the tracked frequency, and noise that doesn't is spread out.

  • ESC is rejected if the largest peak is well away from a whole multiple of the ESC frequency, with a message to check the motor poles.
  • Harmonics whose peak is at least 6 dB above the local noise floor are enabled. ATT is how far the largest one stands out, limited to 10–50 dB.
  • Rules of thumb: ESC FREQ is 80% of the lowest motor frequency seen. For throttle, REF is the mean throttle and FREQ is fitted from the peaks, and FM_RAT is lowered to keep tracking below REF. BW is FREQ/2. OPTS is a single notch per harmonic, multi-source for ESC. Throttle uses a single average throttle notch, as that is what the fit models.

These are all in one block at the top of AutoFit.js and are the main thing I'd like your view on.

Tested on six batch-logged copter logs, with estimated noise above 30 Hz:

  • On the four flights where it picked ESC, the fit matched or beat the existing hand-set notch.
  • On a ground run, it reports the ESC frequency mismatch and that throttle is zero.
  • Synthetic spectra with known peaks recover the harmonics and attenuation, and a 14/12 pole error is caught.

If the notch needs more filters than F4 boards allow (24), the result says so.

Known limitation: a fixed resonance that sits near a motor harmonic in hover can be picked up as a harmonic.

Sets up the first harmonic notch from the log. The tracking source is ESC
telemetry if logged, then per motor throttle, then average throttle.

The pre-filter spectrum of each FFT window is resampled against the
tracked frequency and averaged, so noise that follows the motors forms
peaks at multiples of the tracked frequency. This verifies the tracking:
ESC is rejected if the largest peak is well away from a whole multiple of
the motor frequency, which points to wrong motor poles. Harmonics whose
peaks stand out from the local noise floor are notched, and the
attenuation is set from how far the largest of them stands out.

Frequency and bandwidth use rules of thumb, collected at the top of
AutoFit.js.
deathnemo added a commit to deathnemo/WebTools that referenced this pull request Oct 24, 2026
)

Порядковый спектр относительно частоты ESC или газа, проверка кратности
пиков, выбор гармоник и ослабления по превышению над шумом, правила PR
без изменений; без DOM: результат и ошибки возвращаются, значения
INS_HNTCH_* собирает auto_fit_values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deathnemo added a commit to deathnemo/WebTools that referenced this pull request Oct 24, 2026
…очнение моторной частоты

find_axis_peaks: пики ищутся на X/Y/Z отдельно и сливаются ближе
max(2 Гц, 2 бина), у пика — список осей; окрестность пика без шума —
не уже главного лепестка окна Ханна (2 бина); окно шума ±50 Гц (шире
горбов гармоник, [наше]). Атрибуция: |freq/f − N| ≤ 0.1 порядка, N ≤ 8;
refine_fundamental уточняет медиану ESC/газа по пику первой гармоники.
Атрибуция по медиане — запасной способ до порядкового спектра PR ArduPilot#363
(задача 7). Тесты: слияние осей, два близких пика, −Infinity, ESC с нулевыми
оборотами, FREQ = 0, уточнение основной (12 в tunewizard-steps.test.cjs).
Дизайн, раздел 5 — новое правило атрибуции.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deathnemo added a commit to deathnemo/WebTools that referenced this pull request Oct 24, 2026
Автоподбор PR ArduPilot#363 на логе пользователя хуже текущих настроек (убирает
третью гармонику: +14/+21 дБ на 153/235 Гц, +5 дБ по полосе 20–400 Гц).
Шаг 2 оценивает несколько вариантов и рекомендует лучший, не хуже
летавшего; атрибуция пиков — по порядковому спектру. Задача 7 разбита
на 7a (ядро) и 7b (интерфейс); дефект 8 (NaN в линиях notch) — в 7a.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deathnemo added a commit to deathnemo/WebTools that referenced this pull request Oct 24, 2026
…у спектру

core/candidates.js: варианты (лог, автоподбор, их сочетания, второй notch),
оценка шума после фильтров на главных пиках и в полосе 20–400 Гц, задержка
на 10/30 Гц, выбор лучшего не хуже лога. Атрибуция пиков по порядковому
спектру PR ArduPilot#363 с медианой как запасным методом. Исправлен дефект upstream 8:
NaN в трекинге убирал среднюю линию notch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
deathnemo added a commit to deathnemo/WebTools that referenced this pull request Oct 24, 2026
…ики, .param

steps/step2.js: при первом показе — автоподбор PR ArduPilot#363, варианты notch_candidates
(+ второй notch), оценка evaluate_candidate и выбор rank_candidates; таблица
вариантов с уровнями на пиках шага 1 и пиках «после», полосами 20–400 Гц
(и с весом f²) и задержкой 10/30 Гц с разницей к логу, пометкой
«рекомендуется» и причинами отказа; вердикт «менять не нужно» / рекомендация /
неполная оценка; таблица гармоник порядкового спектра ESC.
Форма INS_GYRO_FILTER, SCHED_LOOP_RATE, INS_HNTCH_*, INS_HNTC2_* по метаданным
FilterReview (load_param_inputs): «в логе: …», .changed, выключение полей по
ENABLE, ESCMSK с версии фильтра 4, маска HMNCS 8/32 бит. «Применить вариант»,
«Подобрать заново» (варианты помечаются устаревшими при смене интервала),
«Пересчитать фильтры» (строка «Текущий»), «Сохранить/Загрузить .param»,
«Принять» → state.steps[2] и шаг 3. Графики через реестр: спектр с линиями
notch (shapes из notch_line_stats), бодэ амплитуда/фаза со свёрткой, спектрограмма
с линиями notch формы. Передаточная функция значений формы считается отдельно
(filter_transfer), FFT.H шага 1 не меняется.

Тесты: браузерный прогон шага 2; сверка с FilterReview — бодэ (обе шкалы фазы)
и оценка «после» с параметрами лога.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tridge tridge added the AIReview label Nov 9, 2026
@AP-Review

AP-Review commented Nov 9, 2026 •

Copy link
Copy Markdown

Deprecated — see below for the updated review.

Previous review (2026-11-09)

Automated review note — AI-generated (Claude+Codex), validated against the live diff. Please sanity-check before acting.
Verdict: COMMENT

Reviewed at head c46ecf4014.
Full report: https://firmware.ardupilot.org/Tools/APReview/DevCallReviews/PRReviews/ardupilot/webtools/363/1.html#prWebTools-363

The auto-fit works on synthetic spectra and lints cleanly; there are no blockers, but a few things should be fixed before it leaves draft.

Should fix

  • FilterReview/AutoFit.js:359: nothing bounds the total notch count. Multi-source × up to 8 harmonics × motors (× IMUs if EnableOnAllIMUs is kept) can exceed HAL_HNF_MAX_FILTERS, e.g. an octa with 4 harmonics gives 32 notches, so the firmware boots with "Too many notches". Count the notches and warn, or cap the harmonics.
  • FilterReview/AutoFit.js:257: the per-motor throttle fit uses the mean root thrust across motors, but the multi-source notch it enables tracks each motor separately, so the fitted FREQ is off whenever motors run at different thrust. Resample each motor's contribution against its own thrust.

Lower priority

  • FilterReview/AutoFit.js:335: calculate() and up to three fits run synchronously from the button and can take several seconds with no overlay. Wrap the fit in loading_call like the other heavy controls (index.html:472).
Minor (2)
  • FilterReview/AutoFit.js:375: the auto_fit_info label is never cleared by reset() or a failed fit, so it carries over to the next log.
  • FilterReview/AutoFit.js:321: rounding REF to 0.01 turns a near-idle mean thrust (< 0.005) into REF=0, which disables tracking while still reporting success. Keep more precision or reject it.

Throttle fits now set a single average throttle notch, matching how the
frequency is fitted, rather than a per motor notch fitted to the mean
throttle. Warn if the notch needs more filters than F4 boards allow,
reject a mean throttle that rounds REF to zero, run in the loading
overlay and clear the result text on reset or a failed fit.
@j-w9
j-w9 marked this pull request as ready for review November 9, 2026 06:26
@AP-Review

Copy link
Copy Markdown

Automated review note — AI-generated (Claude+Codex), validated against the live diff. Please sanity-check before acting.
Verdict: COMMENT

Reviewed at head 110f578cdb.
Full report: https://firmware.ardupilot.org/Tools/APReview/DevCallReviews/PRReviews/ardupilot/webtools/363/2.html#prWebTools-363

Most of the previous round is fixed at 110f578, but one new should-fix problem was found in the throttle fit, along with a couple of smaller ones. Since c46ecf4, the per-motor throttle bias, the missing loading overlay, the stale status label and REF rounding to zero are all fixed, and the notch-count warning now catches the octa case.

Should fix

  • FilterReview/AutoFit.js:159: the throttle fit's fundamental can come out 5-10% off, and its 2nd/3rd harmonics then get dropped. The candidate only has to be a maximum within ±10 bins, but its excess uses the highest point within ±10% of its position, so a nearby noise maximum borrows the real peak's height. On a synthetic 100 Hz spectrum this gave FREQ 105 and HMNCS 3 instead of 7. Only accept k if it is the maximum of its own peak window, or snap the position to that maximum.

Lower priority

  • Notch budget (still open): FilterReview/AutoFit.js:341 counts only logged IMUs, while the firmware multiplies by every used IMU. The check at line 400 also ignores an enabled INS_HNTC2, which the firmware adds to the same limit. A quad ESC fit with HMNCS=7, EnableOnAllIMUs and only IMU0 logged gives no warning, but needs 36 filters with 3 IMUs. Use num_gyro from INS_GYRx_ID and add the second notch's count.
Minor (2)
  • FilterReview/AutoFit.js:353: after a valid log, loading a log that is rejected (no PARM, or no gyro data) leaves Gyro_batch in place and Auto fit enabled. Auto fit then fits the old log into the reset parameters and reports success. Disable #auto_fit in reset() and enable it after a successful load.
  • FilterReview/AutoFit.js:327: REF is rounded to 0.01 but FREQ is not rescaled. Near idle this detunes the notch, e.g. a mean of 0.006 writes REF=0.01 and the notch tracks 77 Hz for a 100 Hz peak. Keep more precision, or fit against the rounded REF.

Only take a peak that is the maximum of the window its height is
measured over, so a nearby noise maximum cannot borrow the real peak's
height. Scale FREQ to the rounded REF. Count notch filters over the IMUs
in use and include the second notch. Only enable Auto fit after a log
loads.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants