geometric-traits 0.2.0

Trait-based algebraic and graph algorithms for Rust, supporting no_std environments
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Grassmann-Taksar-Heyman stationary distribution solver for dense
//! row-stochastic matrices.
//!
//! Given a dense square row-stochastic matrix **P**, the GTH algorithm computes
//! a stationary distribution **pi** such that `pi P = pi` and `sum(pi) = 1`.
//! The implementation here follows the dense elimination style used by the
//! QuantEcon reference implementation.
//!
//! # Complexity
//!
//! The dense GTH elimination runs in **O(n^3)** time and uses **O(n^2)** space
//! for a working copy of the matrix plus **O(n)** space for the stationary
//! vector.
//!
//! # Reducible chains
//!
//! For irreducible chains the stationary distribution is unique. For reducible
//! chains, GTH still returns one valid stationary distribution, but uniqueness
//! is no longer guaranteed.
//!
//! # Workspace reuse
//!
//! [`Gth::gth()`] allocates a dense working copy on each call. For repeated
//! solves, reuse a [`GthWorkspace`] via [`Gth::gth_with_workspace()`] to avoid
//! repeated buffer allocation.
//!
//! # Reference
//!
//! Grassmann, W. K., Taksar, M. I., & Heyman, D. P. (1985).
//! *Regenerative Analysis and Steady State Distributions for Markov Chains*.
//! Operations Research, 33(5), 1107-1116.

use alloc::vec::Vec;

use num_traits::{AsPrimitive, ToPrimitive};

use crate::traits::{DenseValuedMatrix2D, Finite, Number};

// ============================================================================
// Configuration
// ============================================================================

/// Configuration for the dense GTH stationary-distribution solver.
#[derive(Debug, Clone, PartialEq)]
pub struct GthConfig {
    /// Tolerance used when validating row-stochastic input.
    ///
    /// Each entry must be exactly nonnegative, and each row sum must differ
    /// from `1.0` by at most this tolerance.
    pub stochastic_tolerance: f64,
}

impl Default for GthConfig {
    #[inline]
    fn default() -> Self {
        Self { stochastic_tolerance: 1e-12 }
    }
}

/// Reusable workspace for repeated dense GTH solves.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct GthWorkspace {
    work: Vec<f64>,
}

impl GthWorkspace {
    /// Creates an empty workspace.
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a workspace pre-allocated for a matrix of the given order.
    #[must_use]
    #[inline]
    pub fn with_capacity(order: usize) -> Self {
        Self { work: Vec::with_capacity(order.saturating_mul(order)) }
    }

    /// Returns the backing buffer capacity in scalar values.
    #[must_use]
    #[inline]
    pub fn capacity(&self) -> usize {
        self.work.capacity()
    }
}

// ============================================================================
// Result
// ============================================================================

/// Result of the dense GTH stationary-distribution solver.
#[derive(Debug, Clone, PartialEq)]
pub struct GthResult {
    stationary: Vec<f64>,
    order: usize,
}

impl GthResult {
    /// Returns the stationary distribution.
    #[must_use]
    #[inline]
    pub fn stationary(&self) -> &[f64] {
        &self.stationary
    }

    /// Returns the matrix order.
    #[must_use]
    #[inline]
    pub fn order(&self) -> usize {
        self.order
    }
}

// ============================================================================
// Error
// ============================================================================

