diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eaa513e..b51c4f8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,6 +97,9 @@ jobs: # That workbook against a later version of it: the cells changed are # found, and which loans a slip in one of them reaches. - run: cargo run --locked --release -p watershed-gpu --example audit -- 20000 + # The provision's derivative by 689 of that workbook's inputs, each + # checked against nudging the input. + - run: cargo run --locked --release -p watershed-gpu --example sensitivities -- 5000 web: name: Web demo (WebAssembly) diff --git a/README.md b/README.md index 4c4d6b6..c119a1b 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,8 @@ with its checks and timings. workbook, checked cell by cell against the values Excel saved, and run as a plan. A workbook that answers for one loan answers for 200,000 in seconds, and can be tried everywhere its inputs can go, to see where it - breaks or what a change to it moved. + breaks or what a change to it moved. Its answer's derivative by hundreds + of its inputs comes with it, for a few times the cost of the answer. - **Live tables in the browser.** A grid whose cells, columns and totals are formulas, updated as edits arrive, as a TypeScript package with components for [Solid](packages/grid-solid) and [React](packages/grid-react). The diff --git a/crates/watershed-core/README.md b/crates/watershed-core/README.md index f0b565e..5e2ef77 100644 --- a/crates/watershed-core/README.md +++ b/crates/watershed-core/README.md @@ -320,7 +320,10 @@ positive number, `min` and `max` of equal values as for the first, a condition as for the branch it takes. A total's smallest or largest value passes its derivative to every member equal to it. Comparisons, conditions' tests and counts have a derivative of zero. A node in `with_respect_to` is -taken as free to vary alone, whether or not it is an input. +taken as free to vary alone, whether or not it is an input. Where nothing +comes down to a node, nothing is passed on through it, so a division by +zero on a branch that is not taken (`when(owed <= 0).then(0).otherwise(x / +owed)`) leaves the derivative at zero and not at not-a-number. Not supported: a derivative through whole numbers or decimals (refused, with the node's name, and nothing added), and removing the nodes a gradient diff --git a/crates/watershed-core/src/derivative.rs b/crates/watershed-core/src/derivative.rs index 9c1aae2..d174616 100644 --- a/crates/watershed-core/src/derivative.rs +++ b/crates/watershed-core/src/derivative.rs @@ -151,9 +151,22 @@ impl Graph { } } for used in used { - if let Some(slope) = slope(&formula, used) { - pass(used, times(adjoint.clone(), slope), self); - } + let Some(slope) = slope(&formula, used) else { + continue; + }; + // A slope that can be infinite (a division by nothing, on a + // branch not taken) would make nothing times infinity, which + // is not a number. Where nothing comes down, nothing is + // passed on. + let term = match unbounded(&slope) { + true => Arc::new(Ir::If( + binary(BinOp::Eq, adjoint.clone(), number(0.0)), + number(0.0), + times(adjoint.clone(), slope), + )), + false => times(adjoint.clone(), slope), + }; + pass(used, term, self); } } @@ -361,6 +374,20 @@ fn a_number(of: &Ir) -> bool { } } +/// Whether an expression can come to infinity from finite numbers: it +/// divides, or takes a logarithm, a root or a power. +fn unbounded(of: &Ir) -> bool { + match of { + Ir::Const(_) | Ir::Ref(_) | Ir::List(_) => false, + Ir::Unary(op, a) => matches!(op, UnOp::Ln | UnOp::Sqrt) || unbounded(a), + Ir::Binary(op, a, b) => { + matches!(op, BinOp::Div | BinOp::Pow) || unbounded(a) || unbounded(b) + } + Ir::If(test, then, otherwise) => unbounded(test) || unbounded(then) || unbounded(otherwise), + Ir::Choose(index, options) => unbounded(index) || options.iter().any(|o| unbounded(o)), + } +} + fn number(x: f64) -> Arc { Arc::new(Ir::Const(Value::F64(x))) } diff --git a/crates/watershed-core/tests/derivative.rs b/crates/watershed-core/tests/derivative.rs index d8e9ccd..bea26be 100644 --- a/crates/watershed-core/tests/derivative.rs +++ b/crates/watershed-core/tests/derivative.rs @@ -76,6 +76,44 @@ fn a_derivative_follows_its_inputs_as_any_node_does() -> Result { Ok(()) } +#[test] +fn a_division_by_nothing_on_a_branch_not_taken_leaves_no_trace() -> Result { + // The share of a loan lost when its property is sold, guarded for a + // loan with nothing owed, as a spreadsheet guards it. With nothing + // owed the loss is nothing and so is its derivative, not the nothing + // times infinity the division's own slope would make of it. + let mut g = Graph::new(); + let owed = g.input("owed", 0.0)?; + let sold = g.input("sold", 150.0)?; + let cut = g.input("cut", 0.2)?; + let chance = g.input("chance", 0.1)?; + let costs = g.input("costs", 0.07)?; + let rate = g.input("rate", 0.0)?; + // Long enough, and of enough nodes, to be taken in steps: the division + // is then a step of its own, outside the condition that guards it. + let lost = g.define( + "lost", + when(owed.le(0.0)).then(0.0).otherwise( + (1.0 - sold * (1.0 - cut) * (1.0 - costs) / (1.0 + rate).pow(2.0) / owed) + .min(1.0) + .max(0.05), + ), + )?; + let loss = g.define("loss", chance * lost * owed)?; + let by = [sold.id(), cut.id(), chance.id(), owed.id()]; + let slopes = g.gradient(loss.id(), &by, "slope")?; + g.stabilize(); + for &slope in &slopes[..3] { + assert_eq!(number(&g, slope), 0.0); + } + // And with something owed, the slopes are the model's own. + g.set(owed, 200.0)?; + g.stabilize(); + let want = -0.1 * 0.8 * 0.93; + assert!((number(&g, slopes[0]) - want).abs() < 1e-12); + Ok(()) +} + #[test] fn a_floor_is_flat_between_its_steps() -> Result { let mut g = Graph::new(); diff --git a/crates/watershed-gpu/README.md b/crates/watershed-gpu/README.md index 75364da..a3b6b5b 100644 --- a/crates/watershed-gpu/README.md +++ b/crates/watershed-gpu/README.md @@ -111,6 +111,7 @@ Where a time is scaled up from a smaller run, it says so. | `spreadsheet` | A public Excel valuation workbook, 10 million trials | Excel's stored values: all 176 cells | 0.5 s | 1.8 s | the graph, a trial at a time: 104 s (scaled) | | `credit_loss` | A workbook that works out one mortgage's expected credit loss (3,124 formulas on three paths of the economy), run for 200,000 mortgages | LibreOffice recalculating the workbook for each of 300 loans: 8×10⁻¹⁶; the values saved in the workbook: all 3,124 cells | not run | 5.4 s, on 4 cores of a different machine (a cloud VM) | LibreOffice, a loan at a time, at the 17.4 ms it took on that machine: 58 minutes (scaled) | | `audit` | The same workbook tried at 200,000 points spread over its inputs' ranges and at every corner of them, each input then moved through its range from 300 starting points, and a later version of the workbook run for the same points | its own findings when run on its own: the two cells changed, and which loans the slip in one of them reaches | not run | 17 s for all of it, on the same 4 cores | | +| `sensitivities` | The same workbook's provision with its derivative by 689 inputs (17 of the bank's choices and every quarter of three paths of the economy), for 50,000 mortgages | nudging each input up and down for the workbook's own loan: all 689 agree, the furthest by 4×10⁻⁹ | not run | 7.6 s, against 1.4 s for the provision alone, on the same 4 cores | nudging each for the book, 1,378 runs of it: 32 minutes (scaled) | | `dosing` | An antibiotic's dosing protocol tried on 5 million made-up patients, each followed for 72 hours | SciPy's LSODA solver, 300 patients: 1.7×10⁻¹⁰ | 60 ms a protocol, 51 protocols in 3.0 s | 1.8 s a protocol | the graph: 70 s (scaled) | | `monte_carlo` | 200,000 positions on 500 shares, 100,000 futures | the graph, bit for bit | 1.6 s | about 29 s (scaled) | the graph: about 25 minutes (scaled) | | `tax_benefit` | A country's tax and benefit rules over 10 million households | the graph, bit for bit | 0.7 s | 0.5 s | the graph: 28 s (scaled) | @@ -435,6 +436,11 @@ What is taken from somewhere, and what is made up. each path, and the provision rises with days past due on every line tried. It still shows the lifetime loss falling a little as today's chance of default nears nine in ten, which is left for a reader to judge. +- **`sensitivities`.** The `credit_loss` workbook and the same made-up book + of loans. A derivative is the slope where each loan stands: it says + nothing of a loan that a change would move to another stage, and it is + nought through a number the workbook rounds, which is why the loan's own + cells are not among the 689. - **`backtest`, `experts`.** Daily prices from 2010 to 2025 for shares with a price throughout, from the FINSABER data set on Hugging Face (`finsaber-team/FINSABER-V2-Data`), which does not say where its prices @@ -463,6 +469,7 @@ cargo run --release --features cuda --example loans cargo run --release --features cuda --example pensions cargo run --release --features cuda --example credit_loss cargo run --release --features cuda --example audit +cargo run --release --features cuda --example sensitivities ``` Without `--features cuda` each runs on the CPU, with fewer scenarios unless diff --git a/crates/watershed-gpu/examples/credit_loss.rs b/crates/watershed-gpu/examples/credit_loss.rs index fad2fef..1eb9d4d 100644 --- a/crates/watershed-gpu/examples/credit_loss.rs +++ b/crates/watershed-gpu/examples/credit_loss.rs @@ -35,21 +35,15 @@ use watershed_core::Value; use watershed_gpu::Scenarios; use watershed_xlsx::{Model, Workbook}; +#[path = "shared/loan_book.rs"] +mod loan_book; +use loan_book::*; + type Result = std::result::Result>; -const WORKBOOK: &str = concat!( - env!("CARGO_MANIFEST_DIR"), - "/examples/shared/credit_loss.xlsx" -); /// What LibreOffice made of the workbook for some loans, a loan at a time. const REFERENCE: &str = include_str!("shared/credit_loss_reference.csv"); -/// The loan's cells: what is owed, the yearly rate, the quarters left, the -/// property's value, the chance of default in a year as scored at first and -/// today, and the days past due. -const LOAN: [&str; 7] = [ - "Loan!B4", "Loan!B5", "Loan!B6", "Loan!B7", "Loan!B8", "Loan!B9", "Loan!B10", -]; /// How likely the slump is, and how bad. const SLUMP: [&str; 2] = ["Model!B6", "Model!B8"]; /// The stage, the provision, and the loss expected in a year and over the @@ -57,48 +51,6 @@ const SLUMP: [&str; 2] = ["Model!B6", "Model!B8"]; const ANSWERS: [&str; 4] = ["Loan!B13", "Loan!B14", "Loan!B15", "Loan!B16"]; const INPUTS: usize = LOAN.len() + SLUMP.len(); -/// A small deterministic random number generator, so every run is the same. -struct Rng(u64); -impl Rng { - fn unit(&mut self) -> f64 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 7; - self.0 ^= self.0 << 17; - ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64 - } -} - -fn to_places(x: f64, places: i32) -> f64 { - let m = 10f64.powi(places); - (x * m).round() / m -} - -/// One loan of a made-up book, as the seven numbers the workbook asks for. -fn made_up_loan(rng: &mut Rng) -> [f64; 7] { - let owed = to_places(40_000.0 * (2.7 * rng.unit()).exp(), 2); - let rate = to_places(0.02 + 0.05 * rng.unit(), 4); - let quarters = (8 + (93.0 * rng.unit()) as u32) as f64; - let value = to_places(owed / (0.2 + 0.9 * rng.unit().powf(0.7)), 0); - let at_first = to_places(0.002 * (2.7 * rng.unit()).exp(), 5); - // Most loans are scored about as they were; one in seven much worse. - let drifted = match rng.unit() < 0.85 { - true => 0.6 + 0.8 * rng.unit(), - false => 2.0 + 6.0 * rng.unit(), - }; - let now = to_places((at_first * drifted).min(0.6), 5); - let late = rng.unit(); - let days = if late < 0.95 { - 0 - } else if late < 0.975 { - 1 + (30.0 * rng.unit()) as u32 - } else if late < 0.99 { - 31 + (59.0 * rng.unit()) as u32 - } else { - 90 + (200.0 * rng.unit()) as u32 - }; - [owed, rate, quarters, value, at_first, now, days as f64] -} - /// The same to about twelve figures. fn close(a: f64, b: f64) -> bool { (a - b).abs() <= 1e-9 * a.abs().max(b.abs()).max(1e-6) diff --git a/crates/watershed-gpu/examples/sensitivities.rs b/crates/watershed-gpu/examples/sensitivities.rs new file mode 100644 index 0000000..37d6fe3 --- /dev/null +++ b/crates/watershed-gpu/examples/sensitivities.rs @@ -0,0 +1,424 @@ +//! What moves a workbook's answer, and by how much, for every input at once. +//! +//! Whoever signs off a provision is asked what it rests on. How much does +//! it move if defaults respond more to unemployment than assumed? If +//! selling a repossessed house costs more? If the slump's third year is +//! worse than the economists drew it? A spreadsheet answers each by +//! changing the number and recalculating: one recalculation of the whole +//! book for each question, and the questions run to hundreds once every +//! quarter of every path of the economy is one. +//! +//! This reads the `credit_loss` example's workbook with `watershed-xlsx` +//! and asks the graph for the derivative of a loan's provision by each of +//! its assumptions and by every quarter of the economy: 688 numbers. They +//! are worked out backwards from the provision, all together, so the lot +//! costs a few times the provision alone, not 688 times. The derivatives +//! are nodes of the graph like any others, so a plan runs them for the +//! whole book with the provision itself. +//! +//! It checks every one of them for the workbook's own loan against nudging +//! that input up and down. Then it adds them up over a made-up book, and +//! says which assumptions and which quarters the book's provision rests on. +//! +//! A derivative is the slope where each loan stands. It says nothing of a +//! loan that a change would carry across a threshold into another stage: +//! that is a jump, not a slope, and the last part shows the difference. +//! For the same reason the loan's own cells are left out: the workbook +//! rounds interest and payments to the penny, and a rounded number's slope +//! is nought. +//! +//! cargo run --release --features cuda --example sensitivities +//! +//! then optionally how many loans (50,000). The workbook is written by +//! `shared/credit_loss.py`; everything in it is made up. + +use std::time::{Duration, Instant}; + +use watershed_core::NodeId; +use watershed_gpu::Scenarios; +use watershed_xlsx::{Cell, Model, Val, Workbook}; + +#[path = "shared/loan_book.rs"] +mod loan_book; +use loan_book::*; + +type Result = std::result::Result>; + +/// The bank's choices on the `Model` sheet: the rows of column B, and the +/// discounts on a forced sale in column E. +const CHOICES: [u32; 11] = [5, 6, 8, 10, 11, 12, 13, 15, 16, 18, 19]; +const DISCOUNTS: std::ops::RangeInclusive = 5..=10; +/// The economy's typed columns, and its rows: a quarter each. +const ECONOMY: [(&str, &str); 6] = [ + ("B", "expected, unemployment"), + ("C", "expected, house prices"), + ("D", "better, unemployment"), + ("E", "better, house prices"), + ("F", "the slump's rise in unemployment"), + ("G", "the slump's fall in house prices"), +]; +const QUARTERS: std::ops::RangeInclusive = 5..=116; +/// How many loans a run takes at once: each gives back hundreds of numbers. +const AT_ONCE: usize = 2_000; + +/// A plan, on the GPU when there is one. +struct Runner { + #[cfg(feature = "gpu")] + gpu: watershed_gpu::Gpu, +} + +impl Runner { + fn new() -> Result { + Ok(Runner { + #[cfg(feature = "gpu")] + gpu: watershed_gpu::Gpu::new()?, + }) + } + + fn run(&self, plan: &Scenarios, inputs: &[f64]) -> Result> { + #[cfg(feature = "gpu")] + return Ok(self.gpu.run(plan, inputs)?); + #[cfg(not(feature = "gpu"))] + Ok(plan.run_cpu(inputs)) + } + + /// The sum over the loans of each thing the plan works out. + fn summed(&self, plan: &Scenarios, loans: &[[f64; 7]], each: usize) -> Result> { + let mut sums = vec![0.0; each]; + for some in loans.chunks(AT_ONCE) { + let got = self.run(plan, some.as_flattened())?; + for one in got.chunks(each) { + for (sum, x) in sums.iter_mut().zip(one) { + *sum += x; + } + } + } + Ok(sums) + } +} + +/// An input the provision is differentiated by. +struct By { + cell: Cell, + /// What it is, in words. + what: String, + /// What the workbook has for it. + value: f64, +} + +fn main() -> Result<()> { + let count: usize = match std::env::args().nth(1) { + Some(n) => n.replace('_', "").parse()?, + None => 50_000, + }; + let runner = Runner::new()?; + + // ---- The workbook ---- + println!("1. The workbook"); + let book = Workbook::open(WORKBOOK)?; + let number = |c: Cell| match book.value(c) { + Val::Num(x) => Ok(x), + _ => Err(format!("{} does not hold a number", book.name(c))), + }; + let text = |name: &str| -> Result { + Ok(match book.value(book.cell(name)?) { + Val::Text(t) => t, + _ => String::new(), + }) + }; + let mut by = Vec::new(); + for row in CHOICES { + let cell = book.cell(&format!("Model!B{row}"))?; + let what = match row { + 5 | 6 => format!( + "How likely the {} path is", + text(&format!("Model!A{row}"))?.to_lowercase() + ), + _ => text(&format!("Model!A{row}"))?, + }; + by.push(By { + cell, + what, + value: number(cell)?, + }); + } + for row in DISCOUNTS { + let cell = book.cell(&format!("Model!E{row}"))?; + let from = number(book.cell(&format!("Model!D{row}"))?)?; + let what = format!("Discount on a forced sale, loan to value from {from}"); + by.push(By { + cell, + what, + value: number(cell)?, + }); + } + let choices = by.len(); + for (column, what) in ECONOMY { + for row in QUARTERS { + let cell = book.cell(&format!("Economy!{column}{row}"))?; + let what = format!("{what}, quarter {}", row - 4); + by.push(By { + cell, + what, + value: number(cell)?, + }); + } + } + let loan: Vec = LOAN + .iter() + .map(|name| book.cell(name)) + .collect::>()?; + let all: Vec = loan + .iter() + .copied() + .chain(by.iter().map(|b| b.cell)) + .collect(); + let provision_cell = book.cell("Loan!B14")?; + let mut model = Model::build(&book, &all, &[provision_cell])?; + let wrong = model.check(); + if let Some(first) = wrong.first() { + return Err(format!("the graph does not agree with the workbook: {first}").into()); + } + let ids = model.inputs(); + let provision = model.outputs()[0]; + let before = model.graph().len(); + let started = Instant::now(); + let slopes: Vec = model + .graph_mut() + .gradient(provision, &ids[loan.len()..], "slope")?; + model.graph_mut().stabilize(); + println!( + " credit_loss.xlsx: {} cells between its inputs and the provision, all as the workbook has them", + model.translated() + ); + println!( + " the provision's derivative by {} of them ({} choices, {} quarters of the economy): {} more nodes, added in {}", + by.len(), + choices, + by.len() - choices, + model.graph().len() - before, + time(started.elapsed()) + ); + println!(); + + // ---- One loan, against nudging ---- + println!("2. The workbook's own loan, against nudging each input"); + let as_given = model.workbook_inputs(); + let mut outputs = vec![provision]; + outputs.extend(&slopes); + // The loan's seven cells vary from loan to loan; the rest stay as the + // workbook has them. + let with_slopes = Scenarios::new(model.graph(), &ids[..loan.len()], &outputs)?; + let alone = Scenarios::new(model.graph(), &ids[..loan.len()], &[provision])?; + let everything = Scenarios::new(model.graph(), &ids, &[provision])?; + let own = runner.run(&with_slopes, &as_given[..loan.len()])?; + let mut nudged = Vec::with_capacity(2 * by.len() * as_given.len()); + let nudge = |x: f64| 1e-6 * x.abs().max(0.01); + for k in 0..by.len() { + for sign in [-1.0, 1.0] { + let mut inputs = as_given.clone(); + inputs[loan.len() + k] += sign * nudge(by[k].value); + nudged.extend(inputs); + } + } + let moved = runner.run(&everything, &nudged)?; + let mut apart = Vec::new(); + let mut worst = 0.0f64; + for (k, b) in by.iter().enumerate() { + let measured = (moved[2 * k + 1] - moved[2 * k]) / (2.0 * nudge(b.value)); + let slope = own[1 + k]; + // To five figures of the slope, or of what a nudge can measure. + let room = 1e-5 * slope.abs() + 1e-13 * own[0] / nudge(b.value); + let off = (measured - slope).abs(); + if off > room { + apart.push(format!("{}: {slope} here, {measured} by nudging", b.what)); + } else if slope != 0.0 { + worst = worst.max(off / slope.abs()); + } + } + println!( + " provision {:.2}; {} derivatives, each against the provision with that input a millionth up and down", + own[0], + by.len() + ); + println!( + " {} agree, the furthest by {worst:.0e} of itself; {} do not", + by.len() - apart.len(), + apart.len() + ); + for line in apart.iter().take(10) { + println!(" {line}"); + } + assert!(apart.is_empty(), "a derivative is not what nudging gives"); + let nonzero = (0..by.len()).filter(|&k| own[1 + k] != 0.0).count(); + println!(" {nonzero} of them are not nought for this loan"); + println!(" what a hundredth more of each would do, the largest first:"); + let effect = |k: usize, slopes: &[f64]| slopes[k] * by[k].value * 0.01; + let mut order: Vec = (0..by.len()).collect(); + order.sort_by(|&a, &b| { + effect(b, &own[1..]) + .abs() + .total_cmp(&effect(a, &own[1..]).abs()) + }); + for &k in order.iter().take(6) { + println!( + " {:>+9.3} {} (now {})", + effect(k, &own[1..]), + by[k].what, + by[k].value + ); + } + println!(); + + // ---- The book ---- + println!("3. The book"); + let mut rng = Rng(0x2545_F491_4F6C_DD1D); + let loans: Vec<[f64; 7]> = (0..count).map(|_| made_up_loan(&mut rng)).collect(); + let started = Instant::now(); + let plain = runner.summed(&alone, &loans, 1)?; + let plain_took = started.elapsed(); + let started = Instant::now(); + let sums = runner.summed(&with_slopes, &loans, outputs.len())?; + let took = started.elapsed(); + assert!((sums[0] - plain[0]).abs() <= 1e-9 * plain[0].abs()); + println!( + " {} loans: the provision alone in {}, with its {} derivatives in {} ({:.1} times as long)", + commas(count as f64), + time(plain_took), + by.len(), + time(took), + took.as_secs_f64() / plain_took.as_secs_f64() + ); + println!( + " nudging each instead is two runs of the book apiece: {} runs, about {}", + commas(2.0 * by.len() as f64), + time(plain_took * 2 * by.len() as u32) + ); + let total = sums[0]; + let book_slopes = &sums[1..]; + println!(" provision for the book: {}", commas(total)); + println!(); + println!(" the bank's choices: what a hundredth more of each does to the provision"); + for (k, b) in by.iter().enumerate().take(choices) { + let moves = effect(k, book_slopes); + println!( + " {:>12} {:>+7.2}% {} (now {})", + signed(moves), + 100.0 * moves / total, + b.what, + b.value + ); + } + println!(); + println!(" the economy: what a year of it does to the provision, by the year it falls in"); + println!( + " unemployment a point higher all that year, or house prices lower by a hundredth of today's" + ); + print!(" {:<34}", ""); + let years = [ + "year 1", + "year 2", + "year 3", + "year 4", + "year 5", + "years 6-10", + "after", + ]; + for year in years { + print!("{year:>12}"); + } + println!(); + let per = QUARTERS.clone().count(); + for (c, (_, what)) in ECONOMY.iter().enumerate() { + // House prices are asked about going down. + let unit = if c % 2 == 0 { 1.0 } else { -0.01 }; + let column = &book_slopes[choices + c * per..choices + (c + 1) * per]; + print!(" {what:<34}"); + for (y, _) in years.iter().enumerate() { + let quarters = match y { + 0..=4 => 4 * y..4 * y + 4, + 5 => 20..40, + _ => 40..per, + }; + print!( + "{:>12}", + signed(unit * column[quarters].iter().sum::()) + ); + } + println!(); + } + println!(); + + // ---- What a slope does not see ---- + println!("4. What a slope does not see"); + let threshold = CHOICES.iter().position(|&row| row == 18).expect("row 18"); + let step = 0.05 * by[threshold].value; + let mut sample = Vec::new(); + let few = &loans[..count.min(10_000)]; + for sign in [0.0, 1.0] { + for loan in few { + let mut inputs = as_given.clone(); + inputs[..loan.len()].copy_from_slice(loan); + inputs[loan.len() + threshold] += sign * step; + sample.extend(inputs); + } + } + let got = runner.run(&everything, &sample)?; + let (was, is): (f64, f64) = (got[..few.len()].iter().sum(), got[few.len()..].iter().sum()); + println!(" {} (now {})", by[threshold].what, by[threshold].value); + println!( + " its derivative for the book is {}: no loan's provision slopes with it", + signed(book_slopes[threshold]) + ); + println!( + " yet at {} the first {} loans set aside {} where they set aside {}: {:+.1}%", + by[threshold].value + step, + commas(few.len() as f64), + commas(is), + commas(was), + 100.0 * (is - was) / was + ); + println!( + " it moves loans from one stage to another, which is a jump: the `audit` example is for those" + ); + assert!(book_slopes[threshold] == 0.0 && is < was); + Ok(()) +} + +/// A sum of money with its sign and thousands separated. +fn signed(x: f64) -> String { + match x >= 0.0 { + true => format!("+{}", commas(x)), + false => commas(x), + } +} + +fn commas(x: f64) -> String { + let digits = format!("{:.0}", x.abs()); + let mut out = String::new(); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i) % 3 == 0 { + out.push(','); + } + out.push(c); + } + if x < 0.0 && digits != "0" { + out.insert(0, '-'); + } + out +} + +fn time(d: Duration) -> String { + let s = d.as_secs_f64(); + if s < 0.001 { + format!("{:.1} µs", s * 1e6) + } else if s < 1.0 { + format!("{:.0} ms", s * 1e3) + } else if s < 120.0 { + format!("{s:.1} s") + } else if s < 7200.0 { + format!("{:.0} minutes", s / 60.0) + } else { + format!("{:.1} hours", s / 3600.0) + } +} diff --git a/crates/watershed-gpu/examples/shared/loan_book.rs b/crates/watershed-gpu/examples/shared/loan_book.rs new file mode 100644 index 0000000..711a3d5 --- /dev/null +++ b/crates/watershed-gpu/examples/shared/loan_book.rs @@ -0,0 +1,54 @@ +//! The made-up loan book the examples that read `credit_loss.xlsx` share. + +/// The workbook, and the loan's cells in it: what is owed, the yearly rate, +/// the quarters left, the property's value, the chance of default in a year +/// as scored at first and today, and the days past due. +pub const WORKBOOK: &str = concat!( + env!("CARGO_MANIFEST_DIR"), + "/examples/shared/credit_loss.xlsx" +); +pub const LOAN: [&str; 7] = [ + "Loan!B4", "Loan!B5", "Loan!B6", "Loan!B7", "Loan!B8", "Loan!B9", "Loan!B10", +]; + +/// A small deterministic random number generator, so every run is the same. +pub struct Rng(pub u64); +impl Rng { + pub fn unit(&mut self) -> f64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + ((self.0 >> 11) as f64 + 0.5) / (1u64 << 53) as f64 + } +} + +fn to_places(x: f64, places: i32) -> f64 { + let m = 10f64.powi(places); + (x * m).round() / m +} + +/// One loan of a made-up book, as the seven numbers the workbook asks for. +pub fn made_up_loan(rng: &mut Rng) -> [f64; 7] { + let owed = to_places(40_000.0 * (2.7 * rng.unit()).exp(), 2); + let rate = to_places(0.02 + 0.05 * rng.unit(), 4); + let quarters = (8 + (93.0 * rng.unit()) as u32) as f64; + let value = to_places(owed / (0.2 + 0.9 * rng.unit().powf(0.7)), 0); + let at_first = to_places(0.002 * (2.7 * rng.unit()).exp(), 5); + // Most loans are scored about as they were; one in seven much worse. + let drifted = match rng.unit() < 0.85 { + true => 0.6 + 0.8 * rng.unit(), + false => 2.0 + 6.0 * rng.unit(), + }; + let now = to_places((at_first * drifted).min(0.6), 5); + let late = rng.unit(); + let days = if late < 0.95 { + 0 + } else if late < 0.975 { + 1 + (30.0 * rng.unit()) as u32 + } else if late < 0.99 { + 31 + (59.0 * rng.unit()) as u32 + } else { + 90 + (200.0 * rng.unit()) as u32 + }; + [owed, rate, quarters, value, at_first, now, days as f64] +} diff --git a/crates/watershed-xlsx/README.md b/crates/watershed-xlsx/README.md index d6ed9dd..f82e554 100644 --- a/crates/watershed-xlsx/README.md +++ b/crates/watershed-xlsx/README.md @@ -29,7 +29,8 @@ The `spreadsheet` example in watershed-gpu does this for a valuation workbook and a million trials, and `credit_loss` for a workbook that works out one loan's expected credit loss, run for a whole loan book. `audit` tries a workbook over the whole of its inputs' ranges, and against a later -version of itself. +version of itself. `sensitivities` asks the graph for an answer's +derivative by hundreds of the workbook's cells at once. ## What is translated