Skip to content

fix: match PIDtoolbox step response with scaled regularization and no smoothing - #241

Merged
nerdCopter merged 7 commits into
masterfrom
fix/step-response-ptb-parity
Nov 20, 2026
Merged

nerdCopter merged 7 commits into
masterfrom
fix/step-response-ptb-parity

Conversation

@nerdCopter

@nerdCopter nerdCopter commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

AI Generated pull-request

Summary

Step response differed from PIDtoolbox in two ways. Both moved Td by several ms and changed the curve shape.

  1. Regularization. wiener_deconvolution_window used |H|^2 + 1e-4 on raw FFTs. PIDtoolbox divides both spectra by their length first (PTstepcalc.m), so its term acts as 1e-4 * N^2. The unscaled term was negligible: noisy estimate, Td about 5 ms too fast. Both spectra are now scaled by 1/n (window length); the term is WIENER_REGULARIZATION.
  2. Smoothing. Two trailing 15-sample moving averages (gyro before deconvolution, and the averaged curve) delayed the trace about 7 ms each and gave a slow start before the rise. PIDtoolbox applies neither by default. Both are removed.

Also: y-axis floor is 0 when no trace is negative, so the plot origin is (0, 0). Tests from the plant definition (identity plant, first-order lag). OVERVIEW.md updated, including PIDtoolbox rounding its sample rate to 0.1 kHz (axis about 1% compressed on a 1.88 kHz log).

Effect on outputs (two EmuFlight logs, 1878 Hz)

  • Td roll/pitch/yaw, flight 1: PIDtoolbox 16.5 / 21.0 / 18.5 ms; before 18 / 27 / 19; replica of this change 17.6 / 22.4 / 19.2.
  • QC-passing windows rise about 5 to 10 times (flight 1: 149/180/308 to 1292/886/1157).
  • Optimal P labels shift. Flight 2 roll/pitch deviation +2.6%/-17.8% (Reliable) becomes -25.3%/-20.7% (FASTER, Unreliable). The gain recommendations are unchanged (about P63/D54 roll, P69/D66 pitch). The deviation thresholds were calibrated on the old output; recalibration is a separate follow-up.
  • Peak-based P:D recommendations: not re-verified beyond the peak values.

Test plan

  • cargo clippy --all-targets --all-features -- -D warnings, cargo fmt --all, cargo test
  • Release runs on two real logs; rendered step response compared with PIDtoolbox screenshots by the maintainer: shapes nearly identical
  • Optimal P threshold recalibration (follow-up)

🤖 Generated with Claude Code

https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ

Summary by CodeRabbit

  • Updates
    • Step-response calculations and averaged plots now use unsmoothed data, changing how the response curve is represented.
    • Wiener regularization is applied consistently to scaled spectra during deconvolution.
    • Plots with entirely nonnegative responses now start the y-axis at zero.
  • Documentation
    • Updated the overview to describe step-response smoothing, sample-rate calculation, plotting, and deconvolution behavior.

nerdCopter and others added 6 commits November 19, 2026 15:40
…time axis)

Both moving-average smoothers (initial gyro, post-average curve) used a
trailing window, delaying the trace and Td by (window-1)/2 samples each.
Make them centered (zero-phase) with shortened edge windows. The
start-at-zero shift now uses the raw first sample of the average.

Build response_time as i / sample_rate instead of linspace(0, 0.5, N),
which stretched the axis by up to 1 sample over the response.

Document the rule in OVERVIEW.md and AGENTS.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ
response_time used linspace(0, RESPONSE_LENGTH_S, N) with N = ceil(RESPONSE_LENGTH_S * sample_rate),
so the spacing was RESPONSE_LENGTH_S / (N - 1) instead of 1 / sample_rate. The plotted trace stretched
by up to one sample over the response (0.02 ms at 50 ms for 1878 Hz, 0.7 ms at 500 ms for 1422 Hz).
Sample i is now at i / sample_rate, matching PIDtoolbox (t = 0 : 1/lograte).

Revert the centered smoothing, which changed the default step-response output and is not part of
this fix. Document the axis in OVERVIEW.md and add a unit test of the axis.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ
Run the step-response time-axis test at 1000 Hz and 1001 Hz. At 1001 Hz
RESPONSE_LENGTH_S * sample_rate is 500.5, so the response length rounds up
and the last sample time is not a round number.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ
The test needs at least one window to pass QC, not every window.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ
… smoothing

