Skip to content

fix: share one step-response builder across plot, console and report - #243

Merged
nerdCopter merged 4 commits into
masterfrom
fix/step-response-peak-parity
Nov 21, 2026
Merged

nerdCopter merged 4 commits into
masterfrom
fix/step-response-peak-parity

Conversation

@nerdCopter

@nerdCopter nerdCopter commented Nov 21, 2026 •

Copy link
Copy Markdown
Owner

AI Generated pull-request

Summary

The legend Peak and the console/report "Actual Peak" came from two different curves. The plot applied a first-sample shift and a second steady-state renormalization. The console, report and title read the raw QC average.

  • Add calc_step_response::displayed_response (average, then steady-state renormalization to mean 1.0). The plot and the P:D analysis in main.rs both call it, so every output uses one curve and one peak.
  • Drop the first-sample shift. PIDtoolbox applies none, and the shift zeroed the whole response for a plant that starts at 1.0.
  • OVERVIEW.md states that peaks are read on the unsmoothed curve.

Refs #242

Gaps left

  • Part 1 of the ticket (peak zone and Optimal P threshold recalibration) is not changed. No known-good tune set was run. The PEAK_* and TD_* constants stay.

Test plan

  • cargo clippy --all-targets --all-features -- -D warnings, cargo fmt, cargo test pass.
  • 3 new tests: identity plant keeps peak 1.0, peak follows steady-state scale (1.2 expected), empty mask and zero steady state return None.
  • 6 real logs (EmuFlight and Betaflight, 15 axes): console and report peaks identical to master on all axes; zones and P:D advice unchanged.
  • Local CodeRabbit run: 0 findings.
  • Owner review of the Step Response PNGs on fa0dba9: correct visually (owner, 2026-11-21). Combined legend peak equals report peak; with --dps the low and high legend peaks use subset masks.

Summary by CodeRabbit

  • Bug Fixes
    • Step-response averages are now plotted without shifting the first sample, and peak values are measured from the displayed, unsmoothed curve.
    • Combined, console, report, and P:D-zone peak values now use the same measurement. With --dps, low- and high-setpoint legend peaks reflect their respective response subsets.
    • P:D recommendations now identify the peak as the maximum finite displayed-response sample, rather than the first maximum after crossing the setpoint.
  • Documentation
    • Updated the overview to describe step-response plotting and peak measurement behavior.

…nd report

The plot legend peak was read after a first-sample shift and a second
renormalization, while the console, report and title read the raw QC
average. Add calc_step_response::displayed_response (average, then
steady-state renormalization to mean 1.0) and call it from the plot and
from the P:D analysis in main, so all outputs use one curve and one peak.

Drop the first-sample shift: PIDtoolbox applies none, and it zeroed the
whole response for a plant that starts at 1.0. Update OVERVIEW.md.

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

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The PR adds a shared displayed-response calculation that normalizes the averaged response without shifting its first sample. Plotting and recommendation analysis use this calculation. The overview defines displayed-response peaks, and a report test checks peak formatting.

Changes: Displayed response and peak values

Layer / File(s) Summary
Calculate and validate displayed response
src/data_analysis/calc_step_response.rs
Adds displayed_response to average masked rows and normalize by the steady-state mean without shifting the first sample. The helper returns None for invalid or out-of-tolerance results. Tests cover normalization, row selection, and rejected inputs.
Use displayed response for peaks
src/plot_functions/plot_step_response.rs, src/main.rs, OVERVIEW.md, src/report.rs
The plot and recommendation analysis use displayed_response. The overview defines peaks as the maximum finite sample of the displayed response and documents how plot, console, report, and P:D-zone peaks relate. A report test checks three-decimal peak formatting.

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

Change: Bug fix

Possibly related issues

  • Issue 242, Part 2: The PR removes the plot’s first-sample shift and uses the shared displayed response for plot and recommendation peak calculations, addressing the described mismatch. Part 1 remains unaddressed.

Possibly related PRs

  • nerdCopter/blackbox_analyzer#241: PR 241 changes step-response scaling and smoothing. Those changes affect the curve that this PR averages, normalizes, and uses to calculate peaks.
Merge Risk: Minimal · up to 50e53

This change centralizes step-response construction so the plot, console and report peaks share one displayed curve, and removes the first-sample shift. No actionable merge-blocking risk was identified.

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 a shared step-response builder used by plot, console and report. The changeset adds calc_step_response::displayed_response and switches plot_step_response, main.rs and the report test …
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 a shared step-response builder used by plot, console and report. The changeset adds calc_step_response::displayed_response and switches plot_step_response, main.rs and the report test to use it, so the title matches the main change. The 'fix:' prefix is a style note only and does not affect relevance. The title is 68 characters and one sentence, which is within a reasonable length.

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: d87a78a6-f337-47b2-be92-7af99d8637d4
Commits

Reviewing files that changed from the base of the PR and between 0dd7187 and 50e53d0.

