diff --git a/.github/workflows/build-all.yml b/.github/workflows/build-all.yml index b04a421..cfbcc69 100644 --- a/.github/workflows/build-all.yml +++ b/.github/workflows/build-all.yml @@ -59,6 +59,7 @@ jobs: - name: Testes e verificações Rust run: | cargo test --locked --workspace + cargo run --locked --release -p xtask -- parity cargo clippy --locked --workspace --all-targets -- -D warnings cargo fmt --all --check desktop-file-validate packaging/linux/controlab.desktop diff --git a/.gitignore b/.gitignore index 11158c4..41cd204 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,6 @@ native/android/app/src/main/jniLibs/ # Cargo workspace /target/ + +# Artefatos locais e logs intermediários de validação +/artifacts/ diff --git a/CHANGELOG.md b/CHANGELOG.md index c2280d4..58d5918 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,29 @@ Todas as mudanças relevantes e lançamentos da suíte ControLAB são documentados neste arquivo. O formato é baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.0.0/) e este projeto segue [Versionamento Semântico](https://semver.org/lang/pt-BR/). +## [Unreleased] + +### Added + +- Suíte permanente de validação acadêmica e conformidade científica em Rust (`academic_lgr_validation`, `academic_controllers_validation`, `academic_requirements_compliance`, `blocklab-core/tests/academic_diagrams` e `mscript/tests/academic_validation`), sem dependência de Python ou MATLAB em tempo de execução. +- Motor genérico de verificação e síntese por restrições em `crates/control-engine/src/controller_synthesis.rs` com modos `temporal_refined` e `auto_simplest` (seleção automática `P -> PI -> PD -> Lead -> PID`) e parametrização canônica de ganhos PID. +- Semântica explícita para restrições de coeficiente de amortecimento (`DampingSpec::{Equal, AtLeast, DidacticEstimate}`), frequência natural (`NaturalFreqSpec::{Equal, AtLeast, OptionalEstimate}`), tempo de acomodação (`AtMost` / `Equal` com tolerância padrão uniforme de `±2%`, piso `0,02 s`) e dominância modal (identificação do polo/par de referência e razão de resíduos de Heaviside). +- Classificação explícita de viabilidade (`Feasible`, `ProvenInfeasible`, `NotFoundWithinSearchBounds`) com provas algébricas de inviabilidade e diagnóstico de estruturas alternativas. +- Painel de conformidade na interface nativa (`controlab-native`) com banner de status global (`CONFORME`, `CONFORME COM ALERTAS`, `NÃO CONFORME`), comparação `Solicitado × Teórico × Medido × Diferença`, marcações `[OBRIGATÓRIA]` vs `[ESTIMATIVA OPCIONAL]`, referência modal, motivos de não conformidade e advertências técnicas. +- Documentação científica pública de validação e benchmarks em `docs/validation/`. + +### Changed + +- Aprimorado o módulo `controllers` para distinguir projeto clássico por alocação de polos via LGR (`lgr_classic`) da síntese por restrições temporais/modais, preservando integralmente o contrato legado de paridade (152/152 casos). +- Aprimorada a verificação de estabilidade para avaliar o polinômio característico não reduzido antes de qualquer simplificação, detectando instabilidade interna por cancelamento polo-zero no SPD ou eixo imaginário. +- Integrada a verificação automática de paridade congelada (`cargo run --locked --release -p xtask -- parity`) ao workflow de CI em `.github/workflows/build-all.yml`. + +### Fixed + +- Corrigidas regressões de formatação (`rustfmt`) e de paridade congelada em `crates/control-engine/src/controllers.rs` nos casos `controller_test_q5_pid_by_root_locus_0` e `controller_test_q5_pid_custom_pi_zero_0`, restaurando 152/152 casos aprovados. +- Corrigida a classificação indevida de controladores numericamente exatos como bem-sucedidos na GUI quando a resposta temporal real ou o amortecimento violam especificações obrigatórias. +- Corrigida a conversão implícita de igualdades de amortecimento ($\xi$) em desigualdades de sobressinal ($M_p$) durante o refinamento numérico. + ## [1.0.0] - 2026-10-30 - Versão inicial nativa Rust unificada do ControLAB (Linux, Windows e Android). diff --git a/README.md b/README.md index b92cac4..1b03b99 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,23 @@ Software para análise, simulação e projeto de **Sistemas de Controle**, desen ## Funcionalidades - **Análise Linear:** Resposta no tempo, estabilidade (Routh-Hurwitz), Lugar Geométrico das Raízes e resposta em frequência (Bode e Nyquist). -- **Controle & Espaço de Estados:** Projeto de controladores e modelagem em espaço de estados. +- **Controle & Espaço de Estados:** Projeto de controladores (síntese clássica via LGR, refinamento numérico por restrições temporais/modais e seleção automática) com verificação explícita de conformidade, além de modelagem em espaço de estados. - **Diagrama de Blocos:** Edição visual e redução de diagramas de blocos. - **Studio `.m`:** Interpretador e editor de scripts integrado (`mscript`). - **Exportação & Visualização:** Gráficos interativos, renderização de fórmulas e exportação para PNG/SVG. +## Validação Científica e Numérica + +O motor computacional nativo em **Rust** (`controlab-engine`, `blocklab-core`, `mscript`, `controlab-native`) passou por validação científica, numérica, funcional, visual e de desempenho documentada em [`docs/validation/`](docs/validation/README.md): + +- **Arquitetura modular 100% Rust:** sem dependências de execução Python ou MATLAB/Simulink na aplicação ou na suíte permanente de testes. +- **Validação independente com MATLAB R2022b (nos casos testados):** 19 casos de Lugar Geométrico das Raízes (`Exercicios_-_LGR.pdf`), 9 questões de Projeto de Controladores (`Projeto_de_controladores.pdf`, 42 configurações auditadas) e 3 suítes opt-in ao vivo do interpretador `mscript` (erro relativo escalado máximo `7,883e-15`). +- **Paridade histórica congelada:** `152/152` casos aprovados frente às referências do motor Python legado (`cargo run --release -p xtask -- parity`). +- **Síntese clássica e refinada com verificação de conformidade:** preserva o projeto didático clássico por LGR (`lgr_classic`) e disponibiliza síntese por restrições (`temporal_refined` e `auto_simplest`) com checagem de estabilidade externa/interna, amortecimento ($\xi$), frequência natural ($\omega_n$), dominância modal, sobressinal real ($M_p$), tempo de acomodação definitivo ($t_s$), erro estacionário e diagnóstico de inviabilidade matemática. +- **Benchmarks reproduzíveis (Rust `--release` vs Python legado `be79347`):** aceleração mediana entre **3,76× e 15,50×** (9,01× em síntese de controladores, 12,89× em LGR e 15,50× na suíte completa de 19 LGRs) e redução de pico de memória RSS de até **11,47×**, medidos em processo persistente JSON-lines com 3 aquecimentos e 5 a 25 iterações em Linux (`Intel Core i5-13420H`). Os ganhos referem-se especificamente às cargas de trabalho medidas — ver metodologia completa em [`docs/validation/benchmarks.md`](docs/validation/benchmarks.md). + +Consulte a documentação completa em [`docs/validation/README.md`](docs/validation/README.md), [`docs/validation/methodology.md`](docs/validation/methodology.md), [`docs/validation/academic-validation.md`](docs/validation/academic-validation.md), [`docs/validation/synthesis-comparison.md`](docs/validation/synthesis-comparison.md) e [`docs/validation/final-acceptance.md`](docs/validation/final-acceptance.md). + ## Interface e Módulos | | | diff --git a/crates/blocklab-core/tests/academic_diagrams.rs b/crates/blocklab-core/tests/academic_diagrams.rs new file mode 100644 index 0000000..eb4186f --- /dev/null +++ b/crates/blocklab-core/tests/academic_diagrams.rs @@ -0,0 +1,272 @@ +//! Block diagram validation for UFERSA Control Systems II academic lists +//! (`Exercicios_-_LGR.pdf` Question 3 and `Projeto_de_controladores.pdf` Questions 3, 4, 6, 7, 8, 9) +//! using `blocklab_core::solve` (Mason's gain formula over exact rational functions). + +use blocklab_core::{ + algebra::RationalFn, + diagram::{Diagram, NodeId, PortRef, Pos, Side, Sign, examples}, + parser::parse_rational, + solve, +}; + +fn p(x: f32, y: f32) -> Pos { + Pos::new(x, y) +} + +fn expr(src: &str) -> RationalFn { + parse_rational(src).unwrap_or_else(|e| panic!("failed to parse '{src}': {e}")) +} + +fn link(d: &mut Diagram, a: NodeId, b: NodeId, port: u8) { + d.link(a, b, port).unwrap(); +} + +fn link_out(d: &mut Diagram, a: NodeId, out: u8, b: NodeId, port: u8) { + d.connect(PortRef::new(a, out), PortRef::new(b, port)) + .unwrap(); +} + +fn flip(d: &mut Diagram, id: NodeId) { + d.node_mut(id).unwrap().flipped = true; +} + +/// Question 3 of `Projeto_de_controladores.pdf`: +/// R(s) -> Sum1(+, -) -> G_c(s) -> Sum2(+, -) -> 18/(2s+11) -> 1/(2s+1) -> branch1 -> 1/(30s) -> branch2 -> C(s) +/// Inner feedback: branch1 -> 0.5 -> Sum2(-) +/// Outer feedback: branch2 -> 1 -> Sum1(-) +fn build_q3_servo_diagram(gc_expr: &str) -> Diagram { + let mut d = Diagram::new(); + let r = d.add_input("R", p(40.0, 200.0)); + let sum1 = d.add_sum( + &[(Sign::Plus, Side::Left), (Sign::Minus, Side::Bottom)], + p(120.0, 200.0), + ); + let gc = d.add_block(gc_expr, p(220.0, 200.0)); + let sum2 = d.add_sum( + &[(Sign::Plus, Side::Left), (Sign::Minus, Side::Bottom)], + p(320.0, 200.0), + ); + let g_amp = d.add_block("18/(2*s + 11)", p(420.0, 200.0)); + let g_mot = d.add_block("1/(2*s + 1)", p(540.0, 200.0)); + let br_inner = d.add_branch(2, p(640.0, 200.0)); + let g_gear = d.add_block("1/(30*s)", p(740.0, 200.0)); + let br_outer = d.add_branch(2, p(840.0, 200.0)); + let c = d.add_output("C", p(940.0, 200.0)); + + let h_inner = d.add_block("0.5", p(480.0, 300.0)); + let h_outer = d.add_block("1", p(480.0, 380.0)); + flip(&mut d, h_inner); + flip(&mut d, h_outer); + + link(&mut d, r, sum1, 0); + link(&mut d, sum1, gc, 0); + link(&mut d, gc, sum2, 0); + link(&mut d, sum2, g_amp, 0); + link(&mut d, g_amp, g_mot, 0); + link(&mut d, g_mot, br_inner, 0); + link_out(&mut d, br_inner, 0, g_gear, 0); + link_out(&mut d, br_inner, 1, h_inner, 0); + link(&mut d, h_inner, sum2, 1); + link(&mut d, g_gear, br_outer, 0); + link_out(&mut d, br_outer, 0, c, 0); + link_out(&mut d, br_outer, 1, h_outer, 0); + link(&mut d, h_outer, sum1, 1); + d +} + +/// Question 7 of `Projeto_de_controladores.pdf`: +/// R(s) -> Sum1(+, -) -> G_c(s) -> 5/(s(s+2)) -> Sum2(+, -) -> 1/s -> br_in -> br_out -> C(s) +/// Inner feedback: br_in -> 2 -> Sum2(-) +/// Outer feedback: br_out -> 1 -> Sum1(-) +fn build_q7_cascade_diagram(gc_expr: &str) -> Diagram { + let mut d = Diagram::new(); + let r = d.add_input("R", p(40.0, 200.0)); + let sum1 = d.add_sum( + &[(Sign::Plus, Side::Left), (Sign::Minus, Side::Bottom)], + p(120.0, 200.0), + ); + let gc = d.add_block(gc_expr, p(220.0, 200.0)); + let g1 = d.add_block("5/(s*(s + 2))", p(340.0, 200.0)); + let sum2 = d.add_sum( + &[(Sign::Plus, Side::Left), (Sign::Minus, Side::Bottom)], + p(440.0, 200.0), + ); + let g2 = d.add_block("1/s", p(540.0, 200.0)); + let br_in = d.add_branch(2, p(640.0, 200.0)); + let br_out = d.add_branch(2, p(720.0, 200.0)); + let c = d.add_output("C", p(820.0, 200.0)); + + let h_in = d.add_block("2", p(540.0, 300.0)); + let h_out = d.add_block("1", p(440.0, 380.0)); + flip(&mut d, h_in); + flip(&mut d, h_out); + + link(&mut d, r, sum1, 0); + link(&mut d, sum1, gc, 0); + link(&mut d, gc, g1, 0); + link(&mut d, g1, sum2, 0); + link(&mut d, sum2, g2, 0); + link(&mut d, g2, br_in, 0); + link_out(&mut d, br_in, 0, br_out, 0); + link_out(&mut d, br_in, 1, h_in, 0); + link(&mut d, h_in, sum2, 1); + link_out(&mut d, br_out, 0, c, 0); + link_out(&mut d, br_out, 1, h_out, 0); + link(&mut d, h_out, sum1, 1); + d +} + +/// Question 9 of `Projeto_de_controladores.pdf`: +/// Second-order canonical block diagram with wn = 1, xi = 0 (2*xi*wn = 0): +/// R(s) -> Sum1(+, -) -> G_c(s) -> wn^2 -> Sum2(+, -) -> 1/s -> br_in -> 1/s -> br_out -> Y(s) +/// Inner feedback: br_in -> 2*xi*wn -> Sum2(-) +/// Outer feedback: br_out -> 1 -> Sum1(-) +fn build_q9_second_order_diagram(gc_expr: &str, wn_sq_expr: &str, two_xi_wn_expr: &str) -> Diagram { + let mut d = Diagram::new(); + let r = d.add_input("R", p(40.0, 200.0)); + let sum1 = d.add_sum( + &[(Sign::Plus, Side::Left), (Sign::Minus, Side::Bottom)], + p(120.0, 200.0), + ); + let gc = d.add_block(gc_expr, p(220.0, 200.0)); + let wn2 = d.add_block(wn_sq_expr, p(340.0, 200.0)); + let sum2 = d.add_sum( + &[(Sign::Plus, Side::Left), (Sign::Minus, Side::Bottom)], + p(440.0, 200.0), + ); + let int1 = d.add_block("1/s", p(540.0, 200.0)); + let br_in = d.add_branch(2, p(640.0, 200.0)); + let int2 = d.add_block("1/s", p(740.0, 200.0)); + let br_out = d.add_branch(2, p(840.0, 200.0)); + let y = d.add_output("Y", p(940.0, 200.0)); + + let h_in = d.add_block(two_xi_wn_expr, p(540.0, 300.0)); + let h_out = d.add_block("1", p(480.0, 380.0)); + flip(&mut d, h_in); + flip(&mut d, h_out); + + link(&mut d, r, sum1, 0); + link(&mut d, sum1, gc, 0); + link(&mut d, gc, wn2, 0); + link(&mut d, wn2, sum2, 0); + link(&mut d, sum2, int1, 0); + link(&mut d, int1, br_in, 0); + link_out(&mut d, br_in, 0, int2, 0); + link_out(&mut d, br_in, 1, h_in, 0); + link(&mut d, h_in, sum2, 1); + link(&mut d, int2, br_out, 0); + link_out(&mut d, br_out, 0, y, 0); + link_out(&mut d, br_out, 1, h_out, 0); + link(&mut d, h_out, sum1, 1); + d +} + +#[test] +fn validate_lgr_question_3_block_diagrams_via_mason() { + // Q3(a) Eq.(14): G(s) = K/(s(s^2+4s+5)), H(s) = 1 + let d3a = examples::feedback_with("K/(s*(s^2 + 4*s + 5))", "1", Sign::Minus); + let r3a = solve(&d3a).unwrap(); + assert_eq!(r3a.transfer, expr("K/(s^3 + 4*s^2 + 5*s + K)")); + + // Q3(b) Eq.(15): G(s) = K/(s(s^2+4s+13)), H(s) = 1/(s+1) + let d3b = examples::feedback_with("K/(s*(s^2 + 4*s + 13))", "1/(s + 1)", Sign::Minus); + let r3b = solve(&d3b).unwrap(); + assert_eq!( + r3b.transfer, + expr("K*(s + 1)/(s^4 + 5*s^3 + 17*s^2 + 13*s + K)") + ); + + // Q3(c) Eq.(16): G(s) = K/(s+3.6), H(s) = (s+1)/s^2 + let d3c = examples::feedback_with("K/(s + 3.6)", "(s + 1)/(s^2)", Sign::Minus); + let r3c = solve(&d3c).unwrap(); + assert_eq!(r3c.transfer, expr("K*s^2/(s^3 + 3.6*s^2 + K*s + K)")); +} + +#[test] +fn validate_controller_design_block_diagrams_q3_q4_q6_q7_q8_q9_via_mason() { + // 1. Q3 Servo Diagram: + // Uncompensated symbolic controller Gc: + let d_q3_sym = build_q3_servo_diagram("Gc"); + let r_q3_sym = solve(&d_q3_sym).unwrap(); + assert_eq!(r_q3_sym.loops.len(), 2); + assert_eq!( + r_q3_sym.transfer, + expr("(3*Gc)/(20*s^3 + 120*s^2 + 100*s + 3*Gc)") + ); + // Compensated with PD controller Gc(s) = (160 + 100*s)/3: + let d_q3_pd = build_q3_servo_diagram("(160 + 100*s)/3"); + let r_q3_pd = solve(&d_q3_pd).unwrap(); + assert_eq!(r_q3_pd.transfer, expr("(5*s + 8)/(s^3 + 6*s^2 + 10*s + 8)")); + assert_eq!(Diagram::from_json(&d_q3_pd.to_json()).unwrap(), d_q3_pd); + + // 2. Q4 Non-unity feedback diagram (G(s) = 5/(s+0.1), H(s) = 0.05, Gc(s) = (7.6s+16)/s): + let d_q4 = examples::feedback_with("((7.6*s + 16)/s)*(5/(s + 0.1))", "0.05", Sign::Minus); + let r_q4 = solve(&d_q4).unwrap(); + assert_eq!(r_q4.transfer, expr("(38*s + 80)/(s^2 + 2*s + 4)")); + + // 3. Q6 PD controller with exact pole-zero cancellation of (s + 2): + // G_c(s) = 8 + 4*s, G(s) = 1/(s*(s+2)^2), H(s) = 1 + // Notice `blocklab-core` performs exact polynomial GCD cancellation, automatically + // reducing 4(s+2)/((s+2)(s^2+2s+4)) to the minimal realization 4/(s^2+2s+4)! + let d_q6 = examples::feedback_with("(8 + 4*s)/(s*(s + 2)^2)", "1", Sign::Minus); + let r_q6 = solve(&d_q6).unwrap(); + assert_eq!(r_q6.transfer, expr("4/(s^2 + 2*s + 4)")); + + // 4. Q7 Cascade Two-Loop Diagram: + // Symbolic Gc: + let d_q7_sym = build_q7_cascade_diagram("Gc"); + let r_q7_sym = solve(&d_q7_sym).unwrap(); + assert_eq!(r_q7_sym.loops.len(), 2); + assert_eq!(r_q7_sym.transfer, expr("(5*Gc)/(s^3 + 4*s^2 + 4*s + 5*Gc)")); + // Compensated with PD controller Gc(s) = 1.6 + 0.8*s: + // Again, exact GCD cancellation reduces (4s+8)/((s+2)(s^2+2s+4)) to 4/(s^2+2s+4)! + let d_q7_pd = build_q7_cascade_diagram("1.6 + 0.8*s"); + let r_q7_pd = solve(&d_q7_pd).unwrap(); + assert_eq!(r_q7_pd.transfer, expr("4/(s^2 + 2*s + 4)")); + + // 5. Q8 Wind Turbine Diagram (Reference path w(s)/w_ref(s) and Disturbance path w(s)/T_p(s)): + // Plant G_p(s) = -7.2/(5*s + 1), Symbolic PI controller Gc(s) = (Kp*s + Ki)/s: + let d_q8_ref = examples::feedback_with("((Kp*s + Ki)/s)*(-7.2/(5*s + 1))", "1", Sign::Minus); + let r_q8_ref = solve(&d_q8_ref).unwrap(); + assert_eq!( + r_q8_ref.transfer, + expr("(-7.2*Kp*s - 7.2*Ki)/(5*s^2 + (1 - 7.2*Kp)*s - 7.2*Ki)") + ); + // Disturbance path (with w_ref = 0): T_p(s) -> Sum_d(+, -) -> G_p(s) -> w(s), + // feedback through G_c(s) into Sum_d(-): + let d_q8_dist = examples::feedback_with("-7.2/(5*s + 1)", "(Kp*s + Ki)/s", Sign::Minus); + let r_q8_dist = solve(&d_q8_dist).unwrap(); + assert_eq!( + r_q8_dist.transfer, + expr("(-7.2*s)/(5*s^2 + (1 - 7.2*Kp)*s - 7.2*Ki)") + ); + + // 6. Q9 Second-Order Block Diagram: + // Symbolic general second-order diagram (wn^2, 2*xi*wn, Gc): + let d_q9_sym = build_q9_second_order_diagram("Gc", "wn^2", "2*xi*wn"); + let r_q9_sym = solve(&d_q9_sym).unwrap(); + assert_eq!( + r_q9_sym.transfer, + expr("(Gc*wn^2)/(s^2 + 2*xi*wn*s + Gc*wn^2)") + ); + // Evaluated at wn = 1, xi = 0 with PD controller Gc(s) = 4 + 2*s: + let d_q9_pd = build_q9_second_order_diagram("4 + 2*s", "1", "0"); + let r_q9_pd = solve(&d_q9_pd).unwrap(); + assert_eq!(r_q9_pd.transfer, expr("(2*s + 4)/(s^2 + 2*s + 4)")); +} + +#[test] +fn validate_q8_independent_reference_block_diagram_reduction() { + // Etapa 10 Section 4 — Independent Q8 reference: + // Plant G(s) = -7.2/(5s + 1), Controller Gc(s) = -1 - 0.2/s = (-s - 0.2)/s + // Reference transfer function T(s) = Gc*G / (1 + Gc*G) simplifies exactly to 1.44/(s + 1.44). + let d_ref = examples::feedback_with("((-s - 0.2)/s)*(-7.2/(5*s + 1))", "1", Sign::Minus); + let r_ref = solve(&d_ref).unwrap(); + assert_eq!(r_ref.transfer, expr("1.44/(s + 1.44)")); + + // Disturbance transfer function T_d(s) = G / (1 + Gc*G) = -7.2*s / (5*s^2 + 8.2*s + 1.44) + // = -1.44*s / ((s + 0.2)*(s + 1.44)), which has T_d(0) = 0 (complete constant disturbance rejection). + let d_dist = examples::feedback_with("-7.2/(5*s + 1)", "(-s - 0.2)/s", Sign::Minus); + let r_dist = solve(&d_dist).unwrap(); + assert_eq!(r_dist.transfer, expr("(-1.44*s)/((s + 0.2)*(s + 1.44))")); +} diff --git a/crates/control-engine/src/controller_synthesis.rs b/crates/control-engine/src/controller_synthesis.rs new file mode 100644 index 0000000..da54be7 --- /dev/null +++ b/crates/control-engine/src/controller_synthesis.rs @@ -0,0 +1,2385 @@ +//! Generic controller compliance verification and constrained numerical synthesis. +//! +//! Separates two fundamentally different engineering workflows: +//! 1. Classic Root-Locus (LGR) pole placement (`lgr_classic`) followed by full closed-loop +//! time-domain compliance verification (detecting overshoot inflation from extra zeros, +//! settling-time mismatch, non-dominant poles, approximate cancellations, and instability). +//! 2. Constrained time-domain synthesis (`temporal_refined` / `auto_simplest`) using generic +//! candidate generation (including stable plant-pole cancellation and multi-scale grids) +//! coupled with bounded Nelder-Mead / coordinate refinement over exact matrix-exponential +//! step simulations. + +use crate::{ + Result, controller_math as math, polynomial as poly, + simulation::{self, Input}, + transfer::TransferFunction, +}; +use num_complex::Complex64 as C; +use serde_json::{Value, json}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DesignObjective { + /// Specifications target dominant closed-loop pole locations (e.g. sd, or xi/wn of poles). + PolePlacement, + /// Specifications impose strict time-domain response limits (e.g. Mp <= 25%, ts <= 4s). + TimeDomainConstraints, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum SettlingSpec { + /// Inequality constraint: measured settling time <= max_s. + AtMost(f64), + /// Equality constraint: |measured settling time - target| <= tolerance. + Equal { target: f64, tolerance: f64 }, +} + +/// Uniform documented default tolerance for settling-time equality constraints: +/// +/- 2% of target, with a 0.02 s floor (e.g., +/-0.02 s at ts=1 s, +/-0.08 s at ts=4 s). +pub fn default_settling_tolerance(target: f64) -> f64 { + (0.02 * target.abs()).max(0.02) +} + +/// Uniform documented default tolerance for damping-ratio equality constraints. +pub fn default_damping_tolerance() -> f64 { + 0.01 +} + +/// Uniform documented default tolerance for natural-frequency equality constraints (+/- 2%, floor 0.01 rad/s). +pub fn default_wn_tolerance(target: f64) -> f64 { + (0.02 * target.abs()).max(0.01) +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum DampingSpec { + /// Mandatory exact equality on the complex conjugate pole pair: |xi - target| <= tolerance. + Equal { target: f64, tolerance: f64 }, + /// Mandatory minimum damping ratio: xi >= min. + AtLeast(f64), + /// Optional didactic estimate (e.g., derived from Mp); reported transparently, not enforced as equality. + DidacticEstimate(f64), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum NaturalFreqSpec { + /// Mandatory exact equality on the reference pole/pair: |wn - target| <= tolerance. + Equal { target: f64, tolerance: f64 }, + /// Mandatory minimum natural frequency: wn >= min. + AtLeast(f64), + /// Optional informational estimate. + OptionalEstimate(f64), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FeasibilityClass { + /// Feasible controller found satisfying all mandatory constraints. + Feasible, + /// Mathematically proven infeasible for the requested structure and constraints. + ProvenInfeasible, + /// No feasible solution found within the numerical search bounds (not a mathematical impossibility proof). + NotFoundWithinSearchBounds, +} + +impl FeasibilityClass { + pub fn as_str(self) -> &'static str { + match self { + Self::Feasible => "feasible", + Self::ProvenInfeasible => "proven_infeasible", + Self::NotFoundWithinSearchBounds => "not_found_within_search_bounds", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ControllerStructure { + P, + PI, + PD, + Lead, + PID, +} + +impl ControllerStructure { + pub fn as_str(self) -> &'static str { + match self { + Self::P => "P", + Self::PI => "PI", + Self::PD => "PD", + Self::Lead => "LEAD", + Self::PID => "PID", + } + } + + pub fn parse(s: &str) -> Option { + match s.trim().to_uppercase().as_str() { + "P" => Some(Self::P), + "PI" => Some(Self::PI), + "PD" => Some(Self::PD), + "LEAD" | "AVANCO" | "AVANÇO" => Some(Self::Lead), + "PID" => Some(Self::PID), + _ => None, + } + } + + pub fn has_integrator(self) -> bool { + matches!(self, Self::PI | Self::PID) + } + + pub fn complexity_order() -> [Self; 5] { + [Self::P, Self::PI, Self::PD, Self::Lead, Self::PID] + } +} + +#[derive(Clone, Debug)] +pub struct DesignSpecs { + pub objective: DesignObjective, + pub max_overshoot_pct: Option, + pub settling_time: Option, + pub settling_criterion_pct: u8, + pub damping: Option, + pub natural_freq: Option, + pub require_complex_dominance: bool, + pub require_zero_step_error: bool, + pub desired_dominant_pole: Option, + pub theoretical_xi: Option, + pub theoretical_wn: Option, + pub theoretical_mp_pct: Option, + pub theoretical_ts_s: Option, +} + +impl Default for DesignSpecs { + fn default() -> Self { + Self { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: None, + settling_time: None, + settling_criterion_pct: 2, + damping: None, + natural_freq: None, + require_complex_dominance: false, + require_zero_step_error: false, + desired_dominant_pole: None, + theoretical_xi: None, + theoretical_wn: None, + theoretical_mp_pct: None, + theoretical_ts_s: None, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RequirementStatus { + Pass, + Warning, + Fail, +} + +impl RequirementStatus { + pub fn as_str(self) -> &'static str { + match self { + Self::Pass => "PASS", + Self::Warning => "WARNING", + Self::Fail => "FAIL", + } + } +} + +#[derive(Clone, Debug)] +pub struct RequirementCheck { + pub id: String, + pub label: String, + pub requested: String, + pub theoretical: String, + pub measured: String, + pub difference: String, + pub status: RequirementStatus, + pub mandatory: bool, + pub message: String, +} + +#[derive(Clone, Debug)] +pub struct CancellationInfo { + pub pole: C, + pub zero: C, + pub distance: f64, + pub exact: bool, + pub unstable: bool, +} + +#[derive(Clone, Debug)] +pub struct VerificationReport { + pub overall_status: RequirementStatus, + pub requirements_passed: bool, + pub numerically_valid: bool, + pub closed_loop_stable: bool, + pub internally_stable: bool, + pub closed_loop_poles: Vec, + pub closed_loop_zeros: Vec, + pub dominant_pole: Option, + pub dominant_pole_ratio: Option, + pub non_dominant_poles: Vec, + pub extra_closed_loop_zeros: Vec, + pub cancellations: Vec, + pub measured_xi: Option, + pub measured_wn: Option, + pub damping_pole_label: Option, + pub has_complex_pair: bool, + pub complex_pair_is_dominant: bool, + pub non_dominant_residue_ratio: Option, + pub measured_overshoot_pct: Option, + pub measured_settling_time_s: Option, + pub measured_rise_time_s: Option, + pub measured_peak_time_s: Option, + pub measured_steady_state_y: Option, + pub summer_steady_state_error: Option, + pub output_tracking_error: Option, + pub checks: Vec, + pub warnings: Vec, + pub failed_requirements: Vec, +} + +impl VerificationReport { + pub fn to_json(&self) -> Value { + let fmt_c = |v: C| json!({"re": v.re, "im": v.im}); + json!({ + "overall_status": self.overall_status.as_str(), + "requirements_passed": self.requirements_passed, + "numerically_valid": self.numerically_valid, + "closed_loop_stable": self.closed_loop_stable, + "internally_stable": self.internally_stable, + "closed_loop_poles": self.closed_loop_poles.iter().copied().map(fmt_c).collect::>(), + "closed_loop_zeros": self.closed_loop_zeros.iter().copied().map(fmt_c).collect::>(), + "dominant_pole": self.dominant_pole.map(fmt_c), + "dominant_pole_ratio": self.dominant_pole_ratio, + "non_dominant_poles": self.non_dominant_poles.iter().copied().map(fmt_c).collect::>(), + "extra_closed_loop_zeros": self.extra_closed_loop_zeros.iter().copied().map(fmt_c).collect::>(), + "cancellations": self.cancellations.iter().map(|c| json!({ + "pole": fmt_c(c.pole), + "zero": fmt_c(c.zero), + "distance": c.distance, + "exact": c.exact, + "unstable": c.unstable, + })).collect::>(), + "modal_analysis": { + "measured_xi": self.measured_xi, + "measured_wn": self.measured_wn, + "damping_pole_label": self.damping_pole_label, + "has_complex_pair": self.has_complex_pair, + "complex_pair_is_dominant": self.complex_pair_is_dominant, + "non_dominant_residue_ratio": self.non_dominant_residue_ratio, + }, + "measured": { + "overshoot_percent": self.measured_overshoot_pct, + "settling_time": self.measured_settling_time_s, + "rise_time": self.measured_rise_time_s, + "peak_time": self.measured_peak_time_s, + "steady_state_y": self.measured_steady_state_y, + "summer_steady_state_error": self.summer_steady_state_error, + "output_tracking_error": self.output_tracking_error, + "xi": self.measured_xi, + "wn": self.measured_wn, + }, + "checks": self.checks.iter().map(|ck| json!({ + "id": ck.id, + "label": ck.label, + "requested": ck.requested, + "theoretical": ck.theoretical, + "measured": ck.measured, + "difference": ck.difference, + "status": ck.status.as_str(), + "mandatory": ck.mandatory, + "message": ck.message, + })).collect::>(), + "warnings": self.warnings, + "failed_requirements": self.failed_requirements, + }) + } +} + +#[derive(Clone, Debug)] +pub struct SynthesizedController { + pub structure: ControllerStructure, + pub transfer: TransferFunction, + pub kp: f64, + pub ki: f64, + pub kd: f64, + pub z: Option, + pub zi: Option, + pub p: Option, + pub k: Option, + pub method_used: String, + pub verification: VerificationReport, +} + +#[derive(Clone, Debug)] +pub struct SynthesisOutcome { + pub feasible: bool, + pub feasibility_class: FeasibilityClass, + pub selected: Option, + pub infeasibility_reasons: Vec, + pub alternatives: Vec, + pub candidates_evaluated: usize, +} + +fn fmt_val(v: f64, decimals: usize) -> String { + format!("{v:.decimals$}").replace('.', ",") +} + +fn fmt_complex(z: C) -> String { + if z.im.abs() < 1e-5 { + fmt_val(z.re, 4) + } else { + format!( + "{} {} {}j", + fmt_val(z.re, 4), + if z.im >= 0.0 { "+" } else { "-" }, + fmt_val(z.im.abs(), 4) + ) + } +} + +/// Exact limit lim_{s -> 0} N(s)/D(s), accounting for exact common powers of s. +fn exact_dc_gain(tf: &TransferFunction) -> f64 { + let nz = tf + .num + .iter() + .rev() + .take_while(|&&v| v.abs() < 1e-14) + .count(); + let dz = tf + .den + .iter() + .rev() + .take_while(|&&v| v.abs() < 1e-14) + .count(); + if nz == tf.num.len() { + return 0.0; + } + let num_c = tf.num[tf.num.len() - nz - 1]; + let den_c = tf.den[tf.den.len() - dz - 1]; + match nz.cmp(&dz) { + std::cmp::Ordering::Greater => 0.0, + std::cmp::Ordering::Equal => num_c / den_c, + std::cmp::Ordering::Less => f64::INFINITY.copysign(num_c / den_c), + } +} + +/// System type (number of pure integrators at s = 0) of an open-loop transfer function. +pub fn system_type(ol: &TransferFunction) -> usize { + let nz = ol + .num + .iter() + .rev() + .take_while(|&&v| v.abs() < 1e-12) + .count(); + let dz = ol + .den + .iter() + .rev() + .take_while(|&&v| v.abs() < 1e-12) + .count(); + dz.saturating_sub(nz) +} + +/// Dominant high-frequency / steady-state sign of plant G(s)H(s) for negative feedback stability. +fn plant_sign(ol: &TransferFunction) -> f64 { + let lead = ol.num[0] / ol.den[0]; + if lead < 0.0 { -1.0 } else { 1.0 } +} + +/// Exact step response metrics with sub-sample linear interpolation for definitive settling time. +struct SampledMetrics { + overshoot_pct: f64, + settling_time: Option, + rise_time: Option, + peak_time: f64, +} + +fn compute_step_metrics( + cl_tf: &TransferFunction, + horizon_s: f64, + points: usize, + threshold: f64, +) -> Result { + let steady = exact_dc_gain(cl_tf); + if !steady.is_finite() || steady.abs() < 1e-12 { + return Err("Ganho estático em malha fechada nulo ou infinito.".into()); + } + let dt = horizon_s / (points.saturating_sub(1).max(1)) as f64; + let t: Vec = (0..points).map(|i| i as f64 * dt).collect(); + let y = simulation::simulate(cl_tf, &t, Input::Step)?; + if y.iter().any(|v| !v.is_finite()) { + return Err("Resposta temporal apresentou valores não finitos.".into()); + } + let sign = steady.signum(); + let mut peak_idx = 0usize; + let mut max_signed = sign * y[0]; + for (i, &val) in y.iter().enumerate().skip(1) { + let sv = sign * val; + if sv > max_signed { + max_signed = sv; + peak_idx = i; + } + } + let overshoot_pct = ((max_signed - steady.abs()) / steady.abs() * 100.0).max(0.0); + + // 10% to 90% rise time with linear interpolation + let interp_crossing = |target_frac: f64| -> Option { + let target = target_frac * steady.abs(); + let idx = y.iter().position(|&v| sign * v >= target)?; + if idx == 0 { + return Some(t[0]); + } + let y0 = sign * y[idx - 1]; + let y1 = sign * y[idx]; + let frac = if (y1 - y0).abs() > 1e-15 { + ((target - y0) / (y1 - y0)).clamp(0.0, 1.0) + } else { + 0.0 + }; + Some(t[idx - 1] + frac * (t[idx] - t[idx - 1])) + }; + let rise_time = interp_crossing(0.1) + .zip(interp_crossing(0.9)) + .map(|(t10, t90)| (t90 - t10).max(0.0)); + + // Definitive entry into +/- threshold band (last sample outside band) + let outside = y + .iter() + .rposition(|&v| (v / steady - 1.0).abs() > threshold); + let settling_time = match outside { + None => Some(0.0), + Some(i) if i + 1 < t.len() => { + let e0 = (y[i] / steady - 1.0).abs(); + let e1 = (y[i + 1] / steady - 1.0).abs(); + let frac = if (e0 - e1).abs() > 1e-15 { + ((e0 - threshold) / (e0 - e1)).clamp(0.0, 1.0) + } else { + 1.0 + }; + Some(t[i] + frac * (t[i + 1] - t[i])) + } + _ => None, + }; + + Ok(SampledMetrics { + overshoot_pct, + settling_time, + rise_time, + peak_time: t[peak_idx], + }) +} + +struct ModalDampingInfo { + measured_xi: Option, + measured_wn: Option, + pole_label: Option, + has_complex_pair: bool, + complex_pair_is_dominant: bool, + non_dominant_residue_ratio: Option, +} + +/// Evaluate polynomial P(s) at complex point s using Horner's method. +fn eval_poly_c(coeffs: &[f64], s: C) -> C { + coeffs + .iter() + .fold(C::new(0.0, 0.0), |acc, &c| acc * s + C::new(c, 0.0)) +} + +/// Identify the closed-loop pole or complex conjugate pair to which damping ratio (xi) +/// and natural frequency (wn) apply, and estimate the modal step-response residue ratio +/// of non-dominant modes versus the reference complex pair. +fn identify_damping_mode( + cl_poles: &[C], + active_poles: &[C], + cl_num: &[f64], + char_poly: &[f64], +) -> ModalDampingInfo { + if cl_poles.is_empty() { + return ModalDampingInfo { + measured_xi: None, + measured_wn: None, + pole_label: None, + has_complex_pair: false, + complex_pair_is_dominant: false, + non_dominant_residue_ratio: None, + }; + } + + // Prefer active (non-cancelled) complex conjugate pairs, falling back to all complex pairs. + let complex_candidates: Vec = active_poles + .iter() + .copied() + .filter(|p| p.im > 1e-6) + .collect(); + let complex_candidates = if complex_candidates.is_empty() { + cl_poles.iter().copied().filter(|p| p.im > 1e-6).collect() + } else { + complex_candidates + }; + + if let Some(pair) = complex_candidates + .iter() + .copied() + .max_by(|a, b| a.re.total_cmp(&b.re)) + { + let wn = pair.norm(); + let xi = if wn > 1e-12 { + (-pair.re / wn).clamp(-1.0, 1.0) + } else { + 0.0 + }; + + // Check if any active (uncancelled) real pole is slower than this complex pair + let slower_active_real: Vec = active_poles + .iter() + .copied() + .filter(|p| p.im.abs() <= 1e-6 && p.re > pair.re + 1e-4) + .collect(); + let complex_pair_is_dominant = slower_active_real.is_empty(); + + // Compute exact Heaviside modal residue ratio for T(s)/s when poles are well separated + let mut dom_res = 0.0; + let mut other_res = 0.0; + let mut residues_valid = !char_poly.is_empty() && char_poly[0].abs() > 1e-14; + if residues_valid { + let lead = char_poly[0]; + for (i, &p) in cl_poles.iter().enumerate() { + if p.norm() < 1e-9 { + residues_valid = false; + break; + } + let mut denom = C::new(lead, 0.0) * p; + for (j, &q) in cl_poles.iter().enumerate() { + if i == j { + continue; + } + let diff = p - q; + if diff.norm() < 1e-5 { + residues_valid = false; + break; + } + denom *= diff; + } + if !residues_valid { + break; + } + let r_mag = (eval_poly_c(cl_num, p) / denom).norm(); + if (p.re - pair.re).abs() < 1e-4 && (p.im.abs() - pair.im.abs()).abs() < 1e-4 { + dom_res += r_mag; + } else { + other_res += r_mag; + } + } + } + let non_dominant_residue_ratio = if residues_valid && dom_res > 1e-12 { + Some(other_res / dom_res) + } else { + None + }; + + let label = if cl_poles.len() <= 2 { + format!( + "par complexo ({} ± {}j)", + fmt_val(pair.re, 4), + fmt_val(pair.im.abs(), 4) + ) + } else if complex_pair_is_dominant { + format!( + "par complexo dominante ({} ± {}j)", + fmt_val(pair.re, 4), + fmt_val(pair.im.abs(), 4) + ) + } else { + let slow_str: Vec = slower_active_real + .iter() + .map(|p| fmt_val(p.re, 4)) + .collect(); + format!( + "par complexo ({} ± {}j; polo real mais lento em {})", + fmt_val(pair.re, 4), + fmt_val(pair.im.abs(), 4), + slow_str.join(", ") + ) + }; + + ModalDampingInfo { + measured_xi: Some(xi), + measured_wn: Some(wn), + pole_label: Some(label), + has_complex_pair: true, + complex_pair_is_dominant, + non_dominant_residue_ratio, + } + } else { + // All closed-loop poles are real (overdamped / critically damped => xi = 1.0) + let slowest = active_poles + .iter() + .chain(cl_poles.iter()) + .copied() + .max_by(|a, b| a.re.total_cmp(&b.re)); + let wn = slowest.map(|p| p.re.abs()); + let poles_str: Vec = cl_poles.iter().map(|p| fmt_val(p.re, 4)).collect(); + ModalDampingInfo { + measured_xi: Some(1.0), + measured_wn: wn, + pole_label: Some(format!( + "polos reais sem par complexo ({})", + poles_str.join(", ") + )), + has_complex_pair: false, + complex_pair_is_dominant: false, + non_dominant_residue_ratio: None, + } + } +} + +/// Comprehensive compliance verification of a candidate controller against plant, feedback, and specs. +pub fn verify_controller( + plant: &TransferFunction, + feedback: Option<&TransferFunction>, + controller: &TransferFunction, + specs: &DesignSpecs, +) -> Result { + let unity = TransferFunction::scalar(1.0); + let h = feedback.unwrap_or(&unity); + + // Unreduced characteristic polynomial: D_c*D_g*D_h + N_c*N_g*N_h = 0. + // Checking its roots detects BOTH external instability AND internal instability + // from unstable (RHP or jw) pole-zero cancellations. + let fwd_num = poly::multiply(&controller.num, &plant.num); + let fwd_den = poly::multiply(&controller.den, &plant.den); + let loop_num = poly::multiply(&fwd_num, &h.num); + let loop_den = poly::multiply(&fwd_den, &h.den); + let char_poly = poly::add(&loop_den, &loop_num, 1.0); + + let cl_poles = poly::roots(&char_poly)?; + let closed_loop_stable = !cl_poles.is_empty() && cl_poles.iter().all(|p| p.re < -1e-7); + + // Closed-loop T_YR(s) = (N_c*N_g*D_h) / (D_c*D_g*D_h + N_c*N_g*N_h) + let cl_num = poly::multiply(&fwd_num, &h.den); + let cl_zeros = poly::roots(&cl_num)?; + + // Detect pole-zero cancellations (both in open-loop Gc*G*H and closed-loop T_YR) + let mut cancellations = Vec::new(); + let mut cancelled_pole_idx = vec![false; cl_poles.len()]; + let mut cancelled_zero_idx = vec![false; cl_zeros.len()]; + for (zi, &z) in cl_zeros.iter().enumerate() { + let mut best: Option<(usize, f64)> = None; + for (pi, &p) in cl_poles.iter().enumerate() { + if cancelled_pole_idx[pi] { + continue; + } + let d = (p - z).norm(); + let tol = 0.05 * p.norm().max(1.0); + if d <= tol && best.is_none_or(|(_, bd)| d < bd) { + best = Some((pi, d)); + } + } + if let Some((pi, d)) = best { + cancelled_pole_idx[pi] = true; + cancelled_zero_idx[zi] = true; + cancellations.push(CancellationInfo { + pole: cl_poles[pi], + zero: z, + distance: d, + exact: d < 1e-4, + unstable: cl_poles[pi].re >= -1e-7, + }); + } + } + + // Also check open-loop unstable cancellations between Gc and G*H + let mut ol_unstable_cancel = false; + let gc_zeros = controller.zeros()?; + let gh_poles = poly::roots(&poly::multiply(&plant.den, &h.den))?; + for &z in &gc_zeros { + for &p in &gh_poles { + if p.re >= -1e-7 && (p - z).norm() < 1e-2 * p.norm().max(1.0) { + ol_unstable_cancel = true; + } + } + } + let internally_stable = + closed_loop_stable && !ol_unstable_cancel && !cancellations.iter().any(|c| c.unstable); + + // Remaining uncancelled poles & zeros + let active_poles: Vec = cl_poles + .iter() + .enumerate() + .filter(|(i, _)| !cancelled_pole_idx[*i]) + .map(|(_, &p)| p) + .collect(); + let extra_zeros: Vec = cl_zeros + .iter() + .enumerate() + .filter(|(i, _)| !cancelled_zero_idx[*i]) + .map(|(_, &z)| z) + .collect(); + + // Identify dominant pole(s) and non-dominant poles among active (uncancelled) poles + let dominant_pole = active_poles.iter().copied().max_by(|a, b| { + a.re.total_cmp(&b.re) + .then(b.im.abs().total_cmp(&a.im.abs())) + }); + let mut non_dominant_poles = Vec::new(); + let mut dominant_pole_ratio: Option = None; + if let Some(dom) = dominant_pole { + let dom_abs_re = dom.re.abs().max(1e-9); + for &p in &active_poles { + let is_dom_or_conj = (p - dom).norm() < 1e-4 || (p - dom.conj()).norm() < 1e-4; + if !is_dom_or_conj { + non_dominant_poles.push(p); + let ratio = p.re.abs() / dom_abs_re; + dominant_pole_ratio = Some(match dominant_pole_ratio { + Some(cur) => cur.min(ratio), + None => ratio, + }); + } + } + } + + // Identify reference pole/pair for damping ratio (xi) and natural frequency (wn) + let modal = identify_damping_mode(&cl_poles, &active_poles, &cl_num, &char_poly); + + // Build closed-loop TF for simulation (applying fast derivative filter only if improper) + let sim_cl_tf = { + let raw_cl = TransferFunction::new(cl_num.clone(), char_poly.clone())?; + if raw_cl.is_proper() { + raw_cl + } else { + let mut f = controller.multiply(plant)?; + while !f.is_proper() { + f = f.multiply(&TransferFunction::new(vec![1.0], vec![0.001, 1.0])?)?; + } + f.feedback(h, -1.0)? + } + }; + + // Steady-state error at summer and output tracking error + let loop_tf = TransferFunction::new(loop_num, loop_den)?; + let h_dc = exact_dc_gain(h); + let ol_type = system_type(&loop_tf); + let summer_ess = if !closed_loop_stable { + None + } else if ol_type >= 1 { + Some(0.0) + } else { + let kp_dc = exact_dc_gain(&loop_tf); + if kp_dc.is_infinite() { + Some(0.0) + } else { + Some(1.0 / (1.0 + kp_dc)) + } + }; + let steady_y = if closed_loop_stable { + Some(exact_dc_gain(&sim_cl_tf)) + } else { + None + }; + let output_tracking_error = steady_y.map(|y| 1.0 - y); + + // High-resolution time-domain simulation when closed-loop is stable + let threshold = if specs.settling_criterion_pct == 5 { + 0.05 + } else { + 0.02 + }; + let mut measured_mp = None; + let mut measured_ts = None; + let mut measured_tr = None; + let mut measured_tp = None; + if closed_loop_stable { + let slowest_decay = active_poles + .iter() + .map(|p| p.re.abs()) + .filter(|&r| r > 1e-6) + .fold(f64::INFINITY, f64::min); + let spec_ts = match specs.settling_time { + Some(SettlingSpec::AtMost(v)) => v, + Some(SettlingSpec::Equal { target, .. }) => target, + None => specs.theoretical_ts_s.unwrap_or(4.0), + }; + let mut horizon = if slowest_decay.is_finite() { + (14.0 / slowest_decay).max(spec_ts * 3.0).max(4.0) + } else { + (spec_ts * 3.0).max(10.0) + }; + horizon = horizon.clamp(1.0, 500.0); + if let Ok(mut m) = compute_step_metrics(&sim_cl_tf, horizon, 2500, threshold) { + // If settling time not reached yet, extend horizon once + if m.settling_time.is_none() && horizon < 500.0 { + let ext = (horizon * 3.0).min(500.0); + if let Ok(m2) = compute_step_metrics(&sim_cl_tf, ext, 3000, threshold) { + m = m2; + } + } + measured_mp = Some(m.overshoot_pct); + measured_ts = m.settling_time; + measured_tr = m.rise_time; + measured_tp = Some(m.peak_time); + } + } + + // Assemble diagnostic warnings + let mut warnings = Vec::new(); + for c in &cancellations { + if c.unstable { + warnings.push(format!( + "Cancelamento polo-zero instável em s = {} (distância {:0.2e}): malha internamente instável.", + fmt_complex(c.pole), + c.distance + )); + } else if c.exact { + warnings.push(format!( + "Cancelamento polo-zero nominal em s = {} (distância {:0.2e}): verificar robustez sob variações paramétricas da planta.", + fmt_complex(c.pole), + c.distance + )); + } else { + warnings.push(format!( + "Cancelamento polo-zero aproximado entre polo s = {} e zero s = {} (distância {:0.4}): dipolo residual sensível a perturbações.", + fmt_complex(c.pole), + fmt_complex(c.zero), + c.distance + )); + } + } + if let (Some(dom), Some(ratio)) = (dominant_pole, dominant_pole_ratio) + && ratio < 5.0 + { + let extra_list: Vec = non_dominant_poles + .iter() + .copied() + .map(fmt_complex) + .collect(); + warnings.push(format!( + "Dominância comprometida: polo(s) adicional(is) em {} possuem razão |Re(p)|/|Re(p_dom)| = {} < 5 em relação ao polo dominante {}.", + extra_list.join(", "), + fmt_val(ratio, 2), + fmt_complex(dom) + )); + } + if let Some(dom) = dominant_pole { + let dom_abs = dom.re.abs().max(1e-6); + let close_zeros: Vec = extra_zeros + .iter() + .filter(|z| z.norm() < 6.0 * dom_abs) + .copied() + .map(fmt_complex) + .collect(); + if !close_zeros.is_empty() { + warnings.push(format!( + "Limitação da aproximação de 2ª ordem: zero(s) de malha fechada não cancelado(s) em {} alteram o sobressinal real e o tempo de acomodação em relação às fórmulas padrão sem zeros.", + close_zeros.join(", ") + )); + } + } + if let (Some(xi), Some(mp_limit)) = (specs.theoretical_xi, specs.max_overshoot_pct) { + let mp_from_xi_val = math::mp_from_xi(xi); + if mp_from_xi_val > mp_limit + 0.05 { + warnings.push(format!( + "Incompatibilidade didática nas especificações: ξ = {} implica sobressinal teórico de 2ª ordem de {}%, superior ao limite literal Mp ≤ {}%.", + fmt_val(xi, 3), + fmt_val(mp_from_xi_val, 2), + fmt_val(mp_limit, 2) + )); + } + } + if (h_dc - 1.0).abs() > 1e-6 + && let (Some(y_ss), Some(ea)) = (steady_y, summer_ess) + { + warnings.push(format!( + "Realimentação não unitária H(0) = {}: o erro atuante no somador é e_a(∞) = {}, enquanto a saída converge para y(∞) = 1/H(0) = {} (erro de rastreamento r(∞) - y(∞) = {}).", + fmt_val(h_dc, 4), + fmt_val(ea, 4), + fmt_val(y_ss, 4), + fmt_val(1.0 - y_ss, 4) + )); + } + + // Build individual requirement checks + let mut checks = Vec::new(); + let mut failed_requirements = Vec::new(); + + // 1. Stability + checks.push(RequirementCheck { + id: "stability".into(), + label: "Estabilidade da malha fechada".into(), + requested: "Re(p) < 0 para todos os polos".into(), + theoretical: "Estável".into(), + measured: if closed_loop_stable { + "Estável".into() + } else { + "Instável".into() + }, + difference: "—".into(), + status: if closed_loop_stable { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }, + mandatory: true, + message: if closed_loop_stable { + "Todos os polos da equação característica estão no semiplano esquerdo.".into() + } else { + "Há polo(s) no semiplano direito ou sobre o eixo imaginário.".into() + }, + }); + if !closed_loop_stable { + failed_requirements.push("Estabilidade da malha fechada".into()); + } + + // 2. Internal stability + checks.push(RequirementCheck { + id: "internal_stability".into(), + label: "Estabilidade interna".into(), + requested: "Sem cancelamento polo-zero no SPD/jω".into(), + theoretical: "Internamente estável".into(), + measured: if internally_stable { + "Internamente estável".into() + } else { + "Instável internamente".into() + }, + difference: "—".into(), + status: if internally_stable { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }, + mandatory: true, + message: if internally_stable { + "Nenhum modo instável oculto por cancelamento polo-zero.".into() + } else { + "Detectada instabilidade interna ou cancelamento instável.".into() + }, + }); + if !internally_stable { + failed_requirements.push("Estabilidade interna".into()); + } + + // 3. Dominant pole placement (when desired_dominant_pole is provided) + if let Some(sd) = specs.desired_dominant_pole { + let min_dist = cl_poles + .iter() + .map(|p| (*p - sd).norm()) + .fold(f64::INFINITY, f64::min); + let closest = cl_poles + .iter() + .copied() + .min_by(|a, b| (*a - sd).norm().total_cmp(&(*b - sd).norm())) + .unwrap_or(C::new(f64::NAN, f64::NAN)); + let pole_ok = min_dist <= 1e-3; + let mandatory = specs.objective == DesignObjective::PolePlacement; + let status = if pole_ok { + RequirementStatus::Pass + } else if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }; + checks.push(RequirementCheck { + id: "dominant_poles".into(), + label: "Polos dominantes".into(), + requested: format!("s = {}", fmt_complex(sd)), + theoretical: format!("s = {}", fmt_complex(sd)), + measured: format!("s = {}", fmt_complex(closest)), + difference: format!("{:0.2e}", min_dist), + status, + mandatory, + message: if pole_ok { + "Polo dominante alocado exatamente na posição desejada.".into() + } else { + "Polo fechado mais próximo difere do polo nominal de 2ª ordem.".into() + }, + }); + if status == RequirementStatus::Fail { + failed_requirements.push("Polos dominantes".into()); + } + } + + // 4. Overshoot Mp + if let Some(mp_limit) = specs.max_overshoot_pct { + let theo = specs + .theoretical_mp_pct + .map(|v| format!("{} %", fmt_val(v, 2))) + .unwrap_or_else(|| "—".into()); + let mandatory = specs.objective == DesignObjective::TimeDomainConstraints; + let (meas_str, diff_str, status, msg) = match measured_mp { + Some(mp) => { + let diff = mp - mp_limit; + let ok = mp <= mp_limit + 1e-6; + let st = if ok { + RequirementStatus::Pass + } else if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }; + let m = if ok { + format!( + "Sobressinal real ({}%) atende ao limite Mp ≤ {}%.", + fmt_val(mp, 2), + fmt_val(mp_limit, 2) + ) + } else { + format!( + "Sobressinal real ({}%) excede o limite solicitado Mp ≤ {}% em {} pp.", + fmt_val(mp, 2), + fmt_val(mp_limit, 2), + fmt_val(diff, 2) + ) + }; + ( + format!("{} %", fmt_val(mp, 2)), + format!( + "{}{} pp", + if diff >= 0.0 { "+" } else { "" }, + fmt_val(diff, 2) + ), + st, + m, + ) + } + None => ( + "Indefinido".into(), + "—".into(), + if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }, + "Não foi possível medir o sobressinal (sistema instável ou ganho DC nulo).".into(), + ), + }; + checks.push(RequirementCheck { + id: "overshoot".into(), + label: "Sobressinal real (Mp)".into(), + requested: format!("≤ {} %", fmt_val(mp_limit, 2)), + theoretical: theo, + measured: meas_str, + difference: diff_str, + status, + mandatory, + message: msg, + }); + if status == RequirementStatus::Fail { + failed_requirements.push(format!("Sobressinal real (Mp ≤ {}%)", fmt_val(mp_limit, 2))); + } + } + + // 5. Settling time ts + if let Some(ts_spec) = specs.settling_time { + let theo = specs + .theoretical_ts_s + .map(|v| format!("{} s", fmt_val(v, 3))) + .unwrap_or_else(|| "—".into()); + let mandatory = specs.objective == DesignObjective::TimeDomainConstraints; + let req_str = match ts_spec { + SettlingSpec::AtMost(max_s) => format!( + "≤ {} s ({}%)", + fmt_val(max_s, 3), + specs.settling_criterion_pct + ), + SettlingSpec::Equal { target, tolerance } => format!( + "= {} ± {} s ({}%)", + fmt_val(target, 3), + fmt_val(tolerance, 2), + specs.settling_criterion_pct + ), + }; + let (meas_str, diff_str, status, msg) = match measured_ts { + Some(ts) => { + let (ok, diff) = match ts_spec { + SettlingSpec::AtMost(max_s) => (ts <= max_s + 1e-6, ts - max_s), + SettlingSpec::Equal { target, tolerance } => { + ((ts - target).abs() <= tolerance + 1e-6, ts - target) + } + }; + let st = if ok { + RequirementStatus::Pass + } else if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }; + let m = if ok { + format!( + "Tempo de acomodação definitivo ({} s) atende à especificação ({req_str}).", + fmt_val(ts, 3) + ) + } else { + format!( + "Tempo de acomodação definitivo ({} s) viola a especificação ({req_str}).", + fmt_val(ts, 3) + ) + }; + ( + format!("{} s", fmt_val(ts, 3)), + format!("{}{} s", if diff >= 0.0 { "+" } else { "" }, fmt_val(diff, 3)), + st, + m, + ) + } + None => ( + "Não acomodou".into(), + "—".into(), + if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }, + "A resposta não entrou definitivamente na faixa de tolerância no horizonte simulado.".into(), + ), + }; + checks.push(RequirementCheck { + id: "settling_time".into(), + label: format!( + "Tempo de acomodação real (ts {}%)", + specs.settling_criterion_pct + ), + requested: req_str.clone(), + theoretical: theo, + measured: meas_str, + difference: diff_str, + status, + mandatory, + message: msg, + }); + if status == RequirementStatus::Fail { + failed_requirements.push(format!("Tempo de acomodação ({req_str})")); + } + } + + // 6. Steady-state error (actuating error at summer) + if specs.require_zero_step_error { + let (meas_str, diff_str, status, msg) = match summer_ess { + Some(ea) => { + let ok = ea.abs() <= 1e-5; + ( + fmt_val(ea, 5), + fmt_val(ea, 5), + if ok { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }, + if ok { + "Erro estacionário nulo no somador para entrada degrau unitário.".into() + } else { + format!( + "Erro estacionário não nulo no somador: e_a(∞) = {} ≠ 0.", + fmt_val(ea, 5) + ) + }, + ) + } + None => ( + "Indefinido".into(), + "—".into(), + RequirementStatus::Fail, + "Erro estacionário indefinido (sistema instável).".into(), + ), + }; + checks.push(RequirementCheck { + id: "steady_state_error".into(), + label: "Erro estacionário (degrau)".into(), + requested: "= 0".into(), + theoretical: "0".into(), + measured: meas_str, + difference: diff_str, + status, + mandatory: true, + message: msg, + }); + if status == RequirementStatus::Fail { + failed_requirements.push("Erro estacionário nulo (e(∞) = 0)".into()); + } + } + + // 7. Damping ratio (xi): explicitly distinguishes mandatory equality, mandatory minimum, + // and optional didactic estimate, identifying which pole/pair it refers to. + let eff_damping = specs + .damping + .or_else(|| specs.theoretical_xi.map(DampingSpec::DidacticEstimate)); + if let Some(d_spec) = eff_damping { + let pole_ctx = modal + .pole_label + .as_deref() + .unwrap_or("polos de malha fechada"); + let (req_str, theo_str, mandatory) = match d_spec { + DampingSpec::Equal { target, tolerance } => ( + format!( + "= {} ± {} (obrigatória)", + fmt_val(target, 4), + fmt_val(tolerance, 3) + ), + fmt_val(target, 4), + true, + ), + DampingSpec::AtLeast(min_xi) => ( + format!("≥ {} (obrigatória)", fmt_val(min_xi, 4)), + fmt_val(min_xi, 4), + true, + ), + DampingSpec::DidacticEstimate(est) => ( + format!("≈ {} (estimativa didática opcional)", fmt_val(est, 4)), + fmt_val(est, 4), + false, + ), + }; + let (meas_str, diff_str, status, msg) = match modal.measured_xi { + Some(xi_m) => { + let meas_with_pole = format!("{} [{}]", fmt_val(xi_m, 4), pole_ctx); + match d_spec { + DampingSpec::Equal { target, tolerance } => { + let diff = xi_m - target; + let needs_complex = target < 1.0 - 1e-6; + let ok = (!needs_complex || modal.has_complex_pair) + && diff.abs() <= tolerance + 1e-6; + let st = if ok { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }; + let m = if ok { + format!( + "Amortecimento calculado ({}) em {} atende à igualdade obrigatória ξ = {} ± {}.", + fmt_val(xi_m, 4), + pole_ctx, + fmt_val(target, 4), + fmt_val(tolerance, 3) + ) + } else if needs_complex && !modal.has_complex_pair { + format!( + "Solicitada igualdade ξ = {} (subamortecido), mas todos os polos de malha fechada são reais ({}).", + fmt_val(target, 4), + pole_ctx + ) + } else { + format!( + "Amortecimento calculado ({}) em {} viola a igualdade obrigatória ξ = {} ± {} (dif.: {}{}).", + fmt_val(xi_m, 4), + pole_ctx, + fmt_val(target, 4), + fmt_val(tolerance, 3), + if diff >= 0.0 { "+" } else { "" }, + fmt_val(diff, 4) + ) + }; + ( + meas_with_pole, + format!("{}{}", if diff >= 0.0 { "+" } else { "" }, fmt_val(diff, 4)), + st, + m, + ) + } + DampingSpec::AtLeast(min_xi) => { + let diff = xi_m - min_xi; + let ok = xi_m >= min_xi - 1e-6; + let st = if ok { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }; + let m = if ok { + format!( + "Amortecimento calculado ({}) em {} atende ao limite mínimo ξ ≥ {}.", + fmt_val(xi_m, 4), + pole_ctx, + fmt_val(min_xi, 4) + ) + } else { + format!( + "Amortecimento calculado ({}) em {} fica abaixo do limite mínimo ξ ≥ {}.", + fmt_val(xi_m, 4), + pole_ctx, + fmt_val(min_xi, 4) + ) + }; + ( + meas_with_pole, + format!("{}{}", if diff >= 0.0 { "+" } else { "" }, fmt_val(diff, 4)), + st, + m, + ) + } + DampingSpec::DidacticEstimate(est) => { + let diff = xi_m - est; + let close = diff.abs() <= 0.02; + let st = if close { + RequirementStatus::Pass + } else { + RequirementStatus::Warning + }; + let m = format!( + "Estimativa didática opcional ξ ≈ {}; valor calculado em {} é {} (não é igualdade obrigatória).", + fmt_val(est, 4), + pole_ctx, + fmt_val(xi_m, 4) + ); + ( + meas_with_pole, + format!("{}{}", if diff >= 0.0 { "+" } else { "" }, fmt_val(diff, 4)), + st, + m, + ) + } + } + } + None => ( + "Indefinido".into(), + "—".into(), + if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }, + "Não foi possível calcular o coeficiente de amortecimento.".into(), + ), + }; + checks.push(RequirementCheck { + id: "damping_ratio".into(), + label: "Coeficiente de amortecimento (ξ)".into(), + requested: req_str.clone(), + theoretical: theo_str, + measured: meas_str, + difference: diff_str, + status, + mandatory, + message: msg, + }); + if mandatory && status == RequirementStatus::Fail { + failed_requirements.push(format!("Coeficiente de amortecimento ({req_str})")); + } + } + + // 8. Natural frequency (wn): mandatory equality / minimum vs optional estimate + let eff_wn = specs + .natural_freq + .or_else(|| specs.theoretical_wn.map(NaturalFreqSpec::OptionalEstimate)); + if let Some(wn_spec) = eff_wn { + let pole_ctx = modal + .pole_label + .as_deref() + .unwrap_or("polos de malha fechada"); + let (req_str, theo_str, mandatory) = match wn_spec { + NaturalFreqSpec::Equal { target, tolerance } => ( + format!( + "= {} ± {} rad/s (obrigatória)", + fmt_val(target, 4), + fmt_val(tolerance, 3) + ), + format!("{} rad/s", fmt_val(target, 4)), + true, + ), + NaturalFreqSpec::AtLeast(min_wn) => ( + format!("≥ {} rad/s (obrigatória)", fmt_val(min_wn, 4)), + format!("{} rad/s", fmt_val(min_wn, 4)), + true, + ), + NaturalFreqSpec::OptionalEstimate(est) => ( + format!("≈ {} rad/s (estimativa opcional)", fmt_val(est, 4)), + format!("{} rad/s", fmt_val(est, 4)), + false, + ), + }; + let (meas_str, diff_str, status, msg) = match modal.measured_wn { + Some(wn_m) => { + let meas_with_pole = format!("{} rad/s [{}]", fmt_val(wn_m, 4), pole_ctx); + match wn_spec { + NaturalFreqSpec::Equal { target, tolerance } => { + let diff = wn_m - target; + let ok = diff.abs() <= tolerance + 1e-6; + ( + meas_with_pole, + format!( + "{}{} rad/s", + if diff >= 0.0 { "+" } else { "" }, + fmt_val(diff, 4) + ), + if ok { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }, + if ok { + format!( + "Frequência natural calculada ({} rad/s) atende à restrição obrigatória.", + fmt_val(wn_m, 4) + ) + } else { + format!( + "Frequência natural calculada ({} rad/s) viola ωn = {} ± {} rad/s.", + fmt_val(wn_m, 4), + fmt_val(target, 4), + fmt_val(tolerance, 3) + ) + }, + ) + } + NaturalFreqSpec::AtLeast(min_wn) => { + let diff = wn_m - min_wn; + let ok = wn_m >= min_wn - 1e-6; + ( + meas_with_pole, + format!( + "{}{} rad/s", + if diff >= 0.0 { "+" } else { "" }, + fmt_val(diff, 4) + ), + if ok { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }, + if ok { + format!( + "Frequência natural ({} rad/s) atende a ωn ≥ {} rad/s.", + fmt_val(wn_m, 4), + fmt_val(min_wn, 4) + ) + } else { + format!( + "Frequência natural ({} rad/s) abaixo de ωn ≥ {} rad/s.", + fmt_val(wn_m, 4), + fmt_val(min_wn, 4) + ) + }, + ) + } + NaturalFreqSpec::OptionalEstimate(est) => { + let diff = wn_m - est; + ( + meas_with_pole, + format!( + "{}{} rad/s", + if diff >= 0.0 { "+" } else { "" }, + fmt_val(diff, 4) + ), + if diff.abs() <= default_wn_tolerance(est) { + RequirementStatus::Pass + } else { + RequirementStatus::Warning + }, + format!( + "Estimativa opcional ωn ≈ {} rad/s; obtido {} rad/s em {}.", + fmt_val(est, 4), + fmt_val(wn_m, 4), + pole_ctx + ), + ) + } + } + } + None => ( + "Indefinido".into(), + "—".into(), + if mandatory { + RequirementStatus::Fail + } else { + RequirementStatus::Warning + }, + "Frequência natural indefinida.".into(), + ), + }; + checks.push(RequirementCheck { + id: "natural_frequency".into(), + label: "Frequência natural (ωn)".into(), + requested: req_str.clone(), + theoretical: theo_str, + measured: meas_str, + difference: diff_str, + status, + mandatory, + message: msg, + }); + if mandatory && status == RequirementStatus::Fail { + failed_requirements.push(format!("Frequência natural ({req_str})")); + } + } + + // 9. Optional explicit dominance check on the complex pair when required + if specs.require_complex_dominance { + let ok = modal.has_complex_pair && modal.complex_pair_is_dominant; + checks.push(RequirementCheck { + id: "complex_dominance".into(), + label: "Dominância do par complexo".into(), + requested: "Par complexo como modo dominante ativo".into(), + theoretical: "Dominante".into(), + measured: modal + .pole_label + .clone() + .unwrap_or_else(|| "Indefinido".into()), + difference: modal + .non_dominant_residue_ratio + .map(|r| format!("razão res. {}", fmt_val(r, 3))) + .unwrap_or_else(|| "—".into()), + status: if ok { + RequirementStatus::Pass + } else { + RequirementStatus::Fail + }, + mandatory: true, + message: if ok { + "O par complexo conjugado é o modo dominante ativo da malha fechada.".into() + } else { + "Há polo real ativo mais lento que o par complexo conjugado (ou ausência de par complexo).".into() + }, + }); + if !ok { + failed_requirements.push("Dominância do par complexo".into()); + } + } + + let requirements_passed = closed_loop_stable + && internally_stable + && checks + .iter() + .all(|ck| !ck.mandatory || ck.status == RequirementStatus::Pass); + let has_warnings = !warnings.is_empty() + || checks + .iter() + .any(|ck| ck.status == RequirementStatus::Warning); + let overall_status = if !requirements_passed { + RequirementStatus::Fail + } else if has_warnings { + RequirementStatus::Warning + } else { + RequirementStatus::Pass + }; + + Ok(VerificationReport { + overall_status, + requirements_passed, + numerically_valid: true, + closed_loop_stable, + internally_stable, + closed_loop_poles: cl_poles, + closed_loop_zeros: cl_zeros, + dominant_pole, + dominant_pole_ratio, + non_dominant_poles, + extra_closed_loop_zeros: extra_zeros, + cancellations, + measured_xi: modal.measured_xi, + measured_wn: modal.measured_wn, + damping_pole_label: modal.pole_label, + has_complex_pair: modal.has_complex_pair, + complex_pair_is_dominant: modal.complex_pair_is_dominant, + non_dominant_residue_ratio: modal.non_dominant_residue_ratio, + measured_overshoot_pct: measured_mp, + measured_settling_time_s: measured_ts, + measured_rise_time_s: measured_tr, + measured_peak_time_s: measured_tp, + measured_steady_state_y: steady_y, + summer_steady_state_error: summer_ess, + output_tracking_error, + checks, + warnings, + failed_requirements, + }) +} + +struct BuiltController { + tf: TransferFunction, + kp: f64, + ki: f64, + kd: f64, + z: Option, + zi: Option, + p: Option, + k: Option, +} + +/// Build a TransferFunction from a parameter vector for a given ControllerStructure. +/// Parameters are stored in strictly positive canonical magnitudes (sign applied externally): +/// - P: [kp_mag] +/// - PI: [kp_mag, z] => sgn * kp_mag * (s + z) / s +/// - PD: [kd_mag, z] => sgn * kd_mag * (s + z) +/// - Lead: [k_mag, z, ratio] => sgn * k_mag * (s + z) / (s + z * (1 + ratio)) +/// - PID: [kd_mag, z1, z2] => sgn * kd_mag * (s + z1) * (s + z2) / s +fn build_candidate_tf( + structure: ControllerStructure, + params: &[f64], + sign: f64, +) -> Option { + if params + .iter() + .any(|v| !v.is_finite() || *v <= 1e-6 || *v > 1e5) + { + return None; + } + match structure { + ControllerStructure::P => { + let kp = sign * params[0]; + let tf = TransferFunction::new(vec![kp], vec![1.0]).ok()?; + Some(BuiltController { + tf, + kp, + ki: 0.0, + kd: 0.0, + z: None, + zi: None, + p: None, + k: Some(kp), + }) + } + ControllerStructure::PI => { + let kp = sign * params[0]; + let z = params[1]; + let ki = kp * z; + let tf = TransferFunction::new(vec![kp, ki], vec![1.0, 0.0]).ok()?; + Some(BuiltController { + tf, + kp, + ki, + kd: 0.0, + z: Some(z), + zi: None, + p: Some(0.0), + k: Some(kp), + }) + } + ControllerStructure::PD => { + let kd = sign * params[0]; + let z = params[1]; + let kp = kd * z; + let tf = TransferFunction::new(vec![kd, kp], vec![1.0]).ok()?; + Some(BuiltController { + tf, + kp, + ki: 0.0, + kd, + z: Some(z), + zi: None, + p: None, + k: Some(kd), + }) + } + ControllerStructure::Lead => { + let k = sign * params[0]; + let z = params[1]; + let p = z * (1.0 + params[2].max(0.25)); + let tf = TransferFunction::new(vec![k, k * z], vec![1.0, p]).ok()?; + Some(BuiltController { + tf, + kp: k, + ki: 0.0, + kd: 0.0, + z: Some(z), + zi: None, + p: Some(p), + k: Some(k), + }) + } + ControllerStructure::PID => { + let kp = sign * params[0]; + let ki = sign * params[1]; + let kd = sign * params[2]; + let tf = TransferFunction::new(vec![kd, kp, ki], vec![1.0, 0.0]).ok()?; + // Real zeros if discriminant >= 0; None if complex conjugate pair (still LHP minimum-phase) + let disc = kp * kp - 4.0 * kd * ki; + let (zi, z) = if disc >= 0.0 { + let s = disc.sqrt(); + let r1 = (kp.abs() - s) / (2.0 * kd.abs()); + let r2 = (kp.abs() + s) / (2.0 * kd.abs()); + (Some(r1), Some(r2)) + } else { + (None, None) + }; + Some(BuiltController { + tf, + kp, + ki, + kd, + z, + zi, + p: Some(0.0), + k: Some(kd), + }) + } + } +} + +/// Fast constraint-violation + regularization cost for numerical refinement. +fn evaluate_candidate_cost( + plant: &TransferFunction, + h: &TransferFunction, + structure: ControllerStructure, + params: &[f64], + sign: f64, + specs: &DesignSpecs, +) -> (f64, bool) { + let Some(built) = build_candidate_tf(structure, params, sign) else { + return (1e12, false); + }; + let (gc, kp, ki, kd) = (built.tf, built.kp, built.ki, built.kd); + let fwd_num = poly::multiply(&gc.num, &plant.num); + let fwd_den = poly::multiply(&gc.den, &plant.den); + let loop_num = poly::multiply(&fwd_num, &h.num); + let loop_den = poly::multiply(&fwd_den, &h.den); + let char_poly = poly::add(&loop_den, &loop_num, 1.0); + let Ok(poles) = poly::roots(&char_poly) else { + return (1e12, false); + }; + if poles.is_empty() { + return (1e12, false); + } + let max_re = poles.iter().map(|p| p.re).fold(f64::NEG_INFINITY, f64::max); + if max_re >= -1e-4 { + return (1e9 + 1e6 * (max_re + 0.01).max(0.0), false); + } + + let cl_num = poly::multiply(&fwd_num, &h.den); + let Ok(raw_cl) = TransferFunction::new(cl_num.clone(), char_poly.clone()) else { + return (1e12, false); + }; + let sim_tf = if raw_cl.is_proper() { + raw_cl + } else { + let Ok(mut f) = gc.multiply(plant) else { + return (1e12, false); + }; + while !f.is_proper() { + let Ok(next) = f.multiply(&TransferFunction::new(vec![1.0], vec![0.001, 1.0]).unwrap()) + else { + return (1e12, false); + }; + f = next; + } + let Ok(cl) = f.feedback(h, -1.0) else { + return (1e12, false); + }; + cl + }; + + let modal = identify_damping_mode(&poles, &poles, &cl_num, &char_poly); + + let threshold = if specs.settling_criterion_pct == 5 { + 0.05 + } else { + 0.02 + }; + let spec_ts = match specs.settling_time { + Some(SettlingSpec::AtMost(v)) => v, + Some(SettlingSpec::Equal { target, .. }) => target, + None => specs.theoretical_ts_s.unwrap_or(4.0), + }; + let slowest = poles + .iter() + .map(|p| p.re.abs()) + .fold(f64::INFINITY, f64::min) + .max(1e-3); + let horizon = (10.0 / slowest).max(spec_ts * 2.5).clamp(1.0, 200.0); + let Ok(m) = compute_step_metrics(&sim_tf, horizon, 500, threshold) else { + return (1e11, false); + }; + + let mut penalty = 0.0; + let mut feasible = true; + + // Mandatory damping ratio constraint + if let Some(d_spec) = specs.damping { + match d_spec { + DampingSpec::Equal { target, tolerance } => match modal.measured_xi { + Some(xi_m) => { + let needs_complex = target < 1.0 - 1e-6; + if needs_complex && !modal.has_complex_pair { + penalty += 5e5 + 1e4 * (1.0 - target); + feasible = false; + } else { + let err = (xi_m - target).abs(); + let safe_tol = (tolerance * 0.4).max(1e-3); + if err > safe_tol { + penalty += 5e4 * ((err - safe_tol) + (err - safe_tol).powi(2)); + } + penalty += 50.0 * err; + if err > tolerance { + feasible = false; + } + } + } + None => { + penalty += 1e6; + feasible = false; + } + }, + DampingSpec::AtLeast(min_xi) => match modal.measured_xi { + Some(xi_m) => { + let deficit = min_xi - xi_m; + if deficit > 0.0 { + penalty += 5e4 * (deficit + deficit * deficit); + feasible = false; + } + } + None => { + penalty += 1e6; + feasible = false; + } + }, + DampingSpec::DidacticEstimate(_) => {} + } + } + + // Mandatory natural frequency constraint + if let Some(wn_spec) = specs.natural_freq { + match wn_spec { + NaturalFreqSpec::Equal { target, tolerance } => match modal.measured_wn { + Some(wn_m) => { + let err = (wn_m - target).abs(); + let safe_tol = (tolerance * 0.4).max(1e-3); + if err > safe_tol { + penalty += 5e4 * ((err - safe_tol) + (err - safe_tol).powi(2)); + } + penalty += 25.0 * err; + if err > tolerance { + feasible = false; + } + } + None => { + penalty += 1e6; + feasible = false; + } + }, + NaturalFreqSpec::AtLeast(min_wn) => match modal.measured_wn { + Some(wn_m) => { + let deficit = min_wn - wn_m; + if deficit > 0.0 { + penalty += 5e4 * (deficit + deficit * deficit); + feasible = false; + } + } + None => { + penalty += 1e6; + feasible = false; + } + }, + NaturalFreqSpec::OptionalEstimate(_) => {} + } + } + + if specs.require_complex_dominance + && !(modal.has_complex_pair && modal.complex_pair_is_dominant) + { + penalty += 2e5; + feasible = false; + } + + if let Some(mp_max) = specs.max_overshoot_pct { + // Keep a tiny 0.05 pp safety margin during fast 500-point search so 2500-point verification passes cleanly. + let excess = m.overshoot_pct - (mp_max - 0.05); + if excess > 0.0 { + penalty += 1e4 * (excess + excess * excess); + } + if m.overshoot_pct > mp_max { + feasible = false; + } + } + + if let Some(ts_spec) = specs.settling_time { + match m.settling_time { + Some(ts) => match ts_spec { + SettlingSpec::AtMost(max_s) => { + let excess = ts - (max_s - 0.01); + if excess > 0.0 { + penalty += 1e4 * (excess + excess * excess); + } + if ts > max_s { + feasible = false; + } + } + SettlingSpec::Equal { target, tolerance } => { + let err = (ts - target).abs(); + let safe_tol = (tolerance * 0.4).max(0.005); + if err > safe_tol { + penalty += 1e4 * ((err - safe_tol) + (err - safe_tol).powi(2)); + } + penalty += 25.0 * err; + if err > tolerance { + feasible = false; + } + } + }, + None => { + penalty += 1e6; + feasible = false; + } + } + } + + if specs.require_zero_step_error { + let Ok(ol) = TransferFunction::new(loop_num, loop_den) else { + return (1e12, false); + }; + if system_type(&ol) == 0 { + let kp_dc = exact_dc_gain(&ol); + let ess = 1.0 / (1.0 + kp_dc); + penalty += 1e6 * ess * ess; + if ess.abs() > 1e-5 { + feasible = false; + } + } + } + + // Mild regularization favoring modest controller gains, avoiding ultra-slow near-origin + // pole-zero dipoles, and preferring cleaner modal dominance. + let sigma_ref = (4.0 / spec_ts.max(0.1)).clamp(0.1, 20.0); + let slow_pole_pen = if slowest < 0.05 * sigma_ref { + 50.0 * (0.05 * sigma_ref - slowest) / (0.05 * sigma_ref) + } else { + 0.0 + }; + let gain_reg = 1e-3 * (kp.abs() + ki.abs() + kd.abs()).ln_1p(); + let res_reg = modal + .non_dominant_residue_ratio + .map(|r| 0.05 * r.min(20.0)) + .unwrap_or(0.0); + (penalty + slow_pole_pen + gain_reg + res_reg, feasible) +} + +/// Adaptive coordinate + coupled-diagonal pattern search (derivative-free, deterministic, bounded). +fn pattern_search_refine( + plant: &TransferFunction, + h: &TransferFunction, + structure: ControllerStructure, + mut best_params: Vec, + sign: f64, + specs: &DesignSpecs, + eval_counter: &mut usize, +) -> Vec { + let dim = best_params.len(); + let (mut best_cost, _) = + evaluate_candidate_cost(plant, h, structure, &best_params, sign, specs); + *eval_counter += 1; + let mut step: Vec = best_params.iter().map(|&v| (v * 0.35).max(0.05)).collect(); + + for _iter in 0..110 { + let mut improved = false; + for d in 0..dim { + for dir in [1.0, -1.0] { + let mut cand = best_params.clone(); + cand[d] += dir * step[d]; + if cand[d] <= 1e-4 { + continue; + } + let (cost, _) = evaluate_candidate_cost(plant, h, structure, &cand, sign, specs); + *eval_counter += 1; + if cost < best_cost - 1e-12 { + best_cost = cost; + best_params = cand; + step[d] *= 1.15; + improved = true; + break; + } + } + } + // Coupled pairwise moves help traverse narrow constraint valleys (e.g., exact xi + exact ts) + if !improved && dim >= 2 { + 'diag: for i in 0..dim { + for j in (i + 1)..dim { + for &(si, sj) in &[(1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] { + let mut cand = best_params.clone(); + cand[i] += si * step[i]; + cand[j] += sj * step[j]; + if cand[i] <= 1e-4 || cand[j] <= 1e-4 { + continue; + } + let (cost, _) = + evaluate_candidate_cost(plant, h, structure, &cand, sign, specs); + *eval_counter += 1; + if cost < best_cost - 1e-12 { + best_cost = cost; + best_params = cand; + improved = true; + break 'diag; + } + } + } + } + } + if !improved { + for s in &mut step { + *s *= 0.55; + } + if step.iter().all(|&s| s < 1e-4) { + break; + } + } + } + best_params +} + +/// Check algebraic infeasibility of a controller structure before numerical search. +fn algebraic_infeasibility_reason( + plant: &TransferFunction, + h: &TransferFunction, + structure: ControllerStructure, + specs: &DesignSpecs, +) -> Option { + let ol = plant.multiply(h).ok()?; + let otype = system_type(&ol); + if specs.require_zero_step_error && otype == 0 && !structure.has_integrator() { + return Some(format!( + "Inviabilidade comprovada — estrutura {} para e(∞) = 0 ao degrau: a planta em malha aberta G(s)H(s) é Tipo 0 (sem polo na origem), resultando em erro estacionário finito e(∞) = 1/(1 + Kp) ≠ 0 sem ação integral.", + structure.as_str() + )); + } + // Pure double integrator (s^2 in denominator, no finite zeros) cannot be stabilized by P or PI alone + let ol_zeros = ol.zeros().unwrap_or_default(); + if otype >= 2 + && ol_zeros.is_empty() + && matches!(structure, ControllerStructure::P | ControllerStructure::PI) + { + return Some(format!( + "Inviabilidade comprovada — estrutura {} para planta Tipo {} sem zeros finitos: o lugar das raízes permanece sobre o eixo imaginário ou no semiplano direito (impossível estabilizar sem avanço de fase/ação derivativa).", + structure.as_str(), + otype + )); + } + // Exact proof for 2nd-order undamped plants G(s) = k/(s^2 + c) with c >= 0 under unity feedback and PD: + // With k*Kd = 2*xi*wn and c + k*Kp = wn^2: + // T(s) = (2*xi*wn*s + wn^2 - c) / (s^2 + 2*xi*wn*s + wn^2). + // Steady-state gain is y(inf) = T(0) = alpha = 1 - c/wn^2. + // - If c = 0 (double integrator): alpha = 1, T(wn*u) = (2*xi*u + 1)/(u^2 + 2*xi*u + 1), strictly time-scale + // invariant for all wn > 0 => constant overshoot Mp(xi). + // - If c > 0 (undamped oscillator, e.g. 1/(s^2 + 1)): positive steady-state tracking requires k*Kp > 0 + // (wn^2 > c), so alpha = 1 - c/wn^2 in (0, 1). Normalizing by y(inf) = alpha yields + // T_norm(wn*u) = T(wn*u)/alpha = ((2*xi/alpha)*u + 1)/(u^2 + 2*xi*u + 1) = H0(u) + (2*xi/alpha)*u*H0(u). + // In dimensionless time tau = wn*t, h0(tau) = L^{-1}{u*H0(u)} > 0 on (0, pi/sqrt(1 - xi^2)), and since + // 2*xi/alpha > 2*xi strictly, max_tau y_norm(tau) >= y_norm(tau*) > max_tau y_{alpha=1}(tau) for every wn > sqrt(c). + let h_is_unity = + h.num.len() == 1 && h.den.len() == 1 && (h.num[0] / h.den[0] - 1.0).abs() < 1e-12; + if structure == ControllerStructure::PD + && h_is_unity + && ol.num.len() == 1 + && ol.den.len() == 3 + && ol.den[1].abs() < 1e-12 + && ol.den[2] / ol.den[0] >= -1e-12 + && let ( + Some(DampingSpec::Equal { + target: xi0, + tolerance: xi_tol, + }), + Some(mp_max), + ) = (specs.damping, specs.max_overshoot_pct) + && xi0 > 0.0 + && xi0 < 1.0 + { + let c_val = ol.den[2] / ol.den[0]; + let xi_upper = (xi0 + xi_tol).min(0.999); + // Scale-invariant lower bound for alpha = 1: T_ref(u) = (2*xi_upper*u + 1)/(u^2 + 2*xi_upper*u + 1) + if let Ok(t_ref) = + TransferFunction::new(vec![2.0 * xi_upper, 1.0], vec![1.0, 2.0 * xi_upper, 1.0]) + && let Ok(m_ref) = compute_step_metrics(&t_ref, 25.0, 2000, 0.02) + && m_ref.overshoot_pct > mp_max + 0.05 + { + if c_val <= 1e-12 { + return Some(format!( + "Inviabilidade matemática comprovada — PD para duplo integrador G(s)=k/s² com igualdade exata ξ = {} ± {} e Mp ≤ {}%: com y(∞)=1, T(ωn·u) = (2ξu + 1)/(u² + 2ξu + 1) é invariante em escala e impõe sobressinal constante ≥ {}% para todo ωn > 0.", + fmt_val(xi0, 4), + fmt_val(xi_tol, 3), + fmt_val(mp_max, 2), + fmt_val(m_ref.overshoot_pct, 2) + )); + } else { + return Some(format!( + "Inviabilidade matemática comprovada — PD para oscilador não amortecido G(s)=k/(s² + {}) com igualdade exata ξ = {} ± {} e Mp ≤ {}%: qualquer PD estabilizante com rastreamento positivo exige ωn² > {}, resultando em ganho estacionário y(∞) = α = 1 - {}/ωn² ∈ (0, 1) e função normalizada T(ωn·u)/y(∞) = ((2ξ/α)u + 1)/(u² + 2ξu + 1); como 2ξ/α > 2ξ e h₀(τ) > 0 no primeiro semiciclo, o sobressinal percentual é estritamente superior à cota de {}% para todo ωn > √{}.", + fmt_val(c_val, 4), + fmt_val(xi0, 4), + fmt_val(xi_tol, 3), + fmt_val(mp_max, 2), + fmt_val(c_val, 4), + fmt_val(c_val, 4), + fmt_val(m_ref.overshoot_pct, 2), + fmt_val(c_val, 4) + )); + } + } + } + None +} + +/// Generic constrained synthesis for a specific controller structure. +pub fn synthesize_for_structure( + plant: &TransferFunction, + feedback: Option<&TransferFunction>, + structure: ControllerStructure, + specs: &DesignSpecs, +) -> Result { + let unity = TransferFunction::scalar(1.0); + let h = feedback.unwrap_or(&unity); + let ol = plant.multiply(h)?; + + if let Some(reason) = algebraic_infeasibility_reason(plant, h, structure, specs) { + return Ok(SynthesisOutcome { + feasible: false, + feasibility_class: FeasibilityClass::ProvenInfeasible, + selected: None, + infeasibility_reasons: vec![reason], + alternatives: vec![], + candidates_evaluated: 0, + }); + } + + let sign = plant_sign(&ol); + let poles = ol.poles()?; + let stable_real_poles: Vec = poles + .iter() + .filter(|p| p.im.abs() < 1e-4 && p.re < -1e-4) + .map(|p| -p.re) + .collect(); + + let ts_ref = match specs.settling_time { + Some(SettlingSpec::AtMost(v)) => v, + Some(SettlingSpec::Equal { target, .. }) => target, + None => specs.theoretical_ts_s.unwrap_or(4.0), + }; + let sigma_scale = (4.0 / ts_ref.max(0.1)).clamp(0.1, 20.0); + let gain_scale = (ol.den[0] / ol.num[0]).abs().clamp(1e-3, 1e3); + + // Generate generic structured parameter seeds + let mut seeds: Vec<(String, Vec)> = Vec::new(); + match structure { + ControllerStructure::P => { + for exp in -20..=20 { + let k = gain_scale * 10.0_f64.powf(exp as f64 * 0.15); + seeds.push(("grid_p".into(), vec![k])); + } + } + ControllerStructure::PI => { + // 1. Generic stable real plant pole cancellation family (z = -p_i) + for &zp in &stable_real_poles { + for &mult in &[0.2, 0.5, 0.8, 1.0, 1.4, 2.0, 3.5, 6.0, 12.0] { + seeds.push(( + "pole_cancellation_pi".into(), + vec![gain_scale * sigma_scale * mult, zp], + )); + } + } + // 2. General 2D (Kp, z) grid + for &z_mult in &[0.1, 0.3, 0.6, 1.0, 1.8, 3.5, 7.0] { + for &k_mult in &[0.2, 0.6, 1.5, 4.0, 10.0, 25.0] { + seeds.push(( + "constrained_pi".into(), + vec![gain_scale * sigma_scale * k_mult, sigma_scale * z_mult], + )); + } + } + } + ControllerStructure::PD => { + // 1. Generic stable real plant pole cancellation family (z = -p_i) + for &zp in &stable_real_poles { + for &mult in &[0.2, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0] { + seeds.push(( + "pole_cancellation_pd".into(), + vec![gain_scale * sigma_scale * mult, zp], + )); + } + } + // 2. General 2D (Kd, z) grid spanning underdamped, critically damped, and overdamped + for &z_mult in &[0.2, 0.5, 0.8, 1.0, 1.5, 2.0, 3.0, 5.0] { + for &k_mult in &[0.25, 0.6, 1.2, 2.0, 3.5, 6.0, 12.0, 25.0, 50.0] { + seeds.push(( + "constrained_pd".into(), + vec![gain_scale * sigma_scale * k_mult, sigma_scale * z_mult], + )); + } + } + } + ControllerStructure::Lead => { + for &z_mult in &[0.3, 0.7, 1.2, 2.0, 3.5] { + for &ratio in &[1.5, 4.0, 10.0] { + for &k_mult in &[0.5, 2.0, 8.0, 30.0] { + seeds.push(( + "constrained_lead".into(), + vec![ + gain_scale * sigma_scale * k_mult, + sigma_scale * z_mult, + ratio, + ], + )); + } + } + } + } + ControllerStructure::PID => { + // Parameterized directly in canonical PID gains [kp_mag, ki_mag, kd_mag] so both + // real-zero and complex-conjugate-zero minimum-phase PIDs are represented uniformly. + // 1. Double-pole or single-pole cancellation seeds + for &zp in &stable_real_poles { + for &k_mult in &[0.5, 2.0, 8.0, 30.0, 100.0] { + let kd = gain_scale * k_mult; + seeds.push(( + "pole_cancellation_pid".into(), + vec![kd * (2.0 * zp), kd * zp * zp, kd], + )); + let z2 = sigma_scale * 1.5; + seeds.push(( + "pole_cancellation_pid".into(), + vec![kd * (zp + z2), kd * zp * z2, kd], + )); + } + } + // 2. General real-zero (well-separated & equal) and complex-zero PID seeds + for &z1_m in &[0.06, 0.25, 0.7, 1.5] { + for &z2_m in &[0.4, 0.9, 2.0] { + for &k_mult in &[0.5, 2.0, 8.0, 20.0, 50.0] { + let kd = gain_scale * sigma_scale * k_mult; + let z1 = sigma_scale * z1_m; + let z2 = sigma_scale * z2_m; + seeds.push(( + "constrained_pid".into(), + vec![kd * (z1 + z2), kd * z1 * z2, kd], + )); + } + } + } + // 3. Complex-conjugate-zero minimum-phase PID seeds (kp^2 < 4*kd*ki) + for &wn_z_m in &[0.5, 1.0, 1.8] { + for &xi_z in &[0.35, 0.65] { + for &k_mult in &[0.5, 2.0, 5.0, 15.0] { + let kd = gain_scale * sigma_scale * k_mult; + let wz = sigma_scale * wn_z_m; + seeds.push(( + "constrained_pid_complex_zeros".into(), + vec![kd * (2.0 * xi_z * wz), kd * wz * wz, kd], + )); + } + } + } + } + } + + let mut eval_counter = 0usize; + let mut ranked: Vec<(f64, String, Vec)> = Vec::with_capacity(seeds.len()); + for (tag, params) in seeds { + let (cost, _) = evaluate_candidate_cost(plant, h, structure, ¶ms, sign, specs); + eval_counter += 1; + ranked.push((cost, tag, params)); + } + ranked.sort_by(|a, b| a.0.total_cmp(&b.0)); + + // Refine top 6 seeds and perform full 2500-point verification on each + let mut best_feasible: Option<(f64, SynthesizedController)> = None; + let mut best_infeasible: Option<(f64, SynthesizedController)> = None; + + for (_, tag, seed) in ranked.into_iter().take(6) { + let refined = + pattern_search_refine(plant, h, structure, seed, sign, specs, &mut eval_counter); + let Some(built) = build_candidate_tf(structure, &refined, sign) else { + continue; + }; + let Ok(verification) = verify_controller(plant, feedback, &built.tf, specs) else { + continue; + }; + let (score, _) = evaluate_candidate_cost(plant, h, structure, &refined, sign, specs); + let synth = SynthesizedController { + structure, + transfer: built.tf, + kp: built.kp, + ki: built.ki, + kd: built.kd, + z: built.z, + zi: built.zi, + p: built.p, + k: built.k, + method_used: format!("{tag}_refined"), + verification, + }; + if synth.verification.requirements_passed { + if best_feasible.as_ref().is_none_or(|(s, _)| score < *s) { + best_feasible = Some((score, synth)); + } + } else if best_infeasible.as_ref().is_none_or(|(s, _)| score < *s) { + best_infeasible = Some((score, synth)); + } + } + + if let Some((_, winner)) = best_feasible { + Ok(SynthesisOutcome { + feasible: true, + feasibility_class: FeasibilityClass::Feasible, + selected: Some(winner), + infeasibility_reasons: vec![], + alternatives: vec![], + candidates_evaluated: eval_counter, + }) + } else { + let mut reasons = Vec::new(); + let selected = best_infeasible.map(|(_, c)| { + if !c.verification.failed_requirements.is_empty() { + reasons.push(format!( + "Solução não encontrada nos limites de busca numérica para {} (não implica prova de inviabilidade matemática); requisitos violados no melhor candidato: {}.", + structure.as_str(), + c.verification.failed_requirements.join(", ") + )); + } + c + }); + if reasons.is_empty() { + reasons.push(format!( + "Solução não encontrada nos limites de busca numérica para {} (nenhum candidato estabilizante viável localizado).", + structure.as_str() + )); + } + Ok(SynthesisOutcome { + feasible: false, + feasibility_class: FeasibilityClass::NotFoundWithinSearchBounds, + selected, + infeasibility_reasons: reasons, + alternatives: vec![], + candidates_evaluated: eval_counter, + }) + } +} + +/// Automatically select the simplest controller structure (P -> PI -> PD -> Lead -> PID) +/// that satisfies all specifications, returning explicit infeasibility diagnostics for +/// rejected simpler structures. +pub fn synthesize_simplest( + plant: &TransferFunction, + feedback: Option<&TransferFunction>, + specs: &DesignSpecs, +) -> Result { + let mut total_evals = 0usize; + let mut infeasibility_reasons = Vec::new(); + let mut best_fallback: Option = None; + let mut all_proven_infeasible = true; + + for structure in ControllerStructure::complexity_order() { + let outcome = synthesize_for_structure(plant, feedback, structure, specs)?; + total_evals += outcome.candidates_evaluated; + if outcome.feasible + && let Some(winner) = outcome.selected + { + return Ok(SynthesisOutcome { + feasible: true, + feasibility_class: FeasibilityClass::Feasible, + selected: Some(winner), + infeasibility_reasons, + alternatives: vec![], + candidates_evaluated: total_evals, + }); + } + if outcome.feasibility_class != FeasibilityClass::ProvenInfeasible { + all_proven_infeasible = false; + } + infeasibility_reasons.extend(outcome.infeasibility_reasons); + if best_fallback.is_none() { + best_fallback = outcome.selected; + } + } + + Ok(SynthesisOutcome { + feasible: false, + feasibility_class: if all_proven_infeasible { + FeasibilityClass::ProvenInfeasible + } else { + FeasibilityClass::NotFoundWithinSearchBounds + }, + selected: best_fallback, + infeasibility_reasons, + alternatives: vec![], + candidates_evaluated: total_evals, + }) +} diff --git a/crates/control-engine/src/controllers.rs b/crates/control-engine/src/controllers.rs index 4051763..322a18f 100644 --- a/crates/control-engine/src/controllers.rs +++ b/crates/control-engine/src/controllers.rs @@ -535,16 +535,6 @@ fn controller_latex(kind: &str, p: &Value) -> Result { if kind == "PID" { raw = raw.replace("+ -", "- "); raw = raw.replace("+ \\frac{-", "- \\frac{"); - if !p["zi"].is_null() && !p["z"].is_null() { - let zi = n(&p["zi"]); - let zd = n(&p["z"]); - if (zi - zd).abs() < 1e-4 && zi > 0. { - let z_str = fmt(&p["z"], 4, true); - let double_factor = format!("(s + {z_str})(s + {z_str})"); - let squared = format!("(s + {z_str})^2"); - raw = raw.replace(&double_factor, &squared); - } - } } Ok(raw) } @@ -771,6 +761,14 @@ pub fn analyze(p: &Value) -> Result { .or_else(|| p["expr"].as_str().filter(|s| !s.is_empty())) .unwrap_or("5 / (s * (s + 1))"); let plant = TransferFunction::parse(expr)?; + let synth_mode = p["synthesis_mode"] + .as_str() + .unwrap_or("") + .trim() + .to_lowercase(); + if matches!(synth_mode.as_str(), "temporal_refined" | "auto_simplest") { + return analyze_constrained(p, &plant, &synth_mode); + } let method = p["method"].as_str().unwrap_or("").to_lowercase(); if [ "zn_critical", @@ -789,6 +787,550 @@ pub fn analyze(p: &Value) -> Result { } universal(p, &plant) } + +fn specs_from_payload( + p: &Value, + cp: Option<&Value>, +) -> Result { + use crate::controller_synthesis::{ + DampingSpec, DesignObjective, DesignSpecs, NaturalFreqSpec, SettlingSpec, + default_damping_tolerance, default_settling_tolerance, default_wn_tolerance, + }; + let crit = p["settling_criterion"] + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| p["settling_criterion"].to_string()) + .replace('%', ""); + let criterion_pct: u8 = if crit.trim() == "5" { 5 } else { 2 }; + + let desired_pole = math::desired_pole(&p["desired_pole"])?; + let explicit_mp = optional(p, "mp")?; + let explicit_ts = optional(p, "ts")?; + let explicit_xi = optional(p, "xi")?; + let explicit_wn = optional(p, "wn")?; + + let objective = match p["design_objective"] + .as_str() + .unwrap_or("") + .trim() + .to_lowercase() + .as_str() + { + "pole_placement" | "poles" => DesignObjective::PolePlacement, + "temporal" | "temporal_constraints" | "time_domain" => { + DesignObjective::TimeDomainConstraints + } + _ => { + if desired_pole.is_some() + || (explicit_xi.is_some() + && explicit_wn.is_some() + && explicit_mp.is_none() + && explicit_ts.is_none()) + { + DesignObjective::PolePlacement + } else { + DesignObjective::TimeDomainConstraints + } + } + }; + + let theo_xi = explicit_xi + .or_else(|| cp.and_then(|v| v["xi"].as_f64())) + .or_else(|| { + explicit_mp + .filter(|&m| m > 0.0 && m < 100.0) + .and_then(|m| math::xi_from_mp(m).ok()) + }); + let theo_wn = explicit_wn + .or_else(|| cp.and_then(|v| v["wn"].as_f64())) + .or_else(|| { + theo_xi.zip(explicit_ts).map(|(x, ts)| { + let factor = if criterion_pct == 5 { 3.0 } else { 4.0 }; + factor / (x * ts) + }) + }); + let theo_mp = theo_xi + .filter(|&x| x > 0.0 && x < 1.0) + .map(math::mp_from_xi) + .or_else(|| cp.and_then(|v| v["mp"].as_f64())); + let theo_ts = cp + .and_then(|v| v["ts"].as_f64()) + .or(explicit_ts) + .or_else(|| { + theo_xi.zip(theo_wn).map(|(x, w)| { + let factor = if criterion_pct == 5 { 3.0 } else { 4.0 }; + factor / (x * w) + }) + }); + + // Only enforce overshoot Mp as a mandatory cap when Mp was explicitly requested + // (never silently replace an explicit xi equality with an Mp inequality). + let max_overshoot_pct = explicit_mp; + + // Explicit damping ratio semantics: + // - "equal": mandatory equality |xi - target| <= xi_tol + // - "at_least": mandatory lower bound xi >= target + // - "estimate": optional didactic estimate (informational only) + // - "auto" (default): if xi was explicitly entered WITHOUT Mp, preserve equality ("equal"); + // if both Mp and xi were entered (didactic pairing), treat xi as didactic estimate unless overridden; + // if only Mp was entered, treat derived xi as didactic estimate. + let xi_constraint_mode = p["xi_constraint"] + .as_str() + .unwrap_or("auto") + .trim() + .to_lowercase(); + let xi_tol = optional(p, "xi_tolerance")?.unwrap_or_else(default_damping_tolerance); + let damping = match (explicit_xi, theo_xi) { + (Some(xi), _) => match xi_constraint_mode.as_str() { + "equal" | "igualdade" => Some(DampingSpec::Equal { + target: xi, + tolerance: xi_tol, + }), + "at_least" | "min" | "minimo" => Some(DampingSpec::AtLeast(xi)), + "estimate" | "didactic" | "estimativa" => Some(DampingSpec::DidacticEstimate(xi)), + _ => { + if explicit_mp.is_none() { + Some(DampingSpec::Equal { + target: xi, + tolerance: xi_tol, + }) + } else { + Some(DampingSpec::DidacticEstimate(xi)) + } + } + }, + (None, Some(xi)) => match xi_constraint_mode.as_str() { + "equal" | "igualdade" => Some(DampingSpec::Equal { + target: xi, + tolerance: xi_tol, + }), + "at_least" | "min" | "minimo" => Some(DampingSpec::AtLeast(xi)), + _ => Some(DampingSpec::DidacticEstimate(xi)), + }, + (None, None) => None, + }; + + // Explicit natural frequency semantics: + let wn_constraint_mode = p["wn_constraint"] + .as_str() + .unwrap_or("auto") + .trim() + .to_lowercase(); + let wn_tol_opt = optional(p, "wn_tolerance")?; + let natural_freq = match (explicit_wn, theo_wn) { + (Some(wn), _) => { + let tol = wn_tol_opt.unwrap_or_else(|| default_wn_tolerance(wn)); + match wn_constraint_mode.as_str() { + "at_least" | "min" | "minimo" => Some(NaturalFreqSpec::AtLeast(wn)), + "estimate" | "estimativa" => Some(NaturalFreqSpec::OptionalEstimate(wn)), + _ => Some(NaturalFreqSpec::Equal { + target: wn, + tolerance: tol, + }), + } + } + (None, Some(wn)) => { + let tol = wn_tol_opt.unwrap_or_else(|| default_wn_tolerance(wn)); + match wn_constraint_mode.as_str() { + "equal" | "igualdade" => Some(NaturalFreqSpec::Equal { + target: wn, + tolerance: tol, + }), + "at_least" | "min" | "minimo" => Some(NaturalFreqSpec::AtLeast(wn)), + _ => Some(NaturalFreqSpec::OptionalEstimate(wn)), + } + } + (None, None) => None, + }; + + let require_complex_dominance = p["require_complex_dominance"].as_bool().unwrap_or(false); + + let ts_constraint_mode = p["ts_constraint"] + .as_str() + .unwrap_or("at_most") + .trim() + .to_lowercase(); + let ts_tol_opt = optional(p, "ts_tolerance")?; + let settling_time = explicit_ts.or(theo_ts).map(|v| { + if ts_constraint_mode == "equal" { + let tol = ts_tol_opt.unwrap_or_else(|| default_settling_tolerance(v)); + SettlingSpec::Equal { + target: v, + tolerance: tol, + } + } else { + SettlingSpec::AtMost(v) + } + }); + + let kind_str = p["controller_type"] + .as_str() + .unwrap_or("") + .trim() + .to_uppercase(); + let require_zero_step_error = p["require_zero_error"] + .as_bool() + .unwrap_or(matches!(kind_str.as_str(), "PI" | "PID")); + + let dom_pole = desired_pole.or_else(|| { + cp.and_then(|v| { + let re = v["re"].as_f64()?; + let im = v["im"].as_f64()?; + (re > 0.0 && im > 0.0).then_some(C::new(-re, im)) + }) + }); + + Ok(DesignSpecs { + objective, + max_overshoot_pct, + settling_time, + settling_criterion_pct: criterion_pct, + damping, + natural_freq, + require_complex_dominance, + require_zero_step_error, + desired_dominant_pole: dom_pole, + theoretical_xi: theo_xi, + theoretical_wn: theo_wn, + theoretical_mp_pct: theo_mp, + theoretical_ts_s: theo_ts, + }) +} + +fn analyze_constrained(p: &Value, forward: &TransferFunction, synth_mode: &str) -> Result { + use crate::controller_synthesis::{ + ControllerStructure, synthesize_for_structure, synthesize_simplest, + }; + + let feedback = p["feedback_expr"] + .as_str() + .filter(|s| !s.trim().is_empty() && !matches!(s.trim(), "1" | "1.0")) + .map(TransferFunction::parse) + .transpose()?; + let plant = if let Some(h) = &feedback { + minreal(&forward.multiply(h)?)? + } else { + forward.clone() + }; + let mode = steady_mode(p); + let specs = specs_from_payload(p, None)?; + + let outcome = if synth_mode == "auto_simplest" { + synthesize_simplest(forward, feedback.as_ref(), &specs)? + } else { + let req_str = p["controller_type"].as_str().unwrap_or("PID"); + let structure = ControllerStructure::parse(req_str).ok_or_else(|| { + format!("Refinamento numérico não suporta o controlador '{req_str}'. Use P, PI, PD, Lead ou PID.") + })?; + let mut res = synthesize_for_structure(forward, feedback.as_ref(), structure, &specs)?; + if !res.feasible { + // Also search alternative structures so the user receives explicit recommendations. + for alt in ControllerStructure::complexity_order() { + if alt == structure { + continue; + } + if let Ok(alt_res) = + synthesize_for_structure(forward, feedback.as_ref(), alt, &specs) + && alt_res.feasible + && let Some(c) = alt_res.selected + { + res.alternatives.push(c); + break; + } + } + } + res + }; + + let Some(chosen) = outcome.selected else { + let reasons = if outcome.infeasibility_reasons.is_empty() { + "Nenhuma estrutura de controlador satisfez as especificações solicitadas.".to_owned() + } else { + outcome.infeasibility_reasons.join(" ") + }; + return Err(reasons); + }; + + let kind = chosen.structure.as_str().to_owned(); + let controller = chosen.transfer.clone(); + let loop_tf = controller.multiply(&plant)?; + let simulation_loop = if !loop_tf.is_proper() { + loop_tf.multiply(&TransferFunction::new(vec![1.], vec![0.001, 1.])?)? + } else { + loop_tf.clone() + }; + let (uncomp_cl, comp_cl) = if let Some(h) = &feedback { + let mut f = controller.multiply(forward)?; + if !f.is_proper() { + f = f.multiply(&TransferFunction::new(vec![1.], vec![0.001, 1.])?)?; + } + (forward.feedback(h, -1.)?, f.feedback(h, -1.)?) + } else { + ( + plant.feedback(&TransferFunction::scalar(1.), -1.)?, + simulation_loop.feedback(&TransferFunction::scalar(1.), -1.)?, + ) + }; + + let comp_poles = comp_cl.poles()?; + let stable = chosen.verification.closed_loop_stable; + let uncomp = uncompensated(&plant, &mode)?; + let err = math::steady_state_error(&loop_tf.num, &loop_tf.den, &mode); + let end = optional(p, "final_time")?; + let t = simulation::time_vector(&comp_cl, end, crate::time_response::points(p)?)?; + let input = match mode.as_str() { + "ramp" => Input::Ramp, + "parabola" => Input::Parabolic, + _ => Input::Step, + }; + let before = simulation::simulate(&uncomp_cl, &t, input)?; + let after = simulation::simulate(&comp_cl, &t, input)?; + let threshold = if specs.settling_criterion_pct == 5 { + 0.05 + } else { + 0.02 + }; + let mb = metrics(&uncomp_cl, &t, threshold)?; + let ma = metrics(&comp_cl, &t, threshold)?; + + let dom = chosen + .verification + .dominant_pole + .unwrap_or(C::new(-1.0, 0.0)); + let mut cp = json!({ + "kp": chosen.kp, + "ki": chosen.ki, + "kd": chosen.kd, + "K": chosen.k.unwrap_or(chosen.kp), + "z": chosen.z, + "zi": chosen.zi, + "p": chosen.p, + "td": if chosen.structure == ControllerStructure::PD && chosen.kp.abs() > 1e-12 { + json!(chosen.kd / chosen.kp) + } else { + Value::Null + }, + "re": dom.re.abs(), + "im": dom.im.abs(), + "criterion_pct": specs.settling_criterion_pct, + "e_atual": uncomp["steady_state_error_raw"], + "e_novo": err["value"], + }); + if let Some(mp) = chosen.verification.measured_overshoot_pct { + cp["mp"] = json!(mp); + } + if let Some(ts) = chosen.verification.measured_settling_time_s { + cp["ts"] = json!(ts); + } + + let design_label = if synth_mode == "auto_simplest" { + format!("Síntese Automática ({kind}) — Controlador Mais Simples por Restrições Temporais") + } else { + format!("Síntese com Refinamento Numérico ({kind}) — Restrições Temporais Reais") + }; + + let gc_latex = + tf_latex(&rounded_tf(&controller, 5, 1e-9), true, false).replace("G(s) = ", "G_c(s) = "); + let expanded = + tf_latex(&rounded_tf(&loop_tf, 5, 0.), true, false).replace("G(s) = ", "G_{ma}(s) = "); + let tc = tf_latex(&rounded_tf(&comp_cl, 5, 0.), true, false).replace("G(s) = ", "T(s) = "); + let plant_fact = tf_latex(forward, true, true); + let plant_exp = tf_latex(forward, true, false); + let feedback_tex = feedback + .as_ref() + .map(|h| tf_latex(h, true, true).replace("G(s) = ", "H(s) = ")) + .unwrap_or_default(); + + let mut c = Context::new(); + set(&mut c, "controller_params", cp.clone()); + set(&mut c, "angle_contributions", json!([])); + set(&mut c, "design_label", design_label.clone()); + let (image, svg) = plot_universal(&plant, &loop_tf, &t, &before, &after, &mode, &c)?; + + let mut rows = vec![ + json!({"header": "SÍNTESE POR RESTRIÇÕES TEMPORAIS"}), + json!({"label": "Controlador selecionado", "value": kind}), + json!({"label": "Conformidade global", "value": if chosen.verification.requirements_passed { "Conforme (requisitos atendidos)" } else { "Não conforme (especificações violadas)" }}), + json!({"label": "Método utilizado", "value": chosen.method_used}), + json!({"label": "Ganho proporcional (Kp)", "value": fmt(&json!(chosen.kp), 5, false)}), + ]; + if chosen.structure.has_integrator() { + rows.push( + json!({"label": "Ganho integral (Ki)", "value": fmt(&json!(chosen.ki), 5, false)}), + ); + } + if matches!( + chosen.structure, + ControllerStructure::PD | ControllerStructure::PID + ) { + rows.push( + json!({"label": "Ganho derivativo (Kd)", "value": fmt(&json!(chosen.kd), 5, false)}), + ); + } + if let Some(z) = chosen.z { + rows.push(json!({"label": "Zero do controlador (z)", "value": fmt(&json!(z), 5, false)})); + } + if let Some(zi) = chosen.zi { + rows.push(json!({"label": "Segundo zero (z₁)", "value": fmt(&json!(zi), 5, false)})); + } + if let Some(pole) = chosen.p + && chosen.structure == ControllerStructure::Lead + { + rows.push( + json!({"label": "Polo do controlador (p)", "value": fmt(&json!(pole), 5, false)}), + ); + } + rows.push(json!({"header": "MÉTRICAS REAIS MEDIDAS (RESPOSTA TEMPORAL)"})); + if let Some(mp) = chosen.verification.measured_overshoot_pct { + rows.push(json!({"label": "Sobressinal real (Mp)", "unit": "%", "value": fmt(&json!(mp), 4, false)})); + } + if let Some(ts) = chosen.verification.measured_settling_time_s { + rows.push(json!({"label": format!("Tempo de acomodação real (ts {}%)", specs.settling_criterion_pct), "unit": "s", "value": fmt(&json!(ts), 4, false)})); + } + if let Some(y_ss) = chosen.verification.measured_steady_state_y { + rows.push( + json!({"label": "Valor estacionário y(∞)", "value": fmt(&json!(y_ss), 5, false)}), + ); + } + if let Some(ea) = chosen.verification.summer_steady_state_error { + rows.push( + json!({"label": "Erro atuante no somador e_a(∞)", "value": fmt(&json!(ea), 5, false)}), + ); + } + rows.push( + json!({"label": "Estabilidade", "value": if stable { "Estável" } else { "Instável" }}), + ); + + let mut steps = vec![json!({ + "number": 1, + "title": "Seleção e Refinamento Numérico sobre a Resposta Temporal Real", + "description": format!( + "Avaliados {} candidatos por simulação temporal exata (exponencial matricial) verificando estabilidade interna, sobressinal real, tempo de acomodação definitivo ({}%) e erro estacionário.", + outcome.candidates_evaluated, specs.settling_criterion_pct + ), + "equations": [gc_latex.clone(), tc.clone()], + "notes": outcome.infeasibility_reasons.clone(), + })]; + if !outcome.alternatives.is_empty() { + let alt_notes: Vec = outcome + .alternatives + .iter() + .map(|a| { + format!( + "Estrutura alternativa viável: {} (Kp={}, Ki={}, Kd={}, Mp={}%, ts={} s)", + a.structure.as_str(), + fmt(&json!(a.kp), 4, false), + fmt(&json!(a.ki), 4, false), + fmt(&json!(a.kd), 4, false), + fmt( + &json!(a.verification.measured_overshoot_pct.unwrap_or(0.0)), + 3, + false + ), + fmt( + &json!(a.verification.measured_settling_time_s.unwrap_or(0.0)), + 3, + false + ), + ) + }) + .collect(); + steps.push(json!({ + "number": 2, + "title": "Estruturas Alternativas Viáveis", + "description": "A estrutura solicitada não satisfez todas as restrições; alternativas mais capazes foram identificadas automaticamente.", + "equations": [], + "notes": alt_notes, + })); + } + + let warning = if !chosen.verification.failed_requirements.is_empty() { + json!(format!( + "Requisitos não atendidos: {}.", + chosen.verification.failed_requirements.join("; ") + )) + } else if !chosen.verification.warnings.is_empty() { + json!(chosen.verification.warnings.join(" ")) + } else { + Value::Null + }; + + let alt_json: Vec = outcome + .alternatives + .iter() + .map(|a| { + json!({ + "controller_type": a.structure.as_str(), + "kp": a.kp, + "ki": a.ki, + "kd": a.kd, + "z": a.z, + "zi": a.zi, + "p": a.p, + "verification": a.verification.to_json(), + }) + }) + .collect(); + + let details = json!({ + "design_type": kind.to_lowercase(), + "controller_type": kind, + "synthesis_mode": synth_mode, + "design_label": design_label, + "input_type": mode, + "settling_criterion": specs.settling_criterion_pct, + "stable": stable, + "warning": warning, + "controller_parameters": cp, + "uncompensated": uncomp, + "angle_contributions": [], + "steps": steps, + "gc_latex": gc_latex, + "gma_factored_latex": expanded, + "gma_expanded_latex": expanded, + "tc_latex": tc, + "plant_latex_factored": plant_fact, + "plant_latex_expanded": plant_exp, + "forward_latex_factored": plant_fact, + "feedback_latex": feedback_tex, + "warnings": chosen.verification.warnings, + "before": mb, + "after": ma, + "closed_loop_poles_before": values::complex_list(&uncomp_cl.poles()?), + "closed_loop_poles_after": values::complex_list(&comp_poles), + "verification": chosen.verification.to_json(), + "synthesis": { + "feasible": outcome.feasible, + "feasibility_class": outcome.feasibility_class.as_str(), + "method_used": chosen.method_used, + "candidates_evaluated": outcome.candidates_evaluated, + "infeasibility_reasons": outcome.infeasibility_reasons, + "alternatives": alt_json, + }, + }); + + let mut latex = vec![ + json!({"label": "Controlador Gc(s)", "value": gc_latex}), + json!({"label": "Malha Fechada Compensada T(s)", "value": tc}), + json!({"label": "Malha Aberta Expandida", "value": expanded}), + json!({"label": "Planta Original G(s)", "value": plant_fact}), + ]; + if feedback.is_some() { + latex.push(json!({"label": "Realimentação H(s)", "value": feedback_tex})); + } + + Ok(json!({ + "success": true, + "module": "controller_design", + "title": "Projeto de Controladores", + "description": design_label, + "image": image, + "svg": svg, + "latex": latex, + "metrics": rows, + "details": details, + })) +} fn universal(p: &Value, forward: &TransferFunction) -> Result { let mut c = Context::new(); let default_kind = if p.get("controller_type").is_none() { @@ -1200,7 +1742,12 @@ fn universal(p: &Value, forward: &TransferFunction) -> Result { let is_equal = is_pid && matches!( pid_mode.as_str(), - "equal" | "iguais" | "zero_duplo" | "duplo" | "reais_iguais" | "zeros_iguais" + "equal" + | "iguais" + | "zero_duplo" + | "duplo" + | "reais_iguais" + | "zeros_iguais" ); let is_cancel = is_pid && matches!( @@ -1369,9 +1916,15 @@ fn universal(p: &Value, forward: &TransferFunction) -> Result { params(&mut c, 1632)?; controller = TransferFunction::new(vec![k, kp, ki], vec![1., 0.])?; } else if is_cancel { - let cancel_spec = optional(p, "pid_cancel_pole")? - .filter(|v| *v > 0.) - .or_else(|| optional(p, "pid_pi_zero").ok().flatten().filter(|v| *v > 0.)); + let cancel_spec = + optional(p, "pid_cancel_pole")? + .filter(|v| *v > 0.) + .or_else(|| { + optional(p, "pid_pi_zero") + .ok() + .flatten() + .filter(|v| *v > 0.) + }); let z1 = match cancel_spec { Some(val) => val, None => { @@ -1666,8 +2219,7 @@ fn universal(p: &Value, forward: &TransferFunction) -> Result { append(&mut c, "mag_eqs", 1479, false)?; append(&mut c, "steps", 1482, false)?; params(&mut c, 1494)?; - controller = - TransferFunction::new(vec![k, k * z.unwrap()], vec![1., 0.])?; + controller = TransferFunction::new(vec![k, k * z.unwrap()], vec![1., 0.])?; } } } @@ -1862,7 +2414,11 @@ fn plot_universal( Key::Marker(Marker::Ring), )); } - let is_equal_zeros = !p["zi"].is_null() + let dl = text(&get(c, "design_label")); + let is_new_pid_mode = + dl.contains("Zeros Reais e Iguais") || dl.contains("Cancelamento de Polo"); + let is_equal_zeros = is_new_pid_mode + && !p["zi"].is_null() && !p["z"].is_null() && (n(&p["zi"]) - n(&p["z"])).abs() < 1e-4; if is_equal_zeros { @@ -1876,7 +2432,7 @@ fn plot_universal( )); } } else { - if !p["zi"].is_null() && !p["z"].is_null() { + if is_new_pid_mode && !p["zi"].is_null() && !p["z"].is_null() { let zi = -n(&p["zi"]); left.marker(zi, 0., Marker::Disc, "black", 6.5); legend.push(( @@ -2169,9 +2725,33 @@ fn finish_universal( if !warning.is_null() { append(&mut c, "metric_rows", 1967, false)?; } - let details = json!({"design_type":kind.to_lowercase(),"controller_type":kind,"design_label":get(&c,"design_label"),"input_type":mode,"settling_criterion":cp["criterion_pct"],"stable":stable,"warning":warning,"controller_parameters":cp,"uncompensated":get(&c,"uncomp"),"angle_contributions":get(&c,"angle_contributions"),"steps":get(&c,"steps"),"gc_latex":gc,"gma_factored_latex":factored,"gma_expanded_latex":expanded,"tc_latex":tc,"plant_latex_factored":get(&c,"plant_latex_factored"),"plant_latex_expanded":get(&c,"plant_latex_expanded"),"forward_latex_factored":get(&c,"forward_latex_factored"),"feedback_latex":get(&c,"feedback_latex"),"warnings":warnings,"before":mb,"after":ma,"closed_loop_poles_before":values::complex_list(&uncomp_cl.poles()?),"closed_loop_poles_after":values::complex_list(&comp_poles)}); + let mut details = json!({"design_type":kind.to_lowercase(),"controller_type":kind,"design_label":get(&c,"design_label"),"input_type":mode,"settling_criterion":cp["criterion_pct"],"stable":stable,"warning":warning,"controller_parameters":cp,"uncompensated":get(&c,"uncomp"),"angle_contributions":get(&c,"angle_contributions"),"steps":get(&c,"steps"),"gc_latex":gc,"gma_factored_latex":factored,"gma_expanded_latex":expanded,"tc_latex":tc,"plant_latex_factored":get(&c,"plant_latex_factored"),"plant_latex_expanded":get(&c,"plant_latex_expanded"),"forward_latex_factored":get(&c,"forward_latex_factored"),"feedback_latex":get(&c,"feedback_latex"),"warnings":warnings,"before":mb,"after":ma,"closed_loop_poles_before":values::complex_list(&uncomp_cl.poles()?),"closed_loop_poles_after":values::complex_list(&comp_poles)}); + let want_verification = + p["verify_requirements"].as_bool() == Some(true) || p.get("synthesis_mode").is_some(); + if want_verification { + let specs = specs_from_payload(p, Some(&cp))?; + let report = + crate::controller_synthesis::verify_controller(forward, feedback, &controller, &specs)?; + let report_json = report.to_json(); + details["verification"] = report_json; + details["synthesis_mode"] = json!( + p["synthesis_mode"] + .as_str() + .filter(|s| !s.is_empty()) + .unwrap_or("lgr_classic") + ); + if !report.requirements_passed { + let failure_msg = format!( + "Projeto clássico por LGR não atende às especificações reais: {}.", + report.failed_requirements.join("; ") + ); + details["warning"] = json!(failure_msg); + } + } let gc_clean = gc.replace("+ -", "- ").replace("+ \\frac{-", "- \\frac{"); - let factored_clean = factored.replace("+ -", "- ").replace("+ \\frac{-", "- \\frac{"); + let factored_clean = factored + .replace("+ -", "- ") + .replace("+ \\frac{-", "- \\frac{"); let mut latex = vec![ json!({"label":"Controlador Gc(s)","value":gc_clean}), json!({"label":format!("Malha Aberta Compensada Gma(s) = {}",if feedback.is_some(){"Gc(s)G(s)H(s)"}else{"Gc(s)G(s)"}),"value":factored_clean}), diff --git a/crates/control-engine/src/lib.rs b/crates/control-engine/src/lib.rs index 3eadc41..9aada10 100644 --- a/crates/control-engine/src/lib.rs +++ b/crates/control-engine/src/lib.rs @@ -1,6 +1,7 @@ //! Scientific Rust engine. The UI remains on the Python engine until parity gates pass. pub mod controller_math; +pub mod controller_synthesis; pub mod controllers; pub mod dispatch; mod exact_transfer; diff --git a/crates/control-engine/tests/academic_controllers_validation.rs b/crates/control-engine/tests/academic_controllers_validation.rs new file mode 100644 index 0000000..049d211 --- /dev/null +++ b/crates/control-engine/tests/academic_controllers_validation.rs @@ -0,0 +1,987 @@ +//! Scientific and numerical validation suite for Controller Design (Projeto de Controladores) +//! based on UFERSA Control Systems II (PEX0257) academic list `Projeto_de_controladores.pdf`. +//! +//! Covers all 9 Questions (Q1 to Q9), including: +//! - Question 1: Reconstructed 2nd-order plant from graphical LGR/step response + PI controller. +//! - Question 2: Reconstructed undamped plant from graphical LGR/step response + PD controller +//! (plus PID zero-error alternative). +//! - Question 3: Multi-loop servo system reduction (inner velocity feedback 0.5 + outer unity loop) + PD controller. +//! - Question 4: Non-unity feedback system (H(s) = 0.05), desired poles -1 +/- sqrt(3)j, PI controller, +//! and explicit distinction between summer actuating error e_a(inf) = 0 and output y(inf) = 1/H(0) = 20. +//! - Question 5: 3rd-order plant 1/(s^3 + 10s^2 + 17s + 8) + PID controller in all three synthesis modes +//! (pole cancellation `cancel`, equal real zeros `equal`, and distinct zeros `distinct`), verifying all 4 +//! closed-loop poles and pole-zero cancellation. +//! - Question 6: 3rd-order Type 1 plant 1/(s(s+2)^2) + PD controller (kp + kd*s), verifying exact +//! pole-zero cancellation of one (s+2) factor and reduced 2nd-order closed-loop transfer function. +//! - Question 7: Two-loop cascade system (inner feedback 2 around 1/s + outer 5/(s(s+2))) + PD controller. +//! - Question 8: Wind turbine speed control with negative plant gain k = -7.2 and time constant tau = 5 +//! (G(s) = -7.2/(5s+1)) + PI controller, verifying both reference step response and step load +//! disturbance rejection T_p(s) = 1/s. +//! - Question 9: Second-order block diagram with wn = 1, xi = 0 reduced to double integrator 1/s^2 + PD controller. +//! +//! Reference sources: +//! - Closed-form analytical derivation (Root-Locus angle/magnitude conditions and Mason's gain formula). +//! - External numerical reference: MATLAB R2022b (Control System Toolbox 9.13 `feedback`, `minreal`, `stepinfo`). + +use controlab_engine::{ + controllers, polynomial as poly, + simulation::{self, Input}, + time_response, + transfer::TransferFunction, +}; +use num_complex::Complex64 as C; +use serde_json::{Value, json}; + +const TOL_COEFF: f64 = 1e-10; +const TOL_SIMPLE_ROOT: f64 = 1e-6; +const TOL_MULT_ROOT: f64 = 1e-4; +const TOL_GAIN: f64 = 1e-6; +const TOL_STEADY_STATE: f64 = 1e-5; +const TOL_WAVEFORM: f64 = 1e-4; +const TOL_OVERSHOOT_PP: f64 = 0.1; +const TOL_SETTLING_S: f64 = 0.02; + +fn c(re: f64, im: f64) -> C { + C::new(re, im) +} + +fn unordered_complex_distance(actual: &[C], expected: &[C]) -> f64 { + assert_eq!( + actual.len(), + expected.len(), + "Root count mismatch: actual={} vs expected={}", + actual.len(), + expected.len() + ); + let mut used = vec![false; expected.len()]; + let mut max_err = 0.0_f64; + for a in actual { + let mut best_idx = 0; + let mut best_dist = f64::INFINITY; + for (j, e) in expected.iter().enumerate() { + if !used[j] { + let d = (*a - *e).norm(); + if d < best_dist { + best_dist = d; + best_idx = j; + } + } + } + used[best_idx] = true; + max_err = max_err.max(best_dist); + } + max_err +} + +fn assert_tf_coeffs_eq( + actual: &TransferFunction, + expected_num: &[f64], + expected_den: &[f64], + ctx: &str, +) { + let norm = actual.normalized(); + assert_eq!(norm.num.len(), expected_num.len(), "{ctx}: num len"); + assert_eq!(norm.den.len(), expected_den.len(), "{ctx}: den len"); + for (a, e) in norm.num.iter().zip(expected_num) { + assert!( + (a - e).abs() <= TOL_COEFF * e.abs().max(1.0), + "{ctx}: num coeff {a} != {e}" + ); + } + for (a, e) in norm.den.iter().zip(expected_den) { + assert!( + (a - e).abs() <= TOL_COEFF * e.abs().max(1.0), + "{ctx}: den coeff {a} != {e}" + ); + } +} + +#[derive(Clone, Debug)] +struct ControllerAcademicCase { + id: &'static str, + question: u32, + payload: Value, + expected_controller_type: &'static str, + expected_kp: f64, + expected_ki: Option, + expected_kd: Option, + expected_z: f64, + expected_zi: Option, + expected_td: Option, + expected_cl_num: &'static [f64], + expected_cl_den: &'static [f64], + expected_cl_poles: &'static [(f64, f64)], + expected_cl_zeros: &'static [(f64, f64)], + /// Theoretical 2nd-order overshoot from dominant poles alone: exp(-xi*pi/sqrt(1-xi^2))*100. + theoretical_2nd_order_mp: f64, + /// Actual measured overshoot from step response (MATLAB R2022b `stepinfo` reference). + matlab_measured_mp: f64, + /// Actual measured 2% settling time (MATLAB R2022b `stepinfo` reference, definitive entry into +/-2% band). + matlab_settling_time_2pct: f64, + matlab_rise_time: f64, + matlab_peak_time: f64, + expected_steady_state_y: f64, + expected_summer_error_ess: f64, + pole_tolerance: f64, + justification: &'static str, +} + +fn all_controller_cases() -> Vec { + const SQRT3: f64 = 1.7320508075688772; + const SQRT84: f64 = 9.16515138991168; + + vec![ + // ========================================================================= + // Q1: Graphical reconstruction G(s) = 1/((s+0.2)(s+0.644)), xi=0.456, wn=0.706 -> PI + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q01_PI", + question: 1, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/((s + 0.2)*(s + 0.644))", + "controller_type": "PI", + "xi": 0.456, + "wn": 0.706, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PI", + expected_kp: 0.49849281561599984, + expected_ki: Some(0.09975099980799994), + expected_kd: None, + expected_z: 0.2001051904524144, + expected_zi: None, + expected_td: None, + expected_cl_num: &[0.49849281561599984, 0.09975099980799994], + expected_cl_den: &[1.0, 0.844, 0.6272928156159999, 0.09975099980799994], + expected_cl_poles: &[ + (-0.321936, 0.6283257211860734), + (-0.321936, -0.6283257211860734), + (-0.200128, 0.0), + ], + expected_cl_zeros: &[(-0.2001051904524144, 0.0)], + theoretical_2nd_order_mp: 19.995527167785674, + matlab_measured_mp: 20.003167761706877, + matlab_settling_time_2pct: 11.79426484164391, + matlab_rise_time: 2.2070596916196417, + matlab_peak_time: 5.006614870951746, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Reconstructed from graphical LGR poles at -0.2 and -0.644; desired pole sd = -0.321936 + 0.628326j lies to the right of uncompensated vertical LGR branch (-0.422), requiring negative phase from a PI controller whose zero z=0.200105 nearly cancels the slow pole at -0.2.", + }, + // ========================================================================= + // Q2: Graphical reconstruction G(s) = 1/(s^2+1), xi=0.5, ts(2%)=4s -> PD + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q02_PD", + question: 2, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/(s^2 + 1)", + "controller_type": "PD", + "xi": 0.5, + "ts": 4.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PD", + expected_kp: 3.0, + expected_ki: None, + expected_kd: Some(2.0), + expected_z: 1.5, + expected_zi: None, + expected_td: Some(2.0 / 3.0), + expected_cl_num: &[2.0, 3.0], + expected_cl_den: &[1.0, 2.0, 4.0], + expected_cl_poles: &[(-1.0, SQRT3), (-1.0, -SQRT3)], + expected_cl_zeros: &[(-1.5, 0.0)], + theoretical_2nd_order_mp: 16.303353482158046, + matlab_measured_mp: 41.251081523683084, + matlab_settling_time_2pct: 3.7232255355095183, + matlab_rise_time: 0.3646132825300812, + matlab_peak_time: 1.059189142777026, + expected_steady_state_y: 0.75, + expected_summer_error_ess: 0.25, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Reconstructed from undamped poles at +/-1j on jw axis; PD controller Gc(s)=3+2s places closed-loop poles at -1 +/- sqrt(3)j; closed-loop PD zero at s=-1.5 increases measured step overshoot to 41.25% compared to 16.30% pure 2nd-order estimate.", + }, + // ========================================================================= + // Q3: Servo system reduced to G(s) = 3/(20*s*(s+1)*(s+5)), sd = -1 +/- 1j -> PD + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q03_PD", + question: 3, + payload: json!({ + "action": "controller_design", + "plant_expr": "3/(20*s*(s + 1)*(s + 5))", + "controller_type": "PD", + "desired_pole": "-1 + 1j", + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PD", + expected_kp: 160.0 / 3.0, + expected_ki: None, + expected_kd: Some(100.0 / 3.0), + expected_z: 1.6, + expected_zi: None, + expected_td: Some(0.625), + expected_cl_num: &[5.0, 8.0], + expected_cl_den: &[1.0, 6.0, 10.0, 8.0], + expected_cl_poles: &[(-1.0, 1.0), (-1.0, -1.0), (-4.0, 0.0)], + expected_cl_zeros: &[(-1.6, 0.0)], + theoretical_2nd_order_mp: 4.321391826377226, + matlab_measured_mp: 8.093793475727473, + matlab_settling_time_2pct: 3.9134175958924926, + matlab_rise_time: 1.1088150985328944, + matlab_peak_time: 2.440740198573554, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Inner loop 18/((2s+11)(2s+1)) with H_in=0.5 reduces to 4.5/((s+1)(s+5)); cascaded with 1/(30s) gives Type-1 plant 0.15/(s(s+1)(s+5)) (e_ss=0 naturally); PD controller places dominant poles at -1 +/- 1j and 3rd pole at -4.", + }, + // ========================================================================= + // Q4: G(s) = 5/(s+0.1), H(s) = 0.05, sd = -1 +/- sqrt(3)j, e_a(inf) = 0 -> PI + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q04_PI", + question: 4, + payload: json!({ + "action": "controller_design", + "plant_expr": "5/(s + 0.1)", + "feedback_expr": "0.05", + "controller_type": "PI", + "desired_pole": "-1 + sqrt(3)j", + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PI", + expected_kp: 7.6, + expected_ki: Some(16.0), + expected_kd: None, + expected_z: 40.0 / 19.0, + expected_zi: None, + expected_td: None, + expected_cl_num: &[38.0, 80.0], + expected_cl_den: &[1.0, 2.0, 4.0], + expected_cl_poles: &[(-1.0, SQRT3), (-1.0, -SQRT3)], + expected_cl_zeros: &[(-40.0 / 19.0, 0.0)], + theoretical_2nd_order_mp: 16.303353482158046, + matlab_measured_mp: 28.38519483760318, + matlab_settling_time_2pct: 3.758556766404977, + matlab_rise_time: 0.48951297792656817, + matlab_peak_time: 1.2433959502165088, + expected_steady_state_y: 20.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Non-unity feedback H(s)=0.05 gives loop plant G(s)H(s)=0.25/(s+0.1); PI controller Kp=7.6, Ki=16 yields characteristic polynomial s^2+2s+4=0; actuating error at summer is e_a(inf)=0 while output steady state is y(inf)=1/H(0)=20.", + }, + // ========================================================================= + // Q5 (Mode 1: Pole Cancellation): G(s) = 1/(s^3+10s^2+17s+8), ts=1, xi=0.4 -> PID + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q05_PID_CANCEL", + question: 5, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/(s^3 + 10*s^2 + 17*s + 8)", + "controller_type": "PID", + "pid_zeros_mode": "cancel", + "xi": 0.4, + "ts": 1.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PID", + expected_kp: 200.0, + expected_ki: Some(100.0), + expected_kd: Some(100.0), + expected_z: 1.0, + expected_zi: Some(1.0), + expected_td: None, + expected_cl_num: &[100.0, 200.0, 100.0], + expected_cl_den: &[1.0, 10.0, 117.0, 208.0, 100.0], + expected_cl_poles: &[(-4.0, SQRT84), (-4.0, -SQRT84), (-1.0, 0.0), (-1.0, 0.0)], + expected_cl_zeros: &[(-1.0, 0.0), (-1.0, 0.0)], + theoretical_2nd_order_mp: 25.382672198010745, + matlab_measured_mp: 25.374074596318753, + matlab_settling_time_2pct: 0.8409399301706838, + matlab_rise_time: 0.14652080454767813, + matlab_peak_time: 0.34538776394908755, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_MULT_ROOT, + justification: "Plant factors as 1/((s+1)^2*(s+8)); canceling one pole at s=-1 requires the second PID zero via angle condition at sd=-4+sqrt(84)j, which also evaluates to z2=1, canceling the entire double pole (s+1)^2 and leaving exact 2nd-order dynamics 100/(s^2+8s+100).", + }, + // ========================================================================= + // Q5 (Mode 2: Equal Zeros): G(s) = 1/(s^3+10s^2+17s+8), ts=1, xi=0.4 -> PID + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q05_PID_EQUAL", + question: 5, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/(s^3 + 10*s^2 + 17*s + 8)", + "controller_type": "PID", + "pid_zeros_mode": "equal", + "xi": 0.4, + "ts": 1.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PID", + expected_kp: 200.0, + expected_ki: Some(100.0), + expected_kd: Some(100.0), + expected_z: 1.0, + expected_zi: Some(1.0), + expected_td: None, + expected_cl_num: &[100.0, 200.0, 100.0], + expected_cl_den: &[1.0, 10.0, 117.0, 208.0, 100.0], + expected_cl_poles: &[(-4.0, SQRT84), (-4.0, -SQRT84), (-1.0, 0.0), (-1.0, 0.0)], + expected_cl_zeros: &[(-1.0, 0.0), (-1.0, 0.0)], + theoretical_2nd_order_mp: 25.382672198010745, + matlab_measured_mp: 25.374074596318753, + matlab_settling_time_2pct: 0.8409399301706838, + matlab_rise_time: 0.14652080454767813, + matlab_peak_time: 0.34538776394908755, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_MULT_ROOT, + justification: "Because the pole at -8 and origin pole at 0 are symmetric relative to Re(sd)=-4, their angle sum at sd=-4+sqrt(84)j is 180 deg; hence the double zero angle equals the double pole angle at -1, yielding z0=1 and identical parameters Kp=200, Ki=100, Kd=100.", + }, + // ========================================================================= + // Q5 (Mode 3: Distinct Zeros with zi = 0.4): G(s) = 1/(s^3+10s^2+17s+8) -> PID + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q05_PID_DISTINCT", + question: 5, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/(s^3 + 10*s^2 + 17*s + 8)", + "controller_type": "PID", + "pid_zeros_mode": "distinct", + "pi_zero": 0.4, + "xi": 0.4, + "ts": 1.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PID", + expected_kp: 197.02970297029572, + expected_ki: Some(62.87128712871236), + expected_kd: Some(99.62871287128709), + expected_z: 1.5776397515527827, + expected_zi: Some(0.4), + expected_td: None, + expected_cl_num: &[99.62871287128709, 197.02970297029572, 62.87128712871236], + expected_cl_den: &[ + 1.0, + 10.0, + 116.62871287128709, + 205.02970297029572, + 62.87128712871236, + ], + expected_cl_poles: &[ + (-4.0, SQRT84), + (-4.0, -SQRT84), + (-1.60933334777678, 0.0), + (-0.3906666522232091, 0.0), + ], + expected_cl_zeros: &[(-1.5776397515527827, 0.0), (-0.4, 0.0)], + theoretical_2nd_order_mp: 25.382672198010745, + matlab_measured_mp: 24.473866097034815, + matlab_settling_time_2pct: 0.8737636210949157, + matlab_rise_time: 0.14738119773290045, + matlab_peak_time: 0.34538776394908755, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Cascade PI-PD synthesis fixing z_i = 0.1*Re(sd) = 0.4 places z_d = 254/161 = 1.577640; non-dominant closed-loop poles at -1.60933 and -0.39067 form near-dipoles with the zeros at -1.57764 and -0.4.", + }, + // ========================================================================= + // Q6: G(s) = 1/(s*(s+2)^2), PD controller kp + kd*s, xi = 0.5, wn = 2 -> Kp=8, Kd=4 + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q06_PD", + question: 6, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/(s*(s + 2)^2)", + "controller_type": "PD", + "xi": 0.5, + "wn": 2.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PD", + expected_kp: 8.0, + expected_ki: None, + expected_kd: Some(4.0), + expected_z: 2.0, + expected_zi: None, + expected_td: Some(0.5), + expected_cl_num: &[4.0, 8.0], + expected_cl_den: &[1.0, 4.0, 8.0, 8.0], + expected_cl_poles: &[(-1.0, SQRT3), (-1.0, -SQRT3), (-2.0, 0.0)], + expected_cl_zeros: &[(-2.0, 0.0)], + theoretical_2nd_order_mp: 16.303353482158046, + matlab_measured_mp: 16.292919869949184, + matlab_settling_time_2pct: 4.037934116881343, + matlab_rise_time: 0.8195145513072228, + matlab_peak_time: 1.7960163725349574, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "At sd = -1 + sqrt(3)j, angle from s=0 is 120 deg and from (s+2)^2 is 2*60=120 deg, requiring 60 deg from PD zero => z = 2.0, which exactly cancels one (s+2) plant pole and reduces T(s) = (4s+8)/(s^3+4s^2+8s+8) to T_min(s) = 4/(s^2+2s+4).", + }, + // ========================================================================= + // Q7: Inner loop 1/s with feedback 2 -> 1/(s+2), times 5/(s(s+2)) -> 5/(s(s+2)^2) -> PD + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q07_PD", + question: 7, + payload: json!({ + "action": "controller_design", + "plant_expr": "5/(s*(s + 2)^2)", + "controller_type": "PD", + "xi": 0.5, + "ts": 4.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PD", + expected_kp: 1.6, + expected_ki: None, + expected_kd: Some(0.8), + expected_z: 2.0, + expected_zi: None, + expected_td: Some(0.5), + expected_cl_num: &[4.0, 8.0], + expected_cl_den: &[1.0, 4.0, 8.0, 8.0], + expected_cl_poles: &[(-1.0, SQRT3), (-1.0, -SQRT3), (-2.0, 0.0)], + expected_cl_zeros: &[(-2.0, 0.0)], + theoretical_2nd_order_mp: 16.303353482158046, + matlab_measured_mp: 16.292919869949184, + matlab_settling_time_2pct: 4.037934116881343, + matlab_rise_time: 0.8195145513072228, + matlab_peak_time: 1.7960163725349574, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Inner loop (1/s)/(1+2/s) = 1/(s+2) in series with 5/(s(s+2)) gives 5/(s(s+2)^2); PD zero z=2 cancels one (s+2) pole with gains Kp=1.6, Kd=0.8 (1/5 of Q6 gains), producing the same closed-loop transfer function 4/(s^2+2s+4).", + }, + // ========================================================================= + // Q8: Wind turbine G(s) = -7.2/(5s+1), ts=4s, Mp=25%, e(inf)=0 -> PI (negative gains) + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q08_PI", + question: 8, + payload: json!({ + "action": "controller_design", + "plant_expr": "-7.2/(5*s + 1)", + "controller_type": "PI", + "ts": 4.0, + "mp": 25.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PI", + expected_kp: -1.25, + expected_ki: Some(-4.260813967920802), + expected_kd: None, + expected_z: 3.4086511743366414, + expected_zi: None, + expected_td: None, + expected_cl_num: &[1.8, 6.135572113805955], + expected_cl_den: &[1.0, 2.0, 6.135572113805955], + expected_cl_poles: &[(-1.0, 2.266180070913597), (-1.0, -2.266180070913597)], + expected_cl_zeros: &[(-3.4086511743366414, 0.0)], + theoretical_2nd_order_mp: 25.0, + matlab_measured_mp: 33.840604831375764, + matlab_settling_time_2pct: 3.965373030165275, + matlab_rise_time: 0.4229095765576573, + matlab_peak_time: 1.059189142777026, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Negative plant gain k=-7.2 (tau=5 => G(s)=-1.44/(s+0.2)) requires negative PI gains Kp=-1.25, Ki=-4.260814; closed-loop poles are -1 +/- 2.26618j (2nd-order Mp=25%), while closed-loop PI zero at -3.40865 increases actual step overshoot to 33.84%.", + }, + // ========================================================================= + // Q9: Second-order block diagram with wn=1, xi=0 -> G(s) = 1/s^2, ts=4s, xi=0.5 -> PD + // ========================================================================= + ControllerAcademicCase { + id: "CTRL_Q09_PD", + question: 9, + payload: json!({ + "action": "controller_design", + "plant_expr": "1/(s^2)", + "controller_type": "PD", + "xi": 0.5, + "ts": 4.0, + "settling_criterion": "2", + "points": 2000, + "dpi": 72 + }), + expected_controller_type: "PD", + expected_kp: 4.0, + expected_ki: None, + expected_kd: Some(2.0), + expected_z: 2.0, + expected_zi: None, + expected_td: Some(0.5), + expected_cl_num: &[2.0, 4.0], + expected_cl_den: &[1.0, 2.0, 4.0], + expected_cl_poles: &[(-1.0, SQRT3), (-1.0, -SQRT3)], + expected_cl_zeros: &[(-2.0, 0.0)], + theoretical_2nd_order_mp: 16.303353482158046, + matlab_measured_mp: 29.835150652637886, + matlab_settling_time_2pct: 3.752715553619379, + matlab_rise_time: 0.4704600578119872, + matlab_peak_time: 1.197_344_248_356_638, + expected_steady_state_y: 1.0, + expected_summer_error_ess: 0.0, + pole_tolerance: TOL_SIMPLE_ROOT, + justification: "Inner loop (1/s)/(1+2*xi*wn/s) with xi=0, wn=1 reduces to 1/s, cascaded with wn^2/s gives double integrator G(s)=1/s^2; PD controller Gc(s)=4+2s places poles at -1 +/- sqrt(3)j; closed-loop zero at s=-2 raises step overshoot from 16.30% to 29.84%.", + }, + ] +} + +#[test] +fn validate_all_9_controller_design_questions_against_analytical_and_matlab() { + let cases = all_controller_cases(); + assert_eq!(cases.len(), 11, "11 configurations covering Q1 through Q9"); + + for case in &cases { + assert!((1..=9).contains(&case.question)); + let res = controllers::analyze(&case.payload).unwrap(); + assert_eq!( + res["success"], true, + "{} ({}): controller design failed", + case.id, case.justification + ); + assert!(res["svg"].as_str().unwrap().contains(" TransferFunction::new(vec![act_kp, cp["ki"].as_f64().unwrap()], vec![1.0, 0.0]) + .unwrap(), + "PD" => { + TransferFunction::new(vec![cp["kd"].as_f64().unwrap(), act_kp], vec![1.0]).unwrap() + } + "PID" => TransferFunction::new( + vec![ + cp["kd"].as_f64().unwrap(), + act_kp, + cp["ki"].as_f64().unwrap(), + ], + vec![1.0, 0.0], + ) + .unwrap(), + other => panic!("Unsupported controller type {other}"), + }; + let forward = gc.multiply(&plant).unwrap(); + let cl_tf = forward.feedback(&feedback, -1.0).unwrap().normalized(); + assert_tf_coeffs_eq(&cl_tf, case.expected_cl_num, case.expected_cl_den, case.id); + + let actual_poles: Vec = det["closed_loop_poles_after"] + .as_array() + .unwrap() + .iter() + .map(|p| c(p["re"].as_f64().unwrap(), p["im"].as_f64().unwrap())) + .collect(); + let expected_poles: Vec = case + .expected_cl_poles + .iter() + .map(|&(re, im)| c(re, im)) + .collect(); + let pole_err = unordered_complex_distance(&actual_poles, &expected_poles); + assert!( + pole_err <= case.pole_tolerance, + "{}: closed-loop pole error {pole_err:e} > {:e}", + case.id, + case.pole_tolerance + ); + + let cl_zeros = cl_tf.zeros().unwrap(); + let expected_zeros: Vec = case + .expected_cl_zeros + .iter() + .map(|&(re, im)| c(re, im)) + .collect(); + let zero_err = unordered_complex_distance(&cl_zeros, &expected_zeros); + assert!( + zero_err <= case.pole_tolerance, + "{}: closed-loop zero error {zero_err:e} > {:e}", + case.id, + case.pole_tolerance + ); + + // 3. Validate theoretical 2nd-order estimate vs actual measured step response metrics. + let theoretical_mp = cp["mp"].as_f64().unwrap(); + assert!( + (theoretical_mp - case.theoretical_2nd_order_mp).abs() <= 1e-3, + "{}: theoretical 2nd-order Mp {theoretical_mp} != {}", + case.id, + case.theoretical_2nd_order_mp + ); + + let after_metrics = &det["after"]; + let act_mp = after_metrics["overshoot_percent"].as_f64().unwrap(); + assert!( + (act_mp - case.matlab_measured_mp).abs() <= TOL_OVERSHOOT_PP, + "{}: measured overshoot {act_mp}% vs MATLAB {}% exceeds {TOL_OVERSHOOT_PP} pp", + case.id, + case.matlab_measured_mp + ); + + let act_ts = after_metrics["settling_time"].as_f64().unwrap(); + assert!( + (act_ts - case.matlab_settling_time_2pct).abs() <= TOL_SETTLING_S, + "{}: settling time (2%) {act_ts}s vs MATLAB {}s exceeds {TOL_SETTLING_S}s", + case.id, + case.matlab_settling_time_2pct + ); + + let act_tr = after_metrics["rise_time"].as_f64().unwrap(); + assert!( + (act_tr - case.matlab_rise_time).abs() <= 0.025, + "{}: rise time {act_tr}s vs MATLAB {}s", + case.id, + case.matlab_rise_time + ); + + let act_tp = after_metrics["peak_time"].as_f64().unwrap(); + assert!( + (act_tp - case.matlab_peak_time).abs() <= 0.035, + "{}: peak time {act_tp}s vs MATLAB {}s", + case.id, + case.matlab_peak_time + ); + + // 4. Validate steady-state output value y(inf) and summer actuating error e_a(inf). + let act_final_y = after_metrics["steady_state_value"].as_f64().unwrap(); + let dc_gain = cl_tf.dc_gain(); + assert!( + (dc_gain - case.expected_steady_state_y).abs() <= TOL_STEADY_STATE, + "{}: exact dc_gain {dc_gain} != {}", + case.id, + case.expected_steady_state_y + ); + assert!( + (act_final_y - case.expected_steady_state_y).abs() <= TOL_STEADY_STATE, + "{}: steady_state_value {act_final_y} != {}", + case.id, + case.expected_steady_state_y + ); + let act_ess = cp["e_novo"].as_f64().unwrap(); + assert!( + (act_ess - case.expected_summer_error_ess).abs() <= TOL_STEADY_STATE, + "{}: steady-state error {act_ess} != {}", + case.id, + case.expected_summer_error_ess + ); + } +} + +#[test] +fn validate_block_diagram_reductions_pole_zero_cancellations_and_q8_disturbance() { + // 1. Q3 Block Diagram Reduction: + // Inner loop: 18/((2s+11)(2s+1)) with feedback 0.5 -> 4.5/((s+1)(s+5)) + // Cascaded with 1/(30s) -> 3/(20s(s+1)(s+5)) = 0.15/(s^3 + 6s^2 + 5s) + let q3_fwd_inner = TransferFunction::parse("18/((2*s + 11)*(2*s + 1))").unwrap(); + let q3_h_inner = TransferFunction::scalar(0.5); + let q3_inner_cl = q3_fwd_inner + .feedback(&q3_h_inner, -1.0) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q3_inner_cl, &[4.5], &[1.0, 6.0, 5.0], "Q3 inner loop"); + let q3_outer_plant = q3_inner_cl + .multiply(&TransferFunction::parse("1/(30*s)").unwrap()) + .unwrap() + .normalized(); + assert_tf_coeffs_eq( + &q3_outer_plant, + &[0.15], + &[1.0, 6.0, 5.0, 0.0], + "Q3 reduced plant", + ); + + // 2. Q4 Non-Unity Feedback Distinction (Summer Error vs Output Tracking): + // G(s) = 5/(s+0.1), H(s) = 0.05, Gc(s) = (7.6s + 16)/s + // T_YR(s) = Gc*G / (1 + Gc*G*H) = (38s + 80)/(s^2 + 2s + 4) -> y(inf) = 20 + // T_EaR(s) = 1 / (1 + Gc*G*H) = s(s + 0.1)/(s^2 + 2s + 4) -> e_a(inf) = 0 + // T_EY_R(s) = 1 - T_YR(s) -> output tracking difference r(inf) - y(inf) = 1 - 20 = -19 + let q4_g = TransferFunction::parse("5/(s + 0.1)").unwrap(); + let q4_h = TransferFunction::scalar(0.05); + let q4_gc = TransferFunction::new(vec![7.6, 16.0], vec![1.0, 0.0]).unwrap(); + let q4_tyr = q4_gc + .multiply(&q4_g) + .unwrap() + .feedback(&q4_h, -1.0) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q4_tyr, &[38.0, 80.0], &[1.0, 2.0, 4.0], "Q4 T_YR(s)"); + assert!((q4_tyr.dc_gain() - 20.0).abs() <= TOL_STEADY_STATE); + let q4_tear = TransferFunction::scalar(1.0) + .feedback( + &q4_gc.multiply(&q4_g).unwrap().multiply(&q4_h).unwrap(), + -1.0, + ) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q4_tear, &[1.0, 0.1, 0.0], &[1.0, 2.0, 4.0], "Q4 T_EaR(s)"); + assert!(q4_tear.dc_gain().abs() <= TOL_STEADY_STATE); + + // 3. Q6 and Q7 Exact Pole-Zero Cancellation and Analytical Step Waveform Verification: + // Unreduced T(s) = (4s + 8)/(s^3 + 4s^2 + 8s + 8) = 4(s+2)/((s+2)(s^2 + 2s + 4)) + // Reduced T_min(s) = 4/(s^2 + 2s + 4) + // Exact unit step response: y(t) = 1 - e^(-t)*(cos(sqrt(3)*t) + (1/sqrt(3))*sin(sqrt(3)*t)) + let q6_unreduced = TransferFunction::new(vec![4.0, 8.0], vec![1.0, 4.0, 8.0, 8.0]).unwrap(); + let q6_reduced = TransferFunction::new(vec![4.0], vec![1.0, 2.0, 4.0]).unwrap(); + let t_grid: Vec = (0..=1000).map(|i| (i as f64) * 0.01).collect(); + let y_unreduced = simulation::simulate(&q6_unreduced, &t_grid, Input::Step).unwrap(); + let y_reduced = simulation::simulate(&q6_reduced, &t_grid, Input::Step).unwrap(); + let sqrt3 = 3.0_f64.sqrt(); + for (idx, &t) in t_grid.iter().enumerate() { + let y_exact = 1.0 - (-t).exp() * ((sqrt3 * t).cos() + (sqrt3 * t).sin() / sqrt3); + assert!( + (y_unreduced[idx] - y_reduced[idx]).abs() <= 1e-12, + "Q6/Q7 pole-zero cancellation mismatch at t={t}: {} vs {}", + y_unreduced[idx], + y_reduced[idx] + ); + assert!( + (y_reduced[idx] - y_exact).abs() <= TOL_WAVEFORM, + "Q6/Q7 step waveform mismatch at t={t}: {} vs {y_exact}", + y_reduced[idx] + ); + } + + // 4. Q7 Block Diagram Reduction: + // Inner loop: (1/s) with feedback 2 -> 1/(s+2) + // Series with 5/(s(s+2)) -> 5/(s(s+2)^2) = 5/(s^3 + 4s^2 + 4s) + let q7_inner = TransferFunction::parse("1/s") + .unwrap() + .feedback(&TransferFunction::scalar(2.0), -1.0) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q7_inner, &[1.0], &[1.0, 2.0], "Q7 inner loop"); + let q7_plant = q7_inner + .multiply(&TransferFunction::parse("5/(s*(s + 2))").unwrap()) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q7_plant, &[5.0], &[1.0, 4.0, 4.0, 0.0], "Q7 reduced plant"); + + // 5. Q8 Step Disturbance Response Validation: + // G_p(s) = -7.2/(5s + 1) = -1.44/(s + 0.2) + // G_c(s) = (-1.25s - 4.260813967920802)/s + // Disturbance transfer function from T_p(s) to w(s): + // T_d(s) = G_p(s) / (1 + G_c(s)G_p(s)) = -1.44*s / (s^2 + 2s + 6.135572113805955) + let q8_gp = TransferFunction::parse("-7.2/(5*s + 1)") + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q8_gp, &[-1.44], &[1.0, 0.2], "Q8 plant"); + let q8_gc = TransferFunction::new(vec![-1.25, -4.260813967920802], vec![1.0, 0.0]).unwrap(); + let q8_td = q8_gp.feedback(&q8_gc, -1.0).unwrap().normalized(); + assert_tf_coeffs_eq( + &q8_td, + &[-1.44, 0.0], + &[1.0, 2.0, 6.135572113805955], + "Q8 disturbance transfer function T_d(s)", + ); + // Steady-state disturbance response to unit step T_p(s) = 1/s is T_d(0) = 0: + assert!( + q8_td.dc_gain().abs() <= TOL_STEADY_STATE, + "Q8 must completely reject constant step load disturbance in steady state" + ); + // Verify analytical disturbance step response waveform: + // w_d(t) = L^-1{ -1.44 / ((s+1)^2 + wd^2) } = (-1.44 / wd) * e^(-t) * sin(wd * t) + let wd = 2.266180070913597_f64; + let t_dist: Vec = (0..=1500).map(|i| (i as f64) * 0.01).collect(); + let y_dist = simulation::simulate(&q8_td, &t_dist, Input::Step).unwrap(); + for (idx, &t) in t_dist.iter().enumerate() { + let exact_wd = (-1.44 / wd) * (-t).exp() * (wd * t).sin(); + assert!( + (y_dist[idx] - exact_wd).abs() <= TOL_WAVEFORM, + "Q8 disturbance step waveform error at t={t}: {} != {exact_wd}", + y_dist[idx] + ); + } + assert!( + y_dist.last().unwrap().abs() <= TOL_STEADY_STATE, + "Q8 disturbance response at t=15s must settle to 0 within TOL_STEADY_STATE" + ); + + // 6. Q9 Block Diagram Reduction (wn = 1, xi = 0): + // Inner loop: (1/s) with feedback 2*xi*wn = 0 -> 1/s + // Outer plant: wn^2 * (1/s) * (1/s) = 1/s^2 + let q9_inner = TransferFunction::parse("1/s") + .unwrap() + .feedback(&TransferFunction::scalar(0.0), -1.0) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q9_inner, &[1.0], &[1.0, 0.0], "Q9 inner loop"); + let q9_plant = q9_inner + .multiply(&TransferFunction::parse("1/s").unwrap()) + .unwrap() + .normalized(); + assert_tf_coeffs_eq(&q9_plant, &[1.0], &[1.0, 0.0, 0.0], "Q9 double integrator"); + + // 7. Q2 Alternative PID Controller (if zero steady-state error e(inf) = 0 is also imposed): + let q2_pid = controllers::analyze(&json!({ + "action": "controller_design", + "plant_expr": "1/(s^2 + 1)", + "controller_type": "PID", + "pid_zeros_mode": "equal", + "xi": 0.5, + "ts": 4.0, + "settling_criterion": "2", + "dpi": 72 + })) + .unwrap(); + assert_eq!(q2_pid["success"], true); + let q2_cp = &q2_pid["details"]["controller_parameters"]; + assert!((q2_cp["kp"].as_f64().unwrap() - 3.737033899038282).abs() <= TOL_GAIN); + assert!((q2_cp["ki"].as_f64().unwrap() - 1.474067798076564).abs() <= TOL_GAIN); + assert!((q2_cp["kd"].as_f64().unwrap() - 2.368516949519141).abs() <= TOL_GAIN); + assert!((q2_cp["z"].as_f64().unwrap() - 0.7888974490720842).abs() <= TOL_GAIN); + assert!(q2_cp["e_novo"].as_f64().unwrap().abs() <= TOL_STEADY_STATE); +} + +#[test] +fn validate_numerical_robustness_repeatability_and_definitive_settling_time() { + // 1. Repeatability across multiple executions (Etapa 04): + let payload = json!({ + "action": "controller_design", + "plant_expr": "-7.2/(5*s + 1)", + "controller_type": "PI", + "ts": 4.0, + "mp": 25.0, + "settling_criterion": "2", + "dpi": 72 + }); + let first = controllers::analyze(&payload).unwrap(); + for _ in 0..5 { + let next = controllers::analyze(&payload).unwrap(); + assert_eq!( + first["details"]["controller_parameters"], + next["details"]["controller_parameters"] + ); + assert_eq!(first["details"]["after"], next["details"]["after"]); + assert_eq!( + first["details"]["closed_loop_poles_after"], + next["details"]["closed_loop_poles_after"] + ); + } + + // 2. Definitive 2% settling-time entry criterion (Etapa 04): + // For underdamped 2nd-order system T(s) = 4/(s^2 + 2s + 4), y(t) oscillates through + // the [0.98, 1.02] band multiple times before entering it definitively at t ~ 4.038s. + // First crossing of 0.98 occurs during the initial rise at t ~ 1.09s; settling time + // must NEVER report the first crossing. + let tr_res = time_response::analyze(&json!({ + "expr": "4/(s^2 + 2*s + 4)", + "settling_threshold": 0.02, + "points": 4000, + "dpi": 72 + })) + .unwrap(); + let ts_2pct = tr_res["details"]["step"]["settling_time"].as_f64().unwrap(); + assert!( + (ts_2pct - 4.037934).abs() <= TOL_SETTLING_S, + "Settling time {ts_2pct}s must be definitive entry (~4.038s), not first crossing (~1.09s)" + ); + + // 3. Sensitivity to small perturbations on well-conditioned polynomial roots: + let base_roots = poly::roots(&[1.0, 6.0, 10.0, 8.0]).unwrap(); + let pert_roots = poly::roots(&[1.0, 6.0, 10.0, 8.0 + 1e-9]).unwrap(); + let sens = unordered_complex_distance(&base_roots, &pert_roots); + assert!( + sens <= 1e-8, + "Excessive root sensitivity to 1e-9 perturbation: {sens:e}" + ); +} diff --git a/crates/control-engine/tests/academic_lgr_validation.rs b/crates/control-engine/tests/academic_lgr_validation.rs new file mode 100644 index 0000000..d0b648c --- /dev/null +++ b/crates/control-engine/tests/academic_lgr_validation.rs @@ -0,0 +1,1226 @@ +//! Scientific and numerical validation suite for Root Locus (Lugar Geometrico das Raizes - LGR) +//! based on UFERSA Control Systems II (PEX0257) academic list `Exercicios_-_LGR.pdf`. +//! +//! Covers all 18 numbered transfer functions (Equations 1 to 18) across Questions 1 to 4 +//! and the parametric characteristic equation of Question 5 (Equation 19, with a2 = 0). +//! Preserves duplicate item labels (`2(i)-1` Eq. 12 and `2(i)-2` Eq. 13) and all +//! mathematically equivalent exercises (`1(a)=2(d)`, `1(b)=2(c)`, `1(c)=2(i)-1=3(a)`). +//! +//! Reference sources: +//! - Closed-form analytical derivation (Evans root-locus rules and Routh-Hurwitz criterion). +//! - External numerical reference: MATLAB R2022b (Control System Toolbox 9.13). + +use controlab_engine::{lgr, polynomial as poly, routh, transfer::TransferFunction}; +use num_complex::Complex64 as C; +use serde_json::{Value, json}; + +const TOL_COEFF: f64 = 1e-10; +const TOL_SIMPLE_ROOT: f64 = 1e-6; +const TOL_MULT_ROOT: f64 = 1e-4; +const TOL_CENTROID: f64 = 1e-6; +const TOL_ANGLE_DEG: f64 = 1e-3; +const TOL_BREAKAWAY_S: f64 = 1e-5; +const TOL_BREAKAWAY_K: f64 = 1e-4; +const TOL_JW_W: f64 = 1e-3; +const TOL_JW_K: f64 = 1e-2; + +#[derive(Clone, Debug)] +struct LgrAcademicCase { + id: &'static str, + question_item: &'static str, + equation_number: u32, + g_expr: &'static str, + h_expr: &'static str, + ol_expr: &'static str, + expected_num: &'static [f64], + expected_den: &'static [f64], + expected_poles: &'static [(f64, f64)], + expected_zeros: &'static [(f64, f64)], + expected_branches: usize, + /// Midpoint test points (s_real, belongs_to_lgr) verifying real-axis LGR segments. + real_axis_probes: &'static [(f64, bool)], + expected_centroid: Option, + expected_asymptote_angles_deg: &'static [f64], + /// Smooth interior breakaway/break-in points (s_real, K_gain) where dK/ds = 0 and K > 0. + expected_breakaway_points: &'static [(f64, f64)], + /// Multiple open-loop poles on the real axis that act as K = 0 breakaway points. + expected_k0_multiple_pole_breakaways: &'static [f64], + /// Departure angles from upper-half-plane complex poles: (pole_re, pole_im, angle_deg). + expected_departure_angles: &'static [(f64, f64, f64)], + /// Arrival angles at upper-half-plane complex zeros: (zero_re, zero_im, angle_deg). + expected_arrival_angles: &'static [(f64, f64, f64)], + /// Upper-half-plane jw crossings: (omega_pos, k_crit). + expected_jw_crossings: &'static [(f64, f64)], + /// Expected positive-gain stability interval label in Routh-Hurwitz analysis. + expected_positive_k_stability: &'static str, + /// Sample gains (k_sample, expected_ strictly_stable) for closed-loop stability verification. + stability_probes: &'static [(f64, bool)], + root_tolerance: f64, + justification: &'static str, +} + +fn c(re: f64, im: f64) -> C { + C::new(re, im) +} + +/// Unordered Hausdorff / greedy optimal matching distance between two complex root sets. +fn unordered_complex_distance(actual: &[C], expected: &[C]) -> f64 { + assert_eq!( + actual.len(), + expected.len(), + "Root count mismatch: actual={} vs expected={}", + actual.len(), + expected.len() + ); + let mut used = vec![false; expected.len()]; + let mut max_err = 0.0_f64; + for a in actual { + let mut best_idx = 0; + let mut best_dist = f64::INFINITY; + for (j, e) in expected.iter().enumerate() { + if !used[j] { + let d = (*a - *e).norm(); + if d < best_dist { + best_dist = d; + best_idx = j; + } + } + } + used[best_idx] = true; + max_err = max_err.max(best_dist); + } + max_err +} + +/// Normalized polynomial residual for P(s) = D(s) + K * N(s) = 0: +/// |P(s)| / (||P||_1 * max(1, |s|)^deg) +fn normalized_char_poly_residual(den: &[f64], num: &[f64], k: f64, root: C) -> f64 { + let char_poly = poly::add(den, num, k); + let val = poly::evaluate(&char_poly, root).norm(); + let l1_norm: f64 = char_poly.iter().map(|c| c.abs()).sum(); + let deg = (char_poly.len().saturating_sub(1)) as i32; + let scale = l1_norm * root.norm().max(1.0).powi(deg); + val / scale.max(1e-15) +} + +/// Verify complex conjugate symmetry of a root set. +fn assert_conjugate_symmetry(roots: &[C], tol: f64, context: &str) { + let conjugates: Vec = roots.iter().map(|r| r.conj()).collect(); + let dist = unordered_complex_distance(roots, &conjugates); + assert!( + dist <= tol, + "{context}: conjugate symmetry violated, max distance = {dist:e} > {tol:e}" + ); +} + +fn wrap_angle_180(deg: f64) -> f64 { + (deg + 180.0).rem_euclid(360.0) - 180.0 +} + +fn all_lgr_academic_cases() -> Vec { + let sqrt2 = 2.0_f64.sqrt(); + let sqrt3 = 3.0_f64.sqrt(); + let sqrt5 = 5.0_f64.sqrt(); + let sqrt7 = 7.0_f64.sqrt(); + let _ = (sqrt2, sqrt3, sqrt5, sqrt7); + const SQRT2: f64 = std::f64::consts::SQRT_2; + const SQRT3: f64 = 1.7320508075688772; + const SQRT5: f64 = 2.23606797749979; + const SQRT7: f64 = 2.6457513110645907; + const SQRT2_6: f64 = 1.6124515496597098; + const SQRT16_5: f64 = 4.06201920231798; + const SQRT2665: f64 = 51.62363799656123; + + vec![ + // ========================================================================= + // Q1(a) - Eq. (1): G(s)H(s) = k / (s(s^2 + 6s + 25)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q1A_EQ01", + question_item: "1(a)", + equation_number: 1, + g_expr: "1/(s*(s^2 + 6*s + 25))", + h_expr: "1", + ol_expr: "1/(s*(s^2 + 6*s + 25))", + expected_num: &[1.0], + expected_den: &[1.0, 6.0, 25.0, 0.0], + expected_poles: &[(0.0, 0.0), (-3.0, 4.0), (-3.0, -4.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(1.0, false), (-1.0, true), (-5.0, true)], + expected_centroid: Some(-2.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-3.0, 4.0, -36.86989764584402)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(5.0, 150.0)], + expected_positive_k_stability: "0 < K < 150", + stability_probes: &[(1.0, true), (75.0, true), (149.0, true), (151.0, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "3rd-order all-pole system with origin pole and complex conjugate pair at -3 +/- 4j; dK/ds = -(3s^2+12s+25) has complex roots -2 +/- sqrt(13/3)j so no real breakaway; Routh gives K_crit = 6*25 = 150 at w = 5 rad/s.", + }, + // ========================================================================= + // Q1(b) - Eq. (2): G(s)H(s) = k(s + 2) / (s^2 + 2s + 3) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q1B_EQ02", + question_item: "1(b)", + equation_number: 2, + g_expr: "(s + 2)/(s^2 + 2*s + 3)", + h_expr: "1", + ol_expr: "(s + 2)/(s^2 + 2*s + 3)", + expected_num: &[1.0, 2.0], + expected_den: &[1.0, 2.0, 3.0], + expected_poles: &[(-1.0, SQRT2), (-1.0, -SQRT2)], + expected_zeros: &[(-2.0, 0.0)], + expected_branches: 2, + real_axis_probes: &[(0.0, false), (-1.0, false), (-3.0, true)], + expected_centroid: Some(0.0), + expected_asymptote_angles_deg: &[180.0], + expected_breakaway_points: &[(-2.0 - SQRT3, 2.0 + 2.0 * SQRT3)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-1.0, SQRT2, 144.73561031724535)], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(0.5, true), (5.0, true), (100.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Circular root locus centered at s = -2 with radius sqrt(3); break-in at s = -2 - sqrt(3) with K = 2 + 2*sqrt(3); unconditionally stable for all K > 0.", + }, + // ========================================================================= + // Q1(c) - Eq. (3): G(s)H(s) = k / (s(s^2 + 4s + 5)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q1C_EQ03", + question_item: "1(c)", + equation_number: 3, + g_expr: "1/(s*(s^2 + 4*s + 5))", + h_expr: "1", + ol_expr: "1/(s*(s^2 + 4*s + 5))", + expected_num: &[1.0], + expected_den: &[1.0, 4.0, 5.0, 0.0], + expected_poles: &[(0.0, 0.0), (-2.0, 1.0), (-2.0, -1.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(1.0, false), (-0.5, true), (-2.0, true)], + expected_centroid: Some(-4.0 / 3.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[(-5.0 / 3.0, 50.0 / 27.0), (-1.0, 2.0)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-2.0, 1.0, -63.43494882292201)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(SQRT5, 20.0)], + expected_positive_k_stability: "0 < K < 20", + stability_probes: &[(1.0, true), (10.0, true), (19.5, true), (20.5, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "3rd-order system where dK/ds = -(3s^2 + 8s + 5) = -(3s+5)(s+1) = 0 gives both a break-in at s = -5/3 (K = 50/27) and a breakaway at s = -1 (K = 2); jw crossing at w = sqrt(5), K = 20.", + }, + // ========================================================================= + // Q2(a) - Eq. (4): G(s) = k / (s(s + 4)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2A_EQ04", + question_item: "2(a)", + equation_number: 4, + g_expr: "1/(s*(s + 4))", + h_expr: "1", + ol_expr: "1/(s*(s + 4))", + expected_num: &[1.0], + expected_den: &[1.0, 4.0, 0.0], + expected_poles: &[(0.0, 0.0), (-4.0, 0.0)], + expected_zeros: &[], + expected_branches: 2, + real_axis_probes: &[(1.0, false), (-2.0, true), (-5.0, false)], + expected_centroid: Some(-2.0), + expected_asymptote_angles_deg: &[90.0, 270.0], + expected_breakaway_points: &[(-2.0, 4.0)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(1.0, true), (4.0, true), (50.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "2nd-order Type 1 system; real segment [-4, 0], breakaway at midpoint s = -2 (K = 4), vertical asymptotes at Re(s) = -2; stable for all K > 0.", + }, + // ========================================================================= + // Q2(b) - Eq. (5): G(s) = k / (s(s + 1)(s + 2)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2B_EQ05", + question_item: "2(b)", + equation_number: 5, + g_expr: "1/(s*(s + 1)*(s + 2))", + h_expr: "1", + ol_expr: "1/(s*(s + 1)*(s + 2))", + expected_num: &[1.0], + expected_den: &[1.0, 3.0, 2.0, 0.0], + expected_poles: &[(0.0, 0.0), (-1.0, 0.0), (-2.0, 0.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(0.5, false), (-0.5, true), (-1.5, false), (-3.0, true)], + expected_centroid: Some(-1.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[(-1.0 + SQRT3 / 3.0, 2.0 * SQRT3 / 9.0)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[], + expected_arrival_angles: &[], + expected_jw_crossings: &[(SQRT2, 6.0)], + expected_positive_k_stability: "0 < K < 6", + stability_probes: &[(0.2, true), (3.0, true), (5.9, true), (6.1, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "3 real poles at 0, -1, -2; dK/ds = -(3s^2+6s+2)=0 yields valid breakaway at s = -1 + sqrt(3)/3 in (-1, 0) with K = 2*sqrt(3)/9; Routh gives K_crit = 3*2 = 6 at w = sqrt(2).", + }, + // ========================================================================= + // Q2(c) - Eq. (6): G(s) = k(s + 2) / (s^2 + 2s + 3) [Equivalent to 1(b)] + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2C_EQ06", + question_item: "2(c)", + equation_number: 6, + g_expr: "(s + 2)/(s^2 + 2*s + 3)", + h_expr: "1", + ol_expr: "(s + 2)/(s^2 + 2*s + 3)", + expected_num: &[1.0, 2.0], + expected_den: &[1.0, 2.0, 3.0], + expected_poles: &[(-1.0, SQRT2), (-1.0, -SQRT2)], + expected_zeros: &[(-2.0, 0.0)], + expected_branches: 2, + real_axis_probes: &[(0.0, false), (-1.0, false), (-3.0, true)], + expected_centroid: Some(0.0), + expected_asymptote_angles_deg: &[180.0], + expected_breakaway_points: &[(-2.0 - SQRT3, 2.0 + 2.0 * SQRT3)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-1.0, SQRT2, 144.73561031724535)], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(0.5, true), (5.0, true), (100.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Mathematically equivalent to 1(b) Eq. (2); preserved in validation matrix.", + }, + // ========================================================================= + // Q2(d) - Eq. (7): G(s) = k / (s(s^2 + 6s + 25)) [Equivalent to 1(a)] + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2D_EQ07", + question_item: "2(d)", + equation_number: 7, + g_expr: "1/(s*(s^2 + 6*s + 25))", + h_expr: "1", + ol_expr: "1/(s*(s^2 + 6*s + 25))", + expected_num: &[1.0], + expected_den: &[1.0, 6.0, 25.0, 0.0], + expected_poles: &[(0.0, 0.0), (-3.0, 4.0), (-3.0, -4.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(1.0, false), (-1.0, true), (-5.0, true)], + expected_centroid: Some(-2.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-3.0, 4.0, -36.86989764584402)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(5.0, 150.0)], + expected_positive_k_stability: "0 < K < 150", + stability_probes: &[(1.0, true), (75.0, true), (149.0, true), (151.0, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Mathematically equivalent to 1(a) Eq. (1); preserved in validation matrix.", + }, + // ========================================================================= + // Q2(e) - Eq. (8): G(s) = k(s + 2)(s + 3) / (s(s + 1)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2E_EQ08", + question_item: "2(e)", + equation_number: 8, + g_expr: "((s + 2)*(s + 3))/(s*(s + 1))", + h_expr: "1", + ol_expr: "((s + 2)*(s + 3))/(s*(s + 1))", + expected_num: &[1.0, 5.0, 6.0], + expected_den: &[1.0, 1.0, 0.0], + expected_poles: &[(0.0, 0.0), (-1.0, 0.0)], + expected_zeros: &[(-2.0, 0.0), (-3.0, 0.0)], + expected_branches: 2, + real_axis_probes: &[ + (0.5, false), + (-0.5, true), + (-1.5, false), + (-2.5, true), + (-3.5, false), + ], + expected_centroid: None, + expected_asymptote_angles_deg: &[], + expected_breakaway_points: &[ + (-(3.0 + SQRT3) / 2.0, 7.0 + 4.0 * SQRT3), + (-(3.0 - SQRT3) / 2.0, 7.0 - 4.0 * SQRT3), + ], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(0.05, true), (1.0, true), (20.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Relative degree zero (P = Z = 2, no asymptotes); breakaway in (-1, 0) at s = -(3-sqrt(3))/2 (K = 7-4*sqrt(3)) and break-in in (-3, -2) at s = -(3+sqrt(3))/2 (K = 7+4*sqrt(3)); circular arc between them.", + }, + // ========================================================================= + // Q2(f) - Eq. (9): G(s) = k(s^2 + 2s + 8) / (s(s + 10)(s + 5)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2F_EQ09", + question_item: "2(f)", + equation_number: 9, + g_expr: "(s^2 + 2*s + 8)/(s*(s + 10)*(s + 5))", + h_expr: "1", + ol_expr: "(s^2 + 2*s + 8)/(s*(s + 10)*(s + 5))", + expected_num: &[1.0, 2.0, 8.0], + expected_den: &[1.0, 15.0, 50.0, 0.0], + expected_poles: &[(0.0, 0.0), (-5.0, 0.0), (-10.0, 0.0)], + expected_zeros: &[(-1.0, SQRT7), (-1.0, -SQRT7)], + expected_branches: 3, + real_axis_probes: &[(1.0, false), (-2.0, true), (-7.5, false), (-12.0, true)], + expected_centroid: Some(-13.0), + expected_asymptote_angles_deg: &[180.0], + expected_breakaway_points: &[(-1.667944789809077, 6.218909031131223)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[], + expected_arrival_angles: &[(-1.0, SQRT7, -109.43118873073795)], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(1.0, true), (10.0, true), (100.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "P=3, Z=2 (complex conjugate zeros at -1 +/- sqrt(7)j); single asymptote at 180 deg with centroid -13; breakaway at s = -1.667945 (K = 6.218909) and arrival angle -109.4312 deg at -1 + sqrt(7)j.", + }, + // ========================================================================= + // Q2(g) - Eq. (10): G(s) = k(s^2 + 4) / ((s + 2)^2 (s + 5)(s + 6)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2G_EQ10", + question_item: "2(g)", + equation_number: 10, + g_expr: "(s^2 + 4)/(((s + 2)^2)*(s + 5)*(s + 6))", + h_expr: "1", + ol_expr: "(s^2 + 4)/(((s + 2)^2)*(s + 5)*(s + 6))", + expected_num: &[1.0, 0.0, 4.0], + expected_den: &[1.0, 15.0, 78.0, 164.0, 120.0], + expected_poles: &[(-2.0, 0.0), (-2.0, 0.0), (-5.0, 0.0), (-6.0, 0.0)], + expected_zeros: &[(0.0, 2.0), (0.0, -2.0)], + expected_branches: 4, + real_axis_probes: &[ + (0.0, false), + (-1.0, false), + (-3.5, false), + (-5.5, true), + (-7.0, false), + ], + expected_centroid: Some(-7.5), + expected_asymptote_angles_deg: &[90.0, 270.0], + expected_breakaway_points: &[(-5.530716069857954, 0.08976101605604443)], + expected_k0_multiple_pole_breakaways: &[-2.0], + expected_departure_angles: &[], + expected_arrival_angles: &[(0.0, 2.0, -139.76363520094115)], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(0.05, true), (1.0, true), (100.0, true)], + root_tolerance: TOL_MULT_ROOT, + justification: "Repeated pole at s = -2 (multiplicity 2, departing immediately at +/-90 deg at K = 0) and simple poles at -5, -6 (breakaway at s = -5.530716, K = 0.089761); zeros on jw axis at +/-2j reached only as K -> +inf, so strictly stable for all finite K > 0.", + }, + // ========================================================================= + // Q2(h) - Eq. (11): G(s) = k / ((s + 1)(s^2 + 4s + 5)) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2H_EQ11", + question_item: "2(h)", + equation_number: 11, + g_expr: "1/((s + 1)*(s^2 + 4*s + 5))", + h_expr: "1", + ol_expr: "1/((s + 1)*(s^2 + 4*s + 5))", + expected_num: &[1.0], + expected_den: &[1.0, 5.0, 9.0, 5.0], + expected_poles: &[(-1.0, 0.0), (-2.0, 1.0), (-2.0, -1.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(0.0, false), (-0.5, false), (-2.0, true)], + expected_centroid: Some(-5.0 / 3.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-2.0, 1.0, -45.0)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(3.0, 40.0)], + expected_positive_k_stability: "0 < K < 40", + stability_probes: &[(1.0, true), (20.0, true), (39.5, true), (40.5, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "3rd-order shifted pole configuration; dK/ds = -(3s^2+10s+9) has negative discriminant (100-108=-8<0), so no real breakaway; Routh gives 5*9 - (5+K) = 0 => K_crit = 40 at w = 3 rad/s.", + }, + // ========================================================================= + // Q2(i)-1 - Eq. (12): G(s) = k / (s(s^2 + 4s + 5)) [First 2(i) in PDF] + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2I1_EQ12", + question_item: "2(i)-1", + equation_number: 12, + g_expr: "1/(s*(s^2 + 4*s + 5))", + h_expr: "1", + ol_expr: "1/(s*(s^2 + 4*s + 5))", + expected_num: &[1.0], + expected_den: &[1.0, 4.0, 5.0, 0.0], + expected_poles: &[(0.0, 0.0), (-2.0, 1.0), (-2.0, -1.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(1.0, false), (-0.5, true), (-2.0, true)], + expected_centroid: Some(-4.0 / 3.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[(-5.0 / 3.0, 50.0 / 27.0), (-1.0, 2.0)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-2.0, 1.0, -63.43494882292201)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(SQRT5, 20.0)], + expected_positive_k_stability: "0 < K < 20", + stability_probes: &[(1.0, true), (10.0, true), (19.5, true), (20.5, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "First item labeled 2(i) in PDF (Equation 12), mathematically equivalent to 1(c) Eq. (3) and 3(a) Eq. (14).", + }, + // ========================================================================= + // Q2(i)-2 - Eq. (13): G(s) = k(s + 2) / ((s + 1)(s^2 + 6s + 10)) [Second 2(i) in PDF] + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q2I2_EQ13", + question_item: "2(i)-2", + equation_number: 13, + g_expr: "(s + 2)/((s + 1)*(s^2 + 6*s + 10))", + h_expr: "1", + ol_expr: "(s + 2)/((s + 1)*(s^2 + 6*s + 10))", + expected_num: &[1.0, 2.0], + expected_den: &[1.0, 7.0, 16.0, 10.0], + expected_poles: &[(-1.0, 0.0), (-3.0, 1.0), (-3.0, -1.0)], + expected_zeros: &[(-2.0, 0.0)], + expected_branches: 3, + real_axis_probes: &[(0.0, false), (-1.5, true), (-3.0, false)], + expected_centroid: Some(-2.5), + expected_asymptote_angles_deg: &[90.0, 270.0], + expected_breakaway_points: &[], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-3.0, 1.0, 71.56505117707799)], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(1.0, true), (15.0, true), (200.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Second item labeled 2(i) in PDF (Equation 13); real pole at -1 moves directly to zero at -2; complex poles at -3 +/- 1j depart at +71.5651 deg and approach vertical asymptotes at Re(s) = -2.5; stable for all K > 0.", + }, + // ========================================================================= + // Q3(a) - Eq. (14): G(s) = k / (s(s^2 + 4s + 5)), H(s) = 1 [Equivalent to 1(c)] + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q3A_EQ14", + question_item: "3(a)", + equation_number: 14, + g_expr: "1/(s*(s^2 + 4*s + 5))", + h_expr: "1", + ol_expr: "1/(s*(s^2 + 4*s + 5))", + expected_num: &[1.0], + expected_den: &[1.0, 4.0, 5.0, 0.0], + expected_poles: &[(0.0, 0.0), (-2.0, 1.0), (-2.0, -1.0)], + expected_zeros: &[], + expected_branches: 3, + real_axis_probes: &[(1.0, false), (-0.5, true), (-2.0, true)], + expected_centroid: Some(-4.0 / 3.0), + expected_asymptote_angles_deg: &[60.0, 180.0, 300.0], + expected_breakaway_points: &[(-5.0 / 3.0, 50.0 / 27.0), (-1.0, 2.0)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-2.0, 1.0, -63.43494882292201)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(SQRT5, 20.0)], + expected_positive_k_stability: "0 < K < 20", + stability_probes: &[(1.0, true), (10.0, true), (19.5, true), (20.5, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Block diagram in Fig. 1 with unity feedback H(s) = 1; equivalent to 1(c) Eq. (3) and 2(i)-1 Eq. (12).", + }, + // ========================================================================= + // Q3(b) - Eq. (15): G(s) = k / (s(s^2 + 4s + 13)), H(s) = 1 / (s + 1) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q3B_EQ15", + question_item: "3(b)", + equation_number: 15, + g_expr: "1/(s*(s^2 + 4*s + 13))", + h_expr: "1/(s + 1)", + ol_expr: "1/(s*(s + 1)*(s^2 + 4*s + 13))", + expected_num: &[1.0], + expected_den: &[1.0, 5.0, 17.0, 13.0, 0.0], + expected_poles: &[(0.0, 0.0), (-1.0, 0.0), (-2.0, 3.0), (-2.0, -3.0)], + expected_zeros: &[], + expected_branches: 4, + real_axis_probes: &[(0.5, false), (-0.5, true), (-2.0, false)], + expected_centroid: Some(-1.25), + expected_asymptote_angles_deg: &[45.0, 135.0, 225.0, 315.0], + expected_breakaway_points: &[(-0.46637844124531597, 2.825166371537658)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-2.0, 3.0, -142.1250163489018)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(SQRT2_6, 37.44)], + expected_positive_k_stability: "0 < K < 37.44", + stability_probes: &[(1.0, true), (20.0, true), (37.0, true), (38.0, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Non-unity feedback H(s) = 1/(s+1) yields 4th-order open-loop G(s)H(s); breakaway in (-1, 0) at s = -0.466378 (K = 2.825166); Routh gives K_crit = 936/25 = 37.44 at w = sqrt(13/5) = sqrt(2.6) rad/s.", + }, + // ========================================================================= + // Q3(c) - Eq. (16): G(s) = k / (s + 3.6), H(s) = (s + 1) / s^2 + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q3C_EQ16", + question_item: "3(c)", + equation_number: 16, + g_expr: "1/(s + 3.6)", + h_expr: "(s + 1)/(s^2)", + ol_expr: "(s + 1)/(s^2*(s + 3.6))", + expected_num: &[1.0, 1.0], + expected_den: &[1.0, 3.6, 0.0, 0.0], + expected_poles: &[(0.0, 0.0), (0.0, 0.0), (-3.6, 0.0)], + expected_zeros: &[(-1.0, 0.0)], + expected_branches: 3, + real_axis_probes: &[(0.5, false), (-0.5, false), (-2.0, true), (-5.0, false)], + expected_centroid: Some(-1.3), + expected_asymptote_angles_deg: &[90.0, 270.0], + expected_breakaway_points: &[], + expected_k0_multiple_pole_breakaways: &[0.0], + expected_departure_angles: &[], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(0.5, true), (5.0, true), (100.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Non-unity feedback H(s)=(s+1)/s^2 with fractional pole at -3.6 and double pole at origin; double pole at s=0 breaks away immediately into LHP at +/-90 deg at K=0 because zero at -1 is closer than pole at -3.6; Routh first column (1, 3.6, 2.6K/3.6, K) > 0 for all K > 0.", + }, + // ========================================================================= + // Q4(a) - Eq. (17): G(s) = k(s + 2) / (s^2 + 4s + 13) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q4A_EQ17", + question_item: "4(a)", + equation_number: 17, + g_expr: "(s + 2)/(s^2 + 4*s + 13)", + h_expr: "1", + ol_expr: "(s + 2)/(s^2 + 4*s + 13)", + expected_num: &[1.0, 2.0], + expected_den: &[1.0, 4.0, 13.0], + expected_poles: &[(-2.0, 3.0), (-2.0, -3.0)], + expected_zeros: &[(-2.0, 0.0)], + expected_branches: 2, + real_axis_probes: &[(0.0, false), (-1.0, false), (-3.5, true)], + expected_centroid: Some(-2.0), + expected_asymptote_angles_deg: &[180.0], + expected_breakaway_points: &[(-5.0, 6.0)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-2.0, 3.0, -180.0)], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "K > 0", + stability_probes: &[(1.0, true), (6.0, true), (50.0, true)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Zero at s = -2 lies vertically below/above poles -2 +/- 3j; departure angle is 180 deg (-180 deg), forming a circle of radius 3 centered at -2 with break-in at s = -5 (K = 6); stable for all K > 0.", + }, + // ========================================================================= + // Q4(b) - Eq. (18): G(s) = k(s - 2)(s - 4) / (s^2 + 6s + 25) + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q4B_EQ18", + question_item: "4(b)", + equation_number: 18, + g_expr: "((s - 2)*(s - 4))/(s^2 + 6*s + 25)", + h_expr: "1", + ol_expr: "((s - 2)*(s - 4))/(s^2 + 6*s + 25)", + expected_num: &[1.0, -6.0, 8.0], + expected_den: &[1.0, 6.0, 25.0], + expected_poles: &[(-3.0, 4.0), (-3.0, -4.0)], + expected_zeros: &[(2.0, 0.0), (4.0, 0.0)], + expected_branches: 2, + real_axis_probes: &[(5.0, false), (3.0, true), (0.0, false), (-5.0, false)], + expected_centroid: None, + expected_asymptote_angles_deg: &[], + expected_breakaway_points: &[((-17.0 + SQRT2665) / 12.0, 51.311818998280614)], + expected_k0_multiple_pole_breakaways: &[], + expected_departure_angles: &[(-3.0, 4.0, 21.59528822706794)], + expected_arrival_angles: &[], + expected_jw_crossings: &[(SQRT16_5, 1.0)], + expected_positive_k_stability: "0 < K < 1", + stability_probes: &[(0.2, true), (0.8, true), (1.2, false), (10.0, false)], + root_tolerance: TOL_SIMPLE_ROOT, + justification: "Relative degree 0 non-minimum phase system with two RHP zeros at +2 and +4; characteristic polynomial (1+K)s^2 + 6(1-K)s + (25+8K) = 0 crosses jw axis at K = 1, w = sqrt(33/2) = sqrt(16.5) rad/s and breaks into real axis at s = (17+sqrt(2665))/24 in (2, 4) with K = 51.311819.", + }, + // ========================================================================= + // Q5(a,b) - Eq. (19): s^3 + a2*s^2 + a1*s + a1 = 0 with a2 = 0 => G(s)H(s) = a1(s + 1)/s^3 + // ========================================================================= + LgrAcademicCase { + id: "LGR_Q5_EQ19", + question_item: "5(a,b)", + equation_number: 19, + g_expr: "(s + 1)/(s^3)", + h_expr: "1", + ol_expr: "(s + 1)/(s^3)", + expected_num: &[1.0, 1.0], + expected_den: &[1.0, 0.0, 0.0, 0.0], + expected_poles: &[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)], + expected_zeros: &[(-1.0, 0.0)], + expected_branches: 3, + real_axis_probes: &[(0.5, false), (-0.5, true), (-2.0, false)], + expected_centroid: Some(0.5), + expected_asymptote_angles_deg: &[90.0, 270.0], + expected_breakaway_points: &[], + expected_k0_multiple_pole_breakaways: &[0.0], + expected_departure_angles: &[], + expected_arrival_angles: &[], + expected_jw_crossings: &[], + expected_positive_k_stability: "\\text{Sem faixa estável}", + stability_probes: &[(0.1, false), (1.0, false), (10.0, false)], + root_tolerance: TOL_MULT_ROOT, + justification: "Parametric characteristic equation s^3 + a2*s^2 + a1*s + a1 = 0 with a2 = 0 and gain K = a1 > 0: equivalent open-loop transfer function G(s)H(s) = (s+1)/s^3; triple pole at s = 0 departs at 60 deg, 180 deg, 300 deg; centroid is sigma_a = +0.5 in RHP, so two branches remain in RHP for all K > 0 (system unstable for all K > 0).", + }, + ] +} + +#[test] +fn validate_all_19_lgr_cases_analytical_and_matlab_reference() { + let cases = all_lgr_academic_cases(); + assert_eq!(cases.len(), 19, "Must validate all 19 LGR cases"); + + for (idx, case) in cases.iter().enumerate() { + assert!( + !case.question_item.is_empty(), + "{}: empty question_item", + case.id + ); + assert_eq!( + case.equation_number as usize, + idx + 1, + "{}: equation_number mismatch", + case.id + ); + // 1. Verify open-loop transfer function G(s)*H(s) and coefficient normalization. + let g_tf = TransferFunction::parse(case.g_expr).unwrap(); + let h_tf = TransferFunction::parse(case.h_expr).unwrap(); + let gh_tf = g_tf.multiply(&h_tf).unwrap().normalized(); + let ol_tf = TransferFunction::parse(case.ol_expr).unwrap().normalized(); + + assert_eq!( + gh_tf.num.len(), + case.expected_num.len(), + "{} ({}): numerator length mismatch", + case.id, + case.justification + ); + assert_eq!( + gh_tf.den.len(), + case.expected_den.len(), + "{} ({}): denominator length mismatch", + case.id, + case.justification + ); + for (a, e) in gh_tf.num.iter().zip(case.expected_num) { + assert!( + (a - e).abs() <= TOL_COEFF, + "{}: numerator coeff {a} != {e}", + case.id + ); + } + for (a, e) in gh_tf.den.iter().zip(case.expected_den) { + assert!( + (a - e).abs() <= TOL_COEFF, + "{}: denominator coeff {a} != {e}", + case.id + ); + } + for (a, e) in ol_tf.num.iter().zip(case.expected_num) { + assert!((a - e).abs() <= TOL_COEFF, "{}: ol num {a} != {e}", case.id); + } + for (a, e) in ol_tf.den.iter().zip(case.expected_den) { + assert!((a - e).abs() <= TOL_COEFF, "{}: ol den {a} != {e}", case.id); + } + + // 2. Run ControLAB LGR engine analysis. + let dpi = if idx == 0 { 140 } else { 72 }; + let res = lgr::analyze(&json!({"expr": case.ol_expr, "dpi": dpi})).unwrap(); + assert_eq!(res["success"], true, "{}: LGR analysis failed", case.id); + assert!( + res["svg"].as_str().unwrap().contains(" = det["polos"] + .as_array() + .unwrap() + .iter() + .map(|p| c(p["re"].as_f64().unwrap(), p["im"].as_f64().unwrap())) + .collect(); + let expected_poles: Vec = case + .expected_poles + .iter() + .map(|&(re, im)| c(re, im)) + .collect(); + let pole_err = unordered_complex_distance(&actual_poles, &expected_poles); + assert!( + pole_err <= case.root_tolerance, + "{}: pole set error {pole_err:e} > {:e}", + case.id, + case.root_tolerance + ); + assert_conjugate_symmetry(&actual_poles, case.root_tolerance, case.id); + + let actual_zeros: Vec = det["zeros"] + .as_array() + .unwrap() + .iter() + .map(|z| c(z["re"].as_f64().unwrap(), z["im"].as_f64().unwrap())) + .collect(); + let expected_zeros: Vec = case + .expected_zeros + .iter() + .map(|&(re, im)| c(re, im)) + .collect(); + let zero_err = unordered_complex_distance(&actual_zeros, &expected_zeros); + assert!( + zero_err <= case.root_tolerance, + "{}: zero set error {zero_err:e} > {:e}", + case.id, + case.root_tolerance + ); + assert_conjugate_symmetry(&actual_zeros, case.root_tolerance, case.id); + + // 5. Verify real-axis segments both via the odd-count rule and phase condition G(sigma)H(sigma) < 0. + let segs = det["passo_a_passo"]["passo_1_2_3"]["segmentos_eixo_real"] + .as_array() + .unwrap(); + assert!( + !segs.is_empty(), + "{}: real-axis segments must be populated", + case.id + ); + for &(sigma, expected_on_lgr) in case.real_axis_probes { + let val = ol_tf.evaluate(c(sigma, 0.0)); + assert!( + val.im.abs() < 1e-12, + "{}: real-axis evaluation at s={sigma} had non-zero imaginary part {}", + case.id, + val.im + ); + let on_lgr_by_phase = val.re < 0.0; + let count_right = expected_poles + .iter() + .chain(expected_zeros.iter()) + .filter(|r| r.im.abs() < 1e-6 && r.re > sigma) + .count(); + let on_lgr_by_count = count_right % 2 == 1; + assert_eq!( + on_lgr_by_phase, expected_on_lgr, + "{}: phase condition at s={sigma} disagrees with expected={expected_on_lgr}", + case.id + ); + assert_eq!( + on_lgr_by_count, expected_on_lgr, + "{}: odd-count rule at s={sigma} disagrees with expected={expected_on_lgr}", + case.id + ); + } + + // 6. Verify asymptotes (centroid and angles). + match case.expected_centroid { + Some(exp_c) => { + let act_c = det["centroide"] + .as_f64() + .unwrap_or_else(|| panic!("{}: expected centroid Some({exp_c})", case.id)); + assert!( + (act_c - exp_c).abs() <= TOL_CENTROID, + "{}: centroid {act_c} != {exp_c}", + case.id + ); + } + None => { + assert!( + det["centroide"].is_null(), + "{}: expected null centroid for relative-degree-0 system", + case.id + ); + } + } + let mut act_asym_angles: Vec = det["angulos_assintotas"] + .as_array() + .unwrap() + .iter() + .map(|v| v["graus"].as_f64().unwrap()) + .collect(); + act_asym_angles.sort_by(f64::total_cmp); + assert_eq!( + act_asym_angles.len(), + case.expected_asymptote_angles_deg.len(), + "{}: asymptote count mismatch", + case.id + ); + for (a, e) in act_asym_angles + .iter() + .zip(case.expected_asymptote_angles_deg) + { + assert!( + (a - e).abs() <= TOL_ANGLE_DEG, + "{}: asymptote angle {a} != {e}", + case.id + ); + } + + // 7. Verify breakaway and break-in points on the real axis. + let mut act_bp: Vec<(f64, f64)> = det["break_points"] + .as_array() + .unwrap() + .iter() + .map(|b| (b["s"].as_f64().unwrap(), b["K"].as_f64().unwrap())) + .collect(); + act_bp.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert_eq!( + act_bp.len(), + case.expected_breakaway_points.len(), + "{}: breakaway point count mismatch: actual={act_bp:?} vs expected={:?}", + case.id, + case.expected_breakaway_points + ); + let d_num = poly::derivative(&ol_tf.num); + let d_den = poly::derivative(&ol_tf.den); + let dk_ds_num = poly::add( + &poly::multiply(&d_num, &ol_tf.den), + &poly::multiply(&ol_tf.num, &d_den), + -1.0, + ); + for ((act_s, act_k), (exp_s, exp_k)) in act_bp.iter().zip(case.expected_breakaway_points) { + assert!( + (act_s - exp_s).abs() <= TOL_BREAKAWAY_S, + "{}: breakaway s {act_s} != {exp_s}", + case.id + ); + assert!( + (act_k - exp_k).abs() <= TOL_BREAKAWAY_K, + "{}: breakaway K {act_k} != {exp_k}", + case.id + ); + // Analytical stationarity check: N'(s)D(s) - N(s)D'(s) = 0 and D(s) + K*N(s) = 0 + let stationarity = poly::evaluate(&dk_ds_num, c(*exp_s, 0.0)).norm(); + assert!( + stationarity <= 1e-7, + "{}: stationarity residual at s={exp_s} is {stationarity:e}", + case.id + ); + let char_res = + normalized_char_poly_residual(&ol_tf.den, &ol_tf.num, *exp_k, c(*exp_s, 0.0)); + assert!( + char_res <= 1e-10, + "{}: char equation residual at breakaway s={exp_s}, K={exp_k} is {char_res:e}", + case.id + ); + } + // Also verify K=0 multiple-pole breakaway roots of dK/ds = 0 when present (Eq. 10, Eq. 16, Eq. 19). + for &mult_s in case.expected_k0_multiple_pole_breakaways { + let stationarity = poly::evaluate(&dk_ds_num, c(mult_s, 0.0)).norm(); + assert!( + stationarity <= 1e-9, + "{}: multiple pole at s={mult_s} must be a root of dK/ds=0, got {stationarity:e}", + case.id + ); + let char_at_k0 = poly::evaluate(&ol_tf.den, c(mult_s, 0.0)).norm(); + assert!( + char_at_k0 <= 1e-9, + "{}: multiple pole at s={mult_s} must satisfy D(s)=0 at K=0", + case.id + ); + } + + // 8. Verify angles of departure and arrival. + let act_dep = det["angulos_partida"].as_array().unwrap(); + assert_eq!( + act_dep.len(), + case.expected_departure_angles.len(), + "{}: departure angle count mismatch", + case.id + ); + for (act, &(re, im, exp_deg)) in act_dep.iter().zip(case.expected_departure_angles) { + let act_deg = act["angulo"].as_f64().unwrap(); + let diff = wrap_angle_180(act_deg - exp_deg).abs(); + assert!( + diff <= TOL_ANGLE_DEG, + "{}: departure angle at ({re}, {im}) was {act_deg} != {exp_deg}", + case.id + ); + } + + let act_arr = det["angulos_chegada"].as_array().unwrap(); + assert_eq!( + act_arr.len(), + case.expected_arrival_angles.len(), + "{}: arrival angle count mismatch", + case.id + ); + for (act, &(re, im, exp_deg)) in act_arr.iter().zip(case.expected_arrival_angles) { + let act_deg = act["angulo"].as_f64().unwrap(); + let diff = wrap_angle_180(act_deg - exp_deg).abs(); + assert!( + diff <= TOL_ANGLE_DEG, + "{}: arrival angle at ({re}, {im}) was {act_deg} != {exp_deg}", + case.id + ); + } + + // 9. Verify jw-axis crossings and Routh-Hurwitz critical gains / stability intervals. + let act_jw: Vec<(f64, f64)> = det["jw_cruzamentos"] + .as_array() + .unwrap() + .iter() + .filter_map(|v| { + let w = v["w"].as_f64().unwrap(); + let k = v["K"].as_f64().unwrap(); + (w > 0.0).then_some((w, k)) + }) + .collect(); + assert_eq!( + act_jw.len(), + case.expected_jw_crossings.len(), + "{}: jw crossing count mismatch: actual={act_jw:?} vs expected={:?}", + case.id, + case.expected_jw_crossings + ); + for ((act_w, act_k), (exp_w, exp_k)) in act_jw.iter().zip(case.expected_jw_crossings) { + assert!( + (act_w - exp_w).abs() <= TOL_JW_W, + "{}: jw crossing omega {act_w} != {exp_w}", + case.id + ); + assert!( + (act_k - exp_k).abs() <= TOL_JW_K, + "{}: jw crossing K {act_k} != {exp_k}", + case.id + ); + // Exact characteristic equation check at s = j * exp_w, K = exp_k: + let jw_res = + normalized_char_poly_residual(&ol_tf.den, &ol_tf.num, *exp_k, c(0.0, *exp_w)); + assert!( + jw_res <= 1e-12, + "{}: exact jw crossing residual at w={exp_w}, K={exp_k} is {jw_res:e}", + case.id + ); + } + + // Cross-check with Routh-Hurwitz module: + let routh_res = routh::analyze(&json!({"expr": case.ol_expr, "dpi": dpi})).unwrap(); + assert_eq!( + routh_res["success"], true, + "{}: Routh analysis failed", + case.id + ); + let k_range = &routh_res["k_range"]; + let stable_latex = k_range["stable_latex"].as_str().unwrap(); + assert!( + stable_latex.contains(case.expected_positive_k_stability), + "{}: Routh stable_latex '{stable_latex}' does not contain '{}'", + case.id, + case.expected_positive_k_stability + ); + // Verify Routh critical_k matches expected jw crossing K_crit: + let routh_crit: Vec = k_range["critical_k"] + .as_array() + .unwrap() + .iter() + .map(|ck| ck["k_val"].as_f64().unwrap()) + .collect(); + for &(_exp_w, exp_k) in case.expected_jw_crossings { + assert!( + routh_crit.iter().any(|&rk| (rk - exp_k).abs() <= 1e-6), + "{}: Routh critical_k {routh_crit:?} missing expected K_crit={exp_k}", + case.id + ); + } + + // 10. Validate characteristic equation D(s) + K*N(s) = 0, conjugate symmetry, + // stability transitions, and branch continuity across gains. + for &(k_probe, expected_stable) in case.stability_probes { + let roots = poly::roots(&poly::add(&ol_tf.den, &ol_tf.num, k_probe)).unwrap(); + assert_eq!(roots.len(), case.expected_branches); + assert_conjugate_symmetry(&roots, case.root_tolerance, case.id); + for r in &roots { + let res_norm = normalized_char_poly_residual(&ol_tf.den, &ol_tf.num, k_probe, *r); + assert!( + res_norm <= 1e-9, + "{}: char poly residual at K={k_probe} for root {r} is {res_norm:e}", + case.id + ); + } + let is_stable = roots.iter().all(|r| r.re < -1e-7); + assert_eq!( + is_stable, expected_stable, + "{}: stability mismatch at K={k_probe}: roots={roots:?}", + case.id + ); + } + + // 11. Verify behavior for K -> 0+ and K -> +infty, plus trajectory branch continuity. + let k_small = 1e-8; + let roots_small = poly::roots(&poly::add(&ol_tf.den, &ol_tf.num, k_small)).unwrap(); + let small_dist = unordered_complex_distance(&roots_small, &expected_poles); + // For triple pole (m=3), perturbation scales as (k_small)^(1/3) = 1e-8/3 ~ 2.15e-3. + let small_tol = if case.id == "LGR_Q5_EQ19" { + 5e-3 + } else if !case.expected_k0_multiple_pole_breakaways.is_empty() { + 5e-4 + } else { + 1e-5 + }; + assert!( + small_dist <= small_tol, + "{}: roots as K->0+ did not converge to open-loop poles: dist={small_dist:e} > {small_tol:e}", + case.id + ); + + let k_large = 1e6; + let roots_large = poly::roots(&poly::add(&ol_tf.den, &ol_tf.num, k_large)).unwrap(); + assert_conjugate_symmetry(&roots_large, 1e-4, case.id); + for r in &roots_large { + let res_norm = normalized_char_poly_residual(&ol_tf.den, &ol_tf.num, k_large, *r); + assert!( + res_norm <= 1e-8, + "{}: high-gain residual at K={k_large} is {res_norm:e}", + case.id + ); + } + // Each finite open-loop zero must attract a closed-loop root as K -> +infty: + for z in &expected_zeros { + let min_dist = roots_large + .iter() + .map(|r| (*r - *z).norm()) + .fold(f64::INFINITY, f64::min); + assert!( + min_dist <= 1e-2, + "{}: open-loop zero {z} not approached at K={k_large}, min_dist={min_dist:e}", + case.id + ); + } + // If P > Z, the remaining (P - Z) roots must diverge to infinity along asymptotes: + if let Some(centroid) = case.expected_centroid { + let mut diverging: Vec = roots_large + .iter() + .copied() + .filter(|r| expected_zeros.iter().all(|z| (*r - *z).norm() > 1.0)) + .collect(); + assert_eq!( + diverging.len(), + case.expected_poles.len() - case.expected_zeros.len(), + "{}: diverging root count mismatch at K={k_large}", + case.id + ); + let mut div_angles: Vec = diverging + .drain(..) + .map(|r| { + let deg = (r - c(centroid, 0.0)).arg().to_degrees(); + deg.rem_euclid(360.0) + }) + .collect(); + div_angles.sort_by(f64::total_cmp); + for (act_a, exp_a) in div_angles.iter().zip(case.expected_asymptote_angles_deg) { + let diff = wrap_angle_180(act_a - exp_a).abs(); + assert!( + diff <= 2.5, + "{}: high-gain diverging root angle {act_a} deg differs from asymptote {exp_a} deg by {diff} deg", + case.id + ); + } + } + } +} + +#[test] +fn validate_lgr_branch_continuity_and_equivalences_and_q5_parametric_departure() { + let cases = all_lgr_academic_cases(); + + // 1. Verify branch continuity on dense logarithmic grid for every case. + let gains: Vec = (0..=400) + .map(|i| 10.0_f64.powf(-3.0 + 6.0 * (i as f64) / 400.0)) + .collect(); + for case in &cases { + let ol_tf = TransferFunction::parse(case.ol_expr).unwrap().normalized(); + let mut prev_roots = poly::roots(&poly::add(&ol_tf.den, &ol_tf.num, gains[0])).unwrap(); + for &k in &gains[1..] { + let roots = poly::roots(&poly::add(&ol_tf.den, &ol_tf.num, k)).unwrap(); + assert!( + roots.iter().all(|r| r.re.is_finite() && r.im.is_finite()), + "{}: non-finite root at K={k}", + case.id + ); + let step_dist = unordered_complex_distance(&roots, &prev_roots); + let max_norm = roots.iter().map(|r| r.norm()).fold(1.0, f64::max); + assert!( + step_dist <= 0.25 * max_norm, + "{}: branch discontinuity at K={k}: step_dist={step_dist} (max_norm={max_norm})", + case.id + ); + prev_roots = roots; + } + } + + // 2. Verify mathematical equivalences required by the problem statement: + // - 1(a) Eq.(1) == 2(d) Eq.(7) + // - 1(b) Eq.(2) == 2(c) Eq.(6) + // - 1(c) Eq.(3) == 2(i)-1 Eq.(12) == 3(a) Eq.(14) + let find_case = |id: &str| -> Value { + let c = cases.iter().find(|c| c.id == id).unwrap(); + lgr::analyze(&json!({"expr": c.ol_expr, "dpi": 72})).unwrap()["detalhes"].clone() + }; + assert_eq!(find_case("LGR_Q1A_EQ01"), find_case("LGR_Q2D_EQ07")); + assert_eq!(find_case("LGR_Q1B_EQ02"), find_case("LGR_Q2C_EQ06")); + let q1c = find_case("LGR_Q1C_EQ03"); + assert_eq!(q1c, find_case("LGR_Q2I1_EQ12")); + assert_eq!(q1c, find_case("LGR_Q3A_EQ14")); + + // 3. Verify Question 5 Eq. (19) triple-pole departure angles (60 deg, 180 deg, 300 deg) + // from s = 0 for s^3 + a2*s^2 + a1*s + a1 = 0 with a2 = 0 and small a1 > 0. + let q5_tf = TransferFunction::parse("(s + 1)/(s^3)").unwrap(); + let k_eps = 1e-6; + let q5_roots = poly::roots(&poly::add(&q5_tf.den, &q5_tf.num, k_eps)).unwrap(); + let mut dep_angles: Vec = q5_roots + .iter() + .map(|r| r.arg().to_degrees().rem_euclid(360.0)) + .collect(); + dep_angles.sort_by(f64::total_cmp); + for (act, exp) in dep_angles.iter().zip(&[60.0, 180.0, 300.0]) { + assert!( + (act - exp).abs() <= 0.5, + "Q5 Eq.(19): triple pole departure angle {act} deg != {exp} deg" + ); + } +} diff --git a/crates/control-engine/tests/academic_requirements_compliance.rs b/crates/control-engine/tests/academic_requirements_compliance.rs new file mode 100644 index 0000000..b2c2b8f --- /dev/null +++ b/crates/control-engine/tests/academic_requirements_compliance.rs @@ -0,0 +1,631 @@ +//! Etapa 10 — Scientific compliance audit, requirement verification, independent Q8 reference, +//! and generic constrained controller synthesis regression tests. +//! +//! Validates that: +//! 1. Numerically accurate LGR controllers are explicitly flagged as `REQUIREMENTS_FAIL` when +//! real closed-loop metrics violate requested specifications (Q2 PD/PID, Q5 literal ts=1s, +//! Q7 literal Mp<=16%, Q8 classic PI Mp=33.84%, Q9 classic PD Mp=29.84%). +//! 2. Unstable systems and internally unstable RHP pole-zero cancellations are never classified +//! as successful designs. +//! 3. Non-dominant poles, approximate cancellations, extra zeros, non-unity feedback tracking +//! error, and didactic specification conflicts (xi=0.5 vs Mp<=16%) are explicitly flagged. +//! 4. The independent Q8 reference solution (Kp = -1.0, Ki = -0.2 => T(s) = 1.44/(s+1.44)) +//! is verified nominally, for disturbance rejection, and under +/-10% plant perturbations. +//! 5. Generic constrained numerical refinement (`temporal_refined`) and automatic simplest +//! controller selection (`auto_simplest`) find strictly compliant controllers for Q2, Q5, +//! Q7, Q8, and Q9 without relaxing tolerances or hardcoding any exercise. + +use controlab_engine::{ + controller_synthesis::{ + ControllerStructure, DampingSpec, DesignObjective, DesignSpecs, FeasibilityClass, + RequirementStatus, SettlingSpec, default_settling_tolerance, synthesize_for_structure, + synthesize_simplest, verify_controller, + }, + controllers, + simulation::{self, Input}, + time_response, + transfer::TransferFunction, +}; +use serde_json::json; + +#[test] +fn numerically_correct_classic_lgr_controllers_fail_requirements_when_specs_violated() { + // 1. Q2 classic PD: G(s) = 1/(s^2+1), Kp=3, Kd=2 -> Mp = 41.25% > 16.3%, ts = 3.72s != 4s + let q2_pd = controllers::analyze(&json!({ + "action": "controller_design", + "plant_expr": "1/(s^2 + 1)", + "controller_type": "PD", + "mp": 16.3, + "xi": 0.5, + "ts": 4.0, + "ts_constraint": "equal", + "ts_tolerance": 0.1, + "settling_criterion": "2", + "synthesis_mode": "lgr_classic", + "verify_requirements": true, + "dpi": 72 + })) + .unwrap(); + let v = &q2_pd["details"]["verification"]; + assert_eq!(v["numerically_valid"], true); + assert_eq!(v["closed_loop_stable"], true); + assert_eq!(v["requirements_passed"], false); + assert_eq!(v["overall_status"], "FAIL"); + assert!(v["measured"]["overshoot_percent"].as_f64().unwrap() > 40.0); + assert!( + v["warnings"] + .as_array() + .unwrap() + .iter() + .any(|w| w.as_str().unwrap().contains("zero(s) de malha fechada")) + ); + + // 2. Q2 classic PID (equal zeros): Mp = 13.99% (MATLAB: 13.97%), but ts = 7.64s != 4s + // (MATLAB: 7.639s) due to slow real pole at s = -0.3685 destroying dominance. + let q2_pid = controllers::analyze(&json!({ + "action": "controller_design", + "plant_expr": "1/(s^2 + 1)", + "controller_type": "PID", + "pid_zeros_mode": "equal", + "mp": 16.3, + "xi": 0.5, + "ts": 4.0, + "ts_constraint": "equal", + "ts_tolerance": 0.1, + "require_zero_error": true, + "settling_criterion": "2", + "synthesis_mode": "lgr_classic", + "verify_requirements": true, + "dpi": 72 + })) + .unwrap(); + let v_pid = &q2_pid["details"]["verification"]; + assert_eq!(v_pid["requirements_passed"], false); + assert_eq!(v_pid["overall_status"], "FAIL"); + let pid_mp = v_pid["measured"]["overshoot_percent"].as_f64().unwrap(); + let pid_ts = v_pid["measured"]["settling_time"].as_f64().unwrap(); + assert!( + (pid_mp - 13.985).abs() < 0.05, + "unexpected Q2 PID Mp={pid_mp}" + ); + assert!( + (pid_ts - 7.639).abs() < 0.05, + "unexpected Q2 PID ts={pid_ts}" + ); + assert!( + v_pid["warnings"] + .as_array() + .unwrap() + .iter() + .any(|w| w.as_str().unwrap().contains("Dominância comprometida")) + ); + + // 3. Q7 classic PD: G(s) = 5/(s*(s+2)^2), xi=0.5 gives Mp = 16.303% > literal 16.0% and ts = 4.038s + let q7_pd = controllers::analyze(&json!({ + "action": "controller_design", + "plant_expr": "5/(s*(s + 2)^2)", + "controller_type": "PD", + "mp": 16.0, + "xi": 0.5, + "ts": 4.0, + "ts_constraint": "equal", + "ts_tolerance": 0.05, + "require_zero_error": true, + "settling_criterion": "2", + "synthesis_mode": "lgr_classic", + "verify_requirements": true, + "dpi": 72 + })) + .unwrap(); + let v7 = &q7_pd["details"]["verification"]; + assert_eq!(v7["requirements_passed"], false); + assert_eq!(v7["overall_status"], "FAIL"); + assert!( + v7["warnings"] + .as_array() + .unwrap() + .iter() + .any(|w| w.as_str().unwrap().contains("Incompatibilidade didática")) + ); + + // 4. Q8 classic PI: G(s) = -7.2/(5s+1), Kp=-1.25, Ki=-4.2608 -> Mp = 33.84% > 25% + let q8_pi = controllers::analyze(&json!({ + "action": "controller_design", + "plant_expr": "-7.2/(5*s + 1)", + "controller_type": "PI", + "mp": 25.0, + "ts": 4.0, + "ts_constraint": "at_most", + "require_zero_error": true, + "settling_criterion": "2", + "synthesis_mode": "lgr_classic", + "verify_requirements": true, + "dpi": 72 + })) + .unwrap(); + let v8 = &q8_pi["details"]["verification"]; + assert_eq!(v8["requirements_passed"], false); + assert_eq!(v8["overall_status"], "FAIL"); + assert!(v8["measured"]["overshoot_percent"].as_f64().unwrap() > 33.0); + + // 5. Q9 classic PD: G(s) = 1/s^2, Kp=4, Kd=2 -> Mp = 29.84% > 16% + let q9_pd = controllers::analyze(&json!({ + "action": "controller_design", + "plant_expr": "1/(s^2)", + "controller_type": "PD", + "mp": 16.0, + "xi": 0.5, + "ts": 4.0, + "ts_constraint": "at_most", + "require_zero_error": true, + "settling_criterion": "2", + "synthesis_mode": "lgr_classic", + "verify_requirements": true, + "dpi": 72 + })) + .unwrap(); + let v9 = &q9_pd["details"]["verification"]; + assert_eq!(v9["requirements_passed"], false); + assert_eq!(v9["overall_status"], "FAIL"); + assert!(v9["measured"]["overshoot_percent"].as_f64().unwrap() > 29.0); +} + +#[test] +fn unstable_systems_and_rhp_cancellations_are_never_classified_as_compliant() { + let specs = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(25.0), + settling_time: Some(SettlingSpec::AtMost(4.0)), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + + // 1. Positive gain on negative-gain plant G(s) = -7.2/(5s+1) -> unstable closed loop! + let plant_neg = TransferFunction::parse("-7.2/(5*s + 1)").unwrap(); + let bad_gc = TransferFunction::new(vec![1.0, 0.2], vec![1.0, 0.0]).unwrap(); + let rep_unstable = verify_controller(&plant_neg, None, &bad_gc, &specs).unwrap(); + assert!(!rep_unstable.closed_loop_stable); + assert!(!rep_unstable.requirements_passed); + assert_eq!(rep_unstable.overall_status, RequirementStatus::Fail); + + // 2. Unstable RHP pole-zero cancellation: G(s) = 1/(s - 1), Gc(s) = 5*(s - 1)/(s + 2) + // Unreduced characteristic polynomial has hidden unstable root at s = +1! + let plant_rhp = TransferFunction::parse("1/(s - 1)").unwrap(); + let cancel_rhp_gc = TransferFunction::parse("5*(s - 1)/(s + 2)").unwrap(); + let rep_cancel = verify_controller(&plant_rhp, None, &cancel_rhp_gc, &specs).unwrap(); + assert!(!rep_cancel.internally_stable); + assert!(!rep_cancel.requirements_passed); + assert_eq!(rep_cancel.overall_status, RequirementStatus::Fail); +} + +#[test] +fn validate_independent_q8_reference_solution_disturbance_and_robustness() { + // Section 4 Independent Reference Case: + // G(s) = -7.2 / (5s + 1) = -1.44 / (s + 0.2) + // Gc(s) = -1 - 0.2/s = -(s + 0.2) / s (Kp = -1.0, Ki = -0.2) + // Reduced closed-loop reference transfer function: T(s) = 1.44 / (s + 1.44) + let plant = TransferFunction::parse("-7.2/(5*s + 1)").unwrap(); + let gc_ref = TransferFunction::new(vec![-1.0, -0.2], vec![1.0, 0.0]).unwrap(); + let specs = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(25.0), + settling_time: Some(SettlingSpec::AtMost(4.0)), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + + let rep = verify_controller(&plant, None, &gc_ref, &specs).unwrap(); + assert!( + rep.closed_loop_stable, + "Nominal Q8 reference must be stable" + ); + assert!( + rep.internally_stable, + "Nominal Q8 reference cancels stable LHP pole -0.2, so internally stable" + ); + assert!( + rep.requirements_passed, + "Nominal Q8 reference must satisfy all Q8 specs: failed={:?}", + rep.failed_requirements + ); + assert!( + rep.measured_overshoot_pct.unwrap() <= 1e-6, + "Expected 0% overshoot, got {:?}", + rep.measured_overshoot_pct + ); + let exact_ts = 50.0_f64.ln() / 1.44; // 2.7166826529... s + assert!( + (rep.measured_settling_time_s.unwrap() - exact_ts).abs() <= 0.01, + "Expected ts(2%) ~ {exact_ts:.5}s, got {:?}", + rep.measured_settling_time_s + ); + assert!((rep.measured_steady_state_y.unwrap() - 1.0).abs() <= 1e-6); + assert!(rep.summer_steady_state_error.unwrap().abs() <= 1e-6); + // Must emit nominal pole-zero cancellation warning so sensitivity is transparent! + assert!( + rep.cancellations + .iter() + .any(|c| (c.pole.re + 0.2).abs() < 1e-5 && c.exact && !c.unstable) + ); + + // Cross-check in time_response module for reduced T(s) = 1.44 / (s + 1.44): + let tr = time_response::analyze(&json!({ + "expr": "1.44 / (s + 1.44)", + "settling_threshold": 0.02, + "points": 4000, + "dpi": 72 + })) + .unwrap(); + assert!(tr["details"]["step"]["overshoot_percent"].as_f64().unwrap() <= 1e-6); + assert!((tr["details"]["step"]["settling_time"].as_f64().unwrap() - exact_ts).abs() <= 0.02); + + // Disturbance rejection verification: + // T_d(s) = G(s) / (1 + Gc(s)G(s)) = (-1.44*s) / ((s + 0.2)*(s + 1.44)) + let td = plant.feedback(&gc_ref, -1.0).unwrap().normalized(); + assert!( + td.dc_gain().abs() <= 1e-12, + "Zero steady-state disturbance error" + ); + let t_dist: Vec = (0..=4000).map(|i| i as f64 * 0.01).collect(); + let y_dist = simulation::simulate(&td, &t_dist, Input::Step).unwrap(); + // Exact closed-form disturbance step response: + // L^-1{ -1.44 / ((s + 0.2)(s + 1.44)) } = (-1.44 / 1.24) * (e^(-0.2t) - e^(-1.44t)) + for (i, &t) in t_dist.iter().enumerate() { + let exact_wd = (-1.44 / 1.24) * ((-0.2 * t).exp() - (-1.44 * t).exp()); + assert!( + (y_dist[i] - exact_wd).abs() <= 1e-6, + "Q8 reference disturbance waveform mismatch at t={t}: {} != {exact_wd}", + y_dist[i] + ); + } + assert!(y_dist.last().unwrap().abs() <= 5e-4); + + // Robustness under +/-10% plant parameter perturbations (tau in {4.5, 5.5}, k in {-6.48, -7.92}): + // Verifies internal stability and non-fragility of the stable pole cancellation at s = -0.2. + for &(tau_p, k_p) in &[(4.5, -7.2), (5.5, -7.2), (5.0, -6.48), (5.0, -7.92)] { + let pert_plant = TransferFunction::new(vec![k_p], vec![tau_p, 1.0]).unwrap(); + let pert_rep = verify_controller(&pert_plant, None, &gc_ref, &specs).unwrap(); + assert!( + pert_rep.closed_loop_stable && pert_rep.internally_stable, + "Perturbed Q8 plant (tau={tau_p}, k={k_p}) must remain internally stable" + ); + assert!( + pert_rep.measured_overshoot_pct.unwrap() <= 1.0, + "Perturbed Q8 overshoot should stay near 0%, got {:?}", + pert_rep.measured_overshoot_pct + ); + assert!(pert_rep.summer_steady_state_error.unwrap().abs() <= 1e-6); + } +} + +#[test] +fn generic_constrained_synthesis_and_auto_simplest_resolve_q2_q5_q7_q8_q9() { + // 1. Q2: G(s) = 1/(s^2 + 1), Mp <= 16.3%, ts(2%) = 4s (+/- 0.1s) + let g2 = TransferFunction::parse("1/(s^2 + 1)").unwrap(); + let specs_q2 = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(16.3), + settling_time: Some(SettlingSpec::Equal { + target: 4.0, + tolerance: 0.1, + }), + settling_criterion_pct: 2, + require_zero_step_error: false, + ..Default::default() + }; + let out_q2_pd = + synthesize_for_structure(&g2, None, ControllerStructure::PD, &specs_q2).unwrap(); + assert!( + out_q2_pd.feasible, + "Q2 refined PD must satisfy Mp<=16.3% and ts=4s" + ); + let c2 = out_q2_pd.selected.unwrap(); + assert!(c2.verification.requirements_passed); + assert!(c2.verification.measured_overshoot_pct.unwrap() <= 16.3); + assert!((c2.verification.measured_settling_time_s.unwrap() - 4.0).abs() <= 0.1); + + // Q2 with e(inf) = 0 -> PID refined + let mut specs_q2_zero = specs_q2.clone(); + specs_q2_zero.require_zero_step_error = true; + let out_q2_pid = + synthesize_for_structure(&g2, None, ControllerStructure::PID, &specs_q2_zero).unwrap(); + assert!( + out_q2_pid.feasible, + "Q2 refined PID must satisfy Mp<=16.3%, ts=4s, ess=0" + ); + let c2_pid = out_q2_pid.selected.unwrap(); + assert!(c2_pid.verification.requirements_passed); + assert!(c2_pid.verification.summer_steady_state_error.unwrap().abs() <= 1e-5); + + // 2. Q5: G(s) = 1/(s^3 + 10s^2 + 17s + 8), literal ts(2%) = 1s (+/- 0.05s), Mp <= 25.38%, ess = 0 + let g5 = TransferFunction::parse("1/(s^3 + 10*s^2 + 17*s + 8)").unwrap(); + let specs_q5 = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(25.38), + settling_time: Some(SettlingSpec::Equal { + target: 1.0, + tolerance: 0.05, + }), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q5 = synthesize_for_structure(&g5, None, ControllerStructure::PID, &specs_q5).unwrap(); + assert!( + out_q5.feasible, + "Q5 refined PID must satisfy literal ts=1s, Mp<=25.38%, ess=0" + ); + let c5 = out_q5.selected.unwrap(); + assert!(c5.verification.requirements_passed); + assert!((c5.verification.measured_settling_time_s.unwrap() - 1.0).abs() <= 0.05); + + // 3. Q7: G(s) = 5/(s*(s+2)^2), literal Mp <= 16.0%, ts(2%) = 4s (+/- 0.05s), ess = 0 + let g7 = TransferFunction::parse("5/(s*(s + 2)^2)").unwrap(); + let specs_q7 = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(16.0), + settling_time: Some(SettlingSpec::Equal { + target: 4.0, + tolerance: 0.05, + }), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q7 = synthesize_for_structure(&g7, None, ControllerStructure::PD, &specs_q7).unwrap(); + assert!( + out_q7.feasible, + "Q7 refined PD must satisfy literal Mp<=16% and ts=4s" + ); + let c7 = out_q7.selected.unwrap(); + assert!(c7.verification.requirements_passed); + assert!(c7.verification.measured_overshoot_pct.unwrap() <= 16.0); + assert!((c7.verification.measured_settling_time_s.unwrap() - 4.0).abs() <= 0.05); + + // 4. Q8: G(s) = -7.2/(5s+1), Mp <= 25%, ts(2%) <= 4s, ess = 0 -> auto_simplest selects PI! + let g8 = TransferFunction::parse("-7.2/(5*s + 1)").unwrap(); + let specs_q8 = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(25.0), + settling_time: Some(SettlingSpec::AtMost(4.0)), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q8 = synthesize_simplest(&g8, None, &specs_q8).unwrap(); + assert!(out_q8.feasible); + assert!( + out_q8 + .infeasibility_reasons + .iter() + .any(|r| r.contains("Tipo 0")), + "P must be rejected algebraically on Type 0 plant" + ); + let c8 = out_q8.selected.unwrap(); + assert_eq!(c8.structure, ControllerStructure::PI); + assert!( + c8.kp < 0.0 && c8.ki < 0.0, + "Negative plant gain requires negative PI gains" + ); + assert!(c8.verification.requirements_passed); + assert!(c8.verification.measured_overshoot_pct.unwrap() <= 25.0); + assert!(c8.verification.measured_settling_time_s.unwrap() <= 4.0); + assert!(c8.verification.summer_steady_state_error.unwrap().abs() <= 1e-5); + + // 5. Q9: G(s) = 1/s^2, Mp <= 16%, ts(2%) <= 4s, ess = 0 -> auto_simplest selects PD! + let g9 = TransferFunction::parse("1/(s^2)").unwrap(); + let specs_q9 = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(16.0), + settling_time: Some(SettlingSpec::AtMost(4.0)), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q9 = synthesize_simplest(&g9, None, &specs_q9).unwrap(); + assert!(out_q9.feasible); + assert!( + out_q9 + .infeasibility_reasons + .iter() + .any(|r| r.contains("Tipo 2")), + "P and PI must be rejected algebraically on double integrator" + ); + let c9 = out_q9.selected.unwrap(); + assert_eq!(c9.structure, ControllerStructure::PD); + assert!(c9.verification.requirements_passed); + assert!(c9.verification.measured_overshoot_pct.unwrap() <= 16.0); + assert!(c9.verification.measured_settling_time_s.unwrap() <= 4.0); + assert!(c9.verification.summer_steady_state_error.unwrap().abs() <= 1e-5); +} + +#[test] +fn etapa11_damping_ratio_semantics_q5_exact_xi_and_proven_infeasibility() { + // 0. Uniform settling-time equality tolerance consistency (+/- 2%, floor 0.02 s) + assert!((default_settling_tolerance(1.0) - 0.02).abs() < 1e-12); + assert!((default_settling_tolerance(4.0) - 0.08).abs() < 1e-12); + + // 1. Verify that Etapa 10's Q5 PID (xi = 0.6669) is REJECTED when mandatory xi = 0.4 +/- 0.01 is enforced! + let g5 = TransferFunction::parse("1/(s^3 + 10*s^2 + 17*s + 8)").unwrap(); + let gc5_e10 = TransferFunction::new( + vec![35.985636144021534, 71.88638085895549, 35.900742386408645], + vec![1.0, 0.0], + ) + .unwrap(); + let q5_strict_specs = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + damping: Some(DampingSpec::Equal { + target: 0.4, + tolerance: 0.01, + }), + settling_time: Some(SettlingSpec::Equal { + target: 1.0, + tolerance: default_settling_tolerance(1.0), + }), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let rep_e10 = verify_controller(&g5, None, &gc5_e10, &q5_strict_specs).unwrap(); + assert!(!rep_e10.requirements_passed); + assert_eq!(rep_e10.overall_status, RequirementStatus::Fail); + assert!( + (rep_e10.measured_xi.unwrap() - 0.666854).abs() < 1e-3, + "Etapa 10 Q5 PID had xi = 0.666854, got {:?}", + rep_e10.measured_xi + ); + + // 2. Q5 PID synthesized with mandatory exact xi = 0.4 +/- 0.01 AND ts(2%) = 1.0 +/- 0.02 s AND ess = 0! + let out_q5 = + synthesize_for_structure(&g5, None, ControllerStructure::PID, &q5_strict_specs).unwrap(); + assert!( + out_q5.feasible, + "Generic PID synthesis must find Q5 solution with exact xi=0.4 and ts=1.0s" + ); + assert_eq!(out_q5.feasibility_class, FeasibilityClass::Feasible); + let c5 = out_q5.selected.unwrap(); + assert!(c5.verification.requirements_passed); + assert!(c5.verification.internally_stable); + assert!(c5.verification.has_complex_pair); + assert!( + (c5.verification.measured_xi.unwrap() - 0.4).abs() <= 0.01, + "Q5 exact xi violated: {:?}", + c5.verification.measured_xi + ); + assert!( + (c5.verification.measured_settling_time_s.unwrap() - 1.0).abs() <= 0.02, + "Q5 exact ts violated: {:?}", + c5.verification.measured_settling_time_s + ); + assert!(c5.verification.summer_steady_state_error.unwrap().abs() <= 1e-5); + assert!( + c5.verification.non_dominant_residue_ratio.unwrap() < 0.25, + "Q5 dominant complex pair must carry >80% of transient modal residue" + ); + + // 3. Q2 PID with mandatory exact xi = 0.5 +/- 0.01, Mp <= 16.3%, ts = 4.0 +/- 0.08 s, ess = 0! + let g2 = TransferFunction::parse("1/(s^2 + 1)").unwrap(); + let q2_pid_exact = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(16.3), + damping: Some(DampingSpec::Equal { + target: 0.5, + tolerance: 0.01, + }), + settling_time: Some(SettlingSpec::Equal { + target: 4.0, + tolerance: default_settling_tolerance(4.0), + }), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q2_pid = + synthesize_for_structure(&g2, None, ControllerStructure::PID, &q2_pid_exact).unwrap(); + assert!( + out_q2_pid.feasible, + "Generic PID synthesis must find Q2 PID solution with exact xi=0.5, Mp<=16.3%, ts=4s, ess=0" + ); + let c2_pid = out_q2_pid.selected.unwrap(); + assert!(c2_pid.verification.requirements_passed); + assert!(c2_pid.verification.complex_pair_is_dominant); + assert!((c2_pid.verification.measured_xi.unwrap() - 0.5).abs() <= 0.01); + assert!(c2_pid.verification.measured_overshoot_pct.unwrap() <= 16.3); + assert!((c2_pid.verification.measured_settling_time_s.unwrap() - 4.0).abs() <= 0.08); + + // 4. Q2 PD and Q9 PD with mandatory exact xi = 0.5 +/- 0.01 + Mp <= 16.3% / 16.0%: + // MUST be classified as mathematically ProvenInfeasible (time-scale invariance proof)! + let q2_pd_exact = DesignSpecs { + require_zero_step_error: false, + ..q2_pid_exact.clone() + }; + let out_q2_pd = + synthesize_for_structure(&g2, None, ControllerStructure::PD, &q2_pd_exact).unwrap(); + assert!(!out_q2_pd.feasible); + assert_eq!( + out_q2_pd.feasibility_class, + FeasibilityClass::ProvenInfeasible + ); + assert!( + out_q2_pd + .infeasibility_reasons + .iter() + .any(|r| r.contains("y(∞) = α = 1 -")), + "Q2 PD proof must explicitly account for steady-state gain y(inf) = 1 - c/wn^2" + ); + + let g9 = TransferFunction::parse("1/(s^2)").unwrap(); + let q9_pd_exact = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(16.0), + damping: Some(DampingSpec::Equal { + target: 0.5, + tolerance: 0.01, + }), + settling_time: Some(SettlingSpec::AtMost(4.0)), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q9_pd = + synthesize_for_structure(&g9, None, ControllerStructure::PD, &q9_pd_exact).unwrap(); + assert!(!out_q9_pd.feasible); + assert_eq!( + out_q9_pd.feasibility_class, + FeasibilityClass::ProvenInfeasible + ); + assert!( + out_q9_pd + .infeasibility_reasons + .iter() + .any(|r| r.contains("duplo integrador")), + "Q9 PD proof must explicitly apply to the double integrator 1/s^2" + ); + + // 5. Q7 PD with mandatory xi = 0.50 +/- 0.01, Mp <= 16.0%, ts = 4.0 +/- 0.08 s, dominant complex pair + let g7 = TransferFunction::parse("5/(s*(s + 2)^2)").unwrap(); + let q7_pd_exact = DesignSpecs { + objective: DesignObjective::TimeDomainConstraints, + max_overshoot_pct: Some(16.0), + damping: Some(DampingSpec::Equal { + target: 0.5, + tolerance: 0.01, + }), + require_complex_dominance: true, + settling_time: Some(SettlingSpec::Equal { + target: 4.0, + tolerance: default_settling_tolerance(4.0), + }), + settling_criterion_pct: 2, + require_zero_step_error: true, + ..Default::default() + }; + let out_q7_pd = + synthesize_for_structure(&g7, None, ControllerStructure::PD, &q7_pd_exact).unwrap(); + assert!(out_q7_pd.feasible); + let c7 = out_q7_pd.selected.unwrap(); + assert!(c7.verification.requirements_passed); + assert!(c7.verification.complex_pair_is_dominant); + assert!((c7.verification.measured_xi.unwrap() - 0.5).abs() <= 0.01); + assert!(c7.verification.measured_overshoot_pct.unwrap() <= 16.0); + assert!((c7.verification.measured_settling_time_s.unwrap() - 4.0).abs() <= 0.08); + + // 6. Tightening Q7 PD tolerance to exact xi = 0.500 +/- 0.001 with dominance must NOT falsely pass + // and must classify as NotFoundWithinSearchBounds (never claiming proof without algebraic theorem). + let q7_pd_ultra_tight = DesignSpecs { + damping: Some(DampingSpec::Equal { + target: 0.5, + tolerance: 0.001, + }), + ..q7_pd_exact + }; + let out_q7_tight = + synthesize_for_structure(&g7, None, ControllerStructure::PD, &q7_pd_ultra_tight).unwrap(); + assert!(!out_q7_tight.feasible); + assert_eq!( + out_q7_tight.feasibility_class, + FeasibilityClass::NotFoundWithinSearchBounds + ); +} diff --git a/crates/control-engine/tests/controllers.rs b/crates/control-engine/tests/controllers.rs index 437c8a3..e51bf3a 100644 --- a/crates/control-engine/tests/controllers.rs +++ b/crates/control-engine/tests/controllers.rs @@ -55,7 +55,8 @@ fn pid_design_question_5_cancellation_and_equal_zeros() { "ts": 1.0, "xi": 0.4, "settling_criterion": "2" - })).unwrap(); + })) + .unwrap(); let p_cancel = &r_cancel["details"]["controller_parameters"]; assert!((p_cancel["kp"].as_f64().unwrap() - 200.0).abs() < 1e-3); assert!((p_cancel["ki"].as_f64().unwrap() - 100.0).abs() < 1e-3); @@ -72,7 +73,8 @@ fn pid_design_question_5_cancellation_and_equal_zeros() { "ts": 1.0, "xi": 0.4, "settling_criterion": "2" - })).unwrap(); + })) + .unwrap(); let p_equal = &r_equal["details"]["controller_parameters"]; assert!((p_equal["kp"].as_f64().unwrap() - 200.0).abs() < 1e-3); assert!((p_equal["ki"].as_f64().unwrap() - 100.0).abs() < 1e-3); @@ -93,7 +95,8 @@ fn pid_design_question_2_cancellation_and_equal_zeros() { "wn": 6.57, "xi": 0.7, "settling_criterion": "2" - })).unwrap(); + })) + .unwrap(); let p_cancel = &r_cancel["details"]["controller_parameters"]; assert!((p_cancel["kp"].as_f64().unwrap() - (-5.215)).abs() < 1e-2); assert!((p_cancel["ki"].as_f64().unwrap() - (-9.652)).abs() < 1e-2); @@ -110,7 +113,8 @@ fn pid_design_question_2_cancellation_and_equal_zeros() { "wn": 6.57, "xi": 0.7, "settling_criterion": "2" - })).unwrap(); + })) + .unwrap(); let p_equal = &r_equal["details"]["controller_parameters"]; assert!((p_equal["kp"].as_f64().unwrap() - (-5.335)).abs() < 1e-2); assert!((p_equal["ki"].as_f64().unwrap() - (-10.22)).abs() < 1e-2); diff --git a/crates/mscript/tests/academic_validation.rs b/crates/mscript/tests/academic_validation.rs new file mode 100644 index 0000000..53727ea --- /dev/null +++ b/crates/mscript/tests/academic_validation.rs @@ -0,0 +1,302 @@ +//! Cross-module validation of UFERSA Control Systems II academic lists +//! (`Exercicios_-_LGR.pdf` and `Projeto_de_controladores.pdf`) executed inside +//! ControLAB's `.m` script interpreter (`mscript::Session`), verifying consistency +//! with closed-form analytical solutions and MATLAB R2022b references. + +use mscript::{Session, Value}; + +fn assert_vec_near(actual: &[f64], expected: &[f64], tol: f64, ctx: &str) { + assert_eq!(actual.len(), expected.len(), "{ctx}: length mismatch"); + for (a, e) in actual.iter().zip(expected) { + assert!((a - e).abs() <= tol * e.abs().max(1.0), "{ctx}: {a} != {e}"); + } +} + +fn get_scalar(session: &Session, name: &str) -> f64 { + let Some(Value::Numeric(m)) = session.get(name) else { + panic!("expected scalar variable '{name}' in workspace"); + }; + assert_eq!((m.rows(), m.cols()), (1, 1), "{name} is not 1x1"); + m.data()[0] +} + +fn get_tf(session: &Session, name: &str) -> (Vec, Vec) { + let Some(Value::TransferFunction(tf)) = session.get(name) else { + panic!("expected transfer function '{name}' in workspace"); + }; + (tf.numerator().to_vec(), tf.denominator().to_vec()) +} + +fn get_vector(session: &Session, name: &str) -> Vec { + let Some(Value::Numeric(m)) = session.get(name) else { + panic!("expected numeric vector '{name}' in workspace"); + }; + m.data().to_vec() +} + +#[test] +fn validate_all_9_controller_questions_in_mscript_studio_interpreter() { + let mut session = Session::new(); + let script = r#" + s = tf('s'); + + % Q1: Reconstructed plant G1 = 1/((s+0.2)*(s+0.644)), PI controller + G1 = 1 / ((s + 0.2) * (s + 0.644)); + Gc1 = pid(0.49849281561599984, 0.09975099980799994, 0); + T1 = feedback(Gc1 * G1, 1); + dc1 = dcgain(T1); + + % Q2: Reconstructed plant G2 = 1/(s^2+1), PD controller Kp=3, Kd=2 + G2 = 1 / (s^2 + 1); + Gc2 = pid(3, 0, 2); + T2 = feedback(Gc2 * G2, 1); + dc2 = dcgain(T2); + + % Q3: Servo system with inner velocity feedback 0.5 and outer unity feedback + G3_in = feedback(18 / ((2*s + 11) * (2*s + 1)), 0.5); + G3 = G3_in * (1 / (30 * s)); + Gc3 = pid(160/3, 0, 100/3); + T3 = feedback(Gc3 * G3, 1); + dc3 = dcgain(T3); + + % Q4: Non-unity feedback H4 = 0.05, G4 = 5/(s+0.1), PI controller Kp=7.6, Ki=16 + G4 = 5 / (s + 0.1); + H4 = tf(0.05, 1); + Gc4 = pid(7.6, 16.0, 0); + T4_yr = feedback(Gc4 * G4, H4); + T4_ear = feedback(tf(1, 1), Gc4 * G4 * H4); + dc4_y = dcgain(T4_yr); + dc4_ea = dcgain(T4_ear); + + % Q5: 3rd-order plant 1/(s^3+10s^2+17s+8), PID controller (Kp=200, Ki=100, Kd=100) + G5 = 1 / (s^3 + 10*s^2 + 17*s + 8); + Gc5 = pid(200, 100, 100); + T5 = feedback(Gc5 * G5, 1); + dc5 = dcgain(T5); + + % Q6: 3rd-order plant 1/(s*(s+2)^2), PD controller Kp=8, Kd=4 + G6 = 1 / (s * (s + 2)^2); + Gc6 = pid(8, 0, 4); + T6 = feedback(Gc6 * G6, 1); + dc6 = dcgain(T6); + t6 = linspace(0, 10, 1001); + y6 = step(T6, t6); + + % Q7: Two-loop cascade system: inner 1/s with feedback 2, outer 5/(s*(s+2)), PD Kp=1.6, Kd=0.8 + G7_in = feedback(1 / s, 2); + G7 = (5 / (s * (s + 2))) * G7_in; + Gc7 = pid(1.6, 0, 0.8); + T7 = feedback(Gc7 * G7, 1); + dc7 = dcgain(T7); + y7 = step(T7, t6); + + % Q8: Wind turbine G8 = -7.2/(5s+1), PI controller Kp=-1.25, Ki=-4.260813967920802 + G8 = -7.2 / (5*s + 1); + Gc8 = pid(-1.25, -4.260813967920802, 0); + T8_ref = feedback(Gc8 * G8, 1); + T8_dist = feedback(G8, Gc8); + dc8_ref = dcgain(T8_ref); + dc8_dist = dcgain(T8_dist); + y8_ref = step(T8_ref, t6); + y8_dist = step(T8_dist, t6); + + % Q9: Second-order diagram with wn=1, xi=0 -> G9 = 1/s^2, PD controller Kp=4, Kd=2 + G9 = 1 / (s^2); + Gc9 = pid(4, 0, 2); + T9 = feedback(Gc9 * G9, 1); + dc9 = dcgain(T9); + y9 = step(T9, t6); + "#; + + let outcome = session.execute(script).unwrap(); + assert!(outcome.plots.is_empty()); + + // Verify transfer function coefficients and DC gains across Q1..Q9: + assert!((get_scalar(&session, "dc1") - 1.0).abs() <= 1e-12); + assert!((get_scalar(&session, "dc2") - 0.75).abs() <= 1e-12); + assert!((get_scalar(&session, "dc3") - 1.0).abs() <= 1e-12); + assert!((get_scalar(&session, "dc4_y") - 20.0).abs() <= 1e-12); + assert!(get_scalar(&session, "dc4_ea").abs() <= 1e-12); + assert!((get_scalar(&session, "dc5") - 1.0).abs() <= 1e-12); + assert!((get_scalar(&session, "dc6") - 1.0).abs() <= 1e-12); + assert!((get_scalar(&session, "dc7") - 1.0).abs() <= 1e-12); + assert!((get_scalar(&session, "dc8_ref") - 1.0).abs() <= 1e-12); + assert!(get_scalar(&session, "dc8_dist").abs() <= 1e-12); + assert!((get_scalar(&session, "dc9") - 1.0).abs() <= 1e-12); + + let (t2_num, t2_den) = get_tf(&session, "T2"); + assert_vec_near(&t2_num, &[2.0, 3.0], 1e-12, "Q2 T2 num"); + assert_vec_near(&t2_den, &[1.0, 2.0, 4.0], 1e-12, "Q2 T2 den"); + + let (t3_num, t3_den) = get_tf(&session, "T3"); + assert_vec_near(&t3_num, &[5.0, 8.0], 1e-12, "Q3 T3 num"); + assert_vec_near(&t3_den, &[1.0, 6.0, 10.0, 8.0], 1e-12, "Q3 T3 den"); + + let (t4_num, t4_den) = get_tf(&session, "T4_yr"); + assert_vec_near(&t4_num, &[38.0, 80.0], 1e-12, "Q4 T4_yr num"); + assert_vec_near(&t4_den, &[1.0, 2.0, 4.0], 1e-12, "Q4 T4_yr den"); + + let (t5_num, t5_den) = get_tf(&session, "T5"); + assert_vec_near(&t5_num, &[100.0, 200.0, 100.0], 1e-12, "Q5 T5 num"); + assert_vec_near( + &t5_den, + &[1.0, 10.0, 117.0, 208.0, 100.0], + 1e-12, + "Q5 T5 den", + ); + + let (t6_num, t6_den) = get_tf(&session, "T6"); + let (t7_num, t7_den) = get_tf(&session, "T7"); + assert_vec_near(&t6_num, &[4.0, 8.0], 1e-12, "Q6 T6 num"); + assert_vec_near(&t6_den, &[1.0, 4.0, 8.0, 8.0], 1e-12, "Q6 T6 den"); + assert_vec_near(&t7_num, &t6_num, 1e-12, "Q7 == Q6 num"); + assert_vec_near(&t7_den, &t6_den, 1e-12, "Q7 == Q6 den"); + + // Verify step response waveforms for Q6, Q7, Q8 (ref & dist), and Q9: + let y6 = get_vector(&session, "y6"); + let y7 = get_vector(&session, "y7"); + assert_vec_near( + &y6, + &y7, + 1e-13, + "Q6 and Q7 step waveforms must be identical", + ); + let sqrt3 = 3.0_f64.sqrt(); + for (i, &actual) in y6.iter().enumerate() { + let t = (i as f64) * 0.01; + let exact = 1.0 - (-t).exp() * ((sqrt3 * t).cos() + (sqrt3 * t).sin() / sqrt3); + assert!( + (actual - exact).abs() <= 1e-10, + "mscript Q6 step response at t={t}: {actual} != {exact}" + ); + } + + let y8_dist = get_vector(&session, "y8_dist"); + let wd8 = 2.266180070913597_f64; + for (i, &actual) in y8_dist.iter().enumerate() { + let t = (i as f64) * 0.01; + let exact = (-1.44 / wd8) * (-t).exp() * (wd8 * t).sin(); + assert!( + (actual - exact).abs() <= 1e-10, + "mscript Q8 disturbance response at t={t}: {actual} != {exact}" + ); + } +} + +#[test] +fn validate_lgr_closed_loop_models_at_critical_and_breakaway_gains_in_mscript() { + let mut session = Session::new(); + let script = r#" + s = tf('s'); + + % Eq.(1) & Eq.(7): G(s) = 1/(s*(s^2+6s+25)), K_crit = 150 -> sustained oscillation at w = 5 rad/s + G_eq1 = 1 / (s * (s^2 + 6*s + 25)); + T_eq1_crit = feedback(150 * G_eq1, 1); + + % Eq.(3), Eq.(12), Eq.(14): G(s) = 1/(s*(s^2+4s+5)), breakaway K = 2 at s = -1 + G_eq3 = 1 / (s * (s^2 + 4*s + 5)); + T_eq3_break = feedback(2 * G_eq3, 1); + + % Eq.(15): G(s) = 1/(s*(s^2+4s+13)), H(s) = 1/(s+1), K_crit = 37.44 + G_eq15 = 1 / (s * (s^2 + 4*s + 13)); + H_eq15 = 1 / (s + 1); + T_eq15_crit = feedback(37.44 * G_eq15, H_eq15); + + % Eq.(16): G(s) = 1/(s+3.6), H(s) = (s+1)/s^2 + G_eq16 = 1 / (s + 3.6); + H_eq16 = (s + 1) / (s^2); + T_eq16 = feedback(10 * G_eq16, H_eq16); + dc_eq16 = dcgain(T_eq16); + "#; + session.execute(script).unwrap(); + + // Eq.(1) at K = 150: denominator s^3 + 6s^2 + 25s + 150 = (s + 6)(s^2 + 25) + let (_, den1) = get_tf(&session, "T_eq1_crit"); + assert_vec_near(&den1, &[1.0, 6.0, 25.0, 150.0], 1e-12, "Eq.1 K_crit den"); + + // Eq.(3) at K = 2: denominator s^3 + 4s^2 + 5s + 2 = (s + 1)^2 * (s + 2) + let (_, den3) = get_tf(&session, "T_eq3_break"); + assert_vec_near(&den3, &[1.0, 4.0, 5.0, 2.0], 1e-12, "Eq.3 breakaway den"); + + // Eq.(15) at K = 37.44: denominator s^4 + 5s^3 + 17s^2 + 13s + 37.44 + let (num15, den15) = get_tf(&session, "T_eq15_crit"); + assert_vec_near(&num15, &[37.44, 37.44], 1e-12, "Eq.15 num"); + assert_vec_near( + &den15, + &[1.0, 5.0, 17.0, 13.0, 37.44], + 1e-12, + "Eq.15 K_crit den", + ); + + // Eq.(16) at K = 10: T(s) = 10*s^2 / (s^3 + 3.6*s^2 + 10*s + 10) -> dcgain = 0 + let (num16, den16) = get_tf(&session, "T_eq16"); + assert_vec_near(&num16, &[10.0, 0.0, 0.0], 1e-12, "Eq.16 num"); + assert_vec_near(&den16, &[1.0, 3.6, 10.0, 10.0], 1e-12, "Eq.16 den"); + assert!(get_scalar(&session, "dc_eq16").abs() <= 1e-12); +} + +#[test] +fn validate_q8_independent_reference_in_mscript() { + // Etapa 10 Section 4 — Independent Q8 reference in Studio .m: + // G(s) = -7.2/(5s+1), Gc(s) = -1 - 0.2/s => T(s) = 1.44/(s+1.44) + // Analytic step response: y(t) = 1 - exp(-1.44*t), Mp = 0%, ts(2%) = ln(50)/1.44 = 2.7166826... s + let mut session = Session::new(); + let script = r#" + s = tf('s'); + G8 = -7.2 / (5*s + 1); + Gc8_ref = pid(-1, -0.2, 0); + T8_ref = feedback(Gc8_ref * G8, 1); + T8_dist = feedback(G8, Gc8_ref); + dc_ref = dcgain(T8_ref); + dc_dist = dcgain(T8_dist); + t = 0:0.01:8; + y_ref = step(T8_ref, t); + y_dist = step(T8_dist, t); + "#; + session.execute(script).unwrap(); + + assert!((get_scalar(&session, "dc_ref") - 1.0).abs() <= 1e-12); + assert!(get_scalar(&session, "dc_dist").abs() <= 1e-12); + + let y_ref = get_vector(&session, "y_ref"); + let mut peak = 0.0_f64; + for (i, &actual) in y_ref.iter().enumerate() { + let t = (i as f64) * 0.01; + let exact = 1.0 - (-1.44 * t).exp(); + assert!( + (actual - exact).abs() <= 1e-10, + "mscript Q8 reference step at t={t}: {actual} != {exact}" + ); + peak = peak.max(actual); + } + assert!( + peak <= 1.0 + 1e-9, + "Q8 reference must have 0% overshoot (peak={peak})" + ); + + // Verify 2% settling time directly from simulated samples: + let mut last_out = 0usize; + for (i, &y) in y_ref.iter().enumerate() { + if (y - 1.0).abs() > 0.02 { + last_out = i; + } + } + let ts_approx = (last_out as f64) * 0.01; + let exact_ts = 50.0_f64.ln() / 1.44; + assert!( + (ts_approx - exact_ts).abs() <= 0.02, + "Q8 reference ts(2%) {ts_approx}s != {exact_ts}s" + ); + + // Verify constant load disturbance rejection in time domain: + // T_d(s) = -1.44*s / ((s+0.2)(s+1.44)), step response = (-1.44/1.24)*(e^(-0.2t) - e^(-1.44t)) + let y_dist = get_vector(&session, "y_dist"); + for (i, &actual) in y_dist.iter().enumerate() { + let t = (i as f64) * 0.01; + let exact_d = (-1.44 / 1.24) * ((-0.2 * t).exp() - (-1.44 * t).exp()); + assert!( + (actual - exact_d).abs() <= 1e-10, + "mscript Q8 reference disturbance at t={t}: {actual} != {exact_d}" + ); + } +} diff --git a/docs/validation/README.md b/docs/validation/README.md new file mode 100644 index 0000000..6b6f52d --- /dev/null +++ b/docs/validation/README.md @@ -0,0 +1,55 @@ +# Validação Científica e Numérica do ControLAB + +Este diretório reúne a documentação pública de validação científica, numérica, funcional, visual e de desempenho do motor computacional nativo em Rust do **ControLAB**. + +A validação cobre o escopo específico dos módulos de controle linear contínuo SISO, diagramas de blocos e interpretador `.m` avaliados frente a: +- Derivações analíticas fechadas. +- Execuções independentes em **MATLAB R2022b** (`9.13.0.2049777`, Control System Toolbox) para os casos testados. +- Referências congeladas do motor Python legado (`be79347`, 152 casos de paridade). +- Problemas acadêmicos de Sistemas de Controle II (UFERSA — 19 casos de Lugar Geométrico das Raízes e 9 questões de Projeto de Controladores). + +> **Escopo das afirmações:** Os resultados documentados aplicam-se exclusivamente às funcionalidades, modelos e casos efetivamente validados nesta suíte. Não se declara equivalência universal com todo o ecossistema MATLAB/Simulink. + +--- + +## Navegação + +| Documento | Conteúdo | +|---|---| +| [`methodology.md`](methodology.md) | Classificação nas 4 categorias independentes, semântica explícita de especificações ($\xi$, $\omega_n$, $t_s$, $M_p$, $e_{ss}$), estabilidade interna e tolerâncias numéricas | +| [`academic-validation.md`](academic-validation.md) | Resultados consolidados dos 19 casos de LGR e das 9 questões de Projeto de Controladores, incluindo a referência independente da Q8 e análises de robustez | +| [`synthesis-comparison.md`](synthesis-comparison.md) | Comparação entre síntese clássica via LGR (`lgr_classic`) e síntese por restrições (`temporal_refined` / `auto_simplest`), provas de inviabilidade matemática e evidências visuais | +| [`benchmarks.md`](benchmarks.md) | Metodologia, ambiente e resultados de desempenho Rust (`--release`) vs motor Python legado (`be79347`) | +| [`final-acceptance.md`](final-acceptance.md) | Síntese de aceitação, cobertura real dos testes, limitações matemáticas conhecidas e análise de riscos | +| [`validation-matrix.csv`](validation-matrix.csv) | Matriz completa das 42 configurações auditadas com status separado nas 4 categorias | +| [`references/`](references/README.md) | Scripts independentes de geração em MATLAB R2022b (`.m`), saídas JSON de referência e resultados consolidados dos benchmarks (`benchmark-results.json`) | + +--- + +## Como Reproduzir a Validação + +Toda a suíte permanente de validação em Rust é autossuficiente e **não requer Python nem MATLAB** em tempo de execução: + +```bash +# 1. Formatação e análise estática +cargo fmt --all -- --check +cargo clippy --workspace --all-targets -- -D warnings + +# 2. Suíte completa do workspace (inclui validação acadêmica, BlockLab, mscript e GUI) +cargo test --workspace + +# 3. Suítes acadêmicas e de conformidade específicas +cargo test -p controlab-engine --test academic_lgr_validation +cargo test -p controlab-engine --test academic_controllers_validation +cargo test -p controlab-engine --test academic_requirements_compliance +cargo test -p blocklab-core --test academic_diagrams +cargo test -p mscript --test academic_validation + +# 4. Compilação release, paridade congelada (152 casos) e auditoria de fontes +cargo build --workspace --release +cargo run --release -p xtask -- parity +cargo run --release -p xtask -- check-sources + +# 5. (Opcional — requer MATLAB local com Control System Toolbox) +cargo test --release -p mscript -- --ignored +``` diff --git a/docs/validation/academic-validation.md b/docs/validation/academic-validation.md new file mode 100644 index 0000000..82531b5 --- /dev/null +++ b/docs/validation/academic-validation.md @@ -0,0 +1,78 @@ +# Validação Acadêmica — LGR e Projeto de Controladores (UFERSA) + +Esta validação reproduz integralmente as duas listas acadêmicas da disciplina de **Sistemas de Controle II (PEX0257)** da UFERSA nos módulos `controlab-engine`, `blocklab-core`, `mscript` e `controlab-native`, comparando os resultados com derivações analíticas fechadas e execuções independentes no **MATLAB R2022b**. + +--- + +## 1. Lugar Geométrico das Raízes (`Exercicios_-_LGR.pdf` — 19 casos) + +Foram validados todos os **19 casos** (Equações 1 a 18 das Questões 1 a 4 + Equação 19 paramétrica da Questão 5 com $a_2 = 0$), preservando integralmente a duplicidade de rótulo `2(i)-1` (Eq. 12) / `2(i)-2` (Eq. 13) e todos os casos matematicamente equivalentes (`1(a) = 2(d)`, `1(b) = 2(c)`, `1(c) = 2(i)-1 = 3(a)`). + +| ID | Item / Eq. | $G(s)H(s)$ | Polos ($K=0$) | Zeros | Centroide / Assíntotas | Pontos de Quebra | Cruzamento $j\omega$ / $K_{\text{crit}}$ | Estabilidade ($K>0$) | Status (4 cat.) | +|---|---|---|---|---|---|---|---|---|---| +| `LGR_Q1A_EQ01` | 1(a) / (1) | $\frac{k}{s(s^2+6s+25)}$ | $0, -3\pm 4j$ | — | $-2$; $60^\circ,180^\circ,300^\circ$ | Nenhum real | $\pm 5j$ ($K=150$) | $00$ | **PASS** | +| `LGR_Q1C_EQ03` | 1(c) / (3) | $\frac{k}{s(s^2+4s+5)}$ | $0, -2\pm j$ | — | $-4/3$; $60^\circ,180^\circ,300^\circ$ | $-5/3$ ($K=50/27$), $-1$ ($K=2$) | $\pm\sqrt{5}j$ ($K=20$) | $00$ | **PASS** | +| `LGR_Q2B_EQ05` | 2(b) / (5) | $\frac{k}{s(s+1)(s+2)}$ | $0, -1, -2$ | — | $-1$; $60^\circ,180^\circ,300^\circ$ | $-0{,}4226$ ($K=0{,}3849$) | $\pm\sqrt{2}j$ ($K=6$) | $00$ | **PASS** | +| `LGR_Q2D_EQ07` | 2(d) / (7) | $\frac{k}{s(s^2+6s+25)}$ | $0, -3\pm 4j$ | — | $-2$; $60^\circ,180^\circ,300^\circ$ | Nenhum real | $\pm 5j$ ($K=150$) | $00$ | **PASS** | +| `LGR_Q2F_EQ09` | 2(f) / (9) | $\frac{k(s^2+2s+8)}{s(s+10)(s+5)}$ | $0, -5, -10$ | $-1\pm\sqrt{7}j$ | $-13$; $180^\circ$ | $-1{,}6679$ ($K=6{,}2189$) | Nenhum | $K>0$ | **PASS** | +| `LGR_Q2G_EQ10` | 2(g) / (10) | $\frac{k(s^2+4)}{(s+2)^2(s+5)(s+6)}$ | $-2$ (2×), $-5, -6$ | $\pm 2j$ | $-7{,}5$; $90^\circ,270^\circ$ | $-5{,}5307$ ($K=0{,}0898$), $-2$ ($K=0$) | $\to\pm 2j$ ($K\to\infty$) | $K>0$ | **PASS** | +| `LGR_Q2H_EQ11` | 2(h) / (11) | $\frac{k}{(s+1)(s^2+4s+5)}$ | $-1, -2\pm j$ | — | $-5/3$; $60^\circ,180^\circ,300^\circ$ | Nenhum real | $\pm 3j$ ($K=40$) | $00$ | **PASS** | +| `LGR_Q3A_EQ14` | 3(a) / (14) | $\frac{k}{s(s^2+4s+5)}$ ($H=1$) | $0, -2\pm j$ | — | $-4/3$; $60^\circ,180^\circ,300^\circ$ | $-5/3$, $-1$ | $\pm\sqrt{5}j$ ($K=20$) | $00$) | $K>0$ | **PASS** | +| `LGR_Q4A_EQ17` | 4(a) / (17) | $\frac{k(s+2)}{s^2+4s+13}$ | $-2\pm 3j$ | $-2$ | $-2$; $180^\circ$ | $-5$ ($K=6$) | Nenhum | $K>0$ | **PASS** | +| `LGR_Q4B_EQ18` | 4(b) / (18) | $\frac{k(s-2)(s-4)}{s^2+6s+25}$ | $-3\pm 4j$ | $+2, +4$ | Grau relativo 0 | $2{,}8853$ ($K=51{,}3118$) | $\pm\sqrt{16{,}5}j$ ($K=1$) | $00$) | Instável $\forall a_1>0$ | **PASS** | + +- **Verificação da equação característica $D(s)+KN(s)=0$:** validada em 190.019 conjuntos de raízes com resíduo normalizado $\le 2{,}13\times 10^{-14}$ (raízes simples) e $\le 3{,}14\times 10^{-8}$ (raízes múltiplas), preservando simetria conjugada em 100% dos ganhos. +- **Reduções via Mason (`blocklab-core`):** Eqs. 14, 15 e 16 reduzidas simbolicamente de forma exata em `crates/blocklab-core/tests/academic_diagrams.rs`. + +--- + +## 2. Projeto de Controladores (`Projeto_de_controladores.pdf` — 9 questões) + +### 2.1 Auditoria da Síntese Clássica por LGR (`lgr_classic`) + +Todos os casos clássicos atingem `NUMERICAL_PASS` frente ao MATLAB R2022b, porém apenas os casos que satisfazem integralmente as restrições reais do enunciado recebem `REQUIREMENTS_PASS`: + +| Questão | Planta | Controlador Clássico | $M_p$ real (Rust / MATLAB) | $t_s(2\%)$ real (Rust / MATLAB) | $e_a(\infty)$ | `NUM` | `REQ` | `OVERALL` | Observação crítica | +|---|---|---|---:|---:|---:|---|---|---|---| +| **Q1** | $\frac{1}{(s+0{,}2)(s+0{,}644)}$ | PI ($K_p=0{,}4985, K_i=0{,}0998$) | `20.00%` / `20.00%` | `11.80 s` / `11.79 s` | `0` | PASS | PASS* | **PASS*** | Quase-cancelamento do 3º polo ($-0{,}200128$) pelo zero ($-0{,}200105$). Ganho DC gráfico unitário apenas reescala $K_p, K_i$ por $1/0{,}1288$. | +| **Q2** | $\frac{1}{s^2+1}$ | PD ($K_p=3, K_d=2$) | `41.26%` / `41.25%` | `3.723 s` / `3.723 s` | `0.25` | PASS | **FAIL** | **FAIL** | Zero do PD em $-1{,}5$ eleva $M_p$ para $41{,}25\%$ (viola $\le 16{,}3\%$) e $t_s \ne 4\text{ s}$. | +| **Q2 (alt)** | $\frac{1}{s^2+1}$ | PID `equal` ($3{,}737; 1{,}474; 2{,}369$) | `13.99%` / `13.97%` | `7.639 s` / `7.639 s` | `0` | PASS | **FAIL** | **FAIL** | Polo real lento em $-0{,}3685$ dobra $t_s$ para $7{,}639\text{ s}$ (viola $t_s = 4\text{ s}$). | +| **Q3** | $\frac{3}{20s(s+1)(s+5)}$ | PD ($K_p=53{,}33, K_d=33{,}33$) | `8.09%` / `8.09%` | `3.914 s` / `3.913 s` | `0` | PASS | PASS* | **PASS*** | Malha interna reduzida exatamente; alerta para razão de dominância $4 < 5$ e zero em $-1{,}6$. | +| **Q4** | $G=\frac{5}{s+0{,}1}, H=0{,}05$ | PI ($K_p=7{,}6, K_i=16$) | `28.39%` / `28.39%` | `3.764 s` / `3.759 s` | `0` | PASS | PASS* | **PASS*** | Erro no somador $e_a(\infty)=0$ atendido; alerta explícito para $y(\infty) = 1/H(0) = 20$ ($r-y = -19$). | +| **Q5** | $\frac{1}{s^3+10s^2+17s+8}$ | PID `cancel`/`equal` ($200; 100; 100$) | `25.38%` / `25.37%` | `0.841 s` / `0.841 s` | `0` | PASS | **FAIL** | **FAIL** | Envelope $4/\sigma=1$ resulta em $t_s = 0{,}841\text{ s}$ (viola igualdade literal $1{,}0 \pm 0{,}02\text{ s}$) e usa cancelamento duplo frágil $(s+1)^2$. | +| **Q6** | $\frac{1}{s(s+2)^2}$ | PD ($K_p=8, K_d=4$) | `16.30%` / `16.29%` | `4.038 s` / `4.038 s` | `0` | PASS | PASS* | **PASS*** | Alocação direta de $(\xi=0{,}5, \omega_n=2)$; alerta de cancelamento nominal em $-2$. | +| **Q7** | $\frac{5}{s(s+2)^2}$ | PD ($K_p=1{,}6, K_d=0{,}8$) | `16.30%` / `16.29%` | `4.038 s` / `4.038 s` | `0` | PASS | **FAIL** | **FAIL** | Viola limite literal $M_p \le 16{,}0\%$ devido ao conflito didático $\xi=0{,}5 \Rightarrow 16{,}303\%$. | +| **Q8** | $\frac{-7{,}2}{5s+1}$ | PI ($K_p=-1{,}25, K_i=-4{,}261$) | `33.84%` / `33.84%` | `3.966 s` / `3.965 s` | `0` | PASS | **FAIL** | **FAIL** | Zero do PI em $-3{,}409$ eleva $M_p$ para $33{,}84\%$ (viola $\le 25\%$). Perturbação rejeitada ($T_d(0)=0$). | +| **Q9** | $\frac{1}{s^2}$ | PD ($K_p=4, K_d=2$) | `29.84%` / `29.84%` | `3.753 s` / `3.753 s` | `0` | PASS | **FAIL** | **FAIL** | Zero do PD em $-2$ eleva $M_p$ para $29{,}84\%$ (viola $\le 16\%$). | + +--- + +## 3. Caso de Referência Independente — Questão 8 ($G_c(s) = -1 - 0{,}2/s$) + +Para $G(s) = \frac{-7{,}2}{5s+1}$, a solução nominal independente $K_p = -1{,}0, K_i = -0{,}2$ foi verificada (sem hardcode no algoritmo) no motor Rust, `blocklab-core`, `mscript`, módulo de resposta temporal e MATLAB R2022b: + +- **Malha fechada de referência:** $T(s) = \frac{1{,}44}{s + 1{,}44}$ (redução de Mason exata no `blocklab-core`; erro máximo de forma de onda vs $1 - e^{-1{,}44t}$ inferior a $10^{-10}$ no `mscript` e $1{,}2\times 10^{-14}$ no MATLAB). +- **Métricas nominais:** $M_p = 0{,}000\%$, $t_s(2\%) = 2{,}71668\text{ s}$ (analítico $\ln(50)/1{,}44$), $y(\infty) = 1{,}0$, $e_{ss} = 0{,}0$. +- **Rejeição à perturbação constante:** $T_d(s) = \frac{-1{,}44s}{(s+0{,}2)(s+1{,}44)}$, $T_d(0) = 0{,}0$ (pico transitório $0{,}7273\text{ rad/s}$). +- **Estabilidade interna e sensibilidade ($\pm 10\%$ em $k$ e $\tau$):** polinômio característico não reduzido $5(s+0{,}2)(s+1{,}44)$ estritamente no SPE; sob variações de $\pm 10\%$ em $k$ e $\tau$, mantém estabilidade interna, $M_p \le 0{,}565\%$ e $t_s(2\%) \le 3{,}019\text{ s} < 4\text{ s}$. + +--- + +## 4. Resolução Completa da Questão 5 com Igualdade Obrigatória $\xi = 0{,}4$ + +Para $G(s) = \frac{1}{s^3 + 10s^2 + 17s + 8}$ sob as quatro restrições simultâneas (**PID**, $e_{ss} = 0$, $t_s(2\%) = 1{,}00 \pm 0{,}02\text{ s}$ e **$\xi = 0{,}40 \pm 0{,}01$ obrigatório**), o motor genérico `temporal_refined` encontra automaticamente: + +- **Ganhos:** $K_p = 227{,}1227,\; K_i = 56{,}8652,\; K_d = 80{,}9373$. +- **Polos e zeros:** par complexo $-3{,}4896 \pm 7{,}9956j$ ($\xi = 0{,}400000$, $\omega_n = 8{,}7239\text{ rad/s}$) + polos reais $-2{,}7491$ e $-0{,}2718$ quase cancelados pelos zeros reais $-2{,}5283$ e $-0{,}2779$. +- **Dominância modal e estabilidade interna:** todos os 4 polos no SPE; razão exata de resíduos modais de Heaviside dos polos reais frente ao par complexo igual a **`0,1056`** (~90% do resíduo transitório pertence ao modo $\xi = 0{,}4$). +- **Métricas (Rust / MATLAB R2022b):** $t_s(2\%) = 0{,}9969\text{ s}$ / $0{,}9970\text{ s}$, $e_{ss} = 0{,}00000$, $M_p = 28{,}844\%$ / $28{,}836\%$. +- **Robustez paramétrica verificada no MATLAB R2022b:** sob deslocamento de $\pm 5\%$ no polo duplo da planta em $-1$, o sistema mantém estabilidade interna com $\xi \in [0{,}395, 0{,}405]$ e $t_s \in [0{,}992\text{ s}, 1{,}004\text{ s}]$ (ainda dentro das metas); sob $\pm 10\%$ no ganho da planta, permanece estável com $\xi \in [0{,}381, 0{,}422]$ e $t_s \in [0{,}938\text{ s}, 1{,}070\text{ s}]$. diff --git a/docs/validation/assets/q2-pid-exact-xi-pass.png b/docs/validation/assets/q2-pid-exact-xi-pass.png new file mode 100644 index 0000000..aca959e Binary files /dev/null and b/docs/validation/assets/q2-pid-exact-xi-pass.png differ diff --git a/docs/validation/assets/q5-exact-xi-pass.png b/docs/validation/assets/q5-exact-xi-pass.png new file mode 100644 index 0000000..5d3f01f Binary files /dev/null and b/docs/validation/assets/q5-exact-xi-pass.png differ diff --git a/docs/validation/assets/q8-classic-fail.png b/docs/validation/assets/q8-classic-fail.png new file mode 100644 index 0000000..bdf5b9e Binary files /dev/null and b/docs/validation/assets/q8-classic-fail.png differ diff --git a/docs/validation/assets/q8-refined-pass.png b/docs/validation/assets/q8-refined-pass.png new file mode 100644 index 0000000..bc7bfe0 Binary files /dev/null and b/docs/validation/assets/q8-refined-pass.png differ diff --git a/docs/validation/benchmarks.md b/docs/validation/benchmarks.md new file mode 100644 index 0000000..85d668e --- /dev/null +++ b/docs/validation/benchmarks.md @@ -0,0 +1,33 @@ +# Benchmarks de Desempenho — Motor Rust (`--release`) vs Motor Python Legado (`be79347`) + +## 1. Metodologia e Ambiente + +Os benchmarks comparam o motor matemático nativo em Rust (`target/release/controlab-engine`) contra o motor Python legado extraído do último commit antes da remoção do backend Python (`be79347:src/python/native_bridge.py`), sob **condições operacionais idênticas**: + +- **Protocolo:** processo trabalhador persistente JSON-lines via `stdin`/`stdout` em ambos os motores, eliminando distorção por tempo de inicialização de processo a cada requisição. +- **Aquecimento e repetições:** 3 rodadas de aquecimento (*warmup*) descartadas, seguidas de 5 a 25 iterações cronometradas por carga de trabalho, registrando mediana, P95, média, mínimo, máximo, desvio padrão e pico de memória RSS. +- **Ambiente de medição:** + - Sistema operacional: Linux `7.3.4-300.fc45.x86_64` (`glibc 2.44`) + - CPU: 13th Gen Intel Core i5-13420H (12 threads lógicos) + - Compilador Rust: `rustc 1.99.1` (`--release`) + - Runtime Python legado: `Python 3.12.14` (NumPy, SciPy, SymPy, python-control, Matplotlib) + +> **Escopo das conclusões:** Os fatores de aceleração e redução de memória abaixo referem-se exclusivamente às seis cargas de trabalho medidas neste hardware e protocolo. Não devem ser extrapolados como ganho universal para qualquer operação arbitrária. + +--- + +## 2. Resultados Quantitativos + +| Carga de Trabalho | Iterações | Mediana Rust (ms) | P95 Rust (ms) | RSS Pico Rust (MB) | Mediana Python (ms) | P95 Python (ms) | RSS Pico Python (MB) | Aceleração (Mediana) | Redução de RAM (RSS) | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| **Parsing, cancelamento simbólico e LaTeX** (5 FTs) | 25 | **8,83** | 14,51 | **6,04** | 33,25 | 36,04 | 68,83 | **3,76×** | **11,39×** | +| **Estabilidade Routh-Hurwitz + raízes + gráfico** (Eqs. 10, 15, 18) | 10 | **88,12** | 98,06 | **21,58** | 1.109,79 | 1.182,45 | 242,54 | **12,59×** | **11,24×** | +| **Geração completa de LGR** (7 passos + 10.001 ganhos + SVG/PNG, 3 sistemas) | 10 | **212,74** | 229,81 | **27,26** | 2.742,20 | 2.803,93 | 270,16 | **12,89×** | **9,91×** | +| **Resposta temporal** (degrau/rampa/impulso, 900 pts, 3 sistemas) | 12 | **221,50** | 247,22 | **20,55** | 1.371,91 | 1.515,15 | 235,79 | **6,19×** | **11,47×** | +| **Síntese de controladores via LGR + deduções + simulação** (Q1, Q4, Q6, Q8) | 10 | **257,62** | 271,59 | **98,82** | 2.321,29 | 2.391,06 | 230,93 | **9,01×** | **2,34×** | +| **Suíte completa de 19 exercícios LGR** (190.019 avaliações de raízes + 19 figuras) | 5 | **1.049,03** | 1.118,14 | **26,68** | 16.263,50 | 16.421,91 | 291,97 | **15,50×** | **10,94×** | + +Complementarmente, no motor Rust em modo `--release`: +- A redução simbólica e numérica de todos os diagramas de blocos acadêmicos via fórmula de Mason (`blocklab-core`) executa em **~20 ms** no total. +- A execução das 9 questões de controladores e modelos de LGR no interpretador `.m` (`mscript`) executa em **~10 ms**. +- A síntese refinada por restrições temporais (`temporal_refined` / `auto_simplest`) executa em **< 300 ms** por questão em build `--release`. diff --git a/docs/validation/final-acceptance.md b/docs/validation/final-acceptance.md new file mode 100644 index 0000000..8dd2d56 --- /dev/null +++ b/docs/validation/final-acceptance.md @@ -0,0 +1,53 @@ +# Relatório de Aceitação Final — Validação Científica do Motor Rust + +## 1. Resumo Executivo + +O motor matemático nativo em Rust do **ControLAB** passou por uma auditoria científica, numérica, funcional, visual e de desempenho em 11 etapas sobre a branch `test/academic-validation`, cobrindo 19 casos de Lugar Geométrico das Raízes (`Exercicios_-_LGR.pdf`), 9 questões de Projeto de Controladores (`Projeto_de_controladores.pdf`), 42 configurações rastreadas em [`validation-matrix.csv`](validation-matrix.csv), 152 casos congelados de paridade histórica e 3 suítes opt-in ao vivo contra o **MATLAB R2022b**. + +| Critério | Status Final | Evidência | +|---|---|---| +| Formatação (`cargo fmt --all -- --check`) | **PASS** | 0 divergências | +| Análise estática (`cargo clippy --workspace --all-targets -- -D warnings`) | **PASS** | 0 warnings | +| Suíte permanente (`cargo test --workspace`) | **PASS** | 411 aprovados, 0 falhas, 3 opt-in ignorados | +| Suíte opt-in MATLAB R2022b (`cargo test --release -p mscript -- --ignored`) | **PASS** | 3/3 aprovados (erro relativo escalado máximo `7,883e-15`) | +| Paridade congelada (`cargo run --release -p xtask -- parity`) | **PASS** | 152/152 casos (`complete_parity: true`, 260 ativos visuais) | +| Auditoria de fontes (`cargo run --release -p xtask -- check-sources`) | **PASS** | 0 dependências Python/JS/TS/HTML/CSS no código-fonte | +| Compilação otimizada (`cargo build --workspace --release`) | **PASS** | Todos os 6 crates compilados sem erros | + +--- + +## 2. Análise Qualitativa da Cobertura de Testes + +A confiança da validação decorre da cobertura específica de comportamentos críticos, e não apenas da contagem bruta de testes: + +- **Casos acadêmicos das listas da UFERSA:** + - `crates/control-engine/tests/academic_lgr_validation.rs`: cobre todos os 19 casos de LGR (polos repetidos, polos na origem, zeros no SPD, grau relativo zero, coeficientes fracionários, realimentação não unitária, questão paramétrica 5 com $a_2=0$, resíduos de $D(s)+KN(s)=0$, simetria conjugada e Routh-Hurwitz). + - `crates/control-engine/tests/academic_controllers_validation.rs`: cobre as 9 questões de controladores via LGR clássico (incluindo os 3 modos de PID na Q5, cancelamento polo-zero exato em Q6/Q7, erro no somador vs saída em Q4, perturbação de carga em Q8, repetibilidade e critério definitivo de $t_s$). + - `crates/blocklab-core/tests/academic_diagrams.rs`: cobre a redução simbólica exata via regra de Mason dos diagramas LGR Q3(a,b,c) e Controladores Q3, Q4, Q6, Q7, Q8 (referência, perturbação e referência independente `1.44/(s+1.44)`) e Q9. + - `crates/mscript/tests/academic_validation.rs`: valida a execução em scripts `.m` dos modelos LGR, controladores e referência independente da Q8. +- **Conformidade semântica, restrições obrigatórias e inviabilidade matemática:** + - `crates/control-engine/tests/academic_requirements_compliance.rs`: verifica que controladores numericamente corretos são reprovados quando violam requisitos reais; rejeita sistemas instáveis e cancelamentos internamente instáveis no SPD; valida a referência independente da Q8 com perturbações de $\pm 10\%$; valida `temporal_refined` e `auto_simplest` com igualdade obrigatória de $\xi$ (Q5 $\xi=0{,}4$, Q2 PID $\xi=0{,}5$, Q7 PD $\xi=0{,}50\pm 0{,}01$), provas de `ProvenInfeasible` diferenciando Q2 ($y(\infty) = 1 - c/\omega_n^2$) de Q9 ($1/s^2$) e distinção para `NotFoundWithinSearchBounds`. +- **Interface nativa (`controlab-native`):** + - `native/src/ui_tests.rs::controller_verification_ui_flags_non_compliant_classic_and_approves_refined`: valida que a GUI exibe `NÃO CONFORME`, `[OBRIGATÓRIA]`, `Motivos de não conformidade` e `Polo(s) de referência (ξ/ωn)` em falhas, e `CONFORME` quando todas as restrições obrigatórias passam. + +--- + +## 3. Limitações Conhecidas e Riscos de Regressão + +- **Escopo do motor:** a validação cobre sistemas SISO lineares contínuos invariantes no tempo; sistemas MIMO, discretos ou não lineares estão fora do escopo atual. +- **Limitações matemáticas documentadas:** + - Q2 PD e Q9 PD são matematicamente inviáveis sob igualdade exata $\xi = 0{,}5$ simultaneamente a $M_p \le 16{,}3\%$/$16{,}0\%$ (detalhado em [`synthesis-comparison.md`](synthesis-comparison.md)). + - Soluções com cancelamento aproximado de polos estáveis (Q1, Q5, Q6, Q7, Q8 referência) são acompanhadas de advertências técnicas na GUI e no JSON para avaliação de robustez paramétrica e esforço de controle. +- **Riscos de regressão avaliados:** + - **Contrato JSON legado:** risco muito baixo — os campos `verification` e `synthesis` são emitidos somente quando `verify_requirements: true` ou `synthesis_mode` são solicitados, mantendo 152/152 casos de paridade intactos. + - **Desempenho de síntese em ordem alta:** o otimizador determinístico é limitado em número de avaliações e executa em `< 0,3 s` nos casos testados em `--release`; em plantas de ordem elevada ($\ge 6$) pode atingir o limite da busca e retornar `NotFoundWithinSearchBounds` com diagnóstico explícito. + - **Layout compacto de LaTeX:** fórmulas extensas de 4ª ordem sofrem corte horizontal leve nos cartões compactos superiores do módulo de controladores (comportamento pré-existente de 2 colunas), sem afetar os gráficos nem o painel de verificação. + +--- + +## 4. Recomendação de Integração + +As alterações estão **prontas para revisão e integração na branch `main` via Pull Request**, mantendo: +- Compatibilidade total com o fluxo didático clássico (`lgr_classic`) e com os 152 casos congelados de paridade. +- Proteção explícita na interface e no motor contra aprovação indevida de controladores que violam especificações reais. +- Execução automática na CI (`.github/workflows/build-all.yml`) de toda a suíte permanente em Rust, incluindo validação acadêmica, paridade congelada e auditoria de fontes, sem dependência de Python ou MATLAB. diff --git a/docs/validation/methodology.md b/docs/validation/methodology.md new file mode 100644 index 0000000..927067f --- /dev/null +++ b/docs/validation/methodology.md @@ -0,0 +1,62 @@ +# Metodologia de Validação Científica e Semântica de Especificações + +## 1. Quatro Categorias Independentes de Validação + +Concordância numérica com o MATLAB não garante que um controlador projetado satisfaça as especificações do problema. Por isso, cada caso e configuração é avaliado separadamente em quatro categorias: + +| Categoria | Critério | +|---|---| +| `NUMERICAL_PASS` | Coeficientes, polos, zeros, trajetórias LGR, ganhos críticos e respostas temporais concordam com a resolução analítica e com o MATLAB R2022b dentro das tolerâncias definidas na Seção 4. | +| `REQUIREMENTS_PASS` | A malha fechada real — sem desprezar zeros adicionais, polos não dominantes ou aproximações de 2ª ordem — é externa e internamente estável e satisfaz **todas** as restrições obrigatórias especificadas. | +| `FUNCTIONAL_PASS` | O fluxo opera ponta a ponta nos módulos Rust (`controlab-engine`, `blocklab-core`, `mscript` e interface `controlab-native`), reportando explicitamente conformidades, alertas e falhas. | +| `VISUAL_PASS` | Os gráficos gerados (LGR e resposta temporal) e o painel de conformidade da GUI refletem fielmente os valores medidos e o status real do projeto. | + +**Regra de aprovação global (`OVERALL`):** uma configuração recebe `PASS` global somente quando todas as categorias aplicáveis forem aprovadas. Caso `NUMERICAL_PASS` seja verdadeiro mas `REQUIREMENTS_PASS` falhe, o status global é obrigatoriamente **`FAIL`**. + +--- + +## 2. Semântica Explícita das Especificações + +O verificador (`crates/control-engine/src/controller_synthesis.rs`) distingue formalmente cada tipo de restrição, impedindo conversões silenciosas de igualdades em desigualdades ou descarte tácito de requisitos: + +| Parâmetro | Modos suportados | Comportamento | +|---|---|---| +| **Coeficiente de amortecimento ($\xi$)** | `Equal { target, tolerance }`, `AtLeast(min)`, `DidacticEstimate(est)` | Igualdade obrigatória (`±0,01` padrão) exige par complexo conjugado quando `target < 1` (rejeita polos puramente reais). Quando informado sem `Mp`, preserva igualdade automaticamente; quando pareado com `Mp`, é sinalizado como estimativa didática opcional, salvo se marcado como obrigatório. | +| **Frequência natural ($\omega_n$)** | `Equal { target, tolerance }`, `AtLeast(min)`, `OptionalEstimate(est)` | Tolerância padrão uniforme de `±2%` (piso `0,01 rad/s`). | +| **Tempo de acomodação ($t_s$)** | `AtMost(max)` e `Equal { target, tolerance }` | Medido pelo critério definitivo de entrada na banda de `±2%` ou `±5%` (último ponto fora da banda com interpolação linear subamostral). Tolerância padrão uniforme de igualdade: `max(2% × alvo, 0,02 s)` (`±0,02 s` para `1 s`; `±0,08 s` para `4 s`). | +| **Sobressinal máximo ($M_p$)** | Limite superior efetivamente medido (`Mp <= max`) | Somente aplicado como restrição obrigatória quando `Mp` é solicitado explicitamente. | +| **Polos dominantes e dominância modal** | `DesignObjective::PolePlacement`, `require_complex_dominance` | Para sistemas de ordem superior, o motor identifica explicitamente a qual polo ou par complexo conjugado $\xi$ e $\omega_n$ se referem, calcula a razão de dominância $|\operatorname{Re}(p_k)|/|\operatorname{Re}(p_{\text{dom}})|$ e a razão exata de resíduos modais de Heaviside $\sum |R_{\text{não-dom}}| / \sum |R_{\text{dom}}|$ para `T(s)/s`. | +| **Erro estacionário ($e_{ss}$)** | `require_zero_step_error` | Distingue explicitamente erro atuante no somador $e_a(\infty) = r(\infty) - H(0)y(\infty)$ do erro de rastreamento da saída $r(\infty) - y(\infty)$ em realimentação não unitária. | +| **Classificação de viabilidade** | `Feasible`, `ProvenInfeasible`, `NotFoundWithinSearchBounds` | Diferencia inviabilidade matematicamente demonstrada de ausência de solução dentro dos limites da busca numérica. | + +--- + +## 3. Estabilidade Externa e Interna Antes de Qualquer Simplificação + +Toda verificação calcula as raízes do polinômio característico **não reduzido**: + +$$P(s) = D_c(s)D_g(s)D_h(s) + N_c(s)N_g(s)N_h(s) = 0$$ + +- Qualquer polo com $\operatorname{Re}(p) \ge -10^{-7}$ reprova imediatamente a estabilidade externa. +- Qualquer cancelamento polo-zero no semiplano direito (SPD) ou sobre o eixo imaginário $j\omega$ (em malha aberta ou fechada) reprova imediatamente a **estabilidade interna**, sem nunca depender de simplificação prévia (`minreal`). +- Cancelamentos estáveis exatos ou aproximados no SPE são permitidos com advertência técnica explícita sobre sensibilidade a variações paramétricas da planta. + +--- + +## 4. Tolerâncias Numéricas e Origem das Referências + +| Grandeza | Tolerância | Erro máximo observado | Fundamento técnico | +|---|---:|---:|---| +| Coeficientes polinomiais | `1e-10` | `4,44e-16` | Aritmética racional exata em `exact_transfer.rs` e `blocklab-core` antes da conversão `f64` | +| Polos e zeros simples | `1e-6` | `7,11e-15` | Decomposição de Schur com balanceamento da matriz companheira | +| Polos de multiplicidade $m > 1$ | `1e-4` | `3,14e-08` | Condicionamento teórico $\epsilon_{\text{mach}}^{1/m}$ ($\approx 1{,}5\times 10^{-8}$ para $m=2$) | +| Ganhos de controladores ($K_p, K_i, K_d, z, \tau_d$) | `1e-6` | `8,88e-16` | Solução analítica direta em `f64` | +| Valor estacionário $y(\infty)$ e $e_a(\infty)$ | `1e-5` | `0,00e+00` | Ganho DC exato com cancelamento de potências de $s$ na origem | +| Forma de onda temporal $y(t)$ | `1e-4` | `4,22e-15` | Exponencial matricial exata via scaling-and-squaring | +| Sobressinal percentual ($M_p$) | `0,1 pp` | `0,017 pp` | Simulação densa (2.000–4.000 pontos) comparada ao `stepinfo` do MATLAB R2022b | +| Tempo de acomodação definitivo ($t_s$) | `0,02 s` | `0,0146 s` | Última saída da faixa com interpolação linear subamostral | + +### Fontes de referência utilizadas +1. **Resoluções analíticas fechadas** (fórmulas exatas para raízes, pontos de quebra, cruzamentos $j\omega$, formula de Mason e formas de onda ao degrau). +2. **MATLAB R2022b (`9.13.0.2049777`) ao vivo** — utilizado tanto para gerar referências independentes dos 19 casos LGR, das 9 questões de controladores, da referência independente da Q8 e dos controladores refinados, quanto nos 3 testes opt-in do `mscript` (`cargo test --release -p mscript -- --ignored`). +3. **Referências congeladas do motor Python legado (`tests/reference/python/`, commit `be79347`)** — verificadas por `cargo run --release -p xtask -- parity` (152/152 casos, 260 ativos visuais). diff --git a/docs/validation/references/README.md b/docs/validation/references/README.md new file mode 100644 index 0000000..5a412e1 --- /dev/null +++ b/docs/validation/references/README.md @@ -0,0 +1,31 @@ +# Referências Científicas e Dados Reproduzíveis + +Este diretório contém o subconjunto mínimo e reproduzível das referências numéricas independentes e dados experimentais de benchmark utilizados na validação científica do motor em Rust do **ControLAB**. + +Estes arquivos têm finalidade exclusivamente científica e documental e **não constituem dependências de execução ou compilação** do ControLAB. + +--- + +## Conteúdo + +| Arquivo | Descrição | +|---|---| +| [`generate_matlab_reference.m`](generate_matlab_reference.m) | Script independente de geração das referências MATLAB R2022b para os 19 casos de LGR e as 10 configurações clássicas de projeto de controladores (Q1–Q9) | +| [`matlab_r2022b_reference.json`](matlab_r2022b_reference.json) | Saída JSON gerada pelo MATLAB R2022b (`9.13.0.2049777`) com polos, zeros, centroide, assíntotas, pontos de quebra, ângulos de partida/chegada, amostras de raízes em 13 ganhos e métricas `stepinfo` | +| [`generate_matlab_etapa10_reference.m`](generate_matlab_etapa10_reference.m) | Script independente de verificação da referência analítica da Questão 8 ($G_c(s) = -1 - 0{,}2/s$, perturbações de $\pm 10\%$ e rejeição a perturbação de carga) e dos controladores refinados por métricas temporais | +| [`matlab_r2022b_etapa10_reference.json`](matlab_r2022b_etapa10_reference.json) | Saída JSON do MATLAB R2022b correspondente a `generate_matlab_etapa10_reference.m` | +| [`generate_matlab_etapa11_reference.m`](generate_matlab_etapa11_reference.m) | Script independente de auditoria dos coeficientes de amortecimento $\xi$, resíduos modais de Heaviside e robustez paramétrica dos controladores sob restrições estritas (`DampingSpec::Equal`) e de limite mínimo (`DampingSpec::AtLeast`) | +| [`matlab_r2022b_etapa11_reference.json`](matlab_r2022b_etapa11_reference.json) | Saída JSON do MATLAB R2022b correspondente a `generate_matlab_etapa11_reference.m` | +| [`benchmark-results.json`](benchmark-results.json) | Dados consolidados dos 6 cenários de benchmark comparando o binário nativo Rust (`--release`) com o motor Python legado (`be79347`), incluindo metadados do ambiente experimental | + +--- + +## Instruções para Reprodução Independente no MATLAB + +Caso disponha do **MATLAB** (R2022b ou compatível) com **Control System Toolbox**, execute a partir deste diretório (`docs/validation/references/`): + +```bash +matlab -batch "run('generate_matlab_reference.m'); run('generate_matlab_etapa10_reference.m'); run('generate_matlab_etapa11_reference.m');" +``` + +Cada script regenera o respectivo arquivo `matlab_r2022b_*.json` no diretório de trabalho atual utilizando exclusivamente funções nativas do MATLAB (`tf`, `pole`, `zero`, `rlocus`, `feedback`, `minreal`, `step`, `stepinfo`, `dcgain`, `residue`, `jsonencode`). diff --git a/docs/validation/references/benchmark-results.json b/docs/validation/references/benchmark-results.json new file mode 100644 index 0000000..4cfc9b5 --- /dev/null +++ b/docs/validation/references/benchmark-results.json @@ -0,0 +1,171 @@ +{ + "environment": { + "os": "Linux-7.3.4-300.fc45.x86_64-x86_64-with-glibc2.44", + "cpu": "13th Gen Intel(R) Core(TM) i5-13420H", + "logical_cores": 12, + "rustc": "rustc 1.99.1 (58cf8f9c3 2026-10-13)", + "cargo": "cargo 1.99.1 (5f94df478 2026-08-27)", + "legacy_python": "Python 3.12.14", + "legacy_commit": "be79347", + "rust_commit": "c32b2d4 (branch test/academic-validation)", + "profile": "release (optimized)" + }, + "benchmarks": [ + { + "id": "tf_preview_parsing", + "description": "Transfer function parsing, symbolic cancellation & LaTeX formatting (5 expressions)", + "batch_size": 5, + "rust_release": { + "iterations": 25, + "median_ms": 8.831, + "p95_ms": 14.507, + "mean_ms": 9.44, + "min_ms": 6.952, + "max_ms": 14.89, + "stdev_ms": 2.213, + "peak_rss_mb": 6.04 + }, + "legacy_python": { + "iterations": 25, + "median_ms": 33.248, + "p95_ms": 36.04, + "mean_ms": 33.686, + "min_ms": 32.312, + "max_ms": 36.79, + "stdev_ms": 1.262, + "peak_rss_mb": 68.83 + }, + "speedup_median_x": 3.76 + }, + { + "id": "routh_stability_roots", + "description": "Routh-Hurwitz symbolic array, critical gains & polynomial root locus (Eq. 10, 15, 18)", + "batch_size": 3, + "rust_release": { + "iterations": 10, + "median_ms": 88.117, + "p95_ms": 98.062, + "mean_ms": 90.341, + "min_ms": 86.591, + "max_ms": 101.808, + "stdev_ms": 4.68, + "peak_rss_mb": 21.58 + }, + "legacy_python": { + "iterations": 10, + "median_ms": 1109.787, + "p95_ms": 1182.455, + "mean_ms": 1116.676, + "min_ms": 1048.147, + "max_ms": 1191.964, + "stdev_ms": 45.24, + "peak_rss_mb": 242.54 + }, + "speedup_median_x": 12.59 + }, + { + "id": "lgr_generation", + "description": "Root Locus 7-step derivation + 10,001-gain root trajectory + figure (Eq. 3, 10, 15)", + "batch_size": 3, + "rust_release": { + "iterations": 10, + "median_ms": 212.736, + "p95_ms": 229.808, + "mean_ms": 214.752, + "min_ms": 203.017, + "max_ms": 233.427, + "stdev_ms": 11.116, + "peak_rss_mb": 27.26 + }, + "legacy_python": { + "iterations": 10, + "median_ms": 2742.2, + "p95_ms": 2803.931, + "mean_ms": 2732.384, + "min_ms": 2636.268, + "max_ms": 2811.49, + "stdev_ms": 55.749, + "peak_rss_mb": 270.16 + }, + "speedup_median_x": 12.89 + }, + { + "id": "time_response_simulation", + "description": "Continuous time response (step, ramp, impulse, 900 pts) + metrics (Q3, Q5, Q8)", + "batch_size": 3, + "rust_release": { + "iterations": 12, + "median_ms": 221.497, + "p95_ms": 247.22, + "mean_ms": 226.524, + "min_ms": 216.058, + "max_ms": 254.941, + "stdev_ms": 11.681, + "peak_rss_mb": 20.55 + }, + "legacy_python": { + "iterations": 12, + "median_ms": 1371.912, + "p95_ms": 1515.148, + "mean_ms": 1381.996, + "min_ms": 1286.242, + "max_ms": 1529.956, + "stdev_ms": 77.376, + "peak_rss_mb": 235.79 + }, + "speedup_median_x": 6.19 + }, + { + "id": "controller_synthesis", + "description": "Controller synthesis via LGR + step deductions + before/after simulation (Q1 PI, Q4 PI, Q6 PD, Q8 PI)", + "batch_size": 4, + "rust_release": { + "iterations": 10, + "median_ms": 257.621, + "p95_ms": 271.585, + "mean_ms": 258.371, + "min_ms": 249.612, + "max_ms": 277.231, + "stdev_ms": 8.066, + "peak_rss_mb": 98.82 + }, + "legacy_python": { + "iterations": 10, + "median_ms": 2321.291, + "p95_ms": 2391.064, + "mean_ms": 2308.402, + "min_ms": 2207.397, + "max_ms": 2398.421, + "stdev_ms": 70.616, + "peak_rss_mb": 230.93 + }, + "speedup_median_x": 9.01 + }, + { + "id": "full_19_lgr_suite", + "description": "Complete execution of all 19 LGR academic exercises (19 x 10,001 gains + 19 figures)", + "batch_size": 19, + "rust_release": { + "iterations": 5, + "median_ms": 1049.032, + "p95_ms": 1118.143, + "mean_ms": 1065.235, + "min_ms": 1036.87, + "max_ms": 1132.002, + "stdev_ms": 38.465, + "peak_rss_mb": 26.68 + }, + "legacy_python": { + "iterations": 5, + "median_ms": 16263.502, + "p95_ms": 16421.908, + "mean_ms": 16177.538, + "min_ms": 15887.676, + "max_ms": 16430.305, + "stdev_ms": 258.433, + "peak_rss_mb": 291.97 + }, + "speedup_median_x": 15.5 + } + ] +} diff --git a/docs/validation/references/generate_matlab_etapa10_reference.m b/docs/validation/references/generate_matlab_etapa10_reference.m new file mode 100644 index 0000000..9b32570 --- /dev/null +++ b/docs/validation/references/generate_matlab_etapa10_reference.m @@ -0,0 +1,110 @@ +% Etapa 10 independent MATLAB R2022b verification script +% Verifies: +% 1. Q2 classic PID (equal zeros) actual stepinfo (detecting report mismatch) +% 2. Q8 independent reference Gc(s) = -1 - 0.2/s (nominal, disturbance, +/-10% perturbations) +% 3. All Etapa 10 refined controllers (Q2 PD, Q2 PID, Q5 PID, Q7 PD, Q8 PI, Q9 PD) + +s = tf('s'); +results = struct(); +results.matlab_version = version; + +% 1. Q2 classic PID (equal zeros) +G2 = 1 / (s^2 + 1); +Gc_q2_pid = pid(3.737034183642664, 1.4740683672853223, 2.3685170918213303); +T_q2_pid = feedback(Gc_q2_pid * G2, 1); +info_q2_pid = stepinfo(T_q2_pid); +results.q2_pid_classic_equal = struct( ... + 'overshoot', info_q2_pid.Overshoot, ... + 'settling_time', info_q2_pid.SettlingTime, ... + 'rise_time', info_q2_pid.RiseTime, ... + 'peak_time', info_q2_pid.PeakTime, ... + 'dcgain', dcgain(T_q2_pid), ... + 'poles_re', real(pole(T_q2_pid)).', ... + 'poles_im', imag(pole(T_q2_pid)).', ... + 'zeros_re', real(zero(T_q2_pid)).', ... + 'zeros_im', imag(zero(T_q2_pid)).' ... +); + +% 2. Q8 independent reference: G(s) = -7.2/(5s+1), Gc(s) = -1 - 0.2/s +G8 = -7.2 / (5*s + 1); +Gc8_ref = pid(-1.0, -0.2, 0); +T8_ref = feedback(Gc8_ref * G8, 1); +T8_ref_min = minreal(T8_ref); +T8_dist = feedback(G8, Gc8_ref); +info_q8_ref = stepinfo(T8_ref); +t_eval = linspace(0, 10, 2001); +y_ref = step(T8_ref, t_eval); +y_exact = 1 - exp(-1.44 * t_eval.'); +y_dist = step(T8_dist, t_eval); + +% Perturbation sensitivity +/-10% on gain k=-7.2 and tau=5 +pert_names = {'k_plus_10', 'k_minus_10', 'tau_plus_10', 'tau_minus_10'}; +pert_ks = [-7.2*1.1, -7.2*0.9, -7.2, -7.2]; +pert_taus = [5.0, 5.0, 5.0*1.1, 5.0*0.9]; +perts = struct(); +for idx = 1:4 + Gp = pert_ks(idx) / (pert_taus(idx)*s + 1); + Tp = feedback(Gc8_ref * Gp, 1); + ip = stepinfo(Tp); + perts.(pert_names{idx}) = struct( ... + 'stable', all(real(pole(Tp)) < 0), ... + 'overshoot', ip.Overshoot, ... + 'settling_time', ip.SettlingTime, ... + 'dcgain', dcgain(Tp), ... + 'poles_re', real(pole(Tp)).', ... + 'poles_im', imag(pole(Tp)).' ... + ); +end + +results.q8_reference = struct( ... + 'overshoot', info_q8_ref.Overshoot, ... + 'settling_time', info_q8_ref.SettlingTime, ... + 'dcgain', dcgain(T8_ref), ... + 'disturbance_dcgain', dcgain(T8_dist), ... + 'disturbance_peak_abs', max(abs(y_dist)), ... + 'max_waveform_err_vs_analytic', max(abs(y_ref - y_exact)), ... + 'unreduced_poles_re', real(pole(T8_ref)).', ... + 'minreal_poles_re', real(pole(T8_ref_min)).', ... + 'perturbations', perts ... +); + +% 3. Refined controllers (from Rust engine temporal_refined) +cases = { ... + 'q2_pd_refined', 1/(s^2 + 1), pid(6.5860656976371965, 0, 13.355570405454662); ... + 'q2_pid_refined', 1/(s^2 + 1), pid(11.096658419745077, 5.285083609612153, 5.542244219291329); ... + 'q5_pid_refined', 1/(s^3 + 10*s^2 + 17*s + 8), pid(71.88638085895549, 35.900742386408645, 35.985636144021534); ... + 'q7_pd_refined', 5/(s*(s+2)^2), pid(0.5183391822300726, 0, 0.2680856376900818); ... + 'q8_pi_refined', -7.2/(5*s + 1), pid(-0.681056036012193, -0.1362112072024386, 0); ... + 'q9_pd_refined', 1/(s^2), pid(1.7458718774059128, 0, 2.440754756613886) ... +}; + +refined = struct(); +for idx = 1:size(cases, 1) + cname = cases{idx, 1}; + Gp = cases{idx, 2}; + Gc = cases{idx, 3}; + T = feedback(Gc * Gp, 1); + info = stepinfo(T); + refined.(cname) = struct( ... + 'stable', all(real(pole(T)) < 0), ... + 'overshoot', info.Overshoot, ... + 'settling_time', info.SettlingTime, ... + 'rise_time', info.RiseTime, ... + 'peak_time', info.PeakTime, ... + 'dcgain', dcgain(T), ... + 'poles_re', real(pole(T)).', ... + 'poles_im', imag(pole(T)).', ... + 'zeros_re', real(zero(T)).', ... + 'zeros_im', imag(zero(T)).' ... + ); +end +results.refined = refined; + +out_json = jsonencode(results, 'PrettyPrint', true); +fid = fopen('matlab_r2022b_etapa10_reference.json', 'w'); +fwrite(fid, out_json, 'char'); +fclose(fid); +fprintf('Saved matlab_etapa10_reference.json successfully.\n'); +fprintf('Q2 PID classic equal: Mp=%.6f%% ts=%.6fs\n', info_q2_pid.Overshoot, info_q2_pid.SettlingTime); +fprintf('Q8 ref: Mp=%.6f%% ts=%.6fs dc=%.6f dist_dc=%.6f err=%.2e\n', ... + info_q8_ref.Overshoot, info_q8_ref.SettlingTime, dcgain(T8_ref), dcgain(T8_dist), max(abs(y_ref - y_exact))); diff --git a/docs/validation/references/generate_matlab_etapa11_reference.m b/docs/validation/references/generate_matlab_etapa11_reference.m new file mode 100644 index 0000000..c767f78 --- /dev/null +++ b/docs/validation/references/generate_matlab_etapa11_reference.m @@ -0,0 +1,149 @@ +% Etapa 11 independent MATLAB R2022b reference verification script +% Verifies: +% 1. Section 1 audit table: exact damping ratio xi of all 5 Etapa 10 refined controllers (both full f64 & 4-decimal rounded gains) +% 2. All Etapa 11 constrained controllers (exact xi=0.4 on Q5, exact xi=0.5 on Q2 PID, exact xi=0.50+-0.01 dominant on Q7 PD, +% and xi>=0.5 solutions on Q2 PD, Q8 PI, Q9 PD) including exact Heaviside modal residue ratios +% 3. Q5 exact xi=0.4 perturbation robustness (+/-5% and +/-10% on plant gain and denominator) + +s = tf('s'); +out = struct(); +out.matlab_version = version; + +% Helper function via anonymous/nested evaluation: +% 1. Etapa 10 Section 1 audit (full-precision gains vs 4-decimal rounded gains) +e10_cases = { ... + 'q2_pd_e10_full', 1/(s^2+1), pid(6.5860656976371965, 0, 13.355570405454662); ... + 'q2_pd_e10_round', 1/(s^2+1), pid(6.5861, 0, 13.3556); ... + 'q2_pid_e10_full', 1/(s^2+1), pid(11.096658419745077, 5.285083609612153, 5.542244219291329); ... + 'q2_pid_e10_round', 1/(s^2+1), pid(11.0967, 5.2851, 5.5422); ... + 'q5_pid_e10_full', 1/(s^3+10*s^2+17*s+8), pid(71.88638085895549, 35.900742386408645, 35.985636144021534); ... + 'q5_pid_e10_round', 1/(s^3+10*s^2+17*s+8), pid(71.8864, 35.9007, 35.9856); ... + 'q7_pd_e10_full', 5/(s*(s+2)^2), pid(0.5183391822300726, 0, 0.2680856376900818); ... + 'q7_pd_e10_round', 5/(s*(s+2)^2), pid(0.5183, 0, 0.2681); ... + 'q9_pd_e10_full', 1/(s^2), pid(1.7458718774059128, 0, 2.440754756613886); ... + 'q9_pd_e10_round', 1/(s^2), pid(1.7459, 0, 2.4408) ... +}; + +e10_audit = struct(); +for idx = 1:size(e10_cases, 1) + cname = e10_cases{idx, 1}; + T = feedback(e10_cases{idx, 3} * e10_cases{idx, 2}, 1); + ps = pole(T); + c_idx = abs(imag(ps)) > 1e-6; + if any(c_idx) + cp = ps(c_idx); + [~, best_i] = max(real(cp)); + dom_c = cp(best_i); + xi_val = -real(dom_c) / abs(dom_c); + wn_val = abs(dom_c); + else + xi_val = 1.0; + wn_val = min(abs(real(ps))); + end + info = stepinfo(T); + e10_audit.(cname) = struct( ... + 'xi', xi_val, ... + 'wn', wn_val, ... + 'overshoot', info.Overshoot, ... + 'settling_time', info.SettlingTime, ... + 'poles_re', real(ps).', ... + 'poles_im', imag(ps).' ... + ); +end +out.etapa10_xi_audit = e10_audit; + +% 2. Etapa 11 constrained controllers +e11_cases = { ... + 'q5_pid_exact_xi04', 1/(s^3+10*s^2+17*s+8), pid(227.12265104923506, 56.86515843458203, 80.93732989873575); ... + 'q2_pid_exact_xi05', 1/(s^2+1), pid(4.236932767669361, 4.5932785085575025, 3.765120324007892); ... + 'q7_pd_exact_xi05_dom', 5/(s*(s+2)^2), pid(1.6029530461209025, 0, 0.8175290091906282); ... + 'q2_pd_xi_at_least', 1/(s^2+1), pid(6.913990838235495, 0, 14.286123681380035); ... + 'q8_pi_refined_e11', -7.2/(5*s+1), pid(-0.5021608353065594, -0.12634484602744345, 0); ... + 'q9_pd_xi_at_least', 1/(s^2), pid(0.10354118646519724, 0, 2.120753150278508) ... +}; + +e11_res = struct(); +for idx = 1:size(e11_cases, 1) + cname = e11_cases{idx, 1}; + T = feedback(e11_cases{idx, 3} * e11_cases{idx, 2}, 1); + ps = pole(T); + zs = zero(T); + [num_c, den_c] = tfdata(T, 'v'); + c_idx = abs(imag(ps)) > 1e-6; + res_ratio = NaN; + if any(c_idx) + cp = ps(c_idx); + [~, best_i] = max(real(cp)); + dom_c = cp(best_i); + xi_val = -real(dom_c) / abs(dom_c); + wn_val = abs(dom_c); + [r_pf, p_pf, ~] = residue(num_c, [den_c 0]); + dom_mask = abs(real(p_pf) - real(dom_c)) < 1e-3 & abs(abs(imag(p_pf)) - abs(imag(dom_c))) < 1e-3; + orig_mask = abs(p_pf) < 1e-6; + other_mask = ~dom_mask & ~orig_mask; + res_ratio = sum(abs(r_pf(other_mask))) / max(sum(abs(r_pf(dom_mask))), 1e-12); + else + xi_val = 1.0; + wn_val = min(abs(real(ps))); + end + info = stepinfo(T); + e11_res.(cname) = struct( ... + 'stable', all(real(ps) < 0), ... + 'xi', xi_val, ... + 'wn', wn_val, ... + 'non_dominant_residue_ratio', res_ratio, ... + 'overshoot', info.Overshoot, ... + 'settling_time', info.SettlingTime, ... + 'rise_time', info.RiseTime, ... + 'peak_time', info.PeakTime, ... + 'dcgain', dcgain(T), ... + 'poles_re', real(ps).', ... + 'poles_im', imag(ps).', ... + 'zeros_re', real(zs).', ... + 'zeros_im', imag(zs).' ... + ); +end +out.etapa11_refined = e11_res; + +% 3. Q5 exact xi=0.4 perturbation robustness (+/-5% and +/-10% on plant gain) +Gc5 = pid(227.12265104923506, 56.86515843458203, 80.93732989873575); +pert_tags = {'gain_plus_5', 'gain_minus_5', 'gain_plus_10', 'gain_minus_10', 'pole1_plus_5', 'pole1_minus_5'}; +pert_plants = { ... + 1.05/(s^3+10*s^2+17*s+8), ... + 0.95/(s^3+10*s^2+17*s+8), ... + 1.10/(s^3+10*s^2+17*s+8), ... + 0.90/(s^3+10*s^2+17*s+8), ... + 1/((s+1.05)^2*(s+8)), ... + 1/((s+0.95)^2*(s+8)) ... +}; +q5_rob = struct(); +for idx = 1:numel(pert_tags) + Tp = feedback(Gc5 * pert_plants{idx}, 1); + ps = pole(Tp); + cp = ps(abs(imag(ps)) > 1e-6); + [~, bi] = max(real(cp)); + xi_p = -real(cp(bi)) / abs(cp(bi)); + ip = stepinfo(Tp); + q5_rob.(pert_tags{idx}) = struct( ... + 'stable', all(real(ps) < 0), ... + 'xi', xi_p, ... + 'overshoot', ip.Overshoot, ... + 'settling_time', ip.SettlingTime, ... + 'dcgain', dcgain(Tp) ... + ); +end +out.q5_exact_robustness = q5_rob; + +json_txt = jsonencode(out, 'PrettyPrint', true); +fid = fopen('matlab_r2022b_etapa11_reference.json', 'w'); +fwrite(fid, json_txt, 'char'); +fclose(fid); +fprintf('Saved matlab_r2022b_etapa11_reference.json successfully.\n'); +fprintf('Q5 exact xi=0.4 MATLAB: xi=%.6f wn=%.4f res_ratio=%.4f Mp=%.3f%% ts=%.4fs\n', ... + e11_res.q5_pid_exact_xi04.xi, e11_res.q5_pid_exact_xi04.wn, e11_res.q5_pid_exact_xi04.non_dominant_residue_ratio, ... + e11_res.q5_pid_exact_xi04.overshoot, e11_res.q5_pid_exact_xi04.settling_time); +fprintf('Q2 PID exact xi=0.5 MATLAB: xi=%.6f wn=%.4f Mp=%.3f%% ts=%.4fs\n', ... + e11_res.q2_pid_exact_xi05.xi, e11_res.q2_pid_exact_xi05.wn, e11_res.q2_pid_exact_xi05.overshoot, e11_res.q2_pid_exact_xi05.settling_time); +fprintf('Q7 PD exact xi=0.50 dom MATLAB: xi=%.6f wn=%.4f res_ratio=%.6f Mp=%.3f%% ts=%.4fs\n', ... + e11_res.q7_pd_exact_xi05_dom.xi, e11_res.q7_pd_exact_xi05_dom.wn, e11_res.q7_pd_exact_xi05_dom.non_dominant_residue_ratio, ... + e11_res.q7_pd_exact_xi05_dom.overshoot, e11_res.q7_pd_exact_xi05_dom.settling_time); diff --git a/docs/validation/references/generate_matlab_reference.m b/docs/validation/references/generate_matlab_reference.m new file mode 100644 index 0000000..1a0b242 --- /dev/null +++ b/docs/validation/references/generate_matlab_reference.m @@ -0,0 +1,315 @@ +% MATLAB R2022b External Reference Generator for ControLAB Academic Validation +% Covers all 19 LGR cases (Exercicios_-_LGR.pdf) and 9 Controller cases (Projeto_de_controladores.pdf) + +s = tf('s'); + +lgr_cases = { + struct('id', 'LGR_1a_eq01', 'question', '1(a)', 'eq', 1, 'num', [1], 'den', [1 6 25 0], 'expr', '1/(s*(s^2+6*s+25))'), + struct('id', 'LGR_1b_eq02', 'question', '1(b)', 'eq', 2, 'num', [1 2], 'den', [1 2 3], 'expr', '(s+2)/(s^2+2*s+3)'), + struct('id', 'LGR_1c_eq03', 'question', '1(c)', 'eq', 3, 'num', [1], 'den', [1 4 5 0], 'expr', '1/(s*(s^2+4*s+5))'), + struct('id', 'LGR_2a_eq04', 'question', '2(a)', 'eq', 4, 'num', [1], 'den', [1 4 0], 'expr', '1/(s*(s+4))'), + struct('id', 'LGR_2b_eq05', 'question', '2(b)', 'eq', 5, 'num', [1], 'den', [1 3 2 0], 'expr', '1/(s*(s+1)*(s+2))'), + struct('id', 'LGR_2c_eq06', 'question', '2(c)', 'eq', 6, 'num', [1 2], 'den', [1 2 3], 'expr', '(s+2)/(s^2+2*s+3)'), + struct('id', 'LGR_2d_eq07', 'question', '2(d)', 'eq', 7, 'num', [1], 'den', [1 6 25 0], 'expr', '1/(s*(s^2+6*s+25))'), + struct('id', 'LGR_2e_eq08', 'question', '2(e)', 'eq', 8, 'num', [1 5 6], 'den', [1 1 0], 'expr', '(s+2)*(s+3)/(s*(s+1))'), + struct('id', 'LGR_2f_eq09', 'question', '2(f)', 'eq', 9, 'num', [1 2 8], 'den', [1 15 50 0], 'expr', '(s^2+2*s+8)/(s*(s+10)*(s+5))'), + struct('id', 'LGR_2g_eq10', 'question', '2(g)', 'eq', 10, 'num', [1 0 4], 'den', conv(conv([1 2],[1 2]), conv([1 5],[1 6])), 'expr', '(s^2+4)/((s+2)^2*(s+5)*(s+6))'), + struct('id', 'LGR_2h_eq11', 'question', '2(h)', 'eq', 11, 'num', [1], 'den', conv([1 1], [1 4 5]), 'expr', '1/((s+1)*(s^2+4*s+5))'), + struct('id', 'LGR_2i1_eq12', 'question', '2(i)-1', 'eq', 12, 'num', [1], 'den', [1 4 5 0], 'expr', '1/(s*(s^2+4*s+5))'), + struct('id', 'LGR_2i2_eq13', 'question', '2(i)-2', 'eq', 13, 'num', [1 2], 'den', conv([1 1], [1 6 10]), 'expr', '(s+2)/((s+1)*(s^2+6*s+10))'), + struct('id', 'LGR_3a_eq14', 'question', '3(a)', 'eq', 14, 'num', [1], 'den', [1 4 5 0], 'expr', '1/(s*(s^2+4*s+5))'), + struct('id', 'LGR_3b_eq15', 'question', '3(b)', 'eq', 15, 'num', [1], 'den', conv([1 1 0], [1 4 13]), 'expr', '1/(s*(s+1)*(s^2+4*s+13))'), + struct('id', 'LGR_3c_eq16', 'question', '3(c)', 'eq', 16, 'num', [1 1], 'den', [1 3.6 0 0], 'expr', '(s+1)/(s^2*(s+3.6))'), + struct('id', 'LGR_4a_eq17', 'question', '4(a)', 'eq', 17, 'num', [1 2], 'den', [1 4 13], 'expr', '(s+2)/(s^2+4*s+13)'), + struct('id', 'LGR_4b_eq18', 'question', '4(b)', 'eq', 18, 'num', conv([1 -2], [1 -4]), 'den', [1 6 25], 'expr', '(s-2)*(s-4)/(s^2+6*s+25)'), + struct('id', 'LGR_5_eq19', 'question', '5(a,b)', 'eq', 19, 'num', [1 1], 'den', [1 0 0 0], 'expr', '(s+1)/s^3') +}; + +sample_gains = [0, 1e-3, 0.01, 0.1, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 1000.0]; + +lgr_out = cell(1, length(lgr_cases)); +for idx = 1:length(lgr_cases) + c = lgr_cases{idx}; + sys = tf(c.num, c.den); + p = pole(sys); + z = zero(sys); + P = length(p); + Z = length(z); + n_branches = max(P, Z); + + if P > Z + centroid = (sum(real(p)) - sum(real(z))) / (P - Z); + asym_angles = zeros(1, P - Z); + for k = 0:(P - Z - 1) + asym_angles(k + 1) = mod((2*k + 1) * 180 / (P - Z), 360); + end + else + centroid = []; + asym_angles = []; + end + + % Breakaway polynomial: N'(s)D(s) - N(s)D'(s) = 0 + dN = polyder(c.num); + dD = polyder(c.den); + t1 = conv(dN, c.den); + t2 = conv(c.num, dD); + max_len = max(length(t1), length(t2)); + t1_pad = [zeros(1, max_len - length(t1)), t1]; + t2_pad = [zeros(1, max_len - length(t2)), t2]; + break_poly = t1_pad - t2_pad; + b_roots = roots(break_poly); + + valid_breaks = {}; + for br_i = 1:length(b_roots) + r = b_roots(br_i); + if abs(imag(r)) < 1e-6 + sr = real(r); + n_val = polyval(c.num, sr); + d_val = polyval(c.den, sr); + if abs(n_val) > 1e-8 + k_val = -d_val / n_val; + if k_val >= -1e-7 + valid_breaks{end+1} = struct('s', sr, 'K', max(0, k_val)); + end + end + end + end + + % Root locus at sample gains + r_mat = rlocus(sys, sample_gains); + locus_samples = cell(1, length(sample_gains)); + for g_i = 1:length(sample_gains) + col = r_mat(:, g_i); + locus_samples{g_i} = struct('K', sample_gains(g_i), 'roots_re', real(col)', 'roots_im', imag(col)'); + end + + % Departure angles for upper-half complex poles + dep_angles = {}; + for p_i = 1:length(p) + pt = p(p_i); + if imag(pt) > 1e-4 + sum_z = 0; + for z_i = 1:length(z) + sum_z = sum_z + atan2d(imag(pt - z(z_i)), real(pt - z(z_i))); + end + sum_p = 0; + for p_j = 1:length(p) + if abs(pt - p(p_j)) > 1e-4 + sum_p = sum_p + atan2d(imag(pt - p(p_j)), real(pt - p(p_j))); + end + end + ang = mod(180 + sum_z - sum_p + 180, 360) - 180; + dep_angles{end+1} = struct('pole_re', real(pt), 'pole_im', imag(pt), 'angle_deg', ang); + end + end + + % Arrival angles for upper-half complex zeros + arr_angles = {}; + for z_i = 1:length(z) + zt = z(z_i); + if imag(zt) > 1e-4 + sum_p = 0; + for p_i = 1:length(p) + sum_p = sum_p + atan2d(imag(zt - p(p_i)), real(zt - p(p_i))); + end + sum_z = 0; + for z_j = 1:length(z) + if abs(zt - z(z_j)) > 1e-4 + sum_z = sum_z + atan2d(imag(zt - z(z_j)), real(zt - z(z_j))); + end + end + ang = mod(180 + sum_p - sum_z + 180, 360) - 180; + arr_angles{end+1} = struct('zero_re', real(zt), 'zero_im', imag(zt), 'angle_deg', ang); + end + end + + lgr_out{idx} = struct( ... + 'id', c.id, ... + 'question', c.question, ... + 'eq', c.eq, ... + 'expr', c.expr, ... + 'num', c.num, ... + 'den', c.den, ... + 'P', P, ... + 'Z', Z, ... + 'branches', n_branches, ... + 'poles_re', real(p)', ... + 'poles_im', imag(p)', ... + 'zeros_re', real(z)', ... + 'zeros_im', imag(z)', ... + 'centroid', centroid, ... + 'asymptotes_deg', asym_angles, ... + 'break_points', {valid_breaks}, ... + 'departure_angles', {dep_angles}, ... + 'arrival_angles', {arr_angles}, ... + 'locus_samples', {locus_samples} ... + ); +end + +% Controller Design Questions (Projeto_de_controladores.pdf) +ctrl_cases = {}; + +% Q1: G(s) = 1/((s+0.2)*(s+0.644)), xi = 0.456, wn = 0.706 -> PI controller +G1 = 1 / ((s + 0.2) * (s + 0.644)); +xi1 = 0.456; wn1 = 0.706; +re1 = xi1 * wn1; im1 = wn1 * sqrt(1 - xi1^2); +sd1 = -re1 + 1i * im1; +% Angle from poles (0, -0.2, -0.644) +ang_p1 = atan2d(im1, -re1) + atan2d(im1, -re1 + 0.2) + atan2d(im1, -re1 + 0.644); +theta_z1 = mod(ang_p1 + 180, 360); +z1 = re1 + im1 / tand(theta_z1); +Kp1 = abs(sd1 * (sd1 + 0.2) * (sd1 + 0.644)) / abs(sd1 + z1); +Ki1 = Kp1 * z1; +Gc1 = Kp1 * (s + z1) / s; +T1 = feedback(Gc1 * G1, 1); +info1 = stepinfo(T1, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q1_PI', 'question', '1', 'controller_type', 'PI', ... + 'Kp', Kp1, 'Ki', Ki1, 'Kd', 0, 'z', z1, 'p', 0, ... + 'cl_poles_re', real(pole(T1))', 'cl_poles_im', imag(pole(T1))', ... + 'cl_zeros_re', real(zero(T1))', 'cl_zeros_im', imag(zero(T1))', ... + 'dcgain', dcgain(T1), 'overshoot', info1.Overshoot, ... + 'settling_time', info1.SettlingTime, 'rise_time', info1.RiseTime, 'peak_time', info1.PeakTime); + +% Q2: G(s) = 1/(s^2+1), xi = 0.5, ts(2%) = 4 -> PD controller (Kp=3, Kd=2, z=1.5) +G2 = 1 / (s^2 + 1); +Kp2 = 3; Kd2 = 2; z2 = 1.5; td2 = 2/3; +Gc2 = Kp2 + Kd2 * s; +T2 = feedback(Gc2 * G2, 1); +info2 = stepinfo(T2, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q2_PD', 'question', '2', 'controller_type', 'PD', ... + 'Kp', Kp2, 'Ki', 0, 'Kd', Kd2, 'z', z2, 'td', td2, ... + 'cl_poles_re', real(pole(T2))', 'cl_poles_im', imag(pole(T2))', ... + 'cl_zeros_re', real(zero(T2))', 'cl_zeros_im', imag(zero(T2))', ... + 'dcgain', dcgain(T2), 'overshoot', info2.Overshoot, ... + 'settling_time', info2.SettlingTime, 'rise_time', info2.RiseTime, 'peak_time', info2.PeakTime); + +% Q3: Inner loop 18/((2s+11)(2s+1)) with feedback 0.5, times 1/(30s), sd = -1 +- 1j -> PD controller +G3_inner = feedback(18 / ((2*s + 11)*(2*s + 1)), 0.5); +G3 = minreal(G3_inner * (1 / (30 * s))); +Kp3 = 160/3; Kd3 = 100/3; z3 = 1.6; td3 = 0.625; +Gc3 = Kp3 + Kd3 * s; +T3 = feedback(Gc3 * G3, 1); +info3 = stepinfo(T3, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q3_PD', 'question', '3', 'controller_type', 'PD', ... + 'Kp', Kp3, 'Ki', 0, 'Kd', Kd3, 'z', z3, 'td', td3, ... + 'cl_poles_re', real(pole(T3))', 'cl_poles_im', imag(pole(T3))', ... + 'cl_zeros_re', real(zero(T3))', 'cl_zeros_im', imag(zero(T3))', ... + 'dcgain', dcgain(T3), 'overshoot', info3.Overshoot, ... + 'settling_time', info3.SettlingTime, 'rise_time', info3.RiseTime, 'peak_time', info3.PeakTime); + +% Q4: G(s) = 5/(s+0.1), H(s) = 0.05, sd = -1 +- sqrt(3)j -> PI controller +G4 = 5 / (s + 0.1); +H4 = tf(0.05); +Kp4 = 7.6; Ki4 = 16.0; z4 = 40/19; +Gc4 = Kp4 + Ki4 / s; +T4 = feedback(Gc4 * G4, H4); +info4 = stepinfo(T4, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q4_PI', 'question', '4', 'controller_type', 'PI', ... + 'Kp', Kp4, 'Ki', Ki4, 'Kd', 0, 'z', z4, ... + 'cl_poles_re', real(pole(T4))', 'cl_poles_im', imag(pole(T4))', ... + 'cl_zeros_re', real(zero(T4))', 'cl_zeros_im', imag(zero(T4))', ... + 'dcgain', dcgain(T4), 'overshoot', info4.Overshoot, ... + 'settling_time', info4.SettlingTime, 'rise_time', info4.RiseTime, 'peak_time', info4.PeakTime); + +% Q5 (Mode 1 & 2: Pole cancellation / Equal zeros z1=z2=1): G(s) = 1/(s^3+10s^2+17s+8), ts=1, xi=0.4 +G5 = 1 / (s^3 + 10*s^2 + 17*s + 8); +Kp5 = 200; Ki5 = 100; Kd5 = 100; +Gc5 = (Kd5*s^2 + Kp5*s + Ki5) / s; +% Note: in ControLAB, improper Gc*G (or proper 3rd order plant + PID) -> deg(num)=2, deg(den)=4 -> strictly proper! +T5 = feedback(Gc5 * G5, 1); +T5_min = minreal(T5); +info5 = stepinfo(T5, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q5_PID_CANCEL_EQUAL', 'question', '5', 'controller_type', 'PID', ... + 'Kp', Kp5, 'Ki', Ki5, 'Kd', Kd5, 'z1', 1.0, 'z2', 1.0, ... + 'cl_poles_re', real(pole(T5))', 'cl_poles_im', imag(pole(T5))', ... + 'cl_zeros_re', real(zero(T5))', 'cl_zeros_im', imag(zero(T5))', ... + 'dcgain', dcgain(T5), 'overshoot', info5.Overshoot, ... + 'settling_time', info5.SettlingTime, 'rise_time', info5.RiseTime, 'peak_time', info5.PeakTime); + +% Q5 (Mode 3: Distinct PI-PD with zi = 0.4) +sd5 = -4 + 1i * sqrt(84); +zi5 = 0.4; +ang_p5 = atan2d(imag(sd5), real(sd5)) + 2*atan2d(imag(sd5), real(sd5)+1) + atan2d(imag(sd5), real(sd5)+8); +ang_zi5 = atan2d(imag(sd5), real(sd5)+zi5); +theta_zd5 = mod(ang_p5 - ang_zi5 + 180, 360); +zd5 = 4 + sqrt(84) / tand(theta_zd5); +K5_dist = abs(sd5 * (sd5+1)^2 * (sd5+8)) / abs((sd5+zi5)*(sd5+zd5)); +Kp5_dist = K5_dist * (zi5 + zd5); +Ki5_dist = K5_dist * zi5 * zd5; +Kd5_dist = K5_dist; +Gc5_dist = (Kd5_dist*s^2 + Kp5_dist*s + Ki5_dist) / s; +T5_dist = feedback(Gc5_dist * G5, 1); +info5_dist = stepinfo(T5_dist, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q5_PID_DISTINCT', 'question', '5', 'controller_type', 'PID', ... + 'Kp', Kp5_dist, 'Ki', Ki5_dist, 'Kd', Kd5_dist, 'z1', zi5, 'z2', zd5, ... + 'cl_poles_re', real(pole(T5_dist))', 'cl_poles_im', imag(pole(T5_dist))', ... + 'cl_zeros_re', real(zero(T5_dist))', 'cl_zeros_im', imag(zero(T5_dist))', ... + 'dcgain', dcgain(T5_dist), 'overshoot', info5_dist.Overshoot, ... + 'settling_time', info5_dist.SettlingTime, 'rise_time', info5_dist.RiseTime, 'peak_time', info5_dist.PeakTime); + +% Q6: G(s) = 1/(s*(s+2)^2), PD controller, xi = 0.5, wn = 2 -> Kp = 8, Kd = 4, z = 2 +G6 = 1 / (s * (s + 2)^2); +Kp6 = 8; Kd6 = 4; z6 = 2.0; td6 = 0.5; +Gc6 = Kp6 + Kd6 * s; +T6 = feedback(Gc6 * G6, 1); +T6_min = minreal(T6); +info6 = stepinfo(T6, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q6_PD', 'question', '6', 'controller_type', 'PD', ... + 'Kp', Kp6, 'Ki', 0, 'Kd', Kd6, 'z', z6, 'td', td6, ... + 'cl_poles_re', real(pole(T6))', 'cl_poles_im', imag(pole(T6))', ... + 'cl_poles_minreal_re', real(pole(T6_min))', 'cl_poles_minreal_im', imag(pole(T6_min))', ... + 'cl_zeros_re', real(zero(T6))', 'cl_zeros_im', imag(zero(T6))', ... + 'dcgain', dcgain(T6), 'overshoot', info6.Overshoot, ... + 'settling_time', info6.SettlingTime, 'rise_time', info6.RiseTime, 'peak_time', info6.PeakTime); + +% Q7: Inner loop 1/s with feedback 2 -> 1/(s+2), times 5/(s*(s+2)) -> 5/(s*(s+2)^2), xi=0.5, ts=4 -> PD +G7_inner = feedback(1/s, 2); +G7 = G7_inner * (5 / (s * (s + 2))); +Kp7 = 1.6; Kd7 = 0.8; z7 = 2.0; td7 = 0.5; +Gc7 = Kp7 + Kd7 * s; +T7 = feedback(Gc7 * G7, 1); +info7 = stepinfo(T7, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q7_PD', 'question', '7', 'controller_type', 'PD', ... + 'Kp', Kp7, 'Ki', 0, 'Kd', Kd7, 'z', z7, 'td', td7, ... + 'cl_poles_re', real(pole(T7))', 'cl_poles_im', imag(pole(T7))', ... + 'cl_zeros_re', real(zero(T7))', 'cl_zeros_im', imag(zero(T7))', ... + 'dcgain', dcgain(T7), 'overshoot', info7.Overshoot, ... + 'settling_time', info7.SettlingTime, 'rise_time', info7.RiseTime, 'peak_time', info7.PeakTime); + +% Q8: G(s) = -7.2/(5s+1), ts=4, Mp=25% -> PI controller +G8 = -7.2 / (5*s + 1); +ln_mp8 = log(0.25); +xi8 = -ln_mp8 / sqrt(pi^2 + ln_mp8^2); +wn8 = 1.0 / xi8; +Kp8 = -1.25; +z8 = wn8^2 / 1.8; +Ki8 = Kp8 * z8; +Gc8 = Kp8 + Ki8 / s; +T8 = feedback(Gc8 * G8, 1); +info8 = stepinfo(T8, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q8_PI', 'question', '8', 'controller_type', 'PI', ... + 'Kp', Kp8, 'Ki', Ki8, 'Kd', 0, 'z', z8, 'xi', xi8, 'wn', wn8, ... + 'cl_poles_re', real(pole(T8))', 'cl_poles_im', imag(pole(T8))', ... + 'cl_zeros_re', real(zero(T8))', 'cl_zeros_im', imag(zero(T8))', ... + 'dcgain', dcgain(T8), 'overshoot', info8.Overshoot, ... + 'settling_time', info8.SettlingTime, 'rise_time', info8.RiseTime, 'peak_time', info8.PeakTime); + +% Q9: G(s) = 1/s^2 (with wn=1, xi=0 in inner/forward diagram), xi=0.5, ts=4 -> PD controller (Kp=4, Kd=2, td=0.5, z=2) +G9 = 1 / s^2; +Kp9 = 4.0; Kd9 = 2.0; z9 = 2.0; td9 = 0.5; +Gc9 = Kp9 + Kd9 * s; +T9 = feedback(Gc9 * G9, 1); +info9 = stepinfo(T9, 'SettlingTimeThreshold', 0.02); +ctrl_cases{end+1} = struct('id', 'CTRL_Q9_PD', 'question', '9', 'controller_type', 'PD', ... + 'Kp', Kp9, 'Ki', 0, 'Kd', Kd9, 'z', z9, 'td', td9, ... + 'cl_poles_re', real(pole(T9))', 'cl_poles_im', imag(pole(T9))', ... + 'cl_zeros_re', real(zero(T9))', 'cl_zeros_im', imag(zero(T9))', ... + 'dcgain', dcgain(T9), 'overshoot', info9.Overshoot, ... + 'settling_time', info9.SettlingTime, 'rise_time', info9.RiseTime, 'peak_time', info9.PeakTime); + +out = struct('matlab_version', version, 'lgr', {lgr_out}, 'controllers', {ctrl_cases}); +json_text = jsonencode(out, 'PrettyPrint', true); +fid = fopen('matlab_r2022b_reference.json', 'w'); +fwrite(fid, json_text, 'char'); +fclose(fid); +disp('MATLAB reference JSON generated successfully.'); diff --git a/docs/validation/references/matlab_r2022b_etapa10_reference.json b/docs/validation/references/matlab_r2022b_etapa10_reference.json new file mode 100644 index 0000000..28040fc --- /dev/null +++ b/docs/validation/references/matlab_r2022b_etapa10_reference.json @@ -0,0 +1,229 @@ +{ + "matlab_version": "9.13.0.2049777 (R2022b)", + "q2_pid_classic_equal": { + "overshoot": 13.969602471663411, + "settling_time": 7.6389489789677878, + "rise_time": 0.47549697621733017, + "peak_time": 1.0131374409171554, + "dcgain": 1, + "poles_re": [ + -0.99999999999999978, + -0.99999999999999978, + -0.36851709182133013 + ], + "poles_im": [ + 1.7320508075688776, + -1.7320508075688776, + 0 + ], + "zeros_re": [ + -0.78889744907202219, + -0.78889744907202219 + ], + "zeros_im": [ + 0, + 0 + ] + }, + "q8_reference": { + "overshoot": 0, + "settling_time": 2.7167183648192852, + "dcgain": 1, + "disturbance_dcgain": 0, + "disturbance_peak_abs": 0.72731126540157143, + "max_waveform_err_vs_analytic": 1.1879386363489175E-14, + "unreduced_poles_re": [ + -1.44, + -0.20000000000000004 + ], + "minreal_poles_re": -1.44, + "perturbations": { + "k_plus_10": { + "stable": true, + "overshoot": 0, + "settling_time": 2.469743968017525, + "dcgain": 1, + "poles_re": [ + -1.5840000000000003, + -0.2 + ], + "poles_im": [ + 0, + 0 + ] + }, + "k_minus_10": { + "stable": true, + "overshoot": 0, + "settling_time": 3.0185759609102862, + "dcgain": 1, + "poles_re": [ + -1.296, + -0.20000000000000004 + ], + "poles_im": [ + 0, + 0 + ] + }, + "tau_plus_10": { + "stable": true, + "overshoot": 0.56495477103724046, + "settling_time": 2.7019416904239519, + "dcgain": 1, + "poles_re": [ + -1.2875655096682024, + -0.20334358124088828 + ], + "poles_im": [ + 0, + 0 + ] + }, + "tau_minus_10": { + "stable": true, + "overshoot": 0, + "settling_time": 2.8321367837510172, + "dcgain": 1, + "poles_re": [ + -1.6253403857772528, + -0.19688183644496909 + ], + "poles_im": [ + 0, + 0 + ] + } + } + }, + "refined": { + "q2_pd_refined": { + "stable": true, + "overshoot": 16.25579893845428, + "settling_time": 3.9991832981053674, + "rise_time": 0.1023520487237265, + "peak_time": 0.39696313063995403, + "dcgain": 0.86817936465914525, + "poles_re": [ + -12.761102514534016, + -0.59446789092064656 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": -0.49313249061585013, + "zeros_im": 0 + }, + "q2_pid_refined": { + "stable": true, + "overshoot": 15.343038104083618, + "settling_time": 3.99999471064722, + "rise_time": 0.23912754193745128, + "peak_time": 0.6113753998467738, + "dcgain": 1, + "poles_re": [ + -2.4857168962912333, + -2.4857168962912333, + -0.570810426708859 + ], + "poles_im": [ + 1.7550281156547052, + -1.7550281156547052, + 0 + ], + "zeros_re": [ + -1.2215455410206053, + -0.78065031695332832 + ], + "zeros_im": [ + 0, + 0 + ] + }, + "q5_pid_refined": { + "stable": true, + "overshoot": 5.9730452506324916, + "settling_time": 0.99991150559017916, + "rise_time": 0.33857018896729407, + "peak_time": 0.70203160190250569, + "dcgain": 1, + "poles_re": [ + -4.0014634752050657, + -4.0014634752050657, + -1.0000271772606102, + -0.99704587232926256 + ], + "poles_im": [ + 4.4715124399710708, + -4.4715124399710708, + 0, + 0 + ], + "zeros_re": [ + -1.000027117726038, + -0.997613845775404 + ], + "zeros_im": [ + 0, + 0 + ] + }, + "q7_pd_refined": { + "stable": true, + "overshoot": 0.18821316105128716, + "settling_time": 4.0002762978460487, + "rise_time": 2.4650272933287942, + "peak_time": 6.0381514399654295, + "dcgain": 1, + "poles_re": [ + -1.9255136227658696, + -1.0372431886170648, + -1.0372431886170648 + ], + "poles_im": [ + 0, + 0.51971432201871892, + -0.51971432201871892 + ], + "zeros_re": -1.9334835938853774, + "zeros_im": 0 + }, + "q8_pi_refined": { + "stable": true, + "overshoot": 0, + "settling_time": 3.9889792045989809, + "rise_time": 2.2401959241530354, + "peak_time": 10.753153077596171, + "dcgain": 1, + "poles_re": [ + -0.98072069185755784, + -0.20000000000000004 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": -0.2, + "zeros_im": 0 + }, + "q9_pd_refined": { + "stable": true, + "overshoot": 15.020194735877968, + "settling_time": 3.9901011264932635, + "rise_time": 0.57373096779191368, + "peak_time": 1.5471605831256925, + "dcgain": 1, + "poles_re": [ + -1.2203773783069432, + -1.2203773783069432 + ], + "poles_im": [ + 0.50650857043349751, + -0.50650857043349751 + ], + "zeros_re": -0.7153, + "zeros_im": 0 + } + } +} diff --git a/docs/validation/references/matlab_r2022b_etapa11_reference.json b/docs/validation/references/matlab_r2022b_etapa11_reference.json new file mode 100644 index 0000000..4b6eaee --- /dev/null +++ b/docs/validation/references/matlab_r2022b_etapa11_reference.json @@ -0,0 +1,353 @@ +{ + "matlab_version": "9.13.0.2049777 (R2022b)", + "etapa10_xi_audit": { + "q2_pd_e10_full": { + "xi": 1, + "wn": 0.59446789092064656, + "overshoot": 16.25579893845428, + "settling_time": 3.9991832981053674, + "poles_re": [ + -12.761102514534016, + -0.59446789092064656 + ], + "poles_im": [ + 0, + 0 + ] + }, + "q2_pd_e10_round": { + "xi": 1, + "wn": 0.594469264292792, + "overshoot": 16.255731045583445, + "settling_time": 3.9991673229455462, + "poles_re": [ + -12.761130735707209, + -0.594469264292792 + ], + "poles_im": [ + 0, + 0 + ] + }, + "q2_pid_e10_full": { + "xi": 0.81690524042219992, + "wn": 3.042846064993467, + "overshoot": 15.343038104083618, + "settling_time": 3.99999471064722, + "poles_re": [ + -2.4857168962912333, + -2.4857168962912333, + -0.570810426708859 + ], + "poles_im": [ + 1.7550281156547052, + -1.7550281156547052, + 0 + ] + }, + "q2_pid_e10_round": { + "xi": 0.8168949304835561, + "wn": 3.0428593761884546, + "overshoot": 15.343252183723454, + "settling_time": 3.9999806897592389, + "poles_re": [ + -2.4856963985827045, + -2.4856963985827045, + -0.57080720283458586 + ], + "poles_im": [ + 1.755080225326171, + -1.755080225326171, + 0 + ] + }, + "q5_pid_e10_full": { + "xi": 0.6668537745309866, + "wn": 6.0005110985828729, + "overshoot": 5.9730452506324916, + "settling_time": 0.99991150559017916, + "poles_re": [ + -4.0014634752050657, + -4.0014634752050657, + -1.0000271772606102, + -0.99704587232926256 + ], + "poles_im": [ + 4.4715124399710708, + -4.4715124399710708, + 0, + 0 + ] + }, + "q5_pid_e10_round": { + "xi": 0.66685400713236709, + "wn": 6.0005061235708084, + "overshoot": 5.9730608273163011, + "settling_time": 0.99991284284940385, + "poles_re": [ + -4.0014615533255, + -4.0014615533255, + -1.0009015038885316, + -0.99617538946045558 + ], + "poles_im": [ + 4.47150748364225, + -4.47150748364225, + 0, + 0 + ] + }, + "q7_pd_e10_full": { + "xi": 0.89405012364351411, + "wn": 1.1601622338465738, + "overshoot": 0.18821316105128716, + "settling_time": 4.0002762978460487, + "poles_re": [ + -1.9255136227658696, + -1.0372431886170648, + -1.0372431886170648 + ], + "poles_im": [ + 0, + 0.51971432201871892, + -0.51971432201871892 + ] + }, + "q7_pd_e10_round": { + "xi": 0.89414666618995742, + "wn": 1.1602134919740597, + "overshoot": 0.18755598477522284, + "settling_time": 4.0010626777298857, + "poles_re": [ + -1.9251979481655725, + -1.0374010259172144, + -1.0374010259172144 + ], + "poles_im": [ + 0, + 0.51951367487733446, + -0.51951367487733446 + ] + }, + "q9_pd_e10_full": { + "xi": 0.92360859123145289, + "wn": 1.3213144506157166, + "overshoot": 15.020194735877968, + "settling_time": 3.9901011264932635, + "poles_re": [ + -1.2203773783069432, + -1.2203773783069432 + ], + "poles_im": [ + 0.50650857043349751, + -0.50650857043349751 + ] + }, + "q9_pd_e10_round": { + "xi": 0.92361827301369581, + "wn": 1.3213250924734607, + "overshoot": 15.019989729307092, + "settling_time": 3.990080780558, + "poles_re": [ + -1.2203999999999997, + -1.2203999999999997 + ], + "poles_im": [ + 0.50648182593258, + -0.50648182593258 + ] + } + }, + "etapa11_refined": { + "q5_pid_exact_xi04": { + "stable": true, + "xi": 0.40000000334313146, + "wn": 8.7239450380071322, + "non_dominant_residue_ratio": 0.10558448406785578, + "overshoot": 28.836465120777266, + "settling_time": 0.99699147589719139, + "rise_time": 0.16046616891969182, + "peak_time": 0.38271084267389643, + "dcgain": 1, + "poles_re": [ + -3.4895780443681481, + -3.4895780443681481, + -2.7490513545669435, + -0.27179255669676805 + ], + "poles_im": [ + 7.9956276863316376, + -7.9956276863316376, + 0, + 0 + ], + "zeros_re": [ + -2.5282630742475654, + -0.27789140766329318 + ], + "zeros_im": [ + 0, + 0 + ] + }, + "q2_pid_exact_xi05": { + "stable": true, + "xi": 0.49999181482492888, + "wn": 1.3909130935713316, + "non_dominant_residue_ratio": 2.3089544372152626, + "overshoot": 13.55848089570253, + "settling_time": 3.9999996672062839, + "rise_time": 0.36847308214252061, + "peak_time": 0.93103098230371506, + "dcgain": 1, + "poles_re": [ + -2.3742300001709156, + -0.69544516191848627, + -0.69544516191848627 + ], + "poles_im": [ + 0, + 1.2045726464735709, + -1.2045726464735709 + ], + "zeros_re": [ + -0.5626556926551598, + -0.5626556926551598 + ], + "zeros_im": [ + 0.95045982307510246, + -0.95045982307510246 + ] + }, + "q7_pd_exact_xi05_dom": { + "stable": true, + "xi": 0.504413649981323, + "wn": 2.0221889629882877, + "non_dominant_residue_ratio": 0.00035209778888584727, + "overshoot": 15.948425565656677, + "settling_time": 3.9715516463013469, + "rise_time": 0.815219777732575, + "peak_time": 1.805914185687187, + "dcgain": 1, + "poles_re": [ + -1.9599605684542594, + -1.0200197157728685, + -1.0200197157728685 + ], + "poles_im": [ + 0, + 1.7460836123926833, + -1.7460836123926833 + ], + "zeros_re": -1.9607292562105672, + "zeros_im": 0 + }, + "q2_pd_xi_at_least": { + "stable": true, + "xi": 1, + "wn": 0.57729138919794865, + "non_dominant_residue_ratio": null, + "overshoot": 15.509802371067849, + "settling_time": 3.9999420093108542, + "rise_time": 0.097451211674090057, + "peak_time": 0.37623850801997039, + "dcgain": 0.87364150143204355, + "poles_re": [ + -13.708832292182088, + -0.57729138919794865 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": -0.48396548934032513, + "zeros_im": 0 + }, + "q8_pi_refined_e11": { + "stable": true, + "xi": 1, + "wn": 0.28521187738134146, + "non_dominant_residue_ratio": null, + "overshoot": 1.8542686605597769, + "settling_time": 3.9916461306505542, + "rise_time": 2.6506247802619831, + "peak_time": 6.9304989516311188, + "dcgain": 1, + "poles_re": [ + -0.637899725460104, + -0.28521187738134146 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": -0.251602349574539, + "zeros_im": 0 + }, + "q9_pd_xi_at_least": { + "stable": true, + "xi": 1, + "wn": 0.050001746355966888, + "non_dominant_residue_ratio": null, + "overshoot": 2.0082910105472251, + "settling_time": 3.9991413350460494, + "rise_time": 0.97210132473948174, + "peak_time": 3.6916949539469521, + "dcgain": 1, + "poles_re": [ + -2.0707514039225412, + -0.050001746355966888 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": -0.048822837514870453, + "zeros_im": 0 + } + }, + "q5_exact_robustness": { + "gain_plus_5": { + "stable": true, + "xi": 0.39035207617030732, + "overshoot": 29.730442459879104, + "settling_time": 0.96598321362511164, + "dcgain": 1 + }, + "gain_minus_5": { + "stable": true, + "xi": 0.41039936413461031, + "overshoot": 27.876572385521659, + "settling_time": 1.0313883595083548, + "dcgain": 1 + }, + "gain_plus_10": { + "stable": true, + "xi": 0.381369507384708, + "overshoot": 30.623763122300794, + "settling_time": 0.93787954436306087, + "dcgain": 1 + }, + "gain_minus_10": { + "stable": true, + "xi": 0.42165251742140708, + "overshoot": 26.860575530504114, + "settling_time": 1.0702640547722742, + "dcgain": 1 + }, + "pole1_plus_5": { + "stable": true, + "xi": 0.40488057560172164, + "overshoot": 27.518310064702646, + "settling_time": 1.0038991234269603, + "dcgain": 1 + }, + "pole1_minus_5": { + "stable": true, + "xi": 0.3950333901440139, + "overshoot": 30.150415011733124, + "settling_time": 0.991688248112747, + "dcgain": 1 + } + } +} diff --git a/docs/validation/references/matlab_r2022b_reference.json b/docs/validation/references/matlab_r2022b_reference.json new file mode 100644 index 0000000..ca962f7 --- /dev/null +++ b/docs/validation/references/matlab_r2022b_reference.json @@ -0,0 +1,4342 @@ +{ + "matlab_version": "9.13.0.2049777 (R2022b)", + "lgr": [ + { + "id": "LGR_1a_eq01", + "question": "1(a)", + "eq": 1, + "expr": "1/(s*(s^2+6*s+25))", + "num": 1, + "den": [ + 1, + 6, + 25, + 0 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + 0, + -3.0000000000000004, + -3.0000000000000004 + ], + "poles_im": [ + 0, + 4, + -4 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -2.0000000000000004, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [], + "departure_angles": [ + { + "pole_re": -3.0000000000000004, + "pole_im": 4, + "angle_deg": -36.869897645844048 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -3.0000000000000004, + -3.0000000000000004 + ], + "roots_im": [ + 0, + 4, + -4 + ] + }, + { + "K": 0.001, + "roots_re": [ + -4.0000384004812869E-5, + -2.999979999807997, + -2.999979999807997 + ], + "roots_im": [ + 0, + 3.9999849999778743, + -3.9999849999778743 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.00040003840481334048, + -2.9997999807975906, + -2.9997999807975906 + ], + "roots_im": [ + 0, + 3.9998499977884925, + -3.9998499977884925 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.0040038448182096436, + -2.997998077590895, + -2.997998077590895 + ], + "roots_im": [ + 0, + 3.9984997797455692, + -3.9984997797455692 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.020096604988219042, + -2.9899516975058886, + -2.9899516975058886 + ], + "roots_im": [ + 0, + 3.9924945948848047, + -3.9924945948848047 + ] + }, + { + "K": 1, + "roots_re": [ + -0.040388867150844991, + -2.9798055664245782, + -2.9798055664245782 + ], + "roots_im": [ + 0, + 3.98497890132304, + -3.98497890132304 + ] + }, + { + "K": 2, + "roots_re": [ + -0.0815753762102226, + -2.95921231189489, + -2.95921231189489 + ], + "roots_im": [ + 0, + 3.9699199964070089, + -3.9699199964070089 + ] + }, + { + "K": 5, + "roots_re": [ + -0.21023612367551775, + -2.894881938162241, + -2.894881938162241 + ], + "roots_im": [ + 0, + 3.9245943802827612, + -3.9245943802827612 + ] + }, + { + "K": 10, + "roots_re": [ + -0.44376745611806312, + -2.7781162719409682, + -2.7781162719409682 + ], + "roots_im": [ + 0, + 3.84920703495901, + -3.84920703495901 + ] + }, + { + "K": 20, + "roots_re": [ + -0.99999999999999978, + -2.5, + -2.5 + ], + "roots_im": [ + 0, + 3.7080992435478319, + -3.7080992435478319 + ] + }, + { + "K": 50, + "roots_re": [ + -3.1220913247724318, + -1.4389543376137843, + -1.4389543376137843 + ], + "roots_im": [ + 0, + 3.7342089799376743, + -3.7342089799376743 + ] + }, + { + "K": 100, + "roots_re": [ + -5.0000000000000009, + -0.49999999999999906, + -0.49999999999999906 + ], + "roots_im": [ + 0, + 4.4440972086577935, + -4.4440972086577935 + ] + }, + { + "K": 1000, + "roots_re": [ + -11.447298641510786, + 2.7236493207553902, + 2.7236493207553902 + ], + "roots_im": [ + 0, + 8.94083825580234, + -8.94083825580234 + ] + } + ] + }, + { + "id": "LGR_1b_eq02", + "question": "1(b)", + "eq": 2, + "expr": "(s+2)/(s^2+2*s+3)", + "num": [ + 1, + 2 + ], + "den": [ + 1, + 2, + 3 + ], + "P": 2, + "Z": 1, + "branches": 2, + "poles_re": [ + -1, + -1 + ], + "poles_im": [ + 1.4142135623730949, + -1.4142135623730949 + ], + "zeros_re": -2, + "zeros_im": 0, + "centroid": 0, + "asymptotes_deg": 180, + "break_points": [ + { + "s": -3.7320508075688772, + "K": 5.4641016151377544 + } + ], + "departure_angles": [ + { + "pole_re": -1, + "pole_im": 1.4142135623730949, + "angle_deg": 144.73561031724535 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -1, + -1 + ], + "roots_im": [ + 1.4142135623730949, + -1.4142135623730949 + ] + }, + { + "K": 0.001, + "roots_re": [ + -1.0005000000000002, + -1.0005000000000002 + ], + "roots_im": [ + 1.414566983214298, + -1.414566983214298 + ] + }, + { + "K": 0.01, + "roots_re": [ + -1.005, + -1.005 + ], + "roots_im": [ + 1.4177358710281689, + -1.4177358710281689 + ] + }, + { + "K": 0.1, + "roots_re": [ + -1.0500000000000003, + -1.0500000000000003 + ], + "roots_im": [ + 1.4482748357960238, + -1.4482748357960238 + ] + }, + { + "K": 0.5, + "roots_re": [ + -1.25, + -1.25 + ], + "roots_im": [ + 1.5612494995995994, + -1.5612494995995994 + ] + }, + { + "K": 1, + "roots_re": [ + -1.5000000000000002, + -1.5000000000000002 + ], + "roots_im": [ + 1.6583123951777, + -1.6583123951777 + ] + }, + { + "K": 2, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 1.7320508075688772, + -1.7320508075688772 + ] + }, + { + "K": 5, + "roots_re": [ + -3.5, + -3.5 + ], + "roots_im": [ + 0.86602540378443971, + -0.86602540378443971 + ] + }, + { + "K": 10, + "roots_re": [ + -2.3944487245360109, + -9.6055512754639878 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -2.1682391336721532, + -19.831760866327848 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -2.0625815928283528, + -49.937418407171648 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -2.0306218132188247, + -99.969378186781171 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -2.0030060210783196, + -999.99699397892164 + ], + "roots_im": [ + 0, + 0 + ] + } + ] + }, + { + "id": "LGR_1c_eq03", + "question": "1(c)", + "eq": 3, + "expr": "1/(s*(s^2+4*s+5))", + "num": 1, + "den": [ + 1, + 4, + 5, + 0 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + 0, + -2.0000000000000004, + -2.0000000000000004 + ], + "poles_im": [ + 0, + 1.0000000000000004, + -1.0000000000000004 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -1.3333333333333337, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [ + { + "s": -1.6666666666666661, + "K": 1.8518518518518521 + }, + { + "s": -1.0000000000000004, + "K": 2 + } + ], + "departure_angles": [ + { + "pole_re": -2.0000000000000004, + "pole_im": 1.0000000000000004, + "angle_deg": -63.434948822921996 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -2.0000000000000004, + -2.0000000000000004 + ], + "roots_im": [ + 0, + 1.0000000000000004, + -1.0000000000000004 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.000200032008642817, + -1.9998999839956777, + -1.9998999839956777 + ], + "roots_im": [ + 0, + 0.99979996298875562, + -0.99979996298875562 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.002003208668261714, + -1.9989983956658688, + -1.9989983956658688 + ], + "roots_im": [ + 0, + 0.99799628871915314, + -0.99799628871915314 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.020328932136253565, + -1.9898355339318745, + -1.9898355339318745 + ], + "roots_im": [ + 0, + 0.97961833631207784, + -0.97961833631207784 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.10929524412788269, + -1.9453523779360573, + -1.9453523779360573 + ], + "roots_im": [ + 0, + 0.889026770989471, + -0.889026770989471 + ] + }, + { + "K": 1, + "roots_re": [ + -0.24512233375330725, + -1.8774388331233451, + -1.8774388331233451 + ], + "roots_im": [ + 0, + 0.7448617666197459, + -0.7448617666197459 + ] + }, + { + "K": 2, + "roots_re": [ + -0.99999999999999967, + -2, + -0.99999999999999967 + ], + "roots_im": [ + 2.8326346177791904E-8, + 0, + -2.8326346177791904E-8 + ] + }, + { + "K": 5, + "roots_re": [ + -0.56814673609040578, + -2.8637065278191871, + -0.56814673609040578 + ], + "roots_im": [ + 1.1929787309366844, + 0, + -1.1929787309366844 + ] + }, + { + "K": 10, + "roots_re": [ + -0.30257066306696745, + -3.3948586738660671, + -0.30257066306696745 + ], + "roots_im": [ + 1.689402768409777, + 0, + -1.689402768409777 + ] + }, + { + "K": 20, + "roots_re": [ + 6.106226635438361E-16, + -3.9999999999999982, + 6.106226635438361E-16 + ], + "roots_im": [ + 2.2360679774997911, + 0, + -2.2360679774997911 + ] + }, + { + "K": 50, + "roots_re": [ + 0.49999999999999956, + -5, + 0.49999999999999956 + ], + "roots_im": [ + 3.1224989991991996, + 0, + -3.1224989991991996 + ] + }, + { + "K": 100, + "roots_re": [ + 0.98451228491057385, + -5.9690245698211459, + 0.98451228491057385 + ], + "roots_im": [ + 3.9728946118295294, + 0, + -3.9728946118295294 + ] + }, + { + "K": 1000, + "roots_re": [ + 3.6690138516344364, + -11.338027703268885, + 3.6690138516344364 + ], + "roots_im": [ + 8.6450621017741476, + 0, + -8.6450621017741476 + ] + } + ] + }, + { + "id": "LGR_2a_eq04", + "question": "2(a)", + "eq": 4, + "expr": "1/(s*(s+4))", + "num": 1, + "den": [ + 1, + 4, + 0 + ], + "P": 2, + "Z": 0, + "branches": 2, + "poles_re": [ + 0, + -4 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -2, + "asymptotes_deg": [ + 90, + 270 + ], + "break_points": [ + { + "s": -2, + "K": 4 + } + ], + "departure_angles": [], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -4 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.00025001562695343022, + -3.9997499843730466 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.0025015644561821081, + -3.9974984355438181 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.025158234186850096, + -3.9748417658131503 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.12917130661302931, + -3.8708286933869709 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -0.2679491924311227, + -3.7320508075688772 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -0.585786437626905, + -3.4142135623730949 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -2.0000000000000004, + -2.0000000000000004 + ], + "roots_im": [ + 1.0000000000000004, + -1.0000000000000004 + ] + }, + { + "K": 10, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 2.4494897427831783, + -2.4494897427831783 + ] + }, + { + "K": 20, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 4, + -4 + ] + }, + { + "K": 50, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 6.7823299831252681, + -6.7823299831252681 + ] + }, + { + "K": 100, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 9.7979589711327133, + -9.7979589711327133 + ] + }, + { + "K": 1000, + "roots_re": [ + -2.0000000000000009, + -2.0000000000000009 + ], + "roots_im": [ + 31.559467676119, + -31.559467676119 + ] + } + ] + }, + { + "id": "LGR_2b_eq05", + "question": "2(b)", + "eq": 5, + "expr": "1/(s*(s+1)*(s+2))", + "num": 1, + "den": [ + 1, + 3, + 2, + 0 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + 0, + -2, + -1 + ], + "poles_im": [ + 0, + 0, + 0 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -1, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [ + { + "s": -0.42264973081037427, + "K": 0.38490017945975047 + } + ], + "departure_angles": [], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -1, + -2 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.00050037550082181539, + -0.998999998999996, + -2.0004996254991831 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.0050380083561189139, + -0.98999899969988014, + -2.0049629919440011 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.054350726076408555, + -0.89896874211899, + -2.0466805318046042 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.40425605802344045, + -0.40425605802344045, + -2.19148788395312 + ], + "roots_im": [ + 0.25442588941636912, + -0.25442588941636912, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -0.33764102137762708, + -0.33764102137762708, + -2.3247179572447463 + ], + "roots_im": [ + 0.56227951206230153, + -0.56227951206230153, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -0.2393101465977161, + -0.2393101465977161, + -2.52137970680457 + ], + "roots_im": [ + 0.857873626595178, + -0.857873626595178, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -0.047919570432539721, + -0.047919570432539721, + -2.9041608591349259 + ], + "roots_im": [ + 1.3112480440771224, + -1.3112480440771224, + 0 + ] + }, + { + "K": 10, + "roots_re": [ + 0.15445365988254636, + 0.15445365988254636, + -3.3089073197650896 + ], + "roots_im": [ + 1.7315570329759917, + -1.7315570329759917, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + 0.41856933431196175, + 0.41856933431196175, + -3.8371386686239193 + ], + "roots_im": [ + 2.2443299375873544, + -2.2443299375873544, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + 0.8872471697907256, + 0.8872471697907256, + -4.7744943395814445 + ], + "roots_im": [ + 3.1120902364245944, + -3.1120902364245944, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + 1.3566988407780185, + 1.3566988407780185, + -5.713397681556037 + ], + "roots_im": [ + 3.95753563197773, + -3.95753563197773, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + 4.0166666051440325, + 4.0166666051440325, + -11.033333210288045 + ], + "roots_im": [ + 8.6313864171117931, + -8.6313864171117931, + 0 + ] + } + ] + }, + { + "id": "LGR_2c_eq06", + "question": "2(c)", + "eq": 6, + "expr": "(s+2)/(s^2+2*s+3)", + "num": [ + 1, + 2 + ], + "den": [ + 1, + 2, + 3 + ], + "P": 2, + "Z": 1, + "branches": 2, + "poles_re": [ + -1, + -1 + ], + "poles_im": [ + 1.4142135623730949, + -1.4142135623730949 + ], + "zeros_re": -2, + "zeros_im": 0, + "centroid": 0, + "asymptotes_deg": 180, + "break_points": [ + { + "s": -3.7320508075688772, + "K": 5.4641016151377544 + } + ], + "departure_angles": [ + { + "pole_re": -1, + "pole_im": 1.4142135623730949, + "angle_deg": 144.73561031724535 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -1, + -1 + ], + "roots_im": [ + 1.4142135623730949, + -1.4142135623730949 + ] + }, + { + "K": 0.001, + "roots_re": [ + -1.0005000000000002, + -1.0005000000000002 + ], + "roots_im": [ + 1.414566983214298, + -1.414566983214298 + ] + }, + { + "K": 0.01, + "roots_re": [ + -1.005, + -1.005 + ], + "roots_im": [ + 1.4177358710281689, + -1.4177358710281689 + ] + }, + { + "K": 0.1, + "roots_re": [ + -1.0500000000000003, + -1.0500000000000003 + ], + "roots_im": [ + 1.4482748357960238, + -1.4482748357960238 + ] + }, + { + "K": 0.5, + "roots_re": [ + -1.25, + -1.25 + ], + "roots_im": [ + 1.5612494995995994, + -1.5612494995995994 + ] + }, + { + "K": 1, + "roots_re": [ + -1.5000000000000002, + -1.5000000000000002 + ], + "roots_im": [ + 1.6583123951777, + -1.6583123951777 + ] + }, + { + "K": 2, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 1.7320508075688772, + -1.7320508075688772 + ] + }, + { + "K": 5, + "roots_re": [ + -3.5, + -3.5 + ], + "roots_im": [ + 0.86602540378443971, + -0.86602540378443971 + ] + }, + { + "K": 10, + "roots_re": [ + -2.3944487245360109, + -9.6055512754639878 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -2.1682391336721532, + -19.831760866327848 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -2.0625815928283528, + -49.937418407171648 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -2.0306218132188247, + -99.969378186781171 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -2.0030060210783196, + -999.99699397892164 + ], + "roots_im": [ + 0, + 0 + ] + } + ] + }, + { + "id": "LGR_2d_eq07", + "question": "2(d)", + "eq": 7, + "expr": "1/(s*(s^2+6*s+25))", + "num": 1, + "den": [ + 1, + 6, + 25, + 0 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + 0, + -3.0000000000000004, + -3.0000000000000004 + ], + "poles_im": [ + 0, + 4, + -4 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -2.0000000000000004, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [], + "departure_angles": [ + { + "pole_re": -3.0000000000000004, + "pole_im": 4, + "angle_deg": -36.869897645844048 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -3.0000000000000004, + -3.0000000000000004 + ], + "roots_im": [ + 0, + 4, + -4 + ] + }, + { + "K": 0.001, + "roots_re": [ + -4.0000384004812869E-5, + -2.999979999807997, + -2.999979999807997 + ], + "roots_im": [ + 0, + 3.9999849999778743, + -3.9999849999778743 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.00040003840481334048, + -2.9997999807975906, + -2.9997999807975906 + ], + "roots_im": [ + 0, + 3.9998499977884925, + -3.9998499977884925 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.0040038448182096436, + -2.997998077590895, + -2.997998077590895 + ], + "roots_im": [ + 0, + 3.9984997797455692, + -3.9984997797455692 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.020096604988219042, + -2.9899516975058886, + -2.9899516975058886 + ], + "roots_im": [ + 0, + 3.9924945948848047, + -3.9924945948848047 + ] + }, + { + "K": 1, + "roots_re": [ + -0.040388867150844991, + -2.9798055664245782, + -2.9798055664245782 + ], + "roots_im": [ + 0, + 3.98497890132304, + -3.98497890132304 + ] + }, + { + "K": 2, + "roots_re": [ + -0.0815753762102226, + -2.95921231189489, + -2.95921231189489 + ], + "roots_im": [ + 0, + 3.9699199964070089, + -3.9699199964070089 + ] + }, + { + "K": 5, + "roots_re": [ + -0.21023612367551775, + -2.894881938162241, + -2.894881938162241 + ], + "roots_im": [ + 0, + 3.9245943802827612, + -3.9245943802827612 + ] + }, + { + "K": 10, + "roots_re": [ + -0.44376745611806312, + -2.7781162719409682, + -2.7781162719409682 + ], + "roots_im": [ + 0, + 3.84920703495901, + -3.84920703495901 + ] + }, + { + "K": 20, + "roots_re": [ + -0.99999999999999978, + -2.5, + -2.5 + ], + "roots_im": [ + 0, + 3.7080992435478319, + -3.7080992435478319 + ] + }, + { + "K": 50, + "roots_re": [ + -3.1220913247724318, + -1.4389543376137843, + -1.4389543376137843 + ], + "roots_im": [ + 0, + 3.7342089799376743, + -3.7342089799376743 + ] + }, + { + "K": 100, + "roots_re": [ + -5.0000000000000009, + -0.49999999999999906, + -0.49999999999999906 + ], + "roots_im": [ + 0, + 4.4440972086577935, + -4.4440972086577935 + ] + }, + { + "K": 1000, + "roots_re": [ + -11.447298641510786, + 2.7236493207553902, + 2.7236493207553902 + ], + "roots_im": [ + 0, + 8.94083825580234, + -8.94083825580234 + ] + } + ] + }, + { + "id": "LGR_2e_eq08", + "question": "2(e)", + "eq": 8, + "expr": "(s+2)*(s+3)/(s*(s+1))", + "num": [ + 1, + 5, + 6 + ], + "den": [ + 1, + 1, + 0 + ], + "P": 2, + "Z": 2, + "branches": 2, + "poles_re": [ + 0, + -1 + ], + "poles_im": [ + 0, + 0 + ], + "zeros_re": [ + -3.0000000000000004, + -1.9999999999999998 + ], + "zeros_im": [ + 0, + 0 + ], + "centroid": [], + "asymptotes_deg": [], + "break_points": [ + { + "s": -2.3660254037844384, + "K": 13.928203230275484 + }, + { + "s": -0.6339745962155614, + "K": 0.071796769724490825 + } + ], + "departure_angles": [], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -1 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.0060060786605548762, + -0.99798992533544917 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.060685265163897814, + -0.97891869523214181 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.68181818181818188, + -0.68181818181818188 + ], + "roots_im": [ + 0.28386354538174524, + -0.28386354538174524 + ] + }, + { + "K": 0.5, + "roots_re": [ + -1.1666666666666665, + -1.1666666666666665 + ], + "roots_im": [ + 0.79930525388545348, + -0.79930525388545348 + ] + }, + { + "K": 1, + "roots_re": [ + -1.5000000000000004, + -1.5000000000000004 + ], + "roots_im": [ + 0.86602540378443893, + -0.86602540378443893 + ] + }, + { + "K": 2, + "roots_re": [ + -1.8333333333333335, + -1.8333333333333335 + ], + "roots_im": [ + 0.79930525388545415, + -0.79930525388545415 + ] + }, + { + "K": 5, + "roots_re": [ + -2.166666666666667, + -2.166666666666667 + ], + "roots_im": [ + 0.55277079839256571, + -0.55277079839256571 + ] + }, + { + "K": 10, + "roots_re": [ + -2.3181818181818179, + -2.3181818181818179 + ], + "roots_im": [ + 0.28386354538174163, + -0.28386354538174163 + ] + }, + { + "K": 20, + "roots_re": [ + -2.1428571428571419, + -2.6666666666666674 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -2.0447236240407252, + -2.8768450034102555 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -2.0210813047678577, + -2.9393147348361026 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -2.0020100746645513, + -2.9939939213394444 + ], + "roots_im": [ + 0, + 0 + ] + } + ] + }, + { + "id": "LGR_2f_eq09", + "question": "2(f)", + "eq": 9, + "expr": "(s^2+2*s+8)/(s*(s+10)*(s+5))", + "num": [ + 1, + 2, + 8 + ], + "den": [ + 1, + 15, + 50, + 0 + ], + "P": 3, + "Z": 2, + "branches": 3, + "poles_re": [ + 0, + -10, + -5 + ], + "poles_im": [ + 0, + 0, + 0 + ], + "zeros_re": [ + -1, + -1 + ], + "zeros_im": [ + 2.6457513110645903, + -2.6457513110645903 + ], + "centroid": -13, + "asymptotes_deg": 180, + "break_points": [ + { + "s": -1.6679447898090769, + "K": 6.218909031131223 + } + ], + "departure_angles": [], + "arrival_angles": [ + { + "zero_re": -1, + "zero_im": 2.6457513110645903, + "angle_deg": -109.43115211890682 + } + ], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -5, + -10 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.00016000128050179481, + -4.9990802942408958, + -10.001759704478598 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.0016001285021086402, + -4.990829281806338, + -10.017570589691552 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.016013305290087085, + -4.9107943553590223, + -10.173192339350893 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.080385055017448179, + -4.5984351292024508, + -10.821179815780122 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -0.16182200481547951, + -4.2756104032278115, + -11.562567591956707 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -0.32989243401243928, + -3.7554835055996483, + -12.91462406038792 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -0.95783884827162658, + -2.5289208924564544, + -16.513240259271914 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 10, + "roots_re": [ + -1.5094961875260275, + -1.5094961875260275, + -21.981007624947956 + ], + "roots_im": [ + 1.166587692445519, + -1.166587692445519, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -1.3137297584910468, + -1.3137297584910468, + -32.372540483017929 + ], + "roots_im": [ + 1.7934811235866148, + -1.7934811235866148, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -1.1451283180275915, + -1.1451283180275915, + -62.709743363944824 + ], + "roots_im": [ + 2.251060916692226, + -2.251060916692226, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -1.0762795371223364, + -1.0762795371223364, + -112.84744092575534 + ], + "roots_im": [ + 2.4353314739367753, + -2.4353314739367753, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -1.0079637956802006, + -1.0079637956802006, + -1012.9840724086405 + ], + "roots_im": [ + 2.6232551933425161, + -2.6232551933425161, + 0 + ] + } + ] + }, + { + "id": "LGR_2g_eq10", + "question": "2(g)", + "eq": 10, + "expr": "(s^2+4)/((s+2)^2*(s+5)*(s+6))", + "num": [ + 1, + 0, + 4 + ], + "den": [ + 1, + 15, + 78, + 164, + 120 + ], + "P": 4, + "Z": 2, + "branches": 4, + "poles_re": [ + -5.9999999999999911, + -5.0000000000000071, + -2, + -2 + ], + "poles_im": [ + 0, + 0, + 3.1624055745239181E-8, + -3.1624055745239181E-8 + ], + "zeros_re": [ + -0, + 0 + ], + "zeros_im": [ + 2.0000000000000004, + -2.0000000000000004 + ], + "centroid": -7.4999999999999991, + "asymptotes_deg": [ + 90, + 270 + ], + "break_points": [ + { + "s": -5.5307160698579665, + "K": 0.089761016056045514 + }, + { + "s": -2.0000000000000004, + "K": 0 + } + ], + "departure_angles": [], + "arrival_angles": [ + { + "zero_re": -0, + "zero_im": 2.0000000000000004, + "angle_deg": -139.76364169072616 + } + ], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -5.9999999999999911, + -5.0000000000000071, + -2, + -2 + ], + "roots_im": [ + 0, + 0, + 3.1624055745239181E-8, + -3.1624055745239181E-8 + ] + }, + { + "K": 0.001, + "roots_re": [ + -5.9974924574760315, + -5.0032293063602538, + -1.9996391180818605, + -1.9996391180818605 + ], + "roots_im": [ + 0, + 0, + 0.025811573279360404, + -0.025811573279360404 + ] + }, + { + "K": 0.01, + "roots_re": [ + -5.9742045708907012, + -5.0329722233479028, + -1.9964116028806966, + -1.9964116028806966 + ], + "roots_im": [ + 0, + 0, + 0.081388672664746475, + -0.081388672664746475 + ] + }, + { + "K": 0.1, + "roots_re": [ + -5.53402317779589, + -5.53402317779589, + -1.9659768222041092, + -1.9659768222041092 + ], + "roots_im": [ + 0.16649958061705578, + -0.16649958061705578, + 0.2505100546490559, + -0.2505100546490559 + ] + }, + { + "K": 0.5, + "roots_re": [ + -5.6414534800846559, + -5.6414534800846559, + -1.858546519915347, + -1.858546519915347 + ], + "roots_im": [ + 1.0099975442883762, + -1.0099975442883762, + 0.50999754428836319, + -0.50999754428836319 + ] + }, + { + "K": 1, + "roots_re": [ + -5.7398491770861018, + -5.7398491770861018, + -1.7601508229138967, + -1.7601508229138967 + ], + "roots_im": [ + 1.4506375370234215, + -1.4506375370234215, + 0.66306125756160306, + -0.66306125756160306 + ] + }, + { + "K": 2, + "roots_re": [ + -5.8805473218139959, + -5.8805473218139959, + -1.6194526781860001, + -1.6194526781860001 + ], + "roots_im": [ + 2.0022911494885478, + -2.0022911494885478, + 0.83324302196743061, + -0.83324302196743061 + ] + }, + { + "K": 5, + "roots_re": [ + -6.1322717633549777, + -6.1322717633549777, + -1.3677282366450219, + -1.3677282366450219 + ], + "roots_im": [ + 2.9717358425216052, + -2.9717358425216052, + 1.0696838744363928, + -1.0696838744363928 + ] + }, + { + "K": 10, + "roots_re": [ + -6.3637563221921258, + -6.3637563221921258, + -1.1362436778078773, + -1.1362436778078773 + ], + "roots_im": [ + 3.9666250260150075, + -3.9666250260150075, + 1.2467277676341491, + -1.2467277676341491 + ] + }, + { + "K": 20, + "roots_re": [ + -6.614397851923699, + -6.614397851923699, + -0.88560214807630444, + -0.88560214807630444 + ], + "roots_im": [ + 5.2945881098906451, + -5.2945881098906451, + 1.4148805090235843, + -1.4148805090235843 + ] + }, + { + "K": 50, + "roots_re": [ + -6.9360036392421893, + -6.9360036392421893, + -0.5639963607578049, + -0.5639963607578049 + ], + "roots_im": [ + 7.8307112031595123, + -7.8307112031595123, + 1.6143730768447193, + -1.6143730768447193 + ] + }, + { + "K": 100, + "roots_re": [ + -7.138732184177508, + -7.138732184177508, + -0.36126781582248324, + -0.36126781582248324 + ], + "roots_im": [ + 10.656541700893124, + -10.656541700893124, + 1.7407270346860255, + -1.7407270346860255 + ] + }, + { + "K": 1000, + "roots_re": [ + -7.4502322330232262, + -7.4502322330232262, + -0.049767766976778316, + -0.049767766976778316 + ], + "roots_im": [ + 31.893103525477944, + -31.893103525477944, + 1.9591795909910374, + -1.9591795909910374 + ] + } + ] + }, + { + "id": "LGR_2h_eq11", + "question": "2(h)", + "eq": 11, + "expr": "1/((s+1)*(s^2+4*s+5))", + "num": 1, + "den": [ + 1, + 5, + 9, + 5 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + -2.0000000000000009, + -2.0000000000000009, + -0.99999999999999967 + ], + "poles_im": [ + 1.000000000000002, + -1.000000000000002, + 0 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -1.6666666666666672, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [], + "departure_angles": [ + { + "pole_re": -2.0000000000000009, + "pole_im": 1.000000000000002, + "angle_deg": -45 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -2.0000000000000009, + -2.0000000000000009, + -0.99999999999999967 + ], + "roots_im": [ + 1.000000000000002, + -1.000000000000002, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -1.9997498749061724, + -1.9997498749061724, + -1.0005002501876568 + ], + "roots_im": [ + 0.9997499374843859, + -0.9997499374843859, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -1.9974874054620553, + -1.9974874054620553, + -1.005025189075891 + ], + "roots_im": [ + 0.99749373447558509, + -0.99749373447558509, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -1.9736477144061759, + -1.9736477144061759, + -1.052704571187651 + ], + "roots_im": [ + 0.97436069177712981, + -0.97436069177712981, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -1.8238994356305214, + -1.8238994356305214, + -1.3522011287389559 + ], + "roots_im": [ + 0.86071661862356952, + -0.86071661862356952, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -1.4999999999999991, + -1.4999999999999991, + -2 + ], + "roots_im": [ + 0.86602540378444071, + -0.86602540378444071, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -1.2281554936539618, + -1.2281554936539618, + -2.5436890126920719 + ], + "roots_im": [ + 1.1151425080399389, + -1.1151425080399389, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -0.92454445783202976, + -0.92454445783202976, + -3.1509110843359416 + ], + "roots_im": [ + 1.5227944001747156, + -1.5227944001747156, + 0 + ] + }, + { + "K": 10, + "roots_re": [ + -0.66959878011472385, + -0.66959878011472385, + -3.6608024397705528 + ], + "roots_im": [ + 1.9102617040201948, + -1.9102617040201948, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -0.36786300772679825, + -0.36786300772679825, + -4.2642739845464064 + ], + "roots_im": [ + 2.3931860563051619, + -2.3931860563051619, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + 0.13589960045214067, + 0.13589960045214067, + -5.2717992009042849 + ], + "roots_im": [ + 3.2271352789634604, + -3.2271352789634604, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + 0.6243864910714132, + 0.6243864910714132, + -6.2487729821428282 + ], + "roots_im": [ + 4.0513504392253585, + -4.0513504392253585, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + 3.3209846228772948, + 3.3209846228772948, + -11.641969245754607 + ], + "roots_im": [ + 8.6773649701355371, + -8.6773649701355371, + 0 + ] + } + ] + }, + { + "id": "LGR_2i1_eq12", + "question": "2(i)-1", + "eq": 12, + "expr": "1/(s*(s^2+4*s+5))", + "num": 1, + "den": [ + 1, + 4, + 5, + 0 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + 0, + -2.0000000000000004, + -2.0000000000000004 + ], + "poles_im": [ + 0, + 1.0000000000000004, + -1.0000000000000004 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -1.3333333333333337, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [ + { + "s": -1.6666666666666661, + "K": 1.8518518518518521 + }, + { + "s": -1.0000000000000004, + "K": 2 + } + ], + "departure_angles": [ + { + "pole_re": -2.0000000000000004, + "pole_im": 1.0000000000000004, + "angle_deg": -63.434948822921996 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -2.0000000000000004, + -2.0000000000000004 + ], + "roots_im": [ + 0, + 1.0000000000000004, + -1.0000000000000004 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.000200032008642817, + -1.9998999839956777, + -1.9998999839956777 + ], + "roots_im": [ + 0, + 0.99979996298875562, + -0.99979996298875562 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.002003208668261714, + -1.9989983956658688, + -1.9989983956658688 + ], + "roots_im": [ + 0, + 0.99799628871915314, + -0.99799628871915314 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.020328932136253565, + -1.9898355339318745, + -1.9898355339318745 + ], + "roots_im": [ + 0, + 0.97961833631207784, + -0.97961833631207784 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.10929524412788269, + -1.9453523779360573, + -1.9453523779360573 + ], + "roots_im": [ + 0, + 0.889026770989471, + -0.889026770989471 + ] + }, + { + "K": 1, + "roots_re": [ + -0.24512233375330725, + -1.8774388331233451, + -1.8774388331233451 + ], + "roots_im": [ + 0, + 0.7448617666197459, + -0.7448617666197459 + ] + }, + { + "K": 2, + "roots_re": [ + -0.99999999999999967, + -2, + -0.99999999999999967 + ], + "roots_im": [ + 2.8326346177791904E-8, + 0, + -2.8326346177791904E-8 + ] + }, + { + "K": 5, + "roots_re": [ + -0.56814673609040578, + -2.8637065278191871, + -0.56814673609040578 + ], + "roots_im": [ + 1.1929787309366844, + 0, + -1.1929787309366844 + ] + }, + { + "K": 10, + "roots_re": [ + -0.30257066306696745, + -3.3948586738660671, + -0.30257066306696745 + ], + "roots_im": [ + 1.689402768409777, + 0, + -1.689402768409777 + ] + }, + { + "K": 20, + "roots_re": [ + 6.106226635438361E-16, + -3.9999999999999982, + 6.106226635438361E-16 + ], + "roots_im": [ + 2.2360679774997911, + 0, + -2.2360679774997911 + ] + }, + { + "K": 50, + "roots_re": [ + 0.49999999999999956, + -5, + 0.49999999999999956 + ], + "roots_im": [ + 3.1224989991991996, + 0, + -3.1224989991991996 + ] + }, + { + "K": 100, + "roots_re": [ + 0.98451228491057385, + -5.9690245698211459, + 0.98451228491057385 + ], + "roots_im": [ + 3.9728946118295294, + 0, + -3.9728946118295294 + ] + }, + { + "K": 1000, + "roots_re": [ + 3.6690138516344364, + -11.338027703268885, + 3.6690138516344364 + ], + "roots_im": [ + 8.6450621017741476, + 0, + -8.6450621017741476 + ] + } + ] + }, + { + "id": "LGR_2i2_eq13", + "question": "2(i)-2", + "eq": 13, + "expr": "(s+2)/((s+1)*(s^2+6*s+10))", + "num": [ + 1, + 2 + ], + "den": [ + 1, + 7, + 16, + 10 + ], + "P": 3, + "Z": 1, + "branches": 3, + "poles_re": [ + -2.9999999999999991, + -2.9999999999999991, + -0.99999999999999933 + ], + "poles_im": [ + 1.0000000000000033, + -1.0000000000000033, + 0 + ], + "zeros_re": -2, + "zeros_im": 0, + "centroid": -2.4999999999999987, + "asymptotes_deg": [ + 90, + 270 + ], + "break_points": [], + "departure_angles": [ + { + "pole_re": -2.9999999999999991, + "pole_im": 1.0000000000000033, + "angle_deg": 71.565051177077947 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -2.9999999999999991, + -2.9999999999999991, + -0.99999999999999933 + ], + "roots_im": [ + 1.0000000000000033, + -1.0000000000000033, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -2.9999000040012791, + -2.9999000040012791, + -1.0001999919974396 + ], + "roots_im": [ + 1.0002999780079611, + -1.0002999780079611, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -2.9990004012803171, + -2.9990004012803171, + -1.0019991974393683 + ], + "roots_im": [ + 1.0029978079308322, + -1.0029978079308322, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -2.990041282799742, + -2.990041282799742, + -1.0199174344005197 + ], + "roots_im": [ + 1.0297876768265286, + -1.0297876768265286, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -2.9511606817331844, + -2.9511606817331844, + -1.0976786365336295 + ], + "roots_im": [ + 1.1453377510407339, + -1.1453377510407339, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -2.9052678568830697, + -2.9052678568830697, + -1.1894642862338631 + ], + "roots_im": [ + 1.2837421720699398, + -1.2837421720699398, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -2.8253145957196919, + -2.8253145957196919, + -1.3493708085606118 + ], + "roots_im": [ + 1.546868887231396, + -1.546868887231396, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -2.6819408558738642, + -2.6819408558738642, + -1.6361182882522731 + ], + "roots_im": [ + 2.2430444224272943, + -2.2430444224272943, + 0 + ] + }, + { + "K": 10, + "roots_re": [ + -2.5977170503464291, + -2.5977170503464291, + -1.8045658993071358 + ], + "roots_im": [ + 3.1426681205834703, + -3.1426681205834703, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -2.5497281170483204, + -2.5497281170483204, + -1.9005437659033604 + ], + "roots_im": [ + 4.4505220788042195, + -4.4505220788042195, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -2.5199833881613145, + -2.5199833881613145, + -1.9600332236773679 + ], + "roots_im": [ + 7.0548693393689854, + -7.0548693393689854, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -2.5099979608400451, + -2.5099979608400451, + -1.9800040783199078 + ], + "roots_im": [ + 9.9880077011635766, + -9.9880077011635766, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -2.5009999979960114, + -2.5009999979960114, + -1.9980000040079846 + ], + "roots_im": [ + 31.618839368294093, + -31.618839368294093, + 0 + ] + } + ] + }, + { + "id": "LGR_3a_eq14", + "question": "3(a)", + "eq": 14, + "expr": "1/(s*(s^2+4*s+5))", + "num": 1, + "den": [ + 1, + 4, + 5, + 0 + ], + "P": 3, + "Z": 0, + "branches": 3, + "poles_re": [ + 0, + -2.0000000000000004, + -2.0000000000000004 + ], + "poles_im": [ + 0, + 1.0000000000000004, + -1.0000000000000004 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -1.3333333333333337, + "asymptotes_deg": [ + 60, + 180, + 300 + ], + "break_points": [ + { + "s": -1.6666666666666661, + "K": 1.8518518518518521 + }, + { + "s": -1.0000000000000004, + "K": 2 + } + ], + "departure_angles": [ + { + "pole_re": -2.0000000000000004, + "pole_im": 1.0000000000000004, + "angle_deg": -63.434948822921996 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -2.0000000000000004, + -2.0000000000000004 + ], + "roots_im": [ + 0, + 1.0000000000000004, + -1.0000000000000004 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.000200032008642817, + -1.9998999839956777, + -1.9998999839956777 + ], + "roots_im": [ + 0, + 0.99979996298875562, + -0.99979996298875562 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.002003208668261714, + -1.9989983956658688, + -1.9989983956658688 + ], + "roots_im": [ + 0, + 0.99799628871915314, + -0.99799628871915314 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.020328932136253565, + -1.9898355339318745, + -1.9898355339318745 + ], + "roots_im": [ + 0, + 0.97961833631207784, + -0.97961833631207784 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.10929524412788269, + -1.9453523779360573, + -1.9453523779360573 + ], + "roots_im": [ + 0, + 0.889026770989471, + -0.889026770989471 + ] + }, + { + "K": 1, + "roots_re": [ + -0.24512233375330725, + -1.8774388331233451, + -1.8774388331233451 + ], + "roots_im": [ + 0, + 0.7448617666197459, + -0.7448617666197459 + ] + }, + { + "K": 2, + "roots_re": [ + -0.99999999999999967, + -2, + -0.99999999999999967 + ], + "roots_im": [ + 2.8326346177791904E-8, + 0, + -2.8326346177791904E-8 + ] + }, + { + "K": 5, + "roots_re": [ + -0.56814673609040578, + -2.8637065278191871, + -0.56814673609040578 + ], + "roots_im": [ + 1.1929787309366844, + 0, + -1.1929787309366844 + ] + }, + { + "K": 10, + "roots_re": [ + -0.30257066306696745, + -3.3948586738660671, + -0.30257066306696745 + ], + "roots_im": [ + 1.689402768409777, + 0, + -1.689402768409777 + ] + }, + { + "K": 20, + "roots_re": [ + 6.106226635438361E-16, + -3.9999999999999982, + 6.106226635438361E-16 + ], + "roots_im": [ + 2.2360679774997911, + 0, + -2.2360679774997911 + ] + }, + { + "K": 50, + "roots_re": [ + 0.49999999999999956, + -5, + 0.49999999999999956 + ], + "roots_im": [ + 3.1224989991991996, + 0, + -3.1224989991991996 + ] + }, + { + "K": 100, + "roots_re": [ + 0.98451228491057385, + -5.9690245698211459, + 0.98451228491057385 + ], + "roots_im": [ + 3.9728946118295294, + 0, + -3.9728946118295294 + ] + }, + { + "K": 1000, + "roots_re": [ + 3.6690138516344364, + -11.338027703268885, + 3.6690138516344364 + ], + "roots_im": [ + 8.6450621017741476, + 0, + -8.6450621017741476 + ] + } + ] + }, + { + "id": "LGR_3b_eq15", + "question": "3(b)", + "eq": 15, + "expr": "1/(s*(s+1)*(s^2+4*s+13))", + "num": 1, + "den": [ + 1, + 5, + 17, + 13, + 0 + ], + "P": 4, + "Z": 0, + "branches": 4, + "poles_re": [ + 0, + -2, + -2, + -1.0000000000000007 + ], + "poles_im": [ + 0, + 3, + -3, + 0 + ], + "zeros_re": [], + "zeros_im": [], + "centroid": -1.2500000000000002, + "asymptotes_deg": [ + 45, + 135, + 225, + 315 + ], + "break_points": [ + { + "s": -0.46637844124531613, + "K": 2.8251663715376574 + } + ], + "departure_angles": [ + { + "pole_re": -2, + "pole_im": 3, + "angle_deg": -142.1250163489018 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + -1.9999999999999976, + -1.9999999999999976, + -0.99999999999999989 + ], + "roots_im": [ + 0, + 2.9999999999999987, + -2.9999999999999987, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -7.6930816129347111E-5, + -2.0000115385926258, + -2.0000115385926258, + -0.99989999199862012 + ], + "roots_im": [ + 0, + 2.9999910257302815, + -2.9999910257302815, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.00077000593638838354, + -2.00011539772334, + -2.00011539772334, + -0.99899919861693331 + ], + "roots_im": [ + 0, + 2.9999102653384804, + -2.9999102653384804, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.0077710989857693938, + -2.0011551561968979, + -2.0011551561968979, + -0.9899185886204338 + ], + "roots_im": [ + 0, + 2.9991034594043775, + -2.9991034594043775, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.040590572141233766, + -2.0058018951209249, + -2.0058018951209249, + -0.94780563761691827 + ], + "roots_im": [ + 0, + 2.9955354785235446, + -2.9955354785235446, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -0.086452618690900665, + -2.0116686564857389, + -2.0116686564857389, + -0.89021006833761573 + ], + "roots_im": [ + 0, + 2.9911176496438996, + -2.9911176496438996, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -0.20622803395421505, + -2.0235936146769413, + -2.0235936146769413, + -0.74658473669189951 + ], + "roots_im": [ + 0, + 2.982430301429734, + -2.982430301429734, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -0.43917466379114845, + -2.0608253362088504, + -2.0608253362088504, + -0.43917466379114845 + ], + "roots_im": [ + 0.43805178416449947, + 2.9576994583741425, + -2.9576994583741425, + -0.43805178416449947 + ] + }, + { + "K": 10, + "roots_re": [ + -0.37297767845389551, + -2.127022321546105, + -2.127022321546105, + -0.37297767845389551 + ], + "roots_im": [ + 0.7915324791406908, + 2.9217824421824483, + -2.9217824421824483, + -0.7915324791406908 + ] + }, + { + "K": 20, + "roots_re": [ + -0.23251174299381744, + -2.2674882570061858, + -2.2674882570061858, + -0.23251174299381744 + ], + "roots_im": [ + 1.1994382431764203, + 2.873484401749351, + -2.873484401749351, + -1.1994382431764203 + ] + }, + { + "K": 50, + "roots_re": [ + 0.1430068892138146, + -2.6430068892138125, + -2.6430068892138125, + 0.1430068892138146 + ], + "roots_im": [ + 1.8063364279642549, + 2.8710773406168677, + -2.8710773406168677, + -1.8063364279642549 + ] + }, + { + "K": 100, + "roots_re": [ + 0.55501592673896294, + -3.0550159267389612, + -3.0550159267389612, + 0.55501592673896294 + ], + "roots_im": [ + 2.269108701701557, + 2.99871817472481, + -2.99871817472481, + -2.269108701701557 + ] + }, + { + "K": 1000, + "roots_re": [ + 2.4830362173141567, + -4.9830362173141474, + -4.9830362173141474, + 2.4830362173141567 + ], + "roots_im": [ + 4.1010798559851036, + 4.32171989078324, + -4.32171989078324, + -4.1010798559851036 + ] + } + ] + }, + { + "id": "LGR_3c_eq16", + "question": "3(c)", + "eq": 16, + "expr": "(s+1)/(s^2*(s+3.6))", + "num": [ + 1, + 1 + ], + "den": [ + 1, + 3.6, + 0, + 0 + ], + "P": 3, + "Z": 1, + "branches": 3, + "poles_re": [ + 0, + 0, + -3.6 + ], + "poles_im": [ + 0, + 0, + 0 + ], + "zeros_re": -1, + "zeros_im": 0, + "centroid": -1.3, + "asymptotes_deg": [ + 90, + 270 + ], + "break_points": [ + { + "s": 0, + "K": 0 + } + ], + "departure_angles": [], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + 0, + -3.6 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.00010031208210491675, + -0.00010031208210491675, + -3.5997993758357913 + ], + "roots_im": [ + 0.016666829224129383, + -0.016666829224129383, + 0 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.0010034306036662741, + -0.0010034306036662741, + -3.5979931387926674 + ], + "roots_im": [ + 0.052709773975347152, + -0.052709773975347152, + 0 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.010065454324541484, + -0.010065454324541484, + -3.5798690913509188 + ], + "roots_im": [ + 0.16683125898817416, + -0.16683125898817416, + 0 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.051038579323461383, + -0.051038579323461383, + -3.49792284135308 + ], + "roots_im": [ + 0.37461585472207243, + -0.37461585472207243, + 0 + ] + }, + { + "K": 1, + "roots_re": [ + -0.10394690936548454, + -0.10394690936548454, + -3.3921061812690323 + ], + "roots_im": [ + 0.53291381335861454, + -0.53291381335861454, + 0 + ] + }, + { + "K": 2, + "roots_re": [ + -0.21601888577823278, + -0.21601888577823278, + -3.1679622284435323 + ], + "roots_im": [ + 0.76462834072203423, + -0.76462834072203423, + 0 + ] + }, + { + "K": 5, + "roots_re": [ + -0.60891385109508822, + -0.60891385109508822, + -2.382172297809825 + ], + "roots_im": [ + 1.3145906230769013, + -1.3145906230769013, + 0 + ] + }, + { + "K": 10, + "roots_re": [ + -1.0732645144905741, + -1.0732645144905741, + -1.4534709710188549 + ], + "roots_im": [ + 2.3933628328905607, + -2.3933628328905607, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -1.2173456074554569, + -1.2173456074554569, + -1.1653087850890891 + ], + "roots_im": [ + 3.9599119447651874, + -3.9599119447651874, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -1.2715965841362871, + -1.2715965841362871, + -1.0568068317274282 + ], + "roots_im": [ + 6.7598356646134494, + -6.7598356646134494, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -1.2864278596714378, + -1.2864278596714378, + -1.027144280657124 + ], + "roots_im": [ + 9.78276082324321, + -9.78276082324321, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -1.2986945149264395, + -1.2986945149264395, + -1.0026109701471178 + ], + "roots_im": [ + 31.554860510257825, + -31.554860510257825, + 0 + ] + } + ] + }, + { + "id": "LGR_4a_eq17", + "question": "4(a)", + "eq": 17, + "expr": "(s+2)/(s^2+4*s+13)", + "num": [ + 1, + 2 + ], + "den": [ + 1, + 4, + 13 + ], + "P": 2, + "Z": 1, + "branches": 2, + "poles_re": [ + -2, + -2 + ], + "poles_im": [ + 3, + -3 + ], + "zeros_re": -2, + "zeros_im": 0, + "centroid": -2, + "asymptotes_deg": 180, + "break_points": [ + { + "s": -5, + "K": 6 + } + ], + "departure_angles": [ + { + "pole_re": -2, + "pole_im": 3, + "angle_deg": -180 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -2, + -2 + ], + "roots_im": [ + 3, + -3 + ] + }, + { + "K": 0.001, + "roots_re": [ + -2.0005000000000006, + -2.0005000000000006 + ], + "roots_im": [ + 2.999999958333333, + -2.999999958333333 + ] + }, + { + "K": 0.01, + "roots_re": [ + -2.005, + -2.005 + ], + "roots_im": [ + 2.99999583333044, + -2.99999583333044 + ] + }, + { + "K": 0.1, + "roots_re": [ + -2.0499999999999994, + -2.0499999999999994 + ], + "roots_im": [ + 2.9995833043941276, + -2.9995833043941276 + ] + }, + { + "K": 0.5, + "roots_re": [ + -2.2499999999999991, + -2.2499999999999991 + ], + "roots_im": [ + 2.9895651857753487, + -2.9895651857753487 + ] + }, + { + "K": 1, + "roots_re": [ + -2.5, + -2.5 + ], + "roots_im": [ + 2.9580398915498076, + -2.9580398915498076 + ] + }, + { + "K": 2, + "roots_re": [ + -3, + -3 + ], + "roots_im": [ + 2.82842712474619, + -2.82842712474619 + ] + }, + { + "K": 5, + "roots_re": [ + -4.5, + -4.5 + ], + "roots_im": [ + 1.6583123951776995, + -1.6583123951776995 + ] + }, + { + "K": 10, + "roots_re": [ + -3, + -11 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 20, + "roots_re": [ + -2.4606079858305434, + -21.539392014169458 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 50, + "roots_re": [ + -2.1806527080182869, + -51.819347291981714 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 100, + "roots_re": [ + -2.0900811461288789, + -101.90991885387112 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + -2.0090000810014579, + -1001.9909999189986 + ], + "roots_im": [ + 0, + 0 + ] + } + ] + }, + { + "id": "LGR_4b_eq18", + "question": "4(b)", + "eq": 18, + "expr": "(s-2)*(s-4)/(s^2+6*s+25)", + "num": [ + 1, + -6, + 8 + ], + "den": [ + 1, + 6, + 25 + ], + "P": 2, + "Z": 2, + "branches": 2, + "poles_re": [ + -3.0000000000000004, + -3.0000000000000004 + ], + "poles_im": [ + 4, + -4 + ], + "zeros_re": [ + 4, + 2 + ], + "zeros_im": [ + 0, + 0 + ], + "centroid": [], + "asymptotes_deg": [], + "break_points": [ + { + "s": 2.8853031663801021, + "K": 51.311818998280643 + } + ], + "departure_angles": [ + { + "pole_re": -3.0000000000000004, + "pole_im": 4, + "angle_deg": 21.595310448967666 + } + ], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + -3.0000000000000004, + -3.0000000000000004 + ], + "roots_im": [ + 4, + -4 + ] + }, + { + "K": 0.001, + "roots_re": [ + -2.994005994005994, + -2.994005994005994 + ], + "roots_im": [ + 4.0023674357651329, + -4.0023674357651329 + ] + }, + { + "K": 0.01, + "roots_re": [ + -2.9405940594059405, + -2.9405940594059405 + ], + "roots_im": [ + 4.023007549844186, + -4.023007549844186 + ] + }, + { + "K": 0.1, + "roots_re": [ + -2.454545454545455, + -2.454545454545455 + ], + "roots_im": [ + 4.1748954557109217, + -4.1748954557109217 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.99999999999999989, + -0.99999999999999989 + ], + "roots_im": [ + 4.281744192888377, + -4.281744192888377 + ] + }, + { + "K": 1, + "roots_re": [ + 0, + 0 + ], + "roots_im": [ + 4.06201920231798, + -4.06201920231798 + ] + }, + { + "K": 2, + "roots_re": [ + 1, + 1 + ], + "roots_im": [ + 3.5590260840104375, + -3.5590260840104375 + ] + }, + { + "K": 5, + "roots_re": [ + 1.9999999999999998, + 1.9999999999999998 + ], + "roots_im": [ + 2.6140645235596867, + -2.6140645235596867 + ] + }, + { + "K": 10, + "roots_re": [ + 2.4545454545454541, + 2.4545454545454541 + ], + "roots_im": [ + 1.8763424945954827, + -1.8763424945954827 + ] + }, + { + "K": 20, + "roots_re": [ + 2.7142857142857131, + 2.7142857142857131 + ], + "roots_im": [ + 1.2009066869446197, + -1.2009066869446197 + ] + }, + { + "K": 50, + "roots_re": [ + 2.88235294117647, + 2.88235294117647 + ], + "roots_im": [ + 0.15929487067915374, + -0.15929487067915374 + ] + }, + { + "K": 100, + "roots_re": [ + 2.2486572194195582, + 3.6325308993923233 + ], + "roots_im": [ + 0, + 0 + ] + }, + { + "K": 1000, + "roots_re": [ + 2.0208210808672797, + 3.9671909071447087 + ], + "roots_im": [ + 0, + 0 + ] + } + ] + }, + { + "id": "LGR_5_eq19", + "question": "5(a,b)", + "eq": 19, + "expr": "(s+1)/s^3", + "num": [ + 1, + 1 + ], + "den": [ + 1, + 0, + 0, + 0 + ], + "P": 3, + "Z": 1, + "branches": 3, + "poles_re": [ + 0, + 0, + 0 + ], + "poles_im": [ + 0, + 0, + 0 + ], + "zeros_re": -1, + "zeros_im": 0, + "centroid": 0.5, + "asymptotes_deg": [ + 90, + 270 + ], + "break_points": [ + { + "s": 0, + "K": 0 + }, + { + "s": 0, + "K": 0 + } + ], + "departure_angles": [], + "arrival_angles": [], + "locus_samples": [ + { + "K": 0, + "roots_re": [ + 0, + 0, + -0 + ], + "roots_im": [ + 0, + 0, + 0 + ] + }, + { + "K": 0.001, + "roots_re": [ + -0.096667942323329731, + 0.048333971161664907, + 0.048333971161664907 + ], + "roots_im": [ + 0, + 0.089490325202057242, + -0.089490325202057242 + ] + }, + { + "K": 0.01, + "roots_re": [ + -0.20000000000000004, + 0.1000000000000001, + 0.1000000000000001 + ], + "roots_im": [ + 0, + 0.20000000000000004, + -0.20000000000000004 + ] + }, + { + "K": 0.1, + "roots_re": [ + -0.39300273897110527, + 0.19650136948555252, + 0.19650136948555252 + ], + "roots_im": [ + 0, + 0.46458407702922055, + -0.46458407702922055 + ] + }, + { + "K": 0.5, + "roots_re": [ + -0.58975451230145859, + 0.29487725615072924, + 0.29487725615072924 + ], + "roots_im": [ + 0, + 0.87227162546132841, + -0.87227162546132841 + ] + }, + { + "K": 1, + "roots_re": [ + -0.6823278038280195, + 0.3411639019140098, + 0.3411639019140098 + ], + "roots_im": [ + 0, + 1.1615413999972526, + -1.1615413999972526 + ] + }, + { + "K": 2, + "roots_re": [ + -0.770916997059248, + 0.38545849852962388, + 0.38545849852962388 + ], + "roots_im": [ + 0, + 1.5638845105269545, + -1.5638845105269545 + ] + }, + { + "K": 5, + "roots_re": [ + -0.86883002034147494, + 0.43441501017073714, + 0.43441501017073714 + ], + "roots_im": [ + 0, + 2.3592687857013903, + -2.3592687857013903 + ] + }, + { + "K": 10, + "roots_re": [ + -0.92169899420467882, + 0.46084949710233941, + 0.46084949710233941 + ], + "roots_im": [ + 0, + 3.2614639009099005, + -3.2614639009099005 + ] + }, + { + "K": 20, + "roots_re": [ + -0.95627600995885809, + 0.47813800497942882, + 0.47813800497942882 + ], + "roots_im": [ + 0, + 4.5481697258806317, + -4.5481697258806317 + ] + }, + { + "K": 50, + "roots_re": [ + -0.98111200886378558, + 0.49055600443189284, + 0.49055600443189284 + ], + "roots_im": [ + 0, + 7.121933415895751, + -7.121933415895751 + ] + }, + { + "K": 100, + "roots_re": [ + -0.99028852405457324, + 0.49514426202728634, + 0.49514426202728634 + ], + "roots_im": [ + 0, + 10.036707802893117, + -10.036707802893117 + ] + }, + { + "K": 1000, + "roots_re": [ + -0.99900298805472831, + 0.49950149402736432, + 0.49950149402736432 + ], + "roots_im": [ + 0, + 31.634609294688744, + -31.634609294688744 + ] + } + ] + } + ], + "controllers": [ + { + "id": "CTRL_Q1_PI", + "question": "1", + "controller_type": "PI", + "Kp": 0.49849281561599984, + "Ki": 0.099750999807999938, + "Kd": 0, + "z": 0.2001051904524144, + "p": 0, + "cl_poles_re": [ + -0.32193599999999983, + -0.32193599999999983, + -0.20012799999999978 + ], + "cl_poles_im": [ + 0.62832572118607344, + -0.62832572118607344, + 0 + ], + "cl_zeros_re": -0.2001051904524144, + "cl_zeros_im": 0, + "dcgain": 1, + "overshoot": 20.003167761706877, + "settling_time": 11.79426484164391, + "rise_time": 2.2070596916196417, + "peak_time": 5.0066148709517462 + }, + { + "id": "CTRL_Q2_PD", + "question": "2", + "controller_type": "PD", + "Kp": 3, + "Ki": 0, + "Kd": 2, + "z": 1.5, + "td": 0.66666666666666663, + "cl_poles_re": [ + -1, + -1 + ], + "cl_poles_im": [ + 1.732050807568877, + -1.732050807568877 + ], + "cl_zeros_re": -1.5, + "cl_zeros_im": 0, + "dcgain": 0.75, + "overshoot": 41.251081523683084, + "settling_time": 3.7232255355095183, + "rise_time": 0.36461328253008118, + "peak_time": 1.0591891427770259 + }, + { + "id": "CTRL_Q3_PD", + "question": "3", + "controller_type": "PD", + "Kp": 53.333333333333336, + "Ki": 0, + "Kd": 33.333333333333336, + "z": 1.6, + "td": 0.625, + "cl_poles_re": [ + -3.9999999999999982, + -1.0000000000000004, + -1.0000000000000004 + ], + "cl_poles_im": [ + 0, + 1.0000000000000002, + -1.0000000000000002 + ], + "cl_zeros_re": -1.6, + "cl_zeros_im": 0, + "dcgain": 1, + "overshoot": 8.0937934757274732, + "settling_time": 3.9134175958924926, + "rise_time": 1.1088150985328944, + "peak_time": 2.440740198573554 + }, + { + "id": "CTRL_Q4_PI", + "question": "4", + "controller_type": "PI", + "Kp": 7.6, + "Ki": 16, + "Kd": 0, + "z": 2.1052631578947367, + "cl_poles_re": [ + -1, + -1 + ], + "cl_poles_im": [ + 1.732050807568877, + -1.732050807568877 + ], + "cl_zeros_re": -2.1052631578947367, + "cl_zeros_im": 0, + "dcgain": 20, + "overshoot": 28.38519483760318, + "settling_time": 3.7585567664049768, + "rise_time": 0.48951297792656817, + "peak_time": 1.2433959502165088 + }, + { + "id": "CTRL_Q5_PID_CANCEL_EQUAL", + "question": "5", + "controller_type": "PID", + "Kp": 200, + "Ki": 100, + "Kd": 100, + "z1": 1, + "z2": 1, + "cl_poles_re": [ + -4.0000000000000018, + -4.0000000000000018, + -1.0000000298100586, + -0.99999997018994258 + ], + "cl_poles_im": [ + 9.165151389911685, + -9.165151389911685, + 0, + 0 + ], + "cl_zeros_re": [ + -1, + -1 + ], + "cl_zeros_im": [ + 0, + 0 + ], + "dcgain": 1, + "overshoot": 25.374074596318753, + "settling_time": 0.8409399301706838, + "rise_time": 0.14652080454767813, + "peak_time": 0.34538776394908755 + }, + { + "id": "CTRL_Q5_PID_DISTINCT", + "question": "5", + "controller_type": "PID", + "Kp": 197.02970297029572, + "Ki": 62.87128712871236, + "Kd": 99.628712871287092, + "z1": 0.4, + "z2": 1.5776397515527827, + "cl_poles_re": [ + -4.0000000000000018, + -4.0000000000000018, + -1.60933334777678, + -0.39066665222320907 + ], + "cl_poles_im": [ + 9.1651513899116779, + -9.1651513899116779, + 0, + 0 + ], + "cl_zeros_re": [ + -1.5776397515527825, + -0.40000000000000013 + ], + "cl_zeros_im": [ + 0, + 0 + ], + "dcgain": 1, + "overshoot": 24.473866097034815, + "settling_time": 0.87376362109491568, + "rise_time": 0.14738119773290045, + "peak_time": 0.34538776394908755 + }, + { + "id": "CTRL_Q6_PD", + "question": "6", + "controller_type": "PD", + "Kp": 8, + "Ki": 0, + "Kd": 4, + "z": 2, + "td": 0.5, + "cl_poles_re": [ + -2.0000000000000013, + -0.99999999999999978, + -0.99999999999999978 + ], + "cl_poles_im": [ + 0, + 1.7320508075688772, + -1.7320508075688772 + ], + "cl_poles_minreal_re": [ + -1, + -1 + ], + "cl_poles_minreal_im": [ + 1.732050807568877, + -1.732050807568877 + ], + "cl_zeros_re": -2, + "cl_zeros_im": 0, + "dcgain": 1, + "overshoot": 16.292919869949184, + "settling_time": 4.0379341168813427, + "rise_time": 0.81951455130722284, + "peak_time": 1.7960163725349574 + }, + { + "id": "CTRL_Q7_PD", + "question": "7", + "controller_type": "PD", + "Kp": 1.6, + "Ki": 0, + "Kd": 0.8, + "z": 2, + "td": 0.5, + "cl_poles_re": [ + -2.0000000000000013, + -0.99999999999999978, + -0.99999999999999978 + ], + "cl_poles_im": [ + 0, + 1.7320508075688772, + -1.7320508075688772 + ], + "cl_zeros_re": -2, + "cl_zeros_im": 0, + "dcgain": 1, + "overshoot": 16.292919869949184, + "settling_time": 4.0379341168813427, + "rise_time": 0.81951455130722284, + "peak_time": 1.7960163725349574 + }, + { + "id": "CTRL_Q8_PI", + "question": "8", + "controller_type": "PI", + "Kp": -1.25, + "Ki": -4.2608139679208019, + "Kd": 0, + "z": 3.4086511743366414, + "xi": 0.40371275194342071, + "wn": 2.4770087028119128, + "cl_poles_re": [ + -1, + -1 + ], + "cl_poles_im": [ + 2.2661800709135971, + -2.2661800709135971 + ], + "cl_zeros_re": -3.4086511743366419, + "cl_zeros_im": 0, + "dcgain": 1, + "overshoot": 33.840604831375764, + "settling_time": 3.9653730301652752, + "rise_time": 0.42290957655765732, + "peak_time": 1.0591891427770259 + }, + { + "id": "CTRL_Q9_PD", + "question": "9", + "controller_type": "PD", + "Kp": 4, + "Ki": 0, + "Kd": 2, + "z": 2, + "td": 0.5, + "cl_poles_re": [ + -1, + -1 + ], + "cl_poles_im": [ + 1.732050807568877, + -1.732050807568877 + ], + "cl_zeros_re": -2, + "cl_zeros_im": 0, + "dcgain": 1, + "overshoot": 29.835150652637886, + "settling_time": 3.752715553619379, + "rise_time": 0.47046005781198719, + "peak_time": 1.1973442483566381 + } + ] +} diff --git a/docs/validation/synthesis-comparison.md b/docs/validation/synthesis-comparison.md new file mode 100644 index 0000000..e39212e --- /dev/null +++ b/docs/validation/synthesis-comparison.md @@ -0,0 +1,61 @@ +# Comparação de Síntese de Controladores e Provas de Inviabilidade + +O módulo de Projeto de Controladores do ControLAB preserva integralmente o método didático clássico via Lugar Geométrico das Raízes (`lgr_classic`) e acrescenta duas modalidades genéricas baseadas em verificação temporal e modal sobre a malha fechada real (`crates/control-engine/src/controller_synthesis.rs`): + +1. **`lgr_classic`:** alocação clássica pelas condições de módulo e fase, agora acompanhada de verificação completa de conformidade (`NÃO CONFORME` sempre que restrições obrigatórias forem violadas). +2. **`temporal_refined`:** busca paramétrica determinística + refinamento coordenado e diagonal acoplado sobre a estrutura escolhida (`P`, `PI`, `PD`, `Lead`, `PID`), impondo estabilidade externa/interna, $M_p$, $t_s$, $e_{ss}$, $\xi$ e $\omega_n$ conforme a semântica selecionada. O controlador PID é parametrizado diretamente em ganhos canônicos $[K_p, K_i, K_d]$, abrangendo zeros reais ou complexos conjugados de fase mínima no SPE. +3. **`auto_simplest`:** percorre a hierarquia `P -> PI -> PD -> Lead -> PID`, descarta estruturas algebricamente inviáveis com justificativa matemática explícita e seleciona a estrutura mais simples que satisfaz todas as restrições. + +--- + +## 1. Comparação Antes (`lgr_classic`) × Depois (`temporal_refined` / `auto_simplest`) + +| Caso | Modo | Ganhos ($K_p, K_i, K_d$) | $\xi$ calculado [polo/par] | $M_p$ (Rust / MATLAB) | $t_s(2\%)$ (Rust / MATLAB) | $e_a(\infty)$ | Conformidade | +|---|---|---|---:|---:|---:|---:|---| +| **Q2 PD** | Clássico LGR | `3.0, 0, 2.0` | `0.5000` (`-1 ± 1.732j`) | `41.26%` / `41.25%` | `3.723 s` / `3.723 s` | `0.250` | **FAIL** ($M_p, t_s$) | +| **Q2 PD** | Refinado ($\xi \ge 0{,}5$) | `6.914, 0, 14.286` | `1.0000` (polos reais) | `15.51%` / `15.51%` | `4.000 s` / `4.000 s` | `0.126` | **PASS*** ($\xi \ge 0{,}5$) | +| **Q2 PID** | Clássico `equal` | `3.737, 1.474, 2.369` | `0.5000` (polo lento `-0.369`) | `13.99%` / `13.97%` | `7.639 s` / `7.639 s` | `0.000` | **FAIL** ($t_s$) | +| **Q2 PID** | **Refinado ($\xi = 0{,}5$ exato)** | `4.2369, 4.5933, 3.7651` | **`0.5000`** (par dom. `-0.695 ± 1.205j`) | `13.58%` / `13.56%` | `4.000 s` / `4.000 s` | `0.000` | **PASS*** (todas) | +| **Q5 PID** | Clássico `cancel`/`equal` | `200, 100, 100` | `0.4000` (`-4 ± 9.165j`) | `25.38%` / `25.37%` | `0.841 s` / `0.841 s` | `0.000` | **FAIL** ($t_s \ne 1$) | +| **Q5 PID** | **Refinado ($\xi = 0{,}4$ exato)** | `227.123, 56.865, 80.937` | **`0.4000`** (`-3.490 ± 7.996j`, `res=0.106`) | `28.84%` / `28.84%` | `0.997 s` / `0.997 s` | `0.000` | **PASS*** (todas) | +| **Q7 PD** | Clássico LGR | `1.6, 0, 0.8` | `0.5000` (`-1 ± 1.732j`) | `16.30%` / `16.29%` | `4.038 s` / `4.038 s` | `0.000` | **FAIL** ($M_p > 16\%$) | +| **Q7 PD** | Refinado ($\xi \ge 0{,}5$) | `0.5183, 0, 0.2681` | `0.8941` (`-1.037 ± 0.520j`) | `0.188%` / `0.188%` | `4.000 s` / `4.000 s` | `0.000` | **PASS*** ($\xi \ge 0{,}5$) | +| **Q7 PD** | **Refinado ($\xi = 0{,}50 \pm 0{,}01$ dom.)** | `1.6030, 0, 0.8175` | **`0.5044`** (dom. `-1.020 ± 1.746j`, `res=0.00035`) | `15.95%` / `15.95%` | `3.972 s` / `3.972 s` | `0.000` | **PASS*** (tol. `±0,01`) | +| **Q8 PI** | Clássico LGR | `-1.25, -4.2608, 0` | `0.4037` (`-1 ± 2.266j`) | `33.84%` / `33.84%` | `3.966 s` / `3.965 s` | `0.000` | **FAIL** ($M_p > 25\%$) | +| **Q8 PI** | **Refinado (`auto_simplest`)** | `-0.5022, -0.1263, 0` | `1.0000` (`-0.638, -0.285`) | `1.854%` / `1.854%` | `3.990 s` / `3.992 s` | `0.000` | **PASS*** (todas) | +| **Q8 PI** | Referência independente | `-1.0, -0.2, 0` | `1.0000` ($T=\frac{1{,}44}{s+1{,}44}$) | `0.000%` / `0.000%` | `2.717 s` / `2.717 s` | `0.000` | **PASS*** (todas) | +| **Q9 PD** | Clássico LGR | `4.0, 0, 2.0` | `0.5000` (`-1 ± 1.732j`) | `29.84%` / `29.84%` | `3.753 s` / `3.753 s` | `0.000` | **FAIL** ($M_p > 16\%$) | +| **Q9 PD** | Refinado ($\xi \ge 0{,}5$) | `1.7459, 0, 2.4408` | `0.9236` (`-1.220 ± 0.507j`) | `15.02%` / `15.02%` | `3.990 s` / `3.990 s` | `0.000` | **PASS*** ($\xi \ge 0{,}5$) | + +--- + +## 2. Demonstrações Matemáticas de Inviabilidade (`ProvenInfeasible`) + +O algoritmo distingue explicitamente **inviabilidade matematicamente comprovada** (`ProvenInfeasible`) de **ausência de solução nos limites da busca** (`NotFoundWithinSearchBounds`): + +1. **Duplo integrador $G(s) = k/s^2$ (Q9) com PD e igualdade $\xi = \xi_0 \in (0,1)$:** + Com realimentação unitária e $G_c(s) = K_p + K_d s$ ($k K_d = 2\xi_0 \omega_n,\; k K_p = \omega_n^2$), a malha fechada possui ganho estacionário unitário $y(\infty) = 1$ e é estritamente invariante por mudança de escala temporal $u = s/\omega_n$: + $$T(\omega_n u) = \frac{2\xi_0 u + 1}{u^2 + 2\xi_0 u + 1}$$ + Para $\xi_0 = 0{,}5$, o sobressinal é constante e igual a **$29{,}835\%$** para todo $\omega_n > 0$ — logo é matematicamente impossível atender simultaneamente a $\xi = 0{,}5$ e $M_p \le 16\%$ com um controlador PD. + +2. **Oscilador não amortecido $G(s) = k/(s^2 + c)$ com $c > 0$ (Q2: $c = 1$) com PD e igualdade $\xi = \xi_0 \in (0,1)$:** + Diferentemente do duplo integrador ($c = 0$), a malha fechada com $k K_d = 2\xi_0 \omega_n$ e $c + k K_p = \omega_n^2$ possui **ganho estacionário não unitário**: + $$T(s) = \frac{2\xi_0 \omega_n s + (\omega_n^2 - c)}{s^2 + 2\xi_0 \omega_n s + \omega_n^2}, \qquad y(\infty) = T(0) = \alpha = 1 - \frac{c}{\omega_n^2}$$ + Qualquer controlador PD estabilizante com rastreamento positivo exige $k K_p > 0 \iff \omega_n^2 > c$, donde $\alpha \in (0, 1)$. Normalizando $T(s)$ pelo seu valor estacionário $y(\infty) = \alpha$ (já que $M_p$ mede o excesso relativo a $y(\infty)$) e aplicando $u = s/\omega_n$: + $$\tilde{T}(\omega_n u) = \frac{T(\omega_n u)}{y(\infty)} = \frac{\frac{2\xi_0}{\alpha}\, u + 1}{u^2 + 2\xi_0 u + 1} = H_0(u) + \frac{2\xi_0}{\alpha}\, u H_0(u)$$ + No tempo adimensional $\tau = \omega_n t$, a resposta ao impulso $h_0(\tau) = \mathcal{L}^{-1}\{u H_0(u)\} = \frac{1}{\sqrt{1-\xi_0^2}}e^{-\xi_0\tau}\sin(\sqrt{1-\xi_0^2}\,\tau)$ é estritamente positiva em todo o primeiro semiciclo $(0, \pi/\sqrt{1-\xi_0^2})$, incluindo o instante de pico $\tau^*$ do caso $\alpha = 1$. Como $2\xi_0/\alpha > 2\xi_0$ estritamente para todo $\alpha \in (0,1)$, resulta: + $$M_p(c > 0, \omega_n) > M_p(c = 0) = 29{,}835\% > 16{,}3\% \qquad \forall\,\omega_n > \sqrt{c}$$ + A inclusão de um integrador (PID na Q2 com zeros complexos conjugados no SPE) introduz o grau de liberdade necessário para satisfazer $\xi = 0{,}5$, $M_p \le 16{,}3\%$, $t_s = 4\text{ s}$ e $e_{ss} = 0$ simultaneamente. + +3. **Outras inviabilidades algébricas verificadas:** planta Tipo 0 sem integrador para $e_{ss} = 0$ (ex.: `P`/`PD` na Q8) e planta Tipo $\ge 2$ sem zeros finitos com `P`/`PI` (ex.: `P`/`PI` na Q9). + +--- + +## 3. Evidências Visuais Selecionadas da Interface Nativa + +| Caso | Captura Real da GUI (`controlab-native`) | +|---|---| +| **Q8 Clássico (`lgr_classic`) — `NÃO CONFORME`** ($M_p = 33{,}84\% > 25\%$, alerta de zero extra) | ![Q8 Clássico Não Conforme](assets/q8-classic-fail.png) | +| **Q8 Refinado (`temporal_refined`) — `CONFORME COM ALERTAS`** ($M_p = 0\%$, $t_s = 3{,}99\text{ s}$) | ![Q8 Refinado Conforme](assets/q8-refined-pass.png) | +| **Q5 Etapa 11 — Igualdade obrigatória $\xi = 0{,}4000$, $t_s = 0{,}997\text{ s}$, razão de resíduos `0,106`** | ![Q5 Igualdade Exata xi=0.4](assets/q5-exact-xi-pass.png) | +| **Q2 PID Etapa 11 — Igualdade obrigatória $\xi = 0{,}5000$ dominante, $M_p = 13{,}58\%$, $t_s = 4{,}000\text{ s}$** | ![Q2 PID Igualdade Exata xi=0.5](assets/q2-pid-exact-xi-pass.png) | diff --git a/docs/validation/validation-matrix.csv b/docs/validation/validation-matrix.csv new file mode 100644 index 0000000..e09cf40 --- /dev/null +++ b/docs/validation/validation-matrix.csv @@ -0,0 +1,43 @@ +case_id,list,question,equation,input_system,controller_or_analysis,expected_reference,controlab_result,max_abs_error,max_rel_error,tolerance,reference_source,modules_verified,numerical_status,requirements_status,functional_status,visual_status,overall_status,observations +LGR_Q1A_EQ01,Exercicios_-_LGR.pdf,1(a),1,"G(s)H(s) = k / (s(s^2 + 6s + 25))",LGR + Routh,"P=3 (0, -3+-4j); Z=0; sigma_a=-2; theta_a=[60,180,300] deg; theta_d=-36.8699 deg; jw=+-5 rad/s (K_crit=150); estavel 00","P=2 (-1+-1.414214j); Z=1 (-2); sigma_a=0.0; theta_a=[180] deg; break-in s=-3.732051 (K=5.464102); theta_d=144.7356 deg; estavel K>0",8.88e-16,1.62e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Equivalente matematicamente ao caso 2(c) Eq.(6); LGR circular centrado em s=-2 com raio sqrt(3)." +LGR_Q1C_EQ03,Exercicios_-_LGR.pdf,1(c),3,"G(s)H(s) = k / (s(s^2 + 4s + 5))",LGR + Routh,"P=3 (0, -2+-1j); Z=0; sigma_a=-4/3; break-in s=-5/3 (K=50/27), breakaway s=-1 (K=2); theta_d=-63.4349 deg; jw=+-sqrt(5) (K_crit=20); estavel 00","P=2 (0, -4); Z=0; sigma_a=-2.0; theta_a=[90,270] deg; breakaway s=-2.0 (K=4.0); estavel K>0",0.00e+00,0.00e+00,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Sistema de 2a ordem Tipo 1 com ramos verticais simetricos em Re(s)=-2 para K >= 4." +LGR_Q2B_EQ05,Exercicios_-_LGR.pdf,2(b),5,"G(s) = k / (s(s + 1)(s + 2))",LGR + Routh,"P=3 (0, -1, -2); Z=0; sigma_a=-1; theta_a=[60,180,300] deg; breakaway s=-0.422650 (K=0.384900); jw=+-sqrt(2) (K_crit=6); estavel 00","P=2 (-1+-1.414214j); Z=1 (-2); sigma_a=0.0; theta_a=[180] deg; break-in s=-3.732051 (K=5.464102); theta_d=144.7356 deg; estavel K>0",8.88e-16,1.62e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Preservado na matriz conforme exigido; resultados identicos ao item 1(b) Eq.(2)." +LGR_Q2D_EQ07,Exercicios_-_LGR.pdf,2(d),7,"G(s) = k / (s(s^2 + 6s + 25))",LGR + Routh,"P=3 (0, -3+-4j); Z=0; sigma_a=-2; theta_a=[60,180,300] deg; theta_d=-36.8699 deg; jw=+-5 rad/s (K_crit=150); estavel 00","P=2 (0, -1); Z=2 (-2, -3); centroide=null; break s=-0.633975 (K=0.071797) e s=-2.366025 (K=13.928203); estavel K>0",1.78e-15,1.28e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Sistema de grau relativo zero (P=Z=2); ambos os ramos terminam nos zeros finitos -2 e -3." +LGR_Q2F_EQ09,Exercicios_-_LGR.pdf,2(f),9,"G(s) = k(s^2 + 2s + 8) / (s(s + 10)(s + 5))",LGR + Routh,"P=3 (0, -5, -10); Z=2 (-1+-sqrt(7)j); sigma_a=-13; theta_a=[180] deg; breakaway s=-1.667945 (K=6.218909); theta_a_arr=-109.4312 deg; estavel K>0","P=3 (0, -5, -10); Z=2 (-1+-2.645751j); sigma_a=-13.0; theta_a=[180] deg; breakaway s=-1.667945 (K=6.218909); theta_a_arr=-109.4312 deg; estavel K>0",3.55e-15,5.71e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Zeros complexos conjugados finitos com angulo de chegada validado em -109.4312 deg." +LGR_Q2G_EQ10,Exercicios_-_LGR.pdf,2(g),10,"G(s) = k(s^2 + 4) / ((s + 2)^2 (s + 5)(s + 6))",LGR + Routh,"P=4 (-2x2, -5, -6); Z=2 (+-2j); sigma_a=-7.5; theta_a=[90,270] deg; breakaway s=-5.530716 (K=0.089761) e s=-2 (K=0); theta_a_arr=-139.7636 deg; estavel K>0","P=4 (-2x2, -5, -6); Z=2 (+-2j); sigma_a=-7.5; theta_a=[90,270] deg; breakaway s=-5.530716 (K=0.089761); theta_a_arr=-139.7636 deg; estavel K>0",3.14e-08,1.57e-08,1e-4,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Polo duplo em s=-2 parte a +-90 deg em K=0; zeros em +-2j sao atingidos apenas no limite K->+inf." +LGR_Q2H_EQ11,Exercicios_-_LGR.pdf,2(h),11,"G(s) = k / ((s + 1)(s^2 + 4s + 5))",LGR + Routh,"P=3 (-1, -2+-1j); Z=0; sigma_a=-5/3; theta_a=[60,180,300] deg; theta_d=-45 deg; jw=+-3 rad/s (K_crit=40); estavel 00","P=3 (-1, -3+-1j); Z=1 (-2); sigma_a=-2.5; theta_a=[90,270] deg; sem break real; theta_d=71.5651 deg; estavel K>0",1.78e-15,5.92e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Segundo item rotulado 2(i) na lista (Eq. 13); polo em -1 vai para zero em -2 e par complexo segue assintotas verticais em -2.5." +LGR_Q3A_EQ14,Exercicios_-_LGR.pdf,3(a),14,"G(s) = k / (s(s^2 + 4s + 5)), H(s) = 1",LGR + Routh + BlockLab,"P=3 (0, -2+-1j); Z=0; sigma_a=-4/3; break-in s=-5/3 (K=50/27), breakaway s=-1 (K=2); theta_d=-63.4349 deg; jw=+-sqrt(5) (K_crit=20); estavel 00","P=3 (0x2, -3.6); Z=1 (-1); sigma_a=-1.3; theta_a=[90,270] deg; sem break K>0 (partida em s=0 para K=0); estavel K>0",8.88e-16,2.47e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, blocklab-core, mscript",PASS,PASS,PASS,PASS,PASS,"Coeficiente fracionario 3.6 e polo duplo na origem; o zero em -1 atrai os ramos de s=0 para o semiplano esquerdo para todo K>0." +LGR_Q4A_EQ17,Exercicios_-_LGR.pdf,4(a),17,"G(s) = k(s + 2) / (s^2 + 4s + 13)",LGR + Routh,"P=2 (-2+-3j); Z=1 (-2); sigma_a=-2; theta_a=[180] deg; break-in s=-5 (K=6); theta_d=-180 deg; estavel K>0","P=2 (-2+-3j); Z=1 (-2); sigma_a=-2.0; theta_a=[180] deg; break-in s=-5.0 (K=6.0); theta_d=-180.0 deg; estavel K>0",8.88e-16,1.48e-16,1e-6,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"LGR circular centrado em s=-2 com raio 3; ramos partem verticalmente na direcao 180 deg e entram no eixo real em s=-5." +LGR_Q4B_EQ18,Exercicios_-_LGR.pdf,4(b),18,"G(s) = k(s - 2)(s - 4) / (s^2 + 6s + 25)",LGR + Routh,"P=2 (-3+-4j); Z=2 (+2, +4); grau relativo 0; break-in s=2.885303 (K=51.311819); theta_d=21.5953 deg; jw=+-sqrt(16.5) (K_crit=1); estavel 0instavel em K=1." +LGR_Q5_EQ19,Exercicios_-_LGR.pdf,5(a-b),19,"s^3 + a2*s^2 + a1*s + a1 = 0 (a2 = 0) => G(s)H(s) = a1(s + 1)/s^3",LGR + Routh,"P=3 (0x3); Z=1 (-1); sigma_a=+0.5; theta_a=[90,270] deg; partida de s=0 em [60,180,300] deg; instavel para todo K=a1>0","P=3 (0x3); Z=1 (-1); sigma_a=+0.5; theta_a=[90,270] deg; partida de s=0 em [60,180,300] deg; sem faixa estavel (instavel K>0)",0.00e+00,0.00e+00,1e-4,Analytical + MATLAB R2022b,"lgr, routh, mscript",PASS,PASS,PASS,PASS,PASS,"Problema parametrico com a2=0; polo triplo na origem e centroide no SPD (+0.5) tornam o sistema instavel para qualquer a1 > 0." +CTRL_Q01_PI,Projeto_de_controladores.pdf,1,N/A,"G(s) = 1 / ((s + 0.2)(s + 0.644)) [reconstruido dos graficos]",PI classico LGR (xi=0.456, wn=0.706),"Kp=0.498493, Ki=0.099751, z=0.200105; polos MF: -0.321936+-0.628326j, -0.200128; Mp=20.00%, ts(2%)=11.79s, y(inf)=1, ess=0","Kp=0.498493, Ki=0.099751, z=0.200105; polos MF: -0.321936+-0.628326j, -0.200128; Mp=20.00%, ts(2%)=11.80s, y(inf)=1.0, ess=0.0",1.69e-03,8.45e-05,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, mscript",PASS,PASS,PASS,PASS,PASS,"Alocacao exata de polos; alerta emitido para cancelamento aproximado do 3o polo em -0.200128 pelo zero em -0.200105 e ambiguidade do ganho DC grafico." +CTRL_Q02_PD_CLASSIC,Projeto_de_controladores.pdf,2 (classic PD),N/A,"G(s) = 1 / (s^2 + 1) [reconstruido dos graficos]",PD classico LGR (xi=0.5, ts(2%)=4s),"Kp=3.0, Kd=2.0, z=1.5; polos MF: -1+-sqrt(3)j; Mp_medido=41.251%, ts(2%)=3.723s, y(inf)=0.75, ess=0.25","Kp=3.0, Kd=2.0, z=1.5; polos MF: -1+-1.732051j; Mp=41.259%, ts(2%)=3.723s; verification=FAIL",8.12e-03,1.97e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, mscript",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: numericamente exato vs MATLAB, mas Mp=41.25% viola Mp<=16.3% (+24.95 pp) e ts=3.723s viola ts=4s; zero em -1.5." +CTRL_Q02_PID_EQUAL_CLASSIC,Projeto_de_controladores.pdf,2 (classic PID equal),N/A,"G(s) = 1 / (s^2 + 1) [variante com erro nulo]",PID zeros iguais classico LGR (xi=0.5, ts=4s, ess=0),"Kp=3.737034, Ki=1.474068, Kd=2.368517, z0=0.788897; polos MF: -1+-sqrt(3)j, -0.368517; Mp=13.970%, ts(2%)=7.639s, ess=0","Kp=3.737034, Ki=1.474068, Kd=2.368517, z0=0.788897; polos MF: -1+-1.732051j, -0.368517; Mp=13.985%, ts(2%)=7.639s; verification=FAIL",1.58e-02,1.13e-03,1e-4,Analytical + MATLAB R2022b,"controllers, time_response, mscript",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO E CORRIGIDO: polo lento em -0.3685 eleva ts para 7.639s (viola ts=4s); corrigida transcricao incorreta de 42.20%/6.14s do relatorio anterior." +CTRL_Q03_PD,Projeto_de_controladores.pdf,3,N/A,"Malha interna 18/((2s+11)(2s+1)) com H_in=0.5 em serie com 1/(30s) => G(s) = 3/(20s(s+1)(s+5))",PD classico LGR (sd = -1 +- 1j, ess=0),"Kp=53.333333, Kd=33.333333, z=1.6; polos MF: -1+-1j, -4; Mp=8.094%, ts(2%)=3.913s, y(inf)=1, ess=0","Kp=53.333333, Kd=33.333333, z=1.6; polos MF: -1+-1j, -4.0; Mp=8.094%, ts(2%)=3.914s, ess=0.0",2.11e-03,5.39e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript",PASS,PASS,PASS,PASS,PASS,"Polos dominantes e ess=0 atendidos; alertas emitidos para razao de dominancia do 3o polo (4 < 5) e zero em -1.6." +CTRL_Q04_PI,Projeto_de_controladores.pdf,4,N/A,"G(s) = 5/(s + 0.1), H(s) = 0.05 => G(s)H(s) = 0.25/(s + 0.1)",PI classico LGR (sd = -1 +- sqrt(3)j, e_a(inf)=0),"Kp=7.6, Ki=16.0, z=2.105263; polos MF: -1+-sqrt(3)j; e_a(inf)=0, y(inf)=20, erro rastreamento=-19","Kp=7.6, Ki=16.0, z=2.105263; polos MF: -1+-1.732051j; e_a(inf)=0.0, y(inf)=20.0, erro rastreamento=-19.0",5.64e-03,1.50e-03,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript",PASS,PASS,PASS,PASS,PASS,"Realimentacao nao unitaria H=0.05: erro atuante no somador e_a(inf)=0 atendido; motor alerta explicitamente que y(inf)=20 (r-y=-19)." +CTRL_Q05_PID_CANCEL_CLASSIC,Projeto_de_controladores.pdf,5 (classic cancel),N/A,"G(s) = 1 / (s^3 + 10s^2 + 17s + 8) = 1 / ((s + 1)^2 (s + 8))",PID classico cancelamento (xi=0.4, ts(2%)=1s, ess=0),"Kp=200, Ki=100, Kd=100, z1=z2=1; polos MF: -4+-sqrt(84)j, -1, -1; Mp=25.374%, ts(2%)=0.841s, ess=0","Kp=200.0, Ki=100.0, Kd=100.0; Mp=25.376%, ts(2%)=0.841s; verification=FAIL (literal ts=1.0+-0.05s)",1.44e-02,5.67e-04,1e-4,Analytical + MATLAB R2022b,"controllers, time_response, mscript",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: alocacao de polos 4/sigma=1 produz ts real de 0.841s (viola igualdade literal ts=1.0+-0.05s) e depende de cancelamento duplo fragil (s+1)^2." +CTRL_Q05_PID_EQUAL_CLASSIC,Projeto_de_controladores.pdf,5 (classic equal),N/A,"G(s) = 1 / (s^3 + 10s^2 + 17s + 8)",PID classico zeros iguais (xi=0.4, ts(2%)=1s, ess=0),"Kp=200, Ki=100, Kd=100, z0=1; Mp=25.374%, ts(2%)=0.841s, ess=0","Kp=200.0, Ki=100.0, Kd=100.0; Mp=25.376%, ts(2%)=0.841s; verification=FAIL (literal ts=1.0+-0.05s)",1.44e-02,5.67e-04,1e-4,Analytical + MATLAB R2022b,"controllers, time_response, mscript",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: identico ao modo cancelamento; ts real 0.841s viola ts=1.0+-0.05s literal." +CTRL_Q05_PID_DISTINCT_CLASSIC,Projeto_de_controladores.pdf,5 (classic distinct),N/A,"G(s) = 1 / (s^3 + 10s^2 + 17s + 8)",PID classico zeros distintos (zi=0.4, xi=0.4, ts=1s),"Kp=197.029703, Ki=62.871287, Kd=99.628713; polos MF: -4+-sqrt(84)j, -1.6093, -0.3907; Mp=24.474%, ts(2%)=0.874s","Kp=197.029703, Ki=62.871287, Kd=99.628713; Mp=24.492%, ts(2%)=0.874s; verification=FAIL (literal ts=1.0+-0.05s)",1.46e-02,5.96e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, mscript",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: ts real 0.874s viola ts=1.0+-0.05s literal; polo lento em -0.391 quase cancelado por zero em -0.4." +CTRL_Q06_PD,Projeto_de_controladores.pdf,6,N/A,"G(s) = 1 / (s(s + 2)^2), Gc(s) = kp + kd*s, H(s) = 1",PD classico LGR (xi=0.5, wn=2 rad/s, ess=0),"Kp=8.0, Kd=4.0, z=2.0; T_min(s)=4/(s^2+2s+4); polos MF: -1+-sqrt(3)j, -2 (cancelado); Mp=16.293%, ts(2%)=4.038s","Kp=8.0, Kd=4.0, z=2.0; polos MF: -1+-1.732051j, -2.0; Mp=16.303%, ts(2%)=4.038s, ess=0.0",1.04e-02,6.38e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript",PASS,PASS,PASS,PASS,PASS,"Enunciado especifica diretamente (xi=0.5, wn=2); polos dominantes e ess=0 atendidos com alerta de cancelamento nominal em s=-2." +CTRL_Q07_PD_CLASSIC,Projeto_de_controladores.pdf,7 (classic PD),N/A,"Malha interna (1/s)/(1+2/s)=1/(s+2) em serie com 5/(s(s+2)) => G(s) = 5/(s(s+2)^2)",PD classico LGR (xi=0.5, ts(2%)=4s, Mp<=16%, ess=0),"Kp=1.6, Kd=0.8, z=2.0; T_min(s)=4/(s^2+2s+4); Mp=16.293%, ts(2%)=4.038s, ess=0","Kp=1.6, Kd=0.8, z=2.0; Mp=16.303%, ts(2%)=4.038s; verification=FAIL (Mp>16% e conflito xi=0.5)",1.04e-02,6.38e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: viola limite literal Mp<=16.0% (16.30%) devido ao conflito didatico xi=0.5 => 16.303%, alem de ts=4.038s." +CTRL_Q08_PI_CLASSIC,Projeto_de_controladores.pdf,8 (classic PI),N/A,"G_p(s) = -7.2/(5s + 1) = -1.44/(s + 0.2)",PI classico LGR (ts(2%)<=4s, Mp<=25%, ess=0),"Kp=-1.25, Ki=-4.260814, z=3.408651; polos MF: -1+-2.266180j; Mp=33.841%, ts(2%)=3.965s, ess=0","Kp=-1.25, Ki=-4.260814, z=3.408651; Mp=33.844%, ts(2%)=3.966s; verification=FAIL (Mp>25%)",3.53e-03,8.90e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript, native-gui",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: zero do PI em -3.4087 eleva Mp para 33.84% (+8.84 pp acima do limite de 25%); GUI exibe banner vermelho NAO CONFORME." +CTRL_Q08_PI_DIST,Projeto_de_controladores.pdf,8 (dist),N/A,"T_d(s) = G_p(s)/(1 + G_c(s)G_p(s)) = -1.44s/(s^2 + 2s + 6.135572), T_p(s) = 1/s",Rejeicao de perturbacao ao degrau,"w_d(t) = (-1.44/2.26618)*e^(-t)*sin(2.26618*t); pico=-0.31257 rad/s; w_d(inf)=0","w_d(t) coincide com solucao analitica (erro max 4.2e-15); w_d(inf)=0.0",4.22e-15,1.35e-14,1e-4,Analytical + MATLAB R2022b,"time_response, blocklab-core, mscript",PASS,PASS,PASS,PASS,PASS,"Acao integral do PI rejeita completamente a perturbacao constante de carga em regime permanente (T_d(0)=0)." +CTRL_Q09_PD_CLASSIC,Projeto_de_controladores.pdf,9 (classic PD),N/A,"Diagrama de 2a ordem com wn=1, xi=0 => G(s) = 1/s^2",PD classico LGR (xi=0.5, Mp<=16%, ts(2%)<=4s, ess=0),"Kp=4.0, Kd=2.0, z=2.0; T(s)=(2s+4)/(s^2+2s+4); Mp=29.835%, ts(2%)=3.753s, ess=0","Kp=4.0, Kd=2.0, z=2.0; Mp=29.844%, ts(2%)=3.753s; verification=FAIL (Mp>16% e conflito xi=0.5)",8.35e-03,2.80e-04,1e-6,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript, native-gui",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 10 RECLASSIFICADO: zero do PD em -2 eleva Mp para 29.84% (+13.84 pp acima de 16%); GUI exibe banner vermelho NAO CONFORME." +CTRL_Q08_PI_INDEPENDENT_REF,Projeto_de_controladores.pdf,8 (ref independente),N/A,"G_p(s) = -7.2/(5s + 1), Gc(s) = -1 - 0.2/s",Referencia independente Q8 (Kp=-1, Ki=-0.2),"T(s)=1.44/(s+1.44); Mp=0%, ts(2%)=ln(50)/1.44=2.716683s, y(inf)=1, ess=0, T_d(0)=0; estavel sob +-10% em k e tau","T(s)=1.44/(s+1.44); Mp=0.000%, ts(2%)=2.71668s, y(inf)=1.0, ess=0.0, T_d(0)=0.0; estavel e conforme sob +-10% em k e tau",3.57e-05,1.31e-05,1e-3,Analytical + MATLAB R2022b,"controllers, time_response, blocklab-core, mscript, native-gui",PASS,PASS,PASS,PASS,PASS,"ETAPA 10 SECAO 4: validada no motor Rust, Studio .m, BlockLab (Mason exato), Resposta no Tempo e GUI; internamente estavel e robusta." +CTRL_Q02_PD_REFINED,Projeto_de_controladores.pdf,2 (refined PD - xi estimado/minimo),N/A,"G(s) = 1 / (s^2 + 1)",PD temporal_refined (Mp<=16.3%, ts(2%)=4.0+-0.08s, xi>=0.5),"MATLAB R2022b (E10): Mp=16.2558%, ts=3.999s, xi=1.0 (polos reais); sob igualdade exata xi=0.5+Mp<=16.3% e INVIABILIDADE MATEMATICA COMPROVADA","Kp=6.5861, Kd=13.3556 (E10) / Kp=6.9140, Kd=14.2861 (E11); Mp<=16.3%, ts=4.000s, xi=1.0>=0.5; sob xi=0.5 exato: ProvenInfeasible",3.04e-04,1.87e-05,1e-2,Analytical + MATLAB R2022b,"controllers, controller_synthesis, time_response",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 AUDITADO: atende Mp<=16.3%, ts=4s e xi>=0.5 (polos reais); provado matematicamente inviavel manter igualdade exata xi=0.5 com PD (Mp>29.84% para todo wn>1)." +CTRL_Q02_PID_REFINED,Projeto_de_controladores.pdf,2 (refined PID - xi estimado/minimo),N/A,"G(s) = 1 / (s^2 + 1)",PID temporal_refined (Mp<=16.3%, ts(2%)=4.0+-0.08s, ess=0, xi>=0.5),"MATLAB R2022b (E10): Mp=15.3430%, ts=4.000s, xi=0.816905 (par -2.486+-1.755j), dcgain=1.0","Kp=11.0967, Ki=5.2851, Kd=5.5422; Mp=15.3470%, ts=4.000s, ess=0.0, xi=0.8169>=0.5",3.98e-03,2.60e-04,1e-2,MATLAB R2022b,"controllers, controller_synthesis, time_response",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 AUDITADO: atende Mp<=16.3%, ts=4s, ess=0 e xi>=0.5; nao preserva igualdade exata xi=0.5 (ver CTRL_Q02_PID_EXACT_XI05)." +CTRL_Q05_PID_REFINED,Projeto_de_controladores.pdf,5 (refined PID E10 - sem igualdade xi),N/A,"G(s) = 1 / (s^3 + 10s^2 + 17s + 8)",PID temporal_refined E10 (ts(2%)=1.0s, ess=0; xi nao imposto como igualdade),"MATLAB R2022b (E10): Mp=5.9730%, ts=0.99991s, xi=0.666854 (viola igualdade xi=0.4)","Kp=71.8864, Ki=35.9007, Kd=35.9856; ts=0.99989s, ess=0.0, xi=0.6669; verification(xi=0.4 obrigatoria)=FAIL",5.70e-05,1.90e-05,1e-2,MATLAB R2022b,"controllers, controller_synthesis, time_response",PASS,FAIL,PASS,PASS,FAIL,"ETAPA 11 RECLASSIFICADO: satisfaz ts=1.0s e ess=0, mas xi=0.6669 viola igualdade explicita xi=0.4 do enunciado (resolvido em CTRL_Q05_PID_EXACT_XI04)." +CTRL_Q07_PD_REFINED,Projeto_de_controladores.pdf,7 (refined PD - xi estimado/minimo),N/A,"G(s) = 5 / (s(s + 2)^2)",PD temporal_refined (Mp<=16.0%, ts(2%)=4.0+-0.08s, ess=0, xi>=0.5),"MATLAB R2022b (E10): Mp=0.1882%, ts=4.00028s, xi=0.894050 (par -1.037+-0.520j), dcgain=1.0","Kp=0.5183, Kd=0.2681; Mp=0.1882%, ts=4.00017s, ess=0.0, xi=0.8941>=0.5",1.11e-04,2.78e-05,1e-2,MATLAB R2022b,"controllers, controller_synthesis, time_response",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 AUDITADO: atende Mp<=16%, ts=4s, ess=0 e xi>=0.5; ver CTRL_Q07_PD_EXACT_XI05_DOM para xi=0.50+-0.01 dominante." +CTRL_Q08_PI_REFINED,Projeto_de_controladores.pdf,8 (refined PI / auto_simplest),N/A,"G_p(s) = -7.2/(5s + 1)",PI temporal_refined e auto_simplest (Mp<=25%, ts(2%)<=4.0s, ess=0),"MATLAB R2022b: E10 Mp=0.0%, ts=3.989s; E11 Mp=1.854%, ts=3.992s, polos reais (-0.638, -0.285), dcgain=1.0","E11 auto_simplest: Kp=-0.5022, Ki=-0.1263; Mp=1.854%, ts=3.990s<=4s, ess=0.0 (sem cancelamento fragil)",1.99e-03,5.00e-04,1e-2,MATLAB R2022b,"controllers, controller_synthesis, time_response, native-gui",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 AUDITADO: Q8 nao impoe igualdade de xi (apenas Mp<=25%, ts<=4s, ess=0); auto_simplest descarta P (Tipo 0) e encontra PI sem cancelamento polo-zero exato." +CTRL_Q09_PD_REFINED,Projeto_de_controladores.pdf,9 (refined PD - xi estimado/minimo),N/A,"G(s) = 1 / s^2",PD temporal_refined e auto_simplest (Mp<=16.0%, ts(2%)<=4.0s, ess=0, xi>=0.5),"MATLAB R2022b (E10): Mp=15.020%, ts=3.990s, xi=0.923609; sob igualdade exata xi=0.5+Mp<=16% e INVIABILIDADE MATEMATICA COMPROVADA","E10: Kp=1.7459, Kd=2.4408 (xi=0.9236, Mp=15.02%); E11: Kp=0.1035, Kd=2.1208 (xi=1.0, Mp=2.01%); sob xi=0.5 exato: ProvenInfeasible",4.40e-04,3.58e-05,1e-2,Analytical + MATLAB R2022b,"controllers, controller_synthesis, time_response, native-gui",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 AUDITADO: atende Mp<=16%, ts<=4s, ess=0 e xi>=0.5; provado matematicamente inviavel manter igualdade exata xi=0.5 com PD (invariancia de escala impoe Mp=29.835%)." +CTRL_Q05_PID_EXACT_XI04,Projeto_de_controladores.pdf,5 (Etapa 11 PID - igualdade exata xi=0.4),N/A,"G(s) = 1 / (s^3 + 10s^2 + 17s + 8)",PID temporal_refined (xi=0.40+-0.01 obrigatoria, ts(2%)=1.00+-0.02s, ess=0),"MATLAB R2022b: xi=0.400000, wn=8.7239, res_ratio=0.1056, Mp=28.836%, ts=0.9970s, dcgain=1.0; estavel e dentro das metas sob +-5% no polo duplo","Kp=227.1227, Ki=56.8652, Kd=80.9373; polos -3.4896+-7.9956j, -2.7491, -0.2718; xi=0.4000, ts=0.9969s, res_ratio=0.1056, ess=0.0",7.16e-03,2.48e-04,1e-2,Analytical + MATLAB R2022b,"controllers, controller_synthesis, time_response, native-gui",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 SOLUCAO COMPLETA Q5: satisfaz simultaneamente PID, ess=0, igualdade exata xi=0.4000 e ts=0.997s (1.0+-0.02s), internamente estavel e robusta sob +-5%." +CTRL_Q02_PID_EXACT_XI05,Projeto_de_controladores.pdf,2 (Etapa 11 PID - igualdade exata xi=0.5),N/A,"G(s) = 1 / (s^2 + 1)",PID temporal_refined (xi=0.50+-0.01 obrigatoria, Mp<=16.3%, ts(2%)=4.00+-0.08s, ess=0),"MATLAB R2022b: xi=0.499992 (par dominante -0.6954+-1.2046j), p3=-2.3742, Mp=13.558%, ts=4.0000s, dcgain=1.0","Kp=4.2369, Ki=4.5933, Kd=3.7651 (zeros complexos LHP -0.5627+-0.9505j); xi=0.5000, Mp=13.576%, ts=4.0000s, ess=0.0",1.72e-02,1.27e-03,5e-2,Analytical + MATLAB R2022b,"controllers, controller_synthesis, time_response, native-gui",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 SOLUCAO COMPLETA Q2 PID: satisfaz simultaneamente igualdade exata xi=0.5000 no par dominante, Mp<=16.3%, ts=4.000s e ess=0." +CTRL_Q07_PD_EXACT_XI05_DOM,Projeto_de_controladores.pdf,7 (Etapa 11 PD - xi=0.50+-0.01 dominante),N/A,"G(s) = 5 / (s(s + 2)^2)",PD temporal_refined (xi=0.50+-0.01 obrigatoria, Mp<=16.0%, ts(2%)=4.00+-0.08s, ess=0, par dominante),"MATLAB R2022b: xi=0.504414 (par dominante -1.0200+-1.7461j), p3=-1.9600, z=-1.9607, res_ratio=0.000352, Mp=15.948%, ts=3.9716s","Kp=1.6030, Kd=0.8175; xi=0.5044, Mp=15.950%<=16%, ts=3.9716s, res_ratio=0.000352, ess=0.0",1.22e-03,7.67e-05,1e-2,Analytical + MATLAB R2022b,"controllers, controller_synthesis, time_response",PASS,PASS,PASS,PASS,PASS,"ETAPA 11 SOLUCAO Q7 PD (tol +-0.01): satisfaz xi=0.50+-0.01 no par dominante, Mp<=16.0%, ts=4.0+-0.08s e ess=0; sob tolerancia zero (xi=0.500000 exato) Mp=16.29%>16%." diff --git a/native/modules.json b/native/modules.json index c7da3b5..75e35dd 100644 --- a/native/modules.json +++ b/native/modules.json @@ -147,6 +147,87 @@ ], "showControllerFormula": true }, + { + "name": "synthesis_mode", + "label": "Modo de Síntese", + "type": "select", + "value": "lgr_classic", + "help": "Diferencia a síntese clássica por alocação de polos via LGR do refinamento numérico sobre a resposta temporal real e da seleção automática do controlador mais simples.", + "options": [ + [ + "lgr_classic", + "1. Clássico via LGR (alocação de polos) + verificação real" + ], + [ + "temporal_refined", + "2. Refinamento numérico por restrições temporais (Mp, ts, ess)" + ], + [ + "auto_simplest", + "3. Seleção automática do controlador mais simples (P → PI → PD → Lead → PID)" + ] + ] + }, + { + "name": "ts_constraint", + "label": "Restrição de ts", + "type": "select", + "value": "at_most", + "help": "Define se o tempo de acomodação solicitado é um limite superior (ts ≤ valor) ou uma meta de igualdade (ts = valor).", + "options": [ + [ + "at_most", + "Limite superior (ts ≤ valor)" + ], + [ + "equal", + "Igualdade (ts = valor)" + ] + ], + "when": { + "controller_type": [ + "lead", + "P", + "PD", + "PI", + "PID" + ] + } + }, + { + "name": "xi_constraint", + "label": "Restrição de ξ", + "type": "select", + "value": "auto", + "help": "Define se ξ é tratado automaticamente (igualdade quando informado sem Mp), igualdade obrigatória, limite mínimo (ξ ≥ valor) ou estimativa didática opcional.", + "options": [ + [ + "auto", + "Automático (igualdade se sem Mp)" + ], + [ + "equal", + "Igualdade obrigatória (ξ = valor)" + ], + [ + "at_least", + "Limite mínimo obrigatório (ξ ≥ valor)" + ], + [ + "estimate", + "Estimativa didática opcional" + ] + ], + "when": { + "controller_type": [ + "lead", + "P", + "PD", + "PI", + "PID" + ] + } + }, { "name": "input_type", "label": "Entrada R(s)", diff --git a/native/src/lib.rs b/native/src/lib.rs index e87a6a3..3fa4616 100644 --- a/native/src/lib.rs +++ b/native/src/lib.rs @@ -340,6 +340,18 @@ impl Controlab { && app.schema.contains_key(&page) { app.page = page.clone(); + if let Ok(raw_vals) = std::env::var("CONTROLAB_SCREENSHOT_VALUES") + && let Ok(Value::Object(map)) = serde_json::from_str::(&raw_vals) + && let Some(analysis) = app.analyses.get_mut(&page) + { + for (k, v) in map { + let s = v + .as_str() + .map(str::to_owned) + .unwrap_or_else(|| v.to_string()); + analysis.values.insert(k, s); + } + } if std::env::var_os("CONTROLAB_SCREENSHOT_EMPTY").is_none() { app.calculate(&page, 1080.0); } @@ -489,6 +501,9 @@ impl Controlab { Ok(mut payload) => { payload["response_type"] = json!(a.response); payload["language"] = json!("pt-BR"); + if id == "controllers" { + payload["verify_requirements"] = json!(true); + } if plot_width > 100.0 { payload["width"] = json!(plot_width.round()); } @@ -595,9 +610,15 @@ impl Controlab { a.pan = egui::Vec2::ZERO; a.result = reply; let expr = a.values.get(field).cloned().unwrap_or_default(); + let requirements_failed = tag == "controllers" + && a.result["details"]["verification"]["requirements_passed"].as_bool() == Some(false); let message = match tag { "routh" => "Estabilidade calculada com sucesso!".to_owned(), "lgr" => "LGR calculado e traçado com sucesso!".to_owned(), + "controllers" if requirements_failed => { + "Controlador calculado, mas especificações obrigatórias não foram atendidas." + .to_owned() + } _ => format!("{title} concluída."), }; let name = if expr.is_empty() { title } else { expr.clone() }; @@ -609,7 +630,14 @@ impl Controlab { kind: "math".into(), timestamp: unix_millis(), }); - self.toast(message, ToastKind::Success); + self.toast( + message, + if requirements_failed { + ToastKind::Error + } else { + ToastKind::Success + }, + ); } fn finish_script(&mut self, tag: &str, reply: Value, success: bool, error: String) { diff --git a/native/src/results.rs b/native/src/results.rs index 2e91e2f..b23e206 100644 --- a/native/src/results.rs +++ b/native/src/results.rs @@ -430,6 +430,9 @@ fn scientific(ui: &mut Ui, view: &View, f: &mut Formulas) { } else { latex_grid(ui, view, f, latex); } + if view.id == "controllers" && r["details"]["verification"].is_object() { + verification_panel(ui, p, &r["details"]["verification"]); + } for (i, metric) in list(&r["metrics"]).iter().enumerate() { if let Some(header) = metric["header"].as_str() { kit::group_header(ui, p, header); @@ -451,6 +454,134 @@ fn scientific(ui: &mut Ui, view: &View, f: &mut Formulas) { steps_panel(ui, p, f, list(&r["details"]["steps"])); } +/// Controller requirement verification banner, comparison table, and technical warnings. +fn verification_panel(ui: &mut Ui, p: &Palette, verification: &Value) { + let passed = verification["requirements_passed"] + .as_bool() + .unwrap_or(false); + let overall = verification["overall_status"].as_str().unwrap_or("FAIL"); + let (tone, headline) = match (passed, overall) { + (true, "PASS") => (p.stable, "CONFORME — Todas as especificações atendidas"), + (true, _) => ( + p.marginal, + "CONFORME COM ALERTAS — Especificações atendidas (ver advertências)", + ), + (false, _) => ( + p.unstable, + "NÃO CONFORME — Especificações obrigatórias não atendidas", + ), + }; + + ui.add_space(6.0); + kit::frame(tone.bg, tone.border, 5, 8).show(ui, |ui| { + ui.set_width(ui.available_width()); + let g = kit::wrapped( + ui, + headline, + sans(12.5, Weight::Bold), + tone.fg, + ui.available_width().max(40.0), + ); + let (rect, _) = ui.allocate_exact_size(g.size(), Sense::hover()); + ui.painter().galley(rect.min, g, tone.fg); + + let failed = list(&verification["failed_requirements"]); + if !passed && !failed.is_empty() { + ui.add_space(4.0); + let reasons: Vec<&str> = failed.iter().filter_map(|v| v.as_str()).collect(); + let detail = format!("Motivos de não conformidade: {}", reasons.join("; ")); + let gd = kit::wrapped( + ui, + &detail, + sans(11.3, Weight::Regular), + p.text, + ui.available_width().max(40.0), + ); + let (rd, _) = ui.allocate_exact_size(gd.size(), Sense::hover()); + ui.painter().galley(rd.min, gd, p.text); + } + }); + + if let Some(modal) = verification.get("modal_analysis").filter(|v| v.is_object()) + && let Some(pole_lbl) = modal["damping_pole_label"].as_str() + { + ui.add_space(4.0); + let mut ref_line = format!("Referência modal para ξ e ωn: {pole_lbl}"); + if let Some(rr) = modal["non_dominant_residue_ratio"].as_f64() { + ref_line.push_str(&format!(" | razão de resíduos não dominantes: {:.3}", rr)); + } + kit::striped_row(ui, p, 0, "Polo(s) de referência (ξ/ωn)", &ref_line); + } + + let checks = list(&verification["checks"]); + if !checks.is_empty() { + ui.add_space(6.0); + kit::group_header(ui, p, "VERIFICAÇÃO DE ESPECIFICAÇÕES (SOLICITADO × REAL)"); + for (idx, ck) in checks.iter().enumerate() { + let label = ck["label"].as_str().unwrap_or("Requisito"); + let req = ck["requested"].as_str().unwrap_or("—"); + let theo = ck["theoretical"].as_str().unwrap_or("—"); + let meas = ck["measured"].as_str().unwrap_or("—"); + let diff = ck["difference"].as_str().unwrap_or("—"); + let status = ck["status"].as_str().unwrap_or("FAIL"); + let mandatory = ck["mandatory"].as_bool().unwrap_or(true); + let kind_tag = if mandatory { + "[OBRIGATÓRIA]" + } else { + "[ESTIMATIVA OPCIONAL]" + }; + let badge_label = match status { + "PASS" => "ATENDIDO", + "WARNING" => "ALERTA", + _ => "NÃO ATENDIDO", + }; + let summary = if theo != "—" && theo != req { + format!( + "{meas} {kind_tag} (sol.: {req} | teór.: {theo} | dif.: {diff}) — {badge_label}" + ) + } else if diff != "—" { + format!("{meas} {kind_tag} (sol.: {req} | dif.: {diff}) — {badge_label}") + } else { + format!("{meas} {kind_tag} — {badge_label}") + }; + kit::striped_row(ui, p, idx, label, &summary); + } + } + + let warnings = list(&verification["warnings"]); + if !warnings.is_empty() { + ui.add_space(6.0); + kit::frame(p.marginal.bg, p.marginal.border, 5, 8).show(ui, |ui| { + ui.set_width(ui.available_width()); + let title = kit::wrapped( + ui, + "ADVERTÊNCIAS TÉCNICAS (DOMINÂNCIA, CANCELAMENTOS E APROXIMAÇÕES)", + sans(11.2, Weight::Bold), + p.marginal.fg, + ui.available_width().max(40.0), + ); + let (r, _) = ui.allocate_exact_size(title.size(), Sense::hover()); + ui.painter().galley(r.min, title, p.marginal.fg); + ui.add_space(4.0); + for w in warnings { + if let Some(text_w) = w.as_str() { + let g = kit::wrapped( + ui, + &format!("• {text_w}"), + sans(11.5, Weight::Regular), + p.text, + ui.available_width().max(40.0), + ); + let (rw, _) = ui.allocate_exact_size(g.size(), Sense::hover()); + ui.painter().galley(rw.min, g, p.text); + ui.add_space(2.0); + } + } + }); + } + ui.add_space(6.0); +} + /// `.scientific-latex-grid`: two columns of cards; the last odd card spans both. fn latex_grid(ui: &mut Ui, view: &View, f: &mut Formulas, items: &[Value]) { if items.is_empty() { diff --git a/native/src/ui_tests.rs b/native/src/ui_tests.rs index b498d44..c43598d 100644 --- a/native/src/ui_tests.rs +++ b/native/src/ui_tests.rs @@ -1072,3 +1072,90 @@ fn settings_updates_card_does_not_expand_into_empty_vertical_space() { ); } } + +#[test] +fn controller_verification_ui_flags_non_compliant_classic_and_approves_refined() { + let ctx = egui::Context::default(); + let mut app = fixture(&ctx, false); + app.page = "controllers".into(); + + // 1. Q8 classic PI: numerically valid, but real Mp = 33.84% > 25% => UI MUST flag NÃO CONFORME. + { + let analysis = app.analyses.get_mut("controllers").unwrap(); + analysis + .values + .insert("plant_expr".into(), "-7.2/(5*s + 1)".into()); + analysis + .values + .insert("controller_type".into(), "PI".into()); + analysis + .values + .insert("input_type".into(), "time_spec".into()); + analysis.values.insert("ts".into(), "4".into()); + analysis.values.insert("mp".into(), "25".into()); + analysis.values.insert("xi".into(), String::new()); + analysis.values.insert("wn".into(), String::new()); + analysis + .values + .insert("synthesis_mode".into(), "lgr_classic".into()); + analysis + .values + .insert("ts_constraint".into(), "at_most".into()); + } + app.calculate("controllers", 1080.0); + wait(&mut app, &ctx, "controllers classic Q8", |a| { + let an = &a.analyses["controllers"]; + !an.pending && an.result.is_object() + }); + let classic_res = &app.analyses["controllers"].result; + assert_eq!( + classic_res["details"]["verification"]["requirements_passed"], + false + ); + assert_eq!( + classic_res["details"]["verification"]["overall_status"], + "FAIL" + ); + + render_sized(&mut app, &ctx, 1920.0, 6000.0); + let classic_labels = render_sized(&mut app, &ctx, 1920.0, 6000.0); + assert!( + classic_labels.contains("NÃO CONFORME"), + "UI must display NÃO CONFORME banner for non-compliant Q8 classic PI" + ); + assert!( + classic_labels.contains("VERIFICAÇÃO DE ESPECIFICAÇÕES") + && classic_labels.contains("NÃO ATENDIDO") + && classic_labels.contains("33,84") + && classic_labels.contains("[OBRIGATÓRIA]") + && classic_labels.contains("Motivos de não conformidade") + && classic_labels.contains("Polo(s) de referência (ξ/ωn)"), + "UI must display verification table with mandatory tags, non-compliance reasons, pole reference, and measured 33,84%" + ); + + // 2. Q8 refined PI: must satisfy all constraints and display CONFORME (with technical alerts). + { + let analysis = app.analyses.get_mut("controllers").unwrap(); + analysis + .values + .insert("synthesis_mode".into(), "temporal_refined".into()); + analysis.result = Value::Null; + } + app.calculate("controllers", 1080.0); + wait(&mut app, &ctx, "controllers refined Q8", |a| { + let an = &a.analyses["controllers"]; + !an.pending && an.result.is_object() + }); + let refined_res = &app.analyses["controllers"].result; + assert_eq!( + refined_res["details"]["verification"]["requirements_passed"], + true + ); + + render_sized(&mut app, &ctx, 1920.0, 6000.0); + let refined_labels = render_sized(&mut app, &ctx, 1920.0, 6000.0); + assert!( + refined_labels.contains("CONFORME") && !refined_labels.contains("NÃO CONFORME"), + "UI must display CONFORME banner and not NÃO CONFORME for compliant Q8 refined PI" + ); +}