wiener_deconvolution_window divided by |H|^2 + 1e-4 on raw FFTs. PIDtoolbox
scales both spectra by 1/N first, so its term acts as 1e-4 * N^2. The unscaled
term was negligible, giving a noisy estimate and a Td about 5 ms too fast.
Scale both spectra by 1/padded_n and move the term to WIENER_REGULARIZATION.

Remove the two trailing 15-sample moving averages (gyro before deconvolution,
and the averaged curve). They delayed the trace by about 7 ms each and
produced a slow start before the rise. PIDtoolbox applies neither by default.

Floor the step response plot y-axis at 0 when no trace is negative, so the
plot origin is (0, 0).

Add tests from the plant definition: identity plant (unit step, no delay) and
first-order lag (50% point from the closed-form step response). Update
OVERVIEW.md for regularization, smoothing, time axis and the PIDtoolbox
sample-rate rounding.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ
# Conflicts:
#	OVERVIEW.md
#	src/data_analysis/calc_step_response.rs
@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Step-response calculation now uses unsmoothed gyro data and Wiener regularization on spectra scaled by 1/n. Plotting uses unsmoothed averaged responses, updates peak labels, and sets the unified y-axis floor to zero when all responses are nonnegative.

Changes: Step-response calculation and plotting

Layer / File(s) Summary
Step-response calculation and regularization
src/constants.rs, src/data_analysis/calc_step_response.rs, OVERVIEW.md
The calculation removes gyro and moving-average smoothing, scales spectra before applying Wiener regularization, and adds tests for response timing, crossings, and regularization scaling. The overview and constant comments describe the calculation changes.
Averaged-response plotting
src/plot_functions/plot_step_response.rs, OVERVIEW.md
The plot processes averaged responses without post-averaging smoothing, updates peak labels, and uses a zero y-axis floor when the global minimum is nonnegative. The overview describes these changes.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related PRs

Merge Risk: Minimal · up to 95372

This change removes step-response smoothing and rescales the Wiener regularization to match PIDtoolbox behavior. No concrete defect was found. The Optimal P threshold recalibration is a stated follow-up, so merging carries little risk.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: step response now matches PIDtoolbox by using scaled Wiener regularization and removing smoothing. The raw summary confirms the changes to constants, calc_step_respons…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: step response now matches PIDtoolbox by using scaled Wiener regularization and removing smoothing. The raw summary confirms the changes to constants, calc_step_response.rs, plot_step_response.rs, and OVERVIEW.md. The title is specific and accurate, and it fits the stated objectives of PR #241.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 76c9d137-61da-4b3b-a777-c12ec9f8ba92
Commits

Reviewing files that changed from the base of the PR and between 820b2ac and 95372de.

Files selected for processing: 4

  • OVERVIEW.md
  • src/constants.rs
  • src/data_analysis/calc_step_response.rs
  • src/plot_functions/plot_step_response.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

Recent review details

Additional context used

Code guidelines: 1

AGENTS.md — auto-discovered
Path-based instructions: 1

Source excerpt: **OVERVIEW.md Maintenance:** For new features, add documentation in `OVERVIEW.md` at proper, appropriate locations Information should be balanced or concise; never overly verbose Align verbosity with existing documentation s...

CodeRabbit inference engine (AGENTS.md)

Files:

  • OVERVIEW.md
Learnings: 2

Common learnings

Learnt from: nerdCopter
URL: https://github.com/nerdCopter/blackbox_analyzer/pull/241

Timestamp: 2026-11-20T21:39:01.380Z
Learning: Within repository "nerdCopter/blackbox_analyzer", only for files matching one of ["src/data_analysis/calc_step_response.rs"]: In src/data_analysis/calc_step_response.rs, wiener_deconvolution_window must scale both spectra by the actual window length n, not the power-of-two padded FFT length. This makes the effective regularization on unscaled spectra WIENER_REGULARIZATION * n^2 and avoids a jump in that coefficient when the padded FFT length doubles at nearby sample rates. The inverse FFT still requires normalization by the padded transform length.
Learning: 2026-11-04T18:45:54.507Z

Learnt from: CR
Repo: nerdCopter/blackbox_analyzer PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-04T18:45:54.507Z
Learning: Source excerpt:
## Code Changes