Files selected for processing: 5

  • OVERVIEW.md
  • src/data_analysis/calc_step_response.rs
  • src/main.rs
  • src/plot_functions/plot_step_response.rs
  • src/report.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/243

Timestamp: 2026-11-21T16:04:56.605Z
Learning: Within repository "nerdCopter/blackbox_analyzer", only for files matching one of ["src/main.rs","src/plot_functions/plot_step_response.rs","src/report.rs"]: For step-response peak parity in `src/main.rs`, `src/plot_functions/plot_step_response.rs`, and `src/report.rs`, compare the console and report peak with the combined plot peak. With `--dps`, the low- and high-setpoint curves use subset masks, so their peaks may legitimately differ from the combined peak even though all curves use `displayed_response`. The plot formats peaks to two decimals; console and report use three.
Learning: 2026-11-18T18:09:05.111Z

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

- **Output parity (console, report.md, PNG titles and legends):** any value, label or recommendation shown in more than one output must come from one shared function, never from a copy in each output.
  - All outputs use the same values and the same decision rules; only presentation differs.
  - Pass data the report needs through the result structs (`StepAxisReport`, `FlightReport`); do not re-derive it in `report.rs`.
  - Console and report may be more verbose (extra fields, thresholds, reasoning). Plot titles and legends stay minimal and concise.
  - Changing one output updates the others in the same change, with a test that the report carries the shared function's text.

Applied to files:

  • src/report.rs

@nerdCopter

Copy link
Copy Markdown
Owner Author

@coderabbitai — AI generated comment

Analysis requested on these points:

  1. calc_step_response::displayed_response replaces the plot's process_response body and the raw average in main.rs. Does any caller still build a different curve for the same peak?
  2. The first-sample shift was removed. Is there a state reachable from real logs where the steady-state mean is near zero and the function returns None, and does main.rs skip the axis correctly then?
  3. The steady-state index clamp (ss_start, ss_end) is copied from the plot into the shared function. Check edge values: response length 1, length below STEADY_STATE_START_S * sample_rate, sample rate 0 (sample_rate.unwrap_or_default() in main.rs).
  4. Are the three new tests derived from the definition, and does any assertion pass for a wrong implementation?

@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Tip

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

Analysis chain

Script executed:

#!/bin/bash
printf '%s\n' '--- repository instructions ---'
for f in AGENTS.md src/AGENTS.md src/data_analysis/AGENTS.md src/plot_functions/AGENTS.md; do if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi; done
printf '\n%s\n' '--- relevant files ---'
fd -i 'step.response|overview|main\.rs' .
printf '\n%s\n' '--- source outline ---'
ast-grep outline src/data_analysis/calc_step_response.rs --items all
ast-grep outline src/main.rs --items all --match 'step|process_file|axis|sample_rate'
printf '\n%s\n' '--- symbols and callers ---'
rg -n -C 3 'displayed_response|process_response|calculate_step_response|STEADY_STATE_START_S|Actual Peak|actual_peak|step_response|Peak:' src tests OVERVIEW.md 2>/dev/null || true
printf '\n%s\n' '--- diff summary ---'
git status --short
git diff --stat origin/HEAD...HEAD 2>/dev/null || true

Length of output: 67033


Script executed:

#!/bin/bash
printf '%s\n' '--- outlines ---'
ast-grep outline src/plot_functions/plot_step_response.rs --items all
ast-grep outline src/report.rs --items all --match 'step|peak|report'
printf '\n%s\n' '--- constants ---'
cat -n src/constants.rs | sed -n '1,65p'
printf '\n%s\n' '--- averaging, calculation, and QC ---'
cat -n src/data_analysis/calc_step_response.rs | sed -n '186,449p'
printf '\n%s\n' '--- shared builder and tests ---'
cat -n src/data_analysis/calc_step_response.rs | sed -n '450,655p'
printf '\n%s\n' '--- plot handling ---'
cat -n src/plot_functions/plot_step_response.rs | sed -n '75,350p'
printf '\n%s\n' '--- main input and analysis ---'
cat -n src/main.rs | sed -n '1420,1810p'
printf '\n%s\n' '--- peak propagation and sample-rate references ---'
rg -n -C 3 'peak_values|StepAxisReport|sample_rate\s*=|sample_rate\.unwrap|sample_rate\.is_' src/main.rs src/report.rs src/plot_functions/plot_step_response.rs src/types.rs
printf '\n%s\n' '--- PR diff ---'
git diff origin/HEAD...HEAD -- src/data_analysis/calc_step_response.rs src/main.rs src/plot_functions/plot_step_response.rs OVERVIEW.md

Length of output: 94168


Script executed:

