Skip to main content

lib_jsl_optimization/
dynamic_programming.rs

1//! Dynamic programming: classic optimisation problems solved by tabulation, and solvers for
2//! Markov decision processes.
3//!
4//! The first group (knapsack, coin change, longest common / increasing subsequence, edit distance,
5//! matrix-chain ordering) each return the optimal value together with a reconstruction of one
6//! optimal solution. The second group, [`FiniteMdp`], solves sequential decision problems by
7//! backward induction (finite horizon) or value iteration (discounted, infinite horizon).
8//!
9//! See the book entry [Dynamic programming](https://jwkunz.github.io/lib_jsl/book/optimization/dynamic-programming.html).
10
11use lib_jsl_core::ErrorsJSL;
12
13/// 0/1 knapsack: chooses items (each at most once) maximising total value within `capacity`.
14/// Returns `(best value, chosen item indices in increasing order)`. `O(n · capacity)` time and
15/// memory.
16pub fn knapsack_01(weights: &[usize], values: &[f64], capacity: usize) -> Result<(f64, Vec<usize>), ErrorsJSL> {
17    if weights.len() != values.len() {
18        return Err(ErrorsJSL::IncompatibleArraySizes((weights.len(), values.len())));
19    }
20    let n = weights.len();
21    // best[i][w] = best value using the first i items with capacity w.
22    // ANCHOR: knapsack
23    let mut best = vec![vec![0.0f64; capacity + 1]; n + 1];
24    for i in 1..=n {
25        for w in 0..=capacity {
26            best[i][w] = best[i - 1][w];
27            if weights[i - 1] <= w {
28                best[i][w] = best[i][w].max(best[i - 1][w - weights[i - 1]] + values[i - 1]);
29            }
30        }
31    }
32    let mut chosen = Vec::new();
33    let mut w = capacity;
34    for i in (1..=n).rev() {
35        if best[i][w] != best[i - 1][w] {
36            chosen.push(i - 1);
37            w -= weights[i - 1];
38        }
39    }
40    chosen.reverse();
41    Ok((best[n][capacity], chosen))
42    // ANCHOR_END: knapsack
43}
44
45/// The fewest coins (unlimited supply of each denomination) summing to `amount`, as the count of
46/// each denomination; `None` if the amount cannot be made. Zero-valued denominations are ignored.
47pub fn coin_change_min_coins(coins: &[usize], amount: usize) -> Option<Vec<usize>> {
48    let mut best: Vec<Option<(usize, usize)>> = vec![None; amount + 1]; // (coins used, last coin index)
49    best[0] = Some((0, 0));
50    for a in 1..=amount {
51        for (ci, &c) in coins.iter().enumerate() {
52            if c > 0
53                && c <= a
54                && let Some((used, _)) = best[a - c]
55                && best[a].is_none_or(|(u, _)| used + 1 < u)
56            {
57                best[a] = Some((used + 1, ci));
58            }
59        }
60    }
61    best[amount]?;
62    let mut counts = vec![0; coins.len()];
63    let mut a = amount;
64    while a > 0 {
65        let (_, ci) = best[a]?;
66        counts[ci] += 1;
67        a -= coins[ci];
68    }
69    Some(counts)
70}
71
72/// The number of distinct multisets of coins summing to `amount` (order ignored), saturating at
73/// `u64::MAX`.
74pub fn coin_change_ways(coins: &[usize], amount: usize) -> u64 {
75    let mut ways = vec![0u64; amount + 1];
76    ways[0] = 1;
77    for &c in coins.iter().filter(|&&c| c > 0) {
78        for a in c..=amount {
79            ways[a] = ways[a].saturating_add(ways[a - c]);
80        }
81    }
82    ways[amount]
83}
84
85/// A longest common subsequence of `a` and `b` as pairs of matched indices `(i in a, j in b)`.
86pub fn longest_common_subsequence<T: PartialEq>(a: &[T], b: &[T]) -> Vec<(usize, usize)> {
87    let (n, m) = (a.len(), b.len());
88    let mut len = vec![vec![0usize; m + 1]; n + 1];
89    for i in 1..=n {
90        for j in 1..=m {
91            len[i][j] = if a[i - 1] == b[j - 1] { len[i - 1][j - 1] + 1 } else { len[i - 1][j].max(len[i][j - 1]) };
92        }
93    }
94    let (mut i, mut j) = (n, m);
95    let mut pairs = Vec::with_capacity(len[n][m]);
96    while i > 0 && j > 0 {
97        if a[i - 1] == b[j - 1] {
98            pairs.push((i - 1, j - 1));
99            i -= 1;
100            j -= 1;
101        } else if len[i - 1][j] >= len[i][j - 1] {
102            i -= 1;
103        } else {
104            j -= 1;
105        }
106    }
107    pairs.reverse();
108    pairs
109}
110
111/// One step of an edit script turning sequence `a` into `b`.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub enum EditOp {
114    /// `a[i]` equals `b[j]`: keep it.
115    Keep { i: usize, j: usize },
116    /// Replace `a[i]` with `b[j]`.
117    Substitute { i: usize, j: usize },
118    /// Insert `b[j]`.
119    Insert { j: usize },
120    /// Delete `a[i]`.
121    Delete { i: usize },
122}
123
124/// Levenshtein distance between `a` and `b` (unit cost for insert, delete and substitute) and one
125/// optimal edit script.
126pub fn edit_distance<T: PartialEq>(a: &[T], b: &[T]) -> (usize, Vec<EditOp>) {
127    let (n, m) = (a.len(), b.len());
128    let mut d = vec![vec![0usize; m + 1]; n + 1];
129    for (i, row) in d.iter_mut().enumerate() {
130        row[0] = i;
131    }
132    for (j, cell) in d[0].iter_mut().enumerate() {
133        *cell = j;
134    }
135    for i in 1..=n {
136        for j in 1..=m {
137            let sub = d[i - 1][j - 1] + usize::from(a[i - 1] != b[j - 1]);
138            d[i][j] = sub.min(d[i - 1][j] + 1).min(d[i][j - 1] + 1);
139        }
140    }
141    let (mut i, mut j) = (n, m);
142    let mut script = Vec::new();
143    while i > 0 || j > 0 {
144        if i > 0 && j > 0 && d[i][j] == d[i - 1][j - 1] + usize::from(a[i - 1] != b[j - 1]) {
145            script.push(if a[i - 1] == b[j - 1] { EditOp::Keep { i: i - 1, j: j - 1 } } else { EditOp::Substitute { i: i - 1, j: j - 1 } });
146            i -= 1;
147            j -= 1;
148        } else if i > 0 && d[i][j] == d[i - 1][j] + 1 {
149            script.push(EditOp::Delete { i: i - 1 });
150            i -= 1;
151        } else {
152            script.push(EditOp::Insert { j: j - 1 });
153            j -= 1;
154        }
155    }
156    script.reverse();
157    (d[n][m], script)
158}
159
160/// The cheapest way to multiply a chain of matrices where matrix `k` is `dims[k] × dims[k+1]`:
161/// `(scalar multiplications, parenthesisation such as "((A0A1)A2)")`. Needs at least one matrix
162/// (`dims.len() >= 2`).
163pub fn matrix_chain_order(dims: &[usize]) -> Result<(u64, String), ErrorsJSL> {
164    if dims.len() < 2 {
165        return Err(ErrorsJSL::InvalidInputRange("At least one matrix (two dimensions) is required."));
166    }
167    let n = dims.len() - 1;
168    let mut cost = vec![vec![0u64; n]; n];
169    let mut split = vec![vec![0usize; n]; n];
170    for len in 2..=n {
171        for i in 0..=n - len {
172            let j = i + len - 1;
173            cost[i][j] = u64::MAX;
174            for k in i..j {
175                let c = cost[i][k] + cost[k + 1][j] + (dims[i] * dims[k + 1] * dims[j + 1]) as u64;
176                if c < cost[i][j] {
177                    cost[i][j] = c;
178                    split[i][j] = k;
179                }
180            }
181        }
182    }
183    fn paren(split: &[Vec<usize>], i: usize, j: usize) -> String {
184        if i == j {
185            format!("A{i}")
186        } else {
187            format!("({}{})", paren(split, i, split[i][j]), paren(split, split[i][j] + 1, j))
188        }
189    }
190    Ok((cost[0][n - 1], paren(&split, 0, n - 1)))
191}
192
193/// A longest strictly increasing subsequence, as indices into `values`, in `O(n log n)`.
194pub fn longest_increasing_subsequence<T: PartialOrd>(values: &[T]) -> Vec<usize> {
195    let mut tails: Vec<usize> = Vec::new(); // tails[k] = index of the smallest tail of an increasing run of length k+1
196    let mut prev = vec![usize::MAX; values.len()];
197    for (i, v) in values.iter().enumerate() {
198        let pos = tails.partition_point(|&t| values[t] < *v);
199        if pos > 0 {
200            prev[i] = tails[pos - 1];
201        }
202        if pos == tails.len() {
203            tails.push(i);
204        } else {
205            tails[pos] = i;
206        }
207    }
208    let mut out = Vec::with_capacity(tails.len());
209    let mut cur = tails.last().copied();
210    while let Some(i) = cur {
211        out.push(i);
212        cur = (prev[i] != usize::MAX).then_some(prev[i]);
213    }
214    out.reverse();
215    out
216}
217
218/// A finite Markov decision process: in state `s`, taking action `a` yields `rewards[s][a]` and
219/// moves to state `s'` with the probabilities in `transitions[s][a]` (a list of `(s', prob)`).
220/// Every state must offer at least one action; the probabilities of each action must sum to 1.
221#[derive(Debug, Clone)]
222pub struct FiniteMdp {
223    pub transitions: Vec<Vec<Vec<(usize, f64)>>>,
224    pub rewards: Vec<Vec<f64>>,
225}
226
227/// The value function and a greedy policy.
228#[derive(Debug, Clone, PartialEq)]
229pub struct MdpSolution {
230    pub values: Vec<f64>,
231    /// The maximising action in each state.
232    pub policy: Vec<usize>,
233}
234
235impl FiniteMdp {
236    /// Checks the structural requirements above.
237    pub fn validate(&self) -> Result<(), ErrorsJSL> {
238        let n = self.transitions.len();
239        if n == 0 || self.rewards.len() != n {
240            return Err(ErrorsJSL::IncompatibleArraySizes((n, self.rewards.len())));
241        }
242        for s in 0..n {
243            if self.transitions[s].is_empty() || self.transitions[s].len() != self.rewards[s].len() {
244                return Err(ErrorsJSL::Misconfiguration("Each state needs one or more actions with matching rewards."));
245            }
246            for outcomes in &self.transitions[s] {
247                let total: f64 = outcomes.iter().map(|o| o.1).sum();
248                if outcomes.iter().any(|&(t, p)| t >= n || !(0.0..=1.0).contains(&p)) || (total - 1.0).abs() > 1e-9 {
249                    return Err(ErrorsJSL::Misconfiguration("Transition probabilities must be valid and sum to one."));
250                }
251            }
252        }
253        Ok(())
254    }
255
256    fn q_value(&self, s: usize, a: usize, next_values: &[f64], discount: f64) -> f64 {
257        self.rewards[s][a] + discount * self.transitions[s][a].iter().map(|&(t, p)| p * next_values[t]).sum::<f64>()
258    }
259
260    fn greedy(&self, values: &[f64], discount: f64) -> MdpSolution {
261        let mut policy = Vec::with_capacity(values.len());
262        let mut new_values = Vec::with_capacity(values.len());
263        for s in 0..values.len() {
264            let (a, v) = (0..self.rewards[s].len())
265                .map(|a| (a, self.q_value(s, a, values, discount)))
266                .fold((0, f64::NEG_INFINITY), |best, c| if c.1 > best.1 { c } else { best });
267            policy.push(a);
268            new_values.push(v);
269        }
270        MdpSolution { values: new_values, policy }
271    }
272
273    /// Finite-horizon backward induction: the optimal expected total reward over `horizon` steps
274    /// plus `terminal_values[s]` on arrival in the final state. Returns, for each stage from the
275    /// first (`0`) to the last (`horizon - 1`), the value of being in each state and the optimal
276    /// action there; the first element holds the optimal values over the whole horizon.
277    pub fn backward_induction(&self, horizon: usize, terminal_values: &[f64]) -> Result<Vec<MdpSolution>, ErrorsJSL> {
278        self.validate()?;
279        if terminal_values.len() != self.rewards.len() {
280            return Err(ErrorsJSL::IncompatibleArraySizes((terminal_values.len(), self.rewards.len())));
281        }
282        let mut stages = Vec::with_capacity(horizon);
283        let mut next = terminal_values.to_vec();
284        for _ in 0..horizon {
285            let sol = self.greedy(&next, 1.0);
286            next = sol.values.clone();
287            stages.push(sol);
288        }
289        stages.reverse();
290        Ok(stages)
291    }
292
293    /// Discounted infinite-horizon value iteration with discount in `[0, 1)`. Converges when the
294    /// largest change in value falls below `tolerance`; fails if `max_iterations` is exhausted.
295    pub fn value_iteration(&self, discount: f64, tolerance: f64, max_iterations: usize) -> Result<MdpSolution, ErrorsJSL> {
296        self.validate()?;
297        if !(0.0..1.0).contains(&discount) {
298            return Err(ErrorsJSL::InvalidInputRange("Discount must be in [0, 1)."));
299        }
300        // ANCHOR: value_iteration
301        let mut values = vec![0.0; self.rewards.len()];
302        for _ in 0..max_iterations {
303            let sol = self.greedy(&values, discount);
304            let change = sol.values.iter().zip(&values).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
305            values = sol.values;
306            // Standard stopping rule guaranteeing the value error is below `tolerance`.
307            if change <= tolerance * (1.0 - discount) / (2.0 * discount).max(1e-12) {
308                return Ok(self.greedy(&values, discount));
309            }
310        }
311        Err(ErrorsJSL::RuntimeError("Value iteration did not converge."))
312        // ANCHOR_END: value_iteration
313    }
314
315    /// The expected discounted return of following `policy` forever, by Gauss-Seidel sweeps,
316    /// stopping when a sweep changes no value by `tolerance` or more (the remaining error can be
317    /// up to about `discount / (1 − discount)` times larger).
318    pub fn evaluate_policy(&self, policy: &[usize], discount: f64, tolerance: f64) -> Result<Vec<f64>, ErrorsJSL> {
319        self.validate()?;
320        if policy.len() != self.rewards.len() || policy.iter().zip(&self.rewards).any(|(&a, r)| a >= r.len()) || !(0.0..1.0).contains(&discount) {
321            return Err(ErrorsJSL::InvalidInputRange("Invalid policy or discount."));
322        }
323        let mut v = vec![0.0; policy.len()];
324        for _ in 0..1_000_000 {
325            let mut change: f64 = 0.0;
326            for s in 0..v.len() {
327                let new = self.q_value(s, policy[s], &v, discount);
328                change = change.max((new - v[s]).abs());
329                v[s] = new;
330            }
331            if change < tolerance {
332                return Ok(v);
333            }
334        }
335        Err(ErrorsJSL::RuntimeError("Policy evaluation did not converge."))
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn knapsack_and_coins() {
345        let (best, items) = knapsack_01(&[1, 3, 4, 5], &[1.0, 4.0, 5.0, 7.0], 7).unwrap();
346        assert_eq!(best, 9.0);
347        assert_eq!(items, vec![1, 2]); // weights 3 + 4, values 4 + 5
348        assert_eq!(knapsack_01(&[5], &[3.0], 4).unwrap(), (0.0, vec![]));
349        assert!(knapsack_01(&[1], &[], 3).is_err());
350        let counts = coin_change_min_coins(&[1, 5, 10, 25], 63).unwrap();
351        assert_eq!(counts, vec![3, 0, 1, 2]);
352        assert_eq!(coin_change_min_coins(&[4, 6], 7), None);
353        assert_eq!(coin_change_min_coins(&[3, 7], 0), Some(vec![0, 0]));
354        // A greedy-fooling instance: 6 = 3 + 3, not 4 + 1 + 1.
355        assert_eq!(coin_change_min_coins(&[1, 3, 4], 6).unwrap().iter().sum::<usize>(), 2);
356        assert_eq!(coin_change_ways(&[1, 2, 5], 5), 4);
357        assert_eq!(coin_change_ways(&[2], 3), 0);
358    }
359
360    #[test]
361    fn sequence_alignment_problems() {
362        let a: Vec<char> = "AGGTAB".chars().collect();
363        let b: Vec<char> = "GXTXAYB".chars().collect();
364        let lcs = longest_common_subsequence(&a, &b);
365        assert_eq!(lcs.iter().map(|&(i, _)| a[i]).collect::<String>(), "GTAB");
366        assert!(lcs.windows(2).all(|w| w[0].0 < w[1].0 && w[0].1 < w[1].1));
367        let (d, script) = edit_distance(&"kitten".chars().collect::<Vec<_>>(), &"sitting".chars().collect::<Vec<_>>());
368        assert_eq!(d, 3);
369        assert_eq!(script.iter().filter(|op| !matches!(op, EditOp::Keep { .. })).count(), 3);
370        // Applying the script to "kitten" must produce "sitting".
371        let (ka, kb): (Vec<char>, Vec<char>) = ("kitten".chars().collect(), "sitting".chars().collect());
372        let rebuilt: String = script
373            .iter()
374            .filter_map(|op| match *op {
375                EditOp::Keep { i, .. } => Some(ka[i]),
376                EditOp::Substitute { j, .. } | EditOp::Insert { j } => Some(kb[j]),
377                EditOp::Delete { .. } => None,
378            })
379            .collect();
380        assert_eq!(rebuilt, "sitting");
381        assert_eq!(edit_distance::<u8>(&[], &[1, 2]).0, 2);
382        assert_eq!(edit_distance(&[1, 2, 3], &[1, 2, 3]).1.len(), 3);
383        let lis = longest_increasing_subsequence(&[10, 9, 2, 5, 3, 7, 101, 18]);
384        assert_eq!(lis.len(), 4);
385        assert!(lis.windows(2).all(|w| w[0] < w[1]));
386        assert!(longest_increasing_subsequence::<i32>(&[]).is_empty());
387        assert_eq!(longest_increasing_subsequence(&[3, 3, 3]).len(), 1);
388    }
389
390    #[test]
391    fn matrix_chain() {
392        // CLRS example: 30x35, 35x15, 15x5, 5x10, 10x20, 20x25 -> 15125 multiplications.
393        let (cost, order) = matrix_chain_order(&[30, 35, 15, 5, 10, 20, 25]).unwrap();
394        assert_eq!(cost, 15125);
395        assert_eq!(order, "((A0(A1A2))((A3A4)A5))");
396        assert_eq!(matrix_chain_order(&[4, 5]).unwrap(), (0, "A0".to_string()));
397        assert!(matrix_chain_order(&[3]).is_err());
398    }
399
400    fn inventory_like() -> FiniteMdp {
401        // State 0 = "poor", 1 = "rich". Action 0 = save (safe), action 1 = gamble.
402        FiniteMdp {
403            transitions: vec![vec![vec![(0, 1.0)], vec![(1, 0.5), (0, 0.5)]], vec![vec![(1, 1.0)], vec![(1, 0.8), (0, 0.2)]]],
404            rewards: vec![vec![0.0, 0.0], vec![1.0, 2.0]],
405        }
406    }
407
408    #[test]
409    fn mdp_backward_induction_and_value_iteration() {
410        let mdp = inventory_like();
411        let stages = mdp.backward_induction(1, &[0.0, 0.0]).unwrap();
412        assert_eq!(stages[0].values, vec![0.0, 2.0]); // one step: gamble when rich
413        assert_eq!(stages[0].policy[1], 1);
414        let long = mdp.backward_induction(30, &[0.0, 0.0]).unwrap();
415        assert_eq!(long.len(), 30);
416        let sol = mdp.value_iteration(0.9, 1e-10, 10_000).unwrap();
417        // Bellman optimality holds for the returned values.
418        for s in 0..2 {
419            let best = (0..2).map(|a| mdp.rewards[s][a] + 0.9 * mdp.transitions[s][a].iter().map(|&(t, p)| p * sol.values[t]).sum::<f64>()).fold(f64::MIN, f64::max);
420            assert!((best - sol.values[s]).abs() < 1e-8);
421        }
422        // Following the optimal policy reproduces the optimal values.
423        let v = mdp.evaluate_policy(&sol.policy, 0.9, 1e-12).unwrap();
424        assert!(v.iter().zip(&sol.values).all(|(a, b)| (a - b).abs() < 1e-7));
425        // A worse fixed policy does no better.
426        let always_save = mdp.evaluate_policy(&[0, 0], 0.9, 1e-12).unwrap();
427        assert!(always_save[1] <= sol.values[1] + 1e-9);
428    }
429
430    #[test]
431    fn mdp_validation() {
432        let mut bad = inventory_like();
433        bad.transitions[0][0] = vec![(0, 0.4)];
434        assert!(bad.validate().is_err());
435        assert!(inventory_like().value_iteration(1.0, 1e-6, 10).is_err());
436        assert!(inventory_like().backward_induction(3, &[0.0]).is_err());
437        assert!(inventory_like().evaluate_policy(&[0, 5], 0.5, 1e-6).is_err());
438        let empty = FiniteMdp { transitions: vec![], rewards: vec![] };
439        assert!(empty.validate().is_err());
440    }
441}