- **All constants go in `src/constants.rs`** — no hardcoded magic numbers in function code
  - **Exception:** Axis indices (0=Roll, 1=Pitch, 2=Yaw) are managed via `src/axis_names.rs` module with `AXIS_COUNT`, `AXIS_NAMES`, and `axis_name()` function. Use these instead of creating redundant axis index constants.
  - See `src/axis_names.rs` for centralized axis naming (commit 73f8c04)

Applied to files:

  • src/constants.rs
Additional comments: 1

OVERVIEW.md: 1

339-339: Functional Correctness

The claim that the external reference uses window-length normalization is unresolved. The review comment's premise is the normalization in the specific PIDtoolbox PTstepcalc.m version used for the comparison. The inspected evidence does not contain that code. The Octave port is a derived implementation and uses padded-length normalization, but the MATLAB source was not inspected. The search returned only a DeepWiki summary without the relevant lines, and a secondhand note stating that the upstream repository is delisted.

The local window-length rule is not in dispute here. The PR objectives state that the spectra are scaled by 1/n, and this comment concerns only the attribution to PIDtoolbox. The attribution cannot be confirmed or refuted from the available sources. Resolving it requires the upstream PTstepcalc.m at the version used for the comparison, specifically its FFT normalization and regularization lines.

@nerdCopter

Copy link
Copy Markdown
Owner Author

@coderabbitai — AI generated comment

Analysis requested on PR 241, three points:

  1. wiener_deconvolution_window in src/data_analysis/calc_step_response.rs: both spectra are scaled by 1/padded_n before |H|^2 + WIENER_REGULARIZATION. Is the scaling applied consistently, and is the inverse transform normalization still correct?
  2. Removal of both moving-average smoothers: any remaining caller, constant, doc line or test that still assumes smoothing?
  3. Tests identity_plant_gives_unit_step_with_no_delay and first_order_lag_crossing_matches_plant: do they derive expected values from the plant definition, and can either pass with the old unscaled regularization?

@coderabbitai

coderabbitai Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Step response outline ==='
ast-grep outline src/data_analysis/calc_step_response.rs --items all
printf '%s\n' '=== Named functions and constants ==='
rg -n -C 4 'wiener_deconvolution_window|identity_plant_gives_unit_step_with_no_delay|first_order_lag_crossing_matches_plant|WIENER_REGULARIZATION|padded_n|calculate_step_response' src/data_analysis/calc_step_response.rs src/constants.rs
printf '%s\n' '=== Smoothing references throughout repository ==='
rg -n -i -C 2 'smooth(ing|ed|er|s)?|moving[ _-]?average|rolling[ _-]?average|running[ _-]?average|boxcar|15.sample|STEP_RESPONSE.*(AVERAGE|SMOOTH)|(AVERAGE|SMOOTH).*STEP_RESPONSE' --glob '!Cargo.lock' . || true
printf '%s\n' '=== FFT dependency and usage ==='
rg -n -C 2 'rustfft|realfft|FftPlanner|plan_fft_inverse|process\(' Cargo.toml Cargo.lock src/data_analysis/calc_step_response.rs | head -200
printf '%s\n' '=== Test and overview files ==='
fd -i 'overview|step.?response|test' -t f | head -100

Length of output: 28680


Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== FFT helper outline and source ==='
ast-grep outline src/data_analysis/fft_utils.rs --items all
cat -n src/data_analysis/fft_utils.rs | sed -n '1,220p'
printf '%s\n' '=== Deconvolution and averaging ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '68,236p'
printf '%s\n' '=== Step response processing and QC ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '237,447p'
printf '%s\n' '=== Delay and test fixtures ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '448,680p'
printf '%s\n' '=== Step response plot structure and relevant source ==='
ast-grep outline src/plot_functions/plot_step_response.rs --items all
cat -n src/plot_functions/plot_step_response.rs | sed -n '155,220p'
cat -n src/plot_functions/plot_step_response.rs | sed -n '255,370p'
printf '%s\n' '=== Constants for processing ==='
cat -n src/constants.rs | sed -n '1,100p'
printf '%s\n' '=== Overview location and smoothing references including ignored files ==='
git ls-files | rg -i 'overview|step.?response'
rg --hidden --no-ignore -n -i -C 2 'moving[ _-]?average|15.sample|post.smoothed|smoothed peak|gyro smoothing|curve smoothing|step.response.{0,50}smooth|smooth.{0,50}step.response' -g '!.git/**' . || true
printf '%s\n' '=== PR base metadata and relevant diff ==='
base="$(gh pr view 241 --repo nerdCopter/blackbox_analyzer --json baseRefOid --jq .baseRefOid 2>/dev/null || true)"
printf 'base=%s\n' "$base"
if [ -n "$base" ] && git cat-file -e "$base^{commit}" 2>/dev/null; then
  git diff "$base"...HEAD -- src/data_analysis/calc_step_response.rs src/constants.rs src/plot_functions/plot_step_response.rs | sed -n '1,300p'