/// Errors that can occur while computing a stationary distribution with GTH.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum GthError {
    /// The matrix must be square.
    #[error("The matrix must be square, but has {rows} rows and {columns} columns.")]
    NonSquareMatrix {
        /// Number of rows.
        rows: usize,
        /// Number of columns.
        columns: usize,
    },
    /// The matrix is empty.
    #[error("The matrix is empty.")]
    EmptyMatrix,
    /// A matrix entry is not finite.
    #[error("Found a non-finite value at ({row}, {column}).")]
    NonFiniteValue {
        /// Row index.
        row: usize,
        /// Column index.
        column: usize,
    },
    /// A matrix entry is negative.
    #[error("Found a negative value at ({row}, {column}).")]
    NegativeValue {
        /// Row index.
        row: usize,
        /// Column index.
        column: usize,
    },
    /// A row sum is not approximately one.
    #[error("Row {row} is not stochastic: row sum is {row_sum}.")]
    NonStochasticRow {
        /// Row index.
        row: usize,
        /// Observed row sum.
        row_sum: f64,
    },
    /// The stochastic tolerance must be finite and strictly positive.
    #[error("The stochastic tolerance must be finite and strictly positive.")]
    InvalidStochasticTolerance,
    /// The elimination produced an invalid intermediate value.
    #[error(
        "The GTH solver encountered a numerical breakdown during {stage} at index {index}: {value}."
    )]
    NumericalBreakdown {
        /// Which phase failed.
        stage: GthBreakdownStage,
        /// Pivot or active index associated with the failure.
        index: usize,
        /// Problematic value.
        value: f64,
    },
}

/// Phase of the dense GTH solve where a numerical breakdown occurred.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum GthBreakdownStage {
    /// The elimination scale computed for a pivot row was invalid.
    EliminationScale,
    /// The final stationary mass from back-substitution could not be
    /// normalized.
    StationaryMass,
}

impl core::fmt::Display for GthBreakdownStage {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::EliminationScale => f.write_str("elimination"),
            Self::StationaryMass => f.write_str("normalization"),
        }
    }
}

// ============================================================================
// Private helpers
// ============================================================================

fn validate_config(config: &GthConfig) -> Result<(), GthError> {
    if !config.stochastic_tolerance.is_finite() || config.stochastic_tolerance <= 0.0 {
        return Err(GthError::InvalidStochasticTolerance);
    }
    Ok(())
}

fn read_row_stochastic_matrix_into<M>(
    matrix: &M,
    tolerance: f64,
    flat: &mut Vec<f64>,
) -> Result<usize, GthError>
where
    M: DenseValuedMatrix2D,
    M::Value: Number + ToPrimitive + Finite,
    M::RowIndex: AsPrimitive<usize>,
    M::ColumnIndex: AsPrimitive<usize>,
{
    let rows: usize = matrix.number_of_rows().as_();
    let columns: usize = matrix.number_of_columns().as_();
    if rows != columns {
        return Err(GthError::NonSquareMatrix { rows, columns });
    }
    if rows == 0 {
        return Err(GthError::EmptyMatrix);
    }

    let order = rows;
    let required_len = order.saturating_mul(order);
    flat.clear();
    if flat.capacity() < required_len {
        flat.reserve(required_len - flat.capacity());
    }

    for row_id in matrix.row_indices() {
        let row = row_id.as_();
        let mut row_sum = 0.0;
        for (column_id, value) in matrix.column_indices().zip(matrix.row_values(row_id)) {
            let column = column_id.as_();
            if !value.is_finite() {
                return Err(GthError::NonFiniteValue { row, column });
            }
            let value = value.to_f64().ok_or(GthError::NonFiniteValue { row, column })?;
            if !value.is_finite() {
                return Err(GthError::NonFiniteValue { row, column });
            }
            if value < 0.0 {
                return Err(GthError::NegativeValue { row, column });
            }
            row_sum += value;
            flat.push(value);
        }

        if !row_sum.is_finite() || (row_sum - 1.0).abs() > tolerance {
            return Err(GthError::NonStochasticRow { row, row_sum });
        }
    }

    Ok(order)
}

