From 822f0dadcab02053496fada9292fb8bac2570b7a Mon Sep 17 00:00:00 2001 From: mkrishna793 <271944389+mkrishna793@users.noreply.github.com> Date: Tue, 10 Nov 2026 07:43:11 +0000 Subject: [PATCH] Build bounded compiler foundation and MZI demonstration Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- .github/workflows/ci.yml | 34 ++ .gitignore | 8 + Lean-Semantics/lean/Lumiris.lean | 10 +- Lean-Semantics/lean/Lumiris/Core/Approx.lean | 32 +- Lean-Semantics/lean/Lumiris/Core/Bounded.lean | 90 ++++ .../lean/Lumiris/Core/Encoding.lean | 66 ++- Lean-Semantics/lean/Lumiris/Core/Range.lean | 130 ++++-- .../lean/Lumiris/Core/Semantics.lean | 45 +- Lean-Semantics/lean/Lumiris/Core/Units.lean | 40 +- .../lean/Lumiris/Physics/Control.lean | 46 ++ Lean-Semantics/lean/Lumiris/Physics/Laws.lean | 17 + .../lean/Lumiris => }/Physics/Photonic.lean | 95 ++-- Lean-Semantics/lean/Lumiris/Tests.lean | 21 + .../Physics/lean => }/lake-manifest.json | 0 Lean-Semantics/lean/{lean => }/lakefile.toml | 2 +- Lean-Semantics/rust/Cargo.lock | 410 +---------------- Lean-Semantics/rust/Cargo.toml | 20 +- Lean-Semantics/rust/rust/src/lib.rs | 15 - Lean-Semantics/rust/rust/src/rust/src/main.rs | 1 - Lean-Semantics/rust/rustfmt.toml | 3 + Lean-Semantics/rust/src/lib.rs | 319 ++++++++++++++ Lean-Semantics/rust/src/main.rs | 79 ++++ Lean-Semantics/rust/src/mzi.rs | 297 +++++++++++++ Lean-Semantics/rust/src/rational.rs | 195 ++++++++ README.md | 172 ++++++++ devices/demo-mzi.mzi | 11 + docs/ir.md | 161 +++++++ docs/milestones.md | 78 ++++ docs/verification.md | 99 +++++ examples/mzi-scale.lumi | 6 + examples/reject-zero-divisor.lumi | 5 + examples/safe-division.lumi | 6 + photonic-memristor-compiler-plan.md | 30 +- scripts/audit_repository.py | 51 +++ scripts/check_certificate.py | 416 ++++++++++++++++++ scripts/check_lean.sh | 10 + scripts/demo.sh | 14 + scripts/simulate.py | 77 ++++ scripts/test.sh | 7 + tests/test_pipeline.py | 263 +++++++++++ 40 files changed, 2761 insertions(+), 620 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 Lean-Semantics/lean/Lumiris/Core/Bounded.lean create mode 100644 Lean-Semantics/lean/Lumiris/Physics/Control.lean create mode 100644 Lean-Semantics/lean/Lumiris/Physics/Laws.lean rename Lean-Semantics/lean/Lumiris/{Core/lean/Lumiris => }/Physics/Photonic.lean (91%) create mode 100644 Lean-Semantics/lean/Lumiris/Tests.lean rename Lean-Semantics/lean/{Lumiris/Core/lean/Lumiris/Physics/lean => }/lake-manifest.json (100%) rename Lean-Semantics/lean/{lean => }/lakefile.toml (89%) delete mode 100644 Lean-Semantics/rust/rust/src/lib.rs delete mode 100644 Lean-Semantics/rust/rust/src/rust/src/main.rs create mode 100644 Lean-Semantics/rust/rustfmt.toml create mode 100644 Lean-Semantics/rust/src/lib.rs create mode 100644 Lean-Semantics/rust/src/main.rs create mode 100644 Lean-Semantics/rust/src/mzi.rs create mode 100644 Lean-Semantics/rust/src/rational.rs create mode 100644 README.md create mode 100644 devices/demo-mzi.mzi create mode 100644 docs/ir.md create mode 100644 docs/milestones.md create mode 100644 docs/verification.md create mode 100644 examples/mzi-scale.lumi create mode 100644 examples/reject-zero-divisor.lumi create mode 100644 examples/safe-division.lumi create mode 100644 scripts/audit_repository.py create mode 100644 scripts/check_certificate.py create mode 100755 scripts/check_lean.sh create mode 100755 scripts/demo.sh create mode 100644 scripts/simulate.py create mode 100755 scripts/test.sh create mode 100644 tests/test_pipeline.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..144d62f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: Verify Lumiris +on: + push: + pull_request: +permissions: + contents: read +jobs: + executable: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: cargo fmt --manifest-path Lean-Semantics/rust/Cargo.toml -- --check + - run: scripts/test.sh + - run: scripts/demo.sh artifacts/mzi-demo + - uses: actions/upload-artifact@v4 + with: + name: mzi-demonstration + path: artifacts/mzi-demo + formal: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: Lean-Semantics/lean + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: scripts/demo.sh artifacts/mzi-demo --lean diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d4ef658 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +# Toolchains, dependencies, generated proofs, and reports +**/target/ +**/.lake/ +**/*.olean +**/*.ilean +**/__pycache__/ +.venv/ +artifacts/ diff --git a/Lean-Semantics/lean/Lumiris.lean b/Lean-Semantics/lean/Lumiris.lean index ddcead2..1349fdc 100644 --- a/Lean-Semantics/lean/Lumiris.lean +++ b/Lean-Semantics/lean/Lumiris.lean @@ -1,2 +1,10 @@ import Lumiris.Core.Units -import Lumiris.Core.Range \ No newline at end of file +import Lumiris.Core.Range +import Lumiris.Core.Encoding +import Lumiris.Core.Approx +import Lumiris.Core.Semantics +import Lumiris.Core.Bounded +import Lumiris.Physics.Laws +import Lumiris.Physics.Photonic +import Lumiris.Physics.Control +import Lumiris.Tests diff --git a/Lean-Semantics/lean/Lumiris/Core/Approx.lean b/Lean-Semantics/lean/Lumiris/Core/Approx.lean index f1186ed..564cc7d 100644 --- a/Lean-Semantics/lean/Lumiris/Core/Approx.lean +++ b/Lean-Semantics/lean/Lumiris/Core/Approx.lean @@ -1,55 +1,55 @@ import Lumiris.Core.Range - + /-! # Approximate operations and error composition - + Analog hardware never computes exactly. Each of the four core operations is realized by a physical process whose result is within `ε` of the exact result. These lemmas say how errors propagate through `+ − × ÷`; they are the foundation of the certified error budget. -/ - + namespace Lumiris - + /-- An approximate binary operation with a certified error bound on the given input ranges. -/ structure ApproxOp (op : ℝ → ℝ → ℝ) (A B : Range) where realize : ℝ → ℝ → ℝ err : ℝ err_nonneg : 0 ≤ err spec : ∀ a b, A.contains a → B.contains b → |realize a b - op a b| ≤ err - + namespace ErrProp - + theorem add (a a' b b' : ℝ) : |(a' + b') - (a + b)| ≤ |a' - a| + |b' - b| := by have h : (a' + b') - (a + b) = (a' - a) + (b' - b) := by ring rw [h]; exact abs_add_le _ _ - + theorem sub (a a' b b' : ℝ) : |(a' - b') - (a - b)| ≤ |a' - a| + |b' - b| := by have h : (a' - b') - (a - b) = (a' - a) - (b' - b) := by ring rw [h]; exact abs_sub _ _ - + theorem mul (a a' b b' : ℝ) : |a' * b' - a * b| ≤ |a' - a| * |b| + |a| * |b' - b| + |a' - a| * |b' - b| := by have h : a' * b' - a * b = (a' - a) * b + a * (b' - b) + (a' - a) * (b' - b) := by ring rw [h] calc |(a' - a) * b + a * (b' - b) + (a' - a) * (b' - b)| - ≤ |(a' - a) * b| + |a * (b' - b)| + |(a' - a) * (b' - b)| := abs_add_three _ _ _ + ≤ |(a' - a) * b| + |a * (b' - b)| + |(a' - a) * (b' - b)| := le_trans (abs_add_le _ _) (add_le_add_right (abs_add_le _ _) _) _ = _ := by rw [abs_mul, abs_mul, abs_mul] - + theorem div (a a' b b' : ℝ) (hb : b ≠ 0) (hb' : b' ≠ 0) : |a' / b' - a / b| ≤ (|a' - a| * |b| + |a| * |b' - b|) / (|b| * |b'|) := by have h : a' / b' - a / b = ((a' - a) * b - a * (b' - b)) / (b * b') := by - field_simp; ring + field_simp [hb, hb']; ring rw [h, abs_div, abs_mul b b'] apply div_le_div_of_nonneg_right _ (by positivity) calc |(a' - a) * b - a * (b' - b)| ≤ |(a' - a) * b| + |a * (b' - b)| := abs_sub _ _ _ = _ := by rw [abs_mul, abs_mul] - + /-- A perturbed divisor stays away from zero: `|b| ≥ m`, `|b' − b| ≤ e`, `e < m` ⇒ `|b'| ≥ m − e`. -/ theorem abs_perturbed_ge {b b' m e : ℝ} (hm : m ≤ |b|) (he : |b' - b| ≤ e) : m - e ≤ |b'| := by have := abs_sub_abs_le_abs_sub b b' have h2 : |b - b'| = |b' - b| := abs_sub_comm _ _ linarith - + /-- Monotone bound used in the division case of the budget theorem. -/ theorem div_bound {a a' b b' Ma Mb ea eb m : ℝ} (hMa : |a| ≤ Ma) (hMb : |b| ≤ Mb) (hea : |a' - a| ≤ ea) (heb : |b' - b| ≤ eb) @@ -73,7 +73,7 @@ theorem div_bound {a a' b b' Ma Mb ea eb m : ℝ} · have : 0 < m - eb := by linarith positivity · exact mul_le_mul hm hb'abs (by linarith) (abs_nonneg _) - + end ErrProp - -end Lumiris \ No newline at end of file + +end Lumiris diff --git a/Lean-Semantics/lean/Lumiris/Core/Bounded.lean b/Lean-Semantics/lean/Lumiris/Core/Bounded.lean new file mode 100644 index 0000000..2d470fc --- /dev/null +++ b/Lean-Semantics/lean/Lumiris/Core/Bounded.lean @@ -0,0 +1,90 @@ +import Lumiris.Core.Approx + +/-! +# Bounded, per-device contracts + +Unlike the legacy globally quantified `Realization`, these contracts only hold on +specified physical domains. Each operand's *actual*, not merely ideal, value must +be in the domain. Constants and inputs may both have error. No stochastic claim +is made. Model calibration remains an explicit external assumption. +-/ +noncomputable section +namespace Lumiris.Bounded + +structure Value where + ideal : ℝ + actual : ℝ + range : Range + error : ℝ + error_nonneg : 0 ≤ error + ideal_mem : range.contains ideal + close : |actual - ideal| ≤ error + +def Value.actualRange (v : Value) : Range := + ⟨v.range.lo - v.error, v.range.hi + v.error, by linarith [v.range.le, v.error_nonneg]⟩ + +theorem Value.actual_mem (v : Value) : v.actualRange.contains v.actual := by + obtain ⟨hlo, hhi⟩ := v.ideal_mem + obtain ⟨he0, he1⟩ := abs_le.mp v.close + constructor <;> dsimp [Value.actualRange, Range.contains] <;> linarith + +structure Contract (op : ℝ → ℝ → ℝ) where + inputLeft : Range + inputRight : Range + output : Range + transfer : ℝ → ℝ → ℝ + localError : ℝ + localError_nonneg : 0 ≤ localError + spec : ∀ x y, inputLeft.contains x → inputRight.contains y → + |transfer x y - op x y| ≤ localError + safe : ∀ x y, inputLeft.contains x → inputRight.contains y → output.contains (transfer x y) + +/-- The common composition step. Physical-domain membership is an explicit obligation. -/ +theorem compose {op : ℝ → ℝ → ℝ} (c : Contract op) (a b : Value) + (ha : c.inputLeft.contains a.actual) (hb : c.inputRight.contains b.actual) + {propagated : ℝ} + (hp : |op a.actual b.actual - op a.ideal b.ideal| ≤ propagated) : + |c.transfer a.actual b.actual - op a.ideal b.ideal| ≤ propagated + c.localError := by + calc + _ ≤ |c.transfer a.actual b.actual - op a.actual b.actual| + + |op a.actual b.actual - op a.ideal b.ideal| := abs_sub_le _ _ _ + _ ≤ c.localError + propagated := add_le_add (c.spec _ _ ha hb) hp + _ = _ := add_comm _ _ + +theorem add (c : Contract (· + ·)) (a b : Value) + (ha : c.inputLeft.contains a.actual) (hb : c.inputRight.contains b.actual) : + |c.transfer a.actual b.actual - (a.ideal + b.ideal)| ≤ a.error + b.error + c.localError := by + apply compose c a b ha hb + exact le_trans (ErrProp.add _ _ _ _) (add_le_add a.close b.close) + +theorem sub (c : Contract (· - ·)) (a b : Value) + (ha : c.inputLeft.contains a.actual) (hb : c.inputRight.contains b.actual) : + |c.transfer a.actual b.actual - (a.ideal - b.ideal)| ≤ a.error + b.error + c.localError := by + apply compose c a b ha hb + exact le_trans (ErrProp.sub _ _ _ _) (add_le_add a.close b.close) + +theorem mul (c : Contract (· * ·)) (a b : Value) + (ha : c.inputLeft.contains a.actual) (hb : c.inputRight.contains b.actual) : + |c.transfer a.actual b.actual - a.ideal * b.ideal| ≤ + a.error * b.range.mag + a.range.mag * b.error + a.error * b.error + c.localError := by + apply compose c a b ha hb + have hMa := Range.abs_le_mag a.ideal_mem + have hMb := Range.abs_le_mag b.ideal_mem + have h1 := mul_le_mul a.close hMb (abs_nonneg _) a.error_nonneg + have h2 := mul_le_mul hMa b.close (abs_nonneg _) a.range.mag_nonneg + have h3 := mul_le_mul a.close b.close (abs_nonneg _) a.error_nonneg + have h := ErrProp.mul a.ideal a.actual b.ideal b.actual + linarith + +/-- Division requires separation of the *perturbed* denominator from zero. -/ +theorem div (c : Contract (· / ·)) (a b : Value) + (ha : c.inputLeft.contains a.actual) (hb : c.inputRight.contains b.actual) + (hsafe : b.error < b.range.minMag) : + |c.transfer a.actual b.actual - a.ideal / b.ideal| ≤ + (a.error * b.range.mag + a.range.mag * b.error) / + (b.range.minMag * (b.range.minMag - b.error)) + c.localError := by + apply compose c a b ha hb + exact ErrProp.div_bound (Range.abs_le_mag a.ideal_mem) (Range.abs_le_mag b.ideal_mem) + a.close b.close (Range.minMag_le_abs b.ideal_mem) hsafe a.error_nonneg b.error_nonneg + +end Lumiris.Bounded diff --git a/Lean-Semantics/lean/Lumiris/Core/Encoding.lean b/Lean-Semantics/lean/Lumiris/Core/Encoding.lean index 445ab8e..78bbe75 100644 --- a/Lean-Semantics/lean/Lumiris/Core/Encoding.lean +++ b/Lean-Semantics/lean/Lumiris/Core/Encoding.lean @@ -1,42 +1,60 @@ import Lumiris.Core.Range - +import Mathlib.Analysis.SpecialFunctions.Trigonometric.Basic + /-! # Number encodings - + A real number is carried by a physical quantity (optical power, field amplitude, voltage, conductance, ...). An `Encoding` is a pair `enc/dec` that round-trips exactly on its domain, together with the physical constraints of the carrier (e.g. power is non-negative). -/ - + +noncomputable section + namespace Lumiris - + /-- An encoding of reals (on `domain`) into a physical carrier type `Q`. -/ structure Encoding (Q : Type) where domain : Range enc : ℝ → Q dec : Q → ℝ dec_enc : ∀ x, domain.contains x → dec (enc x) = x - + namespace Encoding - + /-- Linear scaling into a carrier with full-scale value `fs` (e.g. `1.0 ↦ 1 mW`). -/ noncomputable def scaled (fs : ℝ) (hfs : 0 < fs) (domain : Range) : Encoding ℝ where domain := domain enc x := x * fs dec q := q / fs - dec_enc x _ := by field_simp - + dec_enc x _ := by field_simp [ne_of_gt hfs] + /-- Unipolar optical power: domain `[0, 1]`, carrier `P ∈ [0, Pmax]`. The carrier is never negative on the domain. -/ noncomputable def optPow (Pmax : ℝ) (h : 0 < Pmax) : Encoding ℝ := scaled Pmax h ⟨0, 1, by norm_num⟩ - + theorem optPow_nonneg (Pmax : ℝ) (h : 0 < Pmax) {x : ℝ} (hx : (optPow Pmax h).domain.contains x) : 0 ≤ (optPow Pmax h).enc x := by obtain ⟨h0, _⟩ := hx simp only [optPow, scaled] exact mul_nonneg h0 h.le - + +theorem optPow_le_max (Pmax : ℝ) (h : 0 < Pmax) {x : ℝ} + (hx : (optPow Pmax h).domain.contains x) : (optPow Pmax h).enc x ≤ Pmax := by + have hx1 : x ≤ 1 := hx.2 + change x * Pmax ≤ Pmax + nlinarith + +/-- Finite-resolution carriers need an approximate round trip, not an impossible exact inverse. -/ +structure ApproxEncoding (Q : Type) where + domain : Range + enc : ℝ → Q + dec : Q → ℝ + error : ℝ + error_nonneg : 0 ≤ error + roundtrip : ∀ x, domain.contains x → |dec (enc x) - x| ≤ error + /-- Differential (signed) encoding into a pair of non-negative carriers, `x = x⁺ − x⁻` (balanced photodetection, `G⁺ − G⁻` crossbar columns). -/ noncomputable def differential (m : ℝ) (hm : 0 ≤ m) : Encoding (ℝ × ℝ) where @@ -48,32 +66,34 @@ noncomputable def differential (m : ℝ) (hm : 0 ≤ m) : Encoding (ℝ × ℝ) rcases le_total 0 x with hx | hx · rw [max_eq_left hx, max_eq_right (by linarith)]; ring · rw [max_eq_right hx, max_eq_left (by linarith)]; ring - + theorem differential_nonneg (m : ℝ) (hm : 0 ≤ m) (x : ℝ) : 0 ≤ ((differential m hm).enc x).1 ∧ 0 ≤ ((differential m hm).enc x).2 := ⟨le_max_right _ _, le_max_right _ _⟩ - + /-- Conductance encoding: a weight `w ∈ [0, 1]` is stored as `G = Gmin + w·(Gmax − Gmin)`, which always lies in the physically allowed window `[Gmin, Gmax]`. -/ -noncomputable def conductance (Gmin Gmax : ℝ) (h : Gmin < Gmax) : Encoding ℝ where +noncomputable def conductance (Gmin Gmax : ℝ) (_h0 : 0 ≤ Gmin) (h : Gmin < Gmax) : Encoding ℝ where domain := ⟨0, 1, by norm_num⟩ enc w := Gmin + w * (Gmax - Gmin) dec G := (G - Gmin) / (Gmax - Gmin) dec_enc w _ := by have : Gmax - Gmin ≠ 0 := by linarith field_simp - -theorem conductance_in_window (Gmin Gmax : ℝ) (h : Gmin < Gmax) {w : ℝ} - (hw : (conductance Gmin Gmax h).domain.contains w) : - Gmin ≤ (conductance Gmin Gmax h).enc w ∧ (conductance Gmin Gmax h).enc w ≤ Gmax := by + +theorem conductance_in_window (Gmin Gmax : ℝ) (h0 : 0 ≤ Gmin) (h : Gmin < Gmax) {w : ℝ} + (hw : (conductance Gmin Gmax h0 h).domain.contains w) : + Gmin ≤ (conductance Gmin Gmax h0 h).enc w ∧ (conductance Gmin Gmax h0 h).enc w ≤ Gmax := by obtain ⟨h0, h1⟩ := hw simp only [conductance] constructor <;> nlinarith - -/-- Phase encoding of an angle: `φ ↦ e^{iφ}` is only invertible modulo `2π`, so the domain -is `[0, 2π)`-shaped (we use the closed `[0, 2π]` range and the branch `[0, 2π)` in control). -/ + +/-- A closed analysis envelope, NOT an invertible phase encoding: 0 and 2π coincide. -/ def phaseDomain : Range := ⟨0, 2 * Real.pi, by positivity⟩ - + +/-- The half-open branch used when a unique phase representative is required. -/ +def PhaseAngle := {φ : ℝ // 0 ≤ φ ∧ φ < 2 * Real.pi} + end Encoding - -end Lumiris \ No newline at end of file + +end Lumiris diff --git a/Lean-Semantics/lean/Lumiris/Core/Range.lean b/Lean-Semantics/lean/Lumiris/Core/Range.lean index 9ab3588..f3bea0f 100644 --- a/Lean-Semantics/lean/Lumiris/Core/Range.lean +++ b/Lean-Semantics/lean/Lumiris/Core/Range.lean @@ -1,56 +1,58 @@ import Mathlib.Data.Real.Basic import Mathlib.Tactic - + /-! # Ranges (interval arithmetic for range analysis) - + Analog values are bounded (T ≤ 1, G ∈ [Gmin, Gmax], |V| ≤ Vmax). Every L2 value carries a `Range`; lowering inserts scaling so intermediate values fit the hardware. -/ - + +noncomputable section + namespace Lumiris - + /-- A closed real interval `[lo, hi]`. -/ structure Range where lo : ℝ hi : ℝ le : lo ≤ hi - + namespace Range - + /-- `r.contains x` : `x ∈ [lo, hi]`. -/ def contains (r : Range) (x : ℝ) : Prop := r.lo ≤ x ∧ x ≤ r.hi - + def point (c : ℝ) : Range := ⟨c, c, le_rfl⟩ - + theorem contains_point (c : ℝ) : (point c).contains c := ⟨le_rfl, le_rfl⟩ - + /-- Symmetric range `[-m, m]`. -/ def sym (m : ℝ) (hm : 0 ≤ m) : Range := ⟨-m, m, by linarith⟩ - + def add (a b : Range) : Range := ⟨a.lo + b.lo, a.hi + b.hi, by linarith [a.le, b.le]⟩ def neg (a : Range) : Range := ⟨-a.hi, -a.lo, by linarith [a.le]⟩ def sub (a b : Range) : Range := a.add b.neg - + theorem contains_add {a b : Range} {x y : ℝ} (hx : a.contains x) (hy : b.contains y) : (a.add b).contains (x + y) := by obtain ⟨h1, h2⟩ := hx; obtain ⟨h3, h4⟩ := hy exact ⟨by simp only [add]; linarith, by simp only [add]; linarith⟩ - + theorem contains_neg {a : Range} {x : ℝ} (hx : a.contains x) : a.neg.contains (-x) := by obtain ⟨h1, h2⟩ := hx exact ⟨by simp only [neg]; linarith, by simp only [neg]; linarith⟩ - + theorem contains_sub {a b : Range} {x y : ℝ} (hx : a.contains x) (hy : b.contains y) : (a.sub b).contains (x - y) := by have := contains_add hx (contains_neg hy) simpa [sub, sub_eq_add_neg] using this - + /-- Magnitude bound: `|x| ≤ a.mag` for every `x` in the range. -/ def mag (a : Range) : ℝ := max |a.lo| |a.hi| - + theorem mag_nonneg (a : Range) : 0 ≤ a.mag := le_trans (abs_nonneg _) (le_max_left _ _) - + theorem abs_le_mag {a : Range} {x : ℝ} (h : a.contains x) : |x| ≤ a.mag := by obtain ⟨h1, h2⟩ := h unfold mag @@ -63,36 +65,54 @@ theorem abs_le_mag {a : Range} {x : ℝ} (h : a.contains x) : |x| ≤ a.mag := b _ ≤ -a.lo := by linarith _ ≤ |a.lo| := neg_le_abs _ _ ≤ max |a.lo| |a.hi| := le_max_left _ _ - -/-- Product range (symmetric magnitude bound). -/ -def mul (a b : Range) : Range := sym (a.mag * b.mag) (mul_nonneg a.mag_nonneg b.mag_nonneg) - + +/-- A scalar multiple attains its extrema at an interval endpoint. -/ +theorem scalar_bounds {lo hi x c : ℝ} (hx : lo ≤ x ∧ x ≤ hi) : + min (lo * c) (hi * c) ≤ x * c ∧ x * c ≤ max (lo * c) (hi * c) := by + by_cases hc : 0 ≤ c + · exact ⟨le_trans (min_le_left _ _) (mul_le_mul_of_nonneg_right hx.1 hc), + le_trans (mul_le_mul_of_nonneg_right hx.2 hc) (le_max_right _ _)⟩ + · have hc' : c ≤ 0 := le_of_not_ge hc + exact ⟨le_trans (min_le_right _ _) (mul_le_mul_of_nonpos_right hx.2 hc'), + le_trans (mul_le_mul_of_nonpos_right hx.1 hc') (le_max_left _ _)⟩ + +/-- Tight endpoint product range; in particular positive ranges remain positive. -/ +def mul (a b : Range) : Range where + lo := min (min (a.lo * b.lo) (a.hi * b.lo)) (min (a.lo * b.hi) (a.hi * b.hi)) + hi := max (max (a.lo * b.lo) (a.hi * b.lo)) (max (a.lo * b.hi) (a.hi * b.hi)) + le := le_trans (le_trans (min_le_left _ _) (min_le_left _ _)) + (le_trans (le_max_left _ _) (le_max_left _ _)) + theorem contains_of_abs_le {m x : ℝ} (hm : 0 ≤ m) (h : |x| ≤ m) : (sym m hm).contains x := by obtain ⟨h1, h2⟩ := abs_le.mp h exact ⟨h1, h2⟩ - + theorem contains_mul {a b : Range} {x y : ℝ} (hx : a.contains x) (hy : b.contains y) : (a.mul b).contains (x * y) := by - apply contains_of_abs_le - rw [abs_mul] - exact mul_le_mul (abs_le_mag hx) (abs_le_mag hy) (abs_nonneg _) a.mag_nonneg - + have h0 := scalar_bounds (c := b.lo) hx + have h1 := scalar_bounds (c := b.hi) hx + have h2 := scalar_bounds (c := x) hy + rw [mul_comm b.lo x, mul_comm b.hi x, mul_comm y x] at h2 + constructor + · exact le_trans (le_min (le_trans (min_le_left _ _) h0.1) + (le_trans (min_le_right _ _) h1.1)) h2.1 + · exact le_trans h2.2 (max_le (le_trans h0.2 (le_max_left _ _)) + (le_trans h1.2 (le_max_right _ _))) + /-- Scaling by a constant `c`. -/ -def scale (c : ℝ) (a : Range) : Range := sym (|c| * a.mag) (mul_nonneg (abs_nonneg _) a.mag_nonneg) - +def scale (c : ℝ) (a : Range) : Range := (point c).mul a + theorem contains_scale {a : Range} {x : ℝ} (c : ℝ) (hx : a.contains x) : - (a.scale c).contains (c * x) := by - apply contains_of_abs_le - rw [abs_mul] - exact mul_le_mul_of_nonneg_left (abs_le_mag hx) (abs_nonneg _) - + (a.scale c).contains (c * x) := + contains_mul (contains_point c) hx + /-- Lower bound on the magnitude: `a.minMag ≤ |x|` for every `x` in the range. It is `0` whenever the range touches or crosses zero, so division by such a range is unsafe. -/ def minMag (a : Range) : ℝ := if 0 < a.lo then a.lo else if a.hi < 0 then -a.hi else 0 - + theorem minMag_nonneg (a : Range) : 0 ≤ a.minMag := by unfold minMag; split_ifs <;> linarith - + theorem minMag_le_abs {a : Range} {x : ℝ} (h : a.contains x) : a.minMag ≤ |x| := by obtain ⟨h1, h2⟩ := h unfold minMag @@ -102,7 +122,7 @@ theorem minMag_le_abs {a : Range} {x : ℝ} (h : a.contains x) : a.minMag ≤ |x · calc -a.hi ≤ -x := by linarith _ ≤ |x| := neg_le_abs x · exact abs_nonneg x - + /-- A range bounded away from zero is a safe divisor. -/ theorem ne_zero_of_minMag_pos {a : Range} {x : ℝ} (ha : 0 < a.minMag) (h : a.contains x) : x ≠ 0 := by @@ -110,18 +130,34 @@ theorem ne_zero_of_minMag_pos {a : Range} {x : ℝ} (ha : 0 < a.minMag) (h : a.c have := minMag_le_abs h rw [hx, abs_zero] at this linarith - -/-- Quotient range, meaningful only when `0 < b.minMag`. -/ -noncomputable def div (a b : Range) : Range := - sym (a.mag / b.minMag) (div_nonneg a.mag_nonneg b.minMag_nonneg) - + +/-- Tight reciprocal interval. The zero-crossing branch is deliberately uncertifiable. -/ +def reciprocal (a : Range) : Range := + if hp : 0 < a.lo then + ⟨1 / a.hi, 1 / a.lo, one_div_le_one_div_of_le hp a.le⟩ + else if hn : a.hi < 0 then + ⟨1 / a.hi, 1 / a.lo, one_div_le_one_div_of_neg_of_le hn a.le⟩ + else point 0 + +theorem contains_reciprocal {a : Range} {x : ℝ} (ha : 0 < a.minMag) + (hx : a.contains x) : a.reciprocal.contains (1 / x) := by + unfold reciprocal + split_ifs with hp hn + · have hxpos : 0 < x := lt_of_lt_of_le hp hx.1 + exact ⟨one_div_le_one_div_of_le hxpos hx.2, one_div_le_one_div_of_le hp hx.1⟩ + · have hxneg : x < 0 := lt_of_le_of_lt hx.2 hn + exact ⟨one_div_le_one_div_of_neg_of_le hn hx.2, + one_div_le_one_div_of_neg_of_le hxneg hx.1⟩ + · simp [minMag, hp, hn] at ha + +/-- Tight quotient range, meaningful only when `0 < b.minMag`. -/ +def div (a b : Range) : Range := a.mul b.reciprocal + theorem contains_div {a b : Range} {x y : ℝ} (hb : 0 < b.minMag) (hx : a.contains x) (hy : b.contains y) : (a.div b).contains (x / y) := by - apply contains_of_abs_le - rw [abs_div] - have hy' : b.minMag ≤ |y| := minMag_le_abs hy - exact div_le_div₀ a.mag_nonneg (abs_le_mag hx) hb hy' - + have h := contains_mul hx (contains_reciprocal hb hy) + simpa [div, div_eq_mul_inv] using h + end Range - -end Lumiris \ No newline at end of file + +end Lumiris diff --git a/Lean-Semantics/lean/Lumiris/Core/Semantics.lean b/Lean-Semantics/lean/Lumiris/Core/Semantics.lean index 2832168..30947b0 100644 --- a/Lean-Semantics/lean/Lumiris/Core/Semantics.lean +++ b/Lean-Semantics/lean/Lumiris/Core/Semantics.lean @@ -1,8 +1,8 @@ import Lumiris.Core.Approx - + /-! # L2 Core Analog Algebra: syntax, exact semantics, realized semantics, certified error budget - + `Expr` is the abstract core: constants, inputs, and the four field operations `+ − × ÷`. `eval` is the exact mathematical meaning. `realEval` is what analog hardware computes when each operation is realized by an approximate physical process (`Realization`). @@ -10,9 +10,11 @@ The main theorem `budget_sound` proves that the compiler-computed `errBound` rea the difference, and `range_sound` proves that range analysis is sound — the two facts a certificate checker needs. -/ - + +noncomputable section + namespace Lumiris - + inductive Expr where | const : ℝ → Expr | var : ℕ → Expr @@ -20,9 +22,9 @@ inductive Expr where | sub : Expr → Expr → Expr | mul : Expr → Expr → Expr | div : Expr → Expr → Expr - + namespace Expr - + /-- Exact (digital, infinite-precision) meaning. -/ noncomputable def eval (env : ℕ → ℝ) : Expr → ℝ | const c => c @@ -31,7 +33,7 @@ noncomputable def eval (env : ℕ → ℝ) : Expr → ℝ | sub a b => a.eval env - b.eval env | mul a b => a.eval env * b.eval env | div a b => a.eval env / b.eval env - + /-- Range analysis under a typing context `Γ` giving the range of each input. -/ noncomputable def range (Γ : ℕ → Range) : Expr → Range | const c => Range.point c @@ -40,7 +42,7 @@ noncomputable def range (Γ : ℕ → Range) : Expr → Range | sub a b => (a.range Γ).sub (b.range Γ) | mul a b => (a.range Γ).mul (b.range Γ) | div a b => (a.range Γ).div (b.range Γ) - + /-- Every divisor is bounded away from zero (checked by Z3 per instance). -/ def divSafe (Γ : ℕ → Range) : Expr → Prop | const _ => True @@ -49,7 +51,7 @@ def divSafe (Γ : ℕ → Range) : Expr → Prop | sub a b => a.divSafe Γ ∧ b.divSafe Γ | mul a b => a.divSafe Γ ∧ b.divSafe Γ | div a b => a.divSafe Γ ∧ b.divSafe Γ ∧ 0 < (b.range Γ).minMag - + theorem range_sound {Γ : ℕ → Range} {env : ℕ → ℝ} (henv : ∀ i, (Γ i).contains (env i)) : ∀ e : Expr, e.divSafe Γ → (e.range Γ).contains (e.eval env) | const c, _ => Range.contains_point c @@ -59,10 +61,11 @@ theorem range_sound {Γ : ℕ → Range} {env : ℕ → ℝ} (henv : ∀ i, (Γ | mul a b, ⟨ha, hb⟩ => Range.contains_mul (range_sound henv a ha) (range_sound henv b hb) | div a b, ⟨ha, hb, hsafe⟩ => Range.contains_div hsafe (range_sound henv a ha) (range_sound henv b hb) - + end Expr - -/-- A physical realization of the four core operations: each is computed by a process that is + +/-- Legacy idealized global realization. Real devices should use `Bounded.Contract`. +Each operation is computed by a process that is within a fixed `ε` of the exact operation. Inputs may also be encoded with error `εvar`. -/ structure Realization where addR : ℝ → ℝ → ℝ @@ -83,9 +86,9 @@ structure Realization where subR_spec : ∀ a b, |subR a b - (a - b)| ≤ εsub mulR_spec : ∀ a b, |mulR a b - a * b| ≤ εmul divR_spec : ∀ a b, b ≠ 0 → |divR a b - a / b| ≤ εdiv - + namespace Expr - + /-- What the analog hardware computes. -/ noncomputable def realEval (ρ : Realization) (env' : ℕ → ℝ) : Expr → ℝ | const c => c @@ -94,7 +97,7 @@ noncomputable def realEval (ρ : Realization) (env' : ℕ → ℝ) : Expr → | sub a b => ρ.subR (a.realEval ρ env') (b.realEval ρ env') | mul a b => ρ.mulR (a.realEval ρ env') (b.realEval ρ env') | div a b => ρ.divR (a.realEval ρ env') (b.realEval ρ env') - + /-- Compiler-computed error budget. -/ noncomputable def errBound (ρ : Realization) (Γ : ℕ → Range) : Expr → ℝ | const _ => 0 @@ -107,7 +110,7 @@ noncomputable def errBound (ρ : Realization) (Γ : ℕ → Range) : Expr → | div a b => (a.errBound ρ Γ * (b.range Γ).mag + (a.range Γ).mag * b.errBound ρ Γ) / ((b.range Γ).minMag * ((b.range Γ).minMag - b.errBound ρ Γ)) + ρ.εdiv - + /-- Realized divisors stay away from zero: the accumulated error on a divisor is smaller than its guaranteed magnitude. Checked by Z3 per instance. -/ noncomputable def budgetSafe (ρ : Realization) (Γ : ℕ → Range) : Expr → Prop @@ -117,7 +120,7 @@ noncomputable def budgetSafe (ρ : Realization) (Γ : ℕ → Range) : Expr → | sub a b => a.budgetSafe ρ Γ ∧ b.budgetSafe ρ Γ | mul a b => a.budgetSafe ρ Γ ∧ b.budgetSafe ρ Γ | div a b => a.budgetSafe ρ Γ ∧ b.budgetSafe ρ Γ ∧ b.errBound ρ Γ < (b.range Γ).minMag - + theorem errBound_nonneg (ρ : Realization) (Γ : ℕ → Range) : ∀ e : Expr, e.budgetSafe ρ Γ → 0 ≤ e.errBound ρ Γ | const _, _ => le_rfl @@ -140,7 +143,7 @@ theorem errBound_nonneg (ρ : Realization) (Γ : ℕ → Range) : have h3 : 0 < (b.range Γ).minMag - b.errBound ρ Γ := by linarith have h4 : 0 < (b.range Γ).minMag := by linarith simp only [errBound]; positivity - + /-- **Certified error budget.** If inputs lie in their declared ranges, encoded inputs are within `εvar` of the true inputs, divisors are safe, then the analog result is within `errBound` of the exact mathematical result. -/ @@ -222,7 +225,7 @@ theorem budget_sound (ρ : Realization) {Γ : ℕ → Range} {env env' : ℕ → add_le_add (ρ.divR_spec _ _ hb'ne) (ErrProp.div_bound hMa hMb ha hb hm bsafe hea0 heb0) _ = _ := by ring - + end Expr - -end Lumiris \ No newline at end of file + +end Lumiris diff --git a/Lean-Semantics/lean/Lumiris/Core/Units.lean b/Lean-Semantics/lean/Lumiris/Core/Units.lean index c523a03..f1c0f31 100644 --- a/Lean-Semantics/lean/Lumiris/Core/Units.lean +++ b/Lean-Semantics/lean/Lumiris/Core/Units.lean @@ -1,15 +1,15 @@ import Mathlib.Data.Real.Basic import Mathlib.Tactic - + /-! # Physical units as types - + Every physical quantity the compiler manipulates carries its SI dimension in its type. Adding a voltage to a wavelength is a type error, not a runtime surprise. -/ - + namespace Lumiris - + /-- SI dimension exponents: length, mass, time, electric current, temperature. -/ structure Dim where L : ℤ := 0 @@ -18,12 +18,12 @@ structure Dim where I : ℤ := 0 Θ : ℤ := 0 deriving DecidableEq, Repr - + namespace Dim - + def mul (a b : Dim) : Dim := ⟨a.L + b.L, a.M + b.M, a.T + b.T, a.I + b.I, a.Θ + b.Θ⟩ def inv (a : Dim) : Dim := ⟨-a.L, -a.M, -a.T, -a.I, -a.Θ⟩ - + def one : Dim := {} def meter : Dim := { L := 1 } def kilogram : Dim := { M := 1 } @@ -36,7 +36,7 @@ def joule : Dim := { M := 1, L := 2, T := -2 } def volt : Dim := { M := 1, L := 2, T := -3, I := -1 } def ohm : Dim := { M := 1, L := 2, T := -3, I := -2 } def siemens : Dim := { M := -1, L := -2, T := 3, I := 2 } - + /-- Ohm's law `V = I·R` is dimensionally consistent. -/ theorem ampere_mul_ohm : ampere.mul ohm = volt := by decide /-- `P = V·I`. -/ @@ -49,17 +49,17 @@ theorem inv_ohm : ohm.inv = siemens := by decide theorem watt_mul_second : watt.mul second = joule := by decide /-- Heater power `P = V²/R`. -/ theorem volt_sq_div_ohm : (volt.mul volt).mul ohm.inv = watt := by decide - + end Dim - + /-- A real-valued physical quantity tagged with its dimension. -/ structure Quantity (d : Dim) where val : ℝ - + namespace Quantity - + variable {a b : Dim} - + instance : Add (Quantity a) := ⟨fun x y => ⟨x.val + y.val⟩⟩ instance : Sub (Quantity a) := ⟨fun x y => ⟨x.val - y.val⟩⟩ instance : Neg (Quantity a) := ⟨fun x => ⟨-x.val⟩⟩ @@ -67,14 +67,14 @@ instance : HMul (Quantity a) (Quantity b) (Quantity (a.mul b)) := ⟨fun x y => instance : HDiv (Quantity a) (Quantity b) (Quantity (a.mul b.inv)) := ⟨fun x y => ⟨x.val / y.val⟩⟩ instance : SMul ℝ (Quantity a) := ⟨fun c x => ⟨c * x.val⟩⟩ instance : LE (Quantity a) := ⟨fun x y => x.val ≤ y.val⟩ - + @[simp] theorem add_val (x y : Quantity a) : (x + y).val = x.val + y.val := rfl @[simp] theorem sub_val (x y : Quantity a) : (x - y).val = x.val - y.val := rfl @[simp] theorem hmul_val (x : Quantity a) (y : Quantity b) : (x * y).val = x.val * y.val := rfl @[simp] theorem hdiv_val (x : Quantity a) (y : Quantity b) : (x / y).val = x.val / y.val := rfl - + end Quantity - + abbrev Volt := Quantity Dim.volt abbrev Ampere := Quantity Dim.ampere abbrev Watt := Quantity Dim.watt @@ -86,10 +86,10 @@ abbrev Kelvin := Quantity Dim.kelvin /-- Angles (radians) and plain numbers are dimensionless. -/ abbrev Radian := Quantity Dim.one abbrev Scalar := Quantity Dim.one - + /-- Ohm's law stated on typed quantities: the product of a conductance and a voltage is a current. -/ def ohmsLaw (G : Siemens) (V : Volt) : Ampere := ⟨(G * V).val⟩ - + theorem ohmsLaw_val (G : Siemens) (V : Volt) : (ohmsLaw G V).val = G.val * V.val := rfl - -end Lumiris \ No newline at end of file + +end Lumiris diff --git a/Lean-Semantics/lean/Lumiris/Physics/Control.lean b/Lean-Semantics/lean/Lumiris/Physics/Control.lean new file mode 100644 index 0000000..b428d01 --- /dev/null +++ b/Lean-Semantics/lean/Lumiris/Physics/Control.lean @@ -0,0 +1,46 @@ +import Lumiris.Core.Units +import Lumiris.Core.Approx +import Lumiris.Physics.Photonic + +noncomputable section +namespace Lumiris.Control + +/-- A unipolar voltage DAC. `levels` is 2^bits in the concrete backend. -/ +structure VoltageDAC where + levels : ℕ + levels_ge_two : 2 ≤ levels + fullScale : Volt + fullScale_pos : 0 < fullScale.val + +def VoltageDAC.voltage (d : VoltageDAC) (code : Fin d.levels) : Volt := + ⟨(code.val : ℝ) * d.fullScale.val / ((d.levels - 1 : ℕ) : ℝ)⟩ + +theorem VoltageDAC.safe (d : VoltageDAC) (code : Fin d.levels) : + 0 ≤ (d.voltage code).val ∧ (d.voltage code).val ≤ d.fullScale.val := by + have hn : 0 < d.levels - 1 := by have := d.levels_ge_two; omega + have hd : (0 : ℝ) < ((d.levels - 1 : ℕ) : ℝ) := by exact_mod_cast hn + have hc : code.val ≤ d.levels - 1 := by have := code.isLt; omega + have hc' : (code.val : ℝ) ≤ ((d.levels - 1 : ℕ) : ℝ) := by exact_mod_cast hc + constructor + · exact div_nonneg (mul_nonneg (Nat.cast_nonneg _) d.fullScale_pos.le) hd.le + · change (code.val : ℝ) * d.fullScale.val / ((d.levels - 1 : ℕ) : ℝ) ≤ _ + apply (div_le_iff₀ hd).mpr + nlinarith [d.fullScale_pos] + +/-- End-to-end static-weight MZI error, including input conversion error. +The cosine/weight premise must be established for the calibrated phase interval. +The Python checker currently supplies that premise via exact Taylor interval arithmetic; +its Taylor algorithm is not yet linked to this theorem by a kernel-checked proof. -/ +theorem mzi_error {theta weight x actual delta inputError magnitude : ℝ} + (hd : 0 ≤ delta) (he : 0 ≤ inputError) + (ht : |Photonic.mziAmp theta - weight| ≤ delta) + (hx : |x| ≤ magnitude) (hi : |actual - x| ≤ inputError) : + |Photonic.mziAmp theta * actual - weight * x| ≤ + |weight| * inputError + delta * (magnitude + inputError) := by + have h1 := mul_le_mul ht hx (abs_nonneg _) hd + have h2 := mul_le_mul (le_refl |weight|) hi (abs_nonneg _) (abs_nonneg weight) + have h3 := mul_le_mul ht hi (abs_nonneg _) hd + have h := ErrProp.mul weight (Photonic.mziAmp theta) x actual + nlinarith + +end Lumiris.Control diff --git a/Lean-Semantics/lean/Lumiris/Physics/Laws.lean b/Lean-Semantics/lean/Lumiris/Physics/Laws.lean new file mode 100644 index 0000000..c893157 --- /dev/null +++ b/Lean-Semantics/lean/Lumiris/Physics/Laws.lean @@ -0,0 +1,17 @@ +import Lumiris.Core.Range + +/-! Model-level invariants. They do not certify that a fabricated device follows the model. -/ +namespace Lumiris.Laws + +def Passive (transfer : ℝ → ℝ) : Prop := + ∀ P, 0 ≤ P → 0 ≤ transfer P ∧ transfer P ≤ P + +theorem passive_scale {T : ℝ} (h0 : 0 ≤ T) (h1 : T ≤ 1) : + Passive (fun P => T * P) := by + intro P hP + exact ⟨mul_nonneg h0 hP, by nlinarith⟩ + +def ConservesPower (transfer : ℝ → ℝ × ℝ) : Prop := + ∀ P, 0 ≤ P → (transfer P).1 + (transfer P).2 = P + +end Lumiris.Laws diff --git a/Lean-Semantics/lean/Lumiris/Core/lean/Lumiris/Physics/Photonic.lean b/Lean-Semantics/lean/Lumiris/Physics/Photonic.lean similarity index 91% rename from Lean-Semantics/lean/Lumiris/Core/lean/Lumiris/Physics/Photonic.lean rename to Lean-Semantics/lean/Lumiris/Physics/Photonic.lean index 741f4e0..d462c19 100644 --- a/Lean-Semantics/lean/Lumiris/Core/lean/Lumiris/Physics/Photonic.lean +++ b/Lean-Semantics/lean/Lumiris/Physics/Photonic.lean @@ -4,31 +4,29 @@ import Mathlib.Analysis.SpecialFunctions.Log.Basic import Mathlib.LinearAlgebra.UnitaryGroup import Mathlib.Analysis.SpecialFunctions.Trigonometric.Bounds import Mathlib.LinearAlgebra.Matrix.Notation - + /-! # Photonic branches of the Physics Tree - + Each device gives (1) its transfer function, (2) the physical law it obeys, and (3) a realizability theorem: every target value in the declared range is reachable by some physical parameter. -/ - + noncomputable section namespace Lumiris namespace Photonic - + open Real - + /-! ## Mach–Zehnder interferometer (coherent multiply) -/ - + /-- Full complex transfer matrix of an MZI with internal phase `θ` and external phase `φ` (common output phase dropped). -/ def mzi (θ φ : ℝ) : Matrix (Fin 2) (Fin 2) ℂ := !![Complex.exp (φ * Complex.I) * (Real.sin (θ / 2) : ℂ), (Real.cos (θ / 2) : ℂ); Complex.exp (φ * Complex.I) * (Real.cos (θ / 2) : ℂ), -(Real.sin (θ / 2) : ℂ)] - Matrix.of ![![Complex.exp (φ * Complex.I) * (Real.sin (θ / 2) : ℂ), (Real.cos (θ / 2) : ℂ)], - ![Complex.exp (φ * Complex.I) * (Real.cos (θ / 2) : ℂ), -(Real.sin (θ / 2) : ℂ)]] - + /-- Energy conservation: the MZI matrix is unitary (`Mᴴ M = 1`). -/ theorem mzi_unitary (θ φ : ℝ) : (mzi θ φ)ᴴ * mzi θ φ = 1 := by have hs : (Real.sin (θ / 2) : ℂ) ^ 2 + (Real.cos (θ / 2) : ℂ) ^ 2 = 1 := by @@ -40,18 +38,21 @@ theorem mzi_unitary (θ φ : ℝ) : (mzi θ φ)ᴴ * mzi θ φ = 1 := by ext i j fin_cases i <;> fin_cases j <;> simp [mzi, Matrix.mul_apply, Fin.sum_univ_two, Matrix.conjTranspose_apply] <;> - linear_combination (exp := 1) hs * he - + first + | ring + | linear_combination hs + | linear_combination ((starRingEnd ℂ) (Complex.exp (φ * Complex.I)) * Complex.exp (φ * Complex.I)) * hs + he + /-- Bar-port amplitude transmission (real): `t(θ) = cos(θ/2)`. -/ def mziAmp (θ : ℝ) : ℝ := Real.cos (θ / 2) - + /-- Bar-port power transmission `cos²(θ/2)`, and cross-port `sin²(θ/2)`: they sum to 1. -/ theorem mzi_power_conservation (θ : ℝ) : mziAmp θ ^ 2 + Real.sin (θ / 2) ^ 2 = 1 := by unfold mziAmp; rw [add_comm]; exact Real.sin_sq_add_cos_sq _ - + theorem mziAmp_mem (θ : ℝ) : -1 ≤ mziAmp θ ∧ mziAmp θ ≤ 1 := ⟨Real.neg_one_le_cos _, Real.cos_le_one _⟩ - + /-- **Realizability of signed multiply.** Every weight `w ∈ [-1, 1]` is reached by the phase `θ = 2·arccos w ∈ [0, 2π]`. -/ theorem mziAmp_realizable {w : ℝ} (h0 : -1 ≤ w) (h1 : w ≤ 1) : @@ -62,7 +63,7 @@ theorem mziAmp_realizable {w : ℝ} (h0 : -1 ≤ w) (h1 : w ≤ 1) : · unfold mziAmp rw [show 2 * Real.arccos w / 2 = Real.arccos w by ring] exact Real.cos_arccos h0 h1 - + /-- The MZI realizes `x ↦ w·x` with error only from phase inaccuracy: `|cos(θ'/2) − cos(θ/2)| ≤ |θ' − θ|/2`. -/ theorem mziAmp_phase_error (θ θ' x : ℝ) : @@ -73,58 +74,55 @@ theorem mziAmp_phase_error (θ θ' x : ℝ) : have := Real.abs_cos_sub_cos_le (θ' / 2) (θ / 2) calc |Real.cos (θ' / 2) - Real.cos (θ / 2)| ≤ |θ' / 2 - θ / 2| := this _ = |θ' - θ| / 2 := by rw [show θ' / 2 - θ / 2 = (θ' - θ) / 2 by ring, abs_div]; norm_num - + /-! ## PIN attenuator (incoherent multiply, free-carrier absorption) -/ - + /-- Beer–Lambert transmission `T = e^{−αL}`. -/ def attenT (α L : ℝ) : ℝ := Real.exp (-(α * L)) - + theorem attenT_pos (α L : ℝ) : 0 < attenT α L := Real.exp_pos _ - + theorem attenT_le_one {α L : ℝ} (hα : 0 ≤ α) (hL : 0 ≤ L) : attenT α L ≤ 1 := by unfold attenT have : -(α * L) ≤ 0 := by nlinarith simpa using Real.exp_le_exp.mpr this - + /-- The attenuator is passive. -/ theorem attenT_passive {α L : ℝ} (hα : 0 ≤ α) (hL : 0 ≤ L) : Laws.Passive (fun P => attenT α L * P) := Laws.passive_scale (attenT_pos α L).le (attenT_le_one hα hL) - + /-- **Realizability.** Every `T ∈ (0, 1]` is reached by absorption `αL = −ln T ≥ 0`. -/ theorem attenT_realizable {T : ℝ} (h0 : 0 < T) (h1 : T ≤ 1) : ∃ a, 0 ≤ a ∧ attenT a 1 = T := by refine ⟨-Real.log T, ?_, ?_⟩ · have := Real.log_nonpos h0.le h1; linarith · unfold attenT; simp [Real.exp_log h0] - + /-! ## Microring resonator (wavelength-selective multiply) -/ - + /-- All-pass ring transmission as a Lorentzian in the detuning `δ = λ − λ_res`, with intrinsic half-width `γ` and loaded half-width `Γ` (`0 ≤ γ < Γ`). -/ def mrrT (δ γ Γ : ℝ) : ℝ := (δ ^ 2 + γ ^ 2) / (δ ^ 2 + Γ ^ 2) - + theorem mrrT_le_one {δ γ Γ : ℝ} (hγ : 0 ≤ γ) (hΓ : γ < Γ) : mrrT δ γ Γ ≤ 1 := by unfold mrrT - have hpos : 0 < δ ^ 2 + Γ ^ 2 := by positivity have hΓpos : 0 < Γ := by linarith have hpos : 0 < δ ^ 2 + Γ ^ 2 := add_pos_of_nonneg_of_pos (sq_nonneg δ) (pow_pos hΓpos 2) rw [div_le_one hpos] nlinarith - + theorem mrrT_nonneg (δ γ Γ : ℝ) : 0 ≤ mrrT δ γ Γ := by unfold mrrT; positivity - + /-- Minimum transmission (on resonance) is `γ²/Γ²`; `T = 0` needs critical coupling `γ = 0`. -/ theorem mrrT_ge_floor {δ γ Γ : ℝ} (hγ : 0 ≤ γ) (hΓ : γ < Γ) : γ ^ 2 / Γ ^ 2 ≤ mrrT δ γ Γ := by unfold mrrT have hΓpos : 0 < Γ := by linarith - rw [div_le_div_iff₀ (by positivity) (by positivity)] - nlinarith [sq_nonneg δ, sq_nonneg Γ, sq_nonneg γ] have hpos : 0 < δ ^ 2 + Γ ^ 2 := add_pos_of_nonneg_of_pos (sq_nonneg δ) (pow_pos hΓpos 2) rw [div_le_div_iff₀ (pow_pos hΓpos 2) hpos] have hsq : γ ^ 2 ≤ Γ ^ 2 := by nlinarith nlinarith [mul_le_mul_of_nonneg_left hsq (sq_nonneg δ)] - + /-- **Realizability.** Every `T ∈ [γ²/Γ², 1)` is reached by detuning `δ² = (TΓ² − γ²)/(1 − T)` (two roots `±δ`; the compiler picks one side consistently). -/ theorem mrrT_realizable {T γ Γ : ℝ} (hγ : 0 ≤ γ) (hΓ : γ < Γ) @@ -138,44 +136,45 @@ theorem mrrT_realizable {T γ Γ : ℝ} (hγ : 0 ≤ γ) (hΓ : γ < Γ) have hd2nn : 0 ≤ d2 := div_nonneg hnum h1T.le refine ⟨Real.sqrt d2, Real.sqrt_nonneg _, ?_⟩ unfold mrrT - rw [Real.sq_sqrt hd2nn, hd2] - have hdiff : Γ ^ 2 - γ ^ 2 ≠ 0 := by nlinarith - have h1T' : 1 - T ≠ 0 := ne_of_gt h1T - field_simp - ring - + rw [Real.sq_sqrt hd2nn] + have hden : d2 + Γ ^ 2 ≠ 0 := by positivity + apply (div_eq_iff hden).mpr + dsimp [d2] + field_simp [ne_of_gt h1T] + <;> ring + /-! ## Coherent addition, incoherent addition, balanced subtraction, fan-out -/ - + /-- A 50:50 combiner adds field amplitudes exactly, with a fixed scale `1/√2`. -/ def coherentAdd (E1 E2 : ℝ) : ℝ := (E1 + E2) / Real.sqrt 2 - + theorem coherentAdd_exact (E1 E2 : ℝ) : coherentAdd E1 E2 * Real.sqrt 2 = E1 + E2 := by unfold coherentAdd have : Real.sqrt 2 ≠ 0 := by positivity field_simp - + /-- A π phase shift on one arm turns the combiner into an exact subtractor. -/ theorem coherentSub_exact (E1 E2 : ℝ) : coherentAdd E1 (Real.cos Real.pi * E2) * Real.sqrt 2 = E1 - E2 := by rw [Real.cos_pi, coherentAdd_exact]; ring - + /-- Incoherent (different-wavelength) powers add exactly on one photodetector. -/ def detectorSum {n : ℕ} (P : Fin n → ℝ) : ℝ := ∑ i, P i - + /-- Balanced photodetection: `I = R·(P⁺ − P⁻)` — exact signed subtraction with scale `R`. -/ def balanced (R Pplus Pminus : ℝ) : ℝ := R * (Pplus - Pminus) - + theorem balanced_exact (R Pplus Pminus : ℝ) (hR : R ≠ 0) : balanced R Pplus Pminus / R = Pplus - Pminus := by unfold balanced; field_simp - + /-- Fan-out is not free: a 1:2 splitter gives each branch half the power, conserving energy. -/ def splitter (P : ℝ) : ℝ × ℝ := (P / 2, P / 2) - + theorem splitter_conserves (P : ℝ) : (splitter P).1 + (splitter P).2 = P := by - simp [splitter]; - simp [splitter] - + dsimp [splitter] + ring + end Photonic end Lumiris -end \ No newline at end of file +end diff --git a/Lean-Semantics/lean/Lumiris/Tests.lean b/Lean-Semantics/lean/Lumiris/Tests.lean new file mode 100644 index 0000000..1bdbd3d --- /dev/null +++ b/Lean-Semantics/lean/Lumiris/Tests.lean @@ -0,0 +1,21 @@ +import Lumiris.Core.Encoding +import Lumiris.Core.Semantics +import Lumiris.Physics.Control + +noncomputable section +namespace Lumiris.Tests + +example : Dim.volt.mul Dim.ampere = Dim.watt := by decide +example : (Range.mul ⟨1, 2, by norm_num⟩ ⟨1, 2, by norm_num⟩).lo = 1 := by + norm_num [Range.mul] +example : (Range.div ⟨1, 1, by norm_num⟩ ⟨1, 4, by norm_num⟩).lo = 1 / 4 := by + norm_num [Range.div, Range.mul, Range.reciprocal] +example : (Range.div ⟨1, 1, by norm_num⟩ ⟨-4, -1, by norm_num⟩).hi = -(1 / 4) := by + norm_num [Range.div, Range.mul, Range.reciprocal] +example (x : ℝ) : (Encoding.optPow 1 (by norm_num)).dec + ((Encoding.optPow 1 (by norm_num)).enc x) = x := by + simp [Encoding.optPow, Encoding.scaled] +example : ¬ (Range.sym 1 (by norm_num)).minMag > 0 := by + norm_num [Range.minMag, Range.sym] + +end Lumiris.Tests diff --git a/Lean-Semantics/lean/Lumiris/Core/lean/Lumiris/Physics/lean/lake-manifest.json b/Lean-Semantics/lean/lake-manifest.json similarity index 100% rename from Lean-Semantics/lean/Lumiris/Core/lean/Lumiris/Physics/lean/lake-manifest.json rename to Lean-Semantics/lean/lake-manifest.json diff --git a/Lean-Semantics/lean/lean/lakefile.toml b/Lean-Semantics/lean/lakefile.toml similarity index 89% rename from Lean-Semantics/lean/lean/lakefile.toml rename to Lean-Semantics/lean/lakefile.toml index 85a7afd..a2d15b0 100644 --- a/Lean-Semantics/lean/lean/lakefile.toml +++ b/Lean-Semantics/lean/lakefile.toml @@ -7,4 +7,4 @@ scope = "leanprover-community" rev = "v4.35.0" [[lean_lib]] -name = "Lumiris" \ No newline at end of file +name = "Lumiris" diff --git a/Lean-Semantics/rust/Cargo.lock b/Lean-Semantics/rust/Cargo.lock index e0d10f6..a6028a6 100644 --- a/Lean-Semantics/rust/Cargo.lock +++ b/Lean-Semantics/rust/Cargo.lock @@ -1,411 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 4 - -[[package]] -name = "aho-corasick" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" -dependencies = [ - "memchr", -] - -[[package]] -name = "bindgen" -version = "0.66.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" -dependencies = [ - "bitflags", - "cexpr", - "clang-sys", - "lazy_static", - "lazycell", - "peeking_take_while", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex", - "syn 2.0.119", -] - -[[package]] -name = "bitflags" -version = "2.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" - -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - -[[package]] -name = "cfg-if" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" - -[[package]] -name = "clang-sys" -version = "1.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" -dependencies = [ - "glob", - "libc", - "libloading", -] - -[[package]] -name = "equivalent" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" - -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - -[[package]] -name = "indexmap" -version = "2.14.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" -dependencies = [ - "equivalent", - "hashbrown", -] - -[[package]] -name = "itoa" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" - -[[package]] -name = "lazy_static" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" - -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - -[[package]] -name = "libc" -version = "0.2.191" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" - -[[package]] -name = "libloading" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" -dependencies = [ - "cfg-if", - "windows-link", -] - -[[package]] -name = "log" -version = "0.4.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" - +version = 3 + [[package]] name = "lumiris" -version = "0.1.0" -dependencies = [ - "serde", - "serde_json", - "thiserror", - "toml", - "z3", -] - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - -[[package]] -name = "peeking_take_while" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" - -[[package]] -name = "proc-macro2" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quote" -version = "1.0.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "regex" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "serde" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.229" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", -] - -[[package]] -name = "serde_json" -version = "1.0.154" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_spanned" -version = "0.6.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" -dependencies = [ - "serde", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "syn" -version = "2.0.119" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "toml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.22.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" -dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "toml_write", - "winnow", -] - -[[package]] -name = "toml_write" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" - -[[package]] -name = "unicode-ident" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - -[[package]] -name = "z3" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a7ff5718c079e7b813378d67a5bed32ccc2086f151d6185074a7e24f4a565e8" -dependencies = [ - "log", - "z3-sys", -] - -[[package]] -name = "z3-sys" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7cf70fdbc0de3f42b404f49b0d4686a82562254ea29ff0a155eef2f5430f4b0" -dependencies = [ - "bindgen", -] - -[[package]] -name = "zmij" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" \ No newline at end of file +version = "0.2.0" diff --git a/Lean-Semantics/rust/Cargo.toml b/Lean-Semantics/rust/Cargo.toml index c688a75..ca572b4 100644 --- a/Lean-Semantics/rust/Cargo.toml +++ b/Lean-Semantics/rust/Cargo.toml @@ -1,16 +1,14 @@ [package] name = "lumiris" -version = "0.1.0" +version = "0.2.0" edition = "2021" -description = "Lumiris: a verified physics+math compiler core for photonic and memristive hardware" - -[dependencies] -z3 = "0.12" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -toml = "0.8" -thiserror = "1" - +description = "Bounded arithmetic compiler and proof-carrying MZI demonstrator" + +[lib] +path = "src/lib.rs" + [[bin]] name = "lumiris" -path = "src/main.rs" \ No newline at end of file +path = "src/main.rs" + +[dependencies] diff --git a/Lean-Semantics/rust/rust/src/lib.rs b/Lean-Semantics/rust/rust/src/lib.rs deleted file mode 100644 index d85b222..0000000 --- a/Lean-Semantics/rust/rust/src/lib.rs +++ /dev/null @@ -1,15 +0,0 @@ - -pub fn add(left: u64, right: u64) -> u64 { - left + right -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} \ No newline at end of file diff --git a/Lean-Semantics/rust/rust/src/rust/src/main.rs b/Lean-Semantics/rust/rust/src/rust/src/main.rs deleted file mode 100644 index 12430c8..0000000 --- a/Lean-Semantics/rust/rust/src/rust/src/main.rs +++ /dev/null @@ -1 +0,0 @@ -fn main() { println!("lumiris"); } \ No newline at end of file diff --git a/Lean-Semantics/rust/rustfmt.toml b/Lean-Semantics/rust/rustfmt.toml new file mode 100644 index 0000000..d0d3cc2 --- /dev/null +++ b/Lean-Semantics/rust/rustfmt.toml @@ -0,0 +1,3 @@ +edition = "2021" +style_edition = "2021" +max_width = 100 diff --git a/Lean-Semantics/rust/src/lib.rs b/Lean-Semantics/rust/src/lib.rs new file mode 100644 index 0000000..2118822 --- /dev/null +++ b/Lean-Semantics/rust/src/lib.rs @@ -0,0 +1,319 @@ +//! Lumiris v1: bounded straight-line arithmetic, explicit contracts, fail-closed analysis. +pub mod mzi; +pub mod rational; +use rational::{Interval, Rat}; +use std::{collections::BTreeMap, fmt}; +#[derive(Clone, Debug)] +pub struct Error(String); +impl Error { + pub fn new(s: impl Into) -> Self { + Self(s.into()) + } +} +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0) + } +} +impl std::error::Error for Error {} +pub type Result = std::result::Result; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Op { + Add, + Sub, + Mul, + Div, +} +impl Op { + pub fn name(self) -> &'static str { + match self { + Self::Add => "add", + Self::Sub => "sub", + Self::Mul => "mul", + Self::Div => "div", + } + } +} +#[derive(Clone, Debug)] +pub enum Kind { + Input, + Const(Rat), + Binary { + op: Op, + a: String, + b: String, + local: Rat, + input: Interval, + output: Interval, + }, +} +#[derive(Clone, Debug)] +pub struct Node { + pub name: String, + pub kind: Kind, + pub range: Interval, + pub error: Rat, +} +#[derive(Clone, Debug)] +pub struct Program { + pub nodes: Vec, + pub output: String, + pub tolerance: Rat, +} +fn rat(s: &str) -> Result { + s.parse() +} +fn nonneg(x: Rat) -> Result { + if x.nonneg() { + Ok(x) + } else { + Err(Error::new("negative error/tolerance")) + } +} +fn identifier(s: &str) -> bool { + s.len() <= 64 + && s.as_bytes() + .first() + .is_some_and(|c| c.is_ascii_alphabetic()) + && s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_') +} +impl Program { + pub fn parse(source: &str) -> Result { + if source.len() > 65536 { + return Err(Error::new("program exceeds 64 KiB")); + } + let mut nodes: Vec = Vec::new(); + let mut names = BTreeMap::::new(); + let mut output = None; + let mut header = false; + for (line_no, line) in source.lines().enumerate() { + let t: Vec<_> = line.split('#').next().unwrap().split_whitespace().collect(); + if t.is_empty() { + continue; + } + let result = (|| -> Result<()> { + if !header { + if t != ["lumiris", "1"] { + return Err(Error::new("expected lumiris 1 header")); + } + header = true; + return Ok(()); + } + if output.is_some() { + return Err(Error::new("output must be the final statement")); + } + if t[0] == "output" { + if t.len() != 3 || !names.contains_key(t[1]) { + return Err(Error::new("output requires an existing node and tolerance")); + } + let tolerance = nonneg(rat(t[2])?)?; + if nodes[*names.get(t[1]).unwrap()].error > tolerance { + return Err(Error::new( + "output error budget exceeds requested tolerance", + )); + } + output = Some((t[1].to_string(), tolerance)); + return Ok(()); + } + if nodes.len() >= 256 { + return Err(Error::new("at most 256 nodes supported")); + } + if t.len() < 2 || !identifier(t[1]) || names.contains_key(t[1]) { + return Err(Error::new("invalid or duplicate node name")); + } + let node = match t[0] { + "input" if t.len() == 5 => Node { + name: t[1].into(), + kind: Kind::Input, + range: Interval::new(rat(t[2])?, rat(t[3])?)?, + error: nonneg(rat(t[4])?)?, + }, + "const" if t.len() == 4 => { + let v = rat(t[2])?; + Node { + name: t[1].into(), + kind: Kind::Const(v), + range: Interval::point(v), + error: nonneg(rat(t[3])?)?, + } + } + "add" | "sub" | "mul" | "div" if t.len() == 9 => { + let op = match t[0] { + "add" => Op::Add, + "sub" => Op::Sub, + "mul" => Op::Mul, + _ => Op::Div, + }; + let get = |s: &str| -> Result<&Node> { + names.get(s).map(|i| &nodes[*i]).ok_or_else(|| { + Error::new(format!("undefined or forward reference: {s}")) + }) + }; + let (a, b) = (get(t[2])?, get(t[3])?); + let local = nonneg(rat(t[4])?)?; + let input = Interval::new(rat(t[5])?, rat(t[6])?)?; + let physical_output = Interval::new(rat(t[7])?, rat(t[8])?)?; + if !input.contains(a.range.inflate(a.error)?) + || !input.contains(b.range.inflate(b.error)?) + { + return Err(Error::new( + "perturbed operand outside device input domain", + )); + } + let range = match op { + Op::Add => a.range.add(b.range)?, + Op::Sub => a.range.sub(b.range)?, + Op::Mul => a.range.mul(b.range)?, + Op::Div => a.range.div(b.range)?, + }; + let ea = a.error; + let eb = b.error; + let ma = a.range.mag(); + let mb = b.range.mag(); + let propagated = match op { + Op::Add | Op::Sub => ea.add(eb)?, + Op::Mul => ea.mul(mb)?.add(ma.mul(eb)?)?.add(ea.mul(eb)?)?, + Op::Div => { + let m = b.range.min_mag(); + if eb >= m { + return Err(Error::new("perturbed divisor can reach zero")); + } + ea.mul(mb)?.add(ma.mul(eb)?)?.div(m.mul(m.sub(eb)?)?)? + } + }; + let error = propagated.add(local)?; + if !physical_output.contains(range.inflate(error)?) { + return Err(Error::new( + "perturbed result outside device output domain (saturation)", + )); + } + Node { + name: t[1].into(), + kind: Kind::Binary { + op, + a: t[2].into(), + b: t[3].into(), + local, + input, + output: physical_output, + }, + range, + error, + } + } + _ => return Err(Error::new("unknown statement or wrong number of fields")), + }; + names.insert(node.name.clone(), nodes.len()); + nodes.push(node); + Ok(()) + })(); + result.map_err(|e| Error::new(format!("line {}: {e}", line_no + 1)))?; + } + let (output, tolerance) = output.ok_or_else(|| Error::new("missing output statement"))?; + Ok(Self { + nodes, + output, + tolerance, + }) + } + pub fn node(&self, name: &str) -> &Node { + self.nodes + .iter() + .find(|n| n.name == name) + .expect("validated reference") + } + /// Exact rational reference interpretation. Input uncertainty belongs to analysis, not eval. + pub fn eval(&self, env: &BTreeMap) -> Result { + let mut values = BTreeMap::new(); + for n in &self.nodes { + let v = match &n.kind { + Kind::Input => { + let v = *env + .get(&n.name) + .ok_or_else(|| Error::new(format!("missing input {}", n.name)))?; + if !n.range.contains(Interval::point(v)) { + return Err(Error::new("input outside declared range")); + } + v + } + Kind::Const(c) => *c, + Kind::Binary { op, a, b, .. } => { + let x: Rat = values[a]; + let y: Rat = values[b]; + match op { + Op::Add => x.add(y)?, + Op::Sub => x.sub(y)?, + Op::Mul => x.mul(y)?, + Op::Div => x.div(y)?, + } + } + }; + values.insert(n.name.clone(), v); + } + Ok(values[&self.output]) + } + pub fn certificate(&self) -> String { + let mut s = String::from("lumiris-certificate 1\n"); + for n in &self.nodes { + s.push_str(&format!( + "node {} {} {} {}\n", + n.name, n.range.lo, n.range.hi, n.error + )); + } + s.push_str(&format!("output {} {}\n", self.output, self.tolerance)); + s + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unsafe_division() { + assert!(Program::parse( + "lumiris 1\ninput x -1 1 0\nconst a 1 0\ndiv y a x 0 -2 2 -10 10\noutput y 1" + ) + .is_err()); + } + #[test] + fn uncertain_division() { + assert!(Program::parse( + "lumiris 1\ninput x 1 2 1\nconst a 1 0\ndiv y a x 0 -3 3 -10 10\noutput y 10" + ) + .is_err()); + } + #[test] + fn actual_domain() { + assert!(Program::parse( + "lumiris 1\ninput x 0 1 1/10\nconst a 1 0\nmul y a x 0 0 1 -2 2\noutput y 1" + ) + .is_err()); + } + #[test] + fn constant_error() { + let p = Program::parse( + "lumiris 1\nconst a 1 1/10\nconst b 2 1/10\nmul y a b 1/100 -3 3 -4 4\noutput y 1", + ) + .unwrap(); + assert_eq!(p.node("y").error, "8/25".parse().unwrap()); + } + #[test] + fn rejects_bad_syntax() { + for s in [ + "", + "lumiris 2", + "lumiris 1\nconst a 0 0\nconst a 1 0\noutput a 0", + "lumiris 1\nadd a b c 0 -1 1 -2 2\noutput a 0", + "lumiris 1\nconst a 1 -1\noutput a 0", + ] { + assert!(Program::parse(s).is_err()); + } + } + #[test] + fn exact_division() { + let p=Program::parse("lumiris 1\ninput x 1 2 0\nmul square x x 0 0 4 0 4\nconst one 1 0\ndiv y one square 0 0 4 0 2\noutput y 0").unwrap(); + assert_eq!(p.node("y").range.lo, "1/4".parse().unwrap()); + let mut e = BTreeMap::new(); + e.insert("x".into(), "2".parse().unwrap()); + assert_eq!(p.eval(&e).unwrap(), "1/4".parse().unwrap()); + } +} diff --git a/Lean-Semantics/rust/src/main.rs b/Lean-Semantics/rust/src/main.rs new file mode 100644 index 0000000..6f7ad60 --- /dev/null +++ b/Lean-Semantics/rust/src/main.rs @@ -0,0 +1,79 @@ +use lumiris::{mzi, Error, Program, Result}; +use std::{collections::BTreeMap, fs, path::PathBuf}; +fn read(path: &str) -> Result { + let meta = fs::metadata(path).map_err(|e| Error::new(e.to_string()))?; + if meta.len() > 65536 { + return Err(Error::new("input file exceeds 64 KiB")); + } + fs::read_to_string(path).map_err(|e| Error::new(e.to_string())) +} +fn run() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some("eval") && args.len() >= 2 { + let p = Program::parse(&read(&args[1])?)?; + let mut env = BTreeMap::new(); + for arg in &args[2..] { + let (k, v) = arg + .split_once('=') + .ok_or_else(|| Error::new("expected input=value"))?; + if !matches!( + p.nodes.iter().find(|n| n.name == k).map(|n| &n.kind), + Some(lumiris::Kind::Input) + ) || env.insert(k.into(), v.parse()?).is_some() + { + return Err(Error::new("unknown or duplicate input assignment")); + } + } + println!("{}", p.eval(&env)?); + return Ok(()); + } + if args.len() != 3 && args.len() != 5 { + return Err(Error::new("usage: lumiris compile PROGRAM OUTPUT_DIR [--device DEVICE]\n lumiris eval PROGRAM name=n/d ...")); + } + if args[0] != "compile" || (args.len() == 5 && args[3] != "--device") { + return Err(Error::new("invalid command/options")); + } + let source = read(&args[1])?; + let p = Program::parse(&source)?; + let physical = if args.len() == 5 { + let text = read(&args[4])?; + let device = mzi::Device::parse(&text)?; + let c = mzi::compile(&p, &device)?; + Some((text, c.text(&device))) + } else { + None + }; + let out = PathBuf::from(&args[2]); + if out.exists() { + return Err(Error::new( + "output directory already exists; choose a fresh path", + )); + } + fs::create_dir_all(&out).map_err(|e| Error::new(e.to_string()))?; + let write = |name: &str, text: &str| { + fs::write(out.join(name), text).map_err(|e| Error::new(e.to_string())) + }; + write("program.lumi", &source)?; + write("arithmetic.cert", &p.certificate())?; + if let Some((device, certificate)) = physical { + write("device.mzi", &device)?; + write("physical.cert", &certificate)?; + } + println!( + "Compiled {} nodes. Output {}: range [{}, {}], error <= {} (requested {}).", + p.nodes.len(), + p.output, + p.node(&p.output).range.lo, + p.node(&p.output).range.hi, + p.node(&p.output).error, + p.tolerance + ); + println!("Artifacts: {}. Run scripts/check_certificate.py to independently check them; compilation alone is not verification.",out.display()); + Ok(()) +} +fn main() { + if let Err(e) = run() { + eprintln!("lumiris: {e}"); + std::process::exit(1); + } +} diff --git a/Lean-Semantics/rust/src/mzi.rs b/Lean-Semantics/rust/src/mzi.rs new file mode 100644 index 0000000..4d747cc --- /dev/null +++ b/Lean-Semantics/rust/src/mzi.rs @@ -0,0 +1,297 @@ +//! One calibrated thermo-optic MZI, one live field input, one static signed weight. +//! Float inversion proposes a DAC code; exact interval checks decide acceptance. +use crate::rational::{Interval, Rat}; +use crate::{Error, Kind, Op, Program, Result}; +use std::collections::BTreeMap; +pub const SCALE: i128 = 1_000_000_000; +#[derive(Clone, Copy, Debug)] +struct Fixed { + lo: i128, + hi: i128, +} +fn down(n: i128, d: i128) -> i128 { + n.div_euclid(d) +} +fn up(n: i128, d: i128) -> i128 { + -(-n).div_euclid(d) +} +impl Fixed { + fn of(x: Interval) -> Self { + Self { + lo: down(x.lo.n as i128 * SCALE, x.lo.d as i128), + hi: up(x.hi.n as i128 * SCALE, x.hi.d as i128), + } + } + fn add(self, b: Self) -> Self { + Self { + lo: self.lo + b.lo, + hi: self.hi + b.hi, + } + } + fn neg(self) -> Self { + Self { + lo: -self.hi, + hi: -self.lo, + } + } + fn mul(self, b: Self) -> Self { + let p = [ + self.lo * b.lo, + self.lo * b.hi, + self.hi * b.lo, + self.hi * b.hi, + ]; + Self { + lo: down(*p.iter().min().unwrap(), SCALE), + hi: up(*p.iter().max().unwrap(), SCALE), + } + } + fn div_int(self, d: i128) -> Self { + Self { + lo: down(self.lo, d), + hi: up(self.hi, d), + } + } +} +/// Degree-32 cosine polynomial and absolute Lagrange remainder x^34/34!. +/// Directed integer rounding encloses every polynomial operation. +pub fn cos_enclosure(theta: Interval) -> Result { + let half = "1/2".parse::()?; + let x = theta.mul(Interval::point(half))?; + if x.mag() > "8".parse()? { + return Err(Error::new( + "phase outside certified cosine domain |theta/2| <= 8", + )); + } + let x = Fixed::of(x); + let square = x.mul(x); + let mut term = Fixed { + lo: SCALE, + hi: SCALE, + }; + let mut sum = term; + for j in 1..=16 { + term = term.mul(square).div_int((2 * j - 1) * (2 * j)); + sum = sum.add(if j % 2 == 0 { term } else { term.neg() }); + } + let remainder = term.mul(square).div_int(33 * 34); + let r = remainder.lo.abs().max(remainder.hi.abs()); + Interval::new( + Rat::new((sum.lo - r).max(-SCALE), SCALE)?, + Rat::new((sum.hi + r).min(SCALE), SCALE)?, + ) +} +#[derive(Clone, Debug)] +pub struct Device { + pub id: String, + pub vmax: Rat, + pub bits: u32, + pub k: Rat, + pub offset: Rat, + pub phase_error: Rat, + pub input_limit: Rat, +} +impl Device { + pub fn parse(text: &str) -> Result { + let mut fields = BTreeMap::new(); + let mut header = false; + for line in text.lines() { + let t: Vec<_> = line.split('#').next().unwrap().split_whitespace().collect(); + if t.is_empty() { + continue; + } + if !header { + if t != ["lumiris-mzi", "1"] { + return Err(Error::new("expected lumiris-mzi 1 header")); + } + header = true; + continue; + } + if t.len() != 2 || fields.insert(t[0], t[1]).is_some() { + return Err(Error::new("device field duplicated or malformed")); + } + } + let keys = [ + "id", + "voltage_max", + "dac_bits", + "phase_per_v2", + "phase_offset", + "phase_error", + "input_limit", + ]; + if fields.len() != keys.len() || keys.iter().any(|k| !fields.contains_key(k)) { + return Err(Error::new("unknown or missing device field")); + } + let get = |k: &str| -> Result { fields[k].parse() }; + let d = Self { + id: fields["id"].into(), + vmax: get("voltage_max")?, + bits: fields["dac_bits"] + .parse() + .map_err(|_| Error::new("invalid DAC bits"))?, + k: get("phase_per_v2")?, + offset: get("phase_offset")?, + phase_error: get("phase_error")?, + input_limit: get("input_limit")?, + }; + if d.vmax <= Rat::ZERO + || d.vmax > "10".parse()? + || !(2..=16).contains(&d.bits) + || d.k <= Rat::ZERO + || d.k > Rat::ONE + || d.offset.abs() > Rat::ONE + || !d.phase_error.nonneg() + || d.phase_error > Rat::ONE + || d.input_limit <= Rat::ZERO + || d.input_limit > Rat::ONE + { + return Err(Error::new( + "device parameters outside supported safe domain", + )); + } + Ok(d) + } + pub fn voltage(&self, code: u32) -> Result { + if code >= (1 << self.bits) { + return Err(Error::new("DAC code outside range")); + } + self.vmax + .mul(Rat::new(code as i128, ((1u32 << self.bits) - 1) as i128)?) + } + pub fn phase(&self, code: u32) -> Result { + let v = self.voltage(code)?; + Interval::point(self.k.mul(v.mul(v)?)?.add(self.offset)?).inflate(self.phase_error) + } +} +#[derive(Debug)] +pub struct Binding { + pub input: String, + pub weight: Rat, + pub local_budget: Rat, + pub input_range: Interval, + pub input_error: Rat, +} +pub fn bind(p: &Program) -> Result { + if p.nodes.len() != 3 { + return Err(Error::new( + "MZI MVP requires exactly one input, one exact constant, one multiply", + )); + } + let out = p.node(&p.output); + let (a, b, local) = match &out.kind { + Kind::Binary { + op: Op::Mul, + a, + b, + local, + .. + } => (p.node(a), p.node(b), *local), + _ => return Err(Error::new("MZI output must be a multiply")), + }; + let (input, weight) = match (&a.kind, &b.kind) { + (Kind::Input, Kind::Const(w)) => (a, (b, *w)), + (Kind::Const(w), Kind::Input) => (b, (a, *w)), + _ => { + return Err(Error::new( + "MZI multiply needs a static weight and live input", + )) + } + }; + if weight.0.error != Rat::ZERO || weight.1.abs() > Rat::ONE { + return Err(Error::new("MZI static weight must be exact and in [-1,1]")); + } + Ok(Binding { + input: input.name.clone(), + weight: weight.1, + local_budget: local, + input_range: input.range, + input_error: input.error, + }) +} +#[derive(Debug)] +pub struct Certificate { + pub code: u32, + pub voltage: Rat, + pub phase: Interval, + pub transmission: Interval, + pub weight_error: Rat, + pub local_error: Rat, + pub total_error: Rat, +} +impl Certificate { + pub fn text(&self, d: &Device) -> String { + format!("lumiris-mzi-certificate 1\nmodel {}\ncode {}\nvoltage {}\nphase {} {}\ntransmission {} {}\nweight_error {}\nlocal_error {}\ntotal_error {}\n",d.id,self.code,self.voltage,self.phase.lo,self.phase.hi,self.transmission.lo,self.transmission.hi,self.weight_error,self.local_error,self.total_error) + } +} +pub fn compile(p: &Program, d: &Device) -> Result { + let b = bind(p)?; + let actual = b.input_range.inflate(b.input_error)?; + if actual.mag() > d.input_limit { + return Err(Error::new( + "MZI input field exceeds calibrated amplitude limit", + )); + } + let theta = 2.0 * b.weight.f64().acos(); + let power = (theta - d.offset.f64()) / d.k.f64(); + let desired = power.max(0.0).sqrt() / d.vmax.f64() * ((1u32 << d.bits) - 1) as f64; + if !desired.is_finite() { + return Err(Error::new("inverse model failed")); + } + let max = (1u32 << d.bits) - 1; + let center = desired.round().clamp(0.0, max as f64) as u32; + let mut best: Option = None; + for code in center.saturating_sub(1)..=center.saturating_add(1).min(max) { + let phase = d.phase(code)?; + let transmission = cos_enclosure(phase)?; + let weight_error = transmission + .lo + .sub(b.weight)? + .abs() + .max(transmission.hi.sub(b.weight)?.abs()); + let local_error = weight_error.mul(actual.mag())?; + let total_error = b.weight.abs().mul(b.input_error)?.add(local_error)?; + let c = Certificate { + code, + voltage: d.voltage(code)?, + phase, + transmission, + weight_error, + local_error, + total_error, + }; + if best.as_ref().is_none_or(|v| c.total_error < v.total_error) { + best = Some(c); + } + } + let c = best.ok_or_else(|| Error::new("no DAC candidate"))?; + if c.local_error > b.local_budget || c.total_error > p.tolerance { + return Err(Error::new(format!( + "MZI resolution/calibration cannot meet budget: local {}, total {}", + c.local_error, c.total_error + ))); + } + Ok(c) +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn cosine_bounds() { + for i in -160..=160 { + let t = Rat::new(i, 10).unwrap(); + let a = cos_enclosure(Interval::point(t)).unwrap(); + let y = (t.f64() / 2.0).cos(); + assert!( + a.lo.f64() <= y + 1e-15 && y <= a.hi.f64() + 1e-15, + "{i}: {a:?}" + ); + } + } + #[test] + fn broad_cosine() { + let a = cos_enclosure(Interval::new("-1".parse().unwrap(), "1".parse().unwrap()).unwrap()) + .unwrap(); + assert!(a.lo.f64() <= 0.5f64.cos() && a.hi == Rat::ONE); + } +} diff --git a/Lean-Semantics/rust/src/rational.rs b/Lean-Semantics/rust/src/rational.rs new file mode 100644 index 0000000..a14b109 --- /dev/null +++ b/Lean-Semantics/rust/src/rational.rs @@ -0,0 +1,195 @@ +//! Exact bounded rationals. Overflow is an error, never a wrapped certificate. +use crate::{Error, Result}; +use std::{cmp::Ordering, fmt, str::FromStr}; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rat { + pub(crate) n: i64, + pub(crate) d: i64, +} +fn gcd(mut a: i128, mut b: i128) -> i128 { + while b != 0 { + let r = a % b; + a = b; + b = r; + } + a +} +impl Rat { + pub const ZERO: Self = Self { n: 0, d: 1 }; + pub const ONE: Self = Self { n: 1, d: 1 }; + pub fn numerator(self) -> i64 { + self.n + } + pub fn denominator(self) -> i64 { + self.d + } + pub fn new(n: i128, d: i128) -> Result { + if d == 0 || n == i128::MIN || d == i128::MIN { + return Err(Error::new("invalid rational")); + } + let (n, d) = if d < 0 { (-n, -d) } else { (n, d) }; + let g = gcd(n.abs(), d); + let (n, d) = (n / g, d / g); + if n.abs() > i64::MAX as i128 || d > i64::MAX as i128 { + return Err(Error::new( + "rational capacity exceeded; simplify or rescale", + )); + } + Ok(Self { + n: n as i64, + d: d as i64, + }) + } + pub fn add(self, b: Self) -> Result { + Self::new( + self.n as i128 * b.d as i128 + b.n as i128 * self.d as i128, + self.d as i128 * b.d as i128, + ) + } + pub fn neg(self) -> Self { + Self { + n: -self.n, + d: self.d, + } + } + pub fn sub(self, b: Self) -> Result { + self.add(b.neg()) + } + pub fn mul(self, b: Self) -> Result { + Self::new(self.n as i128 * b.n as i128, self.d as i128 * b.d as i128) + } + pub fn div(self, b: Self) -> Result { + Self::new(self.n as i128 * b.d as i128, self.d as i128 * b.n as i128) + } + pub fn abs(self) -> Self { + Self { + n: self.n.abs(), + d: self.d, + } + } + pub fn f64(self) -> f64 { + self.n as f64 / self.d as f64 + } + pub fn nonneg(self) -> bool { + self.n >= 0 + } +} +impl Ord for Rat { + fn cmp(&self, b: &Self) -> Ordering { + (self.n as i128 * b.d as i128).cmp(&(b.n as i128 * self.d as i128)) + } +} +impl PartialOrd for Rat { + fn partial_cmp(&self, b: &Self) -> Option { + Some(self.cmp(b)) + } +} +impl fmt::Display for Rat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}/{}", self.n, self.d) + } +} +impl FromStr for Rat { + type Err = Error; + fn from_str(s: &str) -> Result { + if s.len() > 80 { + return Err(Error::new("rational token too long")); + } + let parts: Vec<_> = s.split('/').collect(); + let parse = |v: &str| { + v.parse::() + .map_err(|_| Error::new("expected integer or n/d rational")) + }; + match parts.as_slice() { + [n] => Self::new(parse(n)? as i128, 1), + [n, d] => Self::new(parse(n)? as i128, parse(d)? as i128), + _ => Err(Error::new("invalid rational")), + } + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Interval { + pub lo: Rat, + pub hi: Rat, +} +impl Interval { + pub fn new(lo: Rat, hi: Rat) -> Result { + if lo > hi { + Err(Error::new("reversed interval")) + } else { + Ok(Self { lo, hi }) + } + } + pub fn point(x: Rat) -> Self { + Self { lo: x, hi: x } + } + pub fn mag(self) -> Rat { + self.lo.abs().max(self.hi.abs()) + } + pub fn min_mag(self) -> Rat { + if self.lo > Rat::ZERO { + self.lo + } else if self.hi < Rat::ZERO { + self.hi.abs() + } else { + Rat::ZERO + } + } + pub fn contains(self, b: Self) -> bool { + self.lo <= b.lo && b.hi <= self.hi + } + pub fn inflate(self, e: Rat) -> Result { + Self::new(self.lo.sub(e)?, self.hi.add(e)?) + } + pub fn add(self, b: Self) -> Result { + Self::new(self.lo.add(b.lo)?, self.hi.add(b.hi)?) + } + pub fn sub(self, b: Self) -> Result { + Self::new(self.lo.sub(b.hi)?, self.hi.sub(b.lo)?) + } + pub fn mul(self, b: Self) -> Result { + let p = [ + self.lo.mul(b.lo)?, + self.lo.mul(b.hi)?, + self.hi.mul(b.lo)?, + self.hi.mul(b.hi)?, + ]; + Self::new(*p.iter().min().unwrap(), *p.iter().max().unwrap()) + } + pub fn div(self, b: Self) -> Result { + if b.min_mag() == Rat::ZERO { + return Err(Error::new("divisor interval touches zero")); + } + self.mul(Self::new(Rat::ONE.div(b.hi)?, Rat::ONE.div(b.lo)?)?) + } +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn exact() { + let a: Rat = "-2/4".parse().unwrap(); + assert_eq!(a.to_string(), "-1/2"); + assert_eq!(a.add(a).unwrap().to_string(), "-1/1"); + } + #[test] + fn reject() { + for s in ["1/0", "NaN", "1.1", "-9223372036854775808", "1/2/3"] { + assert!(s.parse::().is_err(), "{s}"); + } + } + #[test] + fn overflow() { + let a: Rat = "9223372036854775807".parse().unwrap(); + assert!(a.add(Rat::ONE).is_err()); + assert_eq!(a.cmp(&a.neg()), Ordering::Greater); + } + #[test] + fn positive_product() { + let a = Interval::new(Rat::ONE, "2".parse().unwrap()).unwrap(); + let p = a.mul(a).unwrap(); + assert_eq!(p.lo, Rat::ONE); + assert_eq!(p.hi, "4".parse().unwrap()); + assert!(a.div(p).is_ok()); + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..051ae3e --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ +# Lumiris — bounded arithmetic to photonic controls + +Lumiris is an early compiler foundation for photonic and memristive computing. +The executable MVP compiles **bounded, straight-line real arithmetic** and lowers +one static-weight multiplication to an illustrative thermo-optic MZI model. +It does **not** compile arbitrary mathematics, program a real chip, or implement +an adaptive runtime yet. + +## What works + +- A Rust compiler/reference interpreter with no third-party dependencies. +- Versioned textual SSA IR with exact rational constants and explicit uncertainty. +- Tight interval arithmetic, per-node physical input/output contracts, and composed + absolute-error budgets for addition, subtraction, multiplication, and division. +- Fail-closed rejection of zero/uncertain divisors, saturation, invalid domains, + arithmetic overflow, malformed programs, and unsupported device mappings. +- MZI static-weight selection, heater inversion, finite DAC quantization, bounded + calibration error, and directed-rounding cosine enclosures. +- A separate Python checker using arbitrary-precision `Fraction` arithmetic. It + recomputes certificates from the source and device description, rather than + trusting Rust's decisions or its floating-point inverse calculation. +- SW-1 analytical simulation with boundary vectors, seeded disturbances, and + energy-conservation checks. +- A repaired Lean project layout, bounded device-contract theorem scripts, and + generated kernel-checkable **numeric obligations**. See the verification caveat below. + +## Requirements + +- Rust/Cargo **1.82+**; current stable recommended. +- Python **3.11+**, standard library only. +- Optional formal validation: elan, the pinned Lean **4.35.0**, and Mathlib. + Initial Lean dependency/toolchain/cache downloads require network access. + +The Rust compiler, checker, and simulator work offline after Rust is installed. +There is no Z3/JAX installation requirement for this deliberately small MVP: +exact rational inequalities suffice here. Those integrations remain future work. + +## Run the complete executable demonstration + +From the repository root: + +```bash +scripts/demo.sh +``` + +The output directory must not already exist. Choose a new one for another run: + +```bash +scripts/demo.sh artifacts/another-run +``` + +Pipeline: + +```text +examples/mzi-scale.lumi + devices/demo-mzi.mzi + → Rust bounded analysis and MZI lowering + → source-bound arithmetic and physical certificate bundle + → independent exact-rational checker + → generated Lean numeric obligations + → analytical simulation and JSON report +``` + +To also build the formal library and check the generated numeric obligations: + +```bash +# First-time Mathlib preparation: +(cd Lean-Semantics/lean && lake exe cache get) + +scripts/demo.sh artifacts/with-lean --lean +# Or check an existing demo: +scripts/check_lean.sh artifacts/mzi-demo +``` + +**Formal-validation status:** Lean could not be executed in the development +sandbox: Lean/Lake were absent and toolchain release-asset downloads were blocked. +The formal library changes and generated obligations are therefore **not locally +kernel-validated**. CI includes a required-to-pass formal build job, but its result +must be observed before calling the formal milestone complete. + +Even after that job passes, the generated numeric obligations do **not** constitute +a complete Lean proof of the parser, certificate checker, Taylor-enclosure algorithm, +or source-to-hardware compilation. Those trust boundaries are documented in +[docs/verification.md](docs/verification.md). No hardware guarantee is claimed. + +## Example program + +```text +lumiris 1 +input x -9/10 9/10 1/10000 +const weight 1/2 0 +mul y weight x 1/1000 -1 1 -1 1 +output y 11/10000 +``` + +This asks for `y = 0.5 × x` with bounded input conversion uncertainty, a per-op +local-error allowance, and explicit device operating domains. +See [docs/ir.md](docs/ir.md) for the complete grammar and mathematical contracts. + +The illustrative calibration gives these reproducible results: + +| Quantity | Result | +|---|---:| +| DAC code | 1891 of 4095 | +| Heater voltage | approximately 2.308913309 V | +| Ideal output interval | [−0.45, 0.45] | +| Arithmetic contract bound | 0.00105 | +| Independently checked physical-model bound | 0.0004005385444 | +| Maximum sampled error, default seed | approximately 0.0003988068894 | +| Sample vectors | 1018 | + +The calibrated phase coefficient is a rational model parameter, **not an assertion +that a particular fabricated heater has that coefficient**. The device file is +illustrative and is not hardware authorization. + +## Other commands + +```bash +# Exact reference interpretation (rational result): +cargo run --locked --offline --manifest-path Lean-Semantics/rust/Cargo.toml -- \ + eval examples/mzi-scale.lumi x=1/2 +# 1/4 + +# Arithmetic-only graph, including a safe nonlinear denominator: +cargo run --locked --offline --manifest-path Lean-Semantics/rust/Cargo.toml -- \ + compile examples/safe-division.lumi artifacts/division +python3 scripts/check_certificate.py artifacts/division \ + --source examples/safe-division.lumi + +# Expected rejection, nonzero exit status, no compilation bundle: +cargo run --locked --offline --manifest-path Lean-Semantics/rust/Cargo.toml -- \ + compile examples/reject-zero-divisor.lumi artifacts/rejected +``` + +## Tests + +```bash +scripts/test.sh +``` + +This runs the repository-layout/import audit, Rust unit tests, and Python +integration/property/adversarial tests. Coverage includes certificate tampering, +calibration mismatch, unsupported models, positive and negative static weights, +precision failure, output saturation, unsafe division, input domains, and exact +reference evaluation. Randomized tests compare both implementations and check +composed bounds against perturbed arithmetic. + +The layout audit is not a substitute for `lake build`. CI separates executable +validation from formal validation; a passing executable job alone is insufficient +for claiming all formal proofs check. + +## Repository map + +```text +Lean-Semantics/ + lean/ Lean/Mathlib project, all modules reachable from Lumiris + Lumiris/Core/ units, ranges, encodings, semantics, bounded contracts + Lumiris/Physics/ laws, photonic transfer models, DAC and error theorems + rust/ dependency-free compiler and exact interpreter + src/rational.rs checked rational and tight interval arithmetic + src/lib.rs parser, SSA analysis, error contracts, reference semantics + src/mzi.rs calibrated MZI branch and certificate generation + src/main.rs CLI and artifact emission +scripts/ independent checker, SW-1 simulator, demo/test/formal scripts +examples/ accepted and deliberately rejected input programs +devices/ illustrative versioned device model +tests/ cross-implementation and adversarial tests +docs/ formats, verification boundaries, milestone status +``` + +For the long-term vision, see [the plan](photonic-memristor-compiler-plan.md). +For what has actually been implemented and what remains, see +[docs/milestones.md](docs/milestones.md). diff --git a/devices/demo-mzi.mzi b/devices/demo-mzi.mzi new file mode 100644 index 0000000..527b0b1 --- /dev/null +++ b/devices/demo-mzi.mzi @@ -0,0 +1,11 @@ +# Illustrative calibration, NOT a real chip datasheet or hardware authorization. +lumiris-mzi 1 +id illustrative-thermo-optic-v1 +voltage_max 5 +dac_bits 12 +# rad / V^2; rational calibrated model parameter (not claimed equal to pi/8). +phase_per_v2 392699/1000000 +phase_offset 0 +# Absolute bounded phase-model residual, including drift during one invocation. +phase_error 1/100000 +input_limit 1 diff --git a/docs/ir.md b/docs/ir.md new file mode 100644 index 0000000..c88dff7 --- /dev/null +++ b/docs/ir.md @@ -0,0 +1,161 @@ +# Lumiris v1 formats and contracts + +## Program grammar + +UTF-8 plain text, one statement per line. Blank lines and `#` comments are ignored. +Numbers are signed integers or integer fractions `n/d`; decimals, exponents, NaN, +and infinity are rejected. Canonical certificate numbers are reduced fractions. + +```text +lumiris 1 +input NAME LO HI ERROR +const NAME VALUE ERROR +add NAME LEFT RIGHT LOCAL_ERROR INPUT_LO INPUT_HI OUTPUT_LO OUTPUT_HI +sub NAME LEFT RIGHT LOCAL_ERROR INPUT_LO INPUT_HI OUTPUT_LO OUTPUT_HI +mul NAME LEFT RIGHT LOCAL_ERROR INPUT_LO INPUT_HI OUTPUT_LO OUTPUT_HI +div NAME LEFT RIGHT LOCAL_ERROR INPUT_LO INPUT_HI OUTPUT_LO OUTPUT_HI +output NAME TOLERANCE +``` + +- `NAME` is an ASCII letter followed by ASCII letters/digits/underscores, at most + 64 characters. Each name is assigned exactly once. +- Operands must refer to previous nodes. Cycles and forward references are rejected. +- There is exactly one `output`, and it is the final statement. +- Error quantities and tolerance are nonnegative absolute bounds in decoded units. +- Both operands share the supplied physical input interval in v1. A later schema + may support distinct left/right domains and encoding tags. +- The graph has at most 256 nodes and the file has at most 64 KiB. +- Rust rationals use reduced signed 64-bit numerators, positive 64-bit denominators, + and exact 128-bit intermediates. An unrepresentable result is an explicit error; + it is never silently rounded, wrapped, or accepted as a certificate. + +## Semantics + +For every node, maintain an ideal interval `R` and an absolute error `e`: + +```text +ideal ∈ R +|actual − ideal| ≤ e +actual ∈ [R.lo − e, R.hi + e] +``` + +Inputs describe the allowed ideal external values and conversion uncertainty. +Constants can also have nonzero programming/reference uncertainty. + +For a binary node, first check that **both expanded operand intervals** lie in its +physical input domain. Its local device contract is: + +```text +|transfer(actual_a, actual_b) − (actual_a op actual_b)| ≤ local_error +``` + +The ideal interval is computed from endpoint interval arithmetic. Product bounds +use all four endpoint products, preserving positive/negative signs. Division uses +the reciprocal interval and requires that it not touch zero. + +Let `Ma = max(|Ra.lo|, |Ra.hi|)` and similarly `Mb`. Composed errors are: + +```text +add/sub: ea + eb + local +mul: ea Mb + Ma eb + ea eb + local +div: (ea Mb + Ma eb)/(m (m − eb)) + local +``` + +Here `m` is the minimum absolute denominator over its ideal interval. Division +requires **`eb < m`**, not merely a nominal nonzero denominator. + +Finally, the expanded result interval must lie in the declared output domain, and +the selected output's error must not exceed the requested tolerance. + +No independence assumption is used. Reused inputs can be correlated; interval +bounds remain conservative. Sharing a node does not currently model physical +fanout, routing, scheduling, or storage costs. An arithmetic-only certificate is +conditional on the declared local device contracts: it does not prove that an +unregistered physical mechanism implements them. + +## Device schema + +```text +lumiris-mzi 1 +id MODEL_ID +voltage_max RATIONAL +# The remaining fields are required; unknown/duplicate fields are rejected. +dac_bits INTEGER +phase_per_v2 RATIONAL +phase_offset RATIONAL +phase_error RATIONAL +input_limit RATIONAL +``` + +Supported model domain: + +- `2 ≤ dac_bits ≤ 16` +- `0 < voltage_max ≤ 10` V +- `0 < phase_per_v2 ≤ 1` rad/V² +- `|phase_offset| ≤ 1` rad +- `0 ≤ phase_error ≤ 1` rad +- `0 < input_limit ≤ 1`, normalized coherent field amplitude + +These are software-supported bounds, **not universal safe chip limits**. A real +device needs calibrated voltage, thermal, power, endurance, and timing constraints. + +The concrete branch requires exactly one input, one error-free static weight in +`[-1,1]`, and their multiply, selected as output. Either operand order is accepted. +Unsupported graphs are rejected rather than silently assigned the wrong mechanism. + +```text +V = voltage_max × code/(2^bits − 1) +phase_nominal = phase_per_v2 × V² + phase_offset +phase_actual ∈ [phase_nominal − phase_error, phase_nominal + phase_error] +t = cos(phase_actual/2) +output_actual = t × input_actual +``` + +The positive-voltage, non-wrapped inverse branch proposes a nearby DAC code using +`acos` and `sqrt`. At most three adjacent codes are checked. This is not a globally +optimal branch search, and may conservatively reject other feasible settings. +Acceptance does not depend on the floating-point inverse's accuracy. + +A directed-rounded degree-32 Taylor enclosure with order-34 absolute remainder +bounds `t`, for `|phase/2| ≤ 8`. The backend checks every proposed code against its +finite voltage range and input amplitude limit. The independent checker recomputes +the enclosure using arbitrary-precision rational operations without the backend's +fixed-point rounding. + +With weight mismatch bounded by `delta`, ideal input magnitude `M`, and input +uncertainty `ein`: + +```text +physical local error ≤ delta × (M + ein) +physical total error ≤ |weight| × ein + delta × (M + ein) +``` + +The physical local bound must fit the multiplication node's local allowance. The +total must fit both the arithmetic certificate and final output tolerance. + +## Certificate bundle + +```text +program.lumi exact source copy +arithmetic.cert per-node ideal ranges/errors +device.mzi optional exact device-model copy +physical.cert optional MZI control and error claims +Certificate.lean generated numeric inequalities, when requested +simulation.json diagnostic report, when requested +verification.json independent-check report, when requested +``` + +`arithmetic.cert` starts with `lumiris-certificate 1`, then contains one ordered +`node NAME LO HI ERROR` per source node and a final `output NAME TOLERANCE`. + +`physical.cert` starts with `lumiris-mzi-certificate 1`, followed by required fields: +`model`, `code`, `voltage`, `phase LO HI`, `transmission LO HI`, `weight_error`, +`local_error`, and `total_error`. Unknown, missing, or duplicated claims fail. + +Verification recomputes the graph and numerical results. Supply `--source` and +`--device` to bind a bundle to the originally requested files. A consistent bundle +by itself cannot establish that it is the program/calibration the caller intended. + +Compilation refuses existing output directories. Failed analysis or physical +lowering emits no bundle. Filesystem failure during emission can leave a partial +bundle; missing/inconsistent artifacts must never be treated as verification success. diff --git a/docs/milestones.md b/docs/milestones.md new file mode 100644 index 0000000..354e055 --- /dev/null +++ b/docs/milestones.md @@ -0,0 +1,78 @@ +# Implementation checkpoints — 2026-11-10 + +These milestones are the review's three incremental checkpoints, not the full +seven-phase research roadmap. “Implemented” does not imply “kernel-validated.” + +## Milestone 1 — Trustworthy project/build foundation + +Implemented: +- Normalized Lean and Rust source/configuration/manifest locations. +- Restored the missing physics-laws module and removed duplicated draft fragments. +- Made all 11 maintained Lean modules reachable from the default library. +- Repaired the draft triangle-bound proof and revised the MZI matrix proof. +- Added the repository audit, ignore rules, README, and executable/formal CI jobs. +- Confirmed Rust targets build and execute offline with no third-party crates. + +**Open acceptance gate:** run and pass the pinned Lean/Mathlib build. The sandbox +cannot install that toolchain through its permitted network endpoints. Static +import validation passes, but is not a proof-compilation result. + +## Milestone 2 — Bounded software core + +Implemented and executable-tested: +- Versioned SSA text IR and exact rational reference interpreter. +- Tight sign-preserving interval arithmetic and nonzero denominator checks. +- Per-node local error, actual-input-domain and expanded-output checks. +- Uncertainty for both external inputs and constants. +- Independent source-derived certificate checking and tampering rejection. +- Exported Lean rational obligations and documented certificate/trust format. +- Bounded per-device composition theorem scripts for all four operations. + +Deliberate scope limits: +- The Rust implementation rejects rational-capacity overflow; it does not claim + arbitrary-precision compilation. Python checking uses arbitrary precision. +- Generic device-local errors remain explicit assumptions until a supported + physical branch discharges them. +- Parser/SSA-to-Lean semantic refinement is not yet a proved translation. + +## Milestone 3 — End-to-end MZI model demonstration + +Implemented and executable-tested: +- One live input × one exact configured weight, including negative weights. +- Explicit illustrative device calibration and safe parameter limits. +- Positive-branch phase/heater inversion, nearest-code candidate search, finite DAC. +- Independent exact cosine enclosure, calibration error, and composed output bound. +- SW-1 analytical simulator with boundary vectors, seeded perturbations, and + energy conservation diagnostics. +- One-command compilation/check/simulation, plus optional formal validation. +- Useful rejection of unsupported graphs, infeasible precision, and model limits. + +Reproduced default example: +- code 1891; voltage ≈ 2.308913309 V; +- checked physical error ≤ 0.0004005385444; +- 1018 simulation vectors; observed maximum ≈ 0.0003988068894; +- energy residual ≤ 2.23×10^-16. + +**Open formal acceptance gates:** observe the Lean CI result and prove/link the +Taylor-enclosure checker to the MZI theorem. The existing exported numeric +obligations are not that proof. The executable milestone is demonstrated; a fully +Lean-certified compiler milestone must not be marked complete yet. + +## Validation performed here + +- 12 Rust unit tests: passed. +- 23 Python integration/property/adversarial tests: passed. +- 100 randomized arithmetic programs × 10 perturbed vectors: included in tests. +- 200 randomized phase intervals × 3 cosine samples: included in tests. +- End-to-end demo/checker/SW-1 run: passed. +- Layout/import/pin audit: passed. +- Lean kernel validation: **not run**; CI configured, result pending. + +## Next work, in order + +1. Run the formal CI gate and resolve any Lean/Mathlib elaboration issues. +2. Prove the certificate/Taylor checker bridge and source-IR semantic translation. +3. Add explicit encoding tags and unit-typed device schemas across Rust/Lean. +4. Add insertion loss/detection and measured calibration datasets. +5. Generalize the device registry/selection beyond the single concrete branch. +6. Proceed to timing, dynamics, and additional photonic/memristive mechanisms. diff --git a/docs/verification.md b/docs/verification.md new file mode 100644 index 0000000..8c99c59 --- /dev/null +++ b/docs/verification.md @@ -0,0 +1,99 @@ +# Verification and trust boundaries + +## Status of this implementation + +The executable compiler, independent checker, and SW-1 simulation have been run +locally. The formal Lean changes have **not** been compiled locally. The sandbox +has no Lean/Lake toolchain and its network allowlist blocks the release-asset host. +A CI formal job is provided but has not been observed running in this session. +No assertion of a successful Lean build is made. + +There are three intentionally different kinds of evidence: + +| Evidence | What it establishes | What it does not establish | +|---|---|---| +| Independent exact-rational checker | Source-derived arithmetic bounds, physical-domain checks, DAC binding, conservative MZI cosine/error enclosure under the named model | Correctness of Python itself, calibration validity, real-device safety | +| Lean theorem scripts and generated numeric obligations | Once `lake build` and generated-file checking pass: stated mathematical theorems and concrete rational inequalities | A proved parser/compiler/checker or complete source-to-hardware refinement | +| SW-1 sampled simulation | Reproducible model diagnostics, observed bounded error, sampled energy residual | Universal input coverage, tail probabilities, fabrication accuracy | + +A checker `PASS` means the independently recomputed certificate is consistent with +the program and model assumptions. It does not mean “Lean executed” or “hardware +is safe.” The CLI reports Lean's unexecuted status explicitly. + +## Arithmetic foundation + +`Core/Bounded.lean` introduces per-device input/output domains and a local error +specification that only applies inside those domains. Composition requires actual +operand membership, so an input uncertainty cannot be ignored at the domain edge. +The operation-specific theorems cover +, −, ×, ÷ with bounded input uncertainty. + +`Core/Semantics.lean` retains the original expression-tree semantics and global +`Realization` theorem for compatibility/research. Its globally quantified operation +contracts are mathematical idealizations, not the contract used by the executable +physical branch. Constants in this legacy tree remain exact. The executable SSA +IR supports uncertain constants; its independent checker and bounded composition +model account for them. There is not yet a formal translation theorem between +these two syntax representations. + +`Core/Range.lean` now uses sign-preserving endpoint product, scaling, and reciprocal +bounds. The zero-crossing reciprocal fallback cannot be certified by its safety +premise. No unsafe denominator is accepted merely because Lean's totalized division +assigns a value to division by zero. + +## MZI branch + +The trusted physical assumption is: + +```text +theta ∈ k V² + offset ± bounded_phase_residual +bar_output = cos(theta/2) × actual_input +``` + +Within that model, exact interval arithmetic encloses cosine using a Taylor +polynomial. Degree 33 has the same polynomial as degree 32 because its odd +coefficient is zero. Lagrange's remainder is bounded by `|theta/2|^34 / 34!` since +all derivatives of cosine have absolute value at most one. + +The Rust implementation uses integer-directed rounding on a fixed 10^-9 grid. +Its supported domain keeps intermediate fixed-point products inside i128. +The independent Python implementation instead uses exact, arbitrarily large +fractions and checks that the submitted enclosure contains its recomputed bound. +It does not call Rust or reuse Rust's fixed-point implementation. + +`Physics/Control.lean` states the final MZI error composition theorem conditional +on a bound on the cosine/weight mismatch. **The Taylor-enclosure implementation is +not yet proved in Lean or connected to that premise by a kernel-checked bridge.** +The exported `Certificate.lean` checks numeric inequalities only; it is not a proof +of this missing bridge. This is the main remaining formal-certificate task. + +## Explicit omissions + +- No real-chip calibration measurements or uncertainty identification. +- No complex input-state graph/phase-reference tracking; the executable example + uses real signed coherent amplitude and ideal phase matching. +- No optical insertion loss, detector/ADC response, shot/RIN/thermal noise, + nonlinear response, or stochastic tail guarantee. +- No voltage slew, thermal settling, heater resistance/power limit, or controller. +- No general placement/routing, fanout accounting, storage, or physical DAG scheduling. +- No compiler approximation pass for exp/sin/sqrt and no memristor lowering yet. +- No Z3/dReal integration. Exact rational checks handle the implemented instances; + future solver timeout/unknown/δ-sat policies still need design and validation. +- No hardware I/O. Every control file is a model-level artifact only. + +The `phase_error` field must bound **all** residual phase effects assumed for a +single invocation; it is not automatically derived from noise or temperature data. +Sampling that interval uniformly is a stress-test distribution, not a claim that +real noise is uniform or bounded. + +## Fail-closed behavior + +Compilation returns a nonzero exit status on malformed input, unsupported graph, +unrepresentable rational arithmetic, unsafe divisor, insufficient precision, +out-of-domain values, or saturation. No physical control artifact is emitted +before model checks finish. Bundle verification rejects incomplete files, altered +claims, mismatched expected source/calibration, duplicate claims, and inconsistent +DAC/phase/error bindings. A corrupt bundle must never be used as hardware input. + +For hostile external certificates, execution should additionally be sandboxed +with time/memory limits. The current limits bound source size and graph size but +are not a general-purpose resource-isolation mechanism. diff --git a/examples/mzi-scale.lumi b/examples/mzi-scale.lumi new file mode 100644 index 0000000..f5e1a52 --- /dev/null +++ b/examples/mzi-scale.lumi @@ -0,0 +1,6 @@ +# Signed coherent amplitude, normalized so |E| <= 1. +lumiris 1 +input x -9/10 9/10 1/10000 +const weight 1/2 0 +mul y weight x 1/1000 -1 1 -1 1 +output y 11/10000 diff --git a/examples/reject-zero-divisor.lumi b/examples/reject-zero-divisor.lumi new file mode 100644 index 0000000..eb26eac --- /dev/null +++ b/examples/reject-zero-divisor.lumi @@ -0,0 +1,5 @@ +lumiris 1 +input denominator -1 1 0 +const one 1 0 +div y one denominator 0 -2 2 -10 10 +output y 1 diff --git a/examples/safe-division.lumi b/examples/safe-division.lumi new file mode 100644 index 0000000..7de50a8 --- /dev/null +++ b/examples/safe-division.lumi @@ -0,0 +1,6 @@ +lumiris 1 +input x 1 2 1/10000 +mul square x x 1/10000 0 3 0 5 +const one 1 0 +div y one square 1/10000 0 5 0 2 +output y 1/100 diff --git a/photonic-memristor-compiler-plan.md b/photonic-memristor-compiler-plan.md index 0d53e4d..7241d7d 100644 --- a/photonic-memristor-compiler-plan.md +++ b/photonic-memristor-compiler-plan.md @@ -1,5 +1,17 @@ # Plan v2: A Physics + Math Unified Compiler for Photonic and Memristive Hardware +> **Implementation checkpoint (2026-11-10).** This document is the long-term research +> vision, not a claim that all layers exist. The executable MVP now implements +> bounded straight-line rational arithmetic, explicit physical-domain/error checks, +> an exact independent certificate checker, and one static-weight MZI/DAC/SW-1 +> demonstration. See [README](README.md), [milestone status](docs/milestones.md), and +> [verification boundaries](docs/verification.md). The Lean build is pending external +> validation; numeric obligation export is not yet a full source-to-physics proof. +> +> **Near-term scope:** one bounded arithmetic graph and one illustrative calibrated +> MZI. Arbitrary functions, generalized device selection, solver integration, +> memristor lowering, physical scheduling, and closed-loop control remain future work. + **Goal.** Compile *any* mathematics into physical control parameters (voltages, currents, pulses, wavelengths, timings) for light-based and memristor-based chips. All arithmetic reduces to a **Core Analog Algebra** of four operations (+, −, ×, ÷). Each operation can be realized physically in many ways, organized as an extensible **Physics Tree**. Each step is checked by math (Lean4), constraints (Z3/dReal) and a physics simulator (the "Small World") before anything touches hardware. A timing layer with closed-loop correction keeps the hardware correct while it runs. --- @@ -30,7 +42,7 @@ L5 Timing + Adaptive physics-derived timing (ps ... s), disturbance Three checking tools run at every level: - **Lean4 + Mathlib**: general theorems ("for all inputs in range, this lowering is within ε"). -- **Z3 / dReal**: checks for one specific program on one specific chip (ranges, power, timing, wavelength spacing). dReal is needed because Z3 cannot reason about `exp`, `sin`, `ln`. +- **Z3 / dReal**: checks for one specific program on one specific chip (ranges, power, timing, wavelength spacing). Use validated transcendental enclosures or dReal for exp/sin/log constraints outside Z3's supported theories. dReal is δ-complete: δ-sat is not exact satisfiability; unknown/timeouts must fail closed. Solver certificates and their trusted checker must be specified. - **Small World simulator**: executes the physics with noise, drift and crosstalk, and checks that physical laws are obeyed. --- @@ -46,7 +58,7 @@ Three checking tools run at every level: - `const c`: a reference value (laser power level, reference voltage, stored conductance) - `fanout x → (x, x)`: copying is **not free** physically. An optical 1:2 splitter gives each output amplitude x/√2 (power x/2), so the compiler must track it. - `route`: waveguide or wire connections, which add loss and delay - - `store / load`: memory (memristor or PCM states persist at 0 W) + - `store / load`: memory (memristor or PCM states need no refresh power; read/write and peripheral energy still count) - `convert`: optical↔electrical (O/E, E/O) and analog↔digital (ADC/DAC) - `compare / select`: for control flow (`if`, `while`). This is either an analog comparator, or the program is split so a digital host handles control flow and analog hardware runs the arithmetic. @@ -125,7 +137,7 @@ div (abstract) ├── Feedback (TIA/op-amp) V_out = −V_in · G_in / G_fb (memristor in feedback path) ├── Optical gain normalization detector/TIA gain set to 1/c ├── Iterative (Newton) 1/b via x_{k+1} = x_k(2 − b·x_k), uses mul + sub -└── Digital fallback when b varies fast and must be exact +└── Digital fallback when b varies fast or specified digital precision is preferable; arbitrary real division is not generally exact ``` ### 2.2 What a Physics Tree node is (formal contract) @@ -146,7 +158,7 @@ Each node `n` refines its parent and must provide: **Innovation = adding a node.** A researcher who invents a new way to multiply with light, or a new memristor stack, writes a node (data file + small Lean proof file + simulator model). The compiler accepts it **only if**: 1. its Lean refinement proof checks (or a solver discharges the obligations on the declared ranges), -2. it passes the Small World physics checks (laws obeyed, error within claim under Monte Carlo), +2. it passes model-level law checks and statistical validation; Monte Carlo is diagnostic evidence, not a universal error proof, 3. its knob binding passes L4 safety checks. **Choosing a branch** is an optimization pass: for each abstract op, pick the node that minimizes cost (energy/latency/area) under the error budget and the available hardware. Users can also pin choices manually. @@ -201,7 +213,7 @@ Every knob is specified like a datasheet entry, with units enforced by type: Inverse models (parameter → knob), with their traps (all registered in each node's `knob_binding`): - **Thermo-optic**: `Δφ = φ0 + k·V²` ⇒ `V = √(((Δφ − φ0) mod 2π)/k)`; minimum-power branch; your numbers check out (k = π/8 rad/V²). -- **Thermal crosstalk** is linear in power: `φ = C·P`, `P_i = V_i²/R_i` ⇒ solve `P = C⁻¹φ`, check `P ≥ 0` and limits (LP / Z3), then `V_i = √(P_i R_i)`. +- **Thermal crosstalk** is linear in power: `φ = C·P`, `P_i = V_i²/R_i` ⇒ solve `C·P = φ` subject to `P ≥ 0` and limits (LP / Z3); use `C⁻¹φ` only when the model is invertible and well-conditioned, then `V_i = √(P_i R_i)`. - **Electro-optic**: `V = V_π·Δφ/π`. - **Attenuator**: `I = α⁻¹(−ln T / L)` with calibrated monotone α(I); clamp at T_min; compensate the side-effect phase shift. - **Microring**: δ² = (TΓ² − γ²)/(1 − T); choose one side of resonance (±δ) consistently; T_min = γ²/Γ² unless critically coupled. @@ -217,7 +229,7 @@ Inverse models (parameter → knob), with their traps (all registered in each no ### 5.1 Physics-derived timing Timescales span about 15 orders of magnitude, from optical propagation (ps) to drift (seconds to hours). Timing is **computed from physics, not guessed**: -- Exponential settling: a heater with time constant τ needs `t ≥ τ · ln(ΔV / tolerance)` to be within tolerance, so **settling time follows from the required precision**. +- Exponential settling: a first-order modeled state with time constant τ needs `t ≥ max(0, τ · ln(initial_state_error / state_tolerance))` to be within tolerance, so **settling time follows from the required precision**. - Propagation delay: `t = n_g · L / c` per waveguide segment (path-length matching for coherent interference). - Pulse schedules: memristor/PCM pulse + verify-read + thermal cool-down between pulses. - Conversion: DAC update rate, ADC conversion time, photodetector bandwidth. @@ -287,6 +299,6 @@ ONNX/StableHLO/own DSL import, calibration from real measurements. ## 8. Open decisions -1. **Compiler core language**: Rust + Lean certificates (recommended), or the whole compiler written in Lean4? -2. **First Physics Tree branches to build end to end**: photonic (MZI + attenuator + balanced detector) first (recommended), memristor first, or both together? -3. **Repo**: new GitHub repo (name?) or local only for now? +1. **Compiler core language**: Rust chosen for the executable MVP; independent exact certificate checking is implemented. Full Lean certificate-refinement linkage remains open. +2. **First branch**: static-weight thermo-optic MZI chosen and demonstrated at model level. Additional photonic branches and memristors follow after the verification bridge. +3. **Repo**: this repository, `photonics-computing`; executable/formal CI definitions are included. diff --git a/scripts/audit_repository.py b/scripts/audit_repository.py new file mode 100644 index 0000000..b6fd714 --- /dev/null +++ b/scripts/audit_repository.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Check project wiring without pretending to compile Lean proofs.""" + +import json +from pathlib import Path +import re +import tomllib + +ROOT = Path(__file__).resolve().parents[1] +LEAN = ROOT / "Lean-Semantics/lean" +config = tomllib.loads((LEAN / "lakefile.toml").read_text()) +manifest = json.loads((LEAN / "lake-manifest.json").read_text()) +assert config["require"][0]["rev"] == manifest["packages"][0]["inputRev"] +assert (LEAN / "lean-toolchain").read_text().strip().endswith(config["require"][0]["rev"]) +files = { + str(p.relative_to(LEAN)).removesuffix(".lean").replace("/", "."): p + for p in LEAN.rglob("*.lean") + if ".lake" not in p.parts +} +graph = {} +for module, path in files.items(): + source = path.read_text() + # Match declarations, not words in doc comments. + assert not re.search(r"(?m)^\s*(?:axiom\s|.*:=\s*(?:sorry|admit)\s*$)", source), path + graph[module] = re.findall(r"(?m)^import (Lumiris(?:\.[A-Za-z0-9_]+)*)\s*$", source) + for imported in graph[module]: + assert imported in files, f"missing module {imported} imported by {path}" +seen, active = set(), set() + + +def visit(module): + assert module not in active, f"import cycle: {module}" + if module in seen: + return + active.add(module) + for imported in graph[module]: + visit(imported) + active.remove(module) + seen.add(module) + + +visit("Lumiris") +assert seen == set(files), f"unbuilt Lean modules: {set(files)-seen}" +rust = ROOT / "Lean-Semantics/rust" +cargo = tomllib.loads((rust / "Cargo.toml").read_text()) +assert (rust / cargo["lib"]["path"]).is_file() +for binary in cargo["bin"]: + assert (rust / binary["path"]).is_file() +print( + f"PASS: {len(files)} Lean modules reachable, imports resolved, pins aligned, Rust targets exist. This is a layout audit, not proof validation." +) diff --git a/scripts/check_certificate.py b/scripts/check_certificate.py new file mode 100644 index 0000000..4c5d3ea --- /dev/null +++ b/scripts/check_certificate.py @@ -0,0 +1,416 @@ +#!/usr/bin/env python3 +"""Independent exact-rational checker. Does not invoke or trust the Rust compiler. + +Arithmetic/device assumptions are read from source, not inferred from certificates. +Cosine is enclosed by a degree-32 Taylor polynomial plus |x|^34/34!. +The algorithm is exact Python arithmetic; its implementation is NOT Lean-proved. +""" + +from __future__ import annotations +import argparse +from dataclasses import dataclass +from fractions import Fraction as Q +import hashlib +import json +from pathlib import Path +import re + + +class Rejected(ValueError): + pass + + +def require(condition, reason): + if not condition: + raise Rejected(reason) + + +def read(path): + require(Path(path).stat().st_size <= 65536, "file exceeds 64 KiB") + return Path(path).read_text(encoding="utf-8") + + +def rational(s): + require( + len(s) <= 80 and re.fullmatch(r"[+-]?[0-9]+(?:/[+-]?[0-9]+)?", s, flags=re.ASCII), + "invalid rational", + ) + try: + parts = [int(token) for token in s.split("/")] + require( + all(-(2**63) <= v <= 2**63 - 1 for v in parts), "rational token exceeds source capacity" + ) + x = Q(parts[0], parts[1] if len(parts) == 2 else 1) + except (ValueError, ZeroDivisionError) as e: + raise Rejected("invalid rational") from e + require( + abs(x.numerator) <= 2**63 - 1 and x.denominator <= 2**63 - 1, + "rational exceeds source capacity", + ) + return x + + +def lines(text, header): + rows = [s.split("#", 1)[0].split() for s in text.splitlines()] + rows = [s for s in rows if s] + require(rows and rows[0] == header.split(), f"expected {header}") + return rows[1:] + + +@dataclass(frozen=True) +class Interval: + lo: Q + hi: Q + + def __post_init__(self): + require(self.lo <= self.hi, "reversed interval") + + @property + def mag(self): + return max(abs(self.lo), abs(self.hi)) + + @property + def minmag(self): + return self.lo if self.lo > 0 else -self.hi if self.hi < 0 else Q(0) + + def contains(self, other): + return self.lo <= other.lo and other.hi <= self.hi + + def inflate(self, error): + return Interval(self.lo - error, self.hi + error) + + def add(self, b): + return Interval(self.lo + b.lo, self.hi + b.hi) + + def neg(self): + return Interval(-self.hi, -self.lo) + + def mul(self, b): + products = [a * c for a in (self.lo, self.hi) for c in (b.lo, b.hi)] + return Interval(min(products), max(products)) + + def div(self, b): + require(b.minmag > 0, "divisor interval touches zero") + return self.mul(Interval(1 / b.hi, 1 / b.lo)) + + +@dataclass +class Node: + name: str + op: str + interval: Interval + error: Q + args: tuple = () + local: Q = Q(0) + + +@dataclass +class Analysis: + nodes: dict + output: str + tolerance: Q + facts: list + + +def analyze(source): + nodes, facts, output = {}, [], None + for t in lines(source, "lumiris 1"): + require(output is None, "output must be final") + if t[0] == "output": + require(len(t) == 3 and t[1] in nodes, "invalid output") + output, tolerance = t[1], rational(t[2]) + facts.append((nodes[output].error, tolerance)) + require(0 <= nodes[output].error <= tolerance, "output budget exceeded") + continue + require(len(nodes) < 256 and len(t) >= 2, "node limit or malformed node") + name = t[1] + require( + len(name) <= 64 + and re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*", name, flags=re.ASCII) + and name not in nodes, + "invalid/duplicate name", + ) + if t[0] == "input" and len(t) == 5: + n = Node(name, "input", Interval(rational(t[2]), rational(t[3])), rational(t[4])) + elif t[0] == "const" and len(t) == 4: + c = rational(t[2]) + n = Node(name, "const", Interval(c, c), rational(t[3])) + else: + require(len(t) == 9 and t[0] in ("add", "sub", "mul", "div"), "invalid operation") + require(t[2] in nodes and t[3] in nodes, "undefined/forward reference") + a, b = nodes[t[2]], nodes[t[3]] + local = rational(t[4]) + require(local >= 0, "negative local error") + domain = Interval(rational(t[5]), rational(t[6])) + out_domain = Interval(rational(t[7]), rational(t[8])) + for operand in (a, b): + actual = operand.interval.inflate(operand.error) + require(domain.contains(actual), "actual operand outside device domain") + facts.extend([(domain.lo, actual.lo), (actual.hi, domain.hi)]) + ea, eb = a.error, b.error + ma, mb = a.interval.mag, b.interval.mag + if t[0] in ("add", "sub"): + interval = a.interval.add(b.interval if t[0] == "add" else b.interval.neg()) + error = ea + eb + local + elif t[0] == "mul": + interval = a.interval.mul(b.interval) + error = ea * mb + ma * eb + ea * eb + local + else: + m = b.interval.minmag + require(eb < m, "perturbed divisor can reach zero") + interval = a.interval.div(b.interval) + error = (ea * mb + ma * eb) / (m * (m - eb)) + local + # Record a rational witness of strict separation. + facts.append((Q(0), m - eb)) + actual = interval.inflate(error) + require(out_domain.contains(actual), "actual result outside output domain") + facts.extend([(out_domain.lo, actual.lo), (actual.hi, out_domain.hi)]) + n = Node(name, t[0], interval, error, (t[2], t[3]), local) + require(n.error >= 0, "negative uncertainty") + # Match the executable IR capacity and stop adversarial repeated squaring + # before arbitrary-precision integers can grow without bound. + require( + all( + abs(v.numerator) <= 2**63 - 1 and v.denominator <= 2**63 - 1 + for v in (n.interval.lo, n.interval.hi, n.error) + ), + "analyzed rational exceeds compiler capacity", + ) + facts.extend([(n.interval.lo, n.interval.hi), (Q(0), n.error)]) + nodes[name] = n + require(output is not None, "missing output") + return Analysis(nodes, output, tolerance, facts) + + +def check_arithmetic(a, text): + rows = lines(text, "lumiris-certificate 1") + expected = [ + ["node", n.name, str(n.interval.lo), str(n.interval.hi), str(n.error)] + for n in a.nodes.values() + ] + expected.append(["output", a.output, str(a.tolerance)]) + require(len(rows) == len(expected), "certificate node count mismatch") + for row, wanted in zip(rows, expected): + require(len(row) == len(wanted) and row[:2] == wanted[:2], "certificate graph mismatch") + require( + [rational(s) for s in row[2:]] == [Q(s) for s in wanted[2:]], + "arithmetic certificate mismatch", + ) + + +def device_model(text): + fields = {} + for row in lines(text, "lumiris-mzi 1"): + require(len(row) == 2 and row[0] not in fields, "duplicate/malformed device field") + fields[row[0]] = row[1] + require( + set(fields) + == { + "id", + "voltage_max", + "dac_bits", + "phase_per_v2", + "phase_offset", + "phase_error", + "input_limit", + }, + "device schema mismatch", + ) + require(re.fullmatch(r"[+]?[0-9]+", fields["dac_bits"]), "invalid DAC bits") + d = {k: rational(v) if k not in ("id", "dac_bits") else v for k, v in fields.items()} + d["dac_bits"] = int(d["dac_bits"]) + require( + 2 <= d["dac_bits"] <= 16 + and 0 < d["voltage_max"] <= 10 + and 0 < d["phase_per_v2"] <= 1 + and abs(d["phase_offset"]) <= 1 + and 0 <= d["phase_error"] <= 1 + and 0 < d["input_limit"] <= 1, + "unsupported device domain", + ) + return d + + +def cosine_enclosure(phase): + """Exact interval recurrence, no floating-point constants or compiler output.""" + x = phase.mul(Interval(Q(1, 2), Q(1, 2))) + require(x.mag <= 8, "phase exceeds Taylor domain") + square, term, total = x.mul(x), Interval(Q(1), Q(1)), Interval(Q(1), Q(1)) + for j in range(1, 17): + term = term.mul(square).div(Interval(Q((2 * j - 1) * 2 * j), Q((2 * j - 1) * 2 * j))) + total = total.add(term if j % 2 == 0 else term.neg()) + # Degree 33 has zero odd coefficient; order-34 Lagrange remainder <= |x|^34/34!. + from math import factorial + + remainder = x.mag**34 / factorial(34) + return Interval(max(Q(-1), total.lo - remainder), min(Q(1), total.hi + remainder)) + + +def physical_binding(a): + require(len(a.nodes) == 3, "MZI requires three-node graph") + n = a.nodes[a.output] + require(n.op == "mul", "MZI output is not multiply") + left, right = (a.nodes[k] for k in n.args) + if left.op == "const": + left, right = right, left + require( + left.op == "input" + and right.op == "const" + and right.error == 0 + and abs(right.interval.lo) <= 1, + "unsupported MZI binding", + ) + return left, right.interval.lo, n.local + + +def check_physical(a, device_text, text): + d = device_model(device_text) + rows = lines(text, "lumiris-mzi-certificate 1") + fields = {} + for row in rows: + require(len(row) >= 2 and row[0] not in fields, "duplicate/malformed physical claim") + fields[row[0]] = row[1:] + required = { + "model": 1, + "code": 1, + "voltage": 1, + "phase": 2, + "transmission": 2, + "weight_error": 1, + "local_error": 1, + "total_error": 1, + } + require( + set(fields) == set(required) and all(len(fields[k]) == v for k, v in required.items()), + "physical schema mismatch", + ) + require(fields["model"] == [d["id"]], "model identity mismatch") + require(re.fullmatch(r"[0-9]+", fields["code"][0]), "invalid DAC code") + code = int(fields["code"][0]) + require(0 <= code < 2 ** d["dac_bits"], "unsafe DAC code") + v = d["voltage_max"] * code / (2 ** d["dac_bits"] - 1) + require(rational(fields["voltage"][0]) == v, "voltage binding mismatch") + phase = Interval( + d["phase_per_v2"] * v * v + d["phase_offset"] - d["phase_error"], + d["phase_per_v2"] * v * v + d["phase_offset"] + d["phase_error"], + ) + claimed_phase = Interval(*(rational(s) for s in fields["phase"])) + require(phase == claimed_phase, "phase-model binding mismatch") + transmission = Interval(*(rational(s) for s in fields["transmission"])) + require( + transmission.contains(cosine_enclosure(phase)) + and -1 <= transmission.lo <= transmission.hi <= 1, + "invalid cosine enclosure", + ) + inp, weight, budget = physical_binding(a) + actual = inp.interval.inflate(inp.error) + require(actual.mag <= d["input_limit"], "input exceeds calibrated model") + delta = max(abs(transmission.lo - weight), abs(transmission.hi - weight)) + local = delta * actual.mag + total = abs(weight) * inp.error + local + for key, value in (("weight_error", delta), ("local_error", local), ("total_error", total)): + require(rational(fields[key][0]) == value, f"{key} mismatch") + require( + local <= budget and total <= a.tolerance and total <= a.nodes[a.output].error, + "physical error exceeds arithmetic contract", + ) + a.facts.extend( + [ + (Q(0), v), + (v, d["voltage_max"]), + (actual.mag, d["input_limit"]), + (local, budget), + (total, a.tolerance), + (total, a.nodes[a.output].error), + ] + ) + return { + "device": d, + "code": code, + "voltage": v, + "phase": phase, + "input": inp, + "weight": weight, + "total_error": total, + "transmission": transmission, + } + + +def export_lean(a, path): + """Kernel-checkable numeric obligations, NOT a source-to-hardware proof.""" + + def q(x): + return f"({x.numerator} / {x.denominator} : ℚ)" + + out = [ + "import Lumiris", + "", + "-- Generated numeric obligations. See docs/verification.md for trust boundaries.", + "namespace Lumiris.Generated", + ] + for i, (lo, hi) in enumerate(a.facts): + out.append(f"theorem obligation_{i} : {q(lo)} ≤ {q(hi)} := by norm_num") + out.append("end Lumiris.Generated\n") + Path(path).write_text("\n".join(out)) + + +def verify(bundle, expected_source=None, expected_device=None): + bundle = Path(bundle) + source = read(bundle / "program.lumi") + if expected_source: + require(source == read(expected_source), "bundle source differs from requested program") + a = analyze(source) + check_arithmetic(a, read(bundle / "arithmetic.cert")) + physical = None + require( + (bundle / "physical.cert").exists() == (bundle / "device.mzi").exists(), + "incomplete physical bundle", + ) + if expected_device: + require((bundle / "device.mzi").exists(), "expected physical bundle") + if (bundle / "physical.cert").exists(): + device = read(bundle / "device.mzi") + if expected_device: + require( + device == read(expected_device), "bundle device differs from requested calibration" + ) + physical = check_physical(a, device, read(bundle / "physical.cert")) + return a, physical, hashlib.sha256(source.encode()).hexdigest() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("bundle", type=Path) + parser.add_argument("--source", type=Path) + parser.add_argument("--device", type=Path) + parser.add_argument("--lean", type=Path) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + try: + a, p, digest = verify(args.bundle, args.source, args.device) + if args.lean: + export_lean(a, args.lean) + report = json.dumps( + { + "status": "PASS", + "program_sha256": digest, + "nodes": len(a.nodes), + "output": a.output, + "arithmetic_error_bound": str(a.nodes[a.output].error), + "physical_error_bound": str(p["total_error"]) if p else None, + "lean": ( + "numeric obligations exported, not executed" if args.lean else "not executed" + ), + "assumption": "declared bounded operation errors and calibrated device model hold", + }, + indent=2, + ) + if args.report: + args.report.write_text(report + "\n") + print(report) + except (Rejected, OSError, ValueError, KeyError, IndexError, ZeroDivisionError) as e: + parser.exit(1, f"REJECT: {e}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/check_lean.sh b/scripts/check_lean.sh new file mode 100755 index 0000000..9dd62a4 --- /dev/null +++ b/scripts/check_lean.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +command -v lake >/dev/null || { echo 'Lean/Lake unavailable. Install elan and the pinned toolchain.' >&2; exit 1; } +bundle="$(realpath "${1:-artifacts/mzi-demo}")" +python3 scripts/check_certificate.py "$bundle" --lean "$bundle/Certificate.lean" +cd Lean-Semantics/lean +lake build +lake env lean "$bundle/Certificate.lean" +echo 'Lean library and generated numeric obligations checked. See docs/verification.md for remaining trust assumptions.' diff --git a/scripts/demo.sh b/scripts/demo.sh new file mode 100755 index 0000000..1bba011 --- /dev/null +++ b/scripts/demo.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +out="${1:-artifacts/mzi-demo}" +cargo run --locked --offline --manifest-path Lean-Semantics/rust/Cargo.toml -- \ + compile examples/mzi-scale.lumi "$out" --device devices/demo-mzi.mzi +python3 scripts/check_certificate.py "$out" --source examples/mzi-scale.lumi \ + --device devices/demo-mzi.mzi --lean "$out/Certificate.lean" --report "$out/verification.json" +python3 scripts/simulate.py "$out" --report "$out/simulation.json" +if [[ "${2:-}" == "--lean" ]]; then + scripts/check_lean.sh "$out" +else + printf '\nLean was not executed. To check the formal library and generated numeric obligations:\n scripts/check_lean.sh %q\n' "$out" +fi diff --git a/scripts/simulate.py b/scripts/simulate.py new file mode 100644 index 0000000..226abd0 --- /dev/null +++ b/scripts/simulate.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""SW-1 analytical validation of an already checked MZI bundle. + +Finite sampling is diagnostic evidence, not a universal or probabilistic proof. +The model is lossless and real coherent amplitude with bounded phase/input error. +""" + +import argparse +import json +import math +from pathlib import Path +import random +from check_certificate import verify, Rejected, require + + +def simulate(bundle, samples=1000, seed=793): + require(0 <= samples <= 1_000_000, "sample count outside [0, 1000000]") + _, p, digest = verify(bundle) + require(p is not None, "simulation requires a physical certificate") + rng = random.Random(seed) + inp, weight, phase = p["input"], float(p["weight"]), p["phase"] + lo, hi, error = float(inp.interval.lo), float(inp.interval.hi), float(inp.error) + pl, ph = float(phase.lo), float(phase.hi) + vectors = [ + (x, e, theta) + for x in (lo, hi, 0.0 if lo <= 0 <= hi else (lo + hi) / 2) + for e in (-error, error) + for theta in (pl, ph, (pl + ph) / 2) + ] + vectors += [ + (rng.uniform(lo, hi), rng.uniform(-error, error), rng.uniform(pl, ph)) + for _ in range(samples) + ] + worst = energy = 0.0 + for x, perturbation, theta in vectors: + field = x + perturbation + bar = math.cos(theta / 2) * field + cross = math.sin(theta / 2) * field + residual = abs(bar * bar + cross * cross - field * field) + energy = max(energy, residual) + worst = max(worst, abs(bar - weight * x)) + bound = float(p["total_error"]) + require(worst <= bound + 1e-12, "sampled error violates certificate") + require(energy <= 1e-12, "energy conservation violated") + return { + "status": "PASS", + "fidelity": "SW-1 analytical", + "program_sha256": digest, + "seed": seed, + "vectors": len(vectors), + "dac_code": p["code"], + "voltage_V": float(p["voltage"]), + "maximum_absolute_error": worst, + "checked_error_bound": bound, + "maximum_energy_residual": energy, + "scope": "illustrative calibrated model; finite samples are not a proof; no hardware writes", + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("bundle", type=Path) + parser.add_argument("--samples", type=int, default=1000) + parser.add_argument("--seed", type=int, default=793) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + try: + text = json.dumps(simulate(args.bundle, args.samples, args.seed), indent=2) + "\n" + if args.report: + args.report.write_text(text) + print(text, end="") + except (Rejected, OSError, ValueError) as e: + parser.exit(1, f"REJECT: {e}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..31a9ea8 --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +python3 scripts/audit_repository.py +cargo test --locked --offline --manifest-path Lean-Semantics/rust/Cargo.toml +cargo build --locked --offline --manifest-path Lean-Semantics/rust/Cargo.toml +python3 -m unittest discover -s tests -v diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py new file mode 100644 index 0000000..46a37b8 --- /dev/null +++ b/tests/test_pipeline.py @@ -0,0 +1,263 @@ +"""Integration, adversarial-certificate, and numerical property tests (stdlib only).""" + +from fractions import Fraction as Q +import math +from pathlib import Path +import random +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "scripts")) +import check_certificate as ck +from simulate import simulate + +BIN = ROOT / "Lean-Semantics/rust/target/debug/lumiris" + + +class Pipeline(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.bundle = Path(self.temp.name) / "bundle" + + def compile(self, source="mzi-scale.lumi", device=True, text=None, device_text=None): + path = ROOT / "examples" / source + if text is not None: + path = Path(self.temp.name) / "source.lumi" + path.write_text(text) + args = [str(BIN), "compile", str(path), str(self.bundle)] + if device: + dp = ROOT / "devices/demo-mzi.mzi" + if device_text is not None: + dp = Path(self.temp.name) / "custom.mzi" + dp.write_text(device_text) + args.extend(["--device", str(dp)]) + return subprocess.run(args, text=True, capture_output=True) + + def test_end_to_end(self): + r = self.compile() + self.assertEqual(r.returncode, 0, r.stderr) + a, p, _ = ck.verify( + self.bundle, ROOT / "examples/mzi-scale.lumi", ROOT / "devices/demo-mzi.mzi" + ) + self.assertEqual(a.nodes[a.output].interval, ck.Interval(Q(-9, 20), Q(9, 20))) + self.assertLessEqual(p["total_error"], a.tolerance) + report = simulate(self.bundle, 2000) + self.assertEqual(report["status"], "PASS") + self.assertLessEqual(report["maximum_absolute_error"], report["checked_error_bound"]) + out = self.bundle / "Certificate.lean" + ck.export_lean(a, out) + self.assertIn("theorem obligation_", out.read_text()) + + def test_safe_division(self): + r = self.compile("safe-division.lumi", False) + self.assertEqual(r.returncode, 0, r.stderr) + a, _, _ = ck.verify(self.bundle) + self.assertEqual(a.nodes[a.output].interval, ck.Interval(Q(1, 4), Q(1))) + + def test_negative_divisor(self): + text = "lumiris 1\ninput a 1 2 0\ninput b -4 -2 0\ndiv y a b 0 -5 5 -2 0\noutput y 0" + r = self.compile(text=text, device=False) + self.assertEqual(r.returncode, 0, r.stderr) + a, _, _ = ck.verify(self.bundle) + self.assertEqual(a.nodes["y"].interval, ck.Interval(Q(-1), Q(-1, 4))) + + def test_uncertain_divisor_rejected_by_both(self): + text = "lumiris 1\ninput a 1 2 0\ninput b 1 2 1\ndiv y a b 0 -5 5 -10 10\noutput y 10" + r = self.compile(text=text, device=False) + self.assertNotEqual(r.returncode, 0) + with self.assertRaises(ck.Rejected): + ck.analyze(text) + + def test_capacity_and_node_limits(self): + texts = [ + "lumiris 1\nconst a 9223372036854775807 0\nconst b 2 0\nmul y a b 0 -9223372036854775807 9223372036854775807 -9223372036854775807 9223372036854775807\noutput y 0", + "lumiris 1\n" + "\n".join(f"const n{i} 0 0" for i in range(257)) + "\noutput n256 0", + ] + for text in texts: + r = self.compile(text=text, device=False) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(self.bundle.exists()) + + def test_zero_divisor(self): + r = self.compile("reject-zero-divisor.lumi", False) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(self.bundle.exists()) + + def test_tamper_arithmetic(self): + self.assertEqual(self.compile().returncode, 0) + path = self.bundle / "arithmetic.cert" + path.write_text(path.read_text().replace("21/20000", "0/1")) + with self.assertRaises(ck.Rejected): + ck.verify(self.bundle) + + def test_tamper_physics(self): + self.assertEqual(self.compile().returncode, 0) + path = self.bundle / "physical.cert" + original = path.read_text() + mutations = [ + original.replace("code 1891", "code 999999"), + original.replace("voltage 1891/819", "voltage 0"), + original + "code 1\n", + original.replace("weight_error 97361/250000000", "weight_error 0"), + original.replace( + "transmission 250188469/500000000 125097361/250000000", "transmission 1/2 1/2" + ), + ] + for text in mutations: + path.write_text(text) + with self.assertRaises(ck.Rejected): + ck.verify(self.bundle) + + def test_calibration_binding(self): + self.assertEqual(self.compile().returncode, 0) + path = self.bundle / "device.mzi" + path.write_text(path.read_text().replace("392699/1000000", "1/4")) + with self.assertRaises(ck.Rejected): + ck.verify(self.bundle) + + def test_expected_source(self): + self.assertEqual(self.compile().returncode, 0) + with self.assertRaises(ck.Rejected): + ck.verify(self.bundle, ROOT / "examples/safe-division.lumi") + + def test_incomplete_physical_bundle(self): + self.assertEqual(self.compile().returncode, 0) + (self.bundle / "physical.cert").unlink() + with self.assertRaises(ck.Rejected): + ck.verify(self.bundle) + + def test_no_overwrite(self): + self.assertEqual(self.compile().returncode, 0) + before = (self.bundle / "physical.cert").read_bytes() + self.assertNotEqual(self.compile().returncode, 0) + self.assertEqual(before, (self.bundle / "physical.cert").read_bytes()) + + def test_bad_device(self): + device = (ROOT / "devices/demo-mzi.mzi").read_text() + for text in [ + device.replace("dac_bits 12", "dac_bits 1"), + device.replace("phase_error 1/100000", "phase_error -1"), + device + "unknown 1\n", + device + "dac_bits 12\n", + ]: + r = self.compile(device_text=text) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(self.bundle.exists()) + + def test_resolution_failure(self): + text = ( + (ROOT / "examples/mzi-scale.lumi") + .read_text() + .replace("mul y weight x 1/1000", "mul y weight x 0") + ) + r = self.compile(text=text) + self.assertNotEqual(r.returncode, 0) + self.assertFalse(self.bundle.exists()) + + def test_saturation(self): + text = "lumiris 1\ninput x 0 1 1/10\nconst w 1 0\nadd y x w 0 -2 2 0 2\noutput y 1" + r = self.compile(text=text, device=False) + self.assertNotEqual(r.returncode, 0) + + def test_eval(self): + r = subprocess.run( + [str(BIN), "eval", str(ROOT / "examples/mzi-scale.lumi"), "x=1/2"], + capture_output=True, + text=True, + ) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.strip(), "1/4") + r = subprocess.run( + [str(BIN), "eval", str(ROOT / "examples/mzi-scale.lumi"), "x=2"], + capture_output=True, + text=True, + ) + self.assertNotEqual(r.returncode, 0) + + def test_negative_and_endpoint_weights(self): + original = (ROOT / "examples/mzi-scale.lumi").read_text() + for w in ["-1", "-1/2", "0", "1"]: + if self.bundle.exists(): + shutil.rmtree(self.bundle) + r = self.compile( + text=original.replace("const weight 1/2 0", f"const weight {w} 0").replace( + "output y 11/10000", "output y 1/100" + ) + ) + self.assertEqual(r.returncode, 0, r.stderr) + ck.verify(self.bundle) + simulate(self.bundle, 100) + + def test_unknown_and_oversize(self): + for text in [ + "lumiris 1\nconst x NaN 0\noutput x 1", + "lumiris 1\nconst x 1 0\noutput x 0\nconst y 2 0", + "#" * 65537, + ]: + r = self.compile(text=text, device=False) + self.assertNotEqual(r.returncode, 0) + + def test_randomized_arithmetic_compiler_checker_agree(self): + rng = random.Random(9) + for i in range(100): + if self.bundle.exists(): + shutil.rmtree(self.bundle) + lo1, lo2 = rng.randint(-5, 5), rng.randint(1, 5) + hi1, hi2 = lo1 + rng.randint(0, 3), lo2 + rng.randint(0, 3) + op = rng.choice(["add", "sub", "mul", "div"]) + text = f"lumiris 1\ninput a {lo1} {hi1} 1/100\ninput b {lo2} {hi2} 1/100\n{op} y a b 1/1000 -20 20 -100 100\noutput y 10" + r = self.compile(text=text, device=False) + self.assertEqual(r.returncode, 0, r.stderr) + a, _, _ = ck.verify(self.bundle) + n = a.nodes["y"] + for _ in range(10): + x = Q(rng.randint(lo1 * 100, hi1 * 100), 100) + y = Q(rng.randint(lo2 * 100, hi2 * 100), 100) + dx, dy = Q(rng.randint(-10, 10), 1000), Q(rng.randint(-10, 10), 1000) + fn = { + "add": lambda a, b: a + b, + "sub": lambda a, b: a - b, + "mul": lambda a, b: a * b, + "div": lambda a, b: a / b, + }[op] + ideal, actual = fn(x, y), fn(x + dx, y + dy) + Q(1, 1000) + self.assertTrue(n.interval.contains(ck.Interval(ideal, ideal))) + self.assertLessEqual(abs(actual - ideal), n.error) + + +class CheckerProperties(unittest.TestCase): + def test_taylor_encloses_cosine(self): + rng = random.Random(32) + for _ in range(200): + center = Q(rng.randint(-1500, 1500), 100) + width = Q(rng.randint(0, 10), 10000) + phase = ck.Interval(center - width, center + width) + enclosure = ck.cosine_enclosure(phase) + for f in (phase.lo, phase.hi, (phase.lo + phase.hi) / 2): + v = math.cos(float(f) / 2) + self.assertLessEqual(float(enclosure.lo), v + 1e-15) + self.assertLessEqual(v, float(enclosure.hi) + 1e-15) + + def test_checker_stops_exponential_integer_growth(self): + text = "lumiris 1\nconst a 9223372036854775807 0\nmul y a a 0 -9223372036854775807 9223372036854775807 -9223372036854775807 9223372036854775807\noutput y 0" + with self.assertRaises(ck.Rejected): + ck.analyze(text) + + def test_signed_rational_denominators(self): + self.assertEqual(ck.rational("1/-2"), Q(-1, 2)) + self.assertEqual(ck.rational("-1/-2"), Q(1, 2)) + self.assertEqual(ck.rational("1/+2"), Q(1, 2)) + + def test_reject_parser_edges(self): + for s in ["1/0", "nan", "inf", "1e100", "0.1", "1/2/3", "9" * 100, "-9223372036854775808"]: + with self.assertRaises(ck.Rejected): + ck.rational(s) + + +if __name__ == "__main__": + unittest.main()