#!/bin/bash
printf '%s\n' '--- input sample rate and immutability ---'
cat -n src/main.rs | sed -n '1168,1255p'
rg -n -C 3 '\bsample_rate\b' src/main.rs | head -150
printf '\n%s\n' '--- complete None path and report construction ---'
cat -n src/main.rs | sed -n '1795,1938p'
printf '\n%s\n' '--- report peak rendering ---'
rg -n -C 8 'peak_value|step_reports|Actual Peak' src/report.rs
printf '\n%s\n' '--- plot arguments and legend flag ---'
cat -n src/main.rs | sed -n '2090,2165p'
rg -n -C 3 'show_legend|setpoint_threshold' src/main.rs src/plot_functions/plot_step_response.rs
printf '\n%s\n' '--- all peak/builder call sites ---'
rg -n -C 2 '\b(displayed_response|average_responses|find_peak_value|calculate_step_response)\s*\(' --glob '*.rs' .
printf '\n%s\n' '--- applicable nested instruction files ---'
fd -HI '^AGENTS\.md$' src tests

Length of output: 42084


@nerdCopter I checked the call paths against the repository’s output-parity guidance.

  1. Curve and peak parity: The combined plot curve and the P:D analysis use the same QC windows, mask, sample rate, builder, and peak function. The report receives that peak through StepAxisReport. With --dps, the low- and high-setpoint legend peaks use different masks, so they can differ from the combined peak. OVERVIEW.md Line 80 should distinguish the combined legend peak from those subset peaks. The plot formats peaks to two decimals; the console and report use three.

  2. Near-zero steady state: For finite QC-passed log data, I found no path to a near-zero combined steady-state mean. QC requires each steady-state value to be greater than 0.5 and its mean to be greater than 0.75 (src/data_analysis/calc_step_response.rs Line 383). If the builder nevertheless returns None, main.rs leaves the P:D peak and recommendations unset and omits that axis from step_reports. It does so silently. The plot and Optimal P paths are separate, so this does not mean the entire axis is skipped.

  3. Clamp edge cases: For any nonempty response, the clamp selects at least one in-bounds sample.

    • Length 1 selects [0..1].
    • A response shorter than STEADY_STATE_START_S * sample_rate selects its last sample. Normal calculate_step_response output is longer than this threshold for a positive sample rate.
    • A direct call with sample rate 0 selects [0..1] and can return Some if that sample is nonzero. In main.rs, unwrap_or_default() cannot supply 0 because of a missing rate: the analysis is guarded by sample_rate.is_some(). An actual Some(0.0) cannot produce a step-response result because calculate_step_response rejects it.
  4. Tests: The identity and 1.08 / 0.9 = 1.2 expectations follow the definition. The rejection assertions cover zero mean, an empty mask, and zero length. But all nonzero-mask tests use identical rows. An incorrect implementation that selects the first row instead of averaging would pass them. The tests also do not check partial masks, clamp boundaries, or output parity.

I recommend tests with distinct rows and partial masks, nonconstant values at the steady-state boundaries, and a combined plot/report parity check. I did not run tests or inspect the PNGs in this sandbox; the owner’s PNG comparison remains outstanding.


Learnings used

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

- **Before implementing a new statistical/analysis computation**, grep `src/data_analysis/` and `src/plot_functions/` for an existing implementation of the same core primitive (cross-correlation, percentile thresholding, per-row error, event/threshold-crossing counting). Reuse or extend it; if a genuinely new computation is needed, note in a code comment why the existing ones don't cover this case.
Learnt from: CR
Repo: nerdCopter/blackbox_analyzer PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-18T18:09:05.111Z
Learning: Source excerpt:
## Code Changes

- **Output parity (console, report.md, PNG titles and legends):** any value, label or recommendation shown in more than one output must come from one shared function, never from a copy in each output.
  - All outputs use the same values and the same decision rules; only presentation differs.
  - Pass data the report needs through the result structs (`StepAxisReport`, `FlightReport`); do not re-derive it in `report.rs`.
  - Console and report may be more verbose (extra fields, thresholds, reasoning). Plot titles and legends stay minimal and concise.
  - Changing one output updates the others in the same change, with a test that the report carries the shared function's text.

You are interacting with an AI system.

…d peaks in OVERVIEW

Add a test with distinct rows and partial masks so a builder that ignores
the mask or averages the wrong rows fails. OVERVIEW.md now separates the
combined legend peak from the low/high subset legend peaks used with --dps.

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

Addressed the points from your reply, head fa0dba9:

  • Curve and peak parity: valid. OVERVIEW.md and the PR body now state that only the combined legend peak equals the console and report peak. With --dps the low and high legend entries use subset masks.
  • Near-zero steady state: no change. QC bounds the steady-state mean above 0.75 for the combined mask.
  • Clamp edge cases: no change. The clamp always selects at least one in-bounds sample.
  • Tests: valid. Added displayed_response_averages_only_masked_rows with distinct rows and partial masks.

Analysis requested on the new head:

  1. Does the new test fail for an implementation that ignores the mask or averages the wrong rows?
  2. Does any other output still print a peak that is not taken from displayed_response?

@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Tip

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

Analysis chain

Script executed:

#!/bin/bash
printf '%s\n' '--- head ---'
git rev-parse HEAD
git status --short
printf '\n%s\n' '--- applicable instructions ---'
fd -HI '^AGENTS\.md$' . --exclude target --exclude .git
for f in AGENTS.md src/AGENTS.md src/data_analysis/AGENTS.md src/plot_functions/AGENTS.md; do
  if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi
