Coverage Report

Created: 2026-08-13 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/smawk-0.3.2/src/lib.rs
Line
Count
Source
1
//! This crate implements various functions that help speed up dynamic
2
//! programming, most importantly the SMAWK algorithm for finding row
3
//! or column minima in a totally monotone matrix with *m* rows and
4
//! *n* columns in time O(*m* + *n*). This is much better than the
5
//! brute force solution which would take O(*mn*). When *m* and *n*
6
//! are of the same order, this turns a quadratic function into a
7
//! linear function.
8
//!
9
//! # Examples
10
//!
11
//! Computing the column minima of an *m* ✕ *n* Monge matrix can be
12
//! done efficiently with `smawk::column_minima`:
13
//!
14
//! ```
15
//! use smawk::Matrix;
16
//!
17
//! let matrix = vec![
18
//!     vec![3, 2, 4, 5, 6],
19
//!     vec![2, 1, 3, 3, 4],
20
//!     vec![2, 1, 3, 3, 4],
21
//!     vec![3, 2, 4, 3, 4],
22
//!     vec![4, 3, 2, 1, 1],
23
//! ];
24
//! let minima = vec![1, 1, 4, 4, 4];
25
//! assert_eq!(smawk::column_minima(&matrix), minima);
26
//! ```
27
//!
28
//! The `minima` vector gives the index of the minimum value per
29
//! column, so `minima[0] == 1` since the minimum value in the first
30
//! column is 2 (row 1). Note that the smallest row index is returned.
31
//!
32
//! # Definitions
33
//!
34
//! Some of the functions in this crate only work on matrices that are
35
//! *totally monotone*, which we will define below.
36
//!
37
//! ## Monotone Matrices
38
//!
39
//! We start with a helper definition. Given an *m* ✕ *n* matrix `M`,
40
//! we say that `M` is *monotone* when the minimum value of row `i` is
41
//! found to the left of the minimum value in row `i'` where `i < i'`.
42
//!
43
//! More formally, if we let `rm(i)` denote the column index of the
44
//! left-most minimum value in row `i`, then we have
45
//!
46
//! ```text
47
//! rm(0) ≤ rm(1) ≤ ... ≤ rm(m - 1)
48
//! ```
49
//!
50
//! This means that as you go down the rows from top to bottom, the
51
//! row-minima proceed from left to right.
52
//!
53
//! The algorithms in this crate deal with finding such row- and
54
//! column-minima.
55
//!
56
//! ## Totally Monotone Matrices
57
//!
58
//! We say that a matrix `M` is *totally monotone* when every
59
//! sub-matrix is monotone. A sub-matrix is formed by the intersection
60
//! of any two rows `i < i'` and any two columns `j < j'`.
61
//!
62
//! This is often expressed as via this equivalent condition:
63
//!
64
//! ```text
65
//! M[i, j] > M[i, j']  =>  M[i', j] > M[i', j']
66
//! ```
67
//!
68
//! for all `i < i'` and `j < j'`.
69
//!
70
//! ## Monge Property for Matrices
71
//!
72
//! A matrix `M` is said to fulfill the *Monge property* if
73
//!
74
//! ```text
75
//! M[i, j] + M[i', j'] ≤ M[i, j'] + M[i', j]
76
//! ```
77
//!
78
//! for all `i < i'` and `j < j'`. This says that given any rectangle
79
//! in the matrix, the sum of the top-left and bottom-right corners is
80
//! less than or equal to the sum of the bottom-left and upper-right
81
//! corners.
82
//!
83
//! All Monge matrices are totally monotone, so it is enough to
84
//! establish that the Monge property holds in order to use a matrix
85
//! with the functions in this crate. If your program is dealing with
86
//! unknown inputs, it can use [`monge::is_monge`] to verify that a
87
//! matrix is a Monge matrix.
88
89
#![doc(html_root_url = "https://docs.rs/smawk/0.3.2")]
90
// The s! macro from ndarray uses unsafe internally, so we can only
91
// forbid unsafe code when building with the default features.
92
#![cfg_attr(not(feature = "ndarray"), forbid(unsafe_code))]
93
94
#[cfg(feature = "ndarray")]
95
pub mod brute_force;
96
pub mod monge;
97
#[cfg(feature = "ndarray")]
98
pub mod recursive;
99
100
/// Minimal matrix trait for two-dimensional arrays.
101
///
102
/// This provides the functionality needed to represent a read-only
103
/// numeric matrix. You can query the size of the matrix and access
104
/// elements. Modeled after [`ndarray::Array2`] from the [ndarray
105
/// crate](https://crates.io/crates/ndarray).
106
///
107
/// Enable the `ndarray` Cargo feature if you want to use it with
108
/// `ndarray::Array2`.
109
pub trait Matrix<T: Copy> {
110
    /// Return the number of rows.
111
    fn nrows(&self) -> usize;
112
    /// Return the number of columns.
113
    fn ncols(&self) -> usize;
114
    /// Return a matrix element.
115
    fn index(&self, row: usize, column: usize) -> T;
116
}
117
118
/// Simple and inefficient matrix representation used for doctest
119
/// examples and simple unit tests.
120
///
121
/// You should prefer implementing it yourself, or you can enable the
122
/// `ndarray` Cargo feature and use the provided implementation for
123
/// [`ndarray::Array2`].
124
impl<T: Copy> Matrix<T> for Vec<Vec<T>> {
125
    fn nrows(&self) -> usize {
126
        self.len()
127
    }
128
    fn ncols(&self) -> usize {
129
        self[0].len()
130
    }
131
    fn index(&self, row: usize, column: usize) -> T {
132
        self[row][column]
133
    }
134
}
135
136
/// Adapting [`ndarray::Array2`] to the `Matrix` trait.
137
///
138
/// **Note: this implementation is only available if you enable the
139
/// `ndarray` Cargo feature.**
140
#[cfg(feature = "ndarray")]
141
impl<T: Copy> Matrix<T> for ndarray::Array2<T> {
142
    #[inline]
143
    fn nrows(&self) -> usize {
144
        self.nrows()
145
    }
146
    #[inline]
147
    fn ncols(&self) -> usize {
148
        self.ncols()
149
    }
150
    #[inline]
151
    fn index(&self, row: usize, column: usize) -> T {
152
        self[[row, column]]
153
    }
154
}
155
156
/// Compute row minima in O(*m* + *n*) time.
157
///
158
/// This implements the [SMAWK algorithm] for efficiently finding row
159
/// minima in a totally monotone matrix.
160
///
161
/// The SMAWK algorithm is from Agarwal, Klawe, Moran, Shor, and
162
/// Wilbur, *Geometric applications of a matrix searching algorithm*,
163
/// Algorithmica 2, pp. 195-208 (1987) and the code here is a
164
/// translation [David Eppstein's Python code][pads].
165
///
166
/// Running time on an *m* ✕ *n* matrix: O(*m* + *n*).
167
///
168
/// # Examples
169
///
170
/// ```
171
/// use smawk::Matrix;
172
/// let matrix = vec![vec![4, 2, 4, 3],
173
///                   vec![5, 3, 5, 3],
174
///                   vec![5, 3, 3, 1]];
175
/// assert_eq!(smawk::row_minima(&matrix),
176
///            vec![1, 1, 3]);
177
/// ```
178
///
179
/// # Panics
180
///
181
/// It is an error to call this on a matrix with zero columns.
182
///
183
/// [pads]: https://github.com/jfinkels/PADS/blob/master/pads/smawk.py
184
/// [SMAWK algorithm]: https://en.wikipedia.org/wiki/SMAWK_algorithm
185
pub fn row_minima<T: PartialOrd + Copy, M: Matrix<T>>(matrix: &M) -> Vec<usize> {
186
    // Benchmarking shows that SMAWK performs roughly the same on row-
187
    // and column-major matrices.
188
    let mut minima = vec![0; matrix.nrows()];
189
    smawk_inner(
190
        &|j, i| matrix.index(i, j),
191
        &(0..matrix.ncols()).collect::<Vec<_>>(),
192
        &(0..matrix.nrows()).collect::<Vec<_>>(),
193
        &mut minima,
194
    );
195
    minima
196
}
197
198
#[deprecated(since = "0.3.2", note = "Please use `row_minima` instead.")]
199
pub fn smawk_row_minima<T: PartialOrd + Copy, M: Matrix<T>>(matrix: &M) -> Vec<usize> {
200
    row_minima(matrix)
201
}
202
203
/// Compute column minima in O(*m* + *n*) time.
204
///
205
/// This implements the [SMAWK algorithm] for efficiently finding
206
/// column minima in a totally monotone matrix.
207
///
208
/// The SMAWK algorithm is from Agarwal, Klawe, Moran, Shor, and
209
/// Wilbur, *Geometric applications of a matrix searching algorithm*,
210
/// Algorithmica 2, pp. 195-208 (1987) and the code here is a
211
/// translation [David Eppstein's Python code][pads].
212
///
213
/// Running time on an *m* ✕ *n* matrix: O(*m* + *n*).
214
///
215
/// # Examples
216
///
217
/// ```
218
/// use smawk::Matrix;
219
/// let matrix = vec![vec![4, 2, 4, 3],
220
///                   vec![5, 3, 5, 3],
221
///                   vec![5, 3, 3, 1]];
222
/// assert_eq!(smawk::column_minima(&matrix),
223
///            vec![0, 0, 2, 2]);
224
/// ```
225
///
226
/// # Panics
227
///
228
/// It is an error to call this on a matrix with zero rows.
229
///
230
/// [SMAWK algorithm]: https://en.wikipedia.org/wiki/SMAWK_algorithm
231
/// [pads]: https://github.com/jfinkels/PADS/blob/master/pads/smawk.py
232
pub fn column_minima<T: PartialOrd + Copy, M: Matrix<T>>(matrix: &M) -> Vec<usize> {
233
    let mut minima = vec![0; matrix.ncols()];
234
    smawk_inner(
235
        &|i, j| matrix.index(i, j),
236
        &(0..matrix.nrows()).collect::<Vec<_>>(),
237
        &(0..matrix.ncols()).collect::<Vec<_>>(),
238
        &mut minima,
239
    );
240
    minima
241
}
242
243
#[deprecated(since = "0.3.2", note = "Please use `column_minima` instead.")]
244
pub fn smawk_column_minima<T: PartialOrd + Copy, M: Matrix<T>>(matrix: &M) -> Vec<usize> {
245
    column_minima(matrix)
246
}
247
248
/// Compute column minima in the given area of the matrix. The
249
/// `minima` slice is updated inplace.
250
21.6M
fn smawk_inner<T: PartialOrd + Copy, M: Fn(usize, usize) -> T>(
251
21.6M
    matrix: &M,
252
21.6M
    rows: &[usize],
253
21.6M
    cols: &[usize],
254
21.6M
    minima: &mut [usize],
255
21.6M
) {
256
21.6M
    if cols.is_empty() {
257
7.07M
        return;
258
14.6M
    }
259
260
14.6M
    let mut stack = Vec::with_capacity(cols.len());
261
86.3M
    for r in rows {
262
        // TODO: use stack.last() instead of stack.is_empty() etc
263
86.5M
        while !stack.is_empty()
264
64.5M
            && matrix(stack[stack.len() - 1], cols[stack.len() - 1])
265
64.5M
                > matrix(*r, cols[stack.len() - 1])
266
14.8M
        {
267
14.8M
            stack.pop();
268
14.8M
        }
269
71.7M
        if stack.len() != cols.len() {
270
58.5M
            stack.push(*r);
271
58.5M
        }
272
    }
273
14.6M
    let rows = &stack;
274
275
14.6M
    let mut odd_cols = Vec::with_capacity(1 + cols.len() / 2);
276
54.6M
    for (idx, c) in cols.iter().enumerate() {
277
54.6M
        if idx % 2 == 1 {
278
23.7M
            odd_cols.push(*c);
279
30.8M
        }
280
    }
281
282
14.6M
    smawk_inner(matrix, rows, &odd_cols, minima);
283
284
14.6M
    let mut r = 0;
285
54.6M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
smawk::smawk_inner::<f64, smawk::online_column_minima<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<textwrap::core::Word>::{closure#0}>::{closure#0}>::{closure#0}
Line
Count
Source
285
47.0M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
smawk::smawk_inner::<f64, smawk::online_column_minima<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit_usize::Word>::{closure#0}>::{closure#0}>::{closure#0}
Line
Count
Source
285
4.41M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
smawk::smawk_inner::<f64, smawk::online_column_minima<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit::Word>::{closure#0}>::{closure#0}>::{closure#0}
Line
Count
Source
285
3.16M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
286
30.8M
        let mut row = rows[r];
287
30.8M
        let last_row = if c == cols.len() - 1 {
288
7.08M
            rows[rows.len() - 1]
289
        } else {
290
23.7M
            minima[cols[c + 1]]
291
        };
292
30.8M
        let mut pair = (matrix(row, col), row);
293
38.4M
        while row != last_row {
294
7.54M
            r += 1;
295
7.54M
            row = rows[r];
296
7.54M
            if (matrix(row, col), row) < pair {
297
1.24M
                pair = (matrix(row, col), row);
298
6.29M
            }
299
        }
300
30.8M
        minima[col] = pair.1;
301
    }
302
21.6M
}
smawk::smawk_inner::<f64, smawk::online_column_minima<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<textwrap::core::Word>::{closure#0}>::{closure#0}>
Line
Count
Source
250
20.0M
fn smawk_inner<T: PartialOrd + Copy, M: Fn(usize, usize) -> T>(
251
20.0M
    matrix: &M,
252
20.0M
    rows: &[usize],
253
20.0M
    cols: &[usize],
254
20.0M
    minima: &mut [usize],
255
20.0M
) {
256
20.0M
    if cols.is_empty() {
257
6.55M
        return;
258
13.4M
    }
259
260
13.4M
    let mut stack = Vec::with_capacity(cols.len());
261
73.7M
    for r in rows {
262
        // TODO: use stack.last() instead of stack.is_empty() etc
263
74.3M
        while !stack.is_empty()
264
54.0M
            && matrix(stack[stack.len() - 1], cols[stack.len() - 1])
265
54.0M
                > matrix(*r, cols[stack.len() - 1])
266
14.0M
        {
267
14.0M
            stack.pop();
268
14.0M
        }
269
60.3M
        if stack.len() != cols.len() {
270
50.9M
            stack.push(*r);
271
50.9M
        }
272
    }
273
13.4M
    let rows = &stack;
274
275
13.4M
    let mut odd_cols = Vec::with_capacity(1 + cols.len() / 2);
276
47.0M
    for (idx, c) in cols.iter().enumerate() {
277
47.0M
        if idx % 2 == 1 {
278
20.2M
            odd_cols.push(*c);
279
26.8M
        }
280
    }
281
282
13.4M
    smawk_inner(matrix, rows, &odd_cols, minima);
283
284
13.4M
    let mut r = 0;
285
26.8M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
286
26.8M
        let mut row = rows[r];
287
26.8M
        let last_row = if c == cols.len() - 1 {
288
6.56M
            rows[rows.len() - 1]
289
        } else {
290
20.2M
            minima[cols[c + 1]]
291
        };
292
26.8M
        let mut pair = (matrix(row, col), row);
293
33.7M
        while row != last_row {
294
6.94M
            r += 1;
295
6.94M
            row = rows[r];
296
6.94M
            if (matrix(row, col), row) < pair {
297
1.23M
                pair = (matrix(row, col), row);
298
5.70M
            }
299
        }
300
26.8M
        minima[col] = pair.1;
301
    }
302
20.0M
}
smawk::smawk_inner::<f64, smawk::online_column_minima<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit_usize::Word>::{closure#0}>::{closure#0}>
Line
Count
Source
250
1.15M
fn smawk_inner<T: PartialOrd + Copy, M: Fn(usize, usize) -> T>(
251
1.15M
    matrix: &M,
252
1.15M
    rows: &[usize],
253
1.15M
    cols: &[usize],
254
1.15M
    minima: &mut [usize],
255
1.15M
) {
256
1.15M
    if cols.is_empty() {
257
353k
        return;
258
805k
    }
259
260
805k
    let mut stack = Vec::with_capacity(cols.len());
261
7.45M
    for r in rows {
262
        // TODO: use stack.last() instead of stack.is_empty() etc
263
7.19M
        while !stack.is_empty()
264
5.94M
            && matrix(stack[stack.len() - 1], cols[stack.len() - 1])
265
5.94M
                > matrix(*r, cols[stack.len() - 1])
266
548k
        {
267
548k
            stack.pop();
268
548k
        }
269
6.64M
        if stack.len() != cols.len() {
270
4.46M
            stack.push(*r);
271
4.46M
        }
272
    }
273
805k
    let rows = &stack;
274
275
805k
    let mut odd_cols = Vec::with_capacity(1 + cols.len() / 2);
276
4.41M
    for (idx, c) in cols.iter().enumerate() {
277
4.41M
        if idx % 2 == 1 {
278
2.03M
            odd_cols.push(*c);
279
2.38M
        }
280
    }
281
282
805k
    smawk_inner(matrix, rows, &odd_cols, minima);
283
284
805k
    let mut r = 0;
285
2.38M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
286
2.38M
        let mut row = rows[r];
287
2.38M
        let last_row = if c == cols.len() - 1 {
288
354k
            rows[rows.len() - 1]
289
        } else {
290
2.03M
            minima[cols[c + 1]]
291
        };
292
2.38M
        let mut pair = (matrix(row, col), row);
293
2.72M
        while row != last_row {
294
338k
            r += 1;
295
338k
            row = rows[r];
296
338k
            if (matrix(row, col), row) < pair {
297
5.80k
                pair = (matrix(row, col), row);
298
332k
            }
299
        }
300
2.38M
        minima[col] = pair.1;
301
    }
302
1.15M
}
smawk::smawk_inner::<f64, smawk::online_column_minima<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit::Word>::{closure#0}>::{closure#0}>
Line
Count
Source
250
532k
fn smawk_inner<T: PartialOrd + Copy, M: Fn(usize, usize) -> T>(
251
532k
    matrix: &M,
252
532k
    rows: &[usize],
253
532k
    cols: &[usize],
254
532k
    minima: &mut [usize],
255
532k
) {
256
532k
    if cols.is_empty() {
257
166k
        return;
258
365k
    }
259
260
365k
    let mut stack = Vec::with_capacity(cols.len());
261
5.12M
    for r in rows {
262
        // TODO: use stack.last() instead of stack.is_empty() etc
263
5.02M
        while !stack.is_empty()
264
4.50M
            && matrix(stack[stack.len() - 1], cols[stack.len() - 1])
265
4.50M
                > matrix(*r, cols[stack.len() - 1])
266
264k
        {
267
264k
            stack.pop();
268
264k
        }
269
4.75M
        if stack.len() != cols.len() {
270
3.16M
            stack.push(*r);
271
3.16M
        }
272
    }
273
365k
    let rows = &stack;
274
275
365k
    let mut odd_cols = Vec::with_capacity(1 + cols.len() / 2);
276
3.16M
    for (idx, c) in cols.iter().enumerate() {
277
3.16M
        if idx % 2 == 1 {
278
1.49M
            odd_cols.push(*c);
279
1.66M
        }
280
    }
281
282
365k
    smawk_inner(matrix, rows, &odd_cols, minima);
283
284
365k
    let mut r = 0;
285
1.66M
    for (c, &col) in cols.iter().enumerate().filter(|(c, _)| c % 2 == 0) {
286
1.66M
        let mut row = rows[r];
287
1.66M
        let last_row = if c == cols.len() - 1 {
288
167k
            rows[rows.len() - 1]
289
        } else {
290
1.49M
            minima[cols[c + 1]]
291
        };
292
1.66M
        let mut pair = (matrix(row, col), row);
293
1.92M
        while row != last_row {
294
259k
            r += 1;
295
259k
            row = rows[r];
296
259k
            if (matrix(row, col), row) < pair {
297
3.95k
                pair = (matrix(row, col), row);
298
255k
            }
299
        }
300
1.66M
        minima[col] = pair.1;
301
    }
302
532k
}
303
304
/// Compute upper-right column minima in O(*m* + *n*) time.
305
///
306
/// The input matrix must be totally monotone.
307
///
308
/// The function returns a vector of `(usize, T)`. The `usize` in the
309
/// tuple at index `j` tells you the row of the minimum value in
310
/// column `j` and the `T` value is minimum value itself.
311
///
312
/// The algorithm only considers values above the main diagonal, which
313
/// means that it computes values `v(j)` where:
314
///
315
/// ```text
316
/// v(0) = initial
317
/// v(j) = min { M[i, j] | i < j } for j > 0
318
/// ```
319
///
320
/// If we let `r(j)` denote the row index of the minimum value in
321
/// column `j`, the tuples in the result vector become `(r(j), M[r(j),
322
/// j])`.
323
///
324
/// The algorithm is an *online* algorithm, in the sense that `matrix`
325
/// function can refer back to previously computed column minima when
326
/// determining an entry in the matrix. The guarantee is that we only
327
/// call `matrix(i, j)` after having computed `v(i)`. This is
328
/// reflected in the `&[(usize, T)]` argument to `matrix`, which grows
329
/// as more and more values are computed.
330
333k
pub fn online_column_minima<T: Copy + PartialOrd, M: Fn(&[(usize, T)], usize, usize) -> T>(
331
333k
    initial: T,
332
333k
    size: usize,
333
333k
    matrix: M,
334
333k
) -> Vec<(usize, T)> {
335
333k
    let mut result = vec![(0, initial)];
336
337
    // State used by the algorithm.
338
333k
    let mut finished = 0;
339
333k
    let mut base = 0;
340
333k
    let mut tentative = 0;
341
342
    // Shorthand for evaluating the matrix. We need a macro here since
343
    // we don't want to borrow the result vector.
344
    macro_rules! m {
345
        ($i:expr, $j:expr) => {{
346
            assert!($i < $j, "(i, j) not above diagonal: ({}, {})", $i, $j);
347
            assert!(
348
                $i < size && $j < size,
349
                "(i, j) out of bounds: ({}, {}), size: {}",
350
                $i,
351
                $j,
352
                size
353
            );
354
            matrix(&result[..finished + 1], $i, $j)
355
        }};
356
    }
357
358
    // Keep going until we have finished all size columns. Since the
359
    // columns are zero-indexed, we're done when finished == size - 1.
360
27.8M
    while finished < size - 1 {
361
        // First case: we have already advanced past the previous
362
        // tentative value. We make a new tentative value by applying
363
        // smawk_inner to the largest square submatrix that fits under
364
        // the base.
365
27.4M
        let i = finished + 1;
366
27.4M
        if i > tentative {
367
7.07M
            let rows = (base..finished + 1).collect::<Vec<_>>();
368
7.07M
            tentative = std::cmp::min(finished + rows.len(), size - 1);
369
7.07M
            let cols = (finished + 1..tentative + 1).collect::<Vec<_>>();
370
7.07M
            let mut minima = vec![0; tentative + 1];
371
168M
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
smawk::online_column_minima::<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<textwrap::core::Word>::{closure#0}>::{closure#0}
Line
Count
Source
371
143M
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
smawk::online_column_minima::<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit_usize::Word>::{closure#0}>::{closure#0}
Line
Count
Source
371
14.6M
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
smawk::online_column_minima::<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit::Word>::{closure#0}>::{closure#0}
Line
Count
Source
371
10.9M
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
372
37.9M
            for col in cols {
373
30.8M
                let row = minima[col];
374
30.8M
                let v = m![row, col];
375
30.8M
                if col >= result.len() {
376
27.4M
                    result.push((row, v));
377
27.4M
                } else if v < result[col].1 {
378
1.53M
                    result[col] = (row, v);
379
1.83M
                }
380
            }
381
7.07M
            finished = i;
382
7.07M
            continue;
383
20.4M
        }
384
385
        // Second case: the new column minimum is on the diagonal. All
386
        // subsequent ones will be at least as low, so we can clear
387
        // out all our work from higher rows. As in the fourth case,
388
        // the loss of tentative is amortized against the increase in
389
        // base.
390
20.4M
        let diag = m![i - 1, i];
391
20.4M
        if diag < result[i].1 {
392
6.71M
            result[i] = (i - 1, diag);
393
6.71M
            base = i - 1;
394
6.71M
            tentative = i;
395
6.71M
            finished = i;
396
6.71M
            continue;
397
13.7M
        }
398
399
        // Third case: row i-1 does not supply a column minimum in any
400
        // column up to tentative. We simply advance finished while
401
        // maintaining the invariant.
402
13.7M
        if m![i - 1, tentative] >= result[tentative].1 {
403
13.6M
            finished = i;
404
13.6M
            continue;
405
44.5k
        }
406
407
        // Fourth and final case: a new column minimum at tentative.
408
        // This allows us to make progress by incorporating rows prior
409
        // to finished into the base. The base invariant holds because
410
        // these rows cannot supply any later column minima. The work
411
        // done when we last advanced tentative (and undone by this
412
        // step) can be amortized against the increase in base.
413
44.5k
        base = i - 1;
414
44.5k
        tentative = i;
415
44.5k
        finished = i;
416
    }
417
418
333k
    result
419
333k
}
smawk::online_column_minima::<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<textwrap::core::Word>::{closure#0}>
Line
Count
Source
330
332k
pub fn online_column_minima<T: Copy + PartialOrd, M: Fn(&[(usize, T)], usize, usize) -> T>(
331
332k
    initial: T,
332
332k
    size: usize,
333
332k
    matrix: M,
334
332k
) -> Vec<(usize, T)> {
335
332k
    let mut result = vec![(0, initial)];
336
337
    // State used by the algorithm.
338
332k
    let mut finished = 0;
339
332k
    let mut base = 0;
340
332k
    let mut tentative = 0;
341
342
    // Shorthand for evaluating the matrix. We need a macro here since
343
    // we don't want to borrow the result vector.
344
    macro_rules! m {
345
        ($i:expr, $j:expr) => {{
346
            assert!($i < $j, "(i, j) not above diagonal: ({}, {})", $i, $j);
347
            assert!(
348
                $i < size && $j < size,
349
                "(i, j) out of bounds: ({}, {}), size: {}",
350
                $i,
351
                $j,
352
                size
353
            );
354
            matrix(&result[..finished + 1], $i, $j)
355
        }};
356
    }
357
358
    // Keep going until we have finished all size columns. Since the
359
    // columns are zero-indexed, we're done when finished == size - 1.
360
24.1M
    while finished < size - 1 {
361
        // First case: we have already advanced past the previous
362
        // tentative value. We make a new tentative value by applying
363
        // smawk_inner to the largest square submatrix that fits under
364
        // the base.
365
23.8M
        let i = finished + 1;
366
23.8M
        if i > tentative {
367
6.55M
            let rows = (base..finished + 1).collect::<Vec<_>>();
368
6.55M
            tentative = std::cmp::min(finished + rows.len(), size - 1);
369
6.55M
            let cols = (finished + 1..tentative + 1).collect::<Vec<_>>();
370
6.55M
            let mut minima = vec![0; tentative + 1];
371
6.55M
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
372
33.3M
            for col in cols {
373
26.8M
                let row = minima[col];
374
26.8M
                let v = m![row, col];
375
26.8M
                if col >= result.len() {
376
23.8M
                    result.push((row, v));
377
23.8M
                } else if v < result[col].1 {
378
1.18M
                    result[col] = (row, v);
379
1.80M
                }
380
            }
381
6.55M
            finished = i;
382
6.55M
            continue;
383
17.2M
        }
384
385
        // Second case: the new column minimum is on the diagonal. All
386
        // subsequent ones will be at least as low, so we can clear
387
        // out all our work from higher rows. As in the fourth case,
388
        // the loss of tentative is amortized against the increase in
389
        // base.
390
17.2M
        let diag = m![i - 1, i];
391
17.2M
        if diag < result[i].1 {
392
6.31M
            result[i] = (i - 1, diag);
393
6.31M
            base = i - 1;
394
6.31M
            tentative = i;
395
6.31M
            finished = i;
396
6.31M
            continue;
397
10.9M
        }
398
399
        // Third case: row i-1 does not supply a column minimum in any
400
        // column up to tentative. We simply advance finished while
401
        // maintaining the invariant.
402
10.9M
        if m![i - 1, tentative] >= result[tentative].1 {
403
10.9M
            finished = i;
404
10.9M
            continue;
405
26.5k
        }
406
407
        // Fourth and final case: a new column minimum at tentative.
408
        // This allows us to make progress by incorporating rows prior
409
        // to finished into the base. The base invariant holds because
410
        // these rows cannot supply any later column minima. The work
411
        // done when we last advanced tentative (and undone by this
412
        // step) can be amortized against the increase in base.
413
26.5k
        base = i - 1;
414
26.5k
        tentative = i;
415
26.5k
        finished = i;
416
    }
417
418
332k
    result
419
332k
}
smawk::online_column_minima::<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit_usize::Word>::{closure#0}>
Line
Count
Source
330
716
pub fn online_column_minima<T: Copy + PartialOrd, M: Fn(&[(usize, T)], usize, usize) -> T>(
331
716
    initial: T,
332
716
    size: usize,
333
716
    matrix: M,
334
716
) -> Vec<(usize, T)> {
335
716
    let mut result = vec![(0, initial)];
336
337
    // State used by the algorithm.
338
716
    let mut finished = 0;
339
716
    let mut base = 0;
340
716
    let mut tentative = 0;
341
342
    // Shorthand for evaluating the matrix. We need a macro here since
343
    // we don't want to borrow the result vector.
344
    macro_rules! m {
345
        ($i:expr, $j:expr) => {{
346
            assert!($i < $j, "(i, j) not above diagonal: ({}, {})", $i, $j);
347
            assert!(
348
                $i < size && $j < size,
349
                "(i, j) out of bounds: ({}, {}), size: {}",
350
                $i,
351
                $j,
352
                size
353
            );
354
            matrix(&result[..finished + 1], $i, $j)
355
        }};
356
    }
357
358
    // Keep going until we have finished all size columns. Since the
359
    // columns are zero-indexed, we're done when finished == size - 1.
360
2.20M
    while finished < size - 1 {
361
        // First case: we have already advanced past the previous
362
        // tentative value. We make a new tentative value by applying
363
        // smawk_inner to the largest square submatrix that fits under
364
        // the base.
365
2.20M
        let i = finished + 1;
366
2.20M
        if i > tentative {
367
353k
            let rows = (base..finished + 1).collect::<Vec<_>>();
368
353k
            tentative = std::cmp::min(finished + rows.len(), size - 1);
369
353k
            let cols = (finished + 1..tentative + 1).collect::<Vec<_>>();
370
353k
            let mut minima = vec![0; tentative + 1];
371
353k
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
372
2.74M
            for col in cols {
373
2.38M
                let row = minima[col];
374
2.38M
                let v = m![row, col];
375
2.38M
                if col >= result.len() {
376
2.20M
                    result.push((row, v));
377
2.20M
                } else if v < result[col].1 {
378
176k
                    result[col] = (row, v);
379
176k
                }
380
            }
381
353k
            finished = i;
382
353k
            continue;
383
1.84M
        }
384
385
        // Second case: the new column minimum is on the diagonal. All
386
        // subsequent ones will be at least as low, so we can clear
387
        // out all our work from higher rows. As in the fourth case,
388
        // the loss of tentative is amortized against the increase in
389
        // base.
390
1.84M
        let diag = m![i - 1, i];
391
1.84M
        if diag < result[i].1 {
392
248k
            result[i] = (i - 1, diag);
393
248k
            base = i - 1;
394
248k
            tentative = i;
395
248k
            finished = i;
396
248k
            continue;
397
1.59M
        }
398
399
        // Third case: row i-1 does not supply a column minimum in any
400
        // column up to tentative. We simply advance finished while
401
        // maintaining the invariant.
402
1.59M
        if m![i - 1, tentative] >= result[tentative].1 {
403
1.58M
            finished = i;
404
1.58M
            continue;
405
14.9k
        }
406
407
        // Fourth and final case: a new column minimum at tentative.
408
        // This allows us to make progress by incorporating rows prior
409
        // to finished into the base. The base invariant holds because
410
        // these rows cannot supply any later column minima. The work
411
        // done when we last advanced tentative (and undone by this
412
        // step) can be amortized against the increase in base.
413
14.9k
        base = i - 1;
414
14.9k
        tentative = i;
415
14.9k
        finished = i;
416
    }
417
418
716
    result
419
716
}
smawk::online_column_minima::<f64, textwrap::wrap_algorithms::optimal_fit::wrap_optimal_fit<wrap_optimal_fit::Word>::{closure#0}>
Line
Count
Source
330
599
pub fn online_column_minima<T: Copy + PartialOrd, M: Fn(&[(usize, T)], usize, usize) -> T>(
331
599
    initial: T,
332
599
    size: usize,
333
599
    matrix: M,
334
599
) -> Vec<(usize, T)> {
335
599
    let mut result = vec![(0, initial)];
336
337
    // State used by the algorithm.
338
599
    let mut finished = 0;
339
599
    let mut base = 0;
340
599
    let mut tentative = 0;
341
342
    // Shorthand for evaluating the matrix. We need a macro here since
343
    // we don't want to borrow the result vector.
344
    macro_rules! m {
345
        ($i:expr, $j:expr) => {{
346
            assert!($i < $j, "(i, j) not above diagonal: ({}, {})", $i, $j);
347
            assert!(
348
                $i < size && $j < size,
349
                "(i, j) out of bounds: ({}, {}), size: {}",
350
                $i,
351
                $j,
352
                size
353
            );
354
            matrix(&result[..finished + 1], $i, $j)
355
        }};
356
    }
357
358
    // Keep going until we have finished all size columns. Since the
359
    // columns are zero-indexed, we're done when finished == size - 1.
360
1.46M
    while finished < size - 1 {
361
        // First case: we have already advanced past the previous
362
        // tentative value. We make a new tentative value by applying
363
        // smawk_inner to the largest square submatrix that fits under
364
        // the base.
365
1.46M
        let i = finished + 1;
366
1.46M
        if i > tentative {
367
166k
            let rows = (base..finished + 1).collect::<Vec<_>>();
368
166k
            tentative = std::cmp::min(finished + rows.len(), size - 1);
369
166k
            let cols = (finished + 1..tentative + 1).collect::<Vec<_>>();
370
166k
            let mut minima = vec![0; tentative + 1];
371
166k
            smawk_inner(&|i, j| m![i, j], &rows, &cols, &mut minima);
372
1.83M
            for col in cols {
373
1.66M
                let row = minima[col];
374
1.66M
                let v = m![row, col];
375
1.66M
                if col >= result.len() {
376
1.46M
                    result.push((row, v));
377
1.46M
                } else if v < result[col].1 {
378
179k
                    result[col] = (row, v);
379
179k
                }
380
            }
381
166k
            finished = i;
382
166k
            continue;
383
1.30M
        }
384
385
        // Second case: the new column minimum is on the diagonal. All
386
        // subsequent ones will be at least as low, so we can clear
387
        // out all our work from higher rows. As in the fourth case,
388
        // the loss of tentative is amortized against the increase in
389
        // base.
390
1.30M
        let diag = m![i - 1, i];
391
1.30M
        if diag < result[i].1 {
392
146k
            result[i] = (i - 1, diag);
393
146k
            base = i - 1;
394
146k
            tentative = i;
395
146k
            finished = i;
396
146k
            continue;
397
1.15M
        }
398
399
        // Third case: row i-1 does not supply a column minimum in any
400
        // column up to tentative. We simply advance finished while
401
        // maintaining the invariant.
402
1.15M
        if m![i - 1, tentative] >= result[tentative].1 {
403
1.15M
            finished = i;
404
1.15M
            continue;
405
3.11k
        }
406
407
        // Fourth and final case: a new column minimum at tentative.
408
        // This allows us to make progress by incorporating rows prior
409
        // to finished into the base. The base invariant holds because
410
        // these rows cannot supply any later column minima. The work
411
        // done when we last advanced tentative (and undone by this
412
        // step) can be amortized against the increase in base.
413
3.11k
        base = i - 1;
414
3.11k
        tentative = i;
415
3.11k
        finished = i;
416
    }
417
418
599
    result
419
599
}
420
421
#[cfg(test)]
422
mod tests {
423
    use super::*;
424
425
    #[test]
426
    fn smawk_1x1() {
427
        let matrix = vec![vec![2]];
428
        assert_eq!(row_minima(&matrix), vec![0]);
429
        assert_eq!(column_minima(&matrix), vec![0]);
430
    }
431
432
    #[test]
433
    fn smawk_2x1() {
434
        let matrix = vec![
435
            vec![3], //
436
            vec![2],
437
        ];
438
        assert_eq!(row_minima(&matrix), vec![0, 0]);
439
        assert_eq!(column_minima(&matrix), vec![1]);
440
    }
441
442
    #[test]
443
    fn smawk_1x2() {
444
        let matrix = vec![vec![2, 1]];
445
        assert_eq!(row_minima(&matrix), vec![1]);
446
        assert_eq!(column_minima(&matrix), vec![0, 0]);
447
    }
448
449
    #[test]
450
    fn smawk_2x2() {
451
        let matrix = vec![
452
            vec![3, 2], //
453
            vec![2, 1],
454
        ];
455
        assert_eq!(row_minima(&matrix), vec![1, 1]);
456
        assert_eq!(column_minima(&matrix), vec![1, 1]);
457
    }
458
459
    #[test]
460
    fn smawk_3x3() {
461
        let matrix = vec![
462
            vec![3, 4, 4], //
463
            vec![3, 4, 4],
464
            vec![2, 3, 3],
465
        ];
466
        assert_eq!(row_minima(&matrix), vec![0, 0, 0]);
467
        assert_eq!(column_minima(&matrix), vec![2, 2, 2]);
468
    }
469
470
    #[test]
471
    fn smawk_4x4() {
472
        let matrix = vec![
473
            vec![4, 5, 5, 5], //
474
            vec![2, 3, 3, 3],
475
            vec![2, 3, 3, 3],
476
            vec![2, 2, 2, 2],
477
        ];
478
        assert_eq!(row_minima(&matrix), vec![0, 0, 0, 0]);
479
        assert_eq!(column_minima(&matrix), vec![1, 3, 3, 3]);
480
    }
481
482
    #[test]
483
    fn smawk_5x5() {
484
        let matrix = vec![
485
            vec![3, 2, 4, 5, 6],
486
            vec![2, 1, 3, 3, 4],
487
            vec![2, 1, 3, 3, 4],
488
            vec![3, 2, 4, 3, 4],
489
            vec![4, 3, 2, 1, 1],
490
        ];
491
        assert_eq!(row_minima(&matrix), vec![1, 1, 1, 1, 3]);
492
        assert_eq!(column_minima(&matrix), vec![1, 1, 4, 4, 4]);
493
    }
494
495
    #[test]
496
    fn online_1x1() {
497
        let matrix = vec![vec![0]];
498
        let minima = vec![(0, 0)];
499
        assert_eq!(online_column_minima(0, 1, |_, i, j| matrix[i][j]), minima);
500
    }
501
502
    #[test]
503
    fn online_2x2() {
504
        let matrix = vec![
505
            vec![0, 2], //
506
            vec![0, 0],
507
        ];
508
        let minima = vec![(0, 0), (0, 2)];
509
        assert_eq!(online_column_minima(0, 2, |_, i, j| matrix[i][j]), minima);
510
    }
511
512
    #[test]
513
    fn online_3x3() {
514
        let matrix = vec![
515
            vec![0, 4, 4], //
516
            vec![0, 0, 4],
517
            vec![0, 0, 0],
518
        ];
519
        let minima = vec![(0, 0), (0, 4), (0, 4)];
520
        assert_eq!(online_column_minima(0, 3, |_, i, j| matrix[i][j]), minima);
521
    }
522
523
    #[test]
524
    fn online_4x4() {
525
        let matrix = vec![
526
            vec![0, 5, 5, 5], //
527
            vec![0, 0, 3, 3],
528
            vec![0, 0, 0, 3],
529
            vec![0, 0, 0, 0],
530
        ];
531
        let minima = vec![(0, 0), (0, 5), (1, 3), (1, 3)];
532
        assert_eq!(online_column_minima(0, 4, |_, i, j| matrix[i][j]), minima);
533
    }
534
535
    #[test]
536
    fn online_5x5() {
537
        let matrix = vec![
538
            vec![0, 2, 4, 6, 7],
539
            vec![0, 0, 3, 4, 5],
540
            vec![0, 0, 0, 3, 4],
541
            vec![0, 0, 0, 0, 4],
542
            vec![0, 0, 0, 0, 0],
543
        ];
544
        let minima = vec![(0, 0), (0, 2), (1, 3), (2, 3), (2, 4)];
545
        assert_eq!(online_column_minima(0, 5, |_, i, j| matrix[i][j]), minima);
546
    }
547
548
    #[test]
549
    fn smawk_works_with_partial_ord() {
550
        let matrix = vec![
551
            vec![3.0, 2.0], //
552
            vec![2.0, 1.0],
553
        ];
554
        assert_eq!(row_minima(&matrix), vec![1, 1]);
555
        assert_eq!(column_minima(&matrix), vec![1, 1]);
556
    }
557
558
    #[test]
559
    fn online_works_with_partial_ord() {
560
        let matrix = vec![
561
            vec![0.0, 2.0], //
562
            vec![0.0, 0.0],
563
        ];
564
        let minima = vec![(0, 0.0), (0, 2.0)];
565
        assert_eq!(
566
            online_column_minima(0.0, 2, |_, i: usize, j: usize| matrix[i][j]),
567
            minima
568
        );
569
    }
570
}