fn gth_solve(work: &mut [f64], order: usize) -> Result<Vec<f64>, GthError> {
    let mut active = order;
    let mut stationary = vec![0.0; order];

    for pivot in 0..(order.saturating_sub(1)) {
        let row_offset = pivot * order;
        let scale: f64 = ((pivot + 1)..active).map(|column| work[row_offset + column]).sum();
        if !scale.is_finite() || scale < 0.0 {
            return Err(GthError::NumericalBreakdown {
                stage: GthBreakdownStage::EliminationScale,
                index: pivot,
                value: scale,
            });
        }
        if scale == 0.0 {
            active = pivot + 1;
            break;
        }

        for row in (pivot + 1)..active {
            work[row * order + pivot] /= scale;
        }

        for row in (pivot + 1)..active {
            let factor = work[row * order + pivot];
            if factor == 0.0 {
                continue;
            }
            let row_offset = row * order;
            for column in (pivot + 1)..active {
                work[row_offset + column] += factor * work[pivot * order + column];
            }
        }
    }

    stationary[active - 1] = 1.0;
    for pivot in (0..(active - 1)).rev() {
        stationary[pivot] =
            ((pivot + 1)..active).map(|row| stationary[row] * work[row * order + pivot]).sum();
    }

    let normalizer: f64 = stationary[..active].iter().sum();
    if !normalizer.is_finite() || normalizer <= 0.0 {
        return Err(GthError::NumericalBreakdown {
            stage: GthBreakdownStage::StationaryMass,
            index: active.saturating_sub(1),
            value: normalizer,
        });
    }
    for value in &mut stationary[..active] {
        *value /= normalizer;
    }

    Ok(stationary)
}

// ============================================================================
// Public trait
// ============================================================================

/// Trait providing the dense GTH stationary-distribution algorithm.
///
/// The input matrix must already be a dense square row-stochastic matrix.
/// The algorithm does not normalize arbitrary nonnegative weights internally,
/// and rejects any negative entry exactly.
///
/// # Complexity
///
/// O(n^3) time, O(n^2) space.
///
/// # Examples
///
/// ```
/// use geometric_traits::{impls::VecMatrix2D, prelude::*};
///
/// let matrix = VecMatrix2D::new(2, 2, vec![0.10, 0.90, 0.60, 0.40]);
/// let result = matrix.gth(&GthConfig::default()).unwrap();
///
/// assert!((result.stationary()[0] - 0.4).abs() < 1e-10);
/// assert!((result.stationary()[1] - 0.6).abs() < 1e-10);
/// ```
pub trait Gth: DenseValuedMatrix2D + Sized
where
    Self::Value: Number + ToPrimitive + Finite,
    Self::RowIndex: AsPrimitive<usize>,
    Self::ColumnIndex: AsPrimitive<usize>,
{
    /// Computes one stationary distribution while reusing a caller-provided
    /// working buffer.
    ///
    /// This avoids repeated allocation of the dense row-major work matrix when
    /// solving multiple problems of similar size.
    ///
    /// # Errors
    ///
    /// Returns a [`GthError`] if the input is not square, is empty, contains
    /// non-finite or negative values, is not row-stochastic within the
    /// configured tolerance, or if the elimination encounters a numerical
    /// breakdown.
    #[inline]
    fn gth_with_workspace(
        &self,
        config: &GthConfig,
        workspace: &mut GthWorkspace,
    ) -> Result<GthResult, GthError> {
        validate_config(config)?;
        let order = read_row_stochastic_matrix_into(
            self,
            config.stochastic_tolerance,
            &mut workspace.work,
        )?;
        let stationary = gth_solve(&mut workspace.work, order)?;
        Ok(GthResult { stationary, order })
    }

    /// Computes one stationary distribution of a dense row-stochastic matrix.
    ///
    /// # Errors
    ///
    /// Returns a [`GthError`] if the input is not square, is empty, contains
    /// non-finite or negative values, is not row-stochastic within the
    /// configured tolerance, or if the elimination encounters a numerical
    /// breakdown.
    #[inline]
    fn gth(&self, config: &GthConfig) -> Result<GthResult, GthError> {
        let mut workspace = GthWorkspace::default();
        self.gth_with_workspace(config, &mut workspace)
    }
}

impl<M: DenseValuedMatrix2D> Gth for M
where
    M::Value: Number + ToPrimitive + Finite,
    M::RowIndex: AsPrimitive<usize>,
    M::ColumnIndex: AsPrimitive<usize>,
{
}

#[cfg(all(test, feature = "alloc"))]
mod tests {
    use alloc::vec;
    use core::{
        num::ParseIntError,
        ops::{Add, Div, Mul, Rem, Sub},
    };

    use num_traits::{Bounded, Num, One, Zero};

    use super::*;
    use crate::impls::VecMatrix2D;

    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
    struct InfiniteF64(u8);