done
printf '\n%s\n' '--- outlines ---'
ast-grep outline src/data_analysis/calc_step_response.rs --items all --match 'displayed_response|average_responses|find_peak_value'
ast-grep outline src/plot_functions/plot_step_response.rs --items all
ast-grep outline src/report.rs --items all --match 'report|peak|step'
printf '\n%s\n' '--- test, builder and peak call sites ---'
rg -n -C 3 '\b(displayed_response_averages_only_masked_rows|displayed_response|average_responses|find_peak_value)\s*\(' --glob '*.rs' .
printf '\n%s\n' '--- peak-related terms across source and tests ---'
rg -n -i -C 2 '\bpeak(s|ed|ing)?\b|peak[_a-z]*' src tests OVERVIEW.md 2>/dev/null || true

Length of output: 148473


Script executed:

#!/bin/bash
printf '%s\n' '--- average implementation ---'
cat -n src/data_analysis/calc_step_response.rs | sed -n '198,246p'
printf '\n%s\n' '--- builder, peak function, and tests ---'
cat -n src/data_analysis/calc_step_response.rs | sed -n '516,650p'
printf '\n%s\n' '--- plot input masks and series ---'
cat -n src/plot_functions/plot_step_response.rs | sed -n '105,300p'
printf '\n%s\n' '--- plot actual peak label ---'
cat -n src/plot_functions/plot_step_response.rs | sed -n '310,345p'
printf '\n%s\n' '--- analysis input and stored results ---'
cat -n src/main.rs | sed -n '1510,1604p'
cat -n src/main.rs | sed -n '1634,1644p'
cat -n src/main.rs | sed -n '1709,1722p'
cat -n src/main.rs | sed -n '1855,1905p'
printf '\n%s\n' '--- report and documentation ---'
cat -n src/report.rs | sed -n '228,250p'
cat -n OVERVIEW.md | sed -n '67,90p'
cat -n OVERVIEW.md | sed -n '243,255p'
printf '\n%s\n' '--- other direct response consumers ---'
rg -n -C 3 '\b(valid_stacked_responses|step_response_calculation_results|AllStepResponsePlotData|StepResponseResults)\b' src/main.rs src/plot_functions src/data_analysis/optimal_p_estimation.rs src/types.rs

Length of output: 49775


@nerdCopter I checked head fa0dba9 against the repository’s output-parity guidance.

  1. Mask test: partly effective. An implementation that averages all three rows regardless of the mask would fail: its normalized peak is approximately 1.114, not 1.0 or 1.2. But an implementation that selects only the first active row would pass. For the first mask, both selected rows normalize to a flat 1.0; for the second, only one row is selected.

    To test averaging as well as selection, give the two selected rows different normalized shapes. For example, keep their steady states at 1.0 and 2.0, but give the second row a 2.4 sample. The expected normalized value at that sample is 1.7 / 1.5 ≈ 1.133.

  2. Step-response peak outputs: I found no other step-response peak sourced from a different curve. The plot builds combined and subset curves with displayed_response at src/plot_functions/plot_step_response.rs Line 182. The console uses the same builder at src/main.rs Line 1583, and the report receives its peak through StepAxisReport. The --dps subset peaks can differ from the combined peak. Spectrum, motor, and stick peaks are separate metrics.

One documentation inconsistency remains: OVERVIEW.md Lines 86 and 254 say the peak is the first maximum after crossing the setpoint. find_peak_value instead returns the maximum finite sample in the response.

I inspected the code but did not run the tests or inspect the PNGs. The owner’s PNG comparison remains unverified.


Learnings added

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

Timestamp: 2026-11-21T16:04:55.206Z
Learning: Within repository "nerdCopter/blackbox_analyzer", only for files matching one of ["src/main.rs","src/plot_functions/plot_step_response.rs","src/report.rs"]: For step-response peak parity in `src/main.rs`, `src/plot_functions/plot_step_response.rs`, and `src/report.rs`, compare the console and report peak with the combined plot peak. With `--dps`, the low- and high-setpoint curves use subset masks, so their peaks may legitimately differ from the combined peak even though all curves use `displayed_response`. The plot formats peaks to two decimals; console and report use three.

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: CR
Repo: nerdCopter/blackbox_analyzer PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-18T18:09:05.111Z
Learning: Source excerpt:
## Code Changes

- **Output parity (console, report.md, PNG titles and legends):** any value, label or recommendation shown in more than one output must come from one shared function, never from a copy in each output.
  - All outputs use the same values and the same decision rules; only presentation differs.
  - Pass data the report needs through the result structs (`StepAxisReport`, `FlightReport`); do not re-derive it in `report.rs`.
  - Console and report may be more verbose (extra fields, thresholds, reasoning). Plot titles and legends stay minimal and concise.
  - Changing one output updates the others in the same change, with a test that the report carries the shared function's text.

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.

…efinition in OVERVIEW

