fact
stringlengths
7
18.7k
type
stringclasses
10 values
library
stringclasses
5 values
imports
listlengths
0
13
filename
stringclasses
441 values
symbolic_name
stringlengths
1
65
docstring
stringclasses
503 values
linkArgs := if System.Platform.isWindows then #[] else if System.Platform.isOSX then #["-L/opt/homebrew/opt/openblas/lib", "-L/usr/local/opt/openblas/lib", "-lblas"] else -- assuming linux #["-L/usr/lib/x86_64-linux-gnu/", "-lblas", "-lm"]
def
root
[ "import Lake" ]
lakefile.lean
linkArgs
null
inclArgs := if System.Platform.isWindows then #[] else if System.Platform.isOSX then #["-I/opt/homebrew/opt/openblas/include", "-I/usr/local/opt/openblas/include"] else -- assuming linux #[] package scilean { moreLinkArgs := linkArgs } -- -- require mathlib from git "https://github.com/leanprover-community/mathlib4" @ "v4.19.0" require leanblas from git "https://github.com/lecopivo/LeanBLAS" @ "v4.20.1" -- FFI - build all `*.c` files in `./C` directory and package them into `libscileanc.a/so` library target libscileanc pkg : FilePath := do let mut oFiles : Array (Job FilePath) := #[] for file in (← (pkg.dir / "C").readDir) do if file.path.extension == some "c" then let oFile := pkg.buildDir / "c" / (file.fileName.stripSuffix ".c" ++ ".o") let srcJob ← inputTextFile file.path let weakArgs := #["-I", (← getLeanIncludeDir).toString] oFiles := oFiles.push (← buildO oFile srcJob weakArgs #["-fPIC", "-O3", "-DNDEBUG"] "gcc" getLeanTrace) let name := nameToStaticLib "scileanc" buildStaticLib (pkg.sharedLibDir / name) oFiles @[default_target] lean_lib SciLean { roots := #[`SciLean] } -- Files that should be compiled, either to get fast tactic or to make FFI functions work in editor lean_lib SciLean.FFI where precompileModules := true moreLinkObjs := #[libscileanc] @[test_driver] lean_lib Test { globs := #[Glob.submodules `Test] } ---------------------------------------------------------------------------------------------------- lean_exe Doodle { root := `examples.Doodle } lean_exe WaveEquation { root := `examples.WaveEquation } lean_exe HelloWorld { root := `examples.HelloWorld } lean_exe HarmonicOscillator { root := `examples.HarmonicOscillator } lean_exe CircleOptimisation { root := `examples.CircleOptimisation } lean_exe Ballistic { root := `examples.Ballistic } lean_exe WalkOnSpheres { root := `examples.WalkOnSpheres } lean_exe BFGS { root := `Test.optimjl.bfgs } lean_exe LBFGS { root := `Test.optimjl.lbfgs } lean_exe GMM { root := `SciLean.Examples.GMM.Main } lean_exe BlasTest { root := `examples.BlasTest } lean_exe FloatTest { root := `examples.FloatTest } lean_exe ForLoopTest { buildType := .release moreLinkArgs := #["-O3", "-UNDEBUG"] root := `tests.sum_speed_test } lean_exe SurfaceMeshTests { root := `examples.SurfaceMeshTests } lean_exe FloatMatrixTest { root := `examples.FloatMatrixTest } lean_exe ProfileKMeans { root := `examples.Profile.KMeans } lean_exe ProfileKMeansDirection { root := `examples.Profile.KMeansDirection } lean_exe ProfileTensorOps { root := `examples.Profile.TensorOps } lean_exe ProfileGMM { root := `examples.Profile.GMM } lean_exe ProfileLSTM { root := `examples.Profile.LSTM } lean_exe MNISTClassifier where root := `examples.MNISTClassifier
def
root
[ "import Lake" ]
lakefile.lean
inclArgs
null
List.toArrayType (l : List α) {n : USize} (h : l.length = n.toNat) [PlainDataType α] : α^[n] := ⊞ i => l.get ⟨i.1.toNat,sorry_proof⟩ open Lean Meta Elab Term Qq macro_rules | `(⊞[ $x:term, $xs:term,* ]) => do let n := Syntax.mkNumLit (toString (xs.getElems.size + 1)) `(List.toArrayType [$x,$xs,*] (n:=$n) sorry_proof) -- let n := Syntax.mkNumLit (toString xs.getElems.size) -- `(term| ListN.toArrayType (arrayType #[$xs,*] $n (by rfl)) -- @[app_unexpander Array.toArrayType] -- def unexpandArrayToArrayType : Lean.PrettyPrinter.Unexpander -- | `($(_) #[$ys,*] $_*) => -- `(⊞[$ys,*]) -- | _ => throw ()
def
examples
[ "import SciLean", "import SciLean.Core.Functions.ArgMinMax", "import SciLean.Modules.SolversAndOptimizers.GradientDescent" ]
examples/Ballistic.lean
List.toArrayType
null
g := ⊞[0.0, -9.81]
def
examples
[ "import SciLean", "import SciLean.Core.Functions.ArgMinMax", "import SciLean.Modules.SolversAndOptimizers.GradientDescent" ]
examples/Ballistic.lean
g
null
ballisticMotion (x v : Float^[2]) := (v, g - (5.0 + ‖v‖₂) • v) #generate_revDeriv ballisticMotion x v prop_by unfold ballisticMotion; fprop trans_by unfold ballisticMotion; ftrans noncomputable approx aimToTarget (v₀ : Float^[2]) (optimizationRate : Float) := λ (T : Float) (target : Float^[2]) => let shoot := λ (v : Float^[2]) => odeSolve (t₀ := 0) (x₀ := ((0:Float^[2]),v)) (t := T) (f := λ (t : Float) (x,v) => ballisticMotion x v) |>.fst Function.invFun shoot target by -- reformulate inverse as minimization and apply gradient descent conv => enter [2,T,target,shoot] rw [invFun_as_min_norm2 (R:=Float) _ _ sorry_proof] rw [argminFun.approx.gradientDescent v₀ optimizationRate] approx_limit n := sorry_proof unfold scalarGradient set_option trace.Meta.Tactic.simp.discharge true in set_option trace.Meta.Tactic.ftrans.step true in set_option trace.Meta.Tactic.ftrans.theorems true in set_option trace.Meta.Tactic.simp.unify true in ftrans #exit approx_limit 1; intro gdSteps clean_up unsafe_ad; ignore_fun_prop -- run automatic differentiation, it gets blocked on `ℛ shoot` conv => enter [1] autodiff; autodiff; autodiff; autodiff; autodiff -- Precompute forward pass with midpoint method and 50 steps on the interval [0,T] and used linear interpolation conv => enter_let x conv => rw[odeSolve_fixed_dt_on_interval midpoint_step linearInterpolate1D T] approx_limit 50; intro forwardSteps; clean_up -- Use midpoint method with 50 steps on the backward pass conv => --enter_let Rxy₂ rw[odeSolve_fixed_dt midpoint_step] approx_limit 50; intro backwardSteps; clean_up /-- Generate `n` trajectory points in the interval [0,T] -/
def
examples
[ "import SciLean", "import SciLean.Core.Functions.ArgMinMax", "import SciLean.Modules.SolversAndOptimizers.GradientDescent" ]
examples/Ballistic.lean
ballisticMotion
null
shotTrajectoryPoints (n : ℕ) (T : ℝ) (v : ℝ×ℝ) : Array ((ℝ×ℝ)×(ℝ×ℝ)) := odeSolve_fixed_dt_array (λ (t : ℝ) (x,v) => ballisticMotion x v) midpoint_step n 0 (0,v) T /-- Do one step of optimization -/
def
examples
[ "import SciLean", "import SciLean.Core.Functions.ArgMinMax", "import SciLean.Modules.SolversAndOptimizers.GradientDescent" ]
examples/Ballistic.lean
shotTrajectoryPoints
/-- Generate `n` trajectory points in the interval [0,T] -/
aimStep (target : ℝ×ℝ) (v₀ : ℝ×ℝ) := aimToTarget v₀ (5.0:ℝ) (1:ℝ) target
def
examples
[ "import SciLean", "import SciLean.Core.Functions.ArgMinMax", "import SciLean.Modules.SolversAndOptimizers.GradientDescent" ]
examples/Ballistic.lean
aimStep
/-- Do one step of optimization -/
frame : Frame where xmin := -1 ymin := -1 xSize := 2 width := 400 height := 400
def
examples
[ "import ProofWidgets.Component.InteractiveSvg", "import ProofWidgets.Component.HtmlDisplay", "import examples.Ballistic" ]
examples/BallisticWidget.lean
frame
null
State where v : ℝ×ℝ deriving ToJson, FromJson local instance {frame : Frame} : CoeHead (Point frame) (ℝ×ℝ) where coe p := (⟨p.toAbsolute.1⟩, ⟨p.toAbsolute.2⟩) local instance {frame : Frame} : CoeTail (ℝ×ℝ) (Point frame) where coe x := .abs x.1.toFloat x.2.toFloat
structure
examples
[ "import ProofWidgets.Component.InteractiveSvg", "import ProofWidgets.Component.HtmlDisplay", "import examples.Ballistic" ]
examples/BallisticWidget.lean
State
null
isvg : InteractiveSvg State where init := { v := 0 } frame := frame update time Δt action mouseStart mouseEnd selected getData state := if let .some mouseEnd := mouseEnd then let target : ℝ×ℝ := mouseEnd let newVel := aimStep target state.v { v := newVel } else state render time mouseStart mouseEnd state := { elements := Id.run do let n : ℕ := 50 let Δt := (1:ℝ)/n let mut pts : Array (Point frame) := .mkEmpty (n+1) let trajectory := shotTrajectoryPoints 50 1 state.v pts := pts.append (trajectory.map fun xv => xv.1) let mut elems : Array (Element frame) := #[] if let .some target := mouseEnd then elems := elems.push <| Svg.circle target (.px 5) |>.setFill (0.9,0.1,0.1) elems := elems.push <| Svg.line (.abs 0 0) ((0.1:ℝ)•state.v) |>.setStroke (0.9,0.8,0.2) (.px 2) elems := elems.push <| Svg.polyline pts |>.setStroke (0.8,0.8,0.8) (.px 2) elems } open Server RequestM in @[server_rpc_method]
def
examples
[ "import ProofWidgets.Component.InteractiveSvg", "import ProofWidgets.Component.HtmlDisplay", "import examples.Ballistic" ]
examples/BallisticWidget.lean
isvg
null
updateSvg (params : UpdateParams State) : RequestM (RequestTask (UpdateResult State)) := isvg.serverRpcMethod params -- TODO: the tsx file is pretty broken @[widget_module]
def
examples
[ "import ProofWidgets.Component.InteractiveSvg", "import ProofWidgets.Component.HtmlDisplay", "import examples.Ballistic" ]
examples/BallisticWidget.lean
updateSvg
null
SvgWidget : Component (UpdateResult State) where javascript := include_str ".." / "lake-packages" / "proofwidgets" / "build" / "js" / "interactiveSvg.js"
def
examples
[ "import ProofWidgets.Component.InteractiveSvg", "import ProofWidgets.Component.HtmlDisplay", "import examples.Ballistic" ]
examples/BallisticWidget.lean
SvgWidget
null
init : UpdateResult State := { html := Html.ofTHtml <div>Init!!!</div>, state := { state := isvg.init time := 0 selected := none mousePos := none idToData := isvg.render 0 none none isvg.init |>.idToDataList} } #html <SvgWidget html={init.html} state={init.state}/>
def
examples
[ "import ProofWidgets.Component.InteractiveSvg", "import ProofWidgets.Component.HtmlDisplay", "import examples.Ballistic" ]
examples/BallisticWidget.lean
init
null
main : IO Unit := do IO.println "fix this test!" #exit let v := DenseVector.ofFn (Array:=FloatArray) (vstrg := .normal) (fun (i : Fin 3) => i.1.toFloat) IO.println s!"v := {v}" IO.println s!"0.1•v := {v.scal 0.1}" IO.println s!"v+v := {v.axpy 1 v}" IO.println s!"‖v‖₂² := {v.nrm2}"
def
examples
[ "import LeanBLAS" ]
examples/BlasTest.lean
main
null
A (x : ℝ^{2}) : ℝ^{2} := ⊞ i, if i = 0 then x[0] + x[1] else x[0] - x[1] -- We can turn on debugging logging with -- set_option trace.Meta.Tactic.fun_trans.rewrite true in function_properties A (x : ℝ^{2}) argument x IsLin, HasAdjoint, IsSmooth, HasAdjDiff, abbrev ∂ := λ dx => A dx by unfold A; fun_trans, def † := λ x' => ⊞ i, if i = 0 then x'[0] - x'[1] else x'[0] + x'[1] by sorry, abbrev ∂† by unfold adjointDifferential; fun_trans; fun_trans; simp -- Define the loss function.
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
A
/-- choose a particular A: (x, y) ↦ (x + y, x - y) -/
loss (x : ℝ^{2}) : ℝ := ⟪x, A x⟫ function_properties loss (x : ℝ^{2}) argument x IsSmooth, HasAdjDiff, abbrev ∂ := λ dx => (2 : ℝ) * ⟪dx, A x⟫ by { simp[loss]; fun_trans; -- 'trans' makes me think of 'transitive'. simp; funext dx; -- ⊢ ⟪dx, A x⟫ + ⟪x, A dx⟫ = 2 * ⟪dx, A x⟫ -- ⟪dx, A x⟫ + ⟪x, A dx⟫ -- = ⟪dx, A x⟫ + ⟪A† x, dx⟫ -- by definition of adjoint -- = ⟪dx, A x⟫ + ⟪dx, A† x⟫ -- by symmetry of inner product -- = ⟪dx, A x⟫ + ⟪dx, A x⟫ -- by A† = A -- = 2 * ⟪dx, A x⟫ -- by ring sorry }, abbrev ∂† by { unfold gradient; unfold loss; fun_trans; simp } /-- noncomputable version of gradient of loss -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
loss
null
gradLoss (x : ℝ^{2}) : ℝ^{2} := ∇ loss x /-- make gradLoss computable by transforming abstract gradient defn into computable definition. -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
gradLoss
/-- noncomputable version of gradient of loss -/
gradLoss' (x : ℝ^{2}) : ℝ^{2} := (∇ loss x) rewrite_by { unfold gradient; unfold loss; fun_trans } /-- Data at each training iteration -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
gradLoss'
/-- make gradLoss computable by transforming abstract gradient defn into computable definition. -/
TrainIter where iteration : Nat -- iteration count. point : ℝ^{2} -- current point on the circle.. loss_at_point : ℝ -- loss value at current point. gradAmbient : ℝ^{2} -- gradient at current point in ambient space. gradSubmanifold : ℝ^{2} -- gradient at current point on the tagent space.
structure
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
TrainIter
/-- Data at each training iteration -/
normalize (p : ℝ^{2}) : ℝ^{2} := p / ‖p‖ /-- Project 'v' along 'direction'. -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
normalize
/-- Normalize a vector. -/
project (v : ℝ^{2}) (direction: ℝ^{2}) : ℝ^{2} := ⟪v, direction⟫ • direction /-- Project point 'x' to lie on the circle. This is a retraction of (ℝ^2 - origin) onto the embedded S¹. -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
project
/-- Project 'v' along 'direction'. -/
circle_project (x : ℝ^{2}) := normalize x /-- project a vector to the tangent space at `p` by deleting the normal component -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
circle_project
/-- Project point 'x' to lie on the circle. This is a retraction of (ℝ^2 - origin) onto the embedded S¹. -/
projectToCircleTangentSpace (p : ℝ^{2}) (vec : ℝ^{2}) : ℝ^{2} := vec - project (direction := p) vec /-- Calculate gradient at current point -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
projectToCircleTangentSpace
/-- project a vector to the tangent space at `p` by deleting the normal component -/
TrainIter.calcAtPoint (i : Nat) (p : ℝ^{2}) : TrainIter where iteration := i point := p loss_at_point := loss p gradAmbient := gradLoss' p gradSubmanifold := projectToCircleTangentSpace (p := p) (gradLoss' p)
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
TrainIter.calcAtPoint
/-- Calculate gradient at current point -/
HyperParams where learningRate : ℝ := 0.01
structure
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
HyperParams
/-- Calculate gradient at current point -/
HyperParams.default : HyperParams := {}
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
HyperParams.default
/-- Calculate gradient at current point -/
TrainIter.nextPoint (hp : HyperParams) (step : TrainIter) : ℝ^{2} := circle_project <| step.point - hp.learningRate • step.gradSubmanifold /-- run the gradient descent algorithm -/
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
TrainIter.nextPoint
/-- Step to the next point by gradient descent -/
gradientDescend (init: ℝ^{2}) (nsteps : ℕ) (hp : HyperParams := HyperParams.default) : Array TrainIter := Id.run do let mut cur : ℝ^{2} := circle_project init let mut out := #[] for i in List.range nsteps do let step := TrainIter.calcAtPoint i cur out := out.push <| step cur := step.nextPoint hp return out
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
gradientDescend
/-- run the gradient descent algorithm -/
main : IO Unit := do let init : ℝ^{2} := ⊞ i, if i = 0 then 1 else 0 let losses := gradientDescend init 1000 for loss in losses do IO.println s!"{loss}"
def
examples
[ "import SciLean" ]
examples/CircleOptimisation.lean
main
/-- run the gradient descent algorithm -/
g : ℝ := 9.81 open SciLean variable (f : Fin n → ℝ × ℝ) #check λ [i] => f i
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
g
null
ParticleLagrangian {n} (ϕ : ℝ^{d} → ℝ) (m : ℝ^{n}) (x v : ℝ^{d}^{n}) : ℝ := ∑ i, (0.5:ℝ) * m[i] * ∥v[i]∥² - ∑ i, m[i] * ϕ x[i]
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
ParticleLagrangian
null
chainConstraint {n} (l : ℝ^{n}) (x : ℝ^{2}^{n+1}) : Prop := ∀ i : Fin n, ∥x[i.succ] - x[⟨i, sorry_proof⟩]∥ = l[i]
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
chainConstraint
null
chainConstraintFun {n} (l : ℝ^{n}) (x : ℝ^{2}^{n+1}) : ℝ^{n} := λ [i] => l[i]*l[i] - ∥x[i.succ] - x[⟨i, sorry_proof⟩]∥²
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
chainConstraintFun
null
chainConstraintLhs {n} (l : ℝ^{n}) (x : ℝ^{2}^{n+1}) := λ i : Fin n => ∥x[i.succ] - x[⟨i, sorry_proof⟩]∥
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
chainConstraintLhs
null
chainConstraintRhs {n} (l : ℝ^{n}) (x : ℝ^{2}^{n+1}) := λ i : Fin n => l[i]
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
chainConstraintRhs
null
endPoints {n n' : Nat} (l r : ℝ^{2}) (x : ℝ^{2}^{n+1}) (x' : ℝ^{2}^{n'+1}) : ℝ^{2} × ℝ^{2} × ℝ^{2} × ℝ^{2} := (-- top chain constraints x[0] - l, x[⟨n,sorry⟩] - r, -- bottow chain constraints x'[0] - x[⟨(n+1)/4, sorry⟩], x'[⟨n',sorry⟩] - x[⟨3*(n+1)/4, sorry⟩]) argument x isSmooth, diff, hasAdjDiff, adjDiff argument x' isSmooth, diff, hasAdjDiff, adjDiff #check ode_solve #check ReaderM NewtonSettings X Approx (X → Y → X × Y) (constrained_ode_solve f g) -- evolve and project, version 1 Approx ({x : X // g x = 0} → {x : X // g x = 0}) (λ x => let x' := ode_solve f Δt x.1 let μ := solve μ', g (x' + ∂† g x' μ') = 0 x' + ∂† g x' μ) => Approx (X → X) (constrained_ode_solve f g Δt) -- evolve and project, version 2 Approx (X → X) (λ x => let x' := ode_solve f Δt x let μ := solve μ', g (x + (x' - x) + ∂† g x μ') = 0 -- how can I Taylor this and use the fact that `g x = 0`? x' + ∂† g x' μ) => Approx (X → X) (constrained_ode_solve f g Δt) -- This is exact rewrite under some conditions on `f` and `g` -- The condition on `g` is probably `(g x ≠ 0) → let J := ∂ g x; IsInv (J ∘ J†)` this is saying that `J` is surjective map Approx ({x : X // g x = c} → {x : X // g x = c}) (λ x => let f' := λ x'' => let μ := solve μ', ∂ g x'' (∂† g x'' μ') = - ∂ g x'' (f x'') f x + ∂† g x μ let x' := ode_solve f' Δt x x') => Approx (X → X) (constrained_ode_solve f g Δt) -- but I want -- we can use (f : X → X) => λ x y => (f x, y) -- (f : X → Y → X × Y) => (λ x => (f x 0).1) Approx (X → Y → X × Y) (constrained_ode_solve f g Δt) (settings : IterLinSolverSettings) (A' : Approx (X → Y) (λ x => A x)) => Approx ((x₀ : X) → X) (A⁻¹ y) (x dx : X) → Approx ((x₀ : X) → X) ((∂† f x)⁻¹ dx) Approx (NewtonSettings → (x₀ : X) → X) (solve x, f x = 0) Approx (X → X) (solve x, f x = 0) -- evolve and reflect -- inspired by advection reflection sovler ApproxSolution (ℝ → X×Y → X×Y) (λ Δt x₀ μ₀ => let evolve := ode_solve f (Δt/2) let x' := evolve x let μ := 2 * solve μ', g (x' + ∂† g x' μ') = 0 let x'' := evolve (x' + ∂† g x' μ) (x'', μ)) -- let u' := ode_solve f t₀ u₀ 0 = ∇ u', L u' + ⟪μ, g u'⟫ let := u' + solve μ, g u' #exit
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
endPoints
null
L' (m : ℝ×ℝ) (x v : ℝ^{2}×ℝ^{2}) : ℝ := (m.1/2) * ∥v.1∥² + (m.2/2) * ∥v.2∥² - m.1 * g * x.1[1] - m.2 * g * x.2[1] argument x isSmooth, diff, hasAdjDiff, adjDiff argument v isSmooth, diff, hasAdjDiff, adjDiff
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
L'
null
parm (l : ℝ × ℝ) (θ : ℝ^{2}) : ℝ^{2}×ℝ^{2} := let d₁ : ℝ^{2} := ⟨Math.sin θ[0], Math.cos θ[0]⟩ let d₂ : ℝ^{2} := ⟨Math.sin θ[1], Math.cos θ[1]⟩ -- (l.1 * d₁, l.1 * d₁ + l.2 * d₂) (d₁, d₂) argument θ isSmooth
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
parm
null
parm' {n} (l : ℝ^{n}) (θ : ℝ^{n}) (x₀ : ℝ^{2}) : (ℝ^{2})^{n+1} := Id.run do let mut x : (ℝ^{2})^{n+1} := 0 let mut y := x₀ for h : i in [0:n] do let i : Fin n := ⟨i, h.2⟩ let next := i.succ let dir : ℝ^{2} := ⟨Math.cos (θ[i]), Math.sin (θ[i])⟩ y += l[i] * dir x[next] := y x -- This impelementation is paying for zero initialization
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
parm'
null
parm'' {n} (l : ℝ^{n}) (θ : ℝ^{n}) (x₀ : ℝ^{2}) : (ℝ^{2})^{n+1} := Id.run do let mut x : (ℝ^{2})^{n+1} := 0 let mut y := x₀ for h : i in [0:n] do let i : Fin n := ⟨i, h.2⟩ let next := i.succ let dir : ℝ^{2} := ⟨Math.cos (θ[i]), Math.sin (θ[i])⟩ y := y + l[i] * dir x[next] := y x -- There is no way the index access `θ[⟨n',sorry⟩]` and `l[⟨n', sorry⟩]` can be proven correct -- Can be fixed by changing the definition of `funRec`
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
parm''
null
parm''' {n} (l : ℝ^{n}) (θ : ℝ^{n}) (x₀ : ℝ^{2}) : (ℝ^{2})^{n+1} := funRec (n+1) 0 step (reserveElem (n+1) 0) where step : (n' : Nat) → ((ℝ^{2})^{n'}) → (ℝ^{2})^{n'+1} | 0, x => (λ [i] => x₀) | n'+1, x => let dir : ℝ^{2} := ⟨Math.cos (θ[⟨n',sorry_proof⟩]), Math.sin (θ[⟨n',sorry_proof⟩])⟩ let y := x[⟨n', by simp⟩] + l[⟨n', sorry_proof⟩] * dir pushElem 1 y x
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
parm'''
null
funRec.arg_x.diff_simp {α : Nat → Type} [Vec X] [∀ n, Vec (α n)] (f : (n : Nat) → α n → α (n + 1)) [∀ n, IsSmooth (f n)] (n m : Nat) : ∂ (λ x => funRec n m f x) = λ x dx => (funRec (α:=λ n' => α n' × α n') n m (λ n' (x',dx') => (f n' x', ∂ (f n') x' dx')) (x,dx)).2 := sorry_proof @[simp ↓]
theorem
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
funRec.arg_x.diff_simp
null
funRec.arg_f.diff_simp {α : Nat → Type} [Vec X] [∀ n, Vec (α n)] (f : X → (n : Nat) → α n → α (n + 1)) [∀ n, IsSmooth (λ x => f x n)] [∀ x n, IsSmooth (f x n)] (n : Nat) : ∂ (λ x => funRec n m (f x)) = λ x dx y => (∂ (funRec (α:=λ n' => X × α n') n m (λ n' xy' => (xy'.1, f xy'.1 n' xy'.2))) (x,y) (dx,0)).2 := sorry_proof set_option trace.Meta.Tactic.simp.discharge true in set_option trace.Meta.Tactic.simp.unify true in
theorem
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
funRec.arg_f.diff_simp
null
parm'''' {n} (l : ℝ^{n}) (θ : ℝ^{n}) (x₀ : ℝ) : ℝ^{n+1} := let step (n' : Nat) (x : ℝ^{n'}) : ℝ^{n'+1} := pushElem (Cont:=(ℝ^{·})) 1 (θ[⟨n',sorry⟩]) x funRec (n+1) 0 step 0 argument θ -- isSmooth := by simp[parm'''']; infer_instance, diff by simp[parm''''] enter [θ,x,a] simp only [funRec.arg_x.diff_simp (α:= λ n' => ℝ^{n} × ℝ^{n'})] simp -- (λ n' y => (y.1, pushElem 1 (y.1[⟨n',sorry⟩]) (y.snd))) (n+1) 0]
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
parm''''
null
parm'''' {n} (l : ℝ^{n}) (θ : ℝ^{n}) (x₀ : ℝ^{2}) : (ℝ^{2})^{n+1} := step 1 n (λ [i] => x₀) where step : (n m : Nat) → ((ℝ^{2})^{n+1-m}) → (ℝ^{2})^{n+1} | n, 0, x => x | n, m+1, x => pushElem 1 sorry (step n m x) -- | n'+1, x => -- let dir : ℝ^{2} := ⟨Math.cos (θ[⟨n',sorry_proof⟩]), Math.sin (θ[⟨n',sorry_proof⟩])⟩ -- let y := x[⟨n', by simp⟩] + l[⟨n', sorry_proof⟩] * dir -- pushElem 1 y x
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
parm''''
null
L (m l : ℝ×ℝ) (θ ω : ℝ^{2}) := (L' m (parm l θ) (ⅆ (t:=0), parm l (θ + (t:ℝ) * ω))) rewrite_by simp
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
L
null
solver (m l : ℝ×ℝ) (steps : Nat) : Impl (ode_solve (LagrangianSystem (L m l))) := by simp [L, pure_impl, PureImpl] conv in (L _ _) => simp [L, L', parm] pattern (differential _); rmlamlet; enter [θ, ω]; simp -- autodiff simp -- Lagrangian is in a nice form now conv => pattern (LagrangianSystem _); whnf admit
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
solver
null
solver_0 (m k l : ℝ) (steps : Nat) : Impl (λ x v : Q => (L m k l) x v) := by simp [LagrangianSystem, L, L', parm, gradient] conv => pattern (differential _); rmlamlet; enter [x, dx]; simp -- autodiff simp finish_impl
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
solver_0
null
solver_1 (m k l : ℝ) (steps : Nat) : Impl (λ x v : Q => ∇(swap (L m k l) v) x) := by conv in (L _ _ _) => enter [θ, ω] simp [L, L', parm] rmlamlet simp simp [gradient] conv => pattern (differential _); rmlamlet; enter [x, dx]; simp -- autodiff conv in (dual _) => pattern (dual _); rmlamlet; simp -- autodual . finish_impl
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
solver_1
null
solver_2 (m k l : ℝ) (steps : Nat) : Impl (λ x v : Q => ∇(∂ (L m k l) x v) v) := by conv in (L _ _ _) => enter [θ, ω] simp [L, L', parm] rmlamlet simp conv => pattern (differential _); enter [x, dx, y]; rmlamlet; simp -- autodiff (we need to introduce all arguments!) conv => -- autograd - part1 pattern (gradient _) enter [x] simp [gradient] pattern (differential _); enter [x, dx]; rmlamlet; simp -- autodiff conv => pattern (dual _); rmlamlet; simp -- autograd - part2 . finish_impl
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
solver_2
null
solver_3 (m k l : ℝ) (steps : Nat) : Impl (λ x v : Q => ∂(∇((L m k l) x)) v) := by conv in (L _ _ _) => simp [L, L', parm] { pattern (differential _); rmlamlet; enter [θ, ω]; simp } -- autodiff simp -- Lagrangian is in a nice form now conv => -- autograd - part1 pattern (gradient _) enter [x] simp [gradient] pattern (differential _); enter [x, dx]; rmlamlet; simp -- autodiff conv => pattern (dual _); rmlamlet; simp -- autograd - part2 conv => pattern (differential _); enter [x, dx]; rmlamlet; simp -- autodiff conv => enter [1,x,v] rmlamlet finish_impl
def
examples
[ "import SciLean.Core", "import SciLean.Mechanics", "import SciLean.Operators.ODE", "import SciLean.Solver.Solver", "import SciLean.Data.DataArray", "import SciLean.Core.Extra", "import SciLean.Functions.Trigonometric", "import SciLean.Data.FunRec" ]
examples/DoublePendulum.lean
solver_3
null
ε : ℝ := 0.001
def
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
ε
null
pair_add {X Y} [Add X] [Add Y] (x x' : X) (y y' : Y) : (x, y) + (x', y') = (x + x', y + y') := by simp[HAdd.hAdd, Add.add] done @[simp]
theorem
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
pair_add
null
inner_zero {X} [Hilbert X] (x : X) : ⟪0,x⟫ = 0 := sorry @[simp]
theorem
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
inner_zero
null
zero_inner {X} [Hilbert X] (x : X) : ⟪x,0⟫ = 0 := sorry
theorem
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
zero_inner
null
parm (l₁ l₂ : ℝ) (Ω : ℝ×ℝ) : (ℝ^(2:ℕ)) × (ℝ^(2:ℕ)) := let e : ℝ^(2:ℕ) := ⟨0,-1⟩ let Δx₁ := rotate2d Ω.1 (l₁ * e) let Δx₂ := rotate2d Ω.2 (l₂ * e) (Δx₁, Δx₁ + Δx₂) argument Ω isSmooth, diff, hasAdjDiff, adjDiff? set_option trace.Meta.Tactic.simp true function_properties parm.arg_Ω.diff (l₁ l₂ : ℝ) (Ω dΩ : ℝ×ℝ) : (ℝ^(2:ℕ)) × (ℝ^(2:ℕ)) -- argument Ω -- isSmooth, diff, hasAdjDiff, adjDiff argument dΩ -- -- isLin := by simp[diff]; infer_instance; done, -- isSmooth, -- diff --_simp := parm.arg_Ω.diff l₁ l₂ Ω ddΩ by simp[diff] done, -- hasAdjDiff, adjDiff -- := parm.arg_Ω.adjDiff l₁ l₂ Ω ddΩ' by simp[adjDiff,diff]; unfold hold; imp done
def
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
parm
null
g : ℝ := 9.81 -- instance (priority := high) {X Y} [Vec X] [Vec Y] (f : X → Y) : IsSmooth f := sorry -- instance (priority := high) {X Y} [SemiHilbert X] [SemiHilbert Y] (f : X → Y) : HasAdjDiff f := sorry /-
def
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
g
null
L (m₁ m₂ : ℝ) (l₁ l₂ : ℝ) (Ω ω : ℝ×ℝ) : ℝ := let e : ℝ^(2:ℕ) := ⟨0,-1⟩ let x := parm l₁ l₂ Ω let v := δ (λ t : ℝ => parm l₁ l₂ (Ω + t * ω)) 0 1 rewrite_by (simp) m₁/2 * ∥v.1∥² - m₁ * g * x.1.y + m₂/2 * ∥v.2∥² - m₂ * g * x.2.y argument Ω isSmooth, diff, hasAdjDiff, adjDiff argument ω isSmooth, diff, hasAdjDiff, adjDiff
def
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
L
null
momentum (m₁ m₂ : ℝ) (l₁ l₂ : ℝ) (Ω ω : ℝ×ℝ) : ℝ×ℝ := (∂† (λ ω' => L m₁ m₂ l₁ l₂ Ω ω') ω 1) rewrite_by simp #print L.arg_Ω.diff
def
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
momentum
null
velocity (m₁ m₂ : ℝ) (l₁ l₂ : ℝ) (Ω ω' : ℝ×ℝ) : ℝ×ℝ := ((λ ω => momentum m₁ m₂ l₁ l₂ Ω ω)⁻¹ ω') rewrite_by simp[momentum] simp[L.arg_ω.adjDiff] simp only [!?(∀ {X} [Hilbert X] (x y : X) (a : ℝ), ⟪a * x, y⟫ = a * ⟪x,y⟫)] simp only [!?(∀ (x y : ℝ^(2:ℕ)) (θ : ℝ), ⟪rotate2d θ x, rotate2d θ y⟫ = ⟪x,y⟫)] simp only [!?(∀ {X} [Hilbert X] (x y : X) (a : ℝ), ⟪a * x, a * y⟫ = a * a * ⟪x,y⟫)] simp only [!?(∀ {X} [Hilbert X] (x : X), ⟪x,x⟫ = ∥x∥²)] simp; unfold hold; simp -/
def
examples
[ "import SciLean" ]
examples/DoublePendulum2d.lean
velocity
null
Array.intro {n α} (f : Fin n → α) : Array α := Id.run do let mut a : Array α := Array.mkEmpty n for i in [0:n] do a := a.push (f ⟨i, sorry⟩) a
def
examples
[ "import Lean", "import SciLean.Functions.FFT" ]
examples/FFTWidget.lean
Array.intro
null
generateData := Id.run do let n := 6 let steps := 2^n let mut data : Array (Array (Vec2 Float)) := Array.mkEmpty steps for waveNumber in [0:2^n] do let wave : ℝ^{2^n, 2} := introElem λ (i,j) => let θ := 2 * Math.pi * waveNumber * (i.1.toReal / 2^n) if j = 0 then Math.cos θ else Math.sin θ let wave' := FFT wave data := data.push (Array.intro (λ i => ⟨i.1.toFloat, wave'[i,0].toFloat⟩)) data @[widget]
def
examples
[ "import Lean", "import SciLean.Functions.FFT" ]
examples/FFTWidget.lean
generateData
null
helloWidget : UserWidgetDefinition where name := "Hello" javascript := include_str "." / "plot.js" #widget helloWidget (Json.mkObj [ ("data", toJson generateData), ("useTimer", true), ("yDomain", toJson [0, 1]) ])
def
examples
[ "import Lean", "import SciLean.Functions.FFT" ]
examples/FFTWidget.lean
helloWidget
null
test1 : IO Unit := do let v : FloatVector (Fin 3) := VectorType.fromVec ![1,2,3] let v' : FloatVector' (.subvector (offset := 3) (inc := 2)) (Fin 3) := VectorType.fromVec ![1,2,3] let A : FloatMatrix' .RowMajor .normal (Fin 3) (Fin 3) := MatrixType.fromMatrix !![1,1,1; 0,-1,0; -1, 0, 42] IO.println v.data IO.println (10.0•v').data.data IO.println (v'+v').data.data IO.println (MatrixType.gemv 1 1 A v 0).data IO.println "" IO.println A.data IO.println "" IO.println (MatrixType.row A 0).data IO.println (MatrixType.col A 1).data IO.println (MatrixType.Square.diag A).data
def
examples
[ "import SciLean" ]
examples/FloatMatrixTest.lean
test1
null
main : IO Unit := do test1
def
examples
[ "import SciLean" ]
examples/FloatMatrixTest.lean
main
null
main : IO Unit := do IO.println (Float.tgamma 3.1415) IO.println (Float.lgamma 3.1415) IO.println (FloatArray.mk #[1.0,2.0,3.0,4.0,3.0]) IO.println (FloatArray.mk #[1.0,2.0,3.0,4.0,3.0] |>.toByteArray) IO.println (FloatArray.mk #[1.0,2.0,3.0,4.0,3.0] |>.toByteArray |>.toFloatArray sorry) IO.println (FloatArray.mk #[2.0,2.0,3.0,4.0,3.0] |>.toByteArray |>.toFloatArray sorry_proof) #exit IO.println (⊞ (j : Fin 3) => (VectorType.fromVec (X:=FloatVector _) (fun (i : Fin 3) => (10.0:Float)^(i.1+3) + i.1 + 10*j.1)))
def
examples
[ "import SciLean" ]
examples/FloatTest.lean
main
null
IndexType.sum_const {X} [AddCommGroup X] (x : X) : (∑ (i : I), x) = Size.size I • x := by sorry_proof
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
IndexType.sum_const
null
likelihood (x : R^[D]^[N]) (w : R^[K]) (μ : R^[D]^[K]) (σ : R^[D,D]^[K]) : R := ∏ i, ∑ k, w[k] * gaussianS (μ[k]) (σ[k]) (x[i]) namespace Param
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
likelihood
null
Q (q : R^[D]) (l : R^[((D-1)*D)/2]) : R^[D,D] := q.exp.diag + l.lowerTriangular D 1 def_rev_deriv Q in q l by unfold Q data_synth => lsimp def_rev_deriv' Q in q l by unfold Q data_synth => lsimp variable (q : R^[D]) (l : R^[((D-1)*D)/2]) -- properties of parametrization
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
Q
null
det_Q : (Q q l).det = exp q.sum := sorry_proof
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
det_Q
null
det_QTQ : ((Q q l)ᵀ * (Q q l)).det = exp (2 * q.sum) := by simp[DataArrayN.det_mul,det_Q,exp_pull]; ring_nf
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
det_QTQ
null
Q_invertible : (Q q l).Invertible := sorry_proof
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
Q_invertible
null
QTQ_invertible : ((Q q l)ᵀ * (Q q l)).Invertible := sorry_proof
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
QTQ_invertible
null
trace_QTQ : ((Q q l)ᵀ * Q q l).trace = ‖q.exp‖₂² + ‖l‖₂² := sorry_proof attribute [simp, simp_core] det_Q det_QTQ Q_invertible trace_QTQ
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
trace_QTQ
null
likelihood' (x : R^[D]^[N]) (α : R^[K]) (μ : R^[D]^[K]) (q : R^[D]^[K]) (l : R^[((D-1)*D)/2]^[K]) : R := likelihood x (α.softmax) μ (⊞ k => ((Q q[k] l[k])ᵀ * Q q[k] l[k])⁻¹) rewrite_by unfold likelihood simp (disch:=aesop) [gaussianS_ATA]
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
likelihood'
null
prior (m : R) (σ : R^[D,D]^[K]) := ∏ k, /- C(D,m) -/ (σ[k].det)^m * exp (-((σ[k])⁻¹).trace/2) open Lean Meta /-- Take expression full of multiplications and divitions and split it into lists of multiplication and division factors. For example: ``` e = x₁ * x₂ ==> [x₁,x₂] [] e = x₁ * x₂ / y₁ ==> [x₁,x₂] [y₁] e = x₁ / (y₁/x₂) ==> [x₁,x₂] [y₁] e = x₁ * x₂ / y₁ * (x₃ * x₄) / (y₂/x₅)` ==> [x₁,x₂,x₃,x₄,x₄] [y₁,y₂] ``` -/
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
prior
null
parse (e : Expr) : Option (List Expr × List Expr × Bool) := match e.getAppFnArgs with | (``HMul.hMul, #[_, _, _, _, e₁, e₂]) => do match parse e₁, parse e₂ with | .none, .none => return ([e₁,e₂], [], false) | .some (m₁,d₁,neg₁), .none => return (m₁ ++ [e₂], d₁, neg₁) | .none, .some (m₂,d₂,neg₂) => return ([e₁] ++ m₂, d₂, neg₂) | .some (m₁,d₁, neg₁), .some (m₂,d₂, neg₂) => return (m₁ ++ m₂, d₁ ++ d₂, neg₁ ^^ neg₂) | (``HDiv.hDiv, #[_, _, _, _, e₁, e₂]) => match parse e₁, parse e₂ with | none, none => return ([e₁], [e₂], false) | .some (m₁,d₁, neg₁), .none => return (m₁, d₁ ++ [e₂], neg₁) | .none, .some (m₂,d₂,neg₂) => return (e₁ :: d₂, m₂, neg₂) | .some (m₁,d₁,neg₁), .some (m₂,d₂,neg₂) => return (m₁ ++ d₂, d₁ ++ m₂, neg₁ ^^ neg₂) | (``Neg.neg, #[_, _, e]) => match parse e with | none => return ([e],[],true) | some (m,d,neg) => return (m,d,!neg) | (``Inv.inv, #[_, _, e]) => match parse e with | none => return ([],[e],true) | some (m,d,neg) => return (d,m,!neg) | _ => return ([e],[],false) open Qq Lean Meta Mathlib.Tactic in simproc_decl mul_pull_from_sum (sum _) := fun e => do let f := e.appArg! Lean.Meta.lambdaBoundedTelescope f 1 fun is b => do let i := is[0]! let .some (m,d,neg) := parse b | return .continue let (m₁,m₂) := m.toArray.split (fun e => ¬(e.containsFVar i.fvarId!)) let (d₁,d₂) := d.toArray.split (fun e => ¬(e.containsFVar i.fvarId!)) -- skip if all factors depend on the index unless m₁.size ≠ 0 ∨ d₁.size ≠ 0 do return .continue let X ← inferType b let one ← mkAppOptM ``OfNat.ofNat #[X, Expr.lit (.natVal 1), none] let merge := fun (m d : Array Expr) => do match m.size, d.size with | 0, 0 => pure one | _, 0 => mkAppFoldlM ``HMul.hMul m | 0, _ => mkAppM ``Inv.inv #[← mkAppFoldlM ``HMul.hMul d] | _, _ => mkAppM ``HDiv.hDiv #[← mkAppFoldlM ``HMul.hMul m, ← mkAppFoldlM ``HMul.hMul d] let mut e₁ ← merge m₁ d₁ if neg then e₁ ← mkAppM ``Neg.neg #[e₁] let e₂ ← merge m₂ d₂ let mut e' ← mkLambdaFVars #[i] e₂ e' ← mkAppM ``sum #[e'] e' ← mkAppM ``HMul.hMul #[e₁,e'] -- if nothing changes there is no need to pulute the proof with sorry if e.eqv e' then return .continue else let proof ← mkSorry (← mkEq e e') false -- IO.println s!"running simproc on {← ppExpr e}" -- IO.println s!"simplified to {← ppExpr e'}" -- TODO: here we should have `visit` but it gets into infinite loop :( return .done { expr := e', proof? := some proof } attribute [-simp_core] SciLean.ArrayType.sum_ofFn attribute [rsimp] SciLean.ArrayType.sum_ofFn @[simp_core]
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
parse
/-- Take expression full of multiplications and divitions and split it into lists of multiplication and division factors. For example: ``` e = x₁ * x₂ ==> [x₁,x₂] [] e = x₁ * x₂ / y₁ ==> [x₁,x₂] [y₁] e = x₁ / (y₁/x₂) ==> [x₁,x₂] [y₁] e = x₁ * x₂ / y₁ * (x₃ * x₄) / (y₂/x₅)` ==> [x₁,x₂,x₃,x₄,x₄] [y₁,y₂] ``` -/
neg_add_rev' {G : Type*} [SubtractionCommMonoid G] (a b : G) : -(a + b) = -a + -b := by simp[add_comm] @[rsimp]
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
neg_add_rev'
null
sum_normalize (x : R^[I]) : ∑ i, x[i] = x.sum := rfl -- TODO: this theorem replaces (∑ i, ‖x[i]‖₂²) with (∑ i, ‖x[i]‖₂²) instead of ‖x‖₂² -- there must be some issue with transparency omit [PlainDataType R] in @[rsimp]
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
sum_normalize
null
norm_normalize {X} [PlainDataType X] [NormedAddCommGroup X] [AdjointSpace R X] (x : X^[I]) : (∑ i, ‖x[i]‖₂²) = ‖x‖₂² := rfl -- theorem sum_over_prod {R} [AddCommMonoid R] {I J : Type*} [IndexType I] [IndexType J] -- {f : I → J → R} : ∑ i j, f i j = ∑ (i : I×J), f i.1 i.2 := sorry @[rsimp]
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
norm_normalize
null
isum_sum (x : R^[I]^[J]) : ∑ i, x[i].sum = x.uncurry.sum := by simp[DataArrayN.uncurry_def,DataArrayN.sum,Function.HasUncurry.uncurry] rw[sum_sum_eq_sum_prod] @[rsimp]
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
isum_sum
null
isum_norm_exp (x : R^[I]^[J]) : ∑ j, ‖x[j].exp‖₂² = ‖x.uncurry.exp‖₂² := by simp[DataArrayN.uncurry_def,DataArrayN.sum,Function.HasUncurry.uncurry, DataArrayN.norm2_def,DataArrayN.exp] rw[sum_sum_eq_sum_prod] @[rsimp]
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
isum_norm_exp
null
isum_norm (x : R^[I]^[J]) : (∑ j, ‖x[j]‖₂²) = ‖x.uncurry‖₂² := by simp[DataArrayN.uncurry_def,DataArrayN.sum,Function.HasUncurry.uncurry, DataArrayN.norm2_def] rw[sum_sum_eq_sum_prod] open Param Scalar in
theorem
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
isum_norm
null
loss (m : R) (x : R^[D]^[N]) (α : R^[K]) (μ : R^[D]^[K]) (q : R^[D]^[K]) (l : R^[((D-1)*D)/2]^[K]) : R := (let S := ⊞ k => ((Q q[k] l[k])ᵀ * Q q[k] l[k])⁻¹ (- log (likelihood x (α.softmax) μ S * prior m S))) rewrite_by unfold likelihood simp (disch:=aesop) [gaussianS_ATA] simp (disch:=aesop) [simp_core, likelihood, prior, DataArrayN.softmax_def] simp only [simp_core, mul_pull_from_sum, refinedRewritePost, sum_push, gaussian, log_push,exp_pull] ring_nf set_option pp.deepTerms.threshold 10000 set_option profiler true def_rev_deriv loss in α μ q l by unfold loss data_synth => skip open Optimjl
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
loss
null
f {D N : Nat} (K : Nat) (m : Float) (x : Float^[D]^[N]) := { f := fun (α,μ,q,l) => loss (K:=K) m x α μ q l hf := by simp apply HasRevFDeriv_from_HasRevFDerivUpdate data_synth => skip f' := _ : ObjectiveFunction _ _} #check Nat set_option profiler true
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
f
null
main : IO Unit := do let K := 2 let m := 0.0 let xs := ⊞[⊞[1.01,5.0], ⊞[1.03,5.1],⊞[1.1,4.8], ⊞[-1.03,5.0], ⊞[-0.9,4.7],⊞[-1.1,5.1]] let r ← optimize (f K m xs) {show_trace:=true : LBFGS Float K} (0,⊞[⊞[1,0],⊞[-1,2]],0,0) r.print #check Nat #eval! main #exit open Lean Parser Term in syntax "argmin" funBinder* ", " term : term open Lean Elab Parser Term in elab_rules : term | `(argmin $xs:funBinder* , $b:term) => do let f ← elabTerm (← `(fun $xs* => $b)) none let f ← mkUncurryFun' xs.size f let x ← mkAppM ``Function.argmin #[f] return x #check Function.argmin
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
main
null
hoh {D N K} (m : R) (x : R^[D]^[N]) := (argmin (α : R^[K]) μ q l, loss m x α μ q l) rewrite_by skip #check solveFun #print hoh #exit variable (x : R → R^[n]) (x' xi') (hx : HasRevFDerivUpdate R x x') (hxi : ∀ i, HasRevFDerivUpdate R (fun w => (x w)[i]) xi') (i : Fin n) def_rev_deriv loss in x by unfold loss lsimp data_synth => skip set_option trace.Meta.Tactic.data_synth true in #check (HasRevFDerivUpdate R (fun w => (x w)[i] * (x w)[i]) _) rewrite_by data_synth
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
hoh
null
foo (x y : R^[n]) := ‖⊞ i => x[i] + y[i]‖₂² def_rev_deriv foo in x y by unfold foo data_synth => lsimp
def
examples
[ "import SciLean", "import SciLean.Tactic.DataSynth.DefRevDeriv", "import SciLean.Data.DataArray.Operations.GaussianS" ]
examples/GaussianMixtureModel'.lean
foo
null
asdf (e : Expr) : Bool := Id.run do match e with | .lam _ t b _ => if t.isAppOfArity' ``Prod 2 then return true else return asdf b | .mdata _ e => asdf e | _ => return false open Lean Meta in dsimproc_decl prodFunSimproc (_) := fun e => do -- unless asdf e do return .continue unless e.isLambda do return .continue lambdaTelescope e fun xs b => do -- check if lambda has been already processed if let .letE _ _ (.mdata d _) _ _ := b then if .some true = d.get? `prodFunSimproc then return .continue let e' ← xs.foldrM (init:=b) fun x b => do let a ← splitStructureElem x let xs := a.1 let mk := a.2 if xs.size = 1 then mkLambdaFVars #[x] b else let xname ← x.fvarId!.getUserName -- mark values with mdata to preven infinite loop let data := MData.empty.set `prodFunSimproc true let xs ← xs.mapM (fun x => do pure (Expr.mdata data x)) withLetDecls (xs.mapIdx (fun i _ => xname.appendAfter (toString i))) xs fun vars => do let x' := mk.beta vars let b' := b.replaceFVar x x' -- let r ← Simp.simp b' let vars := #[x] ++ vars mkLambdaFVars vars b' return .continue e' #check (fun (x : ℝ×ℝ×ℝ) => x.1 + x.2.1 + x.2.2) rewrite_by simp -zeta only [prodFunSimproc] #check (fun (i : ℕ) => i) rewrite_by lsimp [↓prodFunSimproc] #check (fun (i : ℕ×ℕ) => i.1 + i.2) rewrite_by lsimp [prodFunSimproc] #check (fun (j : ℕ×ℕ) (i : ℕ×ℕ) => i.1 + i.2 + j.1) rewrite_by lsimp [↓prodFunSimproc] #check (fun (j : ℕ) (i : ℕ×ℕ) => i.1 + i.2) rewrite_by lsimp [prodFunSimproc] #check (fun (i : ℕ×ℕ) (j : ℕ) => i.1 + i.2) rewrite_by lsimp [prodFunSimproc] #check (fun (x : ℕ×ℕ) (y : ℕ×ℕ) => x.1 + y.1) rewrite_by lsimp [prodFunSimproc] #check (fun (i : ℕ) (x : ℕ×ℕ) (y : ℕ×ℕ) => x.1 + y.1) rewrite_by lsimp [prodFunSimproc] section Missing variable {R : Type} [RCLike R] {X : Type} [NormedAddCommGroup X] [NormedSpace R X] {Y : Type} [NormedAddCommGroup Y] [NormedSpace R Y] @[fun_prop]
def
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
asdf
null
ite.arg_te.Differentiable_rule {c : Prop} [h : Decidable c] (t e : X → Y) (ht : Differentiable R t) (he : Differentiable R e) : Differentiable R (fun x => ite c (t x) (e x)) := by split_ifs <;> assumption @[fun_prop]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
ite.arg_te.Differentiable_rule
null
dite.arg_te.Differentiable_rule {c : Prop} [h : Decidable c] (t : c → X → Y) (e : ¬c → X → Y) (ht : ∀ h, Differentiable R (t h)) (he : ∀ h, Differentiable R (e h)) : Differentiable R (fun x => dite c (t · x) (e · x)) := by split_ifs <;> aesop @[simp, simp_core]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
dite.arg_te.Differentiable_rule
null
oneHot_unit [Zero α] (i : Unit) (x : α) : oneHot i x = x := rfl
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
oneHot_unit
null
inner_QQT (x y : R^[I]) (Q : R^[I,J]) : ⟪x, Q*Qᵀ*y⟫ = ⟪Qᵀ*x,Qᵀ*y⟫ := by sorry @[scoped simp, scoped simp_core]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
inner_QQT
null
inner_QQT' (x y : R^[I]) (Q : R^[I,J]) : ⟪x, Q*(Qᵀ*y)⟫ = ⟪Qᵀ*x,Qᵀ*y⟫ := sorry @[scoped simp, scoped simp_core]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
inner_QQT'
null
inner_QTQ (x y : R^[J]) (Q : R^[I,J]) : ⟪x, Qᵀ*Q*y⟫ = ⟪Q*x,Q*y⟫ := sorry @[scoped simp, scoped simp_core]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
inner_QTQ
null
inner_QTQ' (x y : R^[J]) (Q : R^[I,J]) : ⟪x, Qᵀ*(Q*y)⟫ = ⟪Q*x,Q*y⟫ := sorry @[scoped simp, scoped simp_core]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
inner_QTQ'
null
gaussian_normalization_invQQT {d : ℕ} (Q : R^[d,d]) : (((2 * π) • (Q*Qᵀ)⁻¹).det) ^ (-(1:R) / 2) = (2 * π)^(-(d:R)/2) * Q.det := sorry @[scoped simp, scoped simp_core]
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
gaussian_normalization_invQQT
null
gaussian_normalization_invQTQ {d : ℕ} (Q : R^[d,d]) : (((2 * π) • (Qᵀ*Q)⁻¹).det) ^ (-(1:R) / 2) = (2 * π)^(-(d:R)/2) * Q.det := sorry
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
gaussian_normalization_invQTQ
null
log_sum_exp (x : I → R) : log (∑ i, exp (x i)) = (⊞ i => x i).logsumexp := sorry
theorem
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
log_sum_exp
null
likelihood (x : R^[D]^[N]) (w : R^[K]) (μ : R^[D]^[K]) (σ : R^[D,D]^[K]) : R := ∏ i, ∑ k, w[k] * (((2*π) • σ[k]).det)^(-(1:R)/2) * exp (-(1:R)/2 * ⟪x[i] - μ[k], (σ[k]⁻¹ * (x[i] - μ[k]) : R^[D])⟫) namespace Param
def
examples
[ "import SciLean", "import SciLean.Data.DataArray.Operations.Simps", "import SciLean.Lean.Meta.Basic", "import SciLean.Tactic.StructureDecomposition" ]
examples/GaussianMixtureModel.lean
likelihood
null