1use ndarray::s;
6use lib_jsl_linalg::{Eig, SVD};
7
8use crate::{
9 dsp::discrete::stream_operator::{StreamOperator, StreamOperatorManagement},
10 prelude::{C1D, C2D, ErrorsJSL},
11};
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum OutputConvention {
16 Standard,
19 Updated,
23}
24
25pub struct StateSpace {
38 pub a: C2D,
40 pub b: C2D,
42 pub c: C2D,
44 pub d: C2D,
46 pub x: C1D,
48 initial_x: C1D,
49 convention: OutputConvention,
50}
51
52impl StateSpace {
53 pub fn new(a: C2D, b: C2D, c: C2D, d: C2D, x: C1D) -> Result<Self, ErrorsJSL> {
64 Self::with_convention(a, b, c, d, x, OutputConvention::Updated)
65 }
66
67 pub fn new_standard(a: C2D, b: C2D, c: C2D, d: C2D, x: C1D) -> Result<Self, ErrorsJSL> {
73 Self::with_convention(a, b, c, d, x, OutputConvention::Standard)
74 }
75 pub fn with_convention(a: C2D, b: C2D, c: C2D, d: C2D, x: C1D, convention: OutputConvention) -> Result<Self, ErrorsJSL> {
80 if a.nrows() == 0 || a.nrows() != a.ncols() {
81 return Err(ErrorsJSL::InvalidInputRange("A must be a non-empty square matrix"));
82 }
83 if a.nrows() != b.nrows() {
84 return Err(ErrorsJSL::InvalidInputRange("A and B are not compatible size"));
85 }
86 if a.nrows() != x.len() {
87 return Err(ErrorsJSL::InvalidInputRange("A and x are not compatible size"));
88 }
89 if c.nrows() != d.nrows() {
90 return Err(ErrorsJSL::InvalidInputRange("C and D are not compatible size"));
91 }
92 if c.ncols() != a.ncols() {
93 return Err(ErrorsJSL::InvalidInputRange("A and C are not compatible size"));
94 }
95 if b.ncols() != d.ncols() {
96 return Err(ErrorsJSL::InvalidInputRange("B and D are not compatible size"));
97 }
98
99 Ok(Self {
100 a,
101 b,
102 c,
103 d,
104 x: x.clone(),
105 initial_x: x,
106 convention,
107 })
108 }
109
110 pub fn convention(&self) -> OutputConvention {
112 self.convention
113 }
114
115 pub fn to_standard(&self) -> StateSpace {
120 let (c, d) = match self.convention {
121 OutputConvention::Standard => (self.c.clone(), self.d.clone()),
122 OutputConvention::Updated => (self.c.dot(&self.a), self.c.dot(&self.b) + &self.d),
123 };
124 StateSpace {
125 a: self.a.clone(),
126 b: self.b.clone(),
127 c,
128 d,
129 x: self.x.clone(),
130 initial_x: self.initial_x.clone(),
131 convention: OutputConvention::Standard,
132 }
133 }
134
135 pub fn step(&mut self, u: C1D) -> Result<C1D, ErrorsJSL> {
141 if u.len() != self.b.ncols() {
142 return Err(ErrorsJSL::IncompatibleArraySizes((u.len(), self.b.ncols())));
143 }
144
145 match self.convention {
146 OutputConvention::Standard => {
147 let y = self.c.dot(&self.x) + self.d.dot(&u);
148 self.x = self.a.dot(&self.x) + self.b.dot(&u);
149 Ok(y)
150 }
151 OutputConvention::Updated => {
152 self.x = self.a.dot(&self.x) + self.b.dot(&u);
153 Ok(self.c.dot(&self.x) + self.d.dot(&u))
154 }
155 }
156 }
157 pub fn is_observable(&self) -> Result<bool, ErrorsJSL> {
164 let state_dim = self.a.nrows();
165 let output_dim = self.c.nrows();
166 let mut big_matrix = C2D::zeros((output_dim * state_dim, state_dim));
167 let mut accumulation = self.c.clone();
168
169 for block in 0..state_dim {
170 let row_start = block * output_dim;
171 let row_end = row_start + output_dim;
172 big_matrix
173 .slice_mut(s![row_start..row_end, ..])
174 .assign(&accumulation);
175 accumulation = accumulation.dot(&self.a);
176 }
177
178 Ok(Self::matrix_rank(&big_matrix)? == state_dim)
179 }
180
181 pub fn is_controllable(&self) -> Result<bool, ErrorsJSL> {
186 let state_dim = self.a.nrows();
187 let input_dim = self.b.ncols();
188 let mut big_matrix = C2D::zeros((state_dim, input_dim * state_dim));
189 let mut accumulation = self.b.clone();
190
191 for block in 0..state_dim {
192 let col_start = block * input_dim;
193 let col_end = col_start + input_dim;
194 big_matrix
195 .slice_mut(s![.., col_start..col_end])
196 .assign(&accumulation);
197 accumulation = self.a.dot(&accumulation);
198 }
199
200 Ok(Self::matrix_rank(&big_matrix)? == state_dim)
201 }
202
203 pub fn get_poles(&self) -> Result<C1D, ErrorsJSL> {
206 let (eigenvalues, _) = self
207 .a
208 .clone()
209 .eig()
210 .map_err(|_| ErrorsJSL::RuntimeError("failed to compute state-space poles"))?;
211 Ok(eigenvalues)
212 }
213
214 pub fn is_stable(&self) -> Result<bool, ErrorsJSL> {
219 let poles = self.get_poles()?;
220 Ok(poles.iter().all(|pole| pole.norm() < 1.0))
221 }
222
223 fn matrix_rank(matrix: &C2D) -> Result<usize, ErrorsJSL> {
224 let (_, singular_values, _) = matrix
225 .clone()
226 .svd(false, false)
227 .map_err(|_| ErrorsJSL::RuntimeError("failed to compute matrix rank"))?;
228 let max_sigma = singular_values.iter().copied().fold(0.0_f64, f64::max);
229 let tolerance = if max_sigma == 0.0 {
230 0.0
231 } else {
232 max_sigma * (matrix.nrows().max(matrix.ncols()) as f64) * f64::EPSILON
233 };
234 Ok(singular_values
235 .iter()
236 .filter(|&&sigma| sigma > tolerance)
237 .count())
238 }
239}
240
241impl StreamOperatorManagement for StateSpace {
242 fn reset(&mut self) -> Result<(), ErrorsJSL> {
243 self.x = self.initial_x.clone();
244 Ok(())
245 }
246
247 fn finalize(&mut self) -> Result<(), ErrorsJSL> {
248 Ok(())
249 }
250}
251
252impl StreamOperator<C1D, C1D> for StateSpace {
253 fn process(&mut self, data_in: &[C1D]) -> Result<Option<Vec<C1D>>, ErrorsJSL> {
254 if data_in.is_empty() {
255 return Ok(None);
256 }
257
258 let mut output = Vec::with_capacity(data_in.len());
259 for u in data_in {
260 output.push(self.step(u.clone())?);
261 }
262 Ok(Some(output))
263 }
264
265 fn flush(&mut self) -> Result<Option<Vec<C1D>>, ErrorsJSL> {
266 Ok(None)
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273 use ndarray::Array1;
274 use num_complex::Complex;
275
276 fn c(re: f64) -> Complex<f64> {
277 Complex::new(re, 0.0)
278 }
279
280 fn vec1(values: &[f64]) -> C1D {
281 Array1::from_iter(values.iter().copied().map(c))
282 }
283
284 fn mat(rows: usize, cols: usize, values: &[f64]) -> C2D {
285 C2D::from_shape_vec((rows, cols), values.iter().copied().map(c).collect()).unwrap()
286 }
287
288 #[test]
289 fn test_state_space_step_matches_reference_update_order() {
290 let mut dut = StateSpace::new(
291 mat(1, 1, &[0.5]),
292 mat(1, 1, &[1.0]),
293 mat(1, 1, &[1.0]),
294 mat(1, 1, &[0.0]),
295 vec1(&[0.0]),
296 )
297 .unwrap();
298
299 let y0 = dut.step(vec1(&[2.0])).unwrap();
300 let y1 = dut.step(vec1(&[0.0])).unwrap();
301
302 assert!((y0[0] - c(2.0)).norm() < 1e-12);
303 assert!((y1[0] - c(1.0)).norm() < 1e-12);
304 assert!((dut.x[0] - c(1.0)).norm() < 1e-12);
305 }
306
307 #[test]
308 fn test_state_space_process_and_reset() {
309 let mut dut = StateSpace::new(
310 mat(1, 1, &[0.5]),
311 mat(1, 1, &[1.0]),
312 mat(1, 1, &[1.0]),
313 mat(1, 1, &[0.0]),
314 vec1(&[0.0]),
315 )
316 .unwrap();
317
318 let output = dut
319 .process(&[vec1(&[1.0]), vec1(&[1.0]), vec1(&[1.0])])
320 .unwrap()
321 .unwrap();
322
323 assert!((output[0][0] - c(1.0)).norm() < 1e-12);
324 assert!((output[1][0] - c(1.5)).norm() < 1e-12);
325 assert!((output[2][0] - c(1.75)).norm() < 1e-12);
326
327 dut.reset().unwrap();
328 assert!((dut.x[0] - c(0.0)).norm() < 1e-12);
329 }
330
331 #[test]
332 fn test_state_space_observable_controllable_and_stable() {
333 let dut = StateSpace::new(
334 mat(2, 2, &[0.5, 0.0, 0.0, 0.25]),
335 mat(2, 1, &[1.0, 1.0]),
336 mat(1, 2, &[1.0, 1.0]),
337 mat(1, 1, &[0.0]),
338 vec1(&[0.0, 0.0]),
339 )
340 .unwrap();
341
342 assert!(dut.is_observable().unwrap());
343 assert!(dut.is_controllable().unwrap());
344 assert!(dut.is_stable().unwrap());
345
346 let poles = dut.get_poles().unwrap();
347 let mut poles = poles.to_vec();
348 poles.sort_by(|a, b| a.re.total_cmp(&b.re));
349 assert!((poles[0] - c(0.25)).norm() < 1e-12);
350 assert!((poles[1] - c(0.5)).norm() < 1e-12);
351 }
352
353 #[test]
354 fn test_state_space_unobservable_and_uncontrollable() {
355 let dut = StateSpace::new(
356 mat(2, 2, &[0.5, 0.0, 0.0, 0.25]),
357 mat(2, 1, &[1.0, 0.0]),
358 mat(1, 2, &[1.0, 0.0]),
359 mat(1, 1, &[0.0]),
360 vec1(&[0.0, 0.0]),
361 )
362 .unwrap();
363
364 assert!(!dut.is_observable().unwrap());
365 assert!(!dut.is_controllable().unwrap());
366 }
367
368 #[test]
369 fn test_standard_convention_reads_the_current_state() {
370 let mut dut = StateSpace::new_standard(
371 mat(1, 1, &[0.5]),
372 mat(1, 1, &[1.0]),
373 mat(1, 1, &[1.0]),
374 mat(1, 1, &[0.0]),
375 vec1(&[0.0]),
376 )
377 .unwrap();
378 assert_eq!(dut.convention(), OutputConvention::Standard);
379 let y: Vec<_> = [2.0, 0.0, 0.0].iter().map(|&u| dut.step(vec1(&[u])).unwrap()[0]).collect();
381 assert!((y[0] - c(0.0)).norm() < 1e-12);
382 assert!((y[1] - c(2.0)).norm() < 1e-12);
383 assert!((y[2] - c(1.0)).norm() < 1e-12);
384 }
385
386 #[test]
387 fn test_to_standard_gives_identical_outputs() {
388 let a = mat(2, 2, &[0.9, 0.2, -0.1, 0.8]);
389 let b = mat(2, 1, &[1.0, 0.5]);
390 let cm = mat(1, 2, &[1.0, -1.0]);
391 let d = mat(1, 1, &[0.3]);
392 let mut updated = StateSpace::new(a, b, cm, d, vec1(&[0.5, -0.2])).unwrap();
393 let mut standard = updated.to_standard();
394 assert_eq!(standard.convention(), OutputConvention::Standard);
395 for k in 0..20 {
396 let u = vec1(&[(0.3 * k as f64).sin()]);
397 let (y1, y2) = (updated.step(u.clone()).unwrap(), standard.step(u).unwrap());
398 assert!((y1[0] - y2[0]).norm() < 1e-12);
399 }
400 }
401
402 #[test]
403 fn test_state_space_rejects_incompatible_sizes() {
404 let err = StateSpace::new(
405 mat(2, 2, &[1.0, 0.0, 0.0, 1.0]),
406 mat(1, 1, &[1.0]),
407 mat(1, 2, &[1.0, 0.0]),
408 mat(1, 1, &[0.0]),
409 vec1(&[0.0, 0.0]),
410 );
411 assert!(err.is_err());
412 }
413}