From f794b90094077c8de8a348e5661be53ee0cd22e4 Mon Sep 17 00:00:00 2001 From: nerdCopter <56646290+nerdCopter@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:15:20 -0600 Subject: [PATCH 1/4] fix: share one displayed step-response builder across plot, console and 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 Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ --- OVERVIEW.md | 7 +- src/data_analysis/calc_step_response.rs | 80 +++++++++++++++++++- src/main.rs | 3 +- src/plot_functions/plot_step_response.rs | 96 ++++-------------------- 4 files changed, 96 insertions(+), 90 deletions(-) diff --git a/OVERVIEW.md b/OVERVIEW.md index e0ca7cb..ab7b2b7 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -71,12 +71,13 @@ All analysis parameters, thresholds, plot dimensions, and algorithmic constants * **Plot Generation (various functions in `src/plot_functions/`):** * `plot_step_response` (in `src/plot_functions/plot_step_response.rs`): Takes the results from `calculate_step_response`. * Separates the QC'd responses into "low" and "high" setpoint groups based on the `setpoint_threshold` if the `--dps` parameter (and thus `show_legend`) is provided. - * **Averaging & Final Normalization (`plot_functions::plot_step_response::process_response`):** + * **Averaging & Final Normalization (`calc_step_response::displayed_response`, shared by the plot, console and report):** * The QC'd responses (either low, high, or combined) are averaged using `calc_step_response::average_responses`. * The averaged response is not smoothed. A trailing or centered moving average would delay or blur the rise, and PIDtoolbox plots the raw average. - * The response is shifted to start at 0.0. The time axis is `i / sample_rate`, as in PIDtoolbox. - * A **final normalization** step is performed: the mean of the steady-state portion of this *averaged and shifted* response is calculated. The entire response is then divided by this mean to ensure the plotted average response aims for a steady-state of 1.0. + * No first-sample shift is applied, as in PIDtoolbox. The time axis is `i / sample_rate`. + * A **final normalization** step is performed: the mean of the steady-state portion of this *averaged* response is calculated. The entire response is then divided by this mean to ensure the plotted average response aims for a steady-state of 1.0. * The final response is only plotted if its steady-state mean (after this final normalization) is within `FINAL_NORMALIZED_STEADY_STATE_TOLERANCE` of 1.0. + * The peak is read on this unsmoothed, renormalized curve. Legend Peak, console and report "Actual Peak", and the P:D zones all use the same value. * Calculates peak value and delay time (Td) for each plotted average response using `calc_step_response::find_peak_value` and `calc_step_response::calculate_delay_time`. * **Delay Time (Td) Calculation:** The delay time is calculated as the time for the step response to reach 50% of its final value. Linear interpolation is used for precise determination of the 50% threshold crossing. A fixed offset of -1ms is applied to the calculated time (in milliseconds) before converting to seconds, and the result is constrained to be non-negative. * Generates and saves the step response plot. The y-axis floor is 0 when no trace goes below 0, so the origin is (0, 0). diff --git a/src/data_analysis/calc_step_response.rs b/src/data_analysis/calc_step_response.rs index 0bc99ff..69abb02 100644 --- a/src/data_analysis/calc_step_response.rs +++ b/src/data_analysis/calc_step_response.rs @@ -7,9 +7,9 @@ use crate::types::StepResponseResult; use crate::constants::{ APPLY_INDIVIDUAL_RESPONSE_Y_CORRECTION, ENABLE_NORMALIZED_STEADY_STATE_MEAN_CHECK, - FRAME_LENGTH_S, HIGH_AUTHORITY_SETPOINT_THRESHOLD_DEG_S, - LOW_AUTHORITY_SETPOINT_THRESHOLD_DEG_S, MOVEMENT_THRESHOLD_DEG_S, - NORMALIZED_STEADY_STATE_MAX_VAL, NORMALIZED_STEADY_STATE_MEAN_MAX, + FINAL_NORMALIZED_STEADY_STATE_TOLERANCE, FRAME_LENGTH_S, + HIGH_AUTHORITY_SETPOINT_THRESHOLD_DEG_S, LOW_AUTHORITY_SETPOINT_THRESHOLD_DEG_S, + MOVEMENT_THRESHOLD_DEG_S, NORMALIZED_STEADY_STATE_MAX_VAL, NORMALIZED_STEADY_STATE_MEAN_MAX, NORMALIZED_STEADY_STATE_MEAN_MIN, NORMALIZED_STEADY_STATE_MIN_VAL, RESPONSE_LENGTH_S, STEADY_STATE_END_S, STEADY_STATE_START_S, SUPERPOSITION_FACTOR, TUKEY_ALPHA, WIENER_REGULARIZATION, Y_CORRECTION_MIN_UNNORMALIZED_MEAN_ABS, @@ -516,6 +516,43 @@ pub fn calculate_delay_time(normalized_response: &Array1, sample_rate: f64) } } +/// Builds the response that every output shows (plot curves, legend, console, report). +/// +/// Averages the masked QC windows, then renormalizes so the steady-state mean is 1.0. +/// PIDtoolbox applies no first-sample shift, so none is applied here. +/// Returns None when no window is selected, the steady-state window is empty or has a +/// zero mean, or the result misses `FINAL_NORMALIZED_STEADY_STATE_TOLERANCE`. +pub fn displayed_response( + stacked_responses: &Array2, + mask: &Array1, + response_length_samples: usize, + sample_rate: f64, +) -> Option> { + if response_length_samples == 0 || !mask.iter().any(|&w| w > 0.0) { + return None; + } + let avg_resp = average_responses(stacked_responses, mask, response_length_samples).ok()?; + if avg_resp.is_empty() { + return None; + } + let ss_start = ((STEADY_STATE_START_S * sample_rate).floor() as usize) + .min(response_length_samples.saturating_sub(1)); + let ss_end = ((STEADY_STATE_END_S * sample_rate).ceil() as usize) + .min(response_length_samples) + .max(ss_start + 1); + let ss_mean = avg_resp.slice(s![ss_start..ss_end]).mean()?; + if ss_mean.abs() <= 1e-9 { + return None; + } + let normalized = avg_resp.mapv(|v| v / ss_mean); + let check_mean = normalized.slice(s![ss_start..ss_end]).mean()?; + if (check_mean - 1.0).abs() <= FINAL_NORMALIZED_STEADY_STATE_TOLERANCE { + Some(normalized) + } else { + None + } +} + /// Finds the peak (maximum) value in a 1D response data array. /// Returns None if the array is empty or contains no finite values. pub fn find_peak_value(response_data: &Array1) -> Option { @@ -548,6 +585,43 @@ mod tests { // 1001 Hz makes RESPONSE_LENGTH_S * rate non-integral (500.5), so the length rounds up. const TEST_SAMPLE_RATES: [f64; 2] = [1000.0, 1001.0]; + // Spec: the displayed response has steady-state mean 1.0 and keeps its own peak. + #[test] + fn displayed_response_identity_plant_is_not_zeroed() { + // A response that starts at 1.0 (instantaneous plant) must stay 1.0, not collapse to 0. + let len = 500; + let stacked = Array2::::ones((2, len)); + let mask = Array1::::ones(2); + let resp = displayed_response(&stacked, &mask, len, 1000.0).expect("response"); + assert!(resp.iter().all(|v| (v - 1.0).abs() < 1e-9)); + assert_eq!(find_peak_value(&resp), Some(1.0)); + } + + #[test] + fn displayed_response_peak_follows_steady_state_scale() { + // Steady state (t >= 0.2 s) is 0.9; one sample at 1.08 is 1.2x steady state. + let len = 500; + let mut row = vec![0.9f32; len]; + row[100] = 1.08; + let stacked = Array2::from_shape_fn((3, len), |(_, i)| row[i]); + let mask = Array1::::ones(3); + let resp = displayed_response(&stacked, &mask, len, 1000.0).expect("response"); + let peak = find_peak_value(&resp).expect("peak"); + assert!((peak - 1.2).abs() < 1e-5, "peak {peak}"); + let ss = resp.slice(s![200..500]).mean().expect("mean"); + assert!((ss - 1.0).abs() < 1e-9); + } + + #[test] + fn displayed_response_rejects_empty_mask_and_zero_steady_state() { + let len = 500; + let stacked = Array2::::zeros((2, len)); + assert!(displayed_response(&stacked, &Array1::::ones(2), len, 1000.0).is_none()); + let ones = Array2::::ones((2, len)); + assert!(displayed_response(&ones, &Array1::::zeros(2), len, 1000.0).is_none()); + assert!(displayed_response(&ones, &Array1::::ones(2), 0, 1000.0).is_none()); + } + #[test] fn response_time_axis_is_sample_index_over_rate() { for rate in TEST_SAMPLE_RATES { diff --git a/src/main.rs b/src/main.rs index f98701a..7489a24 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1580,10 +1580,11 @@ INFO: Skipping Step Response input data filtering for {input_file_str}: {reason} let response_length = response_time.len(); let mask: Array1 = Array1::ones(num_windows); - if let Ok(avg_response) = calc_step_response::average_responses( + if let Some(avg_response) = calc_step_response::displayed_response( valid_stacked_responses, &mask, response_length, + sample_rate.unwrap_or_default(), ) { // Find peak value if let Some(peak_value) = calc_step_response::find_peak_value(&avg_response) diff --git a/src/plot_functions/plot_step_response.rs b/src/plot_functions/plot_step_response.rs index fbce6b9..0397703 100644 --- a/src/plot_functions/plot_step_response.rs +++ b/src/plot_functions/plot_step_response.rs @@ -1,6 +1,6 @@ // src/plot_functions/plot_step_response.rs -use ndarray::{s, Array1, Array2}; +use ndarray::{Array1, Array2}; use plotters::style::RGBColor; use std::error::Error; @@ -9,8 +9,7 @@ use crate::constants::{ COLOR_OPTIMAL_P_DIVIDER, COLOR_OPTIMAL_P_HEADER, COLOR_OPTIMAL_P_RECOMMENDATION, COLOR_OPTIMAL_P_SKIP, COLOR_OPTIMAL_P_TEXT, COLOR_OPTIMAL_P_WARNING, COLOR_STEP_RESPONSE_COMBINED, COLOR_STEP_RESPONSE_HIGH_SP, COLOR_STEP_RESPONSE_LOW_SP, - FINAL_NORMALIZED_STEADY_STATE_TOLERANCE, LINE_WIDTH_PLOT, - LOW_AUTHORITY_SETPOINT_THRESHOLD_DEG_S, RESPONSE_LENGTH_S, STEADY_STATE_END_S, + LINE_WIDTH_PLOT, LOW_AUTHORITY_SETPOINT_THRESHOLD_DEG_S, RESPONSE_LENGTH_S, STEADY_STATE_END_S, STEADY_STATE_START_S, }; use crate::data_analysis::calc_step_response; // For average_responses @@ -178,71 +177,14 @@ pub fn plot_step_response( let process_response = |mask: &Array1, stacked_resp: &Array2, - resp_len_samples_local: usize, // Use a local variable for clarity - ss_start_idx_local: usize, - ss_end_idx_local: usize| + resp_len_samples_local: usize| -> Option> { - // Return type simplified to just the response array - if !mask.iter().any(|&w| w > 0.0) { - return None; - } // No windows selected by mask - - // avg_resp is now an average of *individually Y-corrected* (mostly normalized towards 1) responses - // from calc_step_response.rs - calc_step_response::average_responses(stacked_resp, mask, resp_len_samples_local) - .ok() - .and_then(|avg_resp| { - if avg_resp.is_empty() { - return None; - } - - // Shift the response to start at 0.0 - let mut shifted_response = avg_resp; - let first_val = shifted_response[0]; - shifted_response.mapv_inplace(|v| v - first_val); - - // This steady_state_segment is from the averaged, Y-corrected (upstream), - // and shifted response. Its mean is used for a final normalization refinement. - let steady_state_segment = - shifted_response.slice(s![ss_start_idx_local..ss_end_idx_local]); - if steady_state_segment.is_empty() { - // Guard against empty slice - return None; - } - - steady_state_segment - .mean() - .and_then(|final_ss_mean_for_norm| { - if final_ss_mean_for_norm.abs() > 1e-9 { - // Avoid division by zero - // This final normalization step ensures the plotted response aims for 1.0. - // It refines the average of the Y-corrected individual responses. - let normalized_response = - shifted_response.mapv(|v| v / final_ss_mean_for_norm); - - // Final check on this fully processed and normalized response - let final_check_ss_segment = normalized_response - .slice(s![ss_start_idx_local..ss_end_idx_local]); - if final_check_ss_segment.is_empty() { - return None; - } // Should not happen - - final_check_ss_segment.mean().and_then( - |final_normalized_ss_mean| { - if (final_normalized_ss_mean - 1.0).abs() - <= FINAL_NORMALIZED_STEADY_STATE_TOLERANCE - { - Some(normalized_response) - } else { - None - } - }, - ) - } else { - None - } - }) - }) + calc_step_response::displayed_response( + stacked_resp, + mask, + resp_len_samples_local, + sr, + ) }; let mut series = Vec::new(); @@ -252,25 +194,13 @@ pub fn plot_step_response( &combined_mask, valid_stacked_responses, response_length_samples, - current_ss_start_idx, - current_ss_end_idx, ); if display.show_legend { - let final_low_response = process_response( - &low_mask, - valid_stacked_responses, - response_length_samples, - current_ss_start_idx, - current_ss_end_idx, - ); - let final_high_response = process_response( - &high_mask, - valid_stacked_responses, - response_length_samples, - current_ss_start_idx, - current_ss_end_idx, - ); + let final_low_response = + process_response(&low_mask, valid_stacked_responses, response_length_samples); + let final_high_response = + process_response(&high_mask, valid_stacked_responses, response_length_samples); if let Some(resp) = final_low_response { let peak_val_opt = calc_step_response::find_peak_value(&resp); From fa0dba9a3050bd1a6c3edb0b5e23b4f0501b1c55 Mon Sep 17 00:00:00 2001 From: nerdCopter <56646290+nerdCopter@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:33:13 -0600 Subject: [PATCH 2/4] test: cover masked-row averaging in displayed_response; clarify legend 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 Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ --- OVERVIEW.md | 2 +- src/data_analysis/calc_step_response.rs | 26 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/OVERVIEW.md b/OVERVIEW.md index ab7b2b7..739a5f5 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -77,7 +77,7 @@ All analysis parameters, thresholds, plot dimensions, and algorithmic constants * No first-sample shift is applied, as in PIDtoolbox. The time axis is `i / sample_rate`. * A **final normalization** step is performed: the mean of the steady-state portion of this *averaged* response is calculated. The entire response is then divided by this mean to ensure the plotted average response aims for a steady-state of 1.0. * The final response is only plotted if its steady-state mean (after this final normalization) is within `FINAL_NORMALIZED_STEADY_STATE_TOLERANCE` of 1.0. - * The peak is read on this unsmoothed, renormalized curve. Legend Peak, console and report "Actual Peak", and the P:D zones all use the same value. + * The peak is read on this unsmoothed, renormalized curve. The combined legend Peak (the only legend entry without `--dps`), the console and report "Actual Peak", and the P:D zones all use the same value. With `--dps`, the low- and high-setpoint legend entries use subset masks, so their peaks can differ from the combined peak. The legend prints two decimals; console and report print three. * Calculates peak value and delay time (Td) for each plotted average response using `calc_step_response::find_peak_value` and `calc_step_response::calculate_delay_time`. * **Delay Time (Td) Calculation:** The delay time is calculated as the time for the step response to reach 50% of its final value. Linear interpolation is used for precise determination of the 50% threshold crossing. A fixed offset of -1ms is applied to the calculated time (in milliseconds) before converting to seconds, and the result is constrained to be non-negative. * Generates and saves the step response plot. The y-axis floor is 0 when no trace goes below 0, so the origin is (0, 0). diff --git a/src/data_analysis/calc_step_response.rs b/src/data_analysis/calc_step_response.rs index 69abb02..cecdc07 100644 --- a/src/data_analysis/calc_step_response.rs +++ b/src/data_analysis/calc_step_response.rs @@ -612,6 +612,32 @@ mod tests { assert!((ss - 1.0).abs() < 1e-9); } + #[test] + fn displayed_response_averages_only_masked_rows() { + // Row 0 is flat 1.0, row 1 is flat 2.0, row 2 is flat 4.0 with one peak sample. + // Mask selects rows 0 and 1: average is 1.5 everywhere, so the normalized response is 1.0. + // Mask selecting row 2 only: peak sample 4.8 over steady state 4.0 gives 1.2. + let len = 500; + let stacked = Array2::from_shape_fn((3, len), |(r, i)| match r { + 0 => 1.0f32, + 1 => 2.0, + _ => { + if i == 100 { + 4.8 + } else { + 4.0 + } + } + }); + let first_two = Array1::from_vec(vec![1.0f32, 1.0, 0.0]); + let resp = displayed_response(&stacked, &first_two, len, 1000.0).expect("response"); + assert!(resp.iter().all(|v| (v - 1.0).abs() < 1e-9)); + let third = Array1::from_vec(vec![0.0f32, 0.0, 1.0]); + let resp = displayed_response(&stacked, &third, len, 1000.0).expect("response"); + let peak = find_peak_value(&resp).expect("peak"); + assert!((peak - 1.2).abs() < 1e-5, "peak {peak}"); + } + #[test] fn displayed_response_rejects_empty_mask_and_zero_steady_state() { let len = 500; From f66739d778f5e9877a0cadc8437346fb241fa7ee Mon Sep 17 00:00:00 2001 From: nerdCopter <56646290+nerdCopter@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:16:45 -0600 Subject: [PATCH 3/4] test: make the masked-row test sensitive to averaging; correct peak definition 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 Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ --- OVERVIEW.md | 4 ++-- src/data_analysis/calc_step_response.rs | 25 +++++++++++-------------- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/OVERVIEW.md b/OVERVIEW.md index 739a5f5..c7f130f 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -83,7 +83,7 @@ All analysis parameters, thresholds, plot dimensions, and algorithmic constants * Generates and saves the step response plot. The y-axis floor is 0 when no trace goes below 0, so the origin is (0, 0). * **P:D Ratio Recommendations (`src/main.rs`):** * Based on step response peak analysis, the system provides tuning recommendations: - * **Important:** Peak value is measured as the first maximum after the response crosses the setpoint (1.0). The initial transient dip (visible in first ~30ms) is normal system behavior and not used for tuning recommendations. + * **Important:** Peak value is the maximum finite sample of the displayed response (`find_peak_value`). The initial transient dip (visible in first ~30ms) is normal system behavior and not used for tuning recommendations. * **Peak Analysis Ranges (based on step response overshoot/undershoot):** Simplified 6-zone structure aligned with real-world practical tuning: * **< 1.00 (Undershoot):** Too much D damping. Recommendation (conservative): P:D × (1.05 / peak) — proportional decrease targeting sweet-spot centre. * **1.00–1.02 (Near Optimal):** Critically damped transition zone. Recommendation (none) + optional D−1 hint for fine-tuning. @@ -251,7 +251,7 @@ The system provides intelligent P:D tuning recommendations based on step-respons - Works for all aircraft sizes, including 10+ inch, where D can exceed P - Includes warnings for severe overshoot or unreasonable P:D ratios - Shows recommendations only when the step response needs improvement (no adjustment for 1.02 ≤ peak < 1.08; 1.00 ≤ peak < 1.02 can show an optional D−1 hint; peak ≥ 1.08 can show a D recommendation; see zones above) -- **Note:** Peak value measures the first maximum after crossing the setpoint; the initial transient dip is normal system behavior +- **Note:** Peak value is the maximum finite sample of the displayed response; the initial transient dip is normal system behavior #### Optimal P Estimation (Optional, Experimental) diff --git a/src/data_analysis/calc_step_response.rs b/src/data_analysis/calc_step_response.rs index cecdc07..d01d278 100644 --- a/src/data_analysis/calc_step_response.rs +++ b/src/data_analysis/calc_step_response.rs @@ -614,24 +614,21 @@ mod tests { #[test] fn displayed_response_averages_only_masked_rows() { - // Row 0 is flat 1.0, row 1 is flat 2.0, row 2 is flat 4.0 with one peak sample. - // Mask selects rows 0 and 1: average is 1.5 everywhere, so the normalized response is 1.0. - // Mask selecting row 2 only: peak sample 4.8 over steady state 4.0 gives 1.2. + // Row 0: flat 1.0. Row 1: flat 2.0 with a 2.4 sample at i=100. Row 2: flat 4.0 with a 4.8 sample. + // Rows 0 and 1 selected: average at i=100 is 1.7, steady state 1.5, so peak 1.7/1.5. + // Row 2 only: 4.8 over steady state 4.0 gives 1.2. let len = 500; - let stacked = Array2::from_shape_fn((3, len), |(r, i)| match r { - 0 => 1.0f32, - 1 => 2.0, - _ => { - if i == 100 { - 4.8 - } else { - 4.0 - } - } + let stacked = Array2::from_shape_fn((3, len), |(r, i)| match (r, i) { + (0, _) => 1.0f32, + (1, 100) => 2.4, + (1, _) => 2.0, + (_, 100) => 4.8, + _ => 4.0, }); let first_two = Array1::from_vec(vec![1.0f32, 1.0, 0.0]); let resp = displayed_response(&stacked, &first_two, len, 1000.0).expect("response"); - assert!(resp.iter().all(|v| (v - 1.0).abs() < 1e-9)); + let peak = find_peak_value(&resp).expect("peak"); + assert!((peak - 1.7 / 1.5).abs() < 1e-5, "peak {peak}"); let third = Array1::from_vec(vec![0.0f32, 0.0, 1.0]); let resp = displayed_response(&stacked, &third, len, 1000.0).expect("response"); let peak = find_peak_value(&resp).expect("peak"); From 50e53d0cce660a5f45e9728f1ff2a57baacb7546 Mon Sep 17 00:00:00 2001 From: nerdCopter <56646290+nerdCopter@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:34:00 -0600 Subject: [PATCH 4/4] test: check the report prints the shared displayed-response peak; fix 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 Claude-Session: https://claude.ai/code/session_01KoqKWyH8bEnezDzEVxkNPQ --- OVERVIEW.md | 4 ++-- src/report.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/OVERVIEW.md b/OVERVIEW.md index c7f130f..a3013d3 100644 --- a/OVERVIEW.md +++ b/OVERVIEW.md @@ -77,13 +77,13 @@ All analysis parameters, thresholds, plot dimensions, and algorithmic constants * No first-sample shift is applied, as in PIDtoolbox. The time axis is `i / sample_rate`. * A **final normalization** step is performed: the mean of the steady-state portion of this *averaged* response is calculated. The entire response is then divided by this mean to ensure the plotted average response aims for a steady-state of 1.0. * The final response is only plotted if its steady-state mean (after this final normalization) is within `FINAL_NORMALIZED_STEADY_STATE_TOLERANCE` of 1.0. - * The peak is read on this unsmoothed, renormalized curve. The combined legend Peak (the only legend entry without `--dps`), the console and report "Actual Peak", and the P:D zones all use the same value. With `--dps`, the low- and high-setpoint legend entries use subset masks, so their peaks can differ from the combined peak. The legend prints two decimals; console and report print three. + * The peak is read on this unsmoothed, renormalized curve. The combined legend Peak (the only legend entry without `--dps`), the console "Actual Peak" and report "Peak Value", and the P:D zones all use the same value. With `--dps`, the low- and high-setpoint legend entries use subset masks, so their peaks can differ from the combined peak. The legend prints two decimals; console and report print three. * Calculates peak value and delay time (Td) for each plotted average response using `calc_step_response::find_peak_value` and `calc_step_response::calculate_delay_time`. * **Delay Time (Td) Calculation:** The delay time is calculated as the time for the step response to reach 50% of its final value. Linear interpolation is used for precise determination of the 50% threshold crossing. A fixed offset of -1ms is applied to the calculated time (in milliseconds) before converting to seconds, and the result is constrained to be non-negative. * Generates and saves the step response plot. The y-axis floor is 0 when no trace goes below 0, so the origin is (0, 0). * **P:D Ratio Recommendations (`src/main.rs`):** * Based on step response peak analysis, the system provides tuning recommendations: - * **Important:** Peak value is the maximum finite sample of the displayed response (`find_peak_value`). The initial transient dip (visible in first ~30ms) is normal system behavior and not used for tuning recommendations. + * **Important:** Peak value is the maximum finite sample of the displayed response (`find_peak_value`). The initial transient dip (visible in first ~30ms) is normal system behavior; it lies below 1.0, so it does not set the maximum. `find_peak_value` applies no time filter. * **Peak Analysis Ranges (based on step response overshoot/undershoot):** Simplified 6-zone structure aligned with real-world practical tuning: * **< 1.00 (Undershoot):** Too much D damping. Recommendation (conservative): P:D × (1.05 / peak) — proportional decrease targeting sweet-spot centre. * **1.00–1.02 (Near Optimal):** Critically damped transition zone. Recommendation (none) + optional D−1 hint for fine-tuning. diff --git a/src/report.rs b/src/report.rs index 2d6f80f..a2b5d7f 100644 --- a/src/report.rs +++ b/src/report.rs @@ -916,3 +916,69 @@ fn fmt_dterm_rec(rec: &DTermRec) -> String { None => format!("P:D={:.2}", rec.pd_ratio), } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::data_analysis::calc_step_response::{displayed_response, find_peak_value}; + use ndarray::{Array1, Array2}; + + fn empty_report(step_reports: Vec) -> FlightReport { + FlightReport { + root_name: "peak_parity".to_string(), + sample_rate: Some(1000.0), + trim_window: None, + header_metadata: Vec::new(), + pd_ratios: Default::default(), + pid_labels: Default::default(), + d_ranges: Default::default(), + step_reports, + optimal_p: Default::default(), + gyro_analysis: None, + dterm_results: Vec::new(), + bode_results: Vec::new(), + motor_results: Vec::new(), + motor_desync_results: Vec::new(), + rc_command_steps: Vec::new(), + stick_distribution_results: Vec::new(), + png_links: Vec::new(), + skipped_plots: Vec::new(), + filter_config: None, + dynamic_notch: None, + rpm_filter: None, + rpm_motor_frequencies: None, + debug_fallback: false, + debug_mode_name: None, + } + } + + // Spec: the report prints the peak of the shared displayed response to three decimals. + // Steady state 4.0 with one 4.8 sample gives a peak of exactly 1.200. + #[test] + fn report_carries_the_shared_displayed_response_peak() { + let len = 500; + let stacked = Array2::from_shape_fn((2, len), |(_, i)| if i == 100 { 4.8f32 } else { 4.0 }); + let mask = Array1::::ones(2); + let resp = displayed_response(&stacked, &mask, len, 1000.0).expect("response"); + let peak = find_peak_value(&resp).expect("peak"); + + let step = StepAxisReport { + axis_name: "Roll", + peak_value: peak, + assessment: "Overshoot", + current_pd_ratio: 1.2, + conservative: None, + moderate: None, + aggressive: None, + near_optimal_hint: None, + setpoint_authority_name: None, + setpoint_authority_mean: None, + warnings: Vec::new(), + }; + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("report.md"); + generate_markdown_report(&empty_report(vec![step]), &path).expect("report"); + let text = fs::read_to_string(&path).expect("read"); + assert!(text.contains("- **Peak Value:** 1.200"), "{text}"); + } +}