ratio_markov/
utils.rs

1/// Utility functions.
2use crate::{DMatrix, DVector};
3
4/// get_max_degree Calculates the maximum degree (number of nonzero entries) in the given matrix.
5pub fn get_max_degree(mat: &DMatrix<f64>, columns: bool) -> usize {
6    let (rows, cols) = mat.shape();
7    let mut degrees = DVector::<usize>::zeros(rows);
8    let imax = if columns { rows } else { cols };
9    let jmax = if columns { cols } else { rows };
10    for i in 0..imax {
11        for j in 0..jmax {
12            if mat[(i, j)] > 0.0 {
13                degrees[j] += 1;
14            }
15        }
16    }
17    degrees.max()
18}
19
20/// Prune matrix' values below a certain threshold.
21pub fn prune_matrix(matrix: &mut DMatrix<f64>, threshold: f64) {
22    let (rows, cols) = matrix.shape();
23    for i in 0..rows {
24        for j in 0..cols {
25            if (matrix[(i, j)].abs() - threshold).abs() < f64::EPSILON {
26                matrix[(i, j)] = 0.0;
27            }
28        }
29    }
30}
31
32/// Normalize a matrix' columns.
33pub fn normalize_matrix_columns(matrix: &mut DMatrix<f64>) {
34    for mut col in matrix.column_iter_mut() {
35        let sum = col.sum();
36        if sum.abs() < f64::EPSILON {
37            col.fill(0.0);
38        } else {
39            col *= 1.0 / sum;
40        }
41    }
42}
43
44/// Raise matrix elements to a floating point power.
45pub fn matrix_elementwise_power(matrix: &mut DMatrix<f64>, power: f64) {
46    let (rows, cols) = matrix.shape();
47    for i in 0..rows {
48        for j in 0..cols {
49            matrix[(i, j)] = matrix[(i, j)].powf(power);
50        }
51    }
52}