The masked-row test now gives the two selected rows different shapes, so
an implementation that picks only one active row fails. OVERVIEW.md
described the peak as the first maximum after crossing 1.0, but
find_peak_value returns the maximum finite sample.

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

Analysis requested on head f66739d (changes since fa0dba9: the masked-row test now gives the two selected rows different shapes, and OVERVIEW.md describes the peak as the maximum finite sample of the displayed response):

  1. Would displayed_response_averages_only_masked_rows fail for an implementation that selects only one active row, or ignores the mask?
  2. Does any remaining text in OVERVIEW.md or src describe the peak differently from find_peak_value?
  3. Any remaining point that blocks merging this change?

@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Tip

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

Analysis chain

Script executed:

#!/bin/bash
printf '%s\n' '--- head and status ---'
git rev-parse HEAD
git status --short
printf '\n%s\n' '--- instruction file locations ---'
fd -HI '^AGENTS\.md$' . --exclude .git --exclude target
printf '\n%s\n' '--- applicable instructions ---'
for f in AGENTS.md src/AGENTS.md src/data_analysis/AGENTS.md src/plot_functions/AGENTS.md; do if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi; done
printf '\n%s\n' '--- source outlines ---'
ast-grep outline src/data_analysis/calc_step_response.rs --items all --match 'displayed_response|average_responses|find_peak_value|test'
ast-grep outline src/report.rs --items all --match 'step|report|test'
printf '\n%s\n' '--- test and helper code ---'
rg -n -C 4 'displayed_response_averages_only_masked_rows|fn displayed_response\b|fn find_peak_value\b|fn average_responses\b' src/data_analysis/calc_step_response.rs
printf '\n%s\n' '--- peak text in overview ---'
rg -n -i -C 2 '\bpeak(s|ed|ing)?\b|overshoot|maximum|maximal|highest' OVERVIEW.md
printf '\n%s\n' '--- step-response-related peak text in source ---'
rg -n -i -C 2 'first.{0,60}(peak|maximum)|peak.{0,80}(first|maximum|overshoot|setpoint|response|steady)|(?:maximum|overshoot|setpoint|response).{0,80}peak|find_peak_value|actual peak' src --glob '*.rs'
printf '\n%s\n' '--- changes since previous head ---'
git diff --stat fa0dba9 HEAD 2>&1
git diff fa0dba9 HEAD -- src/data_analysis/calc_step_response.rs OVERVIEW.md 2>&1
printf '\n%s\n' '--- changed files against base ---'
git diff --stat origin/HEAD...HEAD 2>&1

Length of output: 46521


Script executed:

#!/bin/bash
printf '%s\n' '--- averaging and displayed response ---'
cat -n src/data_analysis/calc_step_response.rs | sed -n '198,248p;520,650p'
printf '\n%s\n' '--- full PR change ---'
git diff origin/HEAD...HEAD -- src/data_analysis/calc_step_response.rs src/main.rs src/plot_functions/plot_step_response.rs OVERVIEW.md
printf '\n%s\n' '--- all step-response peak descriptions and references ---'
rg -n -i -C 2 'first.{0,80}(peak|maximum|maxima)|(?:peak|maximum|maxima).{0,80}(first|cross|smooth|transient|time)|(?:step.?response|actual peak|peak value|peak response|peak overshoot|response peak)' src OVERVIEW.md --glob '*.rs' --glob '*.md'
printf '\n%s\n' '--- report tests and peak propagation ---'
fd -i 'test|report' . --exclude .git --exclude target | head -120
rg -n -C 3 'StepAxisReport|Actual Peak|step_response|step_reports|generate_markdown_report|find_peak_value' src/report.rs src/main.rs tests 2>/dev/null | tail -240
printf '\n%s\n' '--- current PR state and checks ---'
gh pr view 243 --repo nerdCopter/blackbox_analyzer --json headRefOid,mergeStateStatus,reviewDecision,statusCheckRollup,body 2>&1

Length of output: 136472


Script executed:

#!/bin/bash
printf '%s\n' '--- report and peak references in tests and test modules ---'
rg -n -C 2 'Peak Value:|peak_value|displayed_response|StepAxisReport|generate_markdown_report' tests src --glob '*.rs' | grep -E -C 3 'test|Peak Value:|peak_value|displayed_response|StepAxisReport|generate_markdown_report' 
printf '\n%s\n' '--- report test structure ---'
ast-grep outline tests/report_filter_config_test.rs --items all
cat -n tests/report_filter_config_test.rs | sed -n '200,245p;315,360p'
printf '\n%s\n' '--- report propagation ---'
cat -n src/main.rs | sed -n '1568,1595p;1634,1643p;1855,1905p'
cat -n src/report.rs | sed -n '232,245p'
printf '\n%s\n' '--- test locations and report test modules ---'
rg -n '^\s*#\[cfg\(test\)\]|^\s*#\[test\]|Peak Value:' src/report.rs tests --glob '*.rs'

Length of output: 28799


@nerdCopter I inspected head f66739d and used the repository’s output-parity guidance and the --dps peak-parity learning.

  1. Mask test: Yes, for the stated implementations. With the first mask, the expected peak is 1.7 / 1.5 ≈ 1.133. Selecting only row 0 gives 1.0; selecting only row 1 gives 1.2. Averaging all three rows gives approximately 1.171. Each fails the assertion at src/data_analysis/calc_step_response.rs Line 631. The test checks the peak, not every response sample, so an incorrect curve with the right peak could still pass.

  2. Peak text: I found no remaining description that defines the step-response peak as the first maximum. Two small clarifications remain:

    • OVERVIEW.md Line 86 says the initial dip is not used. find_peak_value applies no time filter, so any finite sample in the first 30 ms can set the peak.
    • OVERVIEW.md Line 80 calls the report label “Actual Peak.” The report prints “Peak Value” at src/report.rs Line 241.
  3. Merge readiness: The code paths share the peak, but I found no test that checks the shared peak in the report. The repository’s output-parity guidance requires a report regression test. Add one that checks the peak from displayed_response and find_peak_value in the generated report. The owner’s PNG comparison also remains unchecked in the PR test plan.

    At the GitHub lookup, the PR reported BLOCKED with REVIEW_REQUIRED. The listed Rust CI checks passed. I did not run tests or inspect the PNGs in the sandbox.


Learnings used

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

- **Output parity (console, report.md, PNG titles and legends):** any value, label or recommendation shown in more than one output must come from one shared function, never from a copy in each output.
  - All outputs use the same values and the same decision rules; only presentation differs.
  - Pass data the report needs through the result structs (`StepAxisReport`, `FlightReport`); do not re-derive it in `report.rs`.
  - Console and report may be more verbose (extra fields, thresholds, reasoning). Plot titles and legends stay minimal and concise.
  - Changing one output updates the others in the same change, with a test that the report carries the shared function's text.
Learnt from: nerdCopter
URL: https://github.com/nerdCopter/blackbox_analyzer/pull/243

Timestamp: 2026-11-21T16:04:56.605Z
Learning: Within repository "nerdCopter/blackbox_analyzer", only for files matching one of ["src/main.rs","src/plot_functions/plot_step_response.rs","src/report.rs"]: For step-response peak parity in `src/main.rs`, `src/plot_functions/plot_step_response.rs`, and `src/report.rs`, compare the console and report peak with the combined plot peak. With `--dps`, the low- and high-setpoint curves use subset masks, so their peaks may legitimately differ from the combined peak even though all curves use `displayed_response`. The plot formats peaks to two decimals; console and report use three.

You are interacting with an AI system.

… peak wording in OVERVIEW

Add a report test that feeds the peak from displayed_response and
find_peak_value through generate_markdown_report and expects the
three-decimal value. OVERVIEW.md now names the report label "Peak Value"
and states that find_peak_value applies no time filter.

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

Addressed the points from your reply on f66739d, new head below:

  • Report parity test: added report_carries_the_shared_displayed_response_peak in src/report.rs. It feeds the peak from displayed_response and find_peak_value through generate_markdown_report and expects "Peak Value: 1.200".
  • OVERVIEW.md: the report label is now "Peak Value", and the text states that find_peak_value applies no time filter.
  • PR test plan: the owner checked the PNGs on fa0dba9 and found them correct.

Analysis requested on the new head:

  1. Does the report test cover the wiring in main.rs, or only the report formatter? State what remains untested.
  2. Any remaining point that blocks merging this change?

@coderabbitai

coderabbitai Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Tip

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

Analysis chain

Script executed:

#!/bin/bash
printf '%s\n' '--- head ---'
git rev-parse HEAD
git status --short
printf '\n%s\n' '--- instructions ---'
fd -HI '^AGENTS\.md$' . --exclude .git --exclude target
for f in AGENTS.md src/AGENTS.md src/data_analysis/AGENTS.md src/plot_functions/AGENTS.md; do
  if [ -f "$f" ]; then printf '\n--- %s ---\n' "$f"; cat "$f"; fi
done
printf '\n%s\n' '--- source outlines ---'
ast-grep outline src/report.rs --items all --match 'report_carries_the_shared_displayed_response_peak|generate_markdown_report|test'
ast-grep outline src/main.rs --items all --match 'main|process|step'
ast-grep outline src/data_analysis/calc_step_response.rs --items all --match 'displayed_response|find_peak_value'
printf '\n%s\n' '--- report test ---'
rg -n -A100 -B12 'fn report_carries_the_shared_displayed_response_peak' src/report.rs
printf '\n%s\n' '--- report formatter ---'
rg -n -C8 'Peak Value:|step_reports' src/report.rs
printf '\n%s\n' '--- production wiring ---'
rg -n -C10 'displayed_response\(|find_peak_value\(|StepAxisReport\s*\{|step_reports\.push|peak_values\[' src/main.rs
printf '\n%s\n' '--- shared builder and peak ---'
rg -n -A50 'pub fn displayed_response\(' src/data_analysis/calc_step_response.rs
rg -n -A15 'pub fn find_peak_value\(' src/data_analysis/calc_step_response.rs
printf '\n%s\n' '--- documented peak ---'
rg -n -i -C3 'Peak Value|initial dip|time filter|maximum finite|displayed response' OVERVIEW.md
printf '\n%s\n' '--- changes since previous head ---'
git diff --stat f66739d HEAD 2>&1
git diff f66739d HEAD -- src/report.rs OVERVIEW.md 2>&1
printf '\n%s\n' '--- existing integration tests ---'
rg -n -C3 'displayed_response|find_peak_value|Peak Value:|step_response|StepAxisReport' tests --glob '*.rs' 2>/dev/null | head -160 || true
printf '\n%s\n' '--- PR state and checks ---'
gh pr view 243 --repo nerdCopter/blackbox_analyzer --json headRefOid,mergeStateStatus,reviewDecision,statusCheckRollup,body 2>&1

Length of output: 37210


Script executed:

#!/bin/bash
printf '%s\n' '--- steady-state constants ---'
rg -n -C2 'STEADY_STATE_(START|END)_S|FINAL_NORMALIZED_STEADY_STATE_TOLERANCE' src/constants.rs
printf '\n%s\n' '--- test dependencies ---'
rg -n -C2 'tempfile|ndarray|\[dev-dependencies\]' Cargo.toml
printf '\n%s\n' '--- response normalization tests ---'
rg -n -A95 -B8 'displayed_response_averages_only_masked_rows|displayed_response_peak' src/data_analysis/calc_step_response.rs
printf '\n%s\n' '--- current check and review state ---'
gh pr view 243 --repo nerdCopter/blackbox_analyzer --json headRefOid,mergeStateStatus,reviewDecision,statusCheckRollup 2>&1

Length of output: 9074


@nerdCopter Thanks. I inspected head 50e53d0 and used the repository’s output-parity guidance.

  1. Test coverage: The new test covers the shared response and peak helpers through report formatting. It constructs StepAxisReport directly in src/report.rs Line 965. It does not exercise the wiring in src/main.rs Lines 1583–1590 and 1856–1895. In particular, it would not catch a regression in peak storage, axis selection, or report construction there. It also does not compare the console, report, and combined plot outputs end to end. An integration test would cover that gap, but I do not consider it a blocker for this change.

  2. Merge readiness: I found no remaining code blocker in the inspected changes. The new test satisfies the repository’s report parity test guidance. You reported that the PNG check passed on fa0dba9; I did not inspect the PNGs, and the PR checklist still shows that item as unchecked.

    At the latest GitHub lookup, the PR was BLOCKED with REVIEW_REQUIRED. Rust CI’s Test and Lint check passed; the three release builds were still in progress. Confirm the required review and checks are complete before merging. I did not run the tests locally.


Learnings used

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

- **Output parity (console, report.md, PNG titles and legends):** any value, label or recommendation shown in more than one output must come from one shared function, never from a copy in each output.
  - All outputs use the same values and the same decision rules; only presentation differs.
  - Pass data the report needs through the result structs (`StepAxisReport`, `FlightReport`); do not re-derive it in `report.rs`.
  - Console and report may be more verbose (extra fields, thresholds, reasoning). Plot titles and legends stay minimal and concise.
  - Changing one output updates the others in the same change, with a test that the report carries the shared function's text.
Learnt from: nerdCopter
URL: https://github.com/nerdCopter/blackbox_analyzer/pull/243

Timestamp: 2026-11-21T16:04:56.605Z
Learning: Within repository "nerdCopter/blackbox_analyzer", only for files matching one of ["src/main.rs","src/plot_functions/plot_step_response.rs","src/report.rs"]: For step-response peak parity in `src/main.rs`, `src/plot_functions/plot_step_response.rs`, and `src/report.rs`, compare the console and report peak with the combined plot peak. With `--dps`, the low- and high-setpoint curves use subset masks, so their peaks may legitimately differ from the combined peak even though all curves use `displayed_response`. The plot formats peaks to two decimals; console and report use three.

You are interacting with an AI system.

@nerdCopter
nerdCopter marked this pull request as ready for review November 21, 2026 17:42
@nerdCopter

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 21, 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 0898758 into master Nov 21, 2026
5 checks passed
nerdCopter added a commit that referenced this pull request Nov 23, 2026
AI Generated pull-request

Refs #242 (part 1, QC steady-state bounds). Part 2 was merged in PR
#243.

## Summary
- **QC bounds (IT 242 part 1):** with
`APPLY_INDIVIDUAL_RESPONSE_Y_CORRECTION` on (the default), each window
is divided by its own steady-state mean, so the mean check and the final
tolerance could never reject a response. Removed. The per-sample bounds
(min 0.5, max 3, as in PIDtoolbox) stay.
- **Optimal P statistics:** Td is the median of the per-window values,
with a robust spread (1.4826 x MAD / median).
- **Punch detection:** the throttle-rise window is 100 ms (was 50 ms).
The Td achievability factor is 2.0 (was 2.5).
- **Recommendation rules:** no P increase when Td is already faster than
the target. One shared function builds the Optimal text.
- **Outputs:** the Optimal P block has one order and shared value, label
and recommendation text in the console, report and legend; line
formatting differs per output (report bullets, legend minimal). New
`Flight clip` line. The skip reason is in the report.
- **Docs and tests:** README usage block equals `--help` (test).
Recommendation table documented and pinned by a test. `AGENTS.md` scope
and test rules.