fi
printf '%s\n' '=== Python numerical-library availability ==='
python -c 'import numpy; print("numpy", numpy.__version__)' 2>&1 || true

Length of output: 73209


Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Removed smoothing symbol references ==='
rg --hidden --no-ignore -n -C 2 'INITIAL_GYRO_SMOOTHING_WINDOW|POST_AVERAGING_SMOOTHING_WINDOW|moving_average_smooth_f32|moving_average_smooth_f64' -g '!.git/**' . || true
printf '%s\n' '=== Remaining plot normalization ==='
cat -n src/plot_functions/plot_step_response.rs | sed -n '179,258p'
printf '%s\n' '=== Overview step-response description ==='
cat -n OVERVIEW.md | sed -n '45,90p'
printf '%s\n' '=== Independent numerical model of test fixtures ==='
python - <<'PY'
import numpy as np
import math

f = np.float32
frame, padded, step = 2000, 2048, 125
window = (0.5 * (1 - np.cos(2 * np.pi * np.arange(frame) / (frame - 1)))).astype(np.float32)
a = f(f(1) / f(9))

def fixtures(kind):
    if kind == 'identity':
        n = 8000
        signal = np.where((np.arange(n) // 400) % 2 == 0, f(150), f(-150)).astype(np.float32)
        return signal, signal.copy()
    n = 12000
    state = 12345
    level = f(0)
    signal = np.empty(n, np.float32)
    for i in range(n):
        if i % 250 == 0:
            state = (state * 6364136223846793005 + 1442695040888963407) & ((1 << 64) - 1)
            level = f(f(f(state >> 33) / f(1 << 31) - f(0.5)) * f(600))
        signal[i] = level
    gyro = np.zeros(n, np.float32)
    y = f(0)
    for i in range(1, n):
        y = f(y + f(a * f(signal[i - 1] - y)))
        gyro[i] = y
    return signal, gyro

def crossing(r):
    indices = np.flatnonzero(r >= 0.5)
    if not len(indices):
        return float('nan')
    k = int(indices[0])
    return 0.0 if k == 0 else k - 1 + (0.5 - float(r[k-1])) / float(r[k] - r[k-1])

def model(signal, gyro, scaled):
    accepted = []
    count = (len(signal) - frame) // step + 1
    for j in range(count):
        start = j * step
        x = signal[start:start+frame]
        y = gyro[start:start+frame]
        if np.max(np.abs(x)) < 20:
            continue
        h = np.fft.rfft(x * window, n=padded)
        g = np.fft.rfft(y * window, n=padded)
        if scaled:
            h = h * f(1/padded)
            g = g * f(1/padded)
        hs = np.conj(h)
        denom = (h * hs).real + f(0.0001)
        spectrum = g * hs / denom
        impulse = np.fft.irfft(spectrum, n=padded).astype(np.float32)[:frame]
        response = np.cumsum(impulse, dtype=np.float32)[:500]
        ss = np.mean(response[200:500], dtype=np.float32)
        if not np.isfinite(ss) or abs(ss) <= 0.1:
            continue
        response = response / ss
        segment = response[200:500]
        ssmean = np.mean(segment, dtype=np.float32)
        if np.min(segment) > 0.5 and np.max(segment) < 3 and 0.75 < ssmean < 1.25:
            accepted.append(response.astype(np.float64))
    if not accepted:
        return count, 0, None
    return count, len(accepted), np.mean(accepted, axis=0)

expected = math.log(0.5) / math.log(1 - float(a))
print(f'first-order theoretical crossing={expected:.6f} samples')
for kind in ['identity', 'lag']:
    sp, gy = fixtures(kind)
    for scaled in [False, True]:
        total, passed, response = model(sp, gy, scaled)
        if response is None:
            print(kind, 'scaled' if scaled else 'old-unscaled', 'no QC-passing windows')
            continue
        cross = crossing(response)
        end = float(response[-1])
        ok = abs(end - 1) < 0.1 and cross < 2 if kind == 'identity' else abs(cross - expected) < 1.5
        shifted = response - response[0]
        ssmean = float(np.mean(shifted[200:500]))
        print(f'{kind} {"scaled" if scaled else "old-unscaled"}: QC={passed}/{total}, crossing={cross:.6f}, end={end:.6f}, asserts_pass={ok}, plot_shifted_ss_mean={ssmean:.9g}')
        if abs(ssmean) > 1e-9:
            normalized = shifted / ssmean
            print(f'  independent plot model: crossing={crossing(normalized):.6f}, peak={max(normalized):.6f}, first_10={np.array2string(normalized[:10], precision=4)}')
PY

Length of output: 19205


web_search executed:

For the Rust crate realfft version 3.4.0, are the forward and inverse FFT transforms normalized? Check the versioned crate documentation or source and describe the required scale after a forward/inverse round trip.

Length of output: 9556


@nerdCopter

1. FFT scaling

Yes. In src/data_analysis/calc_step_response.rs, Lines 161–170, both spectra use 1 / padded_n. For raw spectra H and G, the result is:

G · conj(H) / (|H|² + WIENER_REGULARIZATION · padded_n²)

The inverse normalization is also correct. realfft does not normalize either transform, and fft_inverse divides its output by padded_n. The two spectrum scale factors cancel in the transfer estimate apart from their effect on regularization; they do not replace the inverse FFT normalization. See the realfft 3.4.0 documentation.

2. Smoothing references

I found no remaining references to either removed smoothing function or constant. OVERVIEW.md describes the unsmoothed paths.

There are stale labels and comments in src/plot_functions/plot_step_response.rs:

  • Lines 291, 314, 336 and 359 say “Smoothed Peak”.
  • Lines 336 and 360 describe the response as “post-smoothed”.

The peak is now taken from the unsmoothed, shifted and normalized response. These labels and comments should be updated.

3. Plant tests

Both tests derive their timing expectations from the plant definitions. The identity test expects an immediate crossing; the lag test uses ln(0.5) / ln(1 - a), approximately 5.885 samples. The identity test’s steady-state assertion checks a normalized response, so it does not independently verify absolute gain.

Both tests can pass with the old unscaled regularization. An independent NumPy model of the fixtures, with smoothing still removed, gave:

Fixture Old unscaled crossing Scaled crossing Test limit
Identity 0.000 samples 0.000 samples < 2 samples
First-order lag 5.843 samples 5.853 samples Within 1.5 samples of 5.885

I did not run the Rust tests. The model supports the conclusion, but the exact Rust results remain to be verified.

A direct regression test could call wiener_deconvolution_window with a 64-sample unit impulse as both input and output. The expected first impulse sample is 1 / (1 + WIENER_REGULARIZATION * 64²), approximately 0.7094. The old unscaled formula gives approximately 0.9999.

Additional coverage gap: The tests stop before the plot’s final processing. In src/plot_functions/plot_step_response.rs, Lines 199–221, the plot subtracts the first response sample and then normalizes the remainder. For a near-instantaneous response, this can amplify small residuals or reject an exact constant unit response. The independent model produced a peak near 1.86 for the scaled identity fixture after this processing. A test of the final plotted response would check this path separately.

You are interacting with an AI system.

Scale the deconvolution spectra by 1/n (window length) instead of the
power-of-two padded length. Padding can double between nearby sample rates,
so the padded length made the regularization jump up to 4x between rates.
With n the term is 1e-4 * n^2 on unscaled FFTs, as in PIDtoolbox, and varies
continuously with the rate.

The step response legend said "Smoothed Peak" after the smoothers were
removed. Use "Peak".

Add a regularization test from the definition: a unit impulse as input and
output gives 1 / (1 + r n^2) at sample 0. Update OVERVIEW.md and the constant
comment.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ
@nerdCopter

Copy link
Copy Markdown
Owner Author

@coderabbitai — AI generated comment

Dispositions for the analysis reply and local findings on head 8fc25f2:

  1. FFT scaling: no change. Confirmed correct.
  2. Stale "Smoothed Peak" labels: fixed in commit 95372de ("Peak").
  3. Padded length vs window length: fixed in 95372de. The spectra are now scaled by 1/n, so the term does not jump with power-of-two padding.
  4. Tests passing with the old regularization: fixed in 95372de. New test wiener_regularization_scales_with_window_length expects 1 / (1 + r n^2) at sample 0 for a unit impulse.
  5. Plotted peak differs from the analysis peak (first-sample shift and renormalization): not changed. This predates this PR; the old output also showed 1.06 against 1.07. Tracked as open.
  6. Final plot processing not covered by a test: not changed, same path predates this PR.

Analysis requested on head 95372de: any remaining issue?

@coderabbitai

coderabbitai Bot commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Repository and pull request revisions ==='
git rev-parse HEAD
gh pr view 241 --repo nerdCopter/blackbox_analyzer --json headRefOid,baseRefOid,files,statusCheckRollup --jq '{headRefOid,baseRefOid,files:[.files[].path],checks:[.statusCheckRollup[] | {name,conclusion,status}]}' 2>&1 || true
printf '%s\n' '=== Local recent commits ==='
git log -6 --oneline
printf '%s\n' '=== Changed files from PR base ==='
base="$(gh pr view 241 --repo nerdCopter/blackbox_analyzer --json baseRefOid --jq .baseRefOid 2>/dev/null || true)"
if [ -n "$base" ] && git cat-file -e "$base^{commit}" 2>/dev/null; then
  git diff --stat "$base"...HEAD
  printf '%s\n' '=== Main analysis diff ==='
  git diff "$base"...HEAD -- src/data_analysis/calc_step_response.rs src/constants.rs
  printf '%s\n' '=== Plot and documentation diff ==='
  git diff "$base"...HEAD -- src/plot_functions/plot_step_response.rs OVERVIEW.md
else
  printf '%s\n' 'Base revision unavailable locally'
fi
printf '%s\n' '=== Step-response outline ==='
ast-grep outline src/data_analysis/calc_step_response.rs --items all
printf '%s\n' '=== Plot outline ==='
ast-grep outline src/plot_functions/plot_step_response.rs --items all
printf '%s\n' '=== Head update diff ==='
git show --stat --oneline 95372de 2>&1 || true
git show --format= --no-ext-diff 95372de -- src/data_analysis/calc_step_response.rs src/plot_functions/plot_step_response.rs OVERVIEW.md 2>&1 || true

Length of output: 45483


Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Deconvolution and FFT inverse ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '69,238p'
ast-grep outline src/data_analysis/fft_utils.rs --items all
cat -n src/data_analysis/fft_utils.rs | sed -n '1,200p'
printf '%s\n' '=== Processing and quality checks ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '239,449p'
printf '%s\n' '=== Delay and peak definitions ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '450,544p'
printf '%s\n' '=== Regression tests ==='
cat -n src/data_analysis/calc_step_response.rs | sed -n '570,680p'
printf '%s\n' '=== Plot final processing and axis ==='
cat -n src/plot_functions/plot_step_response.rs | sed -n '105,255p'
cat -n src/plot_functions/plot_step_response.rs | sed -n '690,770p'
printf '%s\n' '=== Removed smoothing references ==='
rg --hidden -n -i -C 2 'INITIAL_GYRO_SMOOTHING_WINDOW|POST_AVERAGING_SMOOTHING_WINDOW|moving_average_smooth_f32|moving_average_smooth_f64|Smoothed Peak|post.smoothed' -g '!.git/**' . || true
printf '%s\n' '=== Analysis and plot peak consumers ==='
rg -n -C 3 'find_peak_value\s*\(|average_responses\s*\(|calculate_delay_time\s*\(' src
printf '%s\n' '=== Regression test predicted values ==='
python - <<'PY'
r = 0.0001
n, padded_n = 100, 128
print('new window-scaled:', 1 / (1 + r * n * n))
print('prior padded-scaled:', 1 / (1 + r * padded_n * padded_n))
print('old unscaled:', 1 / (1 + r))
PY

Length of output: 53241


Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Peak-based recommendation path ==='
cat -n src/main.rs | sed -n '1550,1655p'
printf '%s\n' '=== Delay consumer ==='
cat -n src/main.rs | sed -n '1910,1995p'
printf '%s\n' '=== Plot extent tracking ==='
rg -n -C 3 'global_resp_min|global_resp_max' src/plot_functions/plot_step_response.rs
printf '%s\n' '=== Current PR check state ==='
gh pr view 241 --repo nerdCopter/blackbox_analyzer --json headRefOid,statusCheckRollup --jq '{headRefOid,checks:[.statusCheckRollup[] | {name,conclusion,status}]}' 2>&1 || true

Length of output: 15671


web_search executed:

Find the official PIDtoolbox PTstepcalc.m source code. For the Wiener deconvolution, does it divide each FFT spectrum by the unpadded input window length and use an FFT length equal to the window length? Quote or link the exact lines if available.

Length of output: 6193


Script executed:

#!/bin/bash
set -u
printf '%s\n' '=== Public PIDtoolbox source ==='
curl -fsSL --max-time 20 'https://raw.githubusercontent.com/bw1129/PIDtoolbox/master/PTstepcalc.m' | nl -ba | sed -n '1,240p' || true

Length of output: 424


Script executed:

#!/bin/bash
set -u
repo="bw1129/PIDtoolbox"
printf '%s\n' '=== Public PIDtoolbox default branch ==='
branch="$(gh api "repos/$repo" --jq '.default_branch' 2>/dev/null || true)"
printf 'branch=%s\n' "$branch"
if [ -n "$branch" ]; then
  printf '%s\n' '=== Matching source paths ==='
  path="$(gh api "repos/$repo/git/trees/$branch?recursive=1" --jq '.tree[] | select(.path | endswith("PTstepcalc.m")) | .path' 2>/dev/null | head -1)"
  printf 'path=%s\n' "$path"
  if [ -n "$path" ]; then
    gh api "repos/$repo/contents/$path?ref=$branch" --jq '.content' | base64 -d | nl -ba | sed -n '1,240p'
  fi
fi

Length of output: 946


@nerdCopter I found no additional confirmed defect in head 95372de.

  • Both spectra now use 1/n, and the inverse FFT still normalizes by the padded length. Correction to my earlier reply: I checked the algebra for padded-length scaling, but that did not establish parity with PIDtoolbox’s window-length convention. I could not retrieve the upstream source to verify exact parity independently.
  • The new impulse test distinguishes window-length scaling: its expected value is 0.5, versus approximately 0.379 with padded-length scaling and 0.9999 with the old unscaled formula.
  • I found no remaining references to the removed smoothers or stale “Smoothed Peak” labels.
  • The plot normalization and peak discrepancy remain as you described. I will not repeat them as new findings.

Remaining validation: The PR description notes that Optimal P thresholds need recalibration and that peak-based P:D recommendations have not been fully re-verified. I recommend checking those outputs on representative logs for this head before relying on them.

GitHub’s Test and Lint check passed. The release builds were still in progress at my last check.

If the existing follow-up does not cover final plot-processing tests, would you like a separate issue for that coverage?


Learnings added

Learnt from: nerdCopter
URL: https://github.com/nerdCopter/blackbox_analyzer/pull/241

Timestamp: 2026-11-20T21:39:00.231Z
Learning: Within repository "nerdCopter/blackbox_analyzer", only for files matching one of ["src/data_analysis/calc_step_response.rs"]: In src/data_analysis/calc_step_response.rs, wiener_deconvolution_window must scale both spectra by the actual window length n, not the power-of-two padded FFT length. This makes the effective regularization on unscaled spectra WIENER_REGULARIZATION * n^2 and avoids a jump in that coefficient when the padded FFT length doubles at nearby sample rates. The inverse FFT still requires normalization by the padded transform length.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


Learnings used

Learnt from: nerdCopter
Repo: nerdCopter/blackbox_analyzer PR: 18
File: src/data_analysis/calc_step_response.rs:0-0
Timestamp: 2025-06-03T18:01:54.978Z
Learning: The user nerdCopter prefers to defer unit testing implementation when suggested for the BlackBox_CSV_Render project.

If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@nerdCopter

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@nerdCopter
nerdCopter merged commit 0dd7187 into master Nov 20, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant