build(lean): verify/lean requires bookspec's Lean; the laws live once

D-69 puts the accounting laws in one place: bookspec's Lean, namespace
`Bookspec`. L-F1 landed there every file of `verify/lean/Wanderbooks/`.
Before deleting the copies, each was checked: comments stripped, namespace
normalised, blank lines dropped, and diffed against its bookspec peer --
all ten are identical (Basic, Entry, Statements, Closing, Ledger,
Apportion, Parties, Prorate, Deductible, Documents). There is nothing
wanderbooks-only left to keep.

So `verify/lean/lakefile.toml` now `[[require]]`s bookspec as a git
dependency at 77e046334eea29e082b53bbe907017d9ffef5a0a -- the same rev
`crates/ledger-core/Cargo.toml` pins the Rust checker to -- with
`subDir = "lean"`. The generated `lake-manifest.json` is committed, because
Lake builds from it and it must not float.

`Wanderbooks.lean` is now a thin local target that imports `Bookspec`:
`lake build` builds and checks the whole law set, and the file says where
a law is edited and how wanderbooks picks it up (move the pin). The
duplicated modules and the `Wanderbooks/` directory are gone.

`Audit.lean` imports `Bookspec` and audits all 151 theorems (the 118
headline laws plus the 33 named laws in `Laws.lean` that cite them) --
the whole set bookspec itself audits. `just prove` still checks standard
axioms only; its summary now says "theorems", since the set is more than
headline ones.

The new `tests/bookspec/pin.rs` reads the rev out of the lakefile, the
manifest, and both crates' Cargo.toml, and fails unless all four name the
same repository at the same commit, and bookspec's `lean/` package. Without
it the Lean laws and the Rust checker could silently be different spec
versions.

Verified: `lake build` from a clean `.lake` (fetches and builds in 7 s);
`just prove` 871 s (Kani 53 harnesses, then 151 theorems, standard axioms
only); `cargo test -p ledger-core --test bookspec pin`; `cargo fmt --check`;
`cargo clippy -p ledger-core --tests -D warnings`.

Co-Authored-By: DeepSeek V4.1 Flash <noreply@opencode.ai>
This commit is contained in:
swaitsandDeepSeek V4.1 Flash committed 2026-11-08 11:35:07 -07:00
1 parent 7a3860de73
commit e431791bbc
18 files changed
+231 -3815

No files matched your search

@@ -86,6 +86,7 @@ mod engine;
mod events;
mod examples;
mod loader_tests;
mod pin;
mod queries;
mod rules_md;
mod run;
+150
View File
@@ -0,0 +1,150 @@
use crate::*;
/// The Lean laws and the Rust checker must come from one bookspec rev
/// (D-69): `verify/lean` requires bookspec's Lean at a git rev, and the
/// crates depend on bookspec's checker and runner at a git rev. If the two
/// drift, `just prove` audits laws the tests do not run against — so this
/// test fails unless every pin names the same repository at the same commit.
///
/// The revs live in four files; the Lean one is in two of them (the
/// lakefile's `[[require]]` and the generated `lake-manifest.json`, which
/// Lake builds from, so both must agree).
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}
/// A pin as one of the files states it: where it was found, the URL and
/// the commit.
struct Pin {
source: String,
url: String,
rev: String,
}
fn lean_pins(root: &Path) -> Vec<Pin> {
let mut pins = Vec::new();
let lakefile = std::fs::read_to_string(root.join("verify/lean/lakefile.toml"))
.expect("verify/lean/lakefile.toml");
let doc: toml::Value = toml::from_str(&lakefile).expect("lakefile.toml parses");
let require = doc
.get("require")
.and_then(toml::Value::as_array)
.expect("lakefile.toml has [[require]]");
let bookspec = require
.iter()
.find(|r| r.get("name").and_then(toml::Value::as_str) == Some("bookspec"))
.expect("lakefile.toml requires bookspec");
assert_eq!(
bookspec.get("subDir").and_then(toml::Value::as_str),
Some("lean"),
"verify/lean/lakefile.toml requires bookspec from its lean/ package"
);
pins.push(Pin {
source: "verify/lean/lakefile.toml".into(),
url: bookspec
.get("git")
.and_then(toml::Value::as_str)
.expect("the require names a git url")
.into(),
rev: bookspec
.get("rev")
.and_then(toml::Value::as_str)
.expect("the require names a rev")
.into(),
});
let manifest = std::fs::read_to_string(root.join("verify/lean/lake-manifest.json"))
.expect("verify/lean/lake-manifest.json (commit it: Lake builds from it)");
let doc: serde_json::Value = serde_json::from_str(&manifest).expect("manifest parses");
let bookspec = doc
.get("packages")
.and_then(serde_json::Value::as_array)
.expect("manifest has packages")
.iter()
.find(|p| p.get("name").and_then(serde_json::Value::as_str) == Some("bookspec"))
.expect("the manifest records bookspec");
assert_eq!(
bookspec.get("subDir").and_then(serde_json::Value::as_str),
Some("lean"),
"verify/lean/lake-manifest.json records bookspec's lean/ package"
);
pins.push(Pin {
source: "verify/lean/lake-manifest.json".into(),
url: bookspec
.get("url")
.and_then(serde_json::Value::as_str)
.expect("the manifest records a url")
.into(),
rev: bookspec
.get("rev")
.and_then(serde_json::Value::as_str)
.expect("the manifest records a rev")
.into(),
});
pins
}
/// Every `bookspec-*` dependency in a crate's manifest, from whichever
/// table it is declared in.
fn cargo_pins(root: &Path, manifest: &str) -> Vec<Pin> {
let path = root.join(manifest);
let text = std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("{manifest}"));
let doc: toml::Value = toml::from_str(&text).unwrap_or_else(|_| panic!("{manifest} parses"));
let mut pins = Vec::new();
for table in ["dependencies", "dev-dependencies", "build-dependencies"] {
let Some(deps) = doc.get(table).and_then(toml::Value::as_table) else {
continue;
};
for (name, dep) in deps {
if !name.starts_with("bookspec-") {
continue;
}
let Some(dep) = dep.as_table() else { continue };
let url = dep
.get("git")
.and_then(toml::Value::as_str)
.unwrap_or_else(|| panic!("{manifest}: {name} is not a git dependency"));
let rev = dep
.get("rev")
.and_then(toml::Value::as_str)
.unwrap_or_else(|| panic!("{manifest}: {name} is pinned to a rev, not a branch"));
pins.push(Pin {
source: format!("{manifest}: {name}"),
url: url.into(),
rev: rev.into(),
});
}
}
assert!(!pins.is_empty(), "{manifest} pins no bookspec crate");
pins
}
#[test]
pub(crate) fn bookspec_rev_is_pinned_once() {
let root = repo_root();
let mut pins = lean_pins(&root);
pins.extend(cargo_pins(&root, "crates/ledger-core/Cargo.toml"));
pins.extend(cargo_pins(&root, "crates/ledger-package/Cargo.toml"));
let first = &pins[0];
let differing: Vec<String> = pins
.iter()
.filter(|p| p.rev != first.rev || p.url != first.url)
.map(|p| format!(" {}: {} @ {}", p.source, p.url, p.rev))
.collect();
assert!(
differing.is_empty(),
"the Lean laws and the Rust checker name different bookspec pins \
(all four must be {} @ {}):\n{}",
first.url,
first.rev,
differing.join("\n")
);
assert_eq!(first.url, "https://git.swaits.com/swaits/bookspec");
assert_eq!(
first.rev.len(),
40,
"a bookspec pin is a full commit: {}",
first.rev
);
}
+1 -1
View File
@@ -78,7 +78,7 @@ prove: (_kani "fast")
echo "Lean audit: a theorem rests on something beyond the standard axioms" >&2
exit 1
fi
echo "Lean: $(wc -l <<<"$audit") headline theorems, standard axioms only"
echo "Lean: $(wc -l <<<"$audit") theorems, standard axioms only"
# The slow Kani harnesses (kani_slow), each under its own 30-minute cap, $(nproc) at a time (CI runs it beside prove)
prove-slow: (_kani "slow")
+2 -2
View File
@@ -14,8 +14,8 @@ node = "26"
# `just prove`: Kani model-checks the accounting kernel. Kani fetches its
# own pinned nightly and CBMC under ~/.kani on first run.
"cargo:kani-verifier" = "0.68.0"
# `just prove`: Lean proves the accounting laws (verify/lean). Matches
# verify/lean/lean-toolchain.
# `just prove`: Lean proves the accounting laws (bookspec's, required by
# verify/lean). Matches verify/lean/lean-toolchain.
"github:leanprover/lean4" = "4.34.1"
# Mutation testing and fuzzing (docs/oracle.md).
"cargo:cargo-mutants" = "27.1.0"
+39 -6
View File
@@ -1,11 +1,11 @@
import Wanderbooks
import Bookspec
/-! `just prove` runs this file: each headline theorem's axioms are printed,
and must be only Lean's standard three (`propext`, `Quot.sound`,
`Classical.choice`) or fewer. No `sorryAx`, nothing assumed. -/
open Wanderbooks
/-! `just prove` runs this file: each theorem's axioms are printed, and must
be only Lean's standard three (`propext`, `Quot.sound`, `Classical.choice`)
or fewer. No `sorryAx`, nothing assumed. The theorems are bookspec's: the
118 headline laws and the 33 named laws that cite them (D-69). -/
open Bookspec
#print axioms Accepted.net_zero
#print axioms sum_movements
#print axioms movement_with_reversal
@@ -124,3 +124,36 @@ open Wanderbooks
#print axioms Deductible.tie_example
#print axioms Deductible.scale_books
#print axioms Deductible.scale_percents
#print axioms law_debits_equal_credits
#print axioms law_accounting_equation
#print axioms law_trial_balance
#print axioms law_net_income_articulates
#print axioms law_cash_flow_is_change_in_cash
#print axioms law_acceptance_is_arithmetic
#print axioms law_accepted_entry_nets_to_zero
#print axioms law_movements_partition_the_net
#print axioms law_reversal_accepted_iff
#print axioms law_reversal_cancels
#print axioms law_normal_side
#print axioms law_trial_balance_is_complete
#print axioms law_period_statements_add_up
#print axioms law_invariant_holds
#print axioms law_posted_is_forever
#print axioms law_closed_periods_frozen
#print axioms law_record_changes_no_figure
#print axioms law_closing_entry_zeroes
#print axioms law_allocation_sums_to_the_whole
#print axioms law_member_run_telescopes
#print axioms law_cumulative_close_hands_out_its_net
#print axioms law_bounded_drift
#print axioms law_capital_unmoved_by_close
#print axioms law_reversal_is_the_exact_opposite
#print axioms law_proration_parts_sum_to_the_total
#print axioms law_proration_part_is_near
#print axioms law_proration_charge_never_falls
#print axioms law_control_account_is_its_documents
#print axioms law_send_changes_no_figure
#print axioms law_settlement_is_a_document_step
#print axioms law_write_off_within_bounds
#print axioms law_discard_moves_no_figure
#print axioms law_deductible_rounds_once
+15 -10
View File
@@ -1,10 +1,15 @@
import Wanderbooks.Basic
import Wanderbooks.Entry
import Wanderbooks.Statements
import Wanderbooks.Closing
import Wanderbooks.Ledger
import Wanderbooks.Apportion
import Wanderbooks.Parties
import Wanderbooks.Prorate
import Wanderbooks.Deductible
import Wanderbooks.Documents
import Bookspec
/-!
# The accounting laws
The laws live once, in bookspec's Lean (`bookspec/lean/Bookspec/`, namespace
`Bookspec`), and this project requires that package (D-69). This module is
the local target `lake build` builds: importing it builds and checks every
law, and `Audit.lean` prints their axioms.
A law that changes is edited in bookspec, and this project moves its pin
(`lakefile.toml`, `lake-manifest.json`) to bookspec's new rev — the same rev
`crates/ledger-core/Cargo.toml` pins the Rust checker to. Nothing here
restates the model.
-/
-509
View File
@@ -1,509 +0,0 @@
import Wanderbooks.Closing
/-!
# Apportioning: the parts sum to the whole, for any number of parts
Mirrors `crates/ledger-core/src/kernel.rs` `apportion`: each part is
first rounded down; the shortfall `s = whole - Σ parts` (not negative) is
`u` whole units plus a fraction `f` (`s = u * unit + f`, `u` below the
number of parts, else the function refuses). A part's *rank* is how many
parts are ahead of it: a strictly larger remainder, or an equal one at an
earlier index. A part of rank below `u` gets one unit; the part of rank 0
also gets the fraction.
Kani proves INVARIANT 1 for up to three parts. Here it holds for every
number of parts: the ranks are exactly `0, …, n-1` in some order (a strict
total order ranks a finite set without gaps or ties), so exactly `u` parts
get a unit and exactly one gets the fraction.
-/
namespace Wanderbooks.Apportion
/-- Part `j` is ahead of part `i` (the closure in `kernel::apportion`). -/
def ahead (r : Nat → Int) (j i : Nat) : Bool :=
decide (r j > r i) || (decide (r j = r i) && decide (j < i))
/-- A part's rank among `n` parts: the parts ahead of it. -/
def rank (r : Nat → Int) (n i : Nat) : Nat :=
((List.range n).filter (fun j => ahead r j i)).length
/-- What part `i` gets added: a unit if its rank is below `u`, and the
fraction too if its rank is 0. -/
def add (r : Nat → Int) (n u : Nat) (unit f : Int) (i : Nat) : Int :=
(if rank r n i < u then unit else 0) + (if rank r n i = 0 then f else 0)
theorem ahead_irrefl (r : Nat → Int) (i : Nat) : ahead r i i = false := by
simp [ahead]
theorem ahead_trans (r : Nat → Int) {a b c : Nat}
(h1 : ahead r a b = true) (h2 : ahead r b c = true) : ahead r a c = true := by
simp only [ahead, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq] at *
omega
theorem ahead_total (r : Nat → Int) {a b : Nat} (h : a ≠ b) :
ahead r a b = true ∨ ahead r b a = true := by
simp only [ahead, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq]
omega
theorem ahead_asymm (r : Nat → Int) {a b : Nat} (h : ahead r a b = true) :
ahead r b a = false := by
simp only [ahead, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq] at h
simp only [ahead, Bool.or_eq_false_iff, Bool.and_eq_false_imp, decide_eq_true_eq,
decide_eq_false_iff_not]
omega
/-- A filter by a weaker predicate is no longer. -/
theorem filter_length_le {p q : Nat → Bool} : ∀ (l : List Nat),
(∀ x ∈ l, p x = true → q x = true) → (l.filter p).length ≤ (l.filter q).length
| [], _ => by simp
| a :: t, sub => by
have ih := filter_length_le t (fun x hx => sub x (List.mem_cons_of_mem a hx))
have ha := sub a (List.mem_cons_self ..)
cases hpa : p a <;> cases hqa : q a <;> simp_all <;> omega
/-- ... and strictly shorter when some element passes only the weaker one. -/
theorem filter_length_lt {p q : Nat → Bool} : ∀ (l : List Nat),
(∀ x ∈ l, p x = true → q x = true) → (∃ x ∈ l, q x = true ∧ p x = false) →
(l.filter p).length < (l.filter q).length
| [], _, w => by simp at w
| a :: t, sub, w => by
have sub' : ∀ x ∈ t, p x = true → q x = true :=
fun x hx => sub x (List.mem_cons_of_mem a hx)
have le := filter_length_le t sub'
have ha := sub a (List.mem_cons_self ..)
obtain ⟨x, hx, hq, hp⟩ := w
rcases List.mem_cons.mp hx with rfl | hx'
· simp [hq, hp]
omega
· have := filter_length_lt t sub' ⟨x, hx', hq, hp⟩
cases hpa : p a <;> cases hqa : q a <;> simp_all <;> omega
/-- Being ahead means a strictly smaller rank. -/
theorem rank_lt_of_ahead (r : Nat → Int) {n a b : Nat} (ha : a < n)
(h : ahead r a b = true) : rank r n a < rank r n b := by
unfold rank
apply filter_length_lt
· intro x _ hx
exact ahead_trans r hx h
· exact ⟨a, List.mem_range.mpr ha, h, ahead_irrefl r a⟩
/-- Distinct parts have distinct ranks. -/
theorem rank_inj (r : Nat → Int) {n a b : Nat} (ha : a < n) (hb : b < n)
(h : rank r n a = rank r n b) : a = b := by
apply Classical.byContradiction
intro hne
rcases ahead_total r hne with h1 | h1
· have := rank_lt_of_ahead r ha h1; omega
· have := rank_lt_of_ahead r hb h1; omega
/-- Every rank is below the number of parts (a part isn't ahead of itself). -/
theorem rank_lt (r : Nat → Int) {n i : Nat} (hi : i < n) : rank r n i < n := by
unfold rank
have := (List.length_filter_lt_length_iff_exists (p := fun j => ahead r j i)
(l := List.range n)).mpr ⟨i, List.mem_range.mpr hi, by simp [ahead_irrefl]⟩
simpa using this
/-- A duplicate-free list inside another is no longer. -/
theorem nodup_length_le : ∀ (l m : List Nat), l.Nodup → (∀ x ∈ l, x ∈ m) →
l.length ≤ m.length
| [], _, _, _ => by simp
| a :: t, m, hn, hs => by
rw [List.nodup_cons] at hn
have ham : a ∈ m := hs a (by simp)
have ih := nodup_length_le t (m.erase a) hn.2 (fun x hx => by
have hxa : x ≠ a := fun e => hn.1 (e ▸ hx)
exact (List.mem_erase_of_ne hxa).mpr (hs x (by simp [hx])))
rw [List.length_erase_of_mem ham] at ih
have : 0 < m.length := List.length_pos_of_mem ham
simp
omega
/-- Mapping a duplicate-free list by a function injective on it keeps it
duplicate-free. -/
theorem nodup_map_of_inj {f : Nat → Nat} : ∀ (l : List Nat), l.Nodup →
(∀ a ∈ l, ∀ b ∈ l, f a = f b → a = b) → (l.map f).Nodup
| [], _, _ => by simp
| a :: t, hn, hi => by
rw [List.nodup_cons] at hn
rw [List.map_cons, List.nodup_cons]
refine ⟨?_, nodup_map_of_inj t hn.2 (fun x hx y hy => hi x (by simp [hx]) y (by simp [hy]))⟩
intro hm
obtain ⟨b, hb, hfb⟩ := List.mem_map.mp hm
have := hi a (by simp) b (by simp [hb]) hfb.symm
exact hn.1 (this ▸ hb)
/-- The ranks of `n` parts are `0, …, n-1` in some order. -/
theorem ranks_perm (r : Nat → Int) (n : Nat) :
((List.range n).map (rank r n)).Perm (List.range n) := by
let L := (List.range n).map (rank r n)
have nd : L.Nodup := nodup_map_of_inj _ List.nodup_range (fun a ha b hb h =>
rank_inj r (List.mem_range.mp ha) (List.mem_range.mp hb) h)
have sub : ∀ x ∈ L, x < n := by
intro x hx
obtain ⟨i, hi, rfl⟩ := List.mem_map.mp hx
exact rank_lt r (List.mem_range.mp hi)
have len : L.length = n := by simp [L]
-- Pigeonhole: n distinct values below n are all of them.
have all : ∀ v < n, v ∈ L := by
intro v hv
apply Classical.byContradiction
intro hnot
have := nodup_length_le L ((List.range n).erase v) nd (fun x hx => by
have hxv : x ≠ v := fun e => hnot (e ▸ hx)
exact (List.mem_erase_of_ne hxv).mpr (List.mem_range.mpr (sub x hx)))
rw [List.length_erase_of_mem (List.mem_range.mpr hv), List.length_range] at this
omega
rw [List.perm_iff_count]
intro a
rw [List.Nodup.count nd, List.Nodup.count List.nodup_range]
by_cases ha : a < n
· simp [all a ha, List.mem_range.mpr ha]
· have h1 : a ∉ L := fun h => ha (sub a h)
simp [h1, List.mem_range, ha]
/-- Sums over permuted lists agree. -/
theorem perm_sum {l₁ l₂ : List Int} (h : l₁.Perm l₂) : l₁.sum = l₂.sum := by
induction h with
| nil => rfl
| cons x _ ih => simp [ih]
| swap x y l => simp; omega
| trans _ _ ih1 ih2 => exact ih1.trans ih2
/-- What the ranks `0, …, n-1` get, together: `u` units and the fraction. -/
theorem sum_by_rank (u : Nat) (unit f : Int) : ∀ n, 0 < n → u ≤ n →
((List.range n).map (fun v => (if v < u then unit else 0) + (if v = 0 then f else 0))).sum
= u * unit + f
| 0, h, _ => absurd h (by decide)
| 1, _, hu => by
rcases Nat.le_one_iff_eq_zero_or_eq_one.mp hu with rfl | rfl <;> simp
| n + 2, _, hu => by
rw [List.range_succ, List.map_append, List.sum_append]
by_cases h : u ≤ n + 1
· rw [sum_by_rank u unit f (n + 1) (by omega) h]
have : ¬ (n + 1 < u) := by omega
simp [this]
· have hu' : u = n + 2 := by omega
subst hu'
have ih := sum_by_rank (n + 1) unit f (n + 1) (by omega) (Nat.le_refl _)
have eq : ((List.range (n + 1)).map
(fun v => (if v < n + 2 then unit else 0) + (if v = 0 then f else 0))) =
((List.range (n + 1)).map
(fun v => (if v < n + 1 then unit else 0) + (if v = 0 then f else 0))) := by
apply List.map_congr_left
intro v hv
have := List.mem_range.mp hv
simp [show v < n + 2 by omega, show v < n + 1 by omega]
rw [eq, ih]
have e : ((n + 2 : Nat) : Int) = ((n + 1 : Nat) : Int) + 1 := by omega
simp only [List.map_cons, List.map_nil, List.sum_cons, List.sum_nil]
rw [e, Int.add_mul, Int.one_mul]
simp
omega
theorem sum_map_add (f g : Nat → Int) : ∀ (l : List Nat),
(l.map (fun i => f i + g i)).sum = (l.map f).sum + (l.map g).sum
| [] => by simp
| a :: t => by simp [sum_map_add f g t]; omega
/-- **INVARIANT 1, for any number of parts.** When the shortfall
`whole - Σ parts` is `u` units plus `f` (with `u` at most the number of
parts, as `apportion` requires before it changes anything), the parts
after apportioning sum to `whole` exactly. -/
theorem apportion_sum (parts r : Nat → Int) (n u : Nat) (unit f whole : Int)
(hn : 0 < n) (hu : u ≤ n)
(hs : whole - ((List.range n).map parts).sum = u * unit + f) :
((List.range n).map (fun i => parts i + add r n u unit f i)).sum = whole := by
rw [sum_map_add]
let g := fun v => (if v < u then unit else 0) + (if v = 0 then f else 0)
have h1 : (List.range n).map (add r n u unit f) = ((List.range n).map (rank r n)).map g := by
simp [List.map_map, add, g, Function.comp_def]
have h2 := perm_sum ((ranks_perm r n).map g)
have h3 := sum_by_rank u unit f n hn hu
show ((List.range n).map parts).sum + ((List.range n).map (add r n u unit f)).sum = whole
rw [h1, h2, h3]
omega
/-- The same, from the shortfall as `apportion` computes it: `u` whole
units by repeated subtraction (`s / unit`) and the rest (`s % unit`). -/
theorem apportion_sum_of_shortfall (parts r : Nat → Int) (n : Nat) (unit whole : Int)
(hn : 0 < n) (hunit : 0 < unit)
(hs : 0 ≤ whole - ((List.range n).map parts).sum)
(hu : ((whole - ((List.range n).map parts).sum) / unit).toNat ≤ n) :
let s := whole - ((List.range n).map parts).sum
((List.range n).map (fun i =>
parts i + add r n (s / unit).toNat unit (s % unit) i)).sum = whole := by
intro s
apply apportion_sum parts r n _ unit _ whole hn hu
have hq : 0 ≤ s / unit := Int.ediv_nonneg hs (Int.le_of_lt hunit)
rw [Int.toNat_of_nonneg hq]
have := Int.mul_ediv_add_emod s unit
rw [Int.mul_comm] at this
exact this.symm
/-! ## Bounded drift
With exact shares there is no sub-unit fraction: every amount is a whole
number of minor units (B-3) and every product `|T| × share` is exact
(`periods::allocate_cumulative` INVARIANT 4), so the remainders, scaled to
whole numbers below `m`, sum to whole units of `m`. Then a part that gets
a unit had a positive remainder, and every apportioned part is under one
unit from its exact share (rules.md B-13). -/
/-- Values in `[0, m)` that are zero wherever `p` fails sum to at most
`(m - 1)` per element where `p` holds. -/
theorem sum_le_count_mul (r : Nat → Int) (p : Nat → Bool) (m : Int) : ∀ (l : List Nat),
(∀ j ∈ l, 0 ≤ r j ∧ r j < m) → (∀ j ∈ l, p j = false → r j = 0) →
(l.map r).sum ≤ ((l.filter p).length : Int) * (m - 1)
| [], _, _ => by simp
| a :: t, hr, hz => by
have ih := sum_le_count_mul r p m t (fun j hj => hr j (List.mem_cons_of_mem a hj))
(fun j hj => hz j (List.mem_cons_of_mem a hj))
have ha := hr a (List.mem_cons_self ..)
simp only [List.map_cons, List.sum_cons, List.filter_cons]
cases hp : p a
· have := hz a (List.mem_cons_self ..) hp
simp only [Bool.false_eq_true, ↓reduceIte]
omega
· simp only [↓reduceIte, List.length_cons]
have e : (((t.filter p).length + 1 : Nat) : Int) * (m - 1)
= ((t.filter p).length : Int) * (m - 1) + (m - 1) := by
rw [Int.natCast_add, Int.add_mul, Int.natCast_one, Int.one_mul]
rw [e]
omega
/-- With remainders in `[0, m)` summing to exactly `u · m` (no sub-unit
fraction), every part ranked below `u` (so given a unit) has a positive
remainder. -/
theorem rem_pos_of_rank_lt (r : Nat → Int) (n u : Nat) (m : Int)
(hr : ∀ i < n, 0 ≤ r i ∧ r i < m)
(hs : ((List.range n).map r).sum = u * m)
{i : Nat} (hi : i < n) (hk : rank r n i < u) : 0 < r i := by
apply Classical.byContradiction
intro hneg
have hri : r i = 0 := by have := hr i hi; omega
-- Every part not ahead of `i` has a remainder no larger than `i`'s: 0.
have hz : ∀ j ∈ List.range n, ahead r j i = false → r j = 0 := by
intro j hj hna
have hj' := List.mem_range.mp hj
have hrj := hr j hj'
by_cases e : j = i
· subst e
exact hri
· rcases ahead_total r e with h | h
· rw [h] at hna
exact absurd hna (by decide)
· simp only [ahead, Bool.or_eq_true, Bool.and_eq_true, decide_eq_true_eq] at h
omega
have hle := sum_le_count_mul r (fun j => ahead r j i) m (List.range n)
(fun j hj => hr j (List.mem_range.mp hj)) hz
have hm : 0 < m := by have := hr i hi; omega
have hrank : ((List.range n).filter (fun j => ahead r j i)).length = rank r n i := rfl
rw [hrank, hs] at hle
have h1 : (rank r n i : Int) * (m - 1) ≤ ((u : Int) - 1) * (m - 1) :=
Int.mul_le_mul_of_nonneg_right (by omega) (by omega)
have h2 : ((u : Int) - 1) * (m - 1) = (u : Int) * m - u - m + 1 := by
simp only [Int.sub_mul, Int.mul_sub, Int.one_mul, Int.mul_one]
omega
omega
/-- **Bounded drift of one apportionment** (rules.md B-13): scaled by `m`,
each apportioned part (rounded down, plus its unit if any) is within one
unit of its exact share `parts i + r i / m`, when there is no sub-unit
fraction. -/
theorem apportion_drift (parts r : Nat → Int) (n u : Nat) (m : Int)
(hr : ∀ i < n, 0 ≤ r i ∧ r i < m)
(hs : ((List.range n).map r).sum = u * m) {i : Nat} (hi : i < n) :
-m < (parts i + add r n u 1 0 i) * m - (parts i * m + r i) ∧
(parts i + add r n u 1 0 i) * m - (parts i * m + r i) < m := by
have hri := hr i hi
unfold add
rw [ite_self, Int.add_zero]
by_cases hk : rank r n i < u
· have hpos := rem_pos_of_rank_lt r n u m hr hs hi hk
simp only [hk, ↓reduceIte]
rw [Int.add_mul, Int.one_mul]
omega
· simp only [hk, ↓reduceIte, Int.add_zero]
omega
/-- Σ c · f = c · Σ f. -/
theorem sum_map_mul_left (c : Int) (f : Nat → Int) : ∀ (l : List Nat),
(l.map (fun j => c * f j)).sum = c * (l.map f).sum
| [] => by simp
| a :: t => by simp [sum_map_mul_left c f t, Int.mul_add]
/-- Σ -f = -Σ f. -/
theorem sum_map_neg (f : Nat → Int) : ∀ (l : List Nat),
(l.map (fun j => -f j)).sum = -(l.map f).sum
| [] => by simp
| a :: t => by simp [sum_map_neg f t]; omega
/-- Values at most `c` sum to at most `c` per element. -/
theorem sum_le_length_mul (f : Nat → Int) (c : Int) : ∀ (l : List Nat),
(∀ j ∈ l, f j ≤ c) → (l.map f).sum ≤ (l.length : Int) * c
| [], _ => by simp
| a :: t, h => by
have ih := sum_le_length_mul f c t (fun j hj => h j (List.mem_cons_of_mem a hj))
have ha := h a (List.mem_cons_self ..)
simp only [List.map_cons, List.sum_cons, List.length_cons]
rw [Int.natCast_add, Int.add_mul, Int.natCast_one, Int.one_mul]
omega
/-- Nonnegative values have a nonnegative sum. -/
theorem sum_nonneg (f : Nat → Int) : ∀ (l : List Nat), (∀ j ∈ l, 0 ≤ f j) → 0 ≤ (l.map f).sum
| [], _ => by simp
| a :: t, h => by
have ih := sum_nonneg f t (fun j hj => h j (List.mem_cons_of_mem a hj))
have ha := h a (List.mem_cons_self ..)
simp only [List.map_cons, List.sum_cons]
omega
/-- Member `i`'s share of `x` rounded down to the unit: `x · w i / W`
(`periods::allocate_cumulative`'s floor; shares `w i / W`). -/
def floorW (w : Nat → Int) (W x : Int) (i : Nat) : Int := x * w i / W
/-- What rounding down took from it, scaled by `W`: `x · w i % W` (it
ranks the members as the Decimal remainder does). -/
def remW (w : Nat → Int) (W x : Int) (i : Nat) : Int := x * w i % W
/-- The whole units the floors fall short of `x`. -/
def shortW (w : Nat → Int) (W : Int) (n : Nat) (x : Int) : Nat :=
(x - ((List.range n).map (floorW w W x)).sum).toNat
/-- The model of `periods::allocate_cumulative`'s split of a gain (`x ≥
0`) at whole minor units: each floor, plus a unit to each of the members
with the largest remainders (ties to the earlier member). -/
def allocNat (w : Nat → Int) (W : Int) (n : Nat) (x : Int) (i : Nat) : Int :=
floorW w W x i + add (remW w W x) n (shortW w W n x) 1 0 i
/-- With the sign: a loss splits as the negation of the same gain
(`allocate_cumulative` scenario 3). -/
def allocW (w : Nat → Int) (W : Int) (n : Nat) (x : Int) (i : Nat) : Int :=
if x < 0 then -allocNat w W n (-x) i else allocNat w W n x i
/-- The floors and remainders of a gain, with shares `w i / W` summing to
one: the remainders sum to whole units, `W · (x − Σ floors)`, each in
`[0, W)`, and the floors fall short by fewer units than there are
members. -/
theorem remW_facts (w : Nat → Int) (W : Int) (n : Nat) (x : Int) (hW : 0 < W)
(hsum : ((List.range n).map w).sum = W) (hn : 0 < n) :
(∀ i < n, 0 ≤ remW w W x i ∧ remW w W x i < W) ∧
((List.range n).map (remW w W x)).sum = (shortW w W n x : Int) * W ∧
x - ((List.range n).map (floorW w W x)).sum = (shortW w W n x : Int) ∧
shortW w W n x ≤ n := by
have hW0 : W ≠ 0 := by omega
have bounds : ∀ i < n, 0 ≤ remW w W x i ∧ remW w W x i < W := fun i _ =>
⟨Int.emod_nonneg _ hW0, Int.emod_lt_of_pos _ hW⟩
-- x · w i = W · floor + rem, summed: x · W = W · Σ floors + Σ rems.
have each : ∀ i, x * w i = W * floorW w W x i + remW w W x i := fun i =>
(Int.mul_ediv_add_emod (x * w i) W).symm
have total : x * W = W * ((List.range n).map (floorW w W x)).sum
+ ((List.range n).map (remW w W x)).sum := by
have h1 : ((List.range n).map (fun j => x * w j)).sum = x * W := by
rw [sum_map_mul_left, hsum]
have h2 : ((List.range n).map (fun j => x * w j)).sum
= ((List.range n).map (fun j => W * floorW w W x j + remW w W x j)).sum := by
congr 1
apply List.map_congr_left
intro i _
exact each i
rw [← h1, h2, sum_map_add (fun j => W * floorW w W x j) (remW w W x), sum_map_mul_left]
let d := x - ((List.range n).map (floorW w W x)).sum
have hd : ((List.range n).map (remW w W x)).sum = W * d := by
show _ = W * (x - _)
rw [Int.mul_sub, Int.mul_comm W x]
omega
have rems_nonneg := sum_nonneg (remW w W x) (List.range n)
(fun j hj => (bounds j (List.mem_range.mp hj)).1)
have rems_lt := sum_le_length_mul (remW w W x) (W - 1) (List.range n)
(fun j hj => by have := (bounds j (List.mem_range.mp hj)).2; omega)
rw [List.length_range] at rems_lt
have d_nonneg : 0 ≤ d := by
apply Classical.byContradiction
intro h
have : W * d < 0 := Int.mul_neg_of_pos_of_neg hW (by omega)
omega
have d_lt : d < n := by
apply Classical.byContradiction
intro h
have h1 : (n : Int) * W ≤ d * W := Int.mul_le_mul_of_nonneg_right (by omega) (by omega)
have h2 : (n : Int) * (W - 1) = n * W - n := by
rw [Int.mul_sub, Int.mul_one]
rw [Int.mul_comm W d] at hd
omega
have hshort : (shortW w W n x : Int) = d := Int.toNat_of_nonneg d_nonneg
refine ⟨bounds, ?_, hshort.symm, ?_⟩
· rw [hshort, hd, Int.mul_comm]
· have : ((shortW w W n x : Nat) : Int) < n := by rw [hshort]; exact d_lt
omega
/-- **The split of a gain sums to it**, exactly. -/
theorem allocNat_sum (w : Nat → Int) (W : Int) (n : Nat) (x : Int) (hW : 0 < W)
(hsum : ((List.range n).map w).sum = W) (hn : 0 < n) :
((List.range n).map (allocNat w W n x)).sum = x := by
obtain ⟨_, _, hx, hu⟩ := remW_facts w W n x hW hsum hn
apply apportion_sum (floorW w W x) (remW w W x) n (shortW w W n x) 1 0 x hn hu
rw [hx]
omega
/-- **`allocate_cumulative`'s split sums to the amount**, gain or loss. -/
theorem allocW_sum (w : Nat → Int) (W : Int) (n : Nat) (x : Int) (hW : 0 < W)
(hsum : ((List.range n).map w).sum = W) (hn : 0 < n) :
((List.range n).map (allocW w W n x)).sum = x := by
unfold allocW
by_cases hx : x < 0
· simp only [hx, ↓reduceIte]
rw [sum_map_neg, allocNat_sum w W n (-x) hW hsum hn]
omega
· simp only [hx, ↓reduceIte]
exact allocNat_sum w W n x hW hsum hn
/-- **Bounded drift** (rules.md B-13): each member's part of an amount is
under one minor unit from their exact share, `|allocW x i · W − x · w i| <
W`, gain or loss. -/
theorem allocW_drift (w : Nat → Int) (W : Int) (n : Nat) (x : Int) (hW : 0 < W)
(hsum : ((List.range n).map w).sum = W) (hn : 0 < n) {i : Nat} (hi : i < n) :
-W < allocW w W n x i * W - x * w i ∧ allocW w W n x i * W - x * w i < W := by
have gain : ∀ y, 0 ≤ y →
-W < allocNat w W n y i * W - y * w i ∧ allocNat w W n y i * W - y * w i < W := by
intro y _
obtain ⟨hr, hs, _, _⟩ := remW_facts w W n y hW hsum hn
have h := apportion_drift (floorW w W y) (remW w W y) n (shortW w W n y) W hr hs hi
have e : floorW w W y i * W + remW w W y i = y * w i := by
rw [Int.mul_comm]
exact Int.mul_ediv_add_emod (y * w i) W
rw [e] at h
exact h
unfold allocW
by_cases hx : x < 0
· simp only [hx, ↓reduceIte]
have h := gain (-x) (by omega)
simp only [Int.neg_mul] at h ⊢
omega
· simp only [hx, ↓reduceIte]
exact gain x (by omega)
/-- **No member's running total is ever a minor unit from their exact
share**, after a cumulative close, whatever earlier closes gave them
(rules.md B-13; D-10): `Closing.trueUp` with `allocate_cumulative`'s
split (Kani `cumulative_close_never_drifts_a_unit_at_*` check the code on
small amounts). -/
theorem allocW_cumulative_drift (w : Nat → Int) (W : Int) (n : Nat) (hW : 0 < W)
(hsum : ((List.range n).map w).sum = W) (hn : 0 < n) (closed net : Int)
(given : Nat → Int) {i : Nat} (hi : i < n) :
-W < (given i + trueUp (allocW w W n) closed net given i) * W - (closed + net) * w i ∧
(given i + trueUp (allocW w W n) closed net given i) * W - (closed + net) * w i < W := by
rw [trueUp_running]
exact allocW_drift w W n (closed + net) hW hsum hn hi
/-- **A cumulative close hands out exactly its net** with
`allocate_cumulative`'s split, gain or loss, whatever the earlier closes
gave, as long as they gave what they closed. -/
theorem allocW_cumulative_total (w : Nat → Int) (W : Int) (n : Nat) (hW : 0 < W)
(hsum : ((List.range n).map w).sum = W) (hn : 0 < n) (closed net : Int)
(given : Nat → Int) (hg : ((List.range n).map given).sum = closed) :
((List.range n).map (trueUp (allocW w W n) closed net given)).sum = net :=
trueUp_total (allocW w W n) (List.range n) (fun x => allocW_sum w W n x hW hsum hn)
closed net given hg
end Wanderbooks.Apportion
-165
View File
@@ -1,165 +0,0 @@
/-!
# Lines, sides, and nets
The vocabulary of double entry. Money is `Int`: an exact count of the
smallest unit the books use. Any finite set of exact decimals (what the
engine stores) scales to integers without loss, and every law here is a
law of addition, so `Int` is a faithful model.
Mirrors `crates/ledger-core/src/kernel.rs` (`flip`, `signed`, `net`,
`totals`) and `account.rs` (`Side`, `AccountType`, `normal_side`).
-/
namespace Wanderbooks
/-- Debit or credit. -/
inductive Side where
| debit
| credit
deriving DecidableEq, Repr
/-- The other side (`kernel::flip`). -/
def Side.flip : Side → Side
| .debit => .credit
| .credit => .debit
@[simp] theorem Side.flip_flip (s : Side) : s.flip.flip = s := by
cases s <;> rfl
theorem Side.flip_ne (s : Side) : s.flip ≠ s := by
cases s <;> simp [Side.flip]
/-- The five account types. -/
inductive AccountType where
| asset
| liability
| equity
| revenue
| expense
deriving DecidableEq, Repr
/-- The side that increases an account (`AccountType::normal_side`). -/
def AccountType.normal : AccountType → Side
| .asset | .expense => .debit
| .liability | .equity | .revenue => .credit
/-- A line's signed amount: `+a` for a debit, `-a` for a credit
(`kernel::signed`). -/
def signed : Side → Int → Int
| .debit, a => a
| .credit, a => -a
@[simp] theorem signed_debit (a : Int) : signed .debit a = a := rfl
@[simp] theorem signed_credit (a : Int) : signed .credit a = -a := rfl
theorem signed_flip (s : Side) (a : Int) : signed s.flip a = -signed s a := by
cases s <;> simp [Side.flip]
/-- One journal line. -/
structure Line where
account : Nat
side : Side
amount : Int
deriving DecidableEq, Repr
/-- A line's signed amount. -/
def Line.signed (l : Line) : Int := Wanderbooks.signed l.side l.amount
/-- The net of some lines: debits minus credits (`kernel::net`). -/
def net : List Line → Int
| [] => 0
| l :: ls => l.signed + net ls
/-- Total debits. -/
def debits : List Line → Int
| [] => 0
| l :: ls => (if l.side = .debit then l.amount else 0) + debits ls
/-- Total credits. -/
def credits : List Line → Int
| [] => 0
| l :: ls => (if l.side = .credit then l.amount else 0) + credits ls
@[simp] theorem net_nil : net [] = 0 := rfl
@[simp] theorem net_cons (l : Line) (ls : List Line) : net (l :: ls) = l.signed + net ls := rfl
theorem net_append (xs ys : List Line) : net (xs ++ ys) = net xs + net ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, net_cons, ih]; omega
/-- The net is debits minus credits. -/
theorem net_eq_debits_sub_credits (ls : List Line) : net ls = debits ls - credits ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
obtain ⟨a, s, m⟩ := l
cases s <;> simp [net, debits, credits, Line.signed, signed, ih] <;> omega
/-- A sum over a list of account codes. -/
def sumOver (f : Nat → Int) : List Nat → Int
| [] => 0
| a :: as => f a + sumOver f as
@[simp] theorem sumOver_nil (f : Nat → Int) : sumOver f [] = 0 := rfl
@[simp] theorem sumOver_cons (f : Nat → Int) (a : Nat) (as : List Nat) :
sumOver f (a :: as) = f a + sumOver f as := rfl
theorem sumOver_add (f g : Nat → Int) (as : List Nat) :
sumOver (fun a => f a + g a) as = sumOver f as + sumOver g as := by
induction as with
| nil => rfl
| cons a as ih => simp only [sumOver_cons, ih]; omega
theorem sumOver_neg (f : Nat → Int) (as : List Nat) :
sumOver (fun a => -f a) as = -sumOver f as := by
induction as with
| nil => rfl
| cons a as ih => simp only [sumOver_cons, ih]; omega
theorem sumOver_zero (as : List Nat) : sumOver (fun _ => 0) as = 0 := by
induction as with
| nil => rfl
| cons a as ih => simp [ih]
theorem sumOver_congr (f g : Nat → Int) (as : List Nat) (h : ∀ a ∈ as, f a = g a) :
sumOver f as = sumOver g as := by
induction as with
| nil => rfl
| cons a as ih =>
simp only [sumOver_cons]
rw [h a (by simp), ih (fun b hb => h b (by simp [hb]))]
/-- No code repeats (a chart's codes are unique). -/
def Distinct : List Nat → Prop
| [] => True
| a :: as => a ∉ as ∧ Distinct as
/-- Summing an indicator over codes that do not include `k` gives zero. -/
theorem sumOver_indicator_absent (k : Nat) (x : Int) (as : List Nat) (h : k ∉ as) :
sumOver (fun a => if k = a then x else 0) as = 0 := by
induction as with
| nil => rfl
| cons a as ih =>
have hka : k ≠ a := fun e => h (e ▸ List.mem_cons_self ..)
have hk : k ∉ as := fun hm => h (List.mem_cons_of_mem _ hm)
simp [hka, ih hk]
/-- Summing an indicator over distinct codes that include `k` picks out
exactly one term. -/
theorem sumOver_indicator (k : Nat) (x : Int) (as : List Nat) (hd : Distinct as)
(hk : k ∈ as) : sumOver (fun a => if k = a then x else 0) as = x := by
induction as with
| nil => simp at hk
| cons a as ih =>
obtain ⟨ha, hd⟩ := hd
by_cases e : k = a
· subst e
simp [sumOver_indicator_absent k x as ha]
· have : k ∈ as := by
cases hk with
| head => exact absurd rfl e
| tail _ h => exact h
simp [e, ih hd this]
end Wanderbooks
-451
View File
@@ -1,451 +0,0 @@
import Wanderbooks.Statements
/-!
# Closing a period, and splitting the net
Mirrors `kernel::closing_line`, `kernel::credit_line`, `kernel::plug_last`,
`periods::allocate`, and `Ledger::close_period_to` (income closing, net to
one equity account or split among members).
-/
namespace Wanderbooks
/-- The line that zeroes an account with movement `m`: the opposite side,
same amount; nothing for zero (`kernel::closing_line`). It is also the
line that credits `m` to an account (`kernel::credit_line`). -/
def closingLine (a : Nat) (m : Int) : List Line :=
if 0 < m then [⟨a, .credit, m⟩] else if m < 0 then [⟨a, .debit, -m⟩] else []
theorem net_closingLine (a : Nat) (m : Int) : net (closingLine a m) = -m := by
unfold closingLine
split
· simp [Line.signed]
· split <;> simp [Line.signed] <;> omega
theorem movement_closingLine (b a : Nat) (m : Int) :
movement b (closingLine a m) = if b = a then -m else 0 := by
by_cases e : b = a
· subst e
rcases (by omega : 0 < m ∨ m < 0 ∨ m = 0) with h | h | h
· simp [closingLine, h, Line.signed]
· have : ¬ 0 < m := by omega
simp [closingLine, h, this, Line.signed]
· simp [closingLine, h]
· have e' : ¬ a = b := fun x => e x.symm
unfold closingLine
split <;> (try split) <;> simp [e']
theorem closingLine_pos (a : Nat) (m : Int) : ∀ l ∈ closingLine a m, 0 < l.amount := by
unfold closingLine
split
· simp; omega
· split
· simp; omega
· simp
theorem closingLine_account (a : Nat) (m : Int) : ∀ l ∈ closingLine a m, l.account = a := by
unfold closingLine
split
· simp
· split <;> simp
theorem closingLine_eq_nil (a : Nat) (m : Int) : closingLine a m = [] ↔ m = 0 := by
unfold closingLine
split
· simp; omega
· split
· simp; omega
· simp; omega
/-- The closing lines for some accounts: one per account with a nonzero
movement. -/
def closings (as : List Nat) (ls : List Line) : List Line :=
match as with
| [] => []
| a :: as => closingLine a (movement a ls) ++ closings as ls
theorem net_closings (as : List Nat) (ls : List Line) :
net (closings as ls) = -sumOver (fun a => movement a ls) as := by
induction as with
| nil => rfl
| cons a as ih => simp only [closings, net_append, net_closingLine, ih, sumOver_cons]; omega
theorem movement_closings (b : Nat) (as : List Nat) (ls : List Line) (hd : Distinct as) :
movement b (closings as ls) = if b ∈ as then -movement b ls else 0 := by
induction as with
| nil => simp [closings]
| cons a as ih =>
obtain ⟨ha, hd⟩ := hd
simp only [closings, movement_append, movement_closingLine, ih hd]
by_cases e : b = a
· subst e; simp [ha]
· simp [e]
theorem closings_pos (as : List Nat) (ls : List Line) : ∀ l ∈ closings as ls, 0 < l.amount := by
induction as with
| nil => simp [closings]
| cons a as ih =>
intro l hl
simp only [closings, List.mem_append] at hl
cases hl with
| inl h => exact closingLine_pos _ _ l h
| inr h => exact ih l h
theorem closings_account (as : List Nat) (ls : List Line) : ∀ l ∈ closings as ls, l.account ∈ as := by
induction as with
| nil => simp [closings]
| cons a as ih =>
intro l hl
simp only [closings, List.mem_append] at hl
cases hl with
| inl h => rw [closingLine_account _ _ l h]; simp
| inr h => exact List.mem_cons_of_mem _ (ih l h)
/-- Nothing to close means every closed account was already at zero. -/
theorem closings_eq_nil (as : List Nat) (ls : List Line) (h : closings as ls = []) :
∀ a ∈ as, movement a ls = 0 := by
induction as with
| nil => simp
| cons a as ih =>
simp only [closings, List.append_eq_nil_iff] at h
intro b hb
cases hb with
| head => exact (closingLine_eq_nil _ _).1 h.1
| tail _ hb => exact ih h.2 b hb
/-! ## The net to equity -/
/-- The sum of some amounts. -/
def total : List Int → Int
| [] => 0
| x :: xs => x + total xs
/-- Lines crediting each target its part (`kernel::credit_line` per
member). -/
def equityLines : List (Nat × Int) → List Line
| [] => []
| (t, c) :: ts => closingLine t c ++ equityLines ts
theorem net_equityLines (ts : List (Nat × Int)) :
net (equityLines ts) = -total (ts.map Prod.snd) := by
induction ts with
| nil => rfl
| cons x ts ih =>
obtain ⟨t, c⟩ := x
simp only [equityLines, net_append, net_closingLine, ih, List.map_cons, total]; omega
theorem movement_equityLines_absent (b : Nat) (ts : List (Nat × Int))
(h : ∀ x ∈ ts, x.1 ≠ b) : movement b (equityLines ts) = 0 := by
induction ts with
| nil => rfl
| cons x ts ih =>
obtain ⟨t, c⟩ := x
have ht : b ≠ t := fun e => h (t, c) (by simp) e.symm
simp only [equityLines, movement_append, movement_closingLine, ht, ite_false,
ih (fun y hy => h y (List.mem_cons_of_mem _ hy))]
rfl
theorem equityLines_pos (ts : List (Nat × Int)) : ∀ l ∈ equityLines ts, 0 < l.amount := by
induction ts with
| nil => simp [equityLines]
| cons x ts ih =>
obtain ⟨t, c⟩ := x
intro l hl
simp only [equityLines, List.mem_append] at hl
cases hl with
| inl h => exact closingLine_pos _ _ l h
| inr h => exact ih l h
theorem equityLines_account (ts : List (Nat × Int)) :
∀ l ∈ equityLines ts, ∃ x ∈ ts, l.account = x.1 := by
induction ts with
| nil => simp [equityLines]
| cons x ts ih =>
obtain ⟨t, c⟩ := x
intro l hl
simp only [equityLines, List.mem_append] at hl
cases hl with
| inl h => exact ⟨(t, c), by simp, closingLine_account _ _ l h⟩
| inr h =>
obtain ⟨y, hy, e⟩ := ih l h
exact ⟨y, List.mem_cons_of_mem _ hy, e⟩
theorem equityLines_eq_nil (ts : List (Nat × Int)) (h : equityLines ts = []) :
total (ts.map Prod.snd) = 0 := by
induction ts with
| nil => rfl
| cons x ts ih =>
obtain ⟨t, c⟩ := x
simp only [equityLines, List.append_eq_nil_iff] at h
simp only [List.map_cons, total, (closingLine_eq_nil _ _).1 h.1, ih h.2]; rfl
/-- The closing entry: zero the closed accounts, credit the net to the
targets. -/
def closingEntry (as : List Nat) (ts : List (Nat × Int)) (ls : List Line) : List Line :=
closings as ls ++ equityLines ts
/-- **A closing entry balances** when the targets' parts sum to the net
of the closing lines (the net income), however that net was split. -/
theorem closingEntry_net (as : List Nat) (ts : List (Nat × Int)) (ls : List Line)
(hsum : total (ts.map Prod.snd) = net (closings as ls)) :
net (closingEntry as ts ls) = 0 := by
rw [closingEntry, net_append, net_equityLines, hsum]; omega
/-- **A closing entry zeroes every account it closes.** -/
theorem closingEntry_zeroes (as : List Nat) (ts : List (Nat × Int)) (ls : List Line)
(hd : Distinct as) (b : Nat) (hb : b ∈ as) (ht : ∀ x ∈ ts, x.1 ≠ b) :
movement b (ls ++ closingEntry as ts ls) = 0 := by
rw [movement_append, closingEntry, movement_append, movement_closings b as ls hd,
movement_equityLines_absent b ts ht]
simp only [hb, ite_true]; omega
/-- **A non-empty closing entry is acceptable**: two or more lines, every
amount positive, debits equal to credits. -/
theorem closingEntry_accepted (as : List Nat) (ts : List (Nat × Int)) (ls : List Line)
(hsum : total (ts.map Prod.snd) = net (closings as ls)) (hne : closings as ls ≠ []) :
Accepted (closingEntry as ts ls) := by
refine ⟨?_, ?_, ?_⟩
· rw [closingEntry, List.length_append]
match hc : closings as ls with
| [] => exact absurd hc hne
| [l] =>
have hl : 0 < l.amount := closings_pos as ls l (by rw [hc]; simp)
have hnet : net (closings as ls) ≠ 0 := by
rw [hc]; obtain ⟨a, s, m⟩ := l
cases s <;> simp [Line.signed] at hl ⊢ <;> omega
have : equityLines ts ≠ [] := fun h => hnet (hsum ▸ equityLines_eq_nil ts h)
have : 1 ≤ (equityLines ts).length := by
cases h : equityLines ts with
| nil => exact absurd h this
| cons _ _ => simp
simp; omega
| _ :: _ :: _ => simp; omega
· intro l hl
simp only [closingEntry, List.mem_append] at hl
cases hl with
| inl h => exact closings_pos as ls l h
| inr h => exact equityLines_pos ts l h
· have := closingEntry_net as ts ls hsum
rw [net_eq_debits_sub_credits] at this; omega
/-! ## Net income -/
/-- The chart's revenue and expense codes: what a close zeroes. -/
def nominalCodes : Chart → List Nat
| [] => []
| (a, t) :: c => if t = .revenue ∨ t = .expense then a :: nominalCodes c else nominalCodes c
theorem nominalCodes_sub (c : Chart) : ∀ a ∈ nominalCodes c, a ∈ codes c := by
induction c with
| nil => simp [nominalCodes]
| cons x c ih =>
obtain ⟨a, t⟩ := x
intro b hb
simp only [nominalCodes] at hb
split at hb
· cases hb with
| head => simp
| tail _ h => exact List.mem_cons_of_mem _ (ih b h)
· exact List.mem_cons_of_mem _ (ih b hb)
theorem nominalCodes_distinct (c : Chart) (hd : Distinct (codes c)) : Distinct (nominalCodes c) := by
induction c with
| nil => trivial
| cons x c ih =>
obtain ⟨a, t⟩ := x
obtain ⟨ha, hd⟩ := hd
simp only [nominalCodes]
split
· exact ⟨fun h => ha (nominalCodes_sub c a h), ih hd⟩
· exact ih hd
/-- **The net a close credits to equity is the period's net income**:
revenue balances minus expense balances. -/
theorem net_closings_is_net_income (c : Chart) (ls : List Line) :
net (closings (nominalCodes c) ls) = typeTotal .revenue ls c - typeTotal .expense ls c := by
rw [net_closings]
induction c with
| nil => rfl
| cons x c ih =>
obtain ⟨a, t⟩ := x
cases t <;> simp [nominalCodes, typeTotal, balance, AccountType.normal, signed] at ih ⊢ <;> omega
/-! ## Splitting among members -/
/-- Make rounded parts sum to the whole: the last becomes the whole minus
the others (`kernel::plug_last`). -/
def plugLast (whole : Int) : List Int → List Int
| [] => []
| [_] => [whole]
| p :: q :: rest => p :: plugLast (whole - p) (q :: rest)
/-- **An allocation's parts sum to the whole, exactly**, however the
other parts were rounded. -/
theorem plugLast_total (whole : Int) (ps : List Int) (h : ps ≠ []) :
total (plugLast whole ps) = whole := by
induction ps generalizing whole with
| nil => exact absurd rfl h
| cons p rest ih =>
match rest, ih with
| [], _ => show total [whole] = whole; simp [total]
| q :: rest, ih =>
simp only [plugLast, total]
have := ih (whole - p) (by simp)
omega
theorem plugLast_length (whole : Int) (ps : List Int) : (plugLast whole ps).length = ps.length := by
induction ps generalizing whole with
| nil => rfl
| cons p rest ih =>
match rest, ih with
| [], _ => rfl
| q :: rest, ih => simp only [plugLast, List.length_cons]; rw [ih]; rfl
/-- Only the last part changes. -/
theorem plugLast_keeps (whole : Int) (ps : List Int) :
(plugLast whole ps).dropLast = ps.dropLast := by
induction ps generalizing whole with
| nil => rfl
| cons p rest ih =>
match rest, ih with
| [], _ => rfl
| q :: rest, ih =>
have hne : plugLast (whole - p) (q :: rest) ≠ [] := by
intro h
have := plugLast_length (whole - p) (q :: rest)
rw [h] at this; simp at this
rw [show plugLast whole (p :: q :: rest) = p :: plugLast (whole - p) (q :: rest) from rfl,
List.dropLast_cons_of_ne_nil hne, ih, List.dropLast_cons_cons]
/-! ## Cumulative member closes
A run of members closes under the run rule of 2026-10-13 to P3
(`CloseTo::MembersRun`, journaled `"cumulative"`; rules.md B-13) gives each
member, at each close, their allocation of the run's total so far minus
their allocation of the total before it. `alloc` is any allocation of an
amount to members (member `i` gets `alloc x i`), such as
`periods::allocate`. -/
/-- What one close gives member `i`: `before` is the run's total before
it, `net` what it closes. -/
def closePart (alloc : Int → Nat → Int) (before net : Int) (i : Nat) : Int :=
alloc (before + net) i - alloc before i
/-- What a run of closes with these nets, starting after `before`, gives
member `i` in all. -/
def runPart (alloc : Int → Nat → Int) : Int → List Int → Nat → Int
| _, [], _ => 0
| before, net :: rest, i => closePart alloc before net i + runPart alloc (before + net) rest i
/-- **A run telescopes**: member `i`'s total from a run is their allocation
of everything the run closed, less their allocation of where it started.
From an empty start (`alloc 0 = 0`), it is exactly their allocation of
the run's total, so its rounding is one allocation's rounding, never a
sum of them. -/
theorem runPart_telescopes (alloc : Int → Nat → Int) (before : Int) (nets : List Int) (i : Nat) :
runPart alloc before nets i = alloc (before + nets.sum) i - alloc before i := by
induction nets generalizing before with
| nil => simp [runPart]
| cons n rest ih =>
simp only [runPart, closePart, ih, List.sum_cons]
rw [show before + n + rest.sum = before + (n + rest.sum) by omega]
omega
/-- A sum of differences is the difference of the sums. -/
theorem sum_map_sub (f g : Nat → Int) (ms : List Nat) :
(ms.map (fun i => f i - g i)).sum = (ms.map f).sum - (ms.map g).sum := by
induction ms with
| nil => simp
| cons m ms ih => simp only [List.map_cons, List.sum_cons, ih]; omega
/-- **Each close hands out exactly its net** when every allocation sums
to its amount (`periods::allocate` does: `kernel::apportion`). -/
theorem closePart_total (alloc : Int → Nat → Int) (members : List Nat)
(sums : ∀ x, (members.map (alloc x)).sum = x) (before net : Int) :
(members.map (closePart alloc before net)).sum = net := by
have h := sum_map_sub (alloc (before + net)) (alloc before) members
unfold closePart
rw [h, sums, sums]
omega
/-! ## Members closes counted from a count's start (P3)
The rule since P3 (`CloseTo::Members`, rules.md B-13; D-10): a close gives
member `i` their allocation of everything the count has closed (`closed`
before it, plus its `net`), less what the count's earlier closes gave them
(`given i`), whatever rule those closes were made under
(`periods::allocate_cumulative`, `kernel::apportion_cumulative`). The run
rule of 2026-10-13 (`CloseTo::MembersRun`, `closePart`) is the special case
where the earlier closes gave exactly the allocation. -/
/-- What a cumulative close gives member `i`. -/
def trueUp (alloc : Int → Nat → Int) (closed net : Int) (given : Nat → Int) (i : Nat) : Int :=
alloc (closed + net) i - given i
/-- **A cumulative close hands out exactly its net**, whatever rule the
earlier closes used, as long as they handed out what they closed. -/
theorem trueUp_total (alloc : Int → Nat → Int) (members : List Nat)
(sums : ∀ x, (members.map (alloc x)).sum = x) (closed net : Int) (given : Nat → Int)
(hg : (members.map given).sum = closed) :
(members.map (trueUp alloc closed net given)).sum = net := by
have h := sum_map_sub (alloc (closed + net)) given members
unfold trueUp
rw [h, sums, hg]
omega
/-- **A running total is one allocation**: after the close, what the count
has given member `i` is their allocation of everything it closed, so its
rounding is one allocation's, never a sum of them. -/
theorem trueUp_running (alloc : Int → Nat → Int) (closed net : Int) (given : Nat → Int)
(i : Nat) : given i + trueUp alloc closed net given i = alloc (closed + net) i := by
unfold trueUp
omega
/-- The run rule is the special case `given = alloc closed`. -/
theorem closePart_eq_trueUp (alloc : Int → Nat → Int) (before net : Int) (i : Nat) :
closePart alloc before net i = trueUp alloc before net (alloc before) i := rfl
/-- **Bounded drift, for any history**: when every allocation is under one
unit from exact (scaled by `W`, the shares being `w i / W`), so is every
member's running total after a cumulative close, whatever the earlier
closes gave (`Apportion.allocW_drift` supplies the hypothesis). -/
theorem cumulative_drift (alloc : Int → Nat → Int) (w : Nat → Int) (W : Int)
(hd : ∀ x i, -W < alloc x i * W - x * w i ∧ alloc x i * W - x * w i < W)
(closed net : Int) (given : Nat → Int) (i : Nat) :
-W < (given i + trueUp alloc closed net given i) * W - (closed + net) * w i ∧
(given i + trueUp alloc closed net given i) * W - (closed + net) * w i < W := by
rw [trueUp_running]
exact hd _ _
/-- The statement of members' equity's share of the earnings `U` not yet
closed, as of a day: what the count's next close would give of them, its
allocation of `closed + U` less its allocation of `closed` (D-38; P3 review
R-1: never the true-up a close hasn't posted). -/
def unclosedShare (alloc : Int → Nat → Int) (closed U : Int) (i : Nat) : Int :=
alloc (closed + U) i - alloc closed i
/-- **Closing a period moves a member's capital on a day by exactly the
true-up the close posts** (D-38, R-1): before, their capital `cap` plus
their share of the unclosed `U`; after closing `net` of it, `cap` plus the
close's part plus their share of the rest. The difference is
`alloc closed i - given i`. -/
theorem statement_after_close (alloc : Int → Nat → Int) (cap closed net U : Int)
(given : Nat → Int) (i : Nat) :
cap + trueUp alloc closed net given i + unclosedShare alloc (closed + net) (U - net) i
= cap + unclosedShare alloc closed U i + (alloc closed i - given i) := by
unfold trueUp unclosedShare
rw [show closed + net + (U - net) = closed + U by omega]
omega
/-- **A member's capital on a day never moves when its period is closed**
(D-38), once the count's closes gave what the cumulative rule gives
(`given = alloc closed`: every count the rule began, and every count after
its first close that posts). -/
theorem statement_unmoved_by_close (alloc : Int → Nat → Int) (cap closed net U : Int)
(i : Nat) :
cap + trueUp alloc closed net (alloc closed) i + unclosedShare alloc (closed + net) (U - net) i
= cap + unclosedShare alloc closed U i := by
rw [statement_after_close]
omega
end Wanderbooks
-330
View File
@@ -1,330 +0,0 @@
import Wanderbooks.Prorate
/-!
# A category's deductible amount: the shares added exactly, rounded once,
half away from zero, at any size
Mirrors `crates/ledger-core/src/kernel.rs` `deductible_amount` and
`Amount::checked_div_round_cent` (rules.md B-32, B-21; owner decision D-67).
The kernel adds each account's exact share `book × percent ÷ 100`, then
divides by 100 once and rounds the total to the cent, half away from zero.
On `Decimal` it does this on integer mantissas over powers of ten: a book
is `b × 10^-p`, a percent `q × 10^-s`, so a share is `b·q ÷ 10^(p+s)` of a
percent-point, and the category is `(Σ bᵢ·qᵢ) ÷ (100 · 10^(p+s))` dollars,
found by exact integer division with the remainder deciding the tie, never
a float and never a per-share rounding.
The model is that, with the power of ten left to be any positive `D`:
books and percents are integers (`Share`), `D` the common denominator they
share (`10^(p+s)` above), and the exact category in dollars is `N ÷ (100·D)`
with `N = Σ bᵢ·qᵢ` (`sumProd`). In cents that is `N ÷ D`: the `÷ 100` of the
percent and the `× 100` of dollars-to-cents cancel, so the one rounding is
`roundHA N D`, the integer nearest `N / D`, ties away from zero. It is
built on `Prorate.roundUnit` (the Nat rounding of the proration kernel, with
the cent as the unit), applied to the magnitude and signed after, which is
what the kernel's `a_mag`, `b_mag` and `negative` do.
This proves the law, not the Rust code. Kani proves the code on `i64` for up
to three accounts and bounded books (`deductible_amount_rounds_once`,
`deductible_amount_refuses_overflow`); `tests/kernel_bridge.rs` and the exact
reference property carry it to `Decimal`; here the law holds for any number
of accounts and any sizes: within half a cent of the exact sum (`near`), a
tie to the cent farther from zero (`tie_away_pos`, `tie_away_neg`), never the
opposite sign (`sign`), odd (`neg`), a function of the exact sum alone
(`of_sum`, `of_perm`, `append`: rounded once, on the sum, and so not the
sum of the rounded shares, which `per_account_differs` shows can differ), and independent of how many decimal places
the books and percents carry (`scale_books`, `scale_percents`). Overflow
(the kernel returns None) is outside the model; integers do not overflow.
-/
namespace Wanderbooks.Deductible
open Wanderbooks.Prorate (roundUnit roundUnit_near roundUnit_scale)
/-- One account's share: its book and its deductible percent, as integers
over the category's common denominator. -/
abbrev Share := Int × Int
/-- The exact sum `Σ bookᵢ × percentᵢ` over the common denominator. -/
def sumProd : List Share → Int
| [] => 0
| (b, q) :: t => b * q + sumProd t
/-- `n / d` to the nearest whole cent, half away from zero: the magnitude
rounded half up (`Prorate.roundUnit`, unit one), then signed. -/
def roundHA (n : Int) (d : Nat) : Int :=
if 0 ≤ n then (roundUnit n.natAbs d 1 : Int) else -(roundUnit n.natAbs d 1 : Int)
/-- The category's deductible amount, in cents: the exact sum `N`, over the
common denominator `D`, rounded once. -/
def deductible (D : Nat) (l : List Share) : Int := roundHA (sumProd l) D
/-! ## The rounding -/
theorem roundUnit_zero (d : Nat) (hd : 0 < d) : roundUnit 0 d 1 = 0 := by
unfold roundUnit
have : 2 * 0 + d * 1 < 2 * d * 1 := by omega
rw [Nat.div_eq_of_lt this, Nat.mul_zero]
/-- Natural-number rounding, in integers: `2·d·r` within `d` of `2·m`. -/
private theorem unit_near_int (m d : Nat) (hd : 0 < d) :
-(d : Int) ≤ 2 * (((d * roundUnit m d 1 : Nat) : Int) - m) ∧
2 * (((d * roundUnit m d 1 : Nat) : Int) - m) ≤ d := by
obtain ⟨h1, h2⟩ := roundUnit_near m d 1 hd Nat.one_pos
have e : 2 * d * roundUnit m d 1 = 2 * (d * roundUnit m d 1) := Nat.mul_assoc 2 d _
rw [e] at h1 h2
generalize d * roundUnit m d 1 = P at h1 h2 ⊢
omega
/-- **Near**: the result is within half a cent of the exact quotient, at any
size: `|2·(d·c − n)| ≤ d`, written without division. (Any other whole cent
is at least as far, so it is a nearest one.) -/
theorem roundHA_near (n : Int) (d : Nat) (hd : 0 < d) :
-(d : Int) ≤ 2 * ((d : Int) * roundHA n d - n) ∧
2 * ((d : Int) * roundHA n d - n) ≤ d := by
have h := unit_near_int n.natAbs d hd
have e : (d : Int) * (roundUnit n.natAbs d 1 : Nat) = ((d * roundUnit n.natAbs d 1 : Nat) : Int) := by
push_cast; rfl
unfold roundHA
generalize d * roundUnit n.natAbs d 1 = P at h e
split
· rename_i hn
have : (n.natAbs : Int) = n := Int.natAbs_of_nonneg hn
rw [e]; omega
· rename_i hn
have : (n.natAbs : Int) = -n := by omega
rw [Int.mul_neg, e]; omega
/-- **Odd symmetry**: rounding half away from zero treats the two signs
alike, so negating the amount negates the result. -/
theorem roundHA_neg (n : Int) (d : Nat) (hd : 0 < d) : roundHA (-n) d = -roundHA n d := by
unfold roundHA
rw [Int.natAbs_neg]
by_cases h0 : n = 0
· subst h0
simp [roundUnit_zero d hd]
· by_cases h : 0 ≤ n
· have h' : ¬ 0 ≤ -n := by omega
simp only [h, h', ↓reduceIte]
· have h' : 0 ≤ -n := by omega
simp only [h, h', ↓reduceIte, Int.neg_neg]
/-- **Sign**: the result is never of the opposite sign to the exact
quotient, and is zero when it is zero. (A small positive amount may round
to zero; none ever rounds across it. An `Int` has no negative zero.) -/
theorem roundHA_sign (n : Int) (d : Nat) (hd : 0 < d) :
(0 ≤ n → 0 ≤ roundHA n d) ∧ (n ≤ 0 → roundHA n d ≤ 0) ∧ (n = 0 → roundHA n d = 0) := by
refine ⟨?_, ?_, ?_⟩
· intro h
unfold roundHA
simp [h]
· intro h
unfold roundHA
by_cases h0 : n = 0
· subst h0; simp [roundUnit_zero d hd]
· have : ¬ 0 ≤ n := by omega
simp [this]
· intro h
subst h
unfold roundHA
simp [roundUnit_zero d hd]
/-- **A tie at exactly a half cent goes away from zero** (positive side):
`n / d = k + 1/2` rounds to `k + 1`, the cent farther from zero. -/
theorem roundHA_tie_pos (n : Int) (d k : Nat) (hd : 0 < d)
(h : 2 * n = (d : Int) * (2 * k + 1)) : roundHA n d = k + 1 ∧ n < (d : Int) * roundHA n d := by
have hQ : (d : Int) * (2 * k + 1) = ((d * (2 * k + 1) : Nat) : Int) := by push_cast; rfl
have hpos : 0 < d * (2 * k + 1) := Nat.mul_pos hd (by omega)
have hn : 0 ≤ n := by rw [hQ] at h; omega
have hm : 2 * n.natAbs = d * (2 * k + 1) := by
have : (n.natAbs : Int) = n := Int.natAbs_of_nonneg hn
rw [hQ] at h; omega
have hr : roundUnit n.natAbs d 1 = k + 1 := by
unfold roundUnit
have k1 : d * (2 * k + 1) = 2 * (d * k) + d := by
rw [Nat.mul_add, Nat.mul_left_comm, Nat.mul_one]
have k2 : 2 * d * 1 * (k + 1) = 2 * (d * k) + 2 * d := by
rw [Nat.mul_one, Nat.mul_add, Nat.mul_one, Nat.mul_assoc]
have e : 2 * n.natAbs + d * 1 = 2 * d * 1 * (k + 1) := by
rw [k2]; omega
rw [e, Nat.mul_div_cancel_left _ (by omega)]
omega
have hc : roundHA n d = k + 1 := by
unfold roundHA
simp [hn, hr]
refine ⟨hc, ?_⟩
rw [hc, Int.mul_add, Int.mul_one]
have k1 : (d : Int) * (2 * k + 1) = 2 * ((d : Int) * k) + d := by
rw [Int.mul_add, Int.mul_left_comm, Int.mul_one]
omega
/-- **A tie goes away from zero** (negative side): `n / d = −(k + 1/2)`
rounds to `−(k + 1)`. -/
theorem roundHA_tie_neg (n : Int) (d k : Nat) (hd : 0 < d)
(h : 2 * n = -((d : Int) * (2 * k + 1))) :
roundHA n d = -((k : Int) + 1) ∧ (d : Int) * roundHA n d < n := by
have h' : 2 * (-n) = (d : Int) * (2 * k + 1) := by omega
obtain ⟨h1, h2⟩ := roundHA_tie_pos (-n) d k hd h'
rw [roundHA_neg n d hd] at h1 h2
rw [Int.mul_neg] at h2
constructor <;> omega
/-- Rounding is unchanged when the amount and its denominator are scaled
together by a positive factor: the same quotient at a finer denominator
rounds the same. -/
theorem roundHA_scale (n : Int) (d c : Nat) (hc : 0 < c) :
roundHA ((c : Int) * n) (c * d) = roundHA n d := by
unfold roundHA
have hna : ((c : Int) * n).natAbs = c * n.natAbs := by
rw [Int.natAbs_mul, Int.natAbs_natCast]
have hcz : (0 : Int) < c := by omega
rw [hna, roundUnit_scale _ _ _ _ hc]
by_cases hn : 0 ≤ n
· have : 0 ≤ (c : Int) * n := Int.mul_nonneg (by omega) hn
simp only [hn, this, ↓reduceIte]
· have : ¬ 0 ≤ (c : Int) * n := by
have : (c : Int) * n < 0 := Int.mul_neg_of_pos_of_neg hcz (by omega)
omega
simp only [hn, this, ↓reduceIte]
/-! ## The category
The headline theorems: the rounding laws above, on the exact sum of a
category's shares. -/
theorem sumProd_append (l l' : List Share) : sumProd (l ++ l') = sumProd l + sumProd l' := by
induction l with
| nil => simp [sumProd]
| cons s t ih => obtain ⟨b, q⟩ := s; simp only [List.cons_append, sumProd, ih]; omega
theorem sumProd_perm {l l' : List Share} (h : l.Perm l') : sumProd l = sumProd l' := by
induction h with
| nil => rfl
| cons s _ ih => obtain ⟨b, q⟩ := s; simp only [sumProd, ih]
| swap s t l =>
obtain ⟨b, q⟩ := s; obtain ⟨b', q'⟩ := t
simp only [sumProd]; omega
| trans _ _ ih ih' => exact ih.trans ih'
theorem sumProd_neg_books (l : List Share) :
sumProd (l.map fun s => (-s.1, s.2)) = -sumProd l := by
induction l with
| nil => simp [sumProd]
| cons s t ih =>
obtain ⟨b, q⟩ := s
simp only [List.map_cons, sumProd, ih, Int.neg_mul]
omega
theorem sumProd_scale_books (c : Int) (l : List Share) :
sumProd (l.map fun s => (c * s.1, s.2)) = c * sumProd l := by
induction l with
| nil => simp [sumProd]
| cons s t ih =>
obtain ⟨b, q⟩ := s
simp only [List.map_cons, sumProd, ih, Int.mul_add, Int.mul_assoc]
theorem sumProd_scale_percents (c : Int) (l : List Share) :
sumProd (l.map fun s => (s.1, c * s.2)) = c * sumProd l := by
induction l with
| nil => simp [sumProd]
| cons s t ih =>
obtain ⟨b, q⟩ := s
simp only [List.map_cons, sumProd, ih, Int.mul_add, Int.mul_left_comm b c q]
/-- **Near**: the category's deductible amount `c` (in cents) is within
half a cent of the exact sum `N / D`, for any number of accounts and any
sizes: `|2·(D·c − N)| ≤ D`, written without division. -/
theorem near (D : Nat) (l : List Share) (hD : 0 < D) :
-(D : Int) ≤ 2 * ((D : Int) * deductible D l - sumProd l) ∧
2 * ((D : Int) * deductible D l - sumProd l) ≤ D :=
roundHA_near (sumProd l) D hD
/-- **Ties go away from zero** (positive): an exact sum of `k + 1/2` cents
gives `k + 1`, the cent farther from zero. -/
theorem tie_away_pos (D : Nat) (l : List Share) (k : Nat) (hD : 0 < D)
(h : 2 * sumProd l = (D : Int) * (2 * k + 1)) :
deductible D l = k + 1 ∧ sumProd l < (D : Int) * deductible D l :=
roundHA_tie_pos (sumProd l) D k hD h
/-- **Ties go away from zero** (negative): an exact sum of `−(k + 1/2)`
cents gives `−(k + 1)`. -/
theorem tie_away_neg (D : Nat) (l : List Share) (k : Nat) (hD : 0 < D)
(h : 2 * sumProd l = -((D : Int) * (2 * k + 1))) :
deductible D l = -((k : Int) + 1) ∧ (D : Int) * deductible D l < sumProd l :=
roundHA_tie_neg (sumProd l) D k hD h
/-- **Sign**: never the opposite sign to the exact sum, and zero when the
sum is zero. -/
theorem sign (D : Nat) (l : List Share) (hD : 0 < D) :
(0 ≤ sumProd l → 0 ≤ deductible D l) ∧ (sumProd l ≤ 0 → deductible D l ≤ 0) ∧
(sumProd l = 0 → deductible D l = 0) :=
roundHA_sign (sumProd l) D hD
/-- **Odd symmetry**: negating every book negates the result. -/
theorem neg (D : Nat) (l : List Share) (hD : 0 < D) :
deductible D (l.map fun s => (-s.1, s.2)) = -deductible D l := by
unfold deductible
rw [sumProd_neg_books, roundHA_neg _ _ hD]
/-- **Round once, (a)**: the result depends on the shares only through
their exact sum. -/
theorem of_sum (D : Nat) {l l' : List Share} (h : sumProd l = sumProd l') :
deductible D l = deductible D l' := by
unfold deductible; rw [h]
/-- Reordering the accounts does not change the result. -/
theorem of_perm (D : Nat) {l l' : List Share} (h : l.Perm l') :
deductible D l = deductible D l' :=
of_sum D (sumProd_perm h)
/-- Two groups of accounts are rounded together, on their exact sum, not
each alone. -/
theorem append (D : Nat) (l l' : List Share) :
deductible D (l ++ l') = roundHA (sumProd l + sumProd l') D := by
unfold deductible; rw [sumProd_append]
/-- An account's share split in two (its percent as the sum of two) gives
the same result. -/
theorem split_percent (D : Nat) (b q q' : Int) (t : List Share) :
deductible D ((b, q + q') :: t) = deductible D ((b, q) :: (b, q') :: t) := by
apply of_sum
simp only [sumProd, Int.mul_add]
omega
/-- **Round once, (b)**: summing per-account roundings can differ from the
category's one rounding. Two accounts of 1.01 (101 cents) at 50% (shares
over `D = 100`, the books' two places): 1.01 once, 1.02 by account. -/
theorem per_account_differs :
deductible 100 [(101, 50), (101, 50)] = 101 ∧
deductible 100 [(101, 50)] + deductible 100 [(101, 50)] = 102 ∧
deductible 100 [(101, 50), (101, 50)] ≠
deductible 100 [(101, 50)] + deductible 100 [(101, 50)] := by
decide
/-- The kernel's second scenario: 1.05 at 50% and 1.05 at 30% is 0.84
once (0.525 + 0.315 = 0.84), not 0.85 by account (0.53 + 0.32). -/
theorem per_account_differs_mixed :
deductible 100 [(105, 50), (105, 30)] = 84 ∧
deductible 100 [(105, 50)] + deductible 100 [(105, 30)] = 85 := by
decide
/-- The kernel's third scenario: 333.33 at 50% is 166.665, a tie, so
166.67. -/
theorem tie_example : deductible 100 [(33333, 50)] = 16667 := by
decide
/-- **Scaling, books**: writing the books at a finer common denominator
(each book times `c`, `D` times `c`) does not change the result: it is
independent of how many decimal places the books carry. -/
theorem scale_books (D c : Nat) (l : List Share) (hc : 0 < c) :
deductible (c * D) (l.map fun s => ((c : Int) * s.1, s.2)) = deductible D l := by
unfold deductible
rw [sumProd_scale_books, roundHA_scale _ _ _ hc]
/-- **Scaling, percents**: likewise for the percents' decimal places. -/
theorem scale_percents (D c : Nat) (l : List Share) (hc : 0 < c) :
deductible (c * D) (l.map fun s => (s.1, (c : Int) * s.2)) = deductible D l := by
unfold deductible
rw [sumProd_scale_percents, roundHA_scale _ _ _ hc]
end Wanderbooks.Deductible
-395
View File
@@ -1,395 +0,0 @@
import Wanderbooks.Entry
/-!
# Documents are the subledgers of their control accounts (rules.md B-38)
Every ledger line may carry the document it belongs to (an invoice or a
bill: `Ledger.line_docs`, `arap::DocTag`). A document's figures are the
sum of its tagged lines; a control account's balance is the sum of every
line on it. Mirrors `Ledger::doc_state` (outstanding), `control_check`,
the control guard (`check_control_lines`: every line a command posts on a
control account carries its document) and `reverse_entry` (a mirror line
copies its original's tag).
The headline, `control_agrees`: for every account and any lines at all,
the account's balance is the sum over the documents of what each carries
on it, plus its untagged ("unattached") lines. Both sides sum the same
lines, so it is an identity, not a reconciliation, and it holds through
any date, since a date is a filter on the lines. A document is one `Nat`
here: an injective coding of `DocRef` (invoices and bills in one id
space), which is all the sums need. Then, over the commands:
a document step (an invoice, a bill, a payment, a write-off, or any entry
whose control lines are tagged) never moves what is unattached; a reversal
moves each document, and what is unattached, by exactly the opposite of
the lines it mirrors (B-38 INVARIANT 3); so books built by these steps
alone have nothing unattached on a control account, ever
(`Reachable.unattached_zero`).
A write-off (S7, B-41) is a document step too: its control line carries the
document and its expense line is off the control accounts. And it never
takes a document below zero: `writeOff_within_bounds` reads the date-sum
before and after it.
-/
namespace Wanderbooks.Documents
open Wanderbooks
/-- A posted line, its day, and the document it carries (`none`: none). -/
structure TLine where
line : Line
date : Nat
doc : Option Nat
deriving DecidableEq
/-- A recorded send of an invoice (plan P4b S5, `Sent`, `invoice.sent`):
the invoice, the day, and a code for who sent it, how, to whom and the
channel's own reference. No figure reads it: a send moves no money. -/
structure Send where
doc : Nat
day : Nat
code : Nat
deriving DecidableEq
/-- A line's signed amount on account `a` (zero on another account). -/
def onAcct (a : Nat) (l : TLine) : Int := if l.line.account = a then l.line.signed else 0
/-- Account `a`'s balance over some lines (the general ledger). -/
def gl (a : Nat) : List TLine → Int
| [] => 0
| l :: ls => onAcct a l + gl a ls
/-- What document `d`'s lines on account `a` sum to (`doc_lines`). -/
def docSum (a d : Nat) : List TLine → Int
| [] => 0
| l :: ls => (if l.doc = some d then onAcct a l else 0) + docSum a d ls
/-- Account `a`'s lines that carry no document. -/
def unattached (a : Nat) : List TLine → Int
| [] => 0
| l :: ls => (if l.doc = none then onAcct a l else 0) + unattached a ls
@[simp] theorem gl_nil (a : Nat) : gl a [] = 0 := rfl
@[simp] theorem docSum_nil (a d : Nat) : docSum a d [] = 0 := rfl
@[simp] theorem unattached_nil (a : Nat) : unattached a [] = 0 := rfl
theorem gl_append (a : Nat) (xs ys : List TLine) : gl a (xs ++ ys) = gl a xs + gl a ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, gl, ih]; omega
theorem docSum_append (a d : Nat) (xs ys : List TLine) :
docSum a d (xs ++ ys) = docSum a d xs + docSum a d ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, docSum, ih]; omega
theorem unattached_append (a : Nat) (xs ys : List TLine) :
unattached a (xs ++ ys) = unattached a xs + unattached a ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, unattached, ih]; omega
/-- Every document some lines carry is among `ds`. -/
def Covers (ds : List Nat) (ls : List TLine) : Prop :=
∀ l ∈ ls, ∀ k, l.doc = some k → k ∈ ds
/-- **The control account agrees with its documents** (B-38 INVARIANT 1):
for any lines, any account, and any distinct document ids covering the
lines' tags, the balance is the documents' sum plus what is unattached. -/
theorem control_agrees (a : Nat) (ds : List Nat) (hd : Distinct ds) :
∀ ls : List TLine, Covers ds ls →
gl a ls = sumOver (fun d => docSum a d ls) ds + unattached a ls := by
intro ls
induction ls with
| nil => intro _; simp [sumOver_zero]
| cons l ls ih =>
intro hc
have hc' : Covers ds ls := fun m hm => hc m (List.mem_cons_of_mem _ hm)
simp only [gl, docSum, unattached]
rw [sumOver_add, ih hc']
cases h : l.doc with
| none =>
simp [sumOver_zero] <;> omega
| some k =>
have hk : k ∈ ds := hc l (List.mem_cons_self ..) k h
have e : sumOver (fun d => if some k = some d then onAcct a l else 0) ds
= sumOver (fun d => if k = d then onAcct a l else 0) ds :=
sumOver_congr _ _ ds (fun d _ => by simp)
simp only [e, sumOver_indicator k (onAcct a l) ds hd hk]
simp <;> omega
/-- The lines dated on or before day `D`. -/
def through (D : Nat) (ls : List TLine) : List TLine := ls.filter (fun l => decide (l.date ≤ D))
theorem through_append (D : Nat) (xs ys : List TLine) :
through D (xs ++ ys) = through D xs ++ through D ys := by
simp [through, List.filter_append]
theorem Covers.through {ds : List Nat} {ls : List TLine} (h : Covers ds ls) (D : Nat) :
Covers ds (through D ls) := fun l hl => h l (List.mem_filter.1 hl).1
/-- **The same through any day**: GL(A, D) = Σ_docs outstanding(d, D) +
unattached(A, D). -/
theorem control_agrees_through (a : Nat) (ds : List Nat) (hd : Distinct ds) (ls : List TLine)
(hc : Covers ds ls) (D : Nat) :
gl a (through D ls) = sumOver (fun d => docSum a d (through D ls)) ds
+ unattached a (through D ls) :=
control_agrees a ds hd _ (hc.through D)
/-! ## The commands -/
/-- A line mirrored by a reversal: its side flipped, its day the
reversal's, its document kept (`reverse_entry_steps` copies the tag). -/
def mirror (D : Nat) (l : TLine) : TLine := { l with line := l.line.reverse, date := D }
theorem onAcct_mirror (a D : Nat) (l : TLine) : onAcct a (mirror D l) = -onAcct a l := by
unfold onAcct mirror
by_cases h : l.line.account = a
· simp [Line.reverse, h]
have := Line.reverse_signed l.line
simp [Line.reverse] at this
exact this
· simp [Line.reverse, h]
theorem docSum_mirror (a d D : Nat) (ls : List TLine) :
docSum a d (ls.map (mirror D)) = -docSum a d ls := by
induction ls with
| nil => simp
| cons l ls ih =>
simp only [List.map_cons, docSum, ih, onAcct_mirror]
have : (mirror D l).doc = l.doc := rfl
rw [this]
by_cases h : l.doc = some d <;> simp [h] <;> omega
theorem unattached_mirror (a D : Nat) (ls : List TLine) :
unattached a (ls.map (mirror D)) = -unattached a ls := by
induction ls with
| nil => simp
| cons l ls ih =>
simp only [List.map_cons, unattached, ih, onAcct_mirror]
have : (mirror D l).doc = l.doc := rfl
rw [this]
by_cases h : l.doc = none <;> simp [h] <;> omega
/-- Every line of `ls` on a control account carries a document: what the
control guard requires of every entry a command posts. -/
def Tagged (control : List Nat) (ls : List TLine) : Prop :=
∀ l ∈ ls, l.line.account ∈ control → l.doc ≠ none
/-- A tagged list moves nothing that is unattached on a control account:
no line it adds on one carries no document. -/
theorem unattached_zero_of_tagged {control : List Nat} {e : List TLine} (h : Tagged control e)
{a : Nat} (ha : a ∈ control) : unattached a e = 0 := by
induction e with
| nil => rfl
| cons l ls ih =>
simp only [unattached]
rw [ih (fun m hm => h m (List.mem_cons_of_mem _ hm))]
by_cases hn : l.doc = none
· have hacc : l.line.account ≠ a := fun e => h l (List.mem_cons_self ..) (e ▸ ha) hn
simp [hn, onAcct, hacc]
· simp [hn]
/-- The two lines a write-off of `amount` posts on day `D` (plan P4b S7):
the document's control line credited, tagged with the document (the
receivable falls), and the same amount of bad-debt expense debited,
untagged (the deduction). -/
def writeOffLines (control expense d D : Nat) (amount : Int) : List TLine :=
[ { line := { account := control, side := .credit, amount := amount }, date := D, doc := some d },
{ line := { account := expense, side := .debit, amount := amount }, date := D, doc := none } ]
/-- The books: the control accounts (the receivables and payables roles),
every posted line in order, and the sends recorded (each on its invoice;
plan P4b S5). -/
structure Books where
control : List Nat
lines : List TLine
sends : List Send
/-- The documents some lines carry: the invoices a send can name. -/
def Books.docs (B : Books) : List Nat :=
B.lines.filterMap (fun l => l.doc)
/-- What the engine allows (S1): a document command, or any entry whose
control lines are all tagged (`Step.document`); a reversal of posted
lines, mirror for mirror, each keeping its tag (`Step.reverse`), dated on
or after them (B-38, "Dating rules"); writing off a bad debt, for at most
what the document is owed (`Step.writeOff`, S7); assigning a document
role an account all of whose lines are documents' (`Step.assign`:
`check_assign_role` SCENARIO 6 refuses one holding an untagged line); and
an account leaving the control accounts once it holds no document's line
(`Step.release`: an assigned role moved off an account no document posted
to; an account holding a document's line stays guarded,
`control_role_of`). -/
inductive Step : Books → Books → Prop
| document (B : Books) (e : List TLine) (h : Tagged B.control e) :
Step B { B with lines := B.lines ++ e }
| reverse (B : Books) (e : List TLine) (he : ∀ l ∈ e, l ∈ B.lines) (D : Nat) :
Step B { B with lines := B.lines ++ e.map (mirror D) }
| writeOff (B : Books) (control expense d D : Nat) (amount : Int)
(hc : control ∈ B.control) (hne : control ≠ expense)
(h : Tagged B.control (writeOffLines control expense d D amount))
(hb : amount ≤ docSum control d (through D B.lines)) :
Step B { B with lines := B.lines ++ writeOffLines control expense d D amount }
| assign (B : Books) (c : Nat) (h : ∀ l ∈ B.lines, l.line.account = c → l.doc ≠ none) :
Step B { B with control := c :: B.control }
| release (B : Books) (c : Nat) (h : ∀ l ∈ B.lines, l.line.account = c → l.doc = none) :
Step B { B with control := B.control.erase c }
/-- `mark_sent` (`Ledger::mark_sent`, plan P4b S5): a send is recorded on
an invoice the books hold, and nothing else changes. It moves no line,
so every figure stays where it was. -/
| markSent (B : Books) (s : Send) (h : s.doc ∈ B.docs) :
Step B { B with sends := s :: B.sends }
/-- **A document step never moves what is unattached** on a control
account: no command adds an untagged control line. -/
theorem Step.document_unattached (B : Books) (e : List TLine) (h : Tagged B.control e)
(a : Nat) (ha : a ∈ B.control) : unattached a (B.lines ++ e) = unattached a B.lines := by
rw [unattached_append, unattached_zero_of_tagged h ha]; omega
/-- **A write-off never moves what is unattached**: its control line carries
the document (a `Step.document` in shape), and its expense line is off the
control accounts, so no control account gains an untagged line (B-41). -/
theorem Step.writeOff_unattached (B : Books) (control expense d D : Nat) (amount : Int)
(h : Tagged B.control (writeOffLines control expense d D amount)) (a : Nat)
(ha : a ∈ B.control) :
unattached a (B.lines ++ writeOffLines control expense d D amount) = unattached a B.lines := by
rw [unattached_append, unattached_zero_of_tagged h ha]; omega
/-- **A settlement is a document step**: its entry's every control line
carries its document (a payment or a discount), so the books' rules for
any entry whose control lines are tagged cover it; no new `Step`
constructor is needed (plan P4b S6; rules.md B-42). -/
theorem settle_posts_a_document_step (B : Books) (e : List TLine)
(h : Tagged B.control e) : Step B { B with lines := B.lines ++ e } :=
Step.document B e h
/-- **A settlement never moves what is unattached** on a control account:
every control line it posts is its document's (B-42, from
`Step.document_unattached`). -/
theorem settle_unattached (B : Books) (e : List TLine) (h : Tagged B.control e) (a : Nat)
(ha : a ∈ B.control) : unattached a (B.lines ++ e) = unattached a B.lines :=
Step.document_unattached B e h a ha
/-- **A reversal moves each document by exactly the opposite of its lines
it mirrors** (B-38 INVARIANT 3), and what is unattached likewise: only
reversing a legacy hand line changes it. -/
theorem Step.reverse_moves (B : Books) (e : List TLine) (D a d : Nat) :
docSum a d (B.lines ++ e.map (mirror D)) = docSum a d B.lines - docSum a d e
∧ unattached a (B.lines ++ e.map (mirror D)) = unattached a B.lines - unattached a e := by
rw [docSum_append, docSum_mirror, unattached_append, unattached_mirror]
omega
/-- **Reversing a reversal restores every document** (B-10): the lines,
mirrored twice, sum as the originals did. -/
theorem reverse_twice (a d D D' : Nat) (e : List TLine) :
docSum a d ((e.map (mirror D)).map (mirror D')) = docSum a d e := by
rw [docSum_mirror, docSum_mirror]; omega
/-- **A send changes no figure** (plan P4b S5): recording one leaves every
control account's balance, every document's sum on it and what is
unattached exactly as they were, through any day. A send adds a record and
no line, so the engine's own statement (`Ledger::mark_sent`) that a
document's DocState is the same before and after is this, line for line. -/
theorem Step.markSent_changes_no_figure (B : Books) (s : Send) (_h : s.doc ∈ B.docs)
(a d D : Nat) :
gl a (through D ({ B with sends := s :: B.sends } : Books).lines)
= gl a (through D B.lines)
∧ docSum a d (through D ({ B with sends := s :: B.sends } : Books).lines)
= docSum a d (through D B.lines)
∧ unattached a (through D ({ B with sends := s :: B.sends } : Books).lines)
= unattached a (through D B.lines) := by
exact ⟨rfl, rfl, rfl⟩
/-- States reachable from books with no lines. -/
inductive Reachable : Books → Prop
| empty (control : List Nat) : Reachable ⟨control, [], []⟩
| step {B B' : Books} : Reachable B → Step B B' → Reachable B'
theorem Reachable.tagged {B : Books} (r : Reachable B) : Tagged B.control B.lines := by
induction r with
| empty => intro l hl; simp at hl
| step _ s ih =>
cases s with
| document e h =>
intro l hl hc
rcases List.mem_append.1 hl with hl | hl
· exact ih l hl hc
· exact h l hl hc
| reverse e he D =>
intro l hl hc
rcases List.mem_append.1 hl with hl | hl
· exact ih l hl hc
· obtain ⟨m, hm, rfl⟩ := List.mem_map.1 hl
exact ih m (he m hm) (by simpa [mirror, Line.reverse] using hc)
| writeOff control expense d D amount hc hne h hb =>
intro l hl hc'
rcases List.mem_append.1 hl with hl | hl
· exact ih l hl hc'
· exact h l hl hc'
| assign c h =>
intro l hl hc
rcases List.mem_cons.1 hc with hc | hc
· exact h l hl hc
· exact ih l hl hc
| release c h =>
intro l hl hc
exact ih l hl (List.mem_of_mem_erase hc)
| markSent _ _ =>
-- A send touches no line: the control lines are the ones it found.
exact ih
/-- **Nothing is ever unattached on a control account** in books these
steps build, through any day, roles assigned and released included:
every control line is a document's. (Books an earlier version wrote, with
hand lines, are covered by the identity `control_agrees` alone; an
account becoming a control account by its first document, holding lines
from before, is outside the model: `control_check` lists those lines.) -/
theorem Reachable.unattached_zero {B : Books} (r : Reachable B) (a : Nat) (ha : a ∈ B.control)
(D : Nat) : unattached a (through D B.lines) = 0 := by
have ht := r.tagged
have : ∀ ls : List TLine, (∀ l ∈ ls, l ∈ B.lines) → unattached a ls = 0 := by
intro ls
induction ls with
| nil => intro _; rfl
| cons l ls ih =>
intro hs
simp only [unattached]
rw [ih (fun m hm => hs m (List.mem_cons_of_mem _ hm))]
by_cases hn : l.doc = none
· have hacc : l.line.account ≠ a :=
fun e => ht l (hs l (List.mem_cons_self ..)) (e ▸ ha) hn
simp [hn, onAcct, hacc]
· simp [hn]
exact this _ (fun l hl => (List.mem_filter.1 hl).1)
/-- **So the control account is its documents**, exactly, on every day:
GL(A, D) = Σ_docs outstanding(d, D). -/
theorem Reachable.control_is_documents {B : Books} (r : Reachable B) (a : Nat)
(ha : a ∈ B.control) (ds : List Nat) (hd : Distinct ds) (hc : Covers ds B.lines) (D : Nat) :
gl a (through D B.lines) = sumOver (fun d => docSum a d (through D B.lines)) ds := by
rw [control_agrees_through a ds hd B.lines hc D, r.unattached_zero a ha D]; omega
/-! ## Writing off a bad debt (B-41, plan P4b S7) -/
/-- What a write-off of `amount` does to the document's own sum through
`D`: the control line it posts there is a credit tagged with the document,
and the expense line carries none and is on another account. -/
theorem docSum_writeOffLines (control expense d D : Nat) (amount : Int) :
docSum control d (through D (writeOffLines control expense d D amount)) = -amount := by
simp [writeOffLines, through, docSum, onAcct, Line.signed]
/-- **A write-off of at most what is owed leaves nothing owed below zero**
(B-41 INVARIANT 1, over the date-sum `docSum … through D`): the credit it
posts on the control line is the amount, so what the document owes through
the write-off's day is what it owed less the amount, and that is never
below zero. Reversing the write-off adds the amount back
(`reverse_twice`), which is the same-year recovery (D-49). -/
theorem writeOff_within_bounds (B : Books) (control expense d D : Nat) (amount : Int)
(h : amount ≤ docSum control d (through D B.lines)) :
0 ≤ docSum control d (through D (B.lines ++ writeOffLines control expense d D amount)) := by
rw [through_append, docSum_append, docSum_writeOffLines]
omega
end Wanderbooks.Documents
-117
View File
@@ -1,117 +0,0 @@
import Wanderbooks.Basic
/-!
# Entries: acceptance, movements, reversals
Mirrors `kernel::check_lines`, `kernel::movements`, `kernel::reversal`,
and `JournalEntry::validate`.
-/
namespace Wanderbooks
/-- What the engine accepts (the arithmetic of `JournalEntry::validate`,
i.e. `kernel::check_lines`): two or more lines, every amount positive,
debits equal to credits. (Range, account, and currency checks are not
arithmetic laws and are left out of the model.) -/
def Accepted (ls : List Line) : Prop :=
2 ≤ ls.length ∧ (∀ l ∈ ls, 0 < l.amount) ∧ debits ls = credits ls
/-- **Every accepted entry nets to zero.** -/
theorem Accepted.net_zero {ls : List Line} (h : Accepted ls) : net ls = 0 := by
rw [net_eq_debits_sub_credits]; have := h.2.2; omega
/-- Net movement of account `a` over some lines. -/
def movement (a : Nat) : List Line → Int
| [] => 0
| l :: ls => (if l.account = a then l.signed else 0) + movement a ls
@[simp] theorem movement_nil (a : Nat) : movement a [] = 0 := rfl
@[simp] theorem movement_cons (a : Nat) (l : Line) (ls : List Line) :
movement a (l :: ls) = (if l.account = a then l.signed else 0) + movement a ls := rfl
theorem movement_append (a : Nat) (xs ys : List Line) :
movement a (xs ++ ys) = movement a xs + movement a ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, movement_cons, ih]; omega
/-- **Movements partition the net.** Summed over a chart's distinct codes
that cover every line's account, the per-account movements add up to the
net of the lines: grouping by account loses and invents nothing. -/
theorem sum_movements (as : List Nat) (hd : Distinct as) :
∀ ls : List Line, (∀ l ∈ ls, l.account ∈ as) →
sumOver (fun a => movement a ls) as = net ls := by
intro ls
induction ls with
| nil => intro _; simpa using sumOver_zero as
| cons l ls ih =>
intro hcov
simp only [movement_cons, net_cons]
rw [sumOver_add, ih (fun m hm => hcov m (List.mem_cons_of_mem _ hm)),
sumOver_indicator l.account l.signed as hd (hcov l (List.mem_cons_self ..))]
/-- So the movements of an accepted entry sum to zero. -/
theorem Accepted.movements_sum_zero {ls : List Line} (h : Accepted ls) (as : List Nat)
(hd : Distinct as) (hcov : ∀ l ∈ ls, l.account ∈ as) :
sumOver (fun a => movement a ls) as = 0 := by
rw [sum_movements as hd ls hcov, h.net_zero]
/-! ## Reversals -/
/-- A line with its side flipped. -/
def Line.reverse (l : Line) : Line := { l with side := l.side.flip }
/-- A reversing entry's lines (`kernel::reversal`). -/
def reversal (ls : List Line) : List Line := ls.map Line.reverse
theorem Line.reverse_signed (l : Line) : l.reverse.signed = -l.signed := by
simp [Line.reverse, Line.signed, signed_flip]
theorem net_reversal (ls : List Line) : net (reversal ls) = -net ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [reversal, List.map_cons] at ih ⊢
simp only [net_cons, ih, Line.reverse_signed]; omega
theorem movement_reversal (a : Nat) (ls : List Line) :
movement a (reversal ls) = -movement a ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [reversal, List.map_cons] at ih ⊢
simp only [movement_cons, ih, Line.reverse_signed]
by_cases h : l.account = a <;> simp [Line.reverse, h] <;> omega
/-- **An entry and its reversal net every account to zero.** -/
theorem movement_with_reversal (a : Nat) (ls : List Line) :
movement a (ls ++ reversal ls) = 0 := by
rw [movement_append, movement_reversal]; omega
theorem debits_reversal (ls : List Line) : debits (reversal ls) = credits ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [reversal, List.map_cons] at ih ⊢
obtain ⟨a, s, m⟩ := l
cases s <;> simp [debits, credits, Line.reverse, Side.flip, ih]
theorem credits_reversal (ls : List Line) : credits (reversal ls) = debits ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [reversal, List.map_cons] at ih ⊢
obtain ⟨a, s, m⟩ := l
cases s <;> simp [debits, credits, Line.reverse, Side.flip, ih]
/-- **A reversal is accepted exactly when the original is.** -/
theorem accepted_reversal_iff (ls : List Line) : Accepted (reversal ls) ↔ Accepted ls := by
unfold Accepted
rw [debits_reversal, credits_reversal]
have hlen : (reversal ls).length = ls.length := List.length_map ..
have hpos : (∀ l ∈ reversal ls, 0 < l.amount) ↔ (∀ l ∈ ls, 0 < l.amount) := by
simp [reversal, Line.reverse]
rw [hlen, hpos]
constructor <;> rintro ⟨a, b, c⟩ <;> exact ⟨a, b, c.symm⟩
end Wanderbooks
-605
View File
@@ -1,605 +0,0 @@
import Wanderbooks.Closing
/-!
# The ledger as a state machine
The engine's command surface (`Ledger`), modelled as the steps it allows:
add an account, start a draft, post, reverse, open a period, close one.
Each step carries the checks the engine makes before it mutates. The
theorems below hold in *every* state reachable from empty books, by any
sequence of commands, of any length.
Mirrors `Ledger::add_account`, `try_create_entry`, `post_entry`,
`reverse_entry`, `create_period`, and `close_period_to`; and, as one step
`record`, everything the books keep about how they are kept: settings,
conventions, decisions, open items and approvals (`apply_settings`,
`apply_convention`, `apply_decision`, `apply_open_item`,
`apply_approval`, and their retirements and resolutions), each a record
the step adds and nothing else; and an account's rename
(`rename_account`, `account.renamed`, rules.md B-31), since the model's
chart is codes and types and a name is no part of it.
-/
namespace Wanderbooks
/-- A journal entry: its id, its date (a day number), its lines. -/
structure Entry where
id : Nat
date : Nat
lines : List Line
deriving DecidableEq
/-- Every line of some entries, in order. -/
def allLines : List Entry → List Line
| [] => []
| e :: es => e.lines ++ allLines es
theorem allLines_append (xs ys : List Entry) : allLines (xs ++ ys) = allLines xs ++ allLines ys := by
induction xs with
| nil => rfl
| cons x xs ih => simp [allLines, ih]
theorem mem_allLines {l : Line} {es : List Entry} : l ∈ allLines es ↔ ∃ e ∈ es, l ∈ e.lines := by
induction es with
| nil => simp [allLines]
| cons e es ih => simp [allLines, ih]
/-- **Any collection of balanced entries nets to zero**: all of them, those
dated through some day, those in some period, any filter at all. -/
theorem net_allLines (es : List Entry) (h : ∀ e ∈ es, net e.lines = 0) : net (allLines es) = 0 := by
induction es with
| nil => rfl
| cons e es ih =>
simp only [allLines, net_append, h e (by simp), ih (fun x hx => h x (by simp [hx]))]
rfl
/-- An accounting period: inclusive day range, open or closed. -/
structure Period where
id : Nat
start : Nat
stop : Nat
closed : Bool
deriving DecidableEq
/-- Whether a day falls in a period. -/
def Period.contains (p : Period) (d : Nat) : Bool := decide (p.start ≤ d ∧ d ≤ p.stop)
/-- The books: chart, posted entries in posting order, drafts, periods,
and the record of how they are kept (settings, conventions, decisions,
open items, approvals), each record abstracted to a number. -/
structure Ledger where
chart : Chart
posted : List Entry
drafts : List Entry
periods : List Period
records : List Nat
/-- Empty books. -/
def Ledger.empty : Ledger := ⟨[], [], [], [], []⟩
/-- Whether a closed period contains a day. -/
def Ledger.closedOn (L : Ledger) (d : Nat) : Prop :=
∃ p ∈ L.periods, p.closed = true ∧ p.contains d = true
/-- Entries dated on or before a day. -/
def through (d : Nat) (es : List Entry) : List Entry := es.filter (fun e => decide (e.date ≤ d))
/-- Mark one period closed. -/
def closeIn (p : Period) (ps : List Period) : List Period :=
ps.map (fun q => if q = p then { q with closed := true } else q)
/-- The closing entry for period `p` crediting targets `ts`, if there is
anything to close. -/
def closingFor (L : Ledger) (p : Period) (ts : List (Nat × Int)) (id : Nat) : List Entry :=
if closings (nominalCodes L.chart) (allLines (through p.stop L.posted)) = [] then []
else [⟨id, p.stop, closingEntry (nominalCodes L.chart) ts (allLines (through p.stop L.posted))⟩]
/-- What the engine allows. -/
inductive Step : Ledger → Ledger → Prop
/-- `add_account`: codes are unique. -/
| addAccount (L : Ledger) (a : Nat) (t : AccountType) (h : a ∉ codes L.chart) :
Step L { L with chart := (a, t) :: L.chart }
/-- `try_create_entry` (and lines added to it): not in a closed period. -/
| draft (L : Ledger) (e : Entry) (h : ¬ L.closedOn e.date) :
Step L { L with drafts := e :: L.drafts }
/-- `post_entry`: a draft, acceptable, on known accounts, not in a closed
period. Appends to the log. -/
| post (L : Ledger) (e : Entry) (hd : e ∈ L.drafts) (ha : Accepted e.lines)
(hk : ∀ l ∈ e.lines, l.account ∈ codes L.chart) (hc : ¬ L.closedOn e.date) :
Step L { L with posted := L.posted ++ [e], drafts := L.drafts.filter (· ≠ e) }
/-- `reverse_entry`: a posted entry's lines, sides flipped, posted on a
day not in a closed period. -/
| reverse (L : Ledger) (e : Entry) (he : e ∈ L.posted) (r : Entry)
(hr : r.lines = reversal e.lines) (hc : ¬ L.closedOn r.date) :
Step L { L with posted := L.posted ++ [r] }
/-- `create_period`: periods open. -/
| openPeriod (L : Ledger) (p : Period) (h : p.closed = false) :
Step L { L with periods := p :: L.periods }
/-- `close_period_to`: an open period with no drafts in it, whose last day
is in no other closed period, with no later period closed, crediting the
net income to equity targets (not themselves revenue or expense) in
parts that sum to it. -/
| close (L : Ledger) (p : Period) (hp : p ∈ L.periods) (hopen : p.closed = false)
(hdrafts : ∀ d ∈ L.drafts, p.contains d.date = false)
(hother : ∀ q ∈ L.periods, q.closed = true → q.contains p.stop = false)
(hlater : ∀ q ∈ L.periods, q.closed = true → q.stop ≤ p.stop)
(ts : List (Nat × Int))
(hts : ∀ x ∈ ts, x.1 ∈ codes L.chart ∧ x.1 ∉ nominalCodes L.chart)
(hsum : total (ts.map Prod.snd)
= net (closings (nominalCodes L.chart) (allLines (through p.stop L.posted))))
(id : Nat) :
Step L { L with posted := L.posted ++ closingFor L p ts id, periods := closeIn p L.periods }
/-- `discard_draft`: a draft removed, with the reason it went. The
drafts shrink; the posted log, the chart, the periods and the records
are as they were, so no balance moves. -/
| discard (L : Ledger) (e : Entry) (hd : e ∈ L.drafts) :
Step L { L with drafts := L.drafts.filter (· ≠ e) }
/-- `apply_settings`, `apply_convention`, `apply_decision`,
`apply_open_item`, `apply_approval` and their retirements and
resolutions, and the 1099 records `set_vendor_1099`,
`set_vendor_w9_flag`, `add_instrument` and `set_entry_instrument`: a
record of how the books are kept, and nothing else. `rename_account`
too: a name is outside the chart the model keeps. -/
| record (L : Ledger) (r : Nat) : Step L { L with records := r :: L.records }
/-- States reachable from empty books. -/
inductive Reachable : Ledger → Prop
| empty : Reachable Ledger.empty
| step {L L' : Ledger} : Reachable L → Step L L' → Reachable L'
/-- What holds in every reachable state. -/
structure Inv (L : Ledger) : Prop where
distinct : Distinct (codes L.chart)
accepted : ∀ e ∈ L.posted, Accepted e.lines
known : ∀ e ∈ L.posted, ∀ l ∈ e.lines, l.account ∈ codes L.chart
draftsOpen : ∀ d ∈ L.drafts, ¬ L.closedOn d.date
theorem closedOn_closeIn (L : Ledger) (p : Period) (d : Nat) :
({ L with periods := closeIn p L.periods } : Ledger).closedOn d →
L.closedOn d ∨ (p ∈ L.periods ∧ p.contains d = true) := by
rintro ⟨q, hq, hc, hd⟩
simp only [closeIn, List.mem_map] at hq
obtain ⟨q', hq', rfl⟩ := hq
by_cases e : q' = p
· subst e; right; simp at hd; exact ⟨hq', by simpa [Period.contains] using hd⟩
· left; simp [e] at hc hd; exact ⟨q', hq', hc, hd⟩
theorem closingFor_lines (L : Ledger) (p : Period) (ts : List (Nat × Int)) (id : Nat) :
∀ e ∈ closingFor L p ts id,
e.date = p.stop ∧ e.lines = closingEntry (nominalCodes L.chart) ts
(allLines (through p.stop L.posted))
∧ closings (nominalCodes L.chart) (allLines (through p.stop L.posted)) ≠ [] := by
intro e he
unfold closingFor at he
split at he
· simp at he
· simp at he; subst he; exact ⟨rfl, rfl, by assumption⟩
/-- **Every step preserves the invariant.** -/
theorem Step.inv {L L' : Ledger} (s : Step L L') (h : Inv L) : Inv L' := by
cases s with
| addAccount a t ha =>
exact ⟨⟨ha, h.distinct⟩, h.accepted,
fun e he l hl => List.mem_cons_of_mem _ (h.known e he l hl), h.draftsOpen⟩
| draft e hc =>
refine ⟨h.distinct, h.accepted, h.known, ?_⟩
intro d hd
cases hd with
| head => exact hc
| tail _ hd => exact h.draftsOpen d hd
| post e hd ha hk hc =>
refine ⟨h.distinct, ?_, ?_, ?_⟩
· intro x hx
simp only [List.mem_append, List.mem_singleton] at hx
rcases hx with hx | rfl
· exact h.accepted x hx
· exact ha
· intro x hx
simp only [List.mem_append, List.mem_singleton] at hx
rcases hx with hx | rfl
· exact h.known x hx
· exact hk
· intro d hd
exact h.draftsOpen d ((List.mem_filter.1 hd).1)
| reverse e he r hr hc =>
refine ⟨h.distinct, ?_, ?_, h.draftsOpen⟩
· intro x hx
simp only [List.mem_append, List.mem_singleton] at hx
rcases hx with hx | rfl
· exact h.accepted x hx
· rw [hr, accepted_reversal_iff]; exact h.accepted e he
· intro x hx
simp only [List.mem_append, List.mem_singleton] at hx
rcases hx with hx | rfl
· exact h.known x hx
· intro l hl
rw [hr] at hl
simp only [reversal, List.mem_map] at hl
obtain ⟨l', hl', rfl⟩ := hl
exact h.known e he l' hl'
| openPeriod p hp =>
refine ⟨h.distinct, h.accepted, h.known, ?_⟩
rintro d hd ⟨q, hq, hc, hdq⟩
cases hq with
| head => simp [hp] at hc
| tail _ hq => exact h.draftsOpen d hd ⟨q, hq, hc, hdq⟩
| close p hp hopen hdrafts hother hlater ts hts hsum id =>
refine ⟨h.distinct, ?_, ?_, ?_⟩
· intro x hx
simp only [List.mem_append] at hx
rcases hx with hx | hx
· exact h.accepted x hx
· obtain ⟨-, hl, hne⟩ := closingFor_lines L p ts id x hx
rw [hl]; exact closingEntry_accepted _ _ _ hsum hne
· intro x hx
simp only [List.mem_append] at hx
rcases hx with hx | hx
· exact h.known x hx
· obtain ⟨-, hl, -⟩ := closingFor_lines L p ts id x hx
intro l hl'
rw [hl] at hl'
simp only [closingEntry, List.mem_append] at hl'
rcases hl' with hl' | hl'
· exact nominalCodes_sub _ _ (closings_account _ _ l hl')
· obtain ⟨y, hy, e⟩ := equityLines_account ts l hl'
rw [e]; exact (hts y hy).1
· intro d hd hcl
rcases closedOn_closeIn L p d.date hcl with hcl | ⟨-, hc⟩
· exact h.draftsOpen d hd hcl
· simp [hdrafts d hd] at hc
| discard e hd =>
refine ⟨h.distinct, h.accepted, h.known, ?_⟩
intro d hd'
exact h.draftsOpen d ((List.mem_filter.1 hd').1)
| record r => exact ⟨h.distinct, h.accepted, h.known, h.draftsOpen⟩
/-- **The invariant holds in every reachable state.** -/
theorem Reachable.inv {L : Ledger} (r : Reachable L) : Inv L := by
induction r with
| empty => exact ⟨trivial, by simp [Ledger.empty], by simp [Ledger.empty], by simp [Ledger.empty]⟩
| step _ s ih => exact s.inv ih
/-! ## The books always balance -/
/-- **The books net to zero**: in every reachable state, the posted lines'
debits equal their credits. -/
theorem Reachable.books_net_zero {L : Ledger} (r : Reachable L) : net (allLines L.posted) = 0 :=
net_allLines _ (fun e he => (r.inv.accepted e he).net_zero)
/-- The same through any day: the books as of any date balance too. -/
theorem Reachable.net_zero_through {L : Ledger} (r : Reachable L) (d : Nat) :
net (allLines (through d L.posted)) = 0 :=
net_allLines _ (fun e he => (r.inv.accepted e ((List.mem_filter.1 he).1)).net_zero)
theorem Reachable.covers {L : Ledger} (r : Reachable L) (es : List Entry)
(hs : ∀ e ∈ es, e ∈ L.posted) : ∀ l ∈ allLines es, l.account ∈ codes L.chart := by
intro l hl
obtain ⟨e, he, hl⟩ := mem_allLines.1 hl
exact r.inv.known e (hs e he) l hl
/-- **The trial balance balances**, in every reachable state. -/
theorem Reachable.trial_balance {L : Ledger} (r : Reachable L) :
tbDebits (allLines L.posted) (codes L.chart) = tbCredits (allLines L.posted) (codes L.chart) :=
trial_balance_balances _ _ r.inv.distinct (r.covers _ (fun _ h => h)) r.books_net_zero
/-- **The trial balance as of any date balances.** -/
theorem Reachable.trial_balance_through {L : Ledger} (r : Reachable L) (d : Nat) :
tbDebits (allLines (through d L.posted)) (codes L.chart)
= tbCredits (allLines (through d L.posted)) (codes L.chart) :=
trial_balance_balances _ _ r.inv.distinct
(r.covers _ (fun _ h => (List.mem_filter.1 h).1)) (r.net_zero_through d)
/-- **The accounting equation holds**, in every reachable state:
Assets = Liabilities + Equity + (Revenue - Expenses). -/
theorem Reachable.accounting_equation {L : Ledger} (r : Reachable L) :
let ls := allLines L.posted
typeTotal .asset ls L.chart
= typeTotal .liability ls L.chart + typeTotal .equity ls L.chart
+ (typeTotal .revenue ls L.chart - typeTotal .expense ls L.chart) :=
Wanderbooks.accounting_equation _ _ r.inv.distinct (r.covers _ (fun _ h => h)) r.books_net_zero
/-- **The balance sheet as of any date balances.** -/
theorem Reachable.accounting_equation_through {L : Ledger} (r : Reachable L) (d : Nat) :
let ls := allLines (through d L.posted)
typeTotal .asset ls L.chart
= typeTotal .liability ls L.chart + typeTotal .equity ls L.chart
+ (typeTotal .revenue ls L.chart - typeTotal .expense ls L.chart) :=
Wanderbooks.accounting_equation _ _ r.inv.distinct
(r.covers _ (fun _ h => (List.mem_filter.1 h).1)) (r.net_zero_through d)
/-! ## Posted is forever -/
/-- **Posting only appends.** No step edits, reorders, or removes a posted
entry. -/
theorem Step.extends {L L' : Ledger} (s : Step L L') : ∃ t, L'.posted = L.posted ++ t := by
cases s with
| addAccount => exact ⟨[], by simp⟩
| draft => exact ⟨[], by simp⟩
| post e => exact ⟨[e], rfl⟩
| reverse e _ r => exact ⟨[r], rfl⟩
| openPeriod => exact ⟨[], by simp⟩
| close p _ _ _ _ _ ts _ _ id => exact ⟨closingFor L p ts id, rfl⟩
| discard => exact ⟨[], by simp⟩
| record => exact ⟨[], by simp⟩
/-- Any number of steps. -/
inductive Steps : Ledger → Ledger → Prop
| refl (L : Ledger) : Steps L L
| tail {L M N : Ledger} : Steps L M → Step M N → Steps L N
/-- **Posted is forever**: after any sequence of commands, the old log is
a prefix of the new one. Every posted entry keeps its place and its
lines. -/
theorem Steps.extends {L L' : Ledger} (s : Steps L L') : ∃ t, L'.posted = L.posted ++ t := by
induction s with
| refl => exact ⟨[], by simp⟩
| tail _ s ih =>
obtain ⟨t, ht⟩ := ih
obtain ⟨u, hu⟩ := s.extends
exact ⟨t ++ u, by rw [hu, ht, List.append_assoc]⟩
/-! ## A discarded draft takes nothing with it -/
/-- **A discard moves no figure**: the posted log, the chart and the
periods are the very same, so every balance, report and closing read from
them is the same too. -/
theorem Step.discard_keeps_books (L : Ledger) (e : Entry) :
({ L with drafts := L.drafts.filter (· ≠ e) } : Ledger).posted = L.posted
∧ ({ L with drafts := L.drafts.filter (· ≠ e) } : Ledger).chart = L.chart
∧ ({ L with drafts := L.drafts.filter (· ≠ e) } : Ledger).periods = L.periods :=
⟨rfl, rfl, rfl⟩
/-- **A discard removes the draft and only it**: afterwards `e` is no
draft, and every draft left was a draft before. -/
theorem Step.discard_drafts (L : Ledger) (e : Entry) :
e ∉ L.drafts.filter (· ≠ e) ∧ ∀ d ∈ L.drafts.filter (· ≠ e), d ∈ L.drafts := by
refine ⟨?_, fun d hd => (List.mem_filter.1 hd).1⟩
intro h
simpa using (List.mem_filter.1 h).2
/-- **Discarding unblocks a close**: if every draft left after a discard
is outside the period `p`, then the draft discarded was the only one in it
(the `hdrafts` hypothesis of `Step.close` holds once the drafts in `p`
are discarded). -/
theorem Step.discard_unblocks_close (L : Ledger) (p : Period) (e : Entry)
(hin : ∀ d ∈ L.drafts, p.contains d.date = true → d = e) :
∀ d ∈ L.drafts.filter (· ≠ e), p.contains d.date = false := by
intro d hd
obtain ⟨h1, h2⟩ := List.mem_filter.1 hd
have hne : d ≠ e := by simpa using h2
cases hc : p.contains d.date with
| false => rfl
| true => exact absurd (hin d h1 hc) hne
/-! ## Closed periods are frozen -/
/-- Entries dated in a period. -/
def within (p : Period) (es : List Entry) : List Entry := es.filter (fun e => p.contains e.date)
theorem within_append (p : Period) (xs ys : List Entry) :
within p (xs ++ ys) = within p xs ++ within p ys := List.filter_append ..
/-- A closed period stays closed. -/
theorem Step.keeps_closed {L L' : Ledger} (s : Step L L') (q : Period) (hq : q ∈ L.periods)
(hc : q.closed = true) : q ∈ L'.periods := by
cases s with
| openPeriod p _ => exact List.mem_cons_of_mem _ hq
| close p _ hopen =>
have : q ≠ p := fun e => by subst e; simp [hopen] at hc
exact List.mem_map.2 ⟨q, hq, by simp [this]⟩
| _ => exact hq
/-- **A step never changes what a closed period contains.** -/
theorem Step.frozen {L L' : Ledger} (s : Step L L') (q : Period) (hq : q ∈ L.periods)
(hc : q.closed = true) : within q L'.posted = within q L.posted := by
have nothing : ∀ e : Entry, ¬ L.closedOn e.date → within q [e] = [] := by
intro e he
simp only [within, List.filter_cons, List.filter_nil]
split
· exact absurd ⟨q, hq, hc, by assumption⟩ he
· rfl
cases s with
| post e _ _ _ hcl => rw [within_append, nothing e hcl, List.append_nil]
| reverse e _ r _ hcl => rw [within_append, nothing r hcl, List.append_nil]
| close p hp hopen hdrafts hother hlater ts hts hsum id =>
rw [within_append]
have : within q (closingFor L p ts id) = [] := by
unfold closingFor
split
· rfl
· simp only [within, List.filter_cons, List.filter_nil]
rw [hother q hq hc]; rfl
rw [this, List.append_nil]
| _ => rfl
/-- **Closed periods are frozen**: once a period is closed, no sequence of
commands adds, removes, or changes an entry dated in it. -/
theorem Steps.frozen {L L' : Ledger} (s : Steps L L') (q : Period) (hq : q ∈ L.periods)
(hc : q.closed = true) : within q L'.posted = within q L.posted ∧ q ∈ L'.periods := by
induction s with
| refl => exact ⟨rfl, hq⟩
| tail _ s ih =>
obtain ⟨h1, h2⟩ := ih
exact ⟨(s.frozen q h2 hc).trans h1, s.keeps_closed q h2 hc⟩
/-! ## Closing -/
/-- **After a close, every revenue and expense account is zero through the
period's last day.** (The trial balance still balances: the close is a
step, and `Reachable.trial_balance` covers every step.) -/
theorem close_zeroes {L : Ledger} (r : Reachable L) (p : Period)
(ts : List (Nat × Int)) (hts : ∀ x ∈ ts, x.1 ∈ codes L.chart ∧ x.1 ∉ nominalCodes L.chart)
(id : Nat) (a : Nat) (ha : a ∈ nominalCodes L.chart) :
movement a (allLines (through p.stop (L.posted ++ closingFor L p ts id))) = 0 := by
have hd := nominalCodes_distinct _ r.inv.distinct
have hta : ∀ x ∈ ts, x.1 ≠ a := fun x hx e => (hts x hx).2 (e ▸ ha)
rw [through, List.filter_append, ← through, allLines_append]
unfold closingFor
split
· rename_i hnil
simp only [List.filter_nil, allLines, List.append_nil]
exact closings_eq_nil _ _ hnil a ha
· simp only [List.filter_cons, Nat.le_refl, decide_true, ite_true, List.filter_nil, allLines,
List.append_nil]
exact closingEntry_zeroes _ ts _ hd a ha hta
/-- **A close credits equity with exactly the period's net income**:
revenue minus expenses through its last day, split among the targets. -/
theorem close_credits_net_income (L : Ledger) (p : Period) (ts : List (Nat × Int))
(hsum : total (ts.map Prod.snd)
= net (closings (nominalCodes L.chart) (allLines (through p.stop L.posted)))) :
let ls := allLines (through p.stop L.posted)
total (ts.map Prod.snd) = typeTotal .revenue ls L.chart - typeTotal .expense ls L.chart := by
intro ls
rw [hsum, net_closings_is_net_income]
/-! ## Period statements add up -/
/-- Entries dated after day `b`, through day `c`. -/
def between (b c : Nat) (es : List Entry) : List Entry :=
es.filter (fun e => decide (b < e.date ∧ e.date ≤ c))
theorem movement_split (a b c : Nat) (h : b ≤ c) (es : List Entry) :
movement a (allLines (through c es))
= movement a (allLines (through b es)) + movement a (allLines (between b c es)) := by
induction es with
| nil => rfl
| cons e es ih =>
simp only [through, between] at ih ⊢
by_cases h1 : e.date ≤ b
· have h2 : e.date ≤ c := by omega
have h3 : ¬ (b < e.date ∧ e.date ≤ c) := by omega
rw [List.filter_cons_of_pos (by simpa using h2), List.filter_cons_of_pos (by simpa using h1),
List.filter_cons_of_neg (by simpa using h3)]
simp only [allLines, movement_append, ih]; omega
· by_cases h2 : e.date ≤ c
· have h3 : b < e.date ∧ e.date ≤ c := by omega
rw [List.filter_cons_of_pos (by simpa using h2), List.filter_cons_of_neg (by simpa using h1),
List.filter_cons_of_pos (by simpa using h3)]
simp only [allLines, movement_append, ih]; omega
· have h3 : ¬ (b < e.date ∧ e.date ≤ c) := by omega
rw [List.filter_cons_of_neg (by simpa using h2), List.filter_cons_of_neg (by simpa using h1),
List.filter_cons_of_neg (by simpa using h3)]
exact ih
theorem typeTotal_split (t : AccountType) (x y z : List Line)
(h : ∀ a, movement a x = movement a y + movement a z) (c : Chart) :
typeTotal t x c = typeTotal t y c + typeTotal t z c := by
induction c with
| nil => rfl
| cons p c ih =>
obtain ⟨a, t'⟩ := p
simp only [typeTotal, h a, ih]
split
· cases t' <;> simp [balance, AccountType.normal, signed] <;> omega
· omega
/-- **Period statements add up**: every account type's total (so revenue,
expenses, and net income) through day `c` is its total through day `b`
plus its total for the days after `b` through `c`. A year's P&L is the sum
of its months'. -/
theorem statements_add_up (t : AccountType) (b c : Nat) (h : b ≤ c) (es : List Entry)
(chart : Chart) :
typeTotal t (allLines (through c es)) chart
= typeTotal t (allLines (through b es)) chart
+ typeTotal t (allLines (between b c es)) chart :=
typeTotal_split t _ _ _ (fun a => movement_split a b c h es) chart
/-! ## The statement of cash flows foots (rules.md B-14 rule 9) -/
/-- Some entries' cash, summed, is the movement of the cash accounts over
their lines, when the cash tag follows the account. -/
theorem cashTotal_is_movement (F : List Line → Line → Flow) (cash : List Nat)
(hd : Distinct cash) (hF : ∀ e l, F e l = .cash ↔ l.account ∈ cash) :
∀ xs : List Entry,
cashTotal F (xs.map Entry.lines) = sumOver (fun a => movement a (allLines xs)) cash := by
intro xs
induction xs with
| nil => simpa [cashTotal, allLines] using (sumOver_zero cash).symm
| cons x xs ih =>
simp only [List.map_cons, cashTotal, allLines, movement_append]
rw [sumOver_add, ← ih, cashOf, secNet_cash_is_movement (F x.lines) cash hd (hF x.lines)]
/-- **The statement of cash flows foots**, in every reachable state: over
the posted entries dated after day `b` through day `c` (any selection of
them, `p`: the engine leaves out closing entries), operating + investing +
financing is the movement of the cash accounts over the same entries, for
any tagging whose cash tag follows the account, and whatever a member or
lender handled for each entry (`C`, rule 11) as long as it nets to zero
(`constructive_nets`). Every posted entry is accepted (`Reachable.inv`),
so each nets to zero. -/
theorem Reachable.cashflow_foots {L : Ledger} (r : Reachable L) (b c : Nat) (p : Entry → Bool)
(F : List Line → Line → Flow) (C : List Line → List Int) (hC : ∀ e, sum3 (C e) = 0)
(cash : List Nat) (hd : Distinct cash)
(hF : ∀ e l, F e l = .cash ↔ l.account ∈ cash) :
let xs := (between b c L.posted).filter p
sectionTotal F C 0 (xs.map Entry.lines) + sectionTotal F C 1 (xs.map Entry.lines)
+ sectionTotal F C 2 (xs.map Entry.lines)
= sumOver (fun a => movement a (allLines xs)) cash := by
intro xs
rw [cashflow_sections_sum_to_cash_change, cashTotal_is_movement F cash hd hF]
· intro e he
obtain ⟨x, hx, rfl⟩ := List.mem_map.1 he
have hb := (List.mem_filter.1 hx).1
exact (r.inv.accepted x (List.mem_filter.1 hb).1).net_zero
· exact fun e _ => hC e
/-- **The sections are the change in the cash accounts' balances**: with
every entry between `b` and `c` counted, the three sections sum to the
cash accounts' movement through `c` less their movement through `b`
(their ending balance less their beginning balance). -/
theorem Reachable.cashflow_is_change_in_cash {L : Ledger} (r : Reachable L) (b c : Nat)
(hbc : b ≤ c) (F : List Line → Line → Flow) (C : List Line → List Int)
(hC : ∀ e, sum3 (C e) = 0) (cash : List Nat) (hd : Distinct cash)
(hF : ∀ e l, F e l = .cash ↔ l.account ∈ cash) :
let es := (between b c L.posted).map Entry.lines
sectionTotal F C 0 es + sectionTotal F C 1 es + sectionTotal F C 2 es
= sumOver (fun a => movement a (allLines (through c L.posted))) cash
- sumOver (fun a => movement a (allLines (through b L.posted))) cash := by
intro es
have h := r.cashflow_foots b c (fun _ => true) F C hC cash hd hF
have hall : (between b c L.posted).filter (fun _ => true) = between b c L.posted :=
List.filter_eq_self.2 (fun _ _ => rfl)
simp only [hall] at h
rw [h]
have hs : ∀ a, movement a (allLines (through c L.posted))
= movement a (allLines (through b L.posted)) + movement a (allLines (between b c L.posted)) :=
fun a => movement_split a b c hbc L.posted
rw [sumOver_congr _ _ cash (fun a _ => hs a), sumOver_add]
omega
/-- **A reversal and its original in one period drop out together**: for
an entry and its reversal (lines flipped, tagged as the original's, and
what was handled for it mirrored, `constructive_neg`), the sum of their
flows in each section is zero. -/
theorem cashflow_reversal_nets (F : List Line → Line → Flow) (C : List Line → List Int)
(e : List Line) (hF : ∀ l ∈ e, F (reversal e) l.reverse = F e l)
(hC : C (reversal e) = (C e).map (fun x => -x)) (k : Nat) :
sectionTotal F C k [e, reversal e] = 0 := by
simp only [sectionTotal, stmt_flows_reversal F C e hF hC, getD_neg]
omega
/-! ## How the books are kept changes no figure -/
/-- **A record changes nothing the books hold**: a settings change, a
convention, a decision, an open item or an approval leaves the chart, every
posted entry, every draft and every period exactly as they were. (The
`record` step touches only `records` by definition: this pins the model.
The engine's side is checked in Rust by `settings_replay_is_pure`.
Settings that change how the same entries are presented, such as the
fiscal year, are outside the model.) -/
theorem Step.record_changes_no_figure (L : Ledger) (r : Nat) :
let L' : Ledger := { L with records := r :: L.records }
L'.chart = L.chart ∧ L'.posted = L.posted ∧ L'.drafts = L.drafts ∧ L'.periods = L.periods :=
⟨rfl, rfl, rfl, rfl⟩
/-- **Any number of records changes no figure**, and they keep the
invariant: a reachable state plus records is reachable, with the same
books. -/
theorem Reachable.records {L : Ledger} (h : Reachable L) (rs : List Nat) :
Reachable { L with records := rs ++ L.records } := by
induction rs with
| nil => simpa using h
| cons r rs ih => exact Reachable.step ih (Step.record _ r)
end Wanderbooks
-215
View File
@@ -1,215 +0,0 @@
import Wanderbooks.Entry
/-!
# A party's part of an entry (rules.md B-35)
Mirrors `kernel::party_target` and `kernel::reverse_target`, and proves
what makes a reversal the exact opposite of what it reverses: the target
is odd (but for the debits fallback, where a sign means nothing, and a
member's entry whose cash isn't its money: an expense booked straight to
capital, a debt converted, a distribution still owed), reversing a target
twice gives it back, and a reversal's movement over any set of accounts
(a member's equity, say) is the original's negated.
-/
namespace Wanderbooks
/-- Which way an entry moved value with its parties (`kernel::Direction`). -/
inductive Direction where
| paid
| received
| neither
deriving DecidableEq, Repr
/-- Paid and received swap; neither stays neither. -/
def Direction.flip : Direction → Direction
| .paid => .received
| .received => .paid
| .neither => .neither
@[simp] theorem Direction.flip_flip (d : Direction) : d.flip.flip = d := by
cases d <;> rfl
/-- The direction of a signed amount (`Direction::of`). -/
def Direction.of (a : Int) : Direction :=
if 0 < a then .paid else if a < 0 then .received else .neither
theorem Direction.of_neg (a : Int) : Direction.of (-a) = (Direction.of a).flip := by
unfold Direction.of
by_cases h1 : 0 < a
· rw [ite_eq_right (show ¬ (0 < -a) by omega), ite_eq_left (show -a < 0 by omega), ite_eq_left h1]; rfl
· by_cases h2 : a < 0
· rw [ite_eq_left (show 0 < -a by omega), ite_eq_right h1, ite_eq_left h2]; rfl
· rw [ite_eq_right (show ¬ (0 < -a) by omega), ite_eq_right (show ¬ (-a < 0) by omega), ite_eq_right h1,
ite_eq_right h2]; rfl
/-- `kernel::PartyTarget`. -/
structure PartyTarget where
amount : Int
direction : Direction
cash : Int
inKind : Int
deriving DecidableEq, Repr
/-- `kernel::reverse_target`: every amount negated, paid and received
swapped. -/
def reverseTarget (t : PartyTarget) : PartyTarget :=
⟨-t.amount, t.direction.flip, -t.cash, -t.inKind⟩
/-- **Reversing a reversal gives the original back** (B-9). -/
theorem reverseTarget_involutive (t : PartyTarget) :
reverseTarget (reverseTarget t) = t := by
cases t; simp [reverseTarget]
/-- A magnitude. -/
def magnitude (e : Int) : Int := if e < 0 then -e else e
theorem magnitude_neg (e : Int) : magnitude (-e) = magnitude e := by
unfold magnitude
by_cases h : e < 0
· rw [ite_eq_right (show ¬ (-e < 0) by omega), ite_eq_left h]
· by_cases h' : -e < 0
· rw [ite_eq_left h', ite_eq_right h]; omega
· rw [ite_eq_right h', ite_eq_right h]; omega
/-- The magnitude `m` with the sign of `like`. -/
def withSign (like m : Int) : Int := if like < 0 then -m else m
theorem withSign_neg (e m : Int) (he : e ≠ 0) : withSign (-e) m = -withSign e m := by
unfold withSign
by_cases h : e < 0
· rw [ite_eq_right (show ¬ (-e < 0) by omega), ite_eq_left h]; omega
· rw [ite_eq_left (show -e < 0 by omega), ite_eq_right h]
/-- What of a member's capital movement `e` counts, as (cash, in kind)
(`kernel::party_target` INVARIANTS 1-2): of a contribution (`e < 0`), the
property in it, at most `|e|`, in kind and the rest cash; of a
distribution, the money it paid (`net`, at most `e`) as cash, then the
property it gave, at most what is left, in kind. The rest of a
distribution is still owed and counts as nothing. -/
def capitalParts (e property net : Int) : Int × Int :=
if e < 0 then
(magnitude e - min (max property 0) (magnitude e), min (max property 0) (magnitude e))
else
(min (max net 0) (magnitude e),
min (max property 0) (magnitude e - min (max net 0) (magnitude e)))
/-- The capital case of `kernel::party_target` (a member's entry moving
equity `e ≠ 0`), signed as `e`; neither when nothing counts. -/
def capitalTarget (e property net : Int) : PartyTarget :=
⟨e, if (capitalParts e property net).1 + (capitalParts e property net).2 = 0 then .neither
else Direction.of e,
withSign e (capitalParts e property net).1, withSign e (capitalParts e property net).2⟩
/-- The rest of `kernel::party_target`: money moved, else the parties'
own-account movement, else the debits; neither moves nothing. -/
def moneyTarget (net own debits : Int) : PartyTarget :=
if net ≠ 0 then ⟨net, Direction.of net, net, 0⟩
else ⟨if own ≠ 0 then own else debits, .neither, 0, 0⟩
/-- `kernel::party_target`. -/
def partyTarget (capital : Option (Int × Int)) (net own debits : Int) : PartyTarget :=
match capital with
| some (e, p) => if e ≠ 0 then capitalTarget e p net else moneyTarget net own debits
| none => moneyTarget net own debits
/-- A member's entry whose cash is exactly its money: the money moved the
member's way (paid out on a distribution, received on a contribution) is
what isn't property. Not so for an expense booked straight to capital, a
debt converted, or a distribution still owed: the reversal arm, never the
lines, gives their reversals a target. -/
def cashIsMoney (e property net : Int) : Prop :=
min (max (if 0 < e then net else -net) 0) (magnitude e) =
magnitude e - min (max property 0) (magnitude e)
/-- Not vacuous: a cash contribution, a property contribution, and a
distribution of money and property each have their cash as their money. -/
example : cashIsMoney (-100) 0 (-100) ∧ cashIsMoney (-100) 100 0 ∧ cashIsMoney 100 40 60 := by
unfold cashIsMoney magnitude
decide
/-- Negating a member's entry whose cash is its money keeps what counts. -/
theorem capitalParts_neg (e p net : Int) (he : e ≠ 0) (h : cashIsMoney e p net) :
capitalParts (-e) p (-net) = capitalParts e p net := by
unfold cashIsMoney at h
unfold capitalParts
rw [magnitude_neg]
by_cases hn : e < 0
· rw [ite_eq_right (show ¬ (0 < e) by omega)] at h
rw [ite_eq_right (show ¬ (-e < 0) by omega), ite_eq_left hn, h]
congr 1
omega
· rw [ite_eq_left (show 0 < e by omega)] at h
rw [ite_eq_left (show -e < 0 by omega), ite_eq_right hn, h]
congr 1
omega
/-- **A member's capital target is odd** whenever its cash is its money. -/
theorem capitalTarget_odd (e p net : Int) (he : e ≠ 0) (h : cashIsMoney e p net) :
capitalTarget (-e) p (-net) = reverseTarget (capitalTarget e p net) := by
unfold capitalTarget reverseTarget
rw [capitalParts_neg e p net he h, withSign_neg _ _ he, withSign_neg _ _ he]
congr 1
by_cases hc : (capitalParts e p net).1 + (capitalParts e p net).2 = 0
· simp [hc, Direction.flip]
· simp [hc, Direction.of_neg]
/-- With money moved, or the parties' own accounts moved, the rest of the
target is odd too. -/
theorem moneyTarget_odd (net own debits : Int) (h : net ≠ 0 ∨ own ≠ 0) :
moneyTarget (-net) (-own) debits = reverseTarget (moneyTarget net own debits) := by
unfold moneyTarget reverseTarget
by_cases hn : net = 0
· have ho : own ≠ 0 := by omega
have : ¬ (-own = 0) := by omega
simp [hn, ho, this, Direction.flip]
· have : ¬ (-net = 0) := by omega
simp [hn, this, Direction.of_neg]
/-- **The target is odd** (rules.md B-35 item 3, B-9): negating an entry's
lines negates its capital movement, its money net and its own-account
movement, while the property beside a capital movement comes from the
other side of the lines and keeps its size; the result is the original's
`reverseTarget`, but for the debits fallback (nothing moved: a sign means
nothing there) and a member's entry whose cash isn't its money. The
engine's reversal arm, not the lines, gives every reversal its target. -/
theorem partyTarget_odd (capital : Option (Int × Int)) (net own debits : Int)
(h : (∃ e p, capital = some (e, p) ∧ e ≠ 0 ∧ cashIsMoney e p net) ∨
((∀ e p, capital = some (e, p) → e = 0) ∧ (net ≠ 0 ∨ own ≠ 0))) :
partyTarget (capital.map fun c => (-c.1, c.2)) (-net) (-own) debits =
reverseTarget (partyTarget capital net own debits) := by
cases capital with
| none =>
simp only [Option.map, partyTarget]
apply moneyTarget_odd
rcases h with ⟨_, _, hc, _⟩ | ⟨_, h⟩
· cases hc
· exact h
| some c =>
obtain ⟨e, p⟩ := c
simp only [Option.map, partyTarget]
by_cases he : e = 0
· have : ¬ (-e ≠ 0) := by omega
simp only [he, ne_eq, not_true_eq_false, ite_false, Int.neg_zero]
apply moneyTarget_odd
rcases h with ⟨e', p', hc, he', _⟩ | ⟨_, h⟩
· simp at hc; omega
· exact h
· have : -e ≠ 0 := by omega
simp only [ne_eq, he, this, not_false_eq_true, ite_true]
rcases h with ⟨e', p', hc, _, hm⟩ | ⟨hz, _⟩
· simp only [Option.some.injEq, Prod.mk.injEq] at hc
obtain ⟨rfl, rfl⟩ := hc
exact capitalTarget_odd e p net he hm
· exact absurd (hz e p rfl) he
/-- **A reversal's movement over any accounts is the original's negated**
(so the equity movement a member's target reads flips with it): summed
over a set of accounts, `movement_reversal` account by account. -/
theorem sumOver_movement_reversal (as : List Nat) (ls : List Line) :
sumOver (fun a => movement a (reversal ls)) as = -sumOver (fun a => movement a ls) as := by
have : (fun a => movement a (reversal ls)) = (fun a => -movement a ls) := by
funext a; exact movement_reversal a ls
rw [this, sumOver_neg]
end Wanderbooks
-324
View File
@@ -1,324 +0,0 @@
/-!
# Proration by days: the parts sum to the total, and none is negative,
for any number of parts
Mirrors `crates/ledger-core/src/kernel.rs` `prorated_through` and
`prorate_by_days` (depreciation, rules.md B-15; daily schedules, B-16).
The kernel computes, through any day of a span, the elapsed share of the
span as a fraction (the months held before, each as days held over days in
the month, plus the days of this one; in the last month, what the others
leave spread over its days). Here that share is `w / V`: `V` the whole
span over any common denominator, `w` the elapsed part of it, which the
walk only ever raises. The charge through it is `cum`: the total times the
share, rounded half up to a multiple of `unit`, capped at the total, and
the total itself once the whole span has elapsed (the kernel's last day,
exact even for a total that isn't a whole number of units).
Kani proves the kernel's laws for up to three parts at bounded sizes
(`prorate_parts_sum_to_total`, `prorate_last_part_absorbs_the_remainder`),
and each charge within half a unit of its exact share
(`a_months_charge_is_within_half_a_cent` and its siblings). Here they
hold for any number of parts and any sizes: `cum` never falls as the
share grows, never exceeds the total, and ends at it, so the parts
(differences of `cum` at each part's end) telescope to the total and are
each at least zero; each charge is within half a unit of its exact share,
so each part is within one unit of its days times the rate (`cum_near`,
`part_near`). The last section writes out the kernel's two formulas and
proves them `cum` (`chargeMid_eq_cum`, `chargeLast_eq_cum`), so these are
laws of the kernel's own arithmetic, not only of the model.
-/
namespace Wanderbooks.Prorate
/-- `num / den` rounded half up to a multiple of `unit`: the kernel's
`round_to_unit` (its `r >= step - r` is `2r >= step`, which is the floor of
`num / step + 1/2`). -/
def roundUnit (num den unit : Nat) : Nat :=
unit * ((2 * num + den * unit) / (2 * den * unit))
/-- The charge of total `t` once `w` of the span's `V` has elapsed. -/
def cum (t unit V w : Nat) : Nat :=
if w = V then t else min t (roundUnit (t * w) V unit)
/-- Rounding never falls as the amount rounded grows. -/
theorem roundUnit_mono (den unit : Nat) {a b : Nat} (h : a ≤ b) :
roundUnit a den unit ≤ roundUnit b den unit := by
unfold roundUnit
apply Nat.mul_le_mul_left
apply Nat.div_le_div_right
omega
/-- The charge never exceeds the total. -/
theorem cum_le (t unit V w : Nat) : cum t unit V w ≤ t := by
unfold cum
split
· exact Nat.le_refl t
· exact Nat.min_le_left _ _
/-- Once the whole span has elapsed, the charge is the total exactly. -/
theorem cum_full (t unit V : Nat) : cum t unit V V = t := by
simp [cum]
/-- Before anything has elapsed, nothing is charged. -/
theorem cum_zero (t unit V : Nat) (hV : 0 < V) (hu : 0 < unit) : cum t unit V 0 = 0 := by
have hne : (0 : Nat) ≠ V := by omega
have hlt : V * unit < 2 * V * unit := by
have : 0 < V * unit := Nat.mul_pos hV hu
rw [Nat.mul_assoc]
omega
simp [cum, hne, roundUnit, Nat.div_eq_of_lt hlt]
/-- **The charge never falls** as the elapsed share grows, up to the
whole span. -/
theorem cum_mono (t unit V : Nat) {w w' : Nat} (h : w ≤ w') (hw' : w' ≤ V) :
cum t unit V w ≤ cum t unit V w' := by
by_cases e' : w' = V
· subst e'
rw [cum_full]
exact cum_le t unit w' w
· have e : w ≠ V := by omega
simp only [cum, e, e', ite_false]
have r := roundUnit_mono V unit (Nat.mul_le_mul_left t h)
omega
/-- The parts of a split: at each part's end (`w` its elapsed share), the
charge through it less the charge before it (the kernel's `out[i]`,
`prorate_by_days`). -/
def parts (t unit V : Nat) : Nat → List Nat → List Int
| _, [] => []
| prev, w :: ws => ((cum t unit V w : Int) - cum t unit V prev) :: parts t unit V w ws
/-- **The parts telescope**: they sum to the charge at the last part's end
less the charge where they start (the shape of `runPart_telescopes`). -/
theorem parts_telescope (t unit V : Nat) (prev : Nat) (ws : List Nat) :
(parts t unit V prev ws).sum = (cum t unit V (ws.getLastD prev) : Int) - cum t unit V prev := by
induction ws generalizing prev with
| nil => simp [parts]
| cons w rest ih =>
simp only [parts, List.sum_cons, ih]
cases rest with
| nil => simp
| cons _ _ => simp only [List.getLastD_cons]; omega
/-- **The parts sum to the total**, for any number of parts: a span
walked from nothing elapsed to all of it. -/
theorem prorate_total (t unit V : Nat) (hV : 0 < V) (hu : 0 < unit) (ws : List Nat)
(hlast : ws.getLastD 0 = V) : (parts t unit V 0 ws).sum = t := by
rw [parts_telescope, hlast, cum_full, cum_zero t unit V hV hu]
simp
/-- The parts' ends rise: each at least the one before, none past the
span. -/
def Rising (V : Nat) : Nat → List Nat → Prop
| _, [] => True
| prev, w :: ws => prev ≤ w ∧ w ≤ V ∧ Rising V w ws
/-- **No part is negative** when the parts' ends rise, for any number of
parts. -/
theorem prorate_nonneg (t unit V : Nat) (prev : Nat) (ws : List Nat) (h : Rising V prev ws) :
∀ x ∈ parts t unit V prev ws, 0 ≤ x := by
induction ws generalizing prev with
| nil => simp [parts]
| cons w rest ih =>
obtain ⟨hpw, hwV, hrest⟩ := h
intro x hx
simp only [parts, List.mem_cons] at hx
rcases hx with hx | hx
· subst hx
have := cum_mono t unit V hpw hwV
omega
· exact ih w hrest x hx
/-- **Each part is within one unit of its exact share** when each charge
is within half a unit of its exact one (Kani's
`a_months_charge_is_within_half_a_cent` and its three siblings prove
that of the kernel): a part is the difference of two charges over the same
denominator `D` (W, the span in MONTH_L-ths of a month), so its error is
at most the two halves. With `x - y` = total × days × MONTH_L / days in
the month and `D` = months × MONTH_L, dividing through by MONTH_L / days in
the month gives the plan's form: |part × months × days in month − total ×
days| <= unit × months × days in month. -/
theorem part_within_a_unit (a b D x y u : Int)
(ha : -(u * D) ≤ 2 * (a * D - x) ∧ 2 * (a * D - x) ≤ u * D)
(hb : -(u * D) ≤ 2 * (b * D - y) ∧ 2 * (b * D - y) ≤ u * D) :
-(u * D) ≤ (a - b) * D - (x - y) ∧ (a - b) * D - (x - y) ≤ u * D := by
rw [Int.sub_mul]
omega
/-! ## The kernel's own formula
`prorated_through` charges in two ways. Through a part but the span's
last, the elapsed share is `e / W` (`W` = months × MONTH_L, `e` = before
+ k × MONTH_L / days in the month): `chargeMid`. Through `k` of the `d`
days of the last part, after `b` of `W`, it is `(b·d + (W − b)·k) / (W·d)`,
and the total itself on its last day: `chargeLast`. Both are `cum`, over
`W` and over `W·d` (`chargeMid_eq_cum`, `chargeLast_eq_cum`), and the two
meet where the last month starts (`chargeLast_start`, rounding being
unchanged when the amount and its denominator are scaled together). So
`cum`'s laws are the kernel's, at any size: through the last month the
charge never falls (`chargeLast_mono`), the split of any number of parts
sums to the total with none negative (`kernel_parts_total`,
`kernel_parts_nonneg`), and each part but the last is within one unit of
its days times the rate (`part_near`). A calendar walk keeps every part's
end short of the span's (rules.md B-15: the first month is at most one,
then whole months), which is the hypothesis `e < W`. -/
/-- **Rounding is within half a unit**, at any size (a tie goes up):
`2·den·r ≤ 2·num + den·unit` and `2·num < 2·den·r + den·unit`. -/
theorem roundUnit_near (num den unit : Nat) (hd : 0 < den) (hu : 0 < unit) :
2 * den * roundUnit num den unit ≤ 2 * num + den * unit ∧
2 * num < 2 * den * roundUnit num den unit + den * unit := by
unfold roundUnit
have hs : 0 < 2 * den * unit := Nat.mul_pos (Nat.mul_pos (by omega) hd) hu
have hdm := Nat.div_add_mod (2 * num + den * unit) (2 * den * unit)
have hml := Nat.mod_lt (2 * num + den * unit) hs
generalize (2 * num + den * unit) / (2 * den * unit) = q at *
generalize (2 * num + den * unit) % (2 * den * unit) = m at *
have e : 2 * den * (unit * q) = 2 * den * unit * q := by
rw [Nat.mul_assoc (2 * den) unit q]
have hS : 2 * den * unit = 2 * (den * unit) := Nat.mul_assoc 2 den unit
rw [e]
generalize 2 * den * unit * q = P at *
generalize 2 * den * unit = S at *
generalize den * unit = DU at *
omega
/-- Rounding is unchanged when the amount and its denominator are scaled
together. -/
theorem roundUnit_scale (n d u c : Nat) (hc : 0 < c) :
roundUnit (c * n) (c * d) u = roundUnit n d u := by
unfold roundUnit
have h1 : 2 * (c * n) + c * d * u = c * (2 * n + d * u) := by
rw [Nat.mul_add, Nat.mul_left_comm 2 c n, Nat.mul_assoc c d u]
have h2 : 2 * (c * d) * u = c * (2 * d * u) := by
rw [Nat.mul_left_comm 2 c d, Nat.mul_assoc c (2 * d) u]
rw [h1, h2, Nat.mul_div_mul_left _ _ hc]
/-- **The charge is within half a unit of its exact share** `t·w / V`, at
any size, short of the span's end (where it is the total): the cap at the
total included. -/
theorem cum_near (t u V w : Nat) (hV : 0 < V) (hu : 0 < u) (hw : w < V) :
2 * V * cum t u V w ≤ 2 * (t * w) + V * u ∧
2 * (t * w) < 2 * V * cum t u V w + V * u := by
have hne : w ≠ V := by omega
simp only [cum, hne, ite_false]
obtain ⟨h1, h2⟩ := roundUnit_near (t * w) V u hV hu
have htw : t * w ≤ t * V := Nat.mul_le_mul_left t (Nat.le_of_lt hw)
have hVu : 0 < V * u := Nat.mul_pos hV hu
by_cases hc : t ≤ roundUnit (t * w) V u
· rw [Nat.min_eq_left hc]
have hm : 2 * V * t ≤ 2 * V * roundUnit (t * w) V u := Nat.mul_le_mul_left _ hc
have e : 2 * V * t = 2 * (t * V) := by rw [Nat.mul_assoc, Nat.mul_comm V t]
constructor <;> omega
· rw [Nat.min_eq_right (by omega)]
exact ⟨h1, h2⟩
/-- **Each part is within one unit of its exact share**, at any size: a
part `c' − c` of the charge (its ends `w ≤ w'` short of the span's end),
against its exact share `t·(w' − w) / V`:
`|(c' − c)·V − t·(w' − w)| ≤ u·V`, written without subtraction. Over
the span `V` = months × MONTH_L and `w' − w` = days × MONTH_L / days in
the month, this is the plan's "each part equals days × rate within one
unit" (plan/served.md P3 defect 9). -/
theorem part_near (t u V w w' : Nat) (hV : 0 < V) (hu : 0 < u) (hw' : w' < V)
(h : w ≤ w') :
cum t u V w' * V + t * w ≤ cum t u V w * V + t * w' + u * V ∧
cum t u V w * V + t * w' ≤ cum t u V w' * V + t * w + u * V := by
obtain ⟨a1, a2⟩ := cum_near t u V w' hV hu hw'
obtain ⟨b1, b2⟩ := cum_near t u V w hV hu (by omega)
have e1 : 2 * V * cum t u V w' = 2 * (cum t u V w' * V) := by
rw [Nat.mul_assoc, Nat.mul_comm V]
have e2 : 2 * V * cum t u V w = 2 * (cum t u V w * V) := by
rw [Nat.mul_assoc, Nat.mul_comm V]
have e3 : V * u = u * V := Nat.mul_comm V u
constructor <;> omega
/-- **A total in whole units is charged in whole units**: every charge is
then a multiple of the unit, and so is every part (a difference of two). -/
theorem cum_dvd (t u V w : Nat) (h : u ∣ t) : u ∣ cum t u V w := by
unfold cum roundUnit
split
· exact h
· rcases Nat.le_total t (u * ((2 * (t * w) + V * u) / (2 * V * u))) with hc | hc
· rw [Nat.min_eq_left hc]; exact h
· rw [Nat.min_eq_right hc]; exact Nat.dvd_mul_right u _
/-- The kernel's charge through a part but the span's last
(`prorated_through`, `last = false`): `e` of the span's `W`. -/
def chargeMid (t u W e : Nat) : Nat := min t (roundUnit (t * e) W u)
/-- The kernel's charge through `k` of the `d` days of the span's last
part, after `b` of `W` (`prorated_through`, `last = true`). -/
def chargeLast (t u W b d k : Nat) : Nat :=
if k = d then t else min t (roundUnit (t * (b * d + (W - b) * k)) (W * d) u)
/-- A part but the last, short of the span's end, is charged `cum`. -/
theorem chargeMid_eq_cum (t u W e : Nat) (h : e < W) : chargeMid t u W e = cum t u W e := by
have : e ≠ W := by omega
simp [chargeMid, cum, this]
/-- The span's last part is charged `cum` over `W·d`. -/
theorem chargeLast_eq_cum (t u W b d k : Nat) (hb : b < W) (hk : k ≤ d) :
chargeLast t u W b d k = cum t u (W * d) (b * d + (W - b) * k) := by
by_cases hkd : k = d
· subst hkd
have e : b * k + (W - b) * k = W * k := by
rw [← Nat.add_mul, Nat.add_sub_of_le (Nat.le_of_lt hb)]
simp [chargeLast, cum, e]
· have hlt : (W - b) * k < (W - b) * d :=
(Nat.mul_lt_mul_left (by omega : 0 < W - b)).mpr (by omega)
have e : b * d + (W - b) * d = W * d := by
rw [← Nat.add_mul, Nat.add_sub_of_le (Nat.le_of_lt hb)]
have hne : b * d + (W - b) * k ≠ W * d := by omega
simp [chargeLast, cum, hkd, hne]
/-- **The last month starts where the month before it ends**: its charge
through none of its days is the charge through the end of the part before
it. -/
theorem chargeLast_start (t u W b d : Nat) (hd : 0 < d) :
chargeLast t u W b d 0 = chargeMid t u W b := by
have hne : (0 : Nat) ≠ d := by omega
have e1 : t * (b * d + (W - b) * 0) = d * (t * b) := by
rw [Nat.mul_zero, Nat.add_zero, ← Nat.mul_assoc, Nat.mul_comm (t * b) d]
have e2 : W * d = d * W := Nat.mul_comm W d
simp only [chargeLast, chargeMid, hne, ite_false, e1, e2, roundUnit_scale _ _ _ _ hd]
/-- **The charge never falls through the span's last month**, at any size:
for days `k ≤ k'` of it. -/
theorem chargeLast_mono (t u W b d k k' : Nat) (hb : b < W) (hk : k ≤ k') (hk' : k' ≤ d) :
chargeLast t u W b d k ≤ chargeLast t u W b d k' := by
rw [chargeLast_eq_cum t u W b d k hb (by omega), chargeLast_eq_cum t u W b d k' hb hk']
apply cum_mono
· exact Nat.add_le_add_left (Nat.mul_le_mul_left _ hk) _
· have : (W - b) * k' ≤ (W - b) * d := Nat.mul_le_mul_left _ hk'
have e : b * d + (W - b) * d = W * d := by
rw [← Nat.add_mul, Nat.add_sub_of_le (Nat.le_of_lt hb)]
omega
/-- The kernel's split (`prorate_by_days`): each part but the last the
charge at its end (`es`, each short of the span's end, `chargeMid_eq_cum`)
less the charge before it; the last, the total less the charge at the end
of the part before it (its last day is charged the total). -/
def kernelParts (t u W : Nat) (es : List Nat) : List Int :=
parts t u W 0 es ++ [(t : Int) - cum t u W (es.getLastD 0)]
/-- **The kernel's parts sum to the total**, for any number of parts. -/
theorem kernel_parts_total (t u W : Nat) (hW : 0 < W) (hu : 0 < u) (es : List Nat) :
(kernelParts t u W es).sum = t := by
simp only [kernelParts, List.sum_append, parts_telescope, cum_zero t u W hW hu,
List.sum_cons, List.sum_nil]
omega
/-- **No part of the kernel's split is negative**, for any number of
parts, when their ends rise within the span. -/
theorem kernel_parts_nonneg (t u W : Nat) (es : List Nat) (h : Rising W 0 es) :
∀ x ∈ kernelParts t u W es, 0 ≤ x := by
intro x hx
simp only [kernelParts, List.mem_append, List.mem_singleton] at hx
rcases hx with hx | hx
· exact prorate_nonneg t u W 0 es h x hx
· subst hx
have := cum_le t u W (es.getLastD 0)
omega
end Wanderbooks.Prorate
-683
View File
@@ -1,683 +0,0 @@
import Wanderbooks.Entry
/-!
# Balances and statements
Mirrors `kernel::normal_balance`, `kernel::columns`,
`Ledger::account_balance`, and `reports::trial_balance`; and the statement
of cash flows (`kernel::take`, `kernel::apply_cash`, `kernel::entry_flows`,
`kernel::constructive`, `cashflow::cash_flow`'s footing and reconciliation
checks).
-/
namespace Wanderbooks
/-- A chart of accounts: each account's code and type. -/
abbrev Chart := List (Nat × AccountType)
/-- The chart's codes. -/
def codes (c : Chart) : List Nat := c.map Prod.fst
@[simp] theorem codes_nil : codes [] = [] := rfl
@[simp] theorem codes_cons (a : Nat) (t : AccountType) (c : Chart) :
codes ((a, t) :: c) = a :: codes c := rfl
/-- An account's balance on its normal side (`kernel::normal_balance`). -/
def balance (t : AccountType) (m : Int) : Int := signed t.normal m
/-- **A normal-side line raises a balance by its amount; an opposite-side
line lowers it.** -/
theorem balance_after_line (t : AccountType) (m : Int) (s : Side) (a : Int) :
balance t (m + signed s a) = balance t m + (if s = t.normal then a else -a) := by
cases t <;> cases s <;> simp [balance, AccountType.normal, signed] <;> omega
/-- The total balance of every account of type `t`. -/
def typeTotal (t : AccountType) (ls : List Line) : Chart → Int
| [] => 0
| (a, t') :: rest => (if t' = t then balance t' (movement a ls) else 0) + typeTotal t ls rest
/-- The accounting equation's two sides differ by the net movement of the
chart's accounts. -/
theorem equation_gap (ls : List Line) (c : Chart) :
typeTotal .asset ls c + typeTotal .expense ls c
- typeTotal .liability ls c - typeTotal .equity ls c - typeTotal .revenue ls c
= sumOver (fun a => movement a ls) (codes c) := by
induction c with
| nil => rfl
| cons x c ih =>
obtain ⟨a, t⟩ := x
cases t <;> simp [typeTotal, balance, AccountType.normal, signed] <;> omega
/-- **The accounting equation.** For lines that net to zero, over a chart
with distinct codes covering every line's account:
Assets = Liabilities + Equity + (Revenue - Expenses). -/
theorem accounting_equation (ls : List Line) (c : Chart) (hd : Distinct (codes c))
(hcov : ∀ l ∈ ls, l.account ∈ codes c) (hnet : net ls = 0) :
typeTotal .asset ls c
= typeTotal .liability ls c + typeTotal .equity ls c
+ (typeTotal .revenue ls c - typeTotal .expense ls c) := by
have := equation_gap ls c
rw [sum_movements _ hd ls hcov, hnet] at this
omega
/-! ## Trial balance -/
/-- The debit column for a movement (`kernel::columns`). -/
def colDebit (m : Int) : Int := if 0 < m then m else 0
/-- The credit column for a movement (`kernel::columns`). -/
def colCredit (m : Int) : Int := if 0 < m then 0 else -m
theorem columns_spec (m : Int) :
0 ≤ colDebit m ∧ 0 ≤ colCredit m ∧ (colDebit m = 0 ∨ colCredit m = 0)
∧ colDebit m - colCredit m = m := by
unfold colDebit colCredit; split <;> omega
/-- The trial balance's debit column total. -/
def tbDebits (ls : List Line) (as : List Nat) : Int := sumOver (fun a => colDebit (movement a ls)) as
/-- The trial balance's credit column total. -/
def tbCredits (ls : List Line) (as : List Nat) : Int :=
sumOver (fun a => colCredit (movement a ls)) as
theorem tb_gap (ls : List Line) (as : List Nat) :
tbDebits ls as - tbCredits ls as = sumOver (fun a => movement a ls) as := by
induction as with
| nil => rfl
| cons a as ih =>
simp only [tbDebits, tbCredits, sumOver_cons] at ih ⊢
have := (columns_spec (movement a ls)).2.2.2
omega
/-- **The trial balance balances** for lines that net to zero. -/
theorem trial_balance_balances (ls : List Line) (as : List Nat) (hd : Distinct as)
(hcov : ∀ l ∈ ls, l.account ∈ as) (hnet : net ls = 0) :
tbDebits ls as = tbCredits ls as := by
have := tb_gap ls as
rw [sum_movements as hd ls hcov, hnet] at this
omega
/-- And conversely: a balanced trial balance means the lines net to zero.
The trial balance is a complete check of the books' arithmetic. -/
theorem trial_balance_iff (ls : List Line) (as : List Nat) (hd : Distinct as)
(hcov : ∀ l ∈ ls, l.account ∈ as) :
tbDebits ls as = tbCredits ls as ↔ net ls = 0 := by
have := tb_gap ls as
rw [sum_movements as hd ls hcov] at this
omega
/-! ## The statement of cash flows (rules.md B-14)
Mirrors `kernel::Flow`, `kernel::take`, `kernel::apply_cash` and
`kernel::entry_flows`, and the identities `cashflow::cash_flow` checks at
runtime: the sections sum to the cash accounts' change, a reversal's flows
are its original's negated, and net income reconciles to operating cash.
Lines are tagged per entry (`F : List Line → Line → Flow`), as the engine
tags them: a revenue or expense line is operating in one entry and
investing in another (rule 4), and a reversal is tagged by its chain's
root. The theorems hold for every such tagging; their hypotheses say what
the engine guarantees (the cash tag follows the account; revenue and
expense lines are operating or investing; a reversal's lines take its
original's tags). A line the engine splits between two sections (the bill
split, rule 12) is two lines here; a split keeps the entry's net. -/
/-- Where a line falls on the statement of cash flows (`kernel::Flow`). -/
inductive Flow where
| cash
| operating
| investing
| financing
deriving DecidableEq, Repr
/-- The net movement of the lines `f` tags `k`. -/
def secNet (f : Line → Flow) (k : Flow) : List Line → Int
| [] => 0
| l :: ls => (if f l = k then l.signed else 0) + secNet f k ls
@[simp] theorem secNet_nil (f : Line → Flow) (k : Flow) : secNet f k [] = 0 := rfl
@[simp] theorem secNet_cons (f : Line → Flow) (k : Flow) (l : Line) (ls : List Line) :
secNet f k (l :: ls) = (if f l = k then l.signed else 0) + secNet f k ls := rfl
/-- **Every line is in exactly one place**: an entry's net is its cash plus
its three sections' movements. -/
theorem net_splits_by_flow (f : Line → Flow) (ls : List Line) :
net ls = secNet f .cash ls + secNet f .operating ls + secNet f .investing ls
+ secNet f .financing ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [net_cons, secNet_cons, ih]
cases f l <;> simp <;> omega
/-- The cash one section takes from what is left (`kernel::take`): only a
section moving against the cash, never more than its own movement. -/
def take (rem n : Int) : Int :=
if 0 < rem ∧ n < 0 then min rem (-n) else if rem < 0 ∧ 0 < n then max rem (-n) else 0
/-- `kernel::apply_cash`: the cash applied to each movement in order, and
what is left. -/
def applyCash : Int → List Int → List Int × Int
| rem, [] => ([], rem)
| rem, n :: ns => (take rem n :: (applyCash (rem - take rem n) ns).1,
(applyCash (rem - take rem n) ns).2)
/-- A sum of integers. -/
def isum : List Int → Int
| [] => 0
| x :: xs => x + isum xs
@[simp] theorem isum_nil : isum [] = 0 := rfl
@[simp] theorem isum_cons (x : Int) (xs : List Int) : isum (x :: xs) = x + isum xs := rfl
theorem isum_append (xs ys : List Int) : isum (xs ++ ys) = isum xs + isum ys := by
induction xs with
| nil => simp
| cons x xs ih => simp only [List.cons_append, isum_cons, ih]; omega
theorem isum_neg (xs : List Int) : isum (xs.map (fun x => -x)) = -isum xs := by
induction xs with
| nil => rfl
| cons x xs ih => simp only [List.map_cons, isum_cons, ih]; omega
/-- Applying cash invents and loses nothing: the parts and what is left
sum to the cash. -/
theorem applyCash_conserves (rem : Int) (ns : List Int) :
isum (applyCash rem ns).1 + (applyCash rem ns).2 = rem := by
induction ns generalizing rem with
| nil => simp [applyCash]
| cons n ns ih =>
simp only [applyCash, isum_cons]
have := ih (rem - take rem n)
omega
theorem applyCash_length (rem : Int) (ns : List Int) :
(applyCash rem ns).1.length = ns.length := by
induction ns generalizing rem with
| nil => rfl
| cons n ns ih => simp [applyCash, ih]
theorem take_zero (n : Int) : take 0 n = 0 := by
simp [take]
/-- With no cash, nothing is applied and nothing is left. -/
theorem applyCash_zero (ns : List Int) : (applyCash 0 ns).2 = 0 := by
induction ns with
| nil => rfl
| cons n ns ih => simp [applyCash, take_zero, ih]
/-- Cash in is used up when the movements against it cover it. -/
theorem applyCash_exhausts_pos (rem : Int) (ns : List Int) (h0 : 0 ≤ rem)
(h : rem + isum ns ≤ 0) : (applyCash rem ns).2 = 0 := by
induction ns generalizing rem with
| nil => simp [applyCash] at h ⊢; omega
| cons n ns ih =>
simp only [applyCash]
simp only [isum_cons] at h
by_cases hr : rem = 0
· subst hr; simp [take_zero, applyCash_zero]
· by_cases hn : n < 0
· by_cases hle : -n ≤ rem
· have ht : take rem n = -n := by
simp only [take]; rw [ite_eq_left (by omega)]; omega
rw [ht]; exact ih _ (by omega) (by omega)
· have ht : take rem n = rem := by
simp only [take]; rw [ite_eq_left (by omega)]; omega
rw [ht, Int.sub_self]; exact applyCash_zero ns
· have ht : take rem n = 0 := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_right (by omega)]
rw [ht, Int.sub_zero]; exact ih _ h0 (by omega)
/-- Cash out is used up when the movements against it cover it. -/
theorem applyCash_exhausts_neg (rem : Int) (ns : List Int) (h0 : rem ≤ 0)
(h : 0 ≤ rem + isum ns) : (applyCash rem ns).2 = 0 := by
induction ns generalizing rem with
| nil => simp [applyCash] at h ⊢; omega
| cons n ns ih =>
simp only [applyCash]
simp only [isum_cons] at h
by_cases hr : rem = 0
· subst hr; simp [take_zero, applyCash_zero]
· by_cases hn : 0 < n
· by_cases hle : rem ≤ -n
· have ht : take rem n = -n := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_left (by omega)]; omega
rw [ht]; exact ih _ (by omega) (by omega)
· have ht : take rem n = rem := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_left (by omega)]; omega
rw [ht, Int.sub_self]; exact applyCash_zero ns
· have ht : take rem n = 0 := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_right (by omega)]
rw [ht, Int.sub_zero]; exact ih _ h0 (by omega)
/-- **Balanced, the cash is used up**: when the cash and the movements sum
to zero, nothing is left over. -/
theorem applyCash_exhausts (rem : Int) (ns : List Int) (h : rem + isum ns = 0) :
(applyCash rem ns).2 = 0 := by
rcases Int.le_total 0 rem with h0 | h0
· exact applyCash_exhausts_pos rem ns h0 (by omega)
· exact applyCash_exhausts_neg rem ns h0 (by omega)
theorem take_neg (r n : Int) : take (-r) (-n) = -take r n := by
simp only [take]
by_cases h1 : 0 < r ∧ n < 0
· rw [ite_eq_right (by omega), ite_eq_left (by omega), ite_eq_left h1]; omega
· by_cases h2 : r < 0 ∧ 0 < n
· rw [ite_eq_left (by omega), ite_eq_right h1, ite_eq_left h2]; omega
· rw [ite_eq_right (by omega), ite_eq_right (by omega), ite_eq_right h1, ite_eq_right h2]; omega
/-- Applying minus the cash to minus the movements gives minus the parts:
what lets a reversal mirror its original. -/
theorem applyCash_neg (rem : Int) (ns : List Int) :
applyCash (-rem) (ns.map (fun x => -x))
= ((applyCash rem ns).1.map (fun x => -x), -(applyCash rem ns).2) := by
induction ns generalizing rem with
| nil => rfl
| cons n ns ih =>
simp only [List.map_cons, applyCash, take_neg]
have : -rem - -take rem n = -(rem - take rem n) := by omega
rw [this, ih]
/-- An entry's cash: the net of the lines tagged cash. -/
def cashOf (F : List Line → Line → Flow) (e : List Line) : Int := secNet (F e) .cash e
/-- An entry's section movements, `[operating, investing, financing]`. -/
def moves (F : List Line → Line → Flow) (e : List Line) : List Int :=
[secNet (F e) .operating e, secNet (F e) .investing e, secNet (F e) .financing e]
/-- An entry's cash flows per section (`kernel::entry_flows`). -/
def flows (F : List Line → Line → Flow) (e : List Line) : List Int :=
(applyCash (cashOf F e) (moves F e)).1
/-- **An entry's cash flows sum to its cash** (`entry_flows_sum`): for a
balanced entry, the sections' cash is exactly the cash that moved. -/
theorem entry_flows_sum (F : List Line → Line → Flow) (e : List Line) (h : net e = 0) :
isum (flows F e) = cashOf F e := by
have hb := net_splits_by_flow (F e) e
have hx : (applyCash (cashOf F e) (moves F e)).2 = 0 := by
apply applyCash_exhausts
simp only [moves, cashOf, isum_cons, isum_nil]
omega
have := applyCash_conserves (cashOf F e) (moves F e)
simp only [flows]
omega
theorem flows_length (F : List Line → Line → Flow) (e : List Line) : (flows F e).length = 3 := by
simp [flows, applyCash_length, moves]
theorem secNet_reversal (f g : Line → Flow) (k : Flow) (ls : List Line)
(h : ∀ l ∈ ls, g l.reverse = f l) : secNet g k (reversal ls) = -secNet f k ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [reversal, List.map_cons] at ih ⊢
simp only [secNet_cons, h l (by simp), Line.reverse_signed,
ih (fun m hm => h m (by simp [hm]))]
split <;> omega
/-- **A reversal's flows are its original's, negated** (`flows_reversal`),
when its lines take its original's tags: what lets an entry and its
reversal drop out of the statement together (rules.md B-14 rule 6). -/
theorem flows_reversal (F : List Line → Line → Flow) (e : List Line)
(hF : ∀ l ∈ e, F (reversal e) l.reverse = F e l) :
flows F (reversal e) = (flows F e).map (fun x => -x) := by
simp only [flows, cashOf, moves]
rw [secNet_reversal (F e) (F (reversal e)) .cash e hF,
secNet_reversal (F e) (F (reversal e)) .operating e hF,
secNet_reversal (F e) (F (reversal e)) .investing e hF,
secNet_reversal (F e) (F (reversal e)) .financing e hF]
have := applyCash_neg (secNet (F e) .cash e)
[secNet (F e) .operating e, secNet (F e) .investing e, secNet (F e) .financing e]
simp only [List.map_cons, List.map_nil] at this
rw [this]
theorem isum_three (xs : List Int) (h : xs.length = 3) :
isum xs = xs.getD 0 0 + xs.getD 1 0 + xs.getD 2 0 := by
match xs, h with
| [a, b, c], _ => simp; omega
/-! ### What a member or lender pays or receives for the company (rule 11)
`kernel::constructive` (D-42): what is left unsettled of an entry's
kinds that can pay or receive for the company (`s`, a financing liability
or a member's capital) settles what is left of the kinds they pay or
receive for (`u`), as if through the cash accounts. The engine sums the
parts by section into an entry's constructive triple; the entry theorems
below take any triple that nets to zero (and, for reversals, mirrors),
which `constructive_nets` and `constructive_neg` give the kernel's. -/
/-- The credits among some movements, `Σ max(-m, 0)`: what cash in can
settle. -/
def creditTotal : List Int → Int
| [] => 0
| m :: ms => max (-m) 0 + creditTotal ms
/-- The debits among some movements, `Σ max(m, 0)`: what cash out can
settle. -/
def debitTotal : List Int → Int
| [] => 0
| m :: ms => max m 0 + debitTotal ms
theorem creditTotal_nonneg (ms : List Int) : 0 ≤ creditTotal ms := by
induction ms with
| nil => simp [creditTotal]
| cons m ms ih => simp only [creditTotal]; omega
theorem debitTotal_nonneg (ms : List Int) : 0 ≤ debitTotal ms := by
induction ms with
| nil => simp [debitTotal]
| cons m ms ih => simp only [debitTotal]; omega
theorem creditTotal_neg (ms : List Int) :
creditTotal (ms.map (fun x => -x)) = debitTotal ms := by
induction ms with
| nil => rfl
| cons m ms ih => simp only [List.map_cons, creditTotal, debitTotal, ih]; omega
theorem debitTotal_neg (ms : List Int) :
debitTotal (ms.map (fun x => -x)) = creditTotal ms := by
induction ms with
| nil => rfl
| cons m ms ih =>
simp only [List.map_cons, creditTotal, debitTotal, ih]
/-- Cash in is used up when the credits cover it (whatever the debits). -/
theorem applyCash_exhausts_in (rem : Int) (ns : List Int) (h0 : 0 ≤ rem)
(h : rem ≤ creditTotal ns) : (applyCash rem ns).2 = 0 := by
induction ns generalizing rem with
| nil => simp [applyCash, creditTotal] at h ⊢; omega
| cons n ns ih =>
simp only [applyCash]
simp only [creditTotal] at h
by_cases hr : rem = 0
· subst hr; simp [take_zero, applyCash_zero]
· by_cases hn : n < 0
· by_cases hle : -n ≤ rem
· have ht : take rem n = -n := by
simp only [take]; rw [ite_eq_left (by omega)]; omega
rw [ht]; exact ih _ (by omega) (by omega)
· have ht : take rem n = rem := by
simp only [take]; rw [ite_eq_left (by omega)]; omega
rw [ht, Int.sub_self]; exact applyCash_zero ns
· have ht : take rem n = 0 := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_right (by omega)]
rw [ht, Int.sub_zero]; exact ih _ h0 (by omega)
/-- Cash out is used up when the debits cover it (whatever the credits). -/
theorem applyCash_exhausts_out (rem : Int) (ns : List Int) (h0 : rem ≤ 0)
(h : -rem ≤ debitTotal ns) : (applyCash rem ns).2 = 0 := by
induction ns generalizing rem with
| nil => simp [applyCash, debitTotal] at h ⊢; omega
| cons n ns ih =>
simp only [applyCash]
simp only [debitTotal] at h
by_cases hr : rem = 0
· subst hr; simp [take_zero, applyCash_zero]
· by_cases hn : 0 < n
· by_cases hle : rem ≤ -n
· have ht : take rem n = -n := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_left (by omega)]; omega
rw [ht]; exact ih _ (by omega) (by omega)
· have ht : take rem n = rem := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_left (by omega)]; omega
rw [ht, Int.sub_self]; exact applyCash_zero ns
· have ht : take rem n = 0 := by
simp only [take]; rw [ite_eq_right (by omega), ite_eq_right (by omega)]
rw [ht, Int.sub_zero]; exact ih _ h0 (by omega)
/-- Which way the money went (`kernel::OnBehalf`). -/
inductive OnBehalf where
| paid
| received
deriving DecidableEq, Repr
/-- The other way: what a reversal does. -/
def OnBehalf.mirror : OnBehalf → OnBehalf
| .paid => .received
| .received => .paid
/-- The cash the sources take, + in (`kernel::constructive`): paid, the
smaller of the sources' credits and the uses' debits; received, minus the
smaller of the sources' debits and the uses' credits. -/
def onBehalfCash : OnBehalf → List Int → List Int → Int
| .paid, s, u => min (creditTotal s) (debitTotal u)
| .received, s, u => -min (debitTotal s) (creditTotal u)
/-- `kernel::constructive`: the sources' parts and the uses' parts. -/
def constructive (w : OnBehalf) (s u : List Int) : List Int × List Int :=
((applyCash (onBehalfCash w s u) s).1, (applyCash (-onBehalfCash w s u) u).1)
/-- **What a member or lender handled for the company nets to zero**
(`constructive_nets`; Kani `constructive_nets_to_zero`): the sources take
exactly what the uses give, so an entry's flows still sum to its cash. -/
theorem constructive_nets (w : OnBehalf) (s u : List Int) :
isum (constructive w s u).1 + isum (constructive w s u).2 = 0 := by
have hs := applyCash_conserves (onBehalfCash w s u) s
have hu := applyCash_conserves (-onBehalfCash w s u) u
have cs := creditTotal_nonneg s
have ds := debitTotal_nonneg s
have cu := creditTotal_nonneg u
have du := debitTotal_nonneg u
have ⟨xs, xu⟩ : (applyCash (onBehalfCash w s u) s).2 = 0 ∧
(applyCash (-onBehalfCash w s u) u).2 = 0 := by
cases w with
| paid =>
simp only [onBehalfCash]
exact ⟨applyCash_exhausts_in _ _ (by omega) (by omega),
applyCash_exhausts_out _ _ (by omega) (by omega)⟩
| received =>
simp only [onBehalfCash]
exact ⟨applyCash_exhausts_out _ _ (by omega) (by omega),
applyCash_exhausts_in _ _ (by omega) (by omega)⟩
simp only [constructive]
omega
theorem onBehalfCash_mirror (w : OnBehalf) (s u : List Int) :
onBehalfCash w.mirror (s.map (fun x => -x)) (u.map (fun x => -x))
= -onBehalfCash w s u := by
cases w <;> simp only [OnBehalf.mirror, onBehalfCash, creditTotal_neg, debitTotal_neg] <;> omega
/-- **The other way, minus the sources and uses give minus the parts**
(`constructive_neg`; Kani `constructive_mirrors`): a payment made for the
company and its reversal drop out together. -/
theorem constructive_neg (w : OnBehalf) (s u : List Int) :
constructive w.mirror (s.map (fun x => -x)) (u.map (fun x => -x))
= ((constructive w s u).1.map (fun x => -x), (constructive w s u).2.map (fun x => -x)) := by
simp only [constructive, onBehalfCash_mirror]
rw [applyCash_neg (onBehalfCash w s u) s, applyCash_neg (-onBehalfCash w s u) u]
/-- Three sections' figures, summed. -/
def sum3 (xs : List Int) : Int := xs.getD 0 0 + xs.getD 1 0 + xs.getD 2 0
@[simp] theorem sum3_cons (a b c : Int) : sum3 [a, b, c] = a + b + c := by
simp [sum3]
/-- **The kernel's parts, by section, net to zero**: split the uses into
operating ones then investing ones (`kernel::constructive` takes them in
that order), and the triple (operating, investing, financing = the
sources) the engine adds to an entry's flows sums to zero. -/
theorem constructive_sections_net (w : OnBehalf) (s uo ui : List Int) :
sum3 [isum ((constructive w s (uo ++ ui)).2.take uo.length),
isum ((constructive w s (uo ++ ui)).2.drop uo.length),
isum (constructive w s (uo ++ ui)).1] = 0 := by
have h := constructive_nets w s (uo ++ ui)
have hs := isum_append ((constructive w s (uo ++ ui)).2.take uo.length)
((constructive w s (uo ++ ui)).2.drop uo.length)
rw [List.take_append_drop] at hs
rw [sum3_cons]
omega
/-- Passes add: two triples that net to zero add to one that does. -/
theorem sum3_add (xs ys : List Int) (hx : sum3 xs = 0) (hy : sum3 ys = 0) :
sum3 [xs.getD 0 0 + ys.getD 0 0, xs.getD 1 0 + ys.getD 1 0, xs.getD 2 0 + ys.getD 2 0] = 0 := by
rw [sum3_cons]
simp only [sum3] at hx hy
omega
/-- Two triples, added section by section. -/
def add3 (xs ys : List Int) : List Int :=
[xs.getD 0 0 + ys.getD 0 0, xs.getD 1 0 + ys.getD 1 0, xs.getD 2 0 + ys.getD 2 0]
/-- An entry's flows on the statement: its cash flows, plus `C e`, what a
member or lender paid or received for it, by section (rule 11). -/
def stmtFlows (F : List Line → Line → Flow) (C : List Line → List Int) (e : List Line) :
List Int :=
add3 (flows F e) (C e)
/-- **An entry's statement flows sum to its cash** when what was handled
for it nets to zero: rule 11 moves no cash (`stmt_flows_sum`). -/
theorem stmt_flows_sum (F : List Line → Line → Flow) (C : List Line → List Int)
(e : List Line) (h : net e = 0) (hC : sum3 (C e) = 0) :
sum3 (stmtFlows F C e) = cashOf F e := by
have he := entry_flows_sum F e h
rw [isum_three _ (flows_length F e)] at he
simp only [stmtFlows, add3, sum3_cons]
simp only [sum3] at hC
omega
theorem getD_neg (xs : List Int) (k : Nat) :
(xs.map (fun x => -x)).getD k 0 = -xs.getD k 0 := by
induction xs generalizing k with
| nil => simp
| cons x xs ih => cases k with
| zero => simp
| succ k => simp only [List.map_cons, List.getD_cons_succ, ih]
/-- **A reversal's statement flows are its original's, negated**, when its
lines take the original's tags and what was handled for it mirrors
(`constructive_neg`). -/
theorem stmt_flows_reversal (F : List Line → Line → Flow) (C : List Line → List Int)
(e : List Line) (hF : ∀ l ∈ e, F (reversal e) l.reverse = F e l)
(hC : C (reversal e) = (C e).map (fun x => -x)) :
stmtFlows F C (reversal e) = (stmtFlows F C e).map (fun x => -x) := by
simp only [stmtFlows, add3, flows_reversal F e hF, hC, getD_neg, List.map_cons,
List.map_nil, List.cons.injEq, and_true]
refine ⟨?_, ?_, ?_⟩ <;> omega
/-- A section's total over some entries: the sum of each entry's cash in
it (`k` = 0 operating, 1 investing, 2 financing), what a member or lender
handled for it included. -/
def sectionTotal (F : List Line → Line → Flow) (C : List Line → List Int) (k : Nat) :
List (List Line) → Int
| [] => 0
| e :: es => (stmtFlows F C e).getD k 0 + sectionTotal F C k es
/-- The entries' cash, summed. -/
def cashTotal (F : List Line → Line → Flow) : List (List Line) → Int
| [] => 0
| e :: es => cashOf F e + cashTotal F es
/-- **The sections sum to the change in cash** (plan P3): over any balanced
entries, operating + investing + financing is the entries' cash, exactly,
whatever a member or lender handled for them as long as it nets to zero
within each entry (rule 11, `constructive_nets`). The statement's footing
(rules.md B-14 rule 9) can't fail on posted entries. -/
theorem cashflow_sections_sum_to_cash_change (F : List Line → Line → Flow)
(C : List Line → List Int) (es : List (List Line)) (h : ∀ e ∈ es, net e = 0)
(hC : ∀ e ∈ es, sum3 (C e) = 0) :
sectionTotal F C 0 es + sectionTotal F C 1 es + sectionTotal F C 2 es = cashTotal F es := by
induction es with
| nil => rfl
| cons e es ih =>
simp only [sectionTotal, cashTotal]
have he := stmt_flows_sum F C e (h e (by simp)) (hC e (by simp))
simp only [sum3] at he
have := ih (fun x hx => h x (by simp [hx])) (fun x hx => hC x (by simp [hx]))
omega
/-- When the cash tag follows the account (a line is cash exactly when
its account is a cash account), an entry's cash is the movement of the
cash accounts. -/
theorem secNet_cash_is_movement (f : Line → Flow) (cash : List Nat) (hd : Distinct cash)
(hf : ∀ l, f l = .cash ↔ l.account ∈ cash) (ls : List Line) :
secNet f .cash ls = sumOver (fun a => movement a ls) cash := by
induction ls with
| nil => simpa using (sumOver_zero cash).symm
| cons l ls ih =>
simp only [secNet_cons, movement_cons]
rw [sumOver_add, ← ih]
by_cases hc : l.account ∈ cash
· rw [ite_eq_left ((hf l).2 hc), sumOver_indicator l.account l.signed cash hd hc]
· rw [ite_eq_right (fun e => hc ((hf l).1 e)), sumOver_indicator_absent l.account l.signed cash hc]
/-! ### Net income reconciled to operating cash (rules.md B-14 rule 8) -/
/-- Net movement of the lines on revenue and expense accounts (`pl`)
tagged `k` (`sel = true`), or on balance-sheet accounts (`sel = false`). -/
def plNet (pl : Nat → Bool) (sel : Bool) (f : Line → Flow) (k : Flow) : List Line → Int
| [] => 0
| l :: ls => (if pl l.account = sel ∧ f l = k then l.signed else 0) + plNet pl sel f k ls
/-- Net movement of every revenue and expense line. -/
def plAll (pl : Nat → Bool) : List Line → Int
| [] => 0
| l :: ls => (if pl l.account = true then l.signed else 0) + plAll pl ls
/-- Net income: revenue less expenses, `-(net of the P&L lines)`. -/
def netIncome (pl : Nat → Bool) (e : List Line) : Int := -plAll pl e
/-- G: the P&L lines rule 4 puts in investing (gains and losses). -/
def gainLoss (pl : Nat → Bool) (F : List Line → Line → Flow) (e : List Line) : Int :=
plNet pl true (F e) .investing e
/-- W: minus the movement of the operating balance-sheet lines. -/
def balanceChange (pl : Nat → Bool) (F : List Line → Line → Flow) (e : List Line) : Int :=
-plNet pl false (F e) .operating e
/-- X: what no cash, real or handled for the company, settled of the
operating movement. -/
def noncashOp (F : List Line → Line → Flow) (C : List Line → List Int) (e : List Line) : Int :=
secNet (F e) .operating e + (stmtFlows F C e).getD 0 0
theorem secNet_split (pl : Nat → Bool) (f : Line → Flow) (k : Flow) (ls : List Line) :
secNet f k ls = plNet pl true f k ls + plNet pl false f k ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [secNet_cons, plNet, ih]
cases pl l.account <;> by_cases h : f l = k <;> simp [h] <;> omega
theorem plAll_split (pl : Nat → Bool) (f : Line → Flow) (ls : List Line)
(h : ∀ l ∈ ls, pl l.account = true → f l = .operating ∨ f l = .investing) :
plAll pl ls = plNet pl true f .operating ls + plNet pl true f .investing ls := by
induction ls with
| nil => rfl
| cons l ls ih =>
simp only [plAll, plNet, ih (fun m hm => h m (by simp [hm]))]
cases hp : pl l.account
· simp
· rcases h l (by simp) hp with hk | hk <;> simp [hk] <;> omega
/-- **Net income reconciles to operating cash**, entry by entry:
operating cash = NI + G + X + W, when revenue and expense lines are only
ever operating or investing (rules.md B-14 rule 8; ASC 230-10-45-28 to
45-30), whatever a member or lender handled for it (rule 11). -/
theorem operating_reconciliation_ties (pl : Nat → Bool) (F : List Line → Line → Flow)
(C : List Line → List Int) (e : List Line)
(h : ∀ l ∈ e, pl l.account = true → F e l = .operating ∨ F e l = .investing) :
(stmtFlows F C e).getD 0 0
= netIncome pl e + gainLoss pl F e + noncashOp F C e + balanceChange pl F e := by
have hs := secNet_split pl (F e) .operating e
have hp := plAll_split pl (F e) e h
simp only [netIncome, gainLoss, noncashOp, balanceChange]
omega
/-- The operating section's total over some entries. -/
def opTotal (pl : Nat → Bool) (F : List Line → Line → Flow) (C : List Line → List Int) :
List (List Line) → Int
| [] => 0
| e :: es => netIncome pl e + gainLoss pl F e + noncashOp F C e + balanceChange pl F e
+ opTotal pl F C es
/-- **The reconciliation schedule ties to the operating section** over any
entries: the section's total is NI + G + X + W summed. -/
theorem operating_reconciliation_ties_all (pl : Nat → Bool) (F : List Line → Line → Flow)
(C : List Line → List Int) (es : List (List Line))
(h : ∀ e ∈ es, ∀ l ∈ e, pl l.account = true → F e l = .operating ∨ F e l = .investing) :
sectionTotal F C 0 es = opTotal pl F C es := by
induction es with
| nil => rfl
| cons e es ih =>
simp only [sectionTotal, opTotal]
rw [operating_reconciliation_ties pl F C e (h e (by simp)),
ih (fun x hx => h x (by simp [hx]))]
end Wanderbooks
+12 -2
View File
@@ -1,6 +1,16 @@
{"version": "1.3.0",
{"version": "1.2.0",
"packagesDir": ".lake/packages",
"packages": [],
"packages":
[{"url": "https://git.swaits.com/swaits/bookspec",
"type": "git",
"subDir": "lean",
"scope": "",
"rev": "77e046334eea29e082b53bbe907017d9ffef5a0a",
"name": "bookspec",
"manifestFile": "lake-manifest.json",
"inputRev": "77e046334eea29e082b53bbe907017d9ffef5a0a",
"inherited": false,
"configFile": "lakefile.toml"}],
"name": "wanderbooks",
"lakeDir": ".lake",
"fixedToolchain": false}
+11
View File
@@ -1,5 +1,16 @@
name = "wanderbooks"
defaultTargets = ["Wanderbooks"]
packagesDir = ".lake/packages"
# The accounting laws are proved once, in bookspec's Lean (D-69): this
# project builds that package and audits its theorems, and holds no copy
# of its files. The rev is the same one the Rust checker is pinned to
# (crates/ledger-core/Cargo.toml); tests/bookspec/pin.rs keeps them equal.
[[require]]
name = "bookspec"
git = "https://git.swaits.com/swaits/bookspec"
rev = "77e046334eea29e082b53bbe907017d9ffef5a0a"
subDir = "lean"
[[lean_lib]]
name = "Wanderbooks"