## Root causes
1. Y-correction divides each window by its own steady-state mean, so
that mean is 1.0 by construction. The mean bounds and the final
tolerance tested that value. Traced on real logs: every window that
passed QC had a mean of 1.0 within 1e-4. PIDtoolbox has no mean check.
2. The plain mean and standard deviation of per-window Td followed a few
windows that fail deconvolution and return Td of 100 ms or more. The
deviation was biased high and the reliability check failed on repeatable
data.
3. A manually applied throttle rise takes 100-250 ms. The 50 ms window
found too few punches (the 5-punch gate failed on about half of the logs
checked). The wider window changes the torque ratio, so the
achievability factor needed a new value.
4. With low noise, a Td already faster than the target still got
"increase P". A faster response has no headroom by that target.

## Behavior changes (output)
- **Optimal P block order:** Recommendation, Td (median), Flight clip,
Deviation, Noise, Td source, Reliable. The legend drops `Current P=`
(the axis title shows it). The console and report keep it.
- **Td labels:** `Td (median)` in the Optimal P block. The first legend
line (`Td:` of the averaged curve) has one decimal.
- **Removed from outputs:** the window count (neighbouring windows
overlap, so it overstates the evidence).
- **New text:** `Td source: N flights, M punches, spread S%`. `Flight
clip: 218s` is the log time available to the step-response windows (the
span after `--start`/`--end` and the 3 s margins; rejected windows can
leave part unused). The flight count in `Td source` is per axis: files
that gave that axis at least one punch.
- **Recommendations (low noise):** P +5% from 0% to 30% slower than
target, P +10% beyond 30% slower (a step rounds down to whole P, so it
can be zero for a very small P). More than 15% faster: `No change
suggested, headroom possible` (headroom is not quantified). Between 15%
faster and 0%: `Current P is optimal`. Increases keep the matching D
line. The full table is in `OVERVIEW.md`.
- **Report:** a skipped axis lists the reason. Legend line width:
step-response curves are 2 px.

## Commits
| Group | Commits |
|---|---|
| QC | `cc444e9` |
| Td statistics and punch source | `f07254d`, `9ae1771`, `c112e30`
(later replaced by `2057094`), `ed3312d`, `dc7f161` |
| Recommendation rules and text | `468ac1b`, `6a903ac`, `c95f8b2`,
`5078044`, `d3fa267` |
| Output layout | `6a351da`, `eb4e870`, `2539850`, `272ebff`, `be555dd`,
`f33e24c`, `d166bfe`, `53cc9a9`, `b5dccfb`, `dbbab9d` (per-axis flight
count) |
| Docs and tests | `7738354`, `ae3ac0a`, `81bff48`, `7dbdf96`,
`b15995d`, `c512bbd`, `29a4740`, `0e6d978`, `f5b0183`, `0bb1057`,
`7771a49` |
| CI fix | `7c37a8b` (`is_multiple_of`) |

## Validation
- `cargo clippy --all-targets --all-features -- -D warnings`, `cargo fmt
--all`, full `cargo test` (513 pass), `cargo build --release`.
- New tests: median and robust spread, shared Optimal text, flight clip,
skip reason in the report, README equals `--help`, recommendation table
(22 Td zone and noise cases).
- Output checked by comparing console, report and legend before and
after each change on real logs.
- Local review: CodeRabbit CLI (2 minor findings, fixed), opencode (4
findings checked, none valid), remote Ollama (no finding). GitHub:
CodeRabbit review and analysis, findings handled in the PR thread and
comments.

## Not verified
- No independent known-good tunes. Optimal P stays experimental.
- The achievability factor is set from a limited set of logs. One value
cannot centre every aircraft.
- Peaks read about 0.035 higher than PIDtoolbox for the same data: BBA
divides each window by its mean (exact), PIDtoolbox multiplies by (2 -
mean). A residual of 0.03-0.05 on some axes is not explained.
- The punch ratio uses the largest single-sample gyro change; a
slope-based ratio is not implemented.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01KoqKWwCzFDgbyFBKx3fnAe


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Improvements**
* Optimal P results now use median-based timing and robust noise
measurements, with updated recommendations and clearer reporting of
flight duration, source counts, and analyses that could not be
performed.
* Throttle-punch detection uses a 100 ms window. Optimal P estimation
requires header metadata and at least five throttle punches in a log or
pooled group; metadata can be embedded or provided separately.
* Step-response results no longer apply the normalized-mean tolerance
check. Plot labels and recommendation details have also been updated.

* **Documentation**
* Command help and README usage guidance clarify supported log formats,
metadata requirements, and analysis options.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
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