gspx 0.1.2

Sparse graph signal processing and spectral graph wavelets in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::collections::HashMap;

use ndarray::{Array2, Array3, ArrayView1, ArrayView2, Axis, Zip};
use num_complex::Complex64;

use crate::{Laplacian, error::GspError, kernel::VfKernel};

use super::shared::{
    SparseFactor, accumulate, apply_direct_term, check_scale, check_scales, check_signal_rows,
    combine_complex_matrix, combine_complex_vec, factorize_shifted_matrix, shifted_matrix,
    solve_multi_rhs,
};

/// Options for lowpass solves.
#[derive(Debug, Clone, Copy, Default)]
pub struct LowpassOptions {
    /// When true, invalidate and rebuild the shifted-factor cache before solving.
    pub refactor: bool,
}

impl LowpassOptions {
    /// Builds options with explicit factor refactor behavior.
    pub const fn with_refactor(refactor: bool) -> Self {
        Self { refactor }
    }
}

/// Convolver for fixed (static) graph topology.
pub struct StaticConvolver {
    laplacian: Laplacian,
    n_vertices: usize,
    shift_factors: HashMap<u64, SparseFactor>,
}

impl StaticConvolver {
    /// Creates a static convolver for a fixed Laplacian.
    ///
    /// # Errors
    /// Returns an error when `l` is not square.
    pub fn new(l: Laplacian) -> Result<Self, GspError> {
        if l.rows() != l.cols() {
            return Err(GspError::Dimensions(format!(
                "Laplacian must be square, got {}x{}",
                l.rows(),
                l.cols()
            )));
        }
        Ok(Self {
            n_vertices: l.rows(),
            laplacian: l,
            shift_factors: HashMap::new(),
        })
    }

    /// Convolves a real-valued signal matrix with a VF kernel.
    ///
    /// # Errors
    /// Returns an error when kernel validation or solves fail.
    pub fn convolve(&mut self, b: ArrayView2<f64>, k: &VfKernel) -> Result<Array3<f64>, GspError> {
        k.validate()?;
        self.check_signal_2d(b)?;
        let n_dim = k.residues.ncols();
        let mut w = Array3::<f64>::zeros((b.nrows(), b.ncols(), n_dim));
        apply_direct_term(&mut w, b, k.direct.view())?;

        for (idx, &q) in k.poles.iter().enumerate() {
            let z = self.solve_shifted(q, b)?;
            accumulate(&mut w, &z, k.residues.row(idx));
        }
        Ok(w)
    }

    /// 1D wrapper around [`StaticConvolver::convolve`].
    ///
    /// # Errors
    /// Returns an error when dimensions are invalid or solves fail.
    pub fn convolve_1d(
        &mut self,
        b: ArrayView1<f64>,
        k: &VfKernel,
    ) -> Result<Array2<f64>, GspError> {
        self.check_signal_1d(b)?;
        let b2 = b.insert_axis(Axis(1));
        let w = self.convolve(b2, k)?;
        Ok(w.index_axis_move(Axis(1), 0))
    }

    /// Convolves a complex-valued signal matrix by splitting real/imaginary parts.
    ///
    /// # Errors
    /// Returns an error when dimensions are invalid or solves fail.
    pub fn convolve_complex(
        &mut self,
        b: ArrayView2<Complex64>,
        k: &VfKernel,
    ) -> Result<Array3<Complex64>, GspError> {
        self.check_signal_2d_complex(b)?;
        let wr = self.convolve(b.mapv(|v| v.re).view(), k)?;
        let wi = self.convolve(b.mapv(|v| v.im).view(), k)?;
        let mut out = Array3::<Complex64>::zeros(wr.raw_dim());
        Zip::from(&mut out)
            .and(&wr)
            .and(&wi)
            .for_each(|o, &r, &i| *o = Complex64::new(r, i));
        Ok(out)
    }

    /// 1D wrapper around [`StaticConvolver::convolve_complex`].
    ///
    /// # Errors
    /// Returns an error when dimensions are invalid or solves fail.
    pub fn convolve_complex_1d(
        &mut self,
        b: ArrayView1<Complex64>,
        k: &VfKernel,
    ) -> Result<Array2<Complex64>, GspError> {
        let b2 = b.insert_axis(Axis(1));
        let w = self.convolve_complex(b2, k)?;
        Ok(w.index_axis_move(Axis(1), 0))
    }

