Skip to content
Merged
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion crates/watershed-core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 30 additions & 3 deletions crates/watershed-core/src/derivative.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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<Ir> {
Arc::new(Ir::Const(Value::F64(x)))
}
Expand Down
38 changes: 38 additions & 0 deletions crates/watershed-core/tests/derivative.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
7 changes: 7 additions & 0 deletions crates/watershed-gpu/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
56 changes: 4 additions & 52 deletions crates/watershed-gpu/examples/credit_loss.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,70 +35,22 @@ 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<T> = std::result::Result<T, Box<dyn std::error::Error>>;

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
/// loan's life.
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)
Expand Down
Loading
Loading