Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions OVERVIEW.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,19 @@ 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. 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 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; 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.
Expand Down Expand Up @@ -250,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)

Expand Down
103 changes: 100 additions & 3 deletions src/data_analysis/calc_step_response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -516,6 +516,43 @@ pub fn calculate_delay_time(normalized_response: &Array1<f64>, 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<f32>,
mask: &Array1<f32>,
response_length_samples: usize,
sample_rate: f64,
) -> Option<Array1<f64>> {
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<f64>) -> Option<f64> {
Expand Down Expand Up @@ -548,6 +585,66 @@ 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::<f32>::ones((2, len));
let mask = Array1::<f32>::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::<f32>::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_averages_only_masked_rows() {
// 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, 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");
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");
assert!((peak - 1.2).abs() < 1e-5, "peak {peak}");
}

#[test]
fn displayed_response_rejects_empty_mask_and_zero_steady_state() {
let len = 500;
let stacked = Array2::<f32>::zeros((2, len));
assert!(displayed_response(&stacked, &Array1::<f32>::ones(2), len, 1000.0).is_none());
let ones = Array2::<f32>::ones((2, len));
assert!(displayed_response(&ones, &Array1::<f32>::zeros(2), len, 1000.0).is_none());
assert!(displayed_response(&ones, &Array1::<f32>::ones(2), 0, 1000.0).is_none());
}

#[test]
fn response_time_axis_is_sample_index_over_rate() {
for rate in TEST_SAMPLE_RATES {
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f32> = 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)
Expand Down
96 changes: 13 additions & 83 deletions src/plot_functions/plot_step_response.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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
Expand Down Expand Up @@ -178,71 +177,14 @@ pub fn plot_step_response(

let process_response = |mask: &Array1<f32>,
stacked_resp: &Array2<f32>,
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<Array1<f64>> {
// 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();
Expand All @@ -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);
Expand Down
Loading
Loading