    /// Applies the analytical low-pass filter over multiple scales.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn lowpass(
        &mut self,
        b: ArrayView2<f64>,
        scales: &[f64],
        order: usize,
    ) -> Result<Vec<Array2<f64>>, GspError> {
        self.check_signal_2d(b)?;
        check_scales(scales)?;
        let mut out = Vec::with_capacity(scales.len());
        for &s in scales {
            out.push(self.lowpass_one(b, s, order)?);
        }
        Ok(out)
    }

    /// Runs lowpass filtering with explicit cache-control options.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn lowpass_with_options(
        &mut self,
        b: ArrayView2<f64>,
        scales: &[f64],
        options: LowpassOptions,
        order: usize,
    ) -> Result<Vec<Array2<f64>>, GspError> {
        self.check_signal_2d(b)?;
        check_scales(scales)?;
        let mut out = Vec::with_capacity(scales.len());
        for &s in scales {
            out.push(self.lowpass_one_with_options(b, s, options, order)?);
        }
        Ok(out)
    }

    /// Applies analytical low-pass filtering to complex signals.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn lowpass_complex(
        &mut self,
        b: ArrayView2<Complex64>,
        scales: &[f64],
        order: usize,
    ) -> Result<Vec<Array2<Complex64>>, GspError> {
        self.check_signal_2d_complex(b)?;
        let yr = self.lowpass(b.mapv(|z| z.re).view(), scales, order)?;
        let yi = self.lowpass(b.mapv(|z| z.im).view(), scales, order)?;
        combine_complex_vec(yr, yi)
    }

    /// Applies one complex low-pass solve at a single scale.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn lowpass_complex_one(
        &mut self,
        b: ArrayView2<Complex64>,
        scale: f64,
        order: usize,
    ) -> Result<Array2<Complex64>, GspError> {
        self.check_signal_2d_complex(b)?;
        let yr = self.lowpass_one(b.mapv(|z| z.re).view(), scale, order)?;
        let yi = self.lowpass_one(b.mapv(|z| z.im).view(), scale, order)?;
        Ok(combine_complex_matrix(yr, yi))
    }

    /// Applies one real low-pass solve at a single scale.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn lowpass_one(
        &mut self,
        b: ArrayView2<f64>,
        scale: f64,
        order: usize,
    ) -> Result<Array2<f64>, GspError> {
        self.lowpass_one_with_options(b, scale, LowpassOptions::default(), order)
    }

    /// Applies one real low-pass solve with cache-control options.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn lowpass_one_with_options(
        &mut self,
        b: ArrayView2<f64>,
        scale: f64,
        options: LowpassOptions,
        order: usize,
    ) -> Result<Array2<f64>, GspError> {
        self.check_signal_2d(b)?;
        check_scale(scale)?;
        if order == 0 {
            return Ok(b.to_owned());
        }
        let q = 1.0 / scale;
        if options.refactor {
            self.shift_factors.remove(&q.to_bits());
        }
        let mut x = b.to_owned();
        for _ in 0..order {
            let mut next = self.solve_shifted(q, x.view())?;
            next *= q;
            x = next;
        }
        Ok(x)
    }

    /// Applies the analytical band-pass filter over multiple scales.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn bandpass(
        &mut self,
        b: ArrayView2<f64>,
        scales: &[f64],
        order: usize,
    ) -> Result<Vec<Array2<f64>>, GspError> {
        self.check_signal_2d(b)?;
        check_scales(scales)?;
        let mut out = Vec::with_capacity(scales.len());
        for &s in scales {
            out.push(self.bandpass_one(b, s, order)?);
        }
        Ok(out)
    }

    /// Applies one real band-pass solve at a single scale.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn bandpass_one(
        &mut self,
        b: ArrayView2<f64>,
        scale: f64,
        order: usize,
    ) -> Result<Array2<f64>, GspError> {
        self.check_signal_2d(b)?;
        check_scale(scale)?;
        if order == 0 {
            return Ok(b.to_owned());
        }
        let q = 1.0 / scale;
        let mut x = b.to_owned();
        for _ in 0..order {
            let x2 = self.solve_shifted(q, x.view())?;
            let x1 = self.solve_shifted(q, x2.view())?;
            let mut next = x2;
            next.scaled_add(-q, &x1);
            next *= 4.0 * q;
            x = next;
        }
        Ok(x)
    }

    /// Applies analytical band-pass filtering to complex signals.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn bandpass_complex(
        &mut self,
        b: ArrayView2<Complex64>,
        scales: &[f64],
        order: usize,
    ) -> Result<Vec<Array2<Complex64>>, GspError> {
        self.check_signal_2d_complex(b)?;
        let yr = self.bandpass(b.mapv(|z| z.re).view(), scales, order)?;
        let yi = self.bandpass(b.mapv(|z| z.im).view(), scales, order)?;
        combine_complex_vec(yr, yi)
    }

    /// Applies one complex band-pass solve at a single scale.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn bandpass_complex_one(
        &mut self,
        b: ArrayView2<Complex64>,
        scale: f64,
        order: usize,
    ) -> Result<Array2<Complex64>, GspError> {
        self.check_signal_2d_complex(b)?;
        let yr = self.bandpass_one(b.mapv(|z| z.re).view(), scale, order)?;
        let yi = self.bandpass_one(b.mapv(|z| z.im).view(), scale, order)?;
        Ok(combine_complex_matrix(yr, yi))
    }

    /// Applies the analytical high-pass filter over multiple scales.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn highpass(
        &mut self,
        b: ArrayView2<f64>,
        scales: &[f64],
    ) -> Result<Vec<Array2<f64>>, GspError> {
        self.check_signal_2d(b)?;
        check_scales(scales)?;
        let mut out = Vec::with_capacity(scales.len());
        for &s in scales {
            out.push(self.highpass_one(b, s)?);
        }
        Ok(out)
    }

    /// Applies one real high-pass solve at a single scale.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn highpass_one(
        &mut self,
        b: ArrayView2<f64>,
        scale: f64,
    ) -> Result<Array2<f64>, GspError> {
        self.check_signal_2d(b)?;
        check_scale(scale)?;
        let q = 1.0 / scale;
        let x1 = self.solve_shifted(q, b)?;
        let mut y = b.to_owned();
        y.scaled_add(-q, &x1);
        Ok(y)
    }

    /// Applies analytical high-pass filtering to complex signals.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn highpass_complex(
        &mut self,
        b: ArrayView2<Complex64>,
        scales: &[f64],
    ) -> Result<Vec<Array2<Complex64>>, GspError> {
        self.check_signal_2d_complex(b)?;
        let yr = self.highpass(b.mapv(|z| z.re).view(), scales)?;
        let yi = self.highpass(b.mapv(|z| z.im).view(), scales)?;
        combine_complex_vec(yr, yi)
    }

    /// Applies one complex high-pass solve at a single scale.
    ///
    /// # Errors
    /// Returns an error when dimensions/scales are invalid or solves fail.
    pub fn highpass_complex_one(
        &mut self,
        b: ArrayView2<Complex64>,
        scale: f64,
    ) -> Result<Array2<Complex64>, GspError> {
        self.check_signal_2d_complex(b)?;
        let yr = self.highpass_one(b.mapv(|z| z.re).view(), scale)?;
        let yi = self.highpass_one(b.mapv(|z| z.im).view(), scale)?;
        Ok(combine_complex_matrix(yr, yi))
    }

    fn check_signal_1d(&self, b: ArrayView1<f64>) -> Result<(), GspError> {
        if b.len() != self.n_vertices {
            return Err(GspError::Dimensions(format!(
                "signal length {} does not match graph size {}",
                b.len(),
                self.n_vertices
            )));
        }
        Ok(())
    }

    fn check_signal_2d(&self, b: ArrayView2<f64>) -> Result<(), GspError> {
        check_signal_rows(b.nrows(), self.n_vertices)
    }

    fn check_signal_2d_complex(&self, b: ArrayView2<Complex64>) -> Result<(), GspError> {
        check_signal_rows(b.nrows(), self.n_vertices)
    }

    fn factor_for_shift(&mut self, q: f64) -> Result<&SparseFactor, GspError> {
        let key = q.to_bits();
        if !self.shift_factors.contains_key(&key) {
            let shifted = shifted_matrix(&self.laplacian, q);
            let factor = factorize_shifted_matrix(&shifted)?;
            self.shift_factors.insert(key, factor);
        }
        self.shift_factors
            .get(&key)
            .ok_or_else(|| GspError::Factorization("failed to cache factor".to_string()))
    }

    fn solve_shifted(&mut self, q: f64, b: ArrayView2<f64>) -> Result<Array2<f64>, GspError> {
        let factor = self.factor_for_shift(q)?;
        solve_multi_rhs(factor, b)
    }
}