    impl Add for InfiniteF64 {
        type Output = Self;

        #[inline]
        fn add(self, rhs: Self) -> Self::Output {
            Self(self.0 + rhs.0)
        }
    }

    impl Sub for InfiniteF64 {
        type Output = Self;

        #[inline]
        fn sub(self, rhs: Self) -> Self::Output {
            Self(self.0 - rhs.0)
        }
    }

    impl Mul for InfiniteF64 {
        type Output = Self;

        #[inline]
        fn mul(self, rhs: Self) -> Self::Output {
            Self(self.0 * rhs.0)
        }
    }

    impl Div for InfiniteF64 {
        type Output = Self;

        #[inline]
        fn div(self, rhs: Self) -> Self::Output {
            Self(self.0 / rhs.0)
        }
    }

    impl Rem for InfiniteF64 {
        type Output = Self;

        #[inline]
        fn rem(self, rhs: Self) -> Self::Output {
            Self(self.0 % rhs.0)
        }
    }

    impl core::ops::AddAssign for InfiniteF64 {
        #[inline]
        fn add_assign(&mut self, rhs: Self) {
            self.0 += rhs.0;
        }
    }

    impl core::ops::SubAssign for InfiniteF64 {
        #[inline]
        fn sub_assign(&mut self, rhs: Self) {
            self.0 -= rhs.0;
        }
    }

    impl Zero for InfiniteF64 {
        #[inline]
        fn zero() -> Self {
            Self(0)
        }

        #[inline]
        fn is_zero(&self) -> bool {
            self.0 == 0
        }
    }

    impl One for InfiniteF64 {
        #[inline]
        fn one() -> Self {
            Self(1)
        }
    }

    impl Bounded for InfiniteF64 {
        #[inline]
        fn min_value() -> Self {
            Self(u8::MIN)
        }

        #[inline]
        fn max_value() -> Self {
            Self(u8::MAX)
        }
    }

    impl Num for InfiniteF64 {
        type FromStrRadixErr = ParseIntError;

        #[inline]
        fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
            u8::from_str_radix(str, radix).map(Self)
        }
    }

    impl ToPrimitive for InfiniteF64 {
        #[inline]
        fn to_i64(&self) -> Option<i64> {
            Some(i64::from(self.0))
        }

        #[inline]
        fn to_u64(&self) -> Option<u64> {
            Some(u64::from(self.0))
        }

        #[inline]
        fn to_f64(&self) -> Option<f64> {
            Some(f64::INFINITY)
        }
    }

    impl Finite for InfiniteF64 {
        #[inline]
        fn is_finite(&self) -> bool {
            true
        }
    }

    #[test]
    fn test_default_config_uses_documented_tolerance() {
        assert!((GthConfig::default().stochastic_tolerance - 1e-12).abs() < f64::EPSILON);
    }

    #[test]
    fn test_non_finite_after_to_f64_conversion_is_rejected() {
        let matrix = VecMatrix2D::new(1, 1, vec![InfiniteF64(1)]);
        let error = matrix.gth(&GthConfig::default()).unwrap_err();
        assert_eq!(error, GthError::NonFiniteValue { row: 0, column: 0 });
    }

    #[test]
    fn test_stationary_mass_breakdown_is_reported_by_private_solver_guard() {
        // This malformed work matrix cannot arise from validated stochastic
        // input, but it exercises the defensive normalizer check directly.
        let mut work = vec![0.0, 1.0, -1.0, 0.0];
        let error = gth_solve(&mut work, 2).unwrap_err();
        assert_eq!(
            error,
            GthError::NumericalBreakdown {
                stage: GthBreakdownStage::StationaryMass,
                index: 1,
                value: 0.0,
            }
        );
    }

    #[test]
    fn test_elimination_breakdown_is_reported_for_negative_scale() {
        let mut work = vec![0.0, -1.0, 1.0, 0.0];
        let error = gth_solve(&mut work, 2).unwrap_err();
        assert_eq!(
            error,
            GthError::NumericalBreakdown {
                stage: GthBreakdownStage::EliminationScale,
                index: 0,
                value: -1.0,
            }
        );
    }
}