Datasets:
AI4M
/

text
stringlengths
0
3.34M
exists ramen [if] \\ [then] true constant ramen include afkit/afkit.f \ AllegroForthKit #1 #6 #0 [afkit] [checkver] ( Low-level ) 0 value (count) 0 value (ts) 0 value (bm) [undefined] LIGHTWEIGHT [if] include afkit/dep/zlib/zlib.f [then] include ramen/fixops.f include afkit/plat/sf/fixedp.f \ must come after fixops. include ramen/res.f include venery/venery.f include ramen/structs.f : ?p. p. ; \ dup $0000fff and if p. else i. then ; : <int is> bounds ?do i @ ." #" i. cell +loop ; : <bin is> dump ; : <skip is> nip ." ( " cell i/ i. ." )" space ; : <fixed is> bounds ?do i @ ?p. cell +loop ; : sfield sfield <fixed ; : svar svar <fixed ; : create-field create-field <fixed ; include ramen/types.f include ramen/superobj.f ( Assets ) include ramen/assets.f include ramen/image.f include ramen/font.f include ramen/buffer.f include ramen/sample.f ( Higher level stuff ) create ldr 256 /allot create project 256 /allot include ramen/publish.f include ramen/draw.f include ramen/default.f : stop ( - ) step> noop ; : void ( - ) stop show> ramenbg ; : project: ( -- <path> ) bl parse project place s" /" project append project count slashes 2drop ; : .project project count type ; variable ldl : ?project project count nip ?exit ldr count -filename project place ; : (included) 1 ldl +! ['] included catch dup 0= if -1 ldl +! ?project else 0 ldl ! then throw ; : rld ldr count nip -exit ldr count (included) ; : ld ( -- <file> ) bl parse s" .f" strjoin 2>r 2r@ file-exists not if project count 2r> strjoin 2>r then ldl @ 0= if 2r@ ldr place then 2r@ (included) 2r> 2drop ; : empty displaywh resolution oscursor on page cr ." [Empty]" void -assets 0 to now source-id 0> if including -name #1 + slashes project place then \ swiftforth empty ; : gild only forth definitions s" marker (empty)" evaluate cr ." [Gild] " ; : now now 1p ; \ must go last gild void
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE Strict #-} {-# LANGUAGE StrictData #-} module FourierPinwheel.Harmonics where import Data.Array.IArray as IA import Data.Array.Repa as R import Data.Complex import Data.List import Data.List as L import Data.Vector.Generic as VG import Data.Vector.Unboxed as VU import Filter.Utils import Math.Gamma import Utils.Parallel data FPData vector = FPData { getFPDataHarmonics :: [vector] , getFPDataHarmonicsOffset :: [vector] , getFPDataCoef :: [vector] , getFPDataCoefHollow :: [vector] } createHarmonics :: ( RealFloat e , Unbox e , NFData e , VG.Vector vector (Complex e) , NFData (vector (Complex e)) , Gamma (Complex e) ) => Int -> Int -> Int -> Int -> Int -> e -> e -> e -> R.Array U DIM4 (Complex e) -> IO (FPData (vector (Complex e))) createHarmonics numR2Freqs phiFreq rhoFreq thetaFreq rFreq alpha periodR2 periodEnv coefficients = do let harmonicVecs = parMap rdeepseq (\radialFreq -> createVector numR2Freqs (2 * phiFreq + 1) 1 (pinwheel periodR2 radialConst alpha radialFreq)) [-rhoFreq .. rhoFreq] harmonicVecsOffset = parMap rdeepseq (\radialFreq -> createVector numR2Freqs (2 * thetaFreq + 1) (-1) (logpolarHarmonics periodR2 radialConst radialFreq)) . L.reverse $ [-rFreq .. rFreq] phaseShiftedCoefArr <- computeUnboxedP . R.zipWith (*) coefficients . fromFunction (extent coefficients) $ \(Z :. r :. theta :. rho :. phi) -> phaseShift (phi - phiFreq - (theta - thetaFreq)) (rho - rhoFreq - (r - rFreq)) radialConst alpha let phaseShiftedCoefVecs = parMap rdeepseq (\r -> VU.convert . toUnboxed . computeS . R.slice phaseShiftedCoefArr $ (Z :. r :. All :. All :. All)) [0 .. 2 * rFreq] coefHollowArr <- computeUnboxedP $ sumArr *^ coefficients let coefHollowVecs = parMap rdeepseq (\r -> VU.convert . toUnboxed . computeS . R.slice coefHollowArr $ (Z :. r :. All :. All :. All)) [0 .. 2 * rFreq] return $ FPData harmonicVecs harmonicVecsOffset phaseShiftedCoefVecs coefHollowVecs where radialConst = 2 * pi / log periodEnv !sumArr1 = computePinwheelArray numR2Freqs phiFreq rhoFreq thetaFreq rFreq alpha periodR2 periodEnv sumArr = fromListUnboxed (extent coefficients) . parMap rdeepseq (\(r, theta, rho, phi) -> let angularFreq = phi - theta radialFreq = rho - r in sumArr1 IA.! (radialFreq, angularFreq)) $ [ (r, theta, rho, phi) | r <- [-rFreq .. rFreq] , theta <- [-thetaFreq .. thetaFreq] , rho <- [-rhoFreq .. rhoFreq] , phi <- [-phiFreq .. phiFreq] ] {-# INLINE createVector #-} createVector :: (RealFloat e, Unbox e, VG.Vector vector (Complex e)) => Int -> Int -> Int -> (Int -> e -> e -> Complex e) -> vector (Complex e) createVector numR2Freqs numAngularFreqs sign f = let centerR2 = div numR2Freqs 2 centerAngular = div numAngularFreqs 2 in VG.convert . toUnboxed . computeS . makeFilter2D . fromFunction (Z :. numAngularFreqs :. numR2Freqs :. numR2Freqs) $ \(Z :. k :. i :. j) -> let x = fromIntegral (i - centerR2) y = fromIntegral (j - centerR2) rho = sqrt $ x ^ 2 + y ^ 2 phi = atan2 y x in if rho == 0 then 0 else f (sign * (k - centerAngular)) phi rho {-# INLINE pinwheel #-} pinwheel :: (RealFloat e) => e -> e -> e -> Int -> Int -> e -> e -> Complex e pinwheel periodR2 radialConst alpha radialFreq angularFreq phi rho = pi * cis (fromIntegral angularFreq * phi) * ((periodR2 / (pi * rho) :+ 0) ** ((2 + alpha) :+ (radialConst * fromIntegral radialFreq))) {-# INLINE logpolarHarmonics #-} logpolarHarmonics :: (RealFloat e) => e -> e -> Int -> Int -> e -> e -> Complex e logpolarHarmonics periodR2 radialConst radialFreq angularFreq phi rho = cis (fromIntegral angularFreq * phi) * ((periodR2 / (pi * rho) :+ 0) ** (0 :+ (radialConst * fromIntegral radialFreq))) {-# INLINE phaseShift #-} phaseShift :: (RealFloat e, Gamma (Complex e)) => Int -> Int -> e -> e -> Complex e phaseShift angularFreq radialFreq radialConst alpha = ((0 :+ (-1)) ^ abs angularFreq) * (gamma $ ((2 + fromIntegral (abs angularFreq) + alpha) :+ (radialConst * fromIntegral radialFreq)) / 2) / (gamma $ ((fromIntegral (abs angularFreq) - alpha) :+ (radialConst * fromIntegral (-radialFreq))) / 2) {-# INLINE computeIndicesFromRadius #-} computeIndicesFromRadius :: Double -> [(Int,Int)] computeIndicesFromRadius radius = let rho = round radius r2 = rho ^ 2 in L.filter (\(x, y) -> let r = fromIntegral $ x ^ 2 + y ^ 2 in r < r2) [(x, y) | x <- [-rho .. rho], y <- [-rho .. rho]] {-# INLINE computePinwheelArray #-} computePinwheelArray :: ( Num e , RealFloat e , Gamma (Complex e) , Unbox e , NFData e ) => Int -> Int -> Int -> Int -> Int -> e -> e -> e -> IA.Array (Int, Int) (Complex e) computePinwheelArray numR2Freqs phiFreq rhoFreq thetaFreq rFreq alpha periodR2 periodEnv = let maxAngularFreq = phiFreq + thetaFreq maxRadialFreq = rhoFreq + rFreq radialConst = 2 * pi / log periodEnv centerR2 = div numR2Freqs 2 idxs = [ (radialFreq, angularFreq) | radialFreq <- [-maxRadialFreq .. maxRadialFreq] , angularFreq <- [-maxAngularFreq .. maxAngularFreq] ] pinwheels = parMap rdeepseq (\(radialFreq, angularFreq) -> let arr = fromFunction (Z :. numR2Freqs :. numR2Freqs) $ \(Z :. i :. j) -> let x = fromIntegral $ i - centerR2 y = fromIntegral $ j - centerR2 rho = sqrt $ x ^ 2 + y ^ 2 phi = atan2 y x in if rho == 0 then 0 else pinwheel periodR2 radialConst alpha radialFreq angularFreq phi rho * phaseShift angularFreq radialFreq radialConst alpha in sumAllS arr / (fromIntegral numR2Freqs^2)) idxs in listArray ((-maxRadialFreq, -maxAngularFreq), (maxRadialFreq, maxAngularFreq)) pinwheels
State Before: case mk.right C : Type u₁ inst✝ : Category C Z X Y P : C f : Z ⟶ X g : Z ⟶ Y inl : X ⟶ P inr : Y ⟶ P c : BinaryCofan X Y h : IsColimit c t : IsInitial Z ⊢ c.ι.app { as := WalkingPair.right } ≫ (Iso.refl c.pt).hom = (BinaryCofan.mk (c.ι.1 { as := WalkingPair.left }) (c.ι.1 { as := WalkingPair.right })).ι.app { as := WalkingPair.right } State After: case mk.right C : Type u₁ inst✝ : Category C Z X Y P : C f : Z ⟶ X g : Z ⟶ Y inl : X ⟶ P inr : Y ⟶ P c : BinaryCofan X Y h : IsColimit c t : IsInitial Z ⊢ BinaryCofan.inr c ≫ 𝟙 c.pt = BinaryCofan.inr c Tactic: dsimp State Before: case mk.right C : Type u₁ inst✝ : Category C Z X Y P : C f : Z ⟶ X g : Z ⟶ Y inl : X ⟶ P inr : Y ⟶ P c : BinaryCofan X Y h : IsColimit c t : IsInitial Z ⊢ BinaryCofan.inr c ≫ 𝟙 c.pt = BinaryCofan.inr c State After: no goals Tactic: simp
/- Copyright (c) 2021 Alena Gusakov, Bhavik Mehta, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alena Gusakov, Bhavik Mehta, Kyle Miller ! This file was ported from Lean 3 source module combinatorics.hall.finite ! leanprover-community/mathlib commit d6fad0e5bf2d6f48da9175d25c3dc5706b3834ce ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Fintype.Basic import Mathlib.Data.Set.Finite /-! # Hall's Marriage Theorem for finite index types This module proves the basic form of Hall's theorem. In constrast to the theorem described in `Combinatorics.Hall.Basic`, this version requires that the indexed family `t : ι → Finset α` have `ι` be finite. The `Combinatorics.Hall.Basic` module applies a compactness argument to this version to remove the `Finite` constraint on `ι`. The modules are split like this since the generalized statement depends on the topology and category theory libraries, but the finite case in this module has few dependencies. A description of this formalization is in [Gusakov2021]. ## Main statements * `Finset.all_card_le_bunionᵢ_card_iff_existsInjective'` is Hall's theorem with a finite index set. This is elsewhere generalized to `Finset.all_card_le_bunionᵢ_card_iff_existsInjective`. ## Tags Hall's Marriage Theorem, indexed families -/ open Finset universe u v namespace HallMarriageTheorem variable {ι : Type u} {α : Type v} [DecidableEq α] {t : ι → Finset α} section Fintype variable [Fintype ι] theorem hall_cond_of_erase {x : ι} (a : α) (ha : ∀ s : Finset ι, s.Nonempty → s ≠ univ → s.card < (s.bunionᵢ t).card) (s' : Finset { x' : ι | x' ≠ x }) : s'.card ≤ (s'.bunionᵢ fun x' => (t x').erase a).card := by haveI := Classical.decEq ι specialize ha (s'.image fun z => z.1) rw [Nonempty.image_iff, Finset.card_image_of_injective s' Subtype.coe_injective] at ha by_cases he : s'.Nonempty · have ha' : s'.card < (s'.bunionᵢ fun x => t x).card := by convert ha he fun h => by simpa [← h] using mem_univ x using 2 ext x simp only [mem_image, mem_bunionᵢ, exists_prop, SetCoe.exists, exists_and_right, exists_eq_right, Subtype.coe_mk] rw [← erase_bunionᵢ] by_cases hb : a ∈ s'.bunionᵢ fun x => t x · rw [card_erase_of_mem hb] exact Nat.le_pred_of_lt ha' · rw [erase_eq_of_not_mem hb] exact Nat.le_of_lt ha' · rw [nonempty_iff_ne_empty, not_not] at he subst s' simp #align hall_marriage_theorem.hall_cond_of_erase HallMarriageTheorem.hall_cond_of_erase /-- First case of the inductive step: assuming that `∀ (s : Finset ι), s.Nonempty → s ≠ univ → s.card < (s.bunionᵢ t).card` and that the statement of **Hall's Marriage Theorem** is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ theorem hall_hard_inductive_step_A {n : ℕ} (hn : Fintype.card ι = n + 1) (ht : ∀ s : Finset ι, s.card ≤ (s.bunionᵢ t).card) (ih : ∀ {ι' : Type u} [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ n → (∀ s' : Finset ι', s'.card ≤ (s'.bunionᵢ t').card) → ∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x) (ha : ∀ s : Finset ι, s.Nonempty → s ≠ univ → s.card < (s.bunionᵢ t).card) : ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by haveI : Nonempty ι := Fintype.card_pos_iff.mp (hn.symm ▸ Nat.succ_pos _) haveI := Classical.decEq ι -- Choose an arbitrary element `x : ι` and `y : t x`. let x := Classical.arbitrary ι have tx_ne : (t x).Nonempty := by rw [← Finset.card_pos] calc 0 < 1 := Nat.one_pos _ ≤ (Finset.bunionᵢ {x} t).card := ht {x} _ = (t x).card := by rw [Finset.singleton_bunionᵢ] choose y hy using tx_ne -- Restrict to everything except `x` and `y`. let ι' := { x' : ι | x' ≠ x } let t' : ι' → Finset α := fun x' => (t x').erase y have card_ι' : Fintype.card ι' = n := calc Fintype.card ι' = Fintype.card ι - 1 := Set.card_ne_eq _ _ = n := by rw [hn, Nat.add_succ_sub_one, add_zero] rcases ih t' card_ι'.le (hall_cond_of_erase y ha) with ⟨f', hfinj, hfr⟩ -- Extend the resulting function. refine' ⟨fun z => if h : z = x then y else f' ⟨z, h⟩, _, _⟩ · rintro z₁ z₂ have key : ∀ {x}, y ≠ f' x := by intro x h simpa [← h] using hfr x by_cases h₁ : z₁ = x <;> by_cases h₂ : z₂ = x <;> simp [h₁, h₂, hfinj.eq_iff, key, key.symm] · intro z simp only [ne_eq, Set.mem_setOf_eq] split_ifs with hz · rwa [hz] · specialize hfr ⟨z, hz⟩ rw [mem_erase] at hfr exact hfr.2 set_option linter.uppercaseLean3 false in #align hall_marriage_theorem.hall_hard_inductive_step_A HallMarriageTheorem.hall_hard_inductive_step_A theorem hall_cond_of_restrict {ι : Type u} {t : ι → Finset α} {s : Finset ι} (ht : ∀ s : Finset ι, s.card ≤ (s.bunionᵢ t).card) (s' : Finset (s : Set ι)) : s'.card ≤ (s'.bunionᵢ fun a' => t a').card := by classical rw [← card_image_of_injective s' Subtype.coe_injective] convert ht (s'.image fun z => z.1) using 1 apply congr_arg ext y simp #align hall_marriage_theorem.hall_cond_of_restrict HallMarriageTheorem.hall_cond_of_restrict /-- Second case of the inductive step: assuming that `∃ (s : Finset ι), s ≠ univ → s.card = (s.bunionᵢ t).card` and that the statement of **Hall's Marriage Theorem** is true for all `ι'` of cardinality ≤ `n`, then it is true for `ι` of cardinality `n + 1`. -/ theorem hall_hard_inductive_step_B {n : ℕ} (hn : Fintype.card ι = n + 1) (ht : ∀ s : Finset ι, s.card ≤ (s.bunionᵢ t).card) (ih : ∀ {ι' : Type u} [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ n → (∀ s' : Finset ι', s'.card ≤ (s'.bunionᵢ t').card) → ∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x) (s : Finset ι) (hs : s.Nonempty) (hns : s ≠ univ) (hus : s.card = (s.bunionᵢ t).card) : ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by haveI := Classical.decEq ι -- Restrict to `s` rw [Nat.add_one] at hn have card_ι'_le : Fintype.card s ≤ n := by apply Nat.le_of_lt_succ calc Fintype.card s = s.card := Fintype.card_coe _ _ < Fintype.card ι := (card_lt_iff_ne_univ _).mpr hns _ = n.succ := hn let t' : s → Finset α := fun x' => t x' rcases ih t' card_ι'_le (hall_cond_of_restrict ht) with ⟨f', hf', hsf'⟩ -- Restrict to `sᶜ` in the domain and `(s.bunionᵢ t)ᶜ` in the codomain. set ι'' := (s : Set ι)ᶜ let t'' : ι'' → Finset α := fun a'' => t a'' \ s.bunionᵢ t have card_ι''_le : Fintype.card ι'' ≤ n := by simp_rw [← Nat.lt_succ_iff, ← hn, ← Finset.coe_compl, coe_sort_coe] rwa [Fintype.card_coe, card_compl_lt_iff_nonempty] rcases ih t'' card_ι''_le (hall_cond_of_compl hus ht) with ⟨f'', hf'', hsf''⟩ -- Put them together have f'_mem_bunionᵢ : ∀ (x') (hx' : x' ∈ s), f' ⟨x', hx'⟩ ∈ s.bunionᵢ t := by intro x' hx' rw [mem_bunionᵢ] exact ⟨x', hx', hsf' _⟩ have f''_not_mem_bunionᵢ : ∀ (x'') (hx'' : ¬x'' ∈ s), ¬f'' ⟨x'', hx''⟩ ∈ s.bunionᵢ t := by intro x'' hx'' have h := hsf'' ⟨x'', hx''⟩ rw [mem_sdiff] at h exact h.2 have im_disj : ∀ (x' x'' : ι) (hx' : x' ∈ s) (hx'' : ¬x'' ∈ s), f' ⟨x', hx'⟩ ≠ f'' ⟨x'', hx''⟩ := by intro x x' hx' hx'' h apply f''_not_mem_bunionᵢ x' hx'' rw [← h] apply f'_mem_bunionᵢ x refine' ⟨fun x => if h : x ∈ s then f' ⟨x, h⟩ else f'' ⟨x, h⟩, _, _⟩ · refine' hf'.dite _ hf'' (@fun x x' => im_disj x x' _ _) · intro x simp only [of_eq_true] split_ifs with h <;> simp · exact hsf' ⟨x, h⟩ · exact sdiff_subset _ _ (hsf'' ⟨x, h⟩) set_option linter.uppercaseLean3 false in #align hall_marriage_theorem.hall_hard_inductive_step_B HallMarriageTheorem.hall_hard_inductive_step_B end Fintype variable [Finite ι] /-- Here we combine the two inductive steps into a full strong induction proof, completing the proof the harder direction of **Hall's Marriage Theorem**. -/ theorem hall_hard_inductive (ht : ∀ s : Finset ι, s.card ≤ (s.bunionᵢ t).card) : ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by cases nonempty_fintype ι induction' hn : Fintype.card ι using Nat.strong_induction_on with n ih generalizing ι rcases n with (_ | _) · rw [Fintype.card_eq_zero_iff] at hn exact ⟨isEmptyElim, isEmptyElim, isEmptyElim⟩ · have ih' : ∀ (ι' : Type u) [Fintype ι'] (t' : ι' → Finset α), Fintype.card ι' ≤ _ → (∀ s' : Finset ι', s'.card ≤ (s'.bunionᵢ t').card) → ∃ f : ι' → α, Function.Injective f ∧ ∀ x, f x ∈ t' x := by intro ι' _ _ hι' ht' exact ih _ (Nat.lt_succ_of_le hι') ht' _ rfl by_cases h : ∀ s : Finset ι, s.Nonempty → s ≠ univ → s.card < (s.bunionᵢ t).card · refine' hall_hard_inductive_step_A hn ht (@fun ι' => ih' ι') h · push_neg at h rcases h with ⟨s, sne, snu, sle⟩ exact hall_hard_inductive_step_B hn ht (@fun ι' => ih' ι') s sne snu (Nat.le_antisymm (ht _) sle) #align hall_marriage_theorem.hall_hard_inductive HallMarriageTheorem.hall_hard_inductive end HallMarriageTheorem /-- This is the version of **Hall's Marriage Theorem** in terms of indexed families of finite sets `t : ι → Finset α` with `ι` finite. It states that there is a set of distinct representatives if and only if every union of `k` of the sets has at least `k` elements. See `Finset.all_card_le_bunionᵢ_card_iff_exists_injective` for a version where the `Finite ι` constraint is removed. -/ theorem Finset.all_card_le_bunionᵢ_card_iff_existsInjective' {ι α : Type _} [Finite ι] [DecidableEq α] (t : ι → Finset α) : (∀ s : Finset ι, s.card ≤ (s.bunionᵢ t).card) ↔ ∃ f : ι → α, Function.Injective f ∧ ∀ x, f x ∈ t x := by constructor · exact HallMarriageTheorem.hall_hard_inductive · rintro ⟨f, hf₁, hf₂⟩ s rw [← card_image_of_injective s hf₁] apply card_le_of_subset intro rw [mem_image, mem_bunionᵢ] rintro ⟨x, hx, rfl⟩ exact ⟨x, hx, hf₂ x⟩ #align finset.all_card_le_bUnion_card_iff_exists_injective' Finset.all_card_le_bunionᵢ_card_iff_existsInjective'
(* Exercise 21 *) Require Import BenB. Variable D : Set. Variables P Q S T : D -> Prop. Variable R : D -> D -> Prop. Theorem exercise_021 : ~((forall x : D, P x) /\ (exists x : D, ~ P x)). Proof. neg_i (1=1) a1. exi_e (exists x:D, ~P x) a a2. con_e2 (forall x:D, P x). hyp a1. neg_e (P a). hyp a2. all_e (forall x:D, P x) a. con_e1 (exists x:D, ~P x). hyp a1. lin_solve. Qed.
{-# OPTIONS --without-K --rewriting #-} open import lib.Basics open import lib.NConnected open import lib.NType2 open import lib.types.FunctionSeq open import lib.types.Span open import lib.types.Pointed open import lib.types.Pushout open import lib.types.PushoutFlip open import lib.types.PushoutFmap open import lib.types.PushoutFlattening open import lib.types.Unit open import lib.types.Paths open import lib.types.Pi open import lib.types.Truncation open import lib.types.Lift open import lib.cubical.Cube open import lib.cubical.Square -- Suspension is defined as a particular case of pushout module lib.types.Suspension.Core where module _ {i} (A : Type i) where susp-span : Span susp-span = span Unit Unit A (λ _ → tt) (λ _ → tt) Susp : Type i Susp = Pushout susp-span -- [north'] and [south'] explictly ask for [A] north' : Susp north' = left tt south' : Susp south' = right tt module _ {i} {A : Type i} where north : Susp A north = north' A south : Susp A south = south' A merid : A → north == south merid x = glue x module SuspElim {j} {P : Susp A → Type j} (n : P north) (s : P south) (p : (x : A) → n == s [ P ↓ merid x ]) where private module P = PushoutElim (λ _ → n) (λ _ → s) p abstract f : Π (Susp A) P f = P.f north-β : f north ↦ n north-β = P.left-β unit {-# REWRITE north-β #-} south-β : f south ↦ s south-β = P.right-β unit {-# REWRITE south-β #-} merid-β : ∀ a → apd f (merid a) == p a merid-β = P.glue-β open SuspElim public using () renaming (f to Susp-elim) module SuspRec {j} {C : Type j} (n s : C) (p : A → n == s) where private module P = PushoutRec {d = susp-span A} (λ _ → n) (λ _ → s) p abstract f : Susp A → C f = P.f north-β : f north ↦ n north-β = P.left-β unit {-# REWRITE north-β #-} south-β : f south ↦ s south-β = P.right-β unit {-# REWRITE south-β #-} merid-β : ∀ a → ap f (merid a) == p a merid-β = P.glue-β open SuspRec public using () renaming (f to Susp-rec) module SuspRecType {j} (n s : Type j) (p : A → n ≃ s) = PushoutRecType {d = susp-span A} (λ _ → n) (λ _ → s) p module SuspPathElim {i} {j} {A : Type i} {B : Type j} (f g : Susp A → B) (n : f north == g north) (s : f south == g south) (m : ∀ a → Square n (ap f (merid a)) (ap g (merid a)) s) where private module M = SuspElim {P = λ sa → f sa == g sa} n s (λ a → ↓-='-from-square (m a)) open M public merid-square-β : ∀ a → natural-square M.f (merid a) == m a merid-square-β a = natural-square-β M.f (merid a) (M.merid-β a) module SuspDoublePathElim {i} {j} {k} {A : Type i} {B : Type j} {C : Type k} (f g : Susp A → Susp B → C) (n-n : f north north == g north north) (n-s : f north south == g north south) (s-n : f south north == g south north) (s-s : f south south == g south south) (n-m : ∀ b → Square n-n (ap (f north) (merid b)) (ap (g north) (merid b)) n-s) (s-m : ∀ b → Square s-n (ap (f south) (merid b)) (ap (g south) (merid b)) s-s) (m-n : ∀ a → Square n-n (ap (λ sa → f sa north) (merid a)) (ap (λ sa → g sa north) (merid a)) s-n) (m-s : ∀ a → Square n-s (ap (λ sa → f sa south) (merid a)) (ap (λ sa → g sa south) (merid a)) s-s) (m-m : ∀ a b → Cube (m-n a) (m-s a) (n-m b) (natural-square (λ sb → ap (λ sa → f sa sb) (merid a)) (merid b)) (natural-square (λ sb → ap (λ sa → g sa sb) (merid a)) (merid b)) (s-m b)) where private module N = SuspElim {P = λ sb → f north sb == g north sb} n-n n-s (λ b → ↓-='-from-square (n-m b)) n-natural-square : ∀ (b : B) → natural-square N.f (merid b) == n-m b n-natural-square b = natural-square-β N.f (merid b) (N.merid-β b) module S = SuspElim {P = λ sb → f south sb == g south sb} s-n s-s (λ b → ↓-='-from-square (s-m b)) s-natural-square : ∀ (b : B) → natural-square S.f (merid b) == s-m b s-natural-square b = natural-square-β S.f (merid b) (S.merid-β b) module M (sb : Susp B) = SuspElim {A = A} {P = λ sa → f sa sb == g sa sb} (N.f sb) (S.f sb) (λ a → Susp-elim {P = λ sb → N.f sb == S.f sb [ (λ sa → f sa sb == g sa sb) ↓ merid a ]} (↓-='-from-square (m-n a)) (↓-='-from-square (m-s a)) (λ b → ap↓ ↓-='-from-square $ cube-to-↓-square $ cube-shift-back (! (n-natural-square b)) $ cube-shift-front (! (s-natural-square b)) $ m-m a b) sb) abstract p : ∀ sa sb → f sa sb == g sa sb p sa sb = M.f sb sa north-north-β : p north north ↦ n-n north-north-β = N.north-β {-# REWRITE north-north-β #-} north-south-β : p north south ↦ n-s north-south-β = N.south-β {-# REWRITE north-south-β #-} south-north-β : p south north ↦ s-n south-north-β = S.north-β {-# REWRITE south-north-β #-} south-south-β : p south south ↦ s-s south-south-β = S.south-β {-# REWRITE south-south-β #-} north-merid-β : ∀ b → apd (p north) (merid b) == ↓-='-from-square (n-m b) north-merid-β = N.merid-β north-merid-square-β : ∀ b → natural-square (p north) (merid b) == n-m b north-merid-square-β b = natural-square-β (p north) (merid b) (north-merid-β b) south-merid-β : ∀ b → apd (p south) (merid b) == ↓-='-from-square (s-m b) south-merid-β = S.merid-β south-merid-square-β : ∀ b → natural-square (p south) (merid b) == s-m b south-merid-square-β b = natural-square-β (p south) (merid b) (south-merid-β b) merid-north-β : ∀ a → apd (λ sa → p sa north) (merid a) == ↓-='-from-square (m-n a) merid-north-β = M.merid-β north merid-north-square-β : ∀ a → natural-square (λ sa → p sa north) (merid a) == m-n a merid-north-square-β a = natural-square-β (λ sa → p sa north) (merid a) (merid-north-β a) merid-south-β : ∀ a → apd (λ sa → p sa south) (merid a) == ↓-='-from-square (m-s a) merid-south-β = M.merid-β south merid-south-square-β : ∀ a → natural-square (λ sa → p sa south) (merid a) == m-s a merid-south-square-β a = natural-square-β (λ sa → p sa south) (merid a) (merid-south-β a) susp-⊙span : ∀ {i} → Ptd i → ⊙Span susp-⊙span X = ⊙span ⊙Unit ⊙Unit X (⊙cst {X = X}) (⊙cst {X = X}) ⊙Susp : ∀ {i} → Type i → Ptd i ⊙Susp A = ⊙[ Susp A , north ] σloop : ∀ {i} (X : Ptd i) → de⊙ X → north' (de⊙ X) == north' (de⊙ X) σloop ⊙[ _ , x₀ ] x = merid x ∙ ! (merid x₀) σloop-pt : ∀ {i} {X : Ptd i} → σloop X (pt X) == idp σloop-pt {X = ⊙[ _ , x₀ ]} = !-inv-r (merid x₀) ⊙σloop : ∀ {i} (X : Ptd i) → X ⊙→ ⊙[ north' (de⊙ X) == north' (de⊙ X) , idp ] ⊙σloop X = σloop X , σloop-pt module _ {i j} where module SuspFmap {A : Type i} {B : Type j} (f : A → B) = SuspRec north south (merid ∘ f) Susp-fmap : {A : Type i} {B : Type j} (f : A → B) → (Susp A → Susp B) Susp-fmap = SuspFmap.f ⊙Susp-fmap : {A : Type i} {B : Type j} (f : A → B) → ⊙Susp A ⊙→ ⊙Susp B ⊙Susp-fmap f = (Susp-fmap f , idp) module _ {i} (A : Type i) where Susp-fmap-idf : ∀ a → Susp-fmap (idf A) a == a Susp-fmap-idf = Susp-elim idp idp $ λ a → ↓-='-in' (ap-idf (merid a) ∙ ! (SuspFmap.merid-β (idf A) a)) ⊙Susp-fmap-idf : ⊙Susp-fmap (idf A) ◃⊙idf =⊙∘ ⊙idf-seq ⊙Susp-fmap-idf = =⊙∘-in (⊙λ=' Susp-fmap-idf idp) transport-Susp : ∀ {i} {A B : Type i} (p : A == B) → transport Susp p ∼ Susp-fmap (coe p) transport-Susp {i} {A} {.A} p@idp sa = ! (Susp-fmap-idf A sa) ⊙transport-⊙Susp : ∀ {i} {A B : Type i} (p : A == B) → ⊙transport ⊙Susp p == ⊙Susp-fmap (coe p) ⊙transport-⊙Susp {i} {A} {.A} p@idp = ! (=⊙∘-out (⊙Susp-fmap-idf A)) module _ {i} {A : Type i} where Susp-fmap-cst : ∀ {j} {B : Type j} (b : B) (a : Susp A) → Susp-fmap (cst b) a == north Susp-fmap-cst b = Susp-elim idp (! (merid b)) $ (λ a → ↓-app=cst-from-square $ SuspFmap.merid-β (cst b) a ∙v⊡ tr-square _) ⊙Susp-fmap-cst : ∀ {j} {Y : Ptd j} → ⊙Susp-fmap {A = A} (λ _ → pt Y) == ⊙cst ⊙Susp-fmap-cst = ⊙λ=' (Susp-fmap-cst _) idp Susp-fmap-∘ : ∀ {i j k} {A : Type i} {B : Type j} {C : Type k} (g : B → C) (f : A → B) (σ : Susp A) → Susp-fmap (g ∘ f) σ == Susp-fmap g (Susp-fmap f σ) Susp-fmap-∘ g f = Susp-elim idp idp (λ a → ↓-='-in' $ ap-∘ (Susp-fmap g) (Susp-fmap f) (merid a) ∙ ap (ap (Susp-fmap g)) (SuspFmap.merid-β f a) ∙ SuspFmap.merid-β g (f a) ∙ ! (SuspFmap.merid-β (g ∘ f) a)) ⊙Susp-fmap-∘ : ∀ {i j k} {A : Type i} {B : Type j} {C : Type k} (g : B → C) (f : A → B) → ⊙Susp-fmap (g ∘ f) == ⊙Susp-fmap g ⊙∘ ⊙Susp-fmap f ⊙Susp-fmap-∘ g f = ⊙λ=' (Susp-fmap-∘ g f) idp ⊙Susp-fmap-seq : ∀ {i} {A B : Type i} → (A –→ B) → ⊙Susp A ⊙–→ ⊙Susp B ⊙Susp-fmap-seq idf-seq = ⊙idf-seq ⊙Susp-fmap-seq (f ◃∘ fs) = ⊙Susp-fmap f ◃⊙∘ ⊙Susp-fmap-seq fs abstract ⊙Susp-fmap-seq-∘ : ∀ {i} {A B : Type i} (fs : A –→ B) → ⊙Susp-fmap (compose fs) ◃⊙idf =⊙∘ ⊙Susp-fmap-seq fs ⊙Susp-fmap-seq-∘ idf-seq = ⊙Susp-fmap-idf _ ⊙Susp-fmap-seq-∘ (f ◃∘ fs) = =⊙∘-in $ ⊙Susp-fmap (f ∘ compose fs) =⟨ ⊙Susp-fmap-∘ f (compose fs) ⟩ ⊙Susp-fmap f ⊙∘ ⊙Susp-fmap (compose fs) =⟨ ap (⊙Susp-fmap f ⊙∘_) (=⊙∘-out (⊙Susp-fmap-seq-∘ fs)) ⟩ ⊙Susp-fmap f ⊙∘ ⊙compose (⊙Susp-fmap-seq fs) =∎ ⊙Susp-fmap-seq-=⊙∘ : ∀ {i} {A B : Type i} {fs gs : A –→ B} → fs =∘ gs → ⊙Susp-fmap-seq fs =⊙∘ ⊙Susp-fmap-seq gs ⊙Susp-fmap-seq-=⊙∘ {fs = fs} {gs = gs} p = ⊙Susp-fmap-seq fs =⊙∘⟨ !⊙∘ (⊙Susp-fmap-seq-∘ fs) ⟩ ⊙Susp-fmap (compose fs) ◃⊙idf =⊙∘₁⟨ ap ⊙Susp-fmap (=∘-out p) ⟩ ⊙Susp-fmap (compose gs) ◃⊙idf =⊙∘⟨ ⊙Susp-fmap-seq-∘ gs ⟩ ⊙Susp-fmap-seq gs ∎⊙∘ {- Extract the 'glue component' of a pushout -} module _ {i j k} {s : Span {i} {j} {k}} where module ExtractGlue = PushoutRec {d = s} {D = Susp (Span.C s)} (λ _ → north) (λ _ → south) merid extract-glue = ExtractGlue.f module _ {x₀ : Span.A s} where ⊙extract-glue : ⊙[ Pushout s , left x₀ ] ⊙→ ⊙[ Susp (Span.C s) , north ] ⊙extract-glue = extract-glue , idp module _ {i j} {A : Type i} {B : Type j} (eq : A ≃ B) where Susp-emap : Susp A ≃ Susp B Susp-emap = equiv (Susp-fmap (–> eq)) (Susp-fmap (<– eq)) (λ sb → Susp-fmap (–> eq) (Susp-fmap (<– eq) sb) =⟨ ! (Susp-fmap-∘ (–> eq) (<– eq) sb) ⟩ Susp-fmap ((–> eq) ∘ (<– eq)) sb =⟨ ap (λ f → Susp-fmap f sb) (λ= (<–-inv-r eq)) ⟩ Susp-fmap (idf B) sb =⟨ Susp-fmap-idf _ sb ⟩ sb =∎) (λ sa → Susp-fmap (<– eq) (Susp-fmap (–> eq) sa) =⟨ ! (Susp-fmap-∘ (<– eq) (–> eq) sa) ⟩ Susp-fmap ((<– eq) ∘ (–> eq)) sa =⟨ ap (λ f → Susp-fmap f sa) (λ= (<–-inv-l eq)) ⟩ Susp-fmap (idf A) sa =⟨ Susp-fmap-idf _ sa ⟩ sa =∎) private -- This is to make sure that we did not screw up [Susp-emap]. test₀ : fst Susp-emap == Susp-fmap (fst eq) test₀ = idp module _ {i j} {A : Type i} {B : Type j} where ⊙Susp-emap : A ≃ B → ⊙Susp A ⊙≃ ⊙Susp B ⊙Susp-emap eq = ≃-to-⊙≃ (Susp-emap eq) idp {- Interaction with [Lift] -} module _ {i j} (A : Type i) where Susp-Lift-econv : Susp (Lift {j = j} A) ≃ Lift {j = j} (Susp A) Susp-Lift-econv = lift-equiv ∘e Susp-emap lower-equiv Susp-Lift-conv : Susp (Lift {j = j} A) == Lift {j = j} (Susp A) Susp-Lift-conv = ua Susp-Lift-econv module _ {i j} (A : Type i) where ⊙Susp-Lift-econv : ⊙Susp (Lift {j = j} A) ⊙≃ ⊙Lift {j = j} (⊙Susp A) ⊙Susp-Lift-econv = ⊙lift-equiv {j = j} ⊙∘e ⊙Susp-emap {A = Lift {j = j} A} {B = A} lower-equiv ⊙Susp-Lift-conv : ⊙Susp (Lift {j = j} A) == ⊙Lift {j = j} (⊙Susp A) ⊙Susp-Lift-conv = ⊙ua ⊙Susp-Lift-econv {- Suspension of an n-connected space is n+1-connected -} abstract Susp-conn : ∀ {i} {A : Type i} {n : ℕ₋₂} → is-connected n A → is-connected (S n) (Susp A) Susp-conn {A = A} {n = n} cA = has-level-in ([ north ] , Trunc-elim (Susp-elim idp (Trunc-rec (λ a → ap [_] (merid a)) (contr-center cA)) (λ x → Trunc-elim {P = λ y → idp == Trunc-rec (λ a → ap [_] (merid a)) y [ (λ z → [ north ] == [ z ]) ↓ (merid x) ]} {{λ _ → ↓-preserves-level ⟨⟩}} (λ x' → ↓-cst=app-in (∙'-unit-l _ ∙ mers-eq n x x')) (contr-center cA)))) where instance _ = cA mers-eq : ∀ {i} {A : Type i} (n : ℕ₋₂) {{_ : is-connected n A}} → (x x' : A) → ap ([_] {n = S n}) (merid x) == Trunc-rec {{has-level-apply (Trunc-level {n = S n}) _ _}} (λ a → ap [_] (merid a)) [ x' ] mers-eq ⟨-2⟩ x x' = contr-has-all-paths _ _ mers-eq {A = A} (S n) x x' = conn-extend (pointed-conn-out A x) (λ y → ((ap [_] (merid x) == ap [_] (merid y)) , has-level-apply (has-level-apply (Trunc-level {n = S (S n)}) _ _) _ _)) (λ _ → idp) x'
lemma add_squared (a b : mynat) : (a + b) ^ (2 : mynat) = a ^ (2 : mynat) + b ^ (2 : mynat) + 2 * a * b := begin rw two_eq_succ_one, rw one_eq_succ_zero, repeat {rw pow_succ}, repeat {rw pow_zero}, ring, end
function [ w, x ] = gm_rule_set_old ( rule, dim_num, point_num ) %*****************************************************************************80 % %% GM_RULE_SET_OLD sets a Grundmann-Moeller rule. (OBSOLETE VERSION) % % Discussion: % % This version of the computation is no longer used. The direct % application of the formula results in overflows and inaccuracies % very quickly. % % This rule returns weights and abscissas of a Grundmann-Moeller % quadrature rule for the DIM_NUM-dimensional unit simplex. % % The dimension POINT_NUM can be determined by calling GM_RULE_SIZE. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 09 July 2007 % % Author: % % John Burkardt % % Reference: % % Axel Grundmann, Michael Moeller, % Invariant Integration Formulas for the N-Simplex % by Combinatorial Methods, % SIAM Journal on Numerical Analysis, % Volume 15, Number 2, April 1978, pages 282-290. % % Parameters: % % Input, integer RULE, the index of the rule. % 0 <= RULE. % % Input, integer DIM_NUM, the spatial dimension. % 1 <= DIM_NUM. % % Input, integer POINT_NUM, the number of points in the rule. % % Output, real W(POINT_NUM), the weights. % % Output, real X(DIM_NUM,POINT_NUM), the abscissas. % s = rule; d = 2 * s + 1; k = 0; n = dim_num; one_pm = 1; for i = 0 : s weight = r8_factorial ( n ) ... * ( one_pm * ( d + n - 2 * i )^d ) ... / ( 2^(2*s) * r8_factorial ( i ) * r8_factorial ( d + n - i ) ); one_pm = - one_pm; beta_sum = s - i; more = 0; beta = []; h = 0; t = 0; while ( 1 ) [ beta, more, h, t ] = comp_next ( beta_sum, dim_num + 1, ... beta, more, h, t ); k = k + 1; w(k) = weight; x(1:dim_num,k) = ( 2 * beta(2:dim_num+1)' + 1 ) / ( d + n - 2 * i ); if ( ~more ) break end end end return end
/- Copyright (c) 2022 Yuyang Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuyang Zhao ! This file was ported from Lean 3 source module ring_theory.mv_polynomial.tower ! leanprover-community/mathlib commit bb168510ef455e9280a152e7f31673cabd3d7496 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Algebra.Algebra.Tower import Mathlib.Data.MvPolynomial.Basic /-! # Algebra towers for multivariate polynomial This file proves some basic results about the algebra tower structure for the type `MvPolynomial σ R`. This structure itself is provided elsewhere as `MvPolynomial.isScalarTower` When you update this file, you can also try to make a corresponding update in `RingTheory.Polynomial.Tower`. -/ variable (R A B : Type _) {σ : Type _} namespace MvPolynomial section Semiring variable [CommSemiring R] [CommSemiring A] [CommSemiring B] variable [Algebra R A] [Algebra A B] [Algebra R B] variable [IsScalarTower R A B] variable {R B} theorem aeval_map_algebraMap (x : σ → B) (p : MvPolynomial σ R) : aeval x (map (algebraMap R A) p) = aeval x p := by rw [aeval_def, aeval_def, eval₂_map, IsScalarTower.algebraMap_eq R A B] #align mv_polynomial.aeval_map_algebra_map MvPolynomial.aeval_map_algebraMap end Semiring section CommSemiring variable [CommSemiring R] [CommSemiring A] [CommSemiring B] variable [Algebra R A] [Algebra A B] [Algebra R B] [IsScalarTower R A B] variable {R A} theorem aeval_algebraMap_apply (x : σ → A) (p : MvPolynomial σ R) : aeval (algebraMap A B ∘ x) p = algebraMap A B (MvPolynomial.aeval x p) := by rw [aeval_def, aeval_def, ← coe_eval₂Hom, ← coe_eval₂Hom, map_eval₂Hom, ← IsScalarTower.algebraMap_eq] -- Porting note: added simp only [Function.comp] #align mv_polynomial.aeval_algebra_map_apply MvPolynomial.aeval_algebraMap_apply theorem aeval_algebraMap_eq_zero_iff [NoZeroSMulDivisors A B] [Nontrivial B] (x : σ → A) (p : MvPolynomial σ R) : aeval (algebraMap A B ∘ x) p = 0 ↔ aeval x p = 0 := by rw [aeval_algebraMap_apply, Algebra.algebraMap_eq_smul_one, smul_eq_zero, iff_false_intro (one_ne_zero' B), or_false_iff] #align mv_polynomial.aeval_algebra_map_eq_zero_iff MvPolynomial.aeval_algebraMap_eq_zero_iff theorem aeval_algebraMap_eq_zero_iff_of_injective {x : σ → A} {p : MvPolynomial σ R} (h : Function.Injective (algebraMap A B)) : aeval (algebraMap A B ∘ x) p = 0 ↔ aeval x p = 0 := by rw [aeval_algebraMap_apply, ← (algebraMap A B).map_zero, h.eq_iff] #align mv_polynomial.aeval_algebra_map_eq_zero_iff_of_injective MvPolynomial.aeval_algebraMap_eq_zero_iff_of_injective end CommSemiring end MvPolynomial namespace Subalgebra open MvPolynomial section CommSemiring variable {R A} [CommSemiring R] [CommSemiring A] [Algebra R A] @[simp] end CommSemiring end Subalgebra
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker ! This file was ported from Lean 3 source module data.polynomial.coeff ! leanprover-community/mathlib commit fa256f00ce018e7b40e1dc756e403c86680bf448 ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathlib.Data.Polynomial.Basic import Mathlib.Data.Finset.NatAntidiagonal import Mathlib.Data.Nat.Choose.Sum /-! # Theory of univariate polynomials The theorems include formulas for computing coefficients, such as `coeff_add`, `coeff_sum`, `coeff_mul` -/ set_option linter.uppercaseLean3 false noncomputable section open Finsupp Finset AddMonoidAlgebra open BigOperators Polynomial namespace Polynomial universe u v variable {R : Type u} {S : Type v} {a b : R} {n m : ℕ} variable [Semiring R] {p q r : R[X]} section Coeff theorem coeff_one (n : ℕ) : coeff (1 : R[X]) n = if 0 = n then 1 else 0 := coeff_monomial #align polynomial.coeff_one Polynomial.coeff_one @[simp] theorem coeff_add (p q : R[X]) (n : ℕ) : coeff (p + q) n = coeff p n + coeff q n := by rcases p with ⟨⟩ rcases q with ⟨⟩ simp_rw [← ofFinsupp_add, coeff] exact Finsupp.add_apply _ _ _ #align polynomial.coeff_add Polynomial.coeff_add set_option linter.deprecated false in @[simp] theorem coeff_bit0 (p : R[X]) (n : ℕ) : coeff (bit0 p) n = bit0 (coeff p n) := by simp [bit0] #align polynomial.coeff_bit0 Polynomial.coeff_bit0 @[simp] theorem coeff_smul [Monoid S] [DistribMulAction S R] (r : S) (p : R[X]) (n : ℕ) : coeff (r • p) n = r • coeff p n := by rcases p with ⟨⟩ simp_rw [← ofFinsupp_smul, coeff] exact Finsupp.smul_apply _ _ _ #align polynomial.coeff_smul Polynomial.coeff_smul theorem support_smul [Monoid S] [DistribMulAction S R] (r : S) (p : R[X]) : support (r • p) ⊆ support p := by intro i hi simp [mem_support_iff] at hi⊢ contrapose! hi simp [hi] #align polynomial.support_smul Polynomial.support_smul /-- `Polynomial.sum` as a linear map. -/ @[simps] def lsum {R A M : Type _} [Semiring R] [Semiring A] [AddCommMonoid M] [Module R A] [Module R M] (f : ℕ → A →ₗ[R] M) : A[X] →ₗ[R] M where toFun p := p.sum fun n r => f n r map_add' p q := sum_add_index p q _ (fun n => (f n).map_zero) fun n _ _ => (f n).map_add _ _ map_smul' c p := by -- Porting note: `dsimp only []` is required for beta reduction. dsimp only [] rw [sum_eq_of_subset _ (fun n r => f n r) (fun n => (f n).map_zero) _ (support_smul c p)] simp only [sum_def, Finset.smul_sum, coeff_smul, LinearMap.map_smul, RingHom.id_apply] #align polynomial.lsum Polynomial.lsum #align polynomial.lsum_apply Polynomial.lsum_apply variable (R) /-- The nth coefficient, as a linear map. -/ def lcoeff (n : ℕ) : R[X] →ₗ[R] R where toFun p := coeff p n map_add' p q := coeff_add p q n map_smul' r p := coeff_smul r p n #align polynomial.lcoeff Polynomial.lcoeff variable {R} @[simp] theorem lcoeff_apply (n : ℕ) (f : R[X]) : lcoeff R n f = coeff f n := rfl #align polynomial.lcoeff_apply Polynomial.lcoeff_apply @[simp] theorem finset_sum_coeff {ι : Type _} (s : Finset ι) (f : ι → R[X]) (n : ℕ) : coeff (∑ b in s, f b) n = ∑ b in s, coeff (f b) n := (lcoeff R n).map_sum #align polynomial.finset_sum_coeff Polynomial.finset_sum_coeff theorem coeff_sum [Semiring S] (n : ℕ) (f : ℕ → R → S[X]) : coeff (p.sum f) n = p.sum fun a b => coeff (f a b) n := by rcases p with ⟨⟩ -- Porting note: Was `simp [Polynomial.sum, support, coeff]`. simp [Polynomial.sum, support_ofFinsupp, coeff_ofFinsupp] #align polynomial.coeff_sum Polynomial.coeff_sum /-- Decomposes the coefficient of the product `p * q` as a sum over `Nat.antidiagonal`. A version which sums over `range (n + 1)` can be obtained by using `Finset.Nat.sum_antidiagonal_eq_sum_range_succ`. -/ theorem coeff_mul (p q : R[X]) (n : ℕ) : coeff (p * q) n = ∑ x in Nat.antidiagonal n, coeff p x.1 * coeff q x.2 := by rcases p with ⟨p⟩; rcases q with ⟨q⟩ simp_rw [← ofFinsupp_mul, coeff] exact AddMonoidAlgebra.mul_apply_antidiagonal p q n _ Nat.mem_antidiagonal #align polynomial.coeff_mul Polynomial.coeff_mul @[simp] theorem mul_coeff_zero (p q : R[X]) : coeff (p * q) 0 = coeff p 0 * coeff q 0 := by simp [coeff_mul] #align polynomial.mul_coeff_zero Polynomial.mul_coeff_zero /-- `constantCoeff p` returns the constant term of the polynomial `p`, defined as `coeff p 0`. This is a ring homomorphism. -/ @[simps] def constantCoeff : R[X] →+* R where toFun p := coeff p 0 map_one' := coeff_one_zero map_mul' := mul_coeff_zero map_zero' := coeff_zero 0 map_add' p q := coeff_add p q 0 #align polynomial.constant_coeff Polynomial.constantCoeff #align polynomial.constant_coeff_apply Polynomial.constantCoeff_apply theorem isUnit_C {x : R} : IsUnit (C x) ↔ IsUnit x := ⟨fun h => (congr_arg IsUnit coeff_C_zero).mp (h.map <| @constantCoeff R _), fun h => h.map C⟩ #align polynomial.is_unit_C Polynomial.isUnit_C theorem coeff_mul_X_zero (p : R[X]) : coeff (p * X) 0 = 0 := by simp #align polynomial.coeff_mul_X_zero Polynomial.coeff_mul_X_zero theorem coeff_X_mul_zero (p : R[X]) : coeff (X * p) 0 = 0 := by simp #align polynomial.coeff_X_mul_zero Polynomial.coeff_X_mul_zero theorem coeff_C_mul_X_pow (x : R) (k n : ℕ) : coeff (C x * X ^ k : R[X]) n = if n = k then x else 0 := by rw [C_mul_X_pow_eq_monomial, coeff_monomial] congr 1 simp [eq_comm] #align polynomial.coeff_C_mul_X_pow Polynomial.coeff_C_mul_X_pow theorem coeff_C_mul_X (x : R) (n : ℕ) : coeff (C x * X : R[X]) n = if n = 1 then x else 0 := by rw [← pow_one X, coeff_C_mul_X_pow] #align polynomial.coeff_C_mul_X Polynomial.coeff_C_mul_X @[simp] theorem coeff_C_mul (p : R[X]) : coeff (C a * p) n = a * coeff p n := by rcases p with ⟨p⟩ simp_rw [← monomial_zero_left, ← ofFinsupp_single, ← ofFinsupp_mul, coeff] exact AddMonoidAlgebra.single_zero_mul_apply p a n #align polynomial.coeff_C_mul Polynomial.coeff_C_mul theorem C_mul' (a : R) (f : R[X]) : C a * f = a • f := by ext rw [coeff_C_mul, coeff_smul, smul_eq_mul] #align polynomial.C_mul' Polynomial.C_mul' @[simp] theorem coeff_mul_C (p : R[X]) (n : ℕ) (a : R) : coeff (p * C a) n = coeff p n * a := by rcases p with ⟨p⟩ simp_rw [← monomial_zero_left, ← ofFinsupp_single, ← ofFinsupp_mul, coeff] exact AddMonoidAlgebra.mul_single_zero_apply p a n #align polynomial.coeff_mul_C Polynomial.coeff_mul_C theorem coeff_X_pow (k n : ℕ) : coeff (X ^ k : R[X]) n = if n = k then 1 else 0 := by simp only [one_mul, RingHom.map_one, ← coeff_C_mul_X_pow] #align polynomial.coeff_X_pow Polynomial.coeff_X_pow @[simp] theorem coeff_X_pow_self (n : ℕ) : coeff (X ^ n : R[X]) n = 1 := by simp [coeff_X_pow] #align polynomial.coeff_X_pow_self Polynomial.coeff_X_pow_self section Fewnomials open Finset theorem support_binomial {k m : ℕ} (hkm : k ≠ m) {x y : R} (hx : x ≠ 0) (hy : y ≠ 0) : support (C x * X ^ k + C y * X ^ m) = {k, m} := by apply subset_antisymm (support_binomial' k m x y) simp_rw [insert_subset, singleton_subset_iff, mem_support_iff, coeff_add, coeff_C_mul, coeff_X_pow_self, mul_one, coeff_X_pow, if_neg hkm, if_neg hkm.symm, mul_zero, zero_add, add_zero, Ne.def, hx, hy] #align polynomial.support_binomial Polynomial.support_binomial theorem support_trinomial {k m n : ℕ} (hkm : k < m) (hmn : m < n) {x y z : R} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : support (C x * X ^ k + C y * X ^ m + C z * X ^ n) = {k, m, n} := by apply subset_antisymm (support_trinomial' k m n x y z) simp_rw [insert_subset, singleton_subset_iff, mem_support_iff, coeff_add, coeff_C_mul, coeff_X_pow_self, mul_one, coeff_X_pow, if_neg hkm.ne, if_neg hkm.ne', if_neg hmn.ne, if_neg hmn.ne', if_neg (hkm.trans hmn).ne, if_neg (hkm.trans hmn).ne', mul_zero, add_zero, zero_add, Ne.def, hx, hy, hz] #align polynomial.support_trinomial Polynomial.support_trinomial theorem card_support_binomial {k m : ℕ} (h : k ≠ m) {x y : R} (hx : x ≠ 0) (hy : y ≠ 0) : card (support (C x * X ^ k + C y * X ^ m)) = 2 := by rw [support_binomial h hx hy, card_insert_of_not_mem (mt mem_singleton.mp h), card_singleton] #align polynomial.card_support_binomial Polynomial.card_support_binomial theorem card_support_trinomial {k m n : ℕ} (hkm : k < m) (hmn : m < n) {x y z : R} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : card (support (C x * X ^ k + C y * X ^ m + C z * X ^ n)) = 3 := by rw [support_trinomial hkm hmn hx hy hz, card_insert_of_not_mem (mt mem_insert.mp (not_or_of_not hkm.ne (mt mem_singleton.mp (hkm.trans hmn).ne))), card_insert_of_not_mem (mt mem_singleton.mp hmn.ne), card_singleton] #align polynomial.card_support_trinomial Polynomial.card_support_trinomial end Fewnomials @[simp] theorem coeff_mul_X_pow (p : R[X]) (n d : ℕ) : coeff (p * Polynomial.X ^ n) (d + n) = coeff p d := by rw [coeff_mul, sum_eq_single (d, n), coeff_X_pow, if_pos rfl, mul_one] · rintro ⟨i, j⟩ h1 h2 rw [coeff_X_pow, if_neg, mul_zero] rintro rfl apply h2 rw [Nat.mem_antidiagonal, add_right_cancel_iff] at h1 subst h1 rfl · exact fun h1 => (h1 (Nat.mem_antidiagonal.2 rfl)).elim #align polynomial.coeff_mul_X_pow Polynomial.coeff_mul_X_pow @[simp] theorem coeff_X_pow_mul (p : R[X]) (n d : ℕ) : coeff (Polynomial.X ^ n * p) (d + n) = coeff p d := by rw [(commute_X_pow p n).eq, coeff_mul_X_pow] #align polynomial.coeff_X_pow_mul Polynomial.coeff_X_pow_mul theorem coeff_mul_X_pow' (p : R[X]) (n d : ℕ) : (p * X ^ n).coeff d = ite (n ≤ d) (p.coeff (d - n)) 0 := by split_ifs with h · rw [← tsub_add_cancel_of_le h, coeff_mul_X_pow, add_tsub_cancel_right] · refine' (coeff_mul _ _ _).trans (Finset.sum_eq_zero fun x hx => _) rw [coeff_X_pow, if_neg, mul_zero] exact ((le_of_add_le_right (Finset.Nat.mem_antidiagonal.mp hx).le).trans_lt <| not_le.mp h).ne #align polynomial.coeff_mul_X_pow' Polynomial.coeff_mul_X_pow' theorem coeff_X_pow_mul' (p : R[X]) (n d : ℕ) : (X ^ n * p).coeff d = ite (n ≤ d) (p.coeff (d - n)) 0 := by rw [(commute_X_pow p n).eq, coeff_mul_X_pow'] #align polynomial.coeff_X_pow_mul' Polynomial.coeff_X_pow_mul' @[simp] theorem coeff_mul_X (p : R[X]) (n : ℕ) : coeff (p * X) (n + 1) = coeff p n := by simpa only [pow_one] using coeff_mul_X_pow p 1 n #align polynomial.coeff_mul_X Polynomial.coeff_mul_X @[simp] theorem coeff_X_mul (p : R[X]) (n : ℕ) : coeff (X * p) (n + 1) = coeff p n := by rw [(commute_X p).eq, coeff_mul_X] #align polynomial.coeff_X_mul Polynomial.coeff_X_mul theorem coeff_mul_monomial (p : R[X]) (n d : ℕ) (r : R) : coeff (p * monomial n r) (d + n) = coeff p d * r := by rw [← C_mul_X_pow_eq_monomial, ← X_pow_mul, ← mul_assoc, coeff_mul_C, coeff_mul_X_pow] #align polynomial.coeff_mul_monomial Polynomial.coeff_mul_monomial theorem coeff_monomial_mul (p : R[X]) (n d : ℕ) (r : R) : coeff (monomial n r * p) (d + n) = r * coeff p d := by rw [← C_mul_X_pow_eq_monomial, mul_assoc, coeff_C_mul, X_pow_mul, coeff_mul_X_pow] #align polynomial.coeff_monomial_mul Polynomial.coeff_monomial_mul -- This can already be proved by `simp`. theorem coeff_mul_monomial_zero (p : R[X]) (d : ℕ) (r : R) : coeff (p * monomial 0 r) d = coeff p d * r := coeff_mul_monomial p 0 d r #align polynomial.coeff_mul_monomial_zero Polynomial.coeff_mul_monomial_zero -- This can already be proved by `simp`. theorem coeff_monomial_zero_mul (p : R[X]) (d : ℕ) (r : R) : coeff (monomial 0 r * p) d = r * coeff p d := coeff_monomial_mul p 0 d r #align polynomial.coeff_monomial_zero_mul Polynomial.coeff_monomial_zero_mul theorem mul_X_pow_eq_zero {p : R[X]} {n : ℕ} (H : p * X ^ n = 0) : p = 0 := ext fun k => (coeff_mul_X_pow p n k).symm.trans <| ext_iff.1 H (k + n) #align polynomial.mul_X_pow_eq_zero Polynomial.mul_X_pow_eq_zero theorem mul_X_pow_injective (n : ℕ) : Function.Injective fun P : R[X] => X ^ n * P := by intro P Q hPQ simp only at hPQ ext i rw [← coeff_X_pow_mul P n i, hPQ, coeff_X_pow_mul Q n i] #align polynomial.mul_X_pow_injective Polynomial.mul_X_pow_injective theorem mul_X_injective : Function.Injective fun P : R[X] => X * P := pow_one (X : R[X]) ▸ mul_X_pow_injective 1 #align polynomial.mul_X_injective Polynomial.mul_X_injective theorem coeff_X_add_C_pow (r : R) (n k : ℕ) : ((X + C r) ^ n).coeff k = r ^ (n - k) * (n.choose k : R) := by rw [(commute_X (C r : R[X])).add_pow, ← lcoeff_apply, LinearMap.map_sum] simp only [one_pow, mul_one, lcoeff_apply, ← C_eq_nat_cast, ← C_pow, coeff_mul_C, Nat.cast_id] rw [Finset.sum_eq_single k, coeff_X_pow_self, one_mul] · intro _ _ h simp [coeff_X_pow, h.symm] · simp only [coeff_X_pow_self, one_mul, not_lt, Finset.mem_range] intro h rw [Nat.choose_eq_zero_of_lt h, Nat.cast_zero, mul_zero] #align polynomial.coeff_X_add_C_pow Polynomial.coeff_X_add_C_pow theorem coeff_one_add_X_pow (R : Type _) [Semiring R] (n k : ℕ) : ((1 + X) ^ n).coeff k = (n.choose k : R) := by rw [add_comm _ X, coeff_X_add_one_pow] #align polynomial.coeff_one_add_X_pow Polynomial.coeff_one_add_X_pow theorem C_dvd_iff_dvd_coeff (r : R) (φ : R[X]) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := by constructor · rintro ⟨φ, rfl⟩ c rw [coeff_C_mul] apply dvd_mul_right · intro h choose c hc using h classical let c' : ℕ → R := fun i => if i ∈ φ.support then c i else 0 let ψ : R[X] := ∑ i in φ.support, monomial i (c' i) use ψ ext i simp only [coeff_C_mul, mem_support_iff, coeff_monomial, finset_sum_coeff, Finset.sum_ite_eq'] split_ifs with hi · rw [hc] · rw [Classical.not_not] at hi rwa [mul_zero] #align polynomial.C_dvd_iff_dvd_coeff Polynomial.C_dvd_iff_dvd_coeff set_option linter.deprecated false in theorem coeff_bit0_mul (P Q : R[X]) (n : ℕ) : coeff (bit0 P * Q) n = 2 * coeff (P * Q) n := by -- Porting note: `two_mul` is required. simp [bit0, add_mul, two_mul] #align polynomial.coeff_bit0_mul Polynomial.coeff_bit0_mul set_option linter.deprecated false in theorem coeff_bit1_mul (P Q : R[X]) (n : ℕ) : coeff (bit1 P * Q) n = 2 * coeff (P * Q) n + coeff Q n := by simp [bit1, add_mul, coeff_bit0_mul] #align polynomial.coeff_bit1_mul Polynomial.coeff_bit1_mul theorem smul_eq_C_mul (a : R) : a • p = C a * p := by simp [ext_iff] #align polynomial.smul_eq_C_mul Polynomial.smul_eq_C_mul theorem update_eq_add_sub_coeff {R : Type _} [Ring R] (p : R[X]) (n : ℕ) (a : R) : p.update n a = p + Polynomial.C (a - p.coeff n) * Polynomial.X ^ n := by ext rw [coeff_update_apply, coeff_add, coeff_C_mul_X_pow] split_ifs with h <;> simp [h] #align polynomial.update_eq_add_sub_coeff Polynomial.update_eq_add_sub_coeff end Coeff section cast @[simp] theorem nat_cast_coeff_zero {n : ℕ} {R : Type _} [Semiring R] : (n : R[X]).coeff 0 = n := by induction' n with n ih · simp · simp [ih] #align polynomial.nat_cast_coeff_zero Polynomial.nat_cast_coeff_zero @[norm_cast] -- @[simp] -- Porting note: simp can prove this theorem nat_cast_inj {m n : ℕ} {R : Type _} [Semiring R] [CharZero R] : (↑m : R[X]) = ↑n ↔ m = n := by constructor · intro h apply_fun fun p => p.coeff 0 at h simpa using h · rintro rfl rfl #align polynomial.nat_cast_inj Polynomial.nat_cast_inj @[simp] theorem int_cast_coeff_zero {i : ℤ} {R : Type _} [Ring R] : (i : R[X]).coeff 0 = i := by cases i <;> simp #align polynomial.int_cast_coeff_zero Polynomial.int_cast_coeff_zero @[norm_cast] -- @[simp] -- Porting note: simp can prove this theorem int_cast_inj {m n : ℤ} {R : Type _} [Ring R] [CharZero R] : (↑m : R[X]) = ↑n ↔ m = n := by constructor · intro h apply_fun fun p => p.coeff 0 at h simpa using h · rintro rfl rfl #align polynomial.int_cast_inj Polynomial.int_cast_inj end cast instance charZero [CharZero R] : CharZero R[X] where cast_injective _x _y := nat_cast_inj.mp #align polynomial.char_zero Polynomial.charZero end Polynomial
wiki:WikiPedia:Airsoft is a combat simulation recreational past time practiced around the world. Unlike paintball, airsoft focuses on recreating military or law enforcement situations with a strong focus on realism using replica firearms that shoot 6mm plastic BBs. Airsoft was started in Asia and its popularity in countries like Japan, China and Taiwan has much to do with the strict firearms laws in those countries. In recent years airsoft has become increasingly popular in the United States and Europe. Airsoft guns range from cheap springpowered guns costing only a few dollars to highend electric and gas powered guns costing as much as six thousand dollars. Many of these, especially the electric guns, are wiki:wikipedia:selective fire guns. As most of these guns are very realistic and designed to look just like the real thing, the tips of the barrels are often painted orange to distinguish them from real firearms. Federal law actually requires these markings on fake guns that are imported or shipped in the US, with some exceptions for law enforcement, movie, and theatrical purposes. California law supposedly prohibits removing the markings required by federal law, but is so ineptly written that it doesnt actually change anything. Still, removing these markings is done at your own risk and generally isnt a wise thing to do. Even with orange tips, many airsoft guns can easily be mistaken for the real thing. Brandishing a replica firearm is legally equivalent to brandishing the real thing. If you do get into Airsoft, NEVER DISPLAY YOUR AIRSOFT GUNS IN PUBLIC unless theyre the type that are made out of clear plastic and obviously identifiable as a toy from a significant distance. When transporting airsoft guns, keep them in a case and out of public view. The added benefit of a case is that they protect your airsoft gun, which are often more fragile than they appear. Where to purchase Big 5 Sporting Goods carries airsoft guns, but they are of inferior quality, reliability, and are not powerful enough to be competitive in most recreational matches. Theyre cheap, however, and are perfect for backyard plinking. The next closest airsoft retailer is Airsoft Extreme in Citrus Heights. Used airsoft guns can often be found on the the http://www.sacairsoft.com/ SacAirsoft forum, Craigslist, Facebook Facebook marketplace, and http://www.ebay.com eBay. There are plenty of airsoft retailers on the internet and many people get their guns this way. If you plan on joining recreational matches or purchasing an airsoft gun, talk with someone already involved in the hobby. They can tell you what you need, what you should look for, and whether or not youre getting a good deal. Legality It is of Illegal in Davis debatable legality to discharge airsoft guns in Davis. http://www.city.davis.ca.us/cmo/citycode/detail.cfm?p26&q1046 Municipal code 26.02.060 prohibits the discharge of air guns within city limits, but electric and spring airsoft guns are not air guns under California law. Gaspowered airsoft guns dont actually operate on compressed air, but instead operate by igniting a flammable gas. Thus, theyre not air guns, but a prosecutor could argue that they fall under the law prohibiting discharge. This would depend on whether they accept the airsoft gun as an airgun (and airsoft guns have a wide variation), but the real risk by prosecution is putting people and property at risk. Various people at the Davis Police Department are under the impression that the municipal code prohibits firing all airsoft guns within the city, although they are not very clear on whether airsoft guns qualify as airguns. For example, one representative at the DPD, after conference with other employees, stated any projectile powered by air is prohibited, regardless of its strength, type of material used, or speed. This is extremely vague: Do http://en.wikipedia.org/wiki/Nerf Nerf guns qualify? Most definitely not. Again, it seems the situation is more important than the actual shooting of airsoft guns. Several police officers have happened upon people playing games (both at three in the morning, and three in the afternoon) and been fine with it. It does not seem from the comments below that anyone has been cited for playing with airsoft guns in Davis. In the interest of avoiding being cited, you should probably consider shooting an airsoft gun in Davis to be extremely discouraged, and act accordingly. That means that you should (in general) NEVER PLAY (OR DISPLAY) IN PUBLIC. You do not want to risk or threaten damage to either person or property, which is what most people get into trouble for. Play at one of the locations listed below or on other privately owned land outside the city limits. (Although people have played in the smaller, lesser known public parks during the night). You, of course, should have the permission of the landowner or tenant if youre not playing on your own property. One can learn more about the federal laws http://en.wikipedia.org/wiki/Legal_issues_in_airsoft#United_States here. Locations Where to play Local venues for playing airsoft: Davis Paintball Center (Its not open on weekdays, so you can play airsoft there on those days) Adventure Zone Laser Tag in Sacramento runs airsoft nights every Tuesday, 69pm Sacramento Airsoft runs events in the area (usually near wiki:yubasutter:Marysville) multiple times a month Where not to play Schools, parks, and other public spaces. Teams/Groups There are several airsoft teams in Davis, or at least people who often group together when playing. If your name is written incorrectly or you want to fix something about your team or add your team, go ahead, that way we know who plays and games can be more easily organized. Wiki airsofters Users/WilliamLewis plays with his brother and some friends when hes back in his hometown. Owns an ICS M4 and various lowend springers/electrics. Wants a gas gun. New Teams Team Delta 1. Users/JohnDudek John Dudek 2. Users/IsaacHamlenGomez Isaac HG 3. Bill Fiore 4. Users/TaylorClark Taylor Clark 5. Users/SeanReedy Sean Reedy 6. Josh Bradford Team Ghost Recon 1. Users/AlexNorris Alex Norris 2. Kurt Smeagol 3. Rhys Johns 4. Kyle Lucas 5. Isaac White Old Teams The Mobile Infantry; formerly Team Breakfast 1. Users/JohnDudek John Dudek 2. Users/IsaacHamlenGomez Isaac HamlenGomez 3. Users/AlexNorris Alex Norris 4. Users/SeanReedy Sean Reedy 5. Kurt Smeagol (spelling) 6. Bill Fiore 7. Users/DanielGonzales Dan Biel 8. Users/TaylorClark Taylor Clark 9. Rhys Johns Team Breakfast supports kicking Team Ramrods ass. Team Ramrod 1. Users/ColinClark Colin Clark 2. John Banvard (Wiggie) 3. Josh Fowler (Juanito) 4. Andrew Hartman 5. Rhys Johns (Joe Dirt) 6. Jackson Jordan (Auction Jackson) 7. Kiel Damasa (KDiesel) Others 1. David Normie Hopper 2. Kevin Smith 3. David Provost 4. Users/DanielGonzales Dan Beil 5. Steven Bishop See Also: Nerf and Paintball 20051103 21:05:30 nbsp If you ask any firearm instructor, or officer of the law, they will tell you that airsoft guns are legally no different from any other type of guns, and just because a cop doesnt put you in jail, doesnt mean that it isnt illegal, maybe he was being nice. Think about it, you need a permit for a slingshot, why not for an airsoft gun? Users/DanielGonzales 20051103 21:47:43 nbsp Danny. Shut up. We pretend its legal. Users/IsaacHamlenGomez 20051103 21:56:56 nbsp who is kevin smith????? Users/TaylorClark 20051103 21:59:24 nbsp Probably not THE http://www.imdb.com/name/nm0003620/ Kevin wiki:WikiPedia:Kevin_Smith Smith? Users/JasonAller 20051103 22:05:32 nbsp Kevin Smith is this dude, to clear it all up, who is friends with David Normie Hopper. I played airsoft with the both of them a time ago, but they both play, even though Kevins never played with Breakfast or Ramrod Users/JohnDudek 20051103 22:14:30 nbsp Thats BS he told you, Daniel. Theyre not classified as firearms. If you rob a store with an airsoft gun, they will charge you as if you had a firearm, but on the federal level: they are not illegal. Look up the wikipedia link about the legality part. Users/Edwins ES 20051103 22:16:42 nbsp Since when do you need a permit for a slingshot? Users/GeorgeLewis 20051103 22:52:39 nbsp You should all read the http://www.city.davis.ca.us/cmo/citycode/detail.cfm?p26&q1046 Municipal code 26.02.060 before commenting any more, it is very clear about saying that you can not fire any guns, air guns, slingshots or metal tipped arrows without a permit stating when, where, and how many shots. Remember the cops dont usually care that much, but it should be known that there is a law against it in case they are having a bad day. Users/DanielGonzales 20051103 22:58:30 nbsp Im pretty sure Airsoft ! Airgun. http://en.wikipedia.org/wiki/Air_gun Air Gun @ Wikipedia. Like I said, those all shoot metal pellets or bbs. And are quite a bit stronger. Users/Edwins ES 20051117 17:14:43 nbsp !!! Does anyone have any information on upgrading guns? like which guns can be upgraded, specifically the spring???? Users/TaylorClark 20051129 18:40:22 nbsp Im interested in finding some new place to play, possibly not where the cops are going to bug us, so if anybody has ideas, please contribute. This is a pressing matter within the airsoft community right now. Users/JohnDudek 20051129 20:20:36 nbsp Field/Park near the Airport. Should be two tables under trees far across from each other. Small gravelly parking lot. Users/Edwins ES 20051205 16:13:33 nbsp apparently Rhys mom talked to a cop and playing airsoft is legal. I told him to get me more details. Users/TaylorClark 20051208 21:48:15 nbsp Who cares if its legal, we should play no matter what Users/SeanReedy 20051208 21:50:46 nbsp Sean, I dont think you realize that thats a bad idea. If its illegal (as in well get taken in) then well stop unless we can play somewhere legal or private. Users/JohnDudek 20060118 14:16:23 nbsp I was looking at the guns at Big 5, and if you read the warning labels, airsoft guns do not have a airgun label, but the gas pistols have a label on the actual gun that says something along the lines of This is an airgun. I think that should clarify that springloaded airsoft guns are NOT air guns. Legal? I say yes! Users/JohnDudek 20060203 18:55:16 nbsp Hey I asked the cops and they said that it is technically illegal, the municipal code prohibiting airguns, firearms, bows, etc. has never been applied to airsoft guns and as long as we use them in a safe and prudent careful manner the cops probably wont bother us. Users/AdamPoe 20060220 23:01:10 nbsp The question is, what counts as an airsoft gun and what falls under that municipal code? I know springloaded guns shouldnt count, but what about gas blowback and electric blowback? Also, Im wondering if theres a feetpersecond (FPS) limit on what guns are allowed, indicating how fast our guns can shoot, and therefore, how powerful they are. Users/AlexanderHo 20060220 23:50:02 nbsp Im assuming its the type of pellet. Any actual air gun shoots metal bbs and pellets. Airsoft guns arent really airguns. They shoot plastic bbs, even if it is gas or electric with blowback. (edit: You do need to be 18 to buy them, in any state). Im sure the force and velocities of shot matter a whole lot too. I think a lot of that is on their wikipedia page. Users/Edwins ES 20060310 23:41:47 nbsp Hey.. im an exresident of Davis in college in san diego.. was coming back up for spring break 0.o wondering if i could find a game somewhere? nightime is cool (haha.. ive played at the arboretum.. its nuts at night ^^) Users/FonChen 20060317 02:50:42 nbsp I asked a couple of cops when I was at University Mall one night, and they said that as long as you play away from bystanders so they dont think youre holding real guns, youre pretty much good. Users/AlexanderHo 20060320 19:30:36 nbsp Hey Fon, we play every Friday night, so just let me know which Friday youre here. Drop a line on my email, the links on my page. Users/JohnDudek 20060819 09:31:12 nbsp Im moving to the city, and I thought Id see if anyone here wanted my airsoft stuff, I never used it much anyway. See http://sacramento.craigslist.org/spo/196180475.html here for details. Users/DavidReid 20061031 21:55:04 nbsp For Halloween 2006, I called the Davis PD to ask them what the rules are concerning AEG and gas blowback airsoft guns in public. The answer was that the gun must have an orange tip, cannot be discharged in the city limits, and cannot be pointed at anyone at any time. They added that anyone can report you, but that the receptionist who answered my call would also answer theirs and could explain the situation to them. So happy airsofting! Users/LiRic 20070610 01:48:41 nbsp So the only thing that strikes me is the environmental issue of Airsoft. How easy/do you recover the plastic BBs? Especially if youre forced to play in obscure outside places so the cops wont bug you, it seems that you could easily litter a field full of plastic rather quickly. Users/AlexMandel Answer: Dont use plastic BBs. There are cornstarch BBs that are just as good and theyre biodegradable. Unfortunately, you have to buy them online as you cant buy them in Davis. 20080620 02:16:41 nbsp where can i join a team and just have weekend skrimmages? Users/mikokuriko 20081211 23:21:36 nbsp are the fields up by Mace within the city limits? if not, seems like a good place to play. Users/BrendanChan Good place to play? The public shouldnt be able to see you where you play. Remember, airsoft guns look like the real deal, especially from a distance. Youd still freak people out and bring a law enforcement response upon yourself. Not to mention, the fields are probably private property. wl Insofar as people seeing us goes, I figured it would be less likely out there than in the middle of downtown. Good point about the property issues though. Users/BrendanChan 20090203 21:51:20 nbsp Any one still plinking around? Users/brunester 20090302 19:21:32 nbsp ian did you delete your team? Users/ddaavviiddkk
-------------------------------------------------------------------------------- -- This file contains functions to turn the tree of parse results into the agda -- data structures they represent. -------------------------------------------------------------------------------- {-# OPTIONS --type-in-type #-} module Parse.TreeConvert where import Data.Sum open import Class.Map open import Class.Monad.Except open import Data.SimpleMap open import Data.String using (fromList; toList; fromChar; uncons) open import Data.Tree open import Data.Tree.Instance open import Data.Word using (fromℕ) open import Prelude open import Prelude.Strings open import CoreTheory open import Bootstrap.InitEnv open import Parse.MultiChar open import Parse.LL1 open import Parse.Generate open import Parse.Escape continueIfInit : ∀ {a} {A : Set a} → List Char → List Char → (List Char → A) → Maybe A continueIfInit {A = A} init s = helper init s where helper : List Char → List Char → (List Char → A) → Maybe A helper [] s f = just $ f s helper (x₁ ∷ init) [] f = nothing helper (x₁ ∷ init) (x ∷ s) f with x ≟ x₁ ... | yes p = helper init s f ... | no ¬p = nothing ruleId : List Char → List Char → Maybe (ℕ ⊎ Char) ruleId nonterm rule = do rules ← lookup nonterm parseRuleMap i ← findIndexList (_≟ (nonterm + "$" + rule)) rules return $ inj₁ i _≡ᴹ_ : ℕ ⊎ Char → Maybe (ℕ ⊎ Char) → Bool x ≡ᴹ y = just x ≣ y toSort : Tree (ℕ ⊎ Char) → Maybe Sort toSort (Node x x₁) = if x ≡ᴹ ruleId "sort" "*" then return ⋆ else if x ≡ᴹ ruleId "sort" "□" then return □ else nothing toConst : Tree (ℕ ⊎ Char) → Maybe Const toConst (Node x x₁) = if x ≡ᴹ ruleId "const" "Char" then return CharT else nothing toChar : Tree (ℕ ⊎ Char) → Maybe Char toChar (Node (inj₁ x) x₁) = nothing toChar (Node (inj₂ y) x₁) = just y toChar' : Tree (ℕ ⊎ Char) → Maybe Char toChar' (Node x x₁) = if x ≡ᴹ ruleId "char" "!!" then (case x₁ of λ { (y ∷ []) → toChar y ; _ → nothing }) else nothing toName : Tree (ℕ ⊎ Char) → Maybe String toName (Node x x₁) = case x₁ of λ { (y ∷ y' ∷ _) → do c ← toChar y n ← toName y' return (fromChar c + n) ; [] → if x ≡ᴹ ruleId "string'" "" then return "" else nothing ; _ → nothing } toNameList : Tree (ℕ ⊎ Char) → Maybe (List String) toNameList (Node x []) = just [] toNameList (Node x (x₁ ∷ x₂ ∷ _)) = do n ← toName x₁ rest ← toNameList x₂ return $ n ∷ rest {-# CATCHALL #-} toNameList _ = nothing toIndex : Tree (ℕ ⊎ Char) → Maybe ℕ toIndex t = do res ← helper t foldl {A = Maybe ℕ} (λ x c → (λ x' → 10 * x' + c) <$> x) (just 0) res where helper' : Tree (ℕ ⊎ Char) → Maybe (List ℕ) helper' (Node x []) = if x ≡ᴹ ruleId "index'" "" then return [] else nothing helper' (Node x (x₁ ∷ _)) = do rest ← helper' x₁ decCase (just x) of (ruleId "index'" "0_index'_" , return (0 ∷ rest)) ∷ (ruleId "index'" "1_index'_" , return (1 ∷ rest)) ∷ (ruleId "index'" "2_index'_" , return (2 ∷ rest)) ∷ (ruleId "index'" "3_index'_" , return (3 ∷ rest)) ∷ (ruleId "index'" "4_index'_" , return (4 ∷ rest)) ∷ (ruleId "index'" "5_index'_" , return (5 ∷ rest)) ∷ (ruleId "index'" "6_index'_" , return (6 ∷ rest)) ∷ (ruleId "index'" "7_index'_" , return (7 ∷ rest)) ∷ (ruleId "index'" "8_index'_" , return (8 ∷ rest)) ∷ (ruleId "index'" "9_index'_" , return (9 ∷ rest)) ∷ [] default nothing helper : Tree (ℕ ⊎ Char) → Maybe (List ℕ) helper (Node x []) = nothing helper (Node x (x₁ ∷ _)) = do rest ← helper' x₁ decCase just x of (ruleId "index" "0_index'_" , return (0 ∷ rest)) ∷ (ruleId "index" "1_index'_" , return (1 ∷ rest)) ∷ (ruleId "index" "2_index'_" , return (2 ∷ rest)) ∷ (ruleId "index" "3_index'_" , return (3 ∷ rest)) ∷ (ruleId "index" "4_index'_" , return (4 ∷ rest)) ∷ (ruleId "index" "5_index'_" , return (5 ∷ rest)) ∷ (ruleId "index" "6_index'_" , return (6 ∷ rest)) ∷ (ruleId "index" "7_index'_" , return (7 ∷ rest)) ∷ (ruleId "index" "8_index'_" , return (8 ∷ rest)) ∷ (ruleId "index" "9_index'_" , return (9 ∷ rest)) ∷ [] default nothing toTerm : Tree (ℕ ⊎ Char) → Maybe AnnTerm toTerm = helper [] where helper : List String → Tree (ℕ ⊎ Char) → Maybe AnnTerm helper accu (Node x x₁) = decCase just x of (ruleId "term" "_var_" , (case x₁ of λ { ((Node y (n ∷ [])) ∷ []) → decCase just y of (ruleId "var" "_string_" , do n' ← toName n return $ case findIndexList (n' ≟_) accu of λ { (just x) → BoundVar $ fromℕ x ; nothing → FreeVar n' }) ∷ (ruleId "var" "_index_" , do n' ← toIndex n return $ BoundVar $ fromℕ n') ∷ [] default nothing ; _ → nothing })) ∷ (ruleId "term" "_sort_" , do s ← head x₁ >>= toSort return $ Sort-A s) ∷ (ruleId "term" "π^space^_term_" , (case x₁ of λ { (y ∷ []) → do y' ← helper accu y return $ Pr1-A y' ; _ → nothing })) ∷ (ruleId "term" "ψ^space^_term_" , (case x₁ of λ { (y ∷ []) → do y' ← helper accu y return $ Pr2-A y' ; _ → nothing })) ∷ (ruleId "term" "β^space^_term_^space^_term_" , (case x₁ of λ { (y ∷ y' ∷ []) → do t ← helper accu y t' ← helper accu y' return $ Beta-A t t' ; _ → nothing })) ∷ (ruleId "term" "δ^space^_term_^space^_term_" , (case x₁ of λ { (y ∷ y' ∷ []) → do t ← helper accu y t' ← helper accu y' return $ Delta-A t t' ; _ → nothing })) ∷ (ruleId "term" "σ^space^_term_" , (case x₁ of λ { (y ∷ []) → helper accu y >>= λ y' → return (Sigma-A y') ; _ → nothing })) ∷ (ruleId "term" "[^space'^_term_^space^_term_^space'^]" , (case x₁ of λ { (y ∷ y' ∷ []) → do t ← helper accu y t' ← helper accu y' return $ App-A t t' ; _ → nothing })) ∷ (ruleId "term" "<^space'^_term_^space^_term_^space'^>" , (case x₁ of λ { (y ∷ y' ∷ []) → do t ← helper accu y t' ← helper accu y' return $ AppE-A t t' ; _ → nothing })) ∷ (ruleId "term" "ρ^space^_term_^space^_string_^space'^.^space'^_term_^space^_term_" , (case x₁ of λ { (y ∷ n' ∷ y' ∷ y'' ∷ []) → do t ← helper accu y n ← toName n' t' ← helper (n ∷ accu) y' t'' ← helper accu y'' return $ Rho-A t t' t'' ; _ → nothing })) ∷ (ruleId "term" "∀^space^_string_^space'^:^space'^_term_^space^_term_" , (case x₁ of λ { (n' ∷ y ∷ y' ∷ []) → do n ← toName n' t ← helper accu y t' ← helper (n ∷ accu) y' return $ All-A n t t' ; _ → nothing })) ∷ (ruleId "term" "Π^space^_string_^space'^:^space'^_term_^space^_term_" , (case x₁ of λ { (n' ∷ y ∷ y' ∷ []) → do n ← toName n' t ← helper accu y t' ← helper (n ∷ accu) y' return $ Pi-A n t t' ; _ → nothing })) ∷ (ruleId "term" "ι^space^_string_^space'^:^space'^_term_^space^_term_" , (case x₁ of λ { (n' ∷ y ∷ y' ∷ []) → do n ← toName n' t ← helper accu y t' ← helper (n ∷ accu) y' return $ Iota-A n t t' ; _ → nothing })) ∷ (ruleId "term" "λ^space^_string_^space'^:^space'^_term_^space^_term_" , (case x₁ of λ { (n' ∷ y ∷ y' ∷ []) → do n ← toName n' t ← helper accu y t' ← helper (n ∷ accu) y' return $ Lam-A n t t' ; _ → nothing })) ∷ (ruleId "term" "Λ^space^_string_^space'^:^space'^_term_^space^_term_" , (case x₁ of λ { (n' ∷ y ∷ y' ∷ []) → do n ← toName n' t ← helper accu y t' ← helper (n ∷ accu) y' return $ LamE-A n t t' ; _ → nothing })) ∷ (ruleId "term" "{^space'^_term_^space'^,^space'^_term_^space^_string_^space'^.^space'^_term_^space'^}" , (case x₁ of λ { (y ∷ y' ∷ n' ∷ y'' ∷ []) → do t ← helper accu y t' ← helper accu y' n ← toName n' t'' ← helper (n ∷ accu) y'' return $ Pair-A t t' t'' ; _ → nothing })) ∷ (ruleId "term" "φ^space^_term_^space^_term_^space^_term_" , (case x₁ of λ { (y ∷ y' ∷ y'' ∷ []) → do t ← helper accu y t' ← helper accu y' t'' ← helper accu y'' return $ Phi-A t t' t'' ; _ → nothing })) ∷ (ruleId "term" "=^space^_term_^space^_term_" , (case x₁ of λ { (y ∷ y' ∷ []) → do t ← helper accu y t' ← helper accu y' return $ Eq-A t t' ; _ → nothing })) ∷ (ruleId "term" "ω^space^_term_" , (case x₁ of λ { (y ∷ []) → do t ← helper accu y return $ M-A t ; _ → nothing })) ∷ (ruleId "term" "μ^space^_term_^space^_term_" , (case x₁ of λ { (y ∷ y' ∷ []) → do t ← helper accu y t' ← helper accu y' return $ Mu-A t t' ; _ → nothing })) ∷ (ruleId "term" "ε^space^_term_" , (case x₁ of λ { (y ∷ []) → do t ← helper accu y return $ Epsilon-A t ; _ → nothing })) ∷ (ruleId "term" "ζEvalStmt^space^_term_" , (case x₁ of λ { (z ∷ []) → do t ← helper accu z return $ Ev-A EvalStmt t ; _ → nothing })) ∷ (ruleId "term" "ζShellCmd^space^_term_^space^_term_" , (case x₁ of λ { (z ∷ z' ∷ []) → do t ← helper accu z t' ← helper accu z' return $ Ev-A ShellCmd (t , t') ; _ → nothing })) ∷ (ruleId "term" "ζCheckTerm^space^_term_^space^_term_" , (case x₁ of λ { (z ∷ z' ∷ []) → do t ← helper accu z t' ← helper accu z' return $ Ev-A CheckTerm (t , t') ; _ → nothing })) ∷ (ruleId "term" "ζParse^space^_term_^space^_term_^space^_term_" , (case x₁ of λ { (z ∷ z' ∷ z'' ∷ []) → do t ← helper accu z t' ← helper accu z' t'' ← helper accu z'' return $ Ev-A Parse (t , t' , t'') ; _ → nothing })) ∷ (ruleId "term" "ζCatchErr^space^_term_^space^_term_" , (case x₁ of λ { (z ∷ z' ∷ []) → do t ← helper accu z t' ← helper accu z' return $ Gamma-A t t' ; _ → nothing })) ∷ (ruleId "term" "ζNormalize^space^_term_" , (case x₁ of λ { (z ∷ []) → do t ← helper accu z return $ Ev-A Normalize t ; _ → nothing })) ∷ (ruleId "term" "ζHeadNormalize^space^_term_" , (case x₁ of λ { (z ∷ []) → do t ← helper accu z return $ Ev-A HeadNormalize t ; _ → nothing })) ∷ (ruleId "term" "ζInferType^space^_term_" , (case x₁ of λ { (z ∷ []) → do t ← helper accu z return $ Ev-A InferType t ; _ → nothing })) ∷ (ruleId "term" "Κ_const_" , (case x₁ of λ { (z ∷ []) → do c ← toConst z return $ Const-A c ; _ → nothing })) ∷ (ruleId "term" "κ_char_" , (case x₁ of λ { (z ∷ []) → do c ← toChar z <∣> toChar' z return $ Char-A c ; _ → nothing })) ∷ (ruleId "term" "γ^space^_term_^space^_term_" , (case x₁ of λ { (z ∷ z' ∷ []) → do t ← helper accu z t' ← helper accu z' return $ CharEq-A t t' ; _ → nothing })) ∷ [] default nothing data Stmt : Set where Let : GlobalName → AnnTerm → Maybe AnnTerm → Stmt Ass : GlobalName → AnnTerm → Stmt SetEval : AnnTerm → String → String → Stmt Import : String → Stmt Empty : Stmt instance Stmt-Show : Show Stmt Stmt-Show = record { show = helper } where helper : Stmt → String helper (Let x x₁ (just x₂)) = "let " + x + " := " + show x₁ + " : " + show x₂ helper (Let x x₁ nothing) = "let " + x + " := " + show x₁ helper (Ass x x₁) = "ass " + x + " : " + show x₁ helper (SetEval x n n') = "seteval " + show x + " " + n + " " + n' helper (Import s) = "import " + s helper Empty = "Empty" toStmt : Tree (ℕ ⊎ Char) → Maybe Stmt toStmt (Node x ((Node x' x₂) ∷ [])) = if x ≡ᴹ ruleId "stmt" "^space'^_stmt'_" then decCase just x' of (ruleId "stmt'" "let^space^_string_^space'^:=^space'^_term_^space'^_lettail_" , (case x₂ of λ { (y ∷ y' ∷ y'' ∷ []) → do n ← toName y t ← toTerm y' return $ Let n t $ toLetTail y'' ; _ → nothing })) ∷ (ruleId "stmt'" "ass^space^_string_^space'^:^space'^_term_^space'^." , (case x₂ of λ { (y ∷ y₁ ∷ []) → do n ← toName y t ← toTerm y₁ return $ Ass n t ; _ → nothing })) ∷ (ruleId "stmt'" "seteval^space^_term_^space^_string_^space^_string_^space'^." , (case x₂ of λ { (y ∷ y' ∷ y'' ∷ []) → do t ← toTerm y n ← toName y' n' ← toName y'' return $ SetEval t n n' ; _ → nothing })) ∷ (ruleId "stmt'" "import^space^_string_^space'^." , (case x₂ of λ { (y ∷ []) → do n ← toName y return $ Import n ; _ → nothing })) ∷ (ruleId "stmt'" "" , return Empty) ∷ [] default nothing else nothing where toLetTail : Tree (ℕ ⊎ Char) → Maybe AnnTerm toLetTail (Node x x₁) = decCase just x of (ruleId "lettail" ":^space'^_term_^space'^." , (case x₁ of λ { (y ∷ []) → toTerm y ; _ → nothing })) ∷ [] default nothing {-# CATCHALL #-} toStmt _ = nothing private -- Folds a tree of constructors back into a term by properly applying the -- constructors and prefixing the namespace {-# TERMINATING #-} foldConstrTree : String → Tree (String ⊎ Char) → AnnTerm foldConstrTree namespace (Node x x₁) = foldl (λ t t' → t ⟪$⟫ t') (ruleToTerm x) (foldConstrTree namespace <$> x₁) where ruleToTerm : String ⊎ Char → AnnTerm ruleToTerm (inj₁ x) = FreeVar (namespace + "$" + ruleToConstr x) ruleToTerm (inj₂ y) = Char-A y convertIfChar : Tree (String ⊎ Char) → Maybe (Tree (ℕ ⊎ Char)) convertIfChar (Node (inj₁ x) x₁) = do rest ← stripPrefix "nameInitChar$" x <∣> stripPrefix "nameTailChar$" x (c , s) ← uncons rest just $ Node (inj₂ $ unescape c s) [] convertIfChar (Node (inj₂ x) x₁) = nothing module _ {M} {{_ : Monad M}} {{_ : MonadExcept M String}} where preCoreGrammar : M Grammar preCoreGrammar = generateCFGNonEscaped "stmt" (map fromList coreGrammarGenerator) private parseToConstrTree : (G : Grammar) → NonTerminal G → String → M (Tree (String ⊎ Char) × String) parseToConstrTree (_ , G , (showRule , showNT)) S s = do (t , rest) ← parseWithInitNT showNT matchMulti show G M S s return (_<$>_ {{Tree-Functor}} (Data.Sum.map₁ showRule) t , rest) parsePreCoreGrammar : String → M (Tree (String ⊎ Char) × String) parsePreCoreGrammar s = do G ← preCoreGrammar parseToConstrTree G (initNT G) s {-# TERMINATING #-} -- cannot just use sequence here because of the char special case synTreeToℕTree : Tree (String ⊎ Char) → M (Tree (ℕ ⊎ Char)) synTreeToℕTree t@(Node (inj₁ x) x₁) with convertIfChar t ... | (just t') = return t' ... | nothing = do id ← fullRuleId x ids ← sequence $ map synTreeToℕTree x₁ return (Node id ids) where fullRuleId : String → M (ℕ ⊎ Char) fullRuleId l with break (_≟ '$') (toList l) -- split at '$' ... | (x , []) = throwError "No '$' character found!" ... | (x , _ ∷ y) = maybeToError (ruleId x y) ("Rule " + l + "doesn't exist!") synTreeToℕTree (Node (inj₂ x) x₁) = return $ Node (inj₂ x) [] -- Parse the next top-level non-terminal symbol from a string, and return a -- term representing the result of the parse, as well as the unparsed rest of -- the string parse : (G : Grammar) → NonTerminal G → String → String → M (AnnTerm × String) parse G S namespace s = do (t , rest) ← parseToConstrTree G S s return (foldConstrTree namespace t , rest) -- Used for bootstrapping parseStmt : String → M (Stmt × String) parseStmt s = do (y' , rest) ← parsePreCoreGrammar s y ← synTreeToℕTree y' case toStmt y of λ where (just x) → return (x , rest) nothing → throwError ("Error while converting syntax tree to statement!\nTree:\n" + show y + "\nRemaining: " + s)
!====================================================================================================================== !> @file rbgs_poisson_matrix.f90 !> @brief This file contains a module for red-black Gauss-Seidel method with heptadiagonal poisson matrix !> @details This file contains a module for red-black Gauss-Seidel (RBGS) solver with convergence criteria and !> RBGS iterator with iteration number !> @author !> - Ji-Hoon Kang ([email protected]), Korea Institute of Science and Technology Information !> !> @date May 2021 !> @version 1.0 !> @par Copyright !> Copyright (c) 2021 Ji-Hoon Kang, Korea Institute of Science and Technology Information, !> All rights reserved. !> @par License !> This project is release under the terms of the MIT License (see LICENSE in ) !====================================================================================================================== !> !> @brief Module for for red-black Gauss-Seidel method with heptadiagonal poisson matrix !> @details Red-black Gauss-Seidel (RBGS) solver with convergence criteria and RBGS iterator with iteration number !> module rbgs_poisson_matrix use mpi use poisson_matrix_operator implicit none private public :: rbgs_solver_poisson_matrix public :: rbgs_iterator_poisson_matrix contains !> !> @brief Red-black Gauss-Seidel solver with convergence criteria !> @param sol Result solution having a shape of 3D matrix !> @param a_poisson Heptadiagonal poisson matrix !> @param rhs RHS vector having a shape of 3D matrix !> @param dm Subdomain !> @param maxiteration Maximum number of iterations !> @param tolerance Convergence criteria !> @param omega Relexation factor !> @param is_aggregated Boolean whether domain is aggregated (.true.) or not (.false.) !> subroutine rbgs_solver_poisson_matrix(sol, a_poisson, rhs, dm, maxiteration, tolerance, omega, is_aggregated) use matrix, only : matrix_heptadiagonal use geometry, only : subdomain, geometry_halocell_update_selectively use mpi_topology, only : myrank, comm_1d_x, comm_1d_y, comm_1d_z implicit none real(kind=8), intent(inout) :: sol(0:,0:,0:) type(matrix_heptadiagonal), intent(in) :: a_poisson real(kind=8), intent(in) :: rhs(0:,0:,0:) type(subdomain), intent(in) :: dm integer(kind=4), intent(in) :: maxiteration real(kind=8), intent(in) :: tolerance real(kind=8), intent(in) :: omega logical, intent(in) :: is_aggregated(0:2) ! Local temporary variables integer(kind=4) :: i, j, k, iter, ista, offset, is_same(0:2) real(kind=8) :: rsd0tol=0.0d0, temp, rsd_norm = 0.0d0 real(kind=8), allocatable :: rsd(:,:,:) allocate( rsd(0:dm%nx+1, 0:dm%ny+1, 0:dm%nz+1) ) rsd(:,:,:) = 0.0d0 call mv_mul_poisson_matrix(rsd, a_poisson, sol, dm, is_aggregated) !$omp parallel do shared(rsd,rhs) do k = 1, dm%nz do j = 1, dm%ny do i = 1, dm%nx rsd(i,j,k) = rhs(i,j,k) - rsd(i,j,k) enddo enddo enddo call vv_dot_3d_matrix(rsd0tol, rsd, rsd, dm%nx, dm%ny, dm%nz, is_aggregated) rsd_norm = rsd0tol ! Starting offset calculation : Offset is zero if domain is aggregated if(is_aggregated(0) .eq. .true.) then is_same(0) = 0 else is_same(0) = 1 endif if(is_aggregated(1) .eq. .true.) then is_same(1) = 0 else is_same(1) = 1 endif if(is_aggregated(2) .eq. .true.) then is_same(2) = 0 else is_same(2) = 1 endif offset = mod(mod(dm%nx,2)*mod(comm_1d_x%myrank*is_same(0),2) & +mod(dm%ny,2)*mod(comm_1d_y%myrank*is_same(1),2) & +mod(dm%nz,2)*mod(comm_1d_z%myrank*is_same(2),2),2 ) ! Main solver do iter=0, maxiteration-1 #ifdef MESSAGE_DETAIL if ((mod(iter,20).EQ.0).AND.(myrank.eq.0)) then print 101, sqrt(rsd_norm), sqrt(rsd_norm/rsd0tol), sqrt(rsd0tol), iter 101 format(' [RBGS solver] mse: ',e14.6,x,', r_mse: ',e14.6,x,', rsd0: ',e14.6,' at ',i5,' iterations.') endif #endif ! Update ghostcell in the direction without aggregation call geometry_halocell_update_selectively(sol, dm, is_aggregated) !$omp parallel do shared(a_poisson, sol) do k = 1, dm%nz do j = 1, dm%ny ista = 1 + mod(j+k+offset,2) do i = ista, dm%nx, 2 temp= a_poisson%coeff(1,i,j,k) * sol(i-1,j,k) & + a_poisson%coeff(2,i,j,k) * sol(i+1,j,k) & + a_poisson%coeff(3,i,j,k) * sol(i,j-1,k) & + a_poisson%coeff(4,i,j,k) * sol(i,j+1,k) & + a_poisson%coeff(5,i,j,k) * sol(i,j,k-1) & + a_poisson%coeff(6,i,j,k) * sol(i,j,k+1) sol(i,j,k) = omega * ( rhs(i,j,k) - temp ) / a_poisson%coeff(0,i,j,k) + (1.0d0-omega)*sol(i,j,k) enddo enddo enddo ! Update ghostcell in the direction without aggregation call geometry_halocell_update_selectively(sol, dm, is_aggregated) !$omp parallel do shared(a_poisson, sol) do k = 1, dm%nz do j = 1, dm%ny ista = 1 + mod(j+k+1+offset,2) do i = ista, dm%nx, 2 temp= a_poisson%coeff(1,i,j,k) * sol(i-1,j,k) & + a_poisson%coeff(2,i,j,k) * sol(i+1,j,k) & + a_poisson%coeff(3,i,j,k) * sol(i,j-1,k) & + a_poisson%coeff(4,i,j,k) * sol(i,j+1,k) & + a_poisson%coeff(5,i,j,k) * sol(i,j,k-1) & + a_poisson%coeff(6,i,j,k) * sol(i,j,k+1) sol(i,j,k) = omega * ( rhs(i,j,k) - temp ) / a_poisson%coeff(0,i,j,k) + (1.0d0-omega)*sol(i,j,k) enddo enddo enddo call mv_mul_poisson_matrix(rsd, a_poisson, sol, dm, is_aggregated) ! Residual calculation and check whether convergence criteria is satisfied. !$omp parallel do shared(rsd,rhs) do k = 1, dm%nz do j = 1, dm%ny do i = 1, dm%nx rsd(i,j,k) = rhs(i,j,k) - rsd(i,j,k) enddo enddo enddo call vv_dot_3d_matrix(rsd_norm, rsd, rsd, dm%nx, dm%ny, dm%nz, is_aggregated) if(sqrt(rsd_norm/rsd0tol).le.tolerance) then exit endif enddo if(myrank.eq.0) then print '(a,i5,a,e15.7,a,e15.7)',' [RBGS solver] Solution obtained. Iter. = ',iter,', mse = ',sqrt(rsd_norm),', r_mse = ',sqrt(rsd_norm/rsd0tol) endif deallocate(rsd) end subroutine rbgs_solver_poisson_matrix !> !> @brief Red-black Gauss-Seidel solver with convergence criteria !> @param sol Result solution having a shape of 3D matrix !> @param a_poisson Heptadiagonal poisson matrix !> @param rhs RHS vector having a shape of 3D matrix !> @param dm Subdomain !> @param maxiteration Maximum number of iterations !> @param omega Relexation factor !> @param is_aggregated Boolean whether domain is aggregated (.true.) or not (.false.) !> subroutine rbgs_iterator_poisson_matrix(sol, a_poisson, rhs, dm, maxiteration, omega, is_aggregated) use matrix, only : matrix_heptadiagonal use geometry, only : subdomain, geometry_halocell_update_selectively use mpi_topology, only : myrank, comm_1d_x, comm_1d_y, comm_1d_z implicit none real(kind=8), intent(inout) :: sol(0:,0:,0:) type(matrix_heptadiagonal), intent(in) :: a_poisson real(kind=8), intent(in) :: rhs(0:,0:,0:) type(subdomain), intent(in) :: dm integer(kind=4),intent(in) :: maxiteration real(kind=8), intent(in) :: omega logical, intent(in) :: is_aggregated(0:2) ! Local temporary variables integer(kind=4) :: i, j, k, iter, ista, offset, is_same(0:2) real(kind=8) :: temp ! Starting offset calculation : Offset is zero if domain is aggregated if(is_aggregated(0) .eq. .true.) then is_same(0) = 0 else is_same(0) = 1 endif if(is_aggregated(1) .eq. .true.) then is_same(1) = 0 else is_same(1) = 1 endif if(is_aggregated(2) .eq. .true.) then is_same(2) = 0 else is_same(2) = 1 endif offset = mod(mod(dm%nx,2)*mod(comm_1d_x%myrank*is_same(0),2) & +mod(dm%ny,2)*mod(comm_1d_y%myrank*is_same(1),2) & +mod(dm%nz,2)*mod(comm_1d_z%myrank*is_same(2),2),2 ) ! Main solver : Residual calculation and convergence check are not necessary do iter=0, maxiteration-1 call geometry_halocell_update_selectively(sol, dm, is_aggregated) !$omp parallel do shared(a_poisson, sol) do k = 1, dm%nz do j = 1, dm%ny ista = 1 + mod(j+k+offset,2) do i = ista, dm%nx, 2 temp= a_poisson%coeff(1,i,j,k) * sol(i-1,j,k) & + a_poisson%coeff(2,i,j,k) * sol(i+1,j,k) & + a_poisson%coeff(3,i,j,k) * sol(i,j-1,k) & + a_poisson%coeff(4,i,j,k) * sol(i,j+1,k) & + a_poisson%coeff(5,i,j,k) * sol(i,j,k-1) & + a_poisson%coeff(6,i,j,k) * sol(i,j,k+1) sol(i,j,k) = omega * ( rhs(i,j,k) - temp ) / a_poisson%coeff(0,i,j,k) + (1.0d0-omega)*sol(i,j,k) enddo enddo enddo call geometry_halocell_update_selectively(sol, dm, is_aggregated) !$omp parallel do shared(a_poisson, sol) do k = 1, dm%nz do j = 1, dm%ny ista = 1 + mod(j+k+1+offset,2) do i = ista, dm%nx, 2 temp= a_poisson%coeff(1,i,j,k) * sol(i-1,j,k) & + a_poisson%coeff(2,i,j,k) * sol(i+1,j,k) & + a_poisson%coeff(3,i,j,k) * sol(i,j-1,k) & + a_poisson%coeff(4,i,j,k) * sol(i,j+1,k) & + a_poisson%coeff(5,i,j,k) * sol(i,j,k-1) & + a_poisson%coeff(6,i,j,k) * sol(i,j,k+1) sol(i,j,k) = omega * ( rhs(i,j,k) - temp ) / a_poisson%coeff(0,i,j,k) + (1.0d0-omega)*sol(i,j,k) enddo enddo enddo enddo #ifdef MESSAGE_DETAIL if(myrank.eq.0) print '(a,i4)',' [RBGS iterator] Iteration completed. Iter. = ',iter #endif end subroutine rbgs_iterator_poisson_matrix end module rbgs_poisson_matrix
! ! Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. ! See https://llvm.org/LICENSE.txt for license information. ! SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception ! ! This tests stringification. The result should be: ! Match:rain ! Match:snow ! #define doCompare(NAME) if(cmp(a%NAME,b%NAME,sizeof(a%NAME))) print *, "Match:", #NAME module weather type WeatherType real rain real snow end type contains ! Dummy routine, just for syntax and macro testing purposes function cmp(a, b, sz) real :: a, b integer :: sz ! Ignored cmp = a .eq. b if (cmp .eq. .true.) then call check(.true., .true., 1) else call check(.false., .true., 1) endif end function cmp subroutine compareWeather(a,b) type (WeatherType) :: a,b doCompare(rain) doCompare(snow) end subroutine compareWeather end module weather program p use weather logical :: res(1) = .false., expect(1) = .true. type(WeatherType) :: foo = WeatherType(1.0, 2.0) type(WeatherType) :: bar = WeatherType(1.0, 2.0) call compareWeather(foo, bar) end program
(* Default settings (from HsToCoq.Coq.Preamble) *) Generalizable All Variables. Unset Implicit Arguments. Set Maximal Implicit Insertion. Unset Strict Implicit. Unset Printing Implicit Defensive. Require Coq.Program.Tactics. Require Coq.Program.Wf. (* Converted imports: *) Require Control.Arrow. Require Control.Category. Require Data.Tuple. Require GHC.Base. Require GHC.Prim. Import Control.Arrow.Notations. Import Control.Category.Notations. Import GHC.Base.Notations. (* Converted type declarations: *) Inductive WrappedMonad (m : Type -> Type) a : Type := | WrapMonad (unwrapMonad : m a) : WrappedMonad m a. Inductive WrappedArrow (a : Type -> Type -> Type) b c : Type := | WrapArrow (unwrapArrow : a b c) : WrappedArrow a b c. Arguments WrapMonad {_} {_} _. Arguments WrapArrow {_} {_} {_} _. Definition unwrapMonad {m : Type -> Type} {a} (arg_0__ : WrappedMonad m a) := let 'WrapMonad unwrapMonad := arg_0__ in unwrapMonad. Definition unwrapArrow {a : Type -> Type -> Type} {b} {c} (arg_0__ : WrappedArrow a b c) := let 'WrapArrow unwrapArrow := arg_0__ in unwrapArrow. (* Converted value declarations: *) (* Skipping all instances of class `GHC.Generics.Generic', including `Control.Applicative.Generic__WrappedMonad' *) (* Skipping all instances of class `GHC.Generics.Generic1', including `Control.Applicative.Generic1__TYPE__WrappedMonad__LiftedRep' *) Instance Unpeel_WrappedMonad {m} {a} : GHC.Prim.Unpeel (WrappedMonad m a) (m a) := GHC.Prim.Build_Unpeel _ _ unwrapMonad WrapMonad. Local Definition Monad__WrappedMonad_op_zgzg__ {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b}, WrappedMonad inst_m a -> WrappedMonad inst_m b -> WrappedMonad inst_m b := fun {a} {b} => GHC.Prim.coerce _GHC.Base.>>_. Local Definition Monad__WrappedMonad_op_zgzgze__ {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b}, WrappedMonad inst_m a -> (a -> WrappedMonad inst_m b) -> WrappedMonad inst_m b := fun {a} {b} => GHC.Prim.coerce _GHC.Base.>>=_. Local Definition Monad__WrappedMonad_return_ {inst_m} `{GHC.Base.Monad inst_m} : forall {a}, a -> WrappedMonad inst_m a := fun {a} => GHC.Prim.coerce GHC.Base.return_. Local Definition Applicative__WrappedMonad_liftA2 {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b} {c}, (a -> b -> c) -> (WrappedMonad inst_m) a -> (WrappedMonad inst_m) b -> (WrappedMonad inst_m) c := fun {a} {b} {c} => fun arg_0__ arg_1__ arg_2__ => match arg_0__, arg_1__, arg_2__ with | f, WrapMonad x, WrapMonad y => WrapMonad (GHC.Base.liftM2 f x y) end. Local Definition Applicative__WrappedMonad_op_zlztzg__ {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b}, (WrappedMonad inst_m) (a -> b) -> (WrappedMonad inst_m) a -> (WrappedMonad inst_m) b := fun {a} {b} => fun arg_0__ arg_1__ => match arg_0__, arg_1__ with | WrapMonad f, WrapMonad v => WrapMonad (GHC.Base.ap f v) end. Local Definition Functor__WrappedMonad_fmap {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b}, (a -> b) -> (WrappedMonad inst_m) a -> (WrappedMonad inst_m) b := fun {a} {b} => fun arg_0__ arg_1__ => match arg_0__, arg_1__ with | f, WrapMonad v => WrapMonad (GHC.Base.liftM f v) end. Local Definition Functor__WrappedMonad_op_zlzd__ {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b}, a -> (WrappedMonad inst_m) b -> (WrappedMonad inst_m) a := fun {a} {b} => Functor__WrappedMonad_fmap GHC.Base.∘ GHC.Base.const. Program Instance Functor__WrappedMonad {m} `{GHC.Base.Monad m} : GHC.Base.Functor (WrappedMonad m) := fun _ k__ => k__ {| GHC.Base.fmap__ := fun {a} {b} => Functor__WrappedMonad_fmap ; GHC.Base.op_zlzd____ := fun {a} {b} => Functor__WrappedMonad_op_zlzd__ |}. Local Definition Applicative__WrappedMonad_op_ztzg__ {inst_m} `{GHC.Base.Monad inst_m} : forall {a} {b}, (WrappedMonad inst_m) a -> (WrappedMonad inst_m) b -> (WrappedMonad inst_m) b := fun {a} {b} => fun a1 a2 => Applicative__WrappedMonad_op_zlztzg__ (GHC.Base.id GHC.Base.<$ a1) a2. Local Definition Applicative__WrappedMonad_pure {inst_m} `{GHC.Base.Monad inst_m} : forall {a}, a -> (WrappedMonad inst_m) a := fun {a} => WrapMonad GHC.Base.∘ GHC.Base.pure. Program Instance Applicative__WrappedMonad {m} `{GHC.Base.Monad m} : GHC.Base.Applicative (WrappedMonad m) := fun _ k__ => k__ {| GHC.Base.liftA2__ := fun {a} {b} {c} => Applicative__WrappedMonad_liftA2 ; GHC.Base.op_zlztzg____ := fun {a} {b} => Applicative__WrappedMonad_op_zlztzg__ ; GHC.Base.op_ztzg____ := fun {a} {b} => Applicative__WrappedMonad_op_ztzg__ ; GHC.Base.pure__ := fun {a} => Applicative__WrappedMonad_pure |}. Program Instance Monad__WrappedMonad {m} `{GHC.Base.Monad m} : GHC.Base.Monad (WrappedMonad m) := fun _ k__ => k__ {| GHC.Base.op_zgzg____ := fun {a} {b} => Monad__WrappedMonad_op_zgzg__ ; GHC.Base.op_zgzgze____ := fun {a} {b} => Monad__WrappedMonad_op_zgzgze__ ; GHC.Base.return___ := fun {a} => Monad__WrappedMonad_return_ |}. (* Skipping all instances of class `GHC.Generics.Generic', including `Control.Applicative.Generic__WrappedArrow' *) (* Skipping all instances of class `GHC.Generics.Generic1', including `Control.Applicative.Generic1__TYPE__WrappedArrow__LiftedRep' *) (* Skipping all instances of class `GHC.Show.Show', including `Control.Applicative.Show__ZipList' *) (* Skipping instance `Control.Applicative.Eq___ZipList' of class `GHC.Base.Eq_' *) (* Skipping instance `Control.Applicative.Ord__ZipList' of class `GHC.Base.Ord' *) (* Skipping all instances of class `GHC.Read.Read', including `Control.Applicative.Read__ZipList' *) (* Skipping instance `Control.Applicative.Functor__ZipList' of class `GHC.Base.Functor' *) (* Skipping instance `Control.Applicative.Foldable__ZipList' of class `Data.Foldable.Foldable' *) (* Skipping all instances of class `GHC.Generics.Generic', including `Control.Applicative.Generic__ZipList' *) (* Skipping all instances of class `GHC.Generics.Generic1', including `Control.Applicative.Generic1__TYPE__ZipList__LiftedRep' *) (* Skipping all instances of class `GHC.Base.Alternative', including `Control.Applicative.Alternative__WrappedMonad' *) Local Definition Functor__WrappedArrow_fmap {inst_a} {inst_b} `{Control.Arrow.Arrow inst_a} : forall {a} {b}, (a -> b) -> (WrappedArrow inst_a inst_b) a -> (WrappedArrow inst_a inst_b) b := fun {a} {b} => fun arg_0__ arg_1__ => match arg_0__, arg_1__ with | f, WrapArrow a => WrapArrow (a Control.Category.>>> Control.Arrow.arr f) end. Local Definition Functor__WrappedArrow_op_zlzd__ {inst_a} {inst_b} `{Control.Arrow.Arrow inst_a} : forall {a} {b}, a -> (WrappedArrow inst_a inst_b) b -> (WrappedArrow inst_a inst_b) a := fun {a} {b} => Functor__WrappedArrow_fmap GHC.Base.∘ GHC.Base.const. Program Instance Functor__WrappedArrow {a} {b} `{Control.Arrow.Arrow a} : GHC.Base.Functor (WrappedArrow a b) := fun _ k__ => k__ {| GHC.Base.fmap__ := fun {a} {b} => Functor__WrappedArrow_fmap ; GHC.Base.op_zlzd____ := fun {a} {b} => Functor__WrappedArrow_op_zlzd__ |}. Local Definition Applicative__WrappedArrow_liftA2 {inst_a} {inst_b} `{Control.Arrow.Arrow inst_a} : forall {a} {b} {c}, (a -> b -> c) -> (WrappedArrow inst_a inst_b) a -> (WrappedArrow inst_a inst_b) b -> (WrappedArrow inst_a inst_b) c := fun {a} {b} {c} => fun arg_0__ arg_1__ arg_2__ => match arg_0__, arg_1__, arg_2__ with | f, WrapArrow u, WrapArrow v => WrapArrow ((u Control.Arrow.&&& v) Control.Category.>>> Control.Arrow.arr (Data.Tuple.uncurry f)) end. Local Definition Applicative__WrappedArrow_op_zlztzg__ {inst_a} {inst_b} `{Control.Arrow.Arrow inst_a} : forall {a} {b}, (WrappedArrow inst_a inst_b) (a -> b) -> (WrappedArrow inst_a inst_b) a -> (WrappedArrow inst_a inst_b) b := fun {a} {b} => Applicative__WrappedArrow_liftA2 GHC.Base.id. Local Definition Applicative__WrappedArrow_op_ztzg__ {inst_a} {inst_b} `{Control.Arrow.Arrow inst_a} : forall {a} {b}, (WrappedArrow inst_a inst_b) a -> (WrappedArrow inst_a inst_b) b -> (WrappedArrow inst_a inst_b) b := fun {a} {b} => fun a1 a2 => Applicative__WrappedArrow_op_zlztzg__ (GHC.Base.id GHC.Base.<$ a1) a2. Local Definition Applicative__WrappedArrow_pure {inst_a} {inst_b} `{Control.Arrow.Arrow inst_a} : forall {a}, a -> (WrappedArrow inst_a inst_b) a := fun {a} => fun x => WrapArrow (Control.Arrow.arr (GHC.Base.const x)). Program Instance Applicative__WrappedArrow {a} {b} `{Control.Arrow.Arrow a} : GHC.Base.Applicative (WrappedArrow a b) := fun _ k__ => k__ {| GHC.Base.liftA2__ := fun {a} {b} {c} => Applicative__WrappedArrow_liftA2 ; GHC.Base.op_zlztzg____ := fun {a} {b} => Applicative__WrappedArrow_op_zlztzg__ ; GHC.Base.op_ztzg____ := fun {a} {b} => Applicative__WrappedArrow_op_ztzg__ ; GHC.Base.pure__ := fun {a} => Applicative__WrappedArrow_pure |}. (* Skipping all instances of class `GHC.Base.Alternative', including `Control.Applicative.Alternative__WrappedArrow' *) (* Skipping instance `Control.Applicative.Applicative__ZipList' of class `GHC.Base.Applicative' *) (* Skipping all instances of class `GHC.Base.Alternative', including `Control.Applicative.Alternative__ZipList' *) (* Skipping definition `Control.Applicative.optional' *) Instance Unpeel_WrappedArrow {a} {b} {c} : GHC.Prim.Unpeel (WrappedArrow a b c) (a b c) := GHC.Prim.Build_Unpeel _ _ unwrapArrow WrapArrow. (* External variables: Type Control.Arrow.Arrow Control.Arrow.arr Control.Arrow.op_zazaza__ Control.Category.op_zgzgzg__ Data.Tuple.uncurry GHC.Base.Applicative GHC.Base.Functor GHC.Base.Monad GHC.Base.ap GHC.Base.const GHC.Base.fmap__ GHC.Base.id GHC.Base.liftA2__ GHC.Base.liftM GHC.Base.liftM2 GHC.Base.op_z2218U__ GHC.Base.op_zgzg__ GHC.Base.op_zgzg____ GHC.Base.op_zgzgze__ GHC.Base.op_zgzgze____ GHC.Base.op_zlzd__ GHC.Base.op_zlzd____ GHC.Base.op_zlztzg____ GHC.Base.op_ztzg____ GHC.Base.pure GHC.Base.pure__ GHC.Base.return_ GHC.Base.return___ GHC.Prim.Build_Unpeel GHC.Prim.Unpeel GHC.Prim.coerce *)
lemma limitin_canonical_iff [simp]: "limitin euclidean f l F \<longleftrightarrow> (f \<longlongrightarrow> l) F"
Special Guest: Cicero Holmes, host of the Spawn on Me podcast, stops by for a limited time to talk about video games that put on seasonal events. What games make good use of seasonal events? Do seasonal events favor a Christian audience? Do you suffer from FOMO? Do we all secretly want to be space truckers? Find out by listening before it’s too late and this episode is gone forever!
# coding:utf-8 # Type: Private Author: BaoChuan Wang import time import numpy as np import matplotlib.pyplot as plt from ReinforcementLearning.Modules.DataAnalysisTools.DataAnalysis import DataAnalysis # 载入数据 action = np.load("./data/action_35000to40000.npy") reward = np.load("./data/reward_35000to40000.npy") state = np.load("./data/state_35000to40000.npy") print(action.shape) print(reward.shape) print(state.shape) # 根据env的state提取state分量 target_xy_array_relate_to_car_x=state[:,0] target_xy_array_relate_to_car_y= state[:,1] car_forward_angle_diff = state[:,2] car_to_way_angle_diff = state[:,3] car_velocity_angle_diff = state[:,4] car_accel_angle_diff = state[:,5] accel = state[:,6] velocity = state[:,7] # 对各个变量随时间作图,观察值域和连续性 time_ = list(range(action.shape[0])) plt.plot(time_,car_to_way_angle_diff) # 观察速度方向和车辆方向的相关性 #plt.plot(car_velocity_angle_diff,car_forward_angle_diff,"ro") plt.show() # 观察不同action下的state的分布! #plt.close() DataAnalysis.plot_hist_on_different_ylabel(car_to_way_angle_diff,action).show()
"Downloads data csv data from the web to a local filepath a csv Writes the training and test data to separate feather files. Usage: src/download_data.r --url=<url> --out_file=<out_file> Options: --url=<url> URL from where to download the data (must be in standard csv format) --out_file=<out_file> Path (including filename) of where to locally write the file " -> doc library(tidyverse) library(tidymodels) library(ggplot2) library(docopt) library(GGally) library(rlang) opt <- docopt(doc) main <- function(url, out_file) { #Do a Try Catch For Website That Does Not Work data <- read.csv(url, header = FALSE) if (dir.exists(out_file)) { write.csv(data, out_file, row.names=FALSE) } else { dir.create(dirname(out_file), recursive = TRUE) write.csv(data, out_file, row.names=FALSE) } } main(opt[["--url"]], opt[["--out_file"]])
module Structure.Relator.Proofs where import Data.Either as Either import Data.Tuple as Tuple open import Functional open import Function.Proofs open import Logic open import Logic.Propositional.Proofs.Structures open import Logic.Propositional open import Logic.Predicate import Lvl open import Structure.Function open import Structure.Operator open import Structure.Setoid open import Structure.Relator.Properties open import Structure.Relator open import Syntax.Transitivity open import Type private variable ℓ ℓ₁ ℓ₂ ℓ₃ ℓₗ ℓₗ₁ ℓₗ₂ ℓₗ₃ ℓₗ₄ ℓₑ ℓₑ₁ ℓₑ₂ ℓₑ₃ ℓₑ₄ : Lvl.Level private variable A B A₁ A₂ B₁ B₂ : Type{ℓ} [≡]-binaryRelator : ∀ ⦃ equiv : Equiv{ℓₗ}(A) ⦄ → BinaryRelator ⦃ equiv ⦄ (_≡_) BinaryRelator.substitution [≡]-binaryRelator {x₁} {y₁} {x₂} {y₂} xy1 xy2 x1x2 = y₁ 🝖-[ xy1 ]-sym x₁ 🝖-[ x1x2 ] x₂ 🝖-[ xy2 ] y₂ 🝖-end reflexive-binaryRelator-sub : ∀ ⦃ equiv : Equiv{ℓₗ}(A) ⦄ {_▫_ : A → A → Type{ℓ}} ⦃ refl : Reflexivity(_▫_) ⦄ ⦃ rel : BinaryRelator ⦃ equiv ⦄ (_▫_) ⦄ → ((_≡_) ⊆₂ (_▫_)) _⊆₂_.proof (reflexive-binaryRelator-sub {_▫_ = _▫_}) xy = substitute₂ᵣ(_▫_) xy (reflexivity(_▫_)) module _ ⦃ equiv-A : Equiv{ℓₑ₁}(A) ⦄ ⦃ equiv-B : Equiv{ℓₑ₂}(B) ⦄ {f : A → B} ⦃ func : Function(f) ⦄ {P : B → Stmt{ℓₗ₃}} ⦃ rel : UnaryRelator(P) ⦄ where [∘]-unaryRelator : UnaryRelator(P ∘ f) [∘]-unaryRelator = [↔]-to-[←] relator-function₁ ([∘]-function ⦃ equiv-c = [↔]-equiv ⦄ ⦃ func-f = [↔]-to-[→] relator-function₁ rel ⦄) module _ ⦃ equiv-A₁ : Equiv{ℓₑ₁}(A₁) ⦄ ⦃ equiv-B₁ : Equiv{ℓₑ₂}(B₁) ⦄ ⦃ equiv-A₂ : Equiv{ℓₑ₃}(A₂) ⦄ ⦃ equiv-B₂ : Equiv{ℓₑ₄}(B₂) ⦄ {f : A₁ → A₂} ⦃ func-f : Function(f) ⦄ {g : B₁ → B₂} ⦃ func-g : Function(g) ⦄ {_▫_ : A₂ → B₂ → Stmt{ℓₗ}} ⦃ rel : BinaryRelator(_▫_) ⦄ where [∘]-binaryRelator : BinaryRelator(x ↦ y ↦ f(x) ▫ g(y)) BinaryRelator.substitution [∘]-binaryRelator xy1 xy2 = substitute₂(_▫_) (congruence₁(f) xy1) (congruence₁(g) xy2) module _ ⦃ equiv-A : Equiv{ℓₑ}(A) ⦄ {P : A → Stmt{ℓₗ₁}} ⦃ rel-P : UnaryRelator(P) ⦄ {▫ : Stmt{ℓₗ₁} → Stmt{ℓₗ₂}} ⦃ rel : Function ⦃ [↔]-equiv ⦄ ⦃ [↔]-equiv ⦄ ▫ ⦄ where unaryRelator-sub : UnaryRelator(▫ ∘ P) unaryRelator-sub = [∘]-unaryRelator ⦃ equiv-B = [↔]-equiv ⦄ ⦃ func = [↔]-to-[→] relator-function₁ rel-P ⦄ ⦃ rel = [↔]-to-[←] (relator-function₁ ⦃ [↔]-equiv ⦄) rel ⦄ module _ ⦃ equiv-A : Equiv{ℓₑ₁}(A) ⦄ ⦃ equiv-B : Equiv{ℓₑ₂}(B) ⦄ {P : A → Stmt{ℓₗ₁}} ⦃ rel-P : UnaryRelator(P) ⦄ {Q : B → Stmt{ℓₗ₂}} ⦃ rel-Q : UnaryRelator(Q) ⦄ {_▫_ : Stmt{ℓₗ₁} → Stmt{ℓₗ₂} → Stmt{ℓₗ₃}} ⦃ rel : BinaryOperator ⦃ [↔]-equiv ⦄ ⦃ [↔]-equiv ⦄ ⦃ [↔]-equiv ⦄ (_▫_) ⦄ where binaryRelator-sub : BinaryRelator(x ↦ y ↦ P(x) ▫ Q(y)) binaryRelator-sub = [∘]-binaryRelator ⦃ equiv-A₂ = [↔]-equiv ⦄ ⦃ equiv-B₂ = [↔]-equiv ⦄ ⦃ func-f = [↔]-to-[→] relator-function₁ rel-P ⦄ ⦃ func-g = [↔]-to-[→] relator-function₁ rel-Q ⦄ ⦃ rel = [↔]-to-[←] (relator-function₂ ⦃ [↔]-equiv ⦄ ⦃ [↔]-equiv ⦄) rel ⦄ module _ ⦃ equiv-A : Equiv{ℓₑ₁}(A) ⦄ ⦃ equiv-B : Equiv{ℓₑ₂}(B) ⦄ {P : A → Stmt{ℓₗ₁}} ⦃ rel-P : UnaryRelator(P) ⦄ {Q : B → Stmt{ℓₗ₂}} ⦃ rel-Q : UnaryRelator(Q) ⦄ where [→]-binaryRelator : BinaryRelator(x ↦ y ↦ (P(x) → Q(y))) [→]-binaryRelator = binaryRelator-sub{_▫_ = _→ᶠ_} [↔]-binaryRelator : BinaryRelator(x ↦ y ↦ (P(x) ↔ Q(y))) [↔]-binaryRelator = binaryRelator-sub{_▫_ = _↔_} [→]-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₃}(A) ⦄ {P : A → Stmt{ℓₗ₁}}{Q : A → Stmt{ℓₗ₂}} → ⦃ rel-P : UnaryRelator(P) ⦄ → ⦃ rel-Q : UnaryRelator(Q) ⦄ → UnaryRelator(\x → P(x) → Q(x)) UnaryRelator.substitution ([→]-unaryRelator {P = P}{Q = Q}) xy pxqx py = substitute₁(Q) xy (pxqx(substitute₁(P) (symmetry(_≡_) xy) py)) [∀]-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₃}(A) ⦄ {P : B → A → Stmt{ℓₗ₁}} → ⦃ rel-P : ∀{x} → UnaryRelator(P(x)) ⦄ → UnaryRelator(\y → ∀{x} → P(x)(y)) UnaryRelator.substitution ([∀]-unaryRelator {P = P}) {x} {a} xy px {b} = substitute₁ (P b) xy px [∃]-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₃}(A) ⦄ {P : B → A → Stmt{ℓₗ₁}} → ⦃ rel-P : ∀{x} → UnaryRelator(P(x)) ⦄ → UnaryRelator(\y → ∃(x ↦ P(x)(y))) UnaryRelator.substitution ([∃]-unaryRelator {P = P}) xy = [∃]-map-proof (substitute₁(P _) xy) instance const-unaryRelator : ∀{P : Stmt{ℓₗ₁}} → ⦃ _ : Equiv{ℓₗ}(A) ⦄ → UnaryRelator{A = A}(const P) UnaryRelator.substitution const-unaryRelator = const id [¬]-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₂}(A) ⦄ {P : A → Stmt{ℓₗ₁}} → ⦃ rel-P : UnaryRelator(P) ⦄ → UnaryRelator(\x → ¬ P(x)) [¬]-unaryRelator {P = P} = [→]-unaryRelator [∧]-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₃}(A) ⦄ {P : A → Stmt{ℓₗ₁}}{Q : A → Stmt{ℓₗ₂}} → ⦃ rel-P : UnaryRelator(P) ⦄ → ⦃ rel-Q : UnaryRelator(Q) ⦄ → UnaryRelator(x ↦ P(x) ∧ Q(x)) UnaryRelator.substitution [∧]-unaryRelator xy = Tuple.map (substitute₁(_) xy) (substitute₁(_) xy) [∨]-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₃}(A) ⦄ {P : A → Stmt{ℓₗ₁}}{Q : A → Stmt{ℓₗ₂}} → ⦃ rel-P : UnaryRelator(P) ⦄ → ⦃ rel-Q : UnaryRelator(Q) ⦄ → UnaryRelator(x ↦ P(x) ∨ Q(x)) UnaryRelator.substitution [∨]-unaryRelator xy = Either.map (substitute₁(_) xy) (substitute₁(_) xy) binary-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₂}(A) ⦄ {P : A → A → Stmt{ℓₗ₁}} → ⦃ rel-P : BinaryRelator(P) ⦄ → UnaryRelator(P $₂_) UnaryRelator.substitution (binary-unaryRelator {P = P}) xy pxx = substitute₂(P) xy xy pxx binary-unaryRelatorₗ : ∀ ⦃ _ : Equiv{ℓₗ₁}(A) ⦄ ⦃ _ : Equiv{ℓₗ₂}(B) ⦄ {_▫_ : A → B → Stmt{ℓₗ₃}} → ⦃ rel-P : BinaryRelator(_▫_) ⦄ → ∀{x} → UnaryRelator(x ▫_) UnaryRelator.substitution binary-unaryRelatorₗ xy x1x2 = substitute₂ _ (reflexivity(_≡_)) xy x1x2 binary-unaryRelatorᵣ : ∀ ⦃ _ : Equiv{ℓₗ₁}(A) ⦄ ⦃ _ : Equiv{ℓₗ₂}(B) ⦄ {_▫_ : A → B → Stmt{ℓₗ₃}} → ⦃ rel-P : BinaryRelator(_▫_) ⦄ → ∀{x} → UnaryRelator(_▫ x) UnaryRelator.substitution binary-unaryRelatorᵣ xy x1x2 = substitute₂ _ xy (reflexivity(_≡_)) x1x2 binaryRelator-from-unaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₂}(A) ⦄ {_▫_ : A → A → Stmt{ℓₗ₁}} → ⦃ relₗ : ∀{x} → UnaryRelator(_▫ x) ⦄ → ⦃ relᵣ : ∀{x} → UnaryRelator(x ▫_) ⦄ → BinaryRelator(_▫_) BinaryRelator.substitution binaryRelator-from-unaryRelator xy1 xy2 = substitute₁ _ xy1 ∘ substitute₁ _ xy2 instance const-binaryRelator : ∀{P : Stmt{ℓₗ}} → ⦃ equiv-A : Equiv{ℓₗ₁}(A) ⦄ ⦃ equiv-B : Equiv{ℓₗ₂}(B) ⦄ → BinaryRelator{A = A}{B = B}((const ∘ const) P) BinaryRelator.substitution const-binaryRelator = (const ∘ const) id -- TODO: Temporary until substitution is a specialization of congruence [¬]-binaryRelator : ∀ ⦃ _ : Equiv{ℓₗ₂}(A) ⦄ ⦃ _ : Equiv{ℓₗ₃}(B) ⦄ {P : A → B → Stmt{ℓₗ₁}} → ⦃ rel-P : BinaryRelator(P) ⦄ → BinaryRelator(\x y → ¬ P(x)(y)) BinaryRelator.substitution ([¬]-binaryRelator {P = P}) xy₁ xy₂ npx py = npx(substitute₂(P) (symmetry(_≡_) xy₁) (symmetry(_≡_) xy₂) py)
program matrix_reduce use, intrinsic :: iso_fortran_env, only : output_unit, error_unit, & dp => REAL64 use :: mpi implicit none integer, parameter :: root = 0 integer :: rank, size, istat, ierr integer :: nr_rows, nr_cols, nr_iters, iter, i, j character(len=15) :: argv real(kind=dp), allocatable, dimension(:, :) :: matrix, total_matrix real(kind=dp) :: r, total call MPI_Init(ierr) call MPI_Comm_rank(MPI_COMM_WORLD, rank, ierr) call MPI_Comm_size(MPI_COMM_WORLD, size, ierr) ! get command line arguments, and broadcast them to all if (rank == root) then nr_rows = 5 if (command_argument_count() >= 1) then call get_command_argument(1, argv) read (argv, '(I10)') nr_rows end if if (command_argument_count() >= 2) then call get_command_argument(2, argv) read (argv, '(I10)') nr_cols else nr_cols = nr_rows end if if (command_argument_count() >= 3) then call get_command_argument(3, argv) read (argv, '(I10)') nr_iters else nr_iters = 1 end if write (unit=output_unit, fmt='(3(A, I10, /))') & 'nr. rows: ', nr_rows, & 'nr. columns: ', nr_cols, & 'nr. iterations: ', nr_iters end if call MPI_Bcast(nr_rows, 1, MPI_INTEGER, root, MPI_COMM_WORLD, ierr) call MPI_Bcast(nr_cols, 1, MPI_INTEGER, root, MPI_COMM_WORLD, ierr) call MPI_Bcast(nr_iters, 1, MPI_INTEGER, root, MPI_COMM_WORLD, ierr) ! allocate matrix for each process allocate(matrix(nr_rows, nr_cols), stat=istat) if (istat /= 0) then write (unit=error_unit, fmt='(A)'), 'can not allocate matrix' call MPI_Abort(MPI_COMM_WORLD, 1, ierr) end if ! allocate and initialize matrix for the root process if (rank == root) then allocate(total_matrix(nr_rows, nr_cols), stat=istat) if (istat /= 0) then write (unit=error_unit, fmt='(A)'), 'can not allocate total_matrix' call MPI_Abort(MPI_COMM_WORLD, 1, ierr) end if end if do iter = 1, nr_iters call random_number(r) do j = 1, nr_cols do i = 1, nr_rows matrix(i, j) = 2*r + i + rank*(j - 1) + rank*size end do end do call MPI_Reduce(matrix, total_matrix, & nr_rows*nr_cols, MPI_DOUBLE_PRECISION, & MPI_SUM, root, MPI_COMM_WORLD, ierr) if (rank == root) then total = sum(total_matrix) write(unit=output_unit, fmt='(A, I5, F8.1)') & 'iteration', iter, total end if end do if (rank == root .and. nr_rows < 20 .and. nr_cols < 20) then do i = 1, nr_rows write (unit=output_unit, fmt='(*(F8.1))') total_matrix(i, :) end do end if call MPI_Finalize(ierr) end program matrix_reduce
function spelled_out_ru(number::Number) end
[GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s ⊢ Set.Nonempty (extremePoints ℝ s) [PROOFSTEP] let S : Set (Set E) := {t | t.Nonempty ∧ IsClosed t ∧ IsExtreme ℝ s t} [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} ⊢ Set.Nonempty (extremePoints ℝ s) [PROOFSTEP] rsuffices ⟨t, ⟨⟨x, hxt⟩, htclos, hst⟩, hBmin⟩ : ∃ t ∈ S, ∀ u ∈ S, u ⊆ t → u = t [GOAL] case intro.intro.intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t ⊢ Set.Nonempty (extremePoints ℝ s) [PROOFSTEP] refine' ⟨x, mem_extremePoints_iff_extreme_singleton.2 _⟩ [GOAL] case intro.intro.intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t ⊢ IsExtreme ℝ s {x} [PROOFSTEP] rwa [← eq_singleton_iff_unique_mem.2 ⟨hxt, fun y hyB => ?_⟩] [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t y : E hyB : y ∈ t ⊢ y = x [PROOFSTEP] by_contra hyx [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t y : E hyB : y ∈ t hyx : ¬y = x ⊢ False [PROOFSTEP] obtain ⟨l, hl⟩ := geometric_hahn_banach_point_point hyx [GOAL] case intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t y : E hyB : y ∈ t hyx : ¬y = x l : E →L[ℝ] ℝ hl : ↑l y < ↑l x ⊢ False [PROOFSTEP] obtain ⟨z, hzt, hz⟩ := (isCompact_of_isClosed_subset hscomp htclos hst.1).exists_forall_ge ⟨x, hxt⟩ l.continuous.continuousOn [GOAL] case intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t y : E hyB : y ∈ t hyx : ¬y = x l : E →L[ℝ] ℝ hl : ↑l y < ↑l x z : E hzt : z ∈ t hz : ∀ (y : E), y ∈ t → ↑l y ≤ ↑l z ⊢ False [PROOFSTEP] have h : IsExposed ℝ t ({z ∈ t | ∀ w ∈ t, l w ≤ l z}) := fun _ => ⟨l, rfl⟩ [GOAL] case intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t y : E hyB : y ∈ t hyx : ¬y = x l : E →L[ℝ] ℝ hl : ↑l y < ↑l x z : E hzt : z ∈ t hz : ∀ (y : E), y ∈ t → ↑l y ≤ ↑l z h : IsExposed ℝ t {z | z ∈ t ∧ ∀ (w : E), w ∈ t → ↑l w ≤ ↑l z} ⊢ False [PROOFSTEP] rw [← hBmin ({z ∈ t | ∀ w ∈ t, l w ≤ l z}) ⟨⟨z, hzt, hz⟩, h.isClosed htclos, hst.trans h.isExtreme⟩ (t.sep_subset _)] at hyB [GOAL] case intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} t : Set E hBmin : ∀ (u : Set E), u ∈ S → u ⊆ t → u = t x : E hxt : x ∈ t htclos : IsClosed t hst : IsExtreme ℝ s t y : E hyx : ¬y = x l : E →L[ℝ] ℝ hyB : y ∈ {z | z ∈ t ∧ ∀ (w : E), w ∈ t → ↑l w ≤ ↑l z} hl : ↑l y < ↑l x z : E hzt : z ∈ t hz : ∀ (y : E), y ∈ t → ↑l y ≤ ↑l z h : IsExposed ℝ t {z | z ∈ t ∧ ∀ (w : E), w ∈ t → ↑l w ≤ ↑l z} ⊢ False [PROOFSTEP] exact hl.not_le (hyB.2 x hxt) [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} ⊢ ∃ t, t ∈ S ∧ ∀ (u : Set E), u ∈ S → u ⊆ t → u = t [PROOFSTEP] refine' zorn_superset _ fun F hFS hF => _ [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F ⊢ ∃ lb, lb ∈ S ∧ ∀ (s : Set E), s ∈ F → lb ⊆ s [PROOFSTEP] obtain rfl | hFnemp := F.eq_empty_or_nonempty [GOAL] case inl E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} hFS : ∅ ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) ∅ ⊢ ∃ lb, lb ∈ S ∧ ∀ (s : Set E), s ∈ ∅ → lb ⊆ s [PROOFSTEP] exact ⟨s, ⟨hsnemp, hscomp.isClosed, IsExtreme.rfl⟩, fun _ => False.elim⟩ [GOAL] case inr E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F ⊢ ∃ lb, lb ∈ S ∧ ∀ (s : Set E), s ∈ F → lb ⊆ s [PROOFSTEP] refine' ⟨⋂₀ F, ⟨_, isClosed_sInter fun t ht => (hFS ht).2.1, isExtreme_sInter hFnemp fun t ht => (hFS ht).2.2⟩, fun t ht => sInter_subset_of_mem ht⟩ [GOAL] case inr E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F ⊢ Set.Nonempty (⋂₀ F) [PROOFSTEP] haveI : Nonempty (↥F) := hFnemp.to_subtype [GOAL] case inr E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F this : Nonempty ↑F ⊢ Set.Nonempty (⋂₀ F) [PROOFSTEP] rw [sInter_eq_iInter] [GOAL] case inr E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F this : Nonempty ↑F ⊢ Set.Nonempty (⋂ (i : ↑F), ↑i) [PROOFSTEP] refine' IsCompact.nonempty_iInter_of_directed_nonempty_compact_closed _ (fun t u => _) (fun t => (hFS t.mem).1) (fun t => isCompact_of_isClosed_subset hscomp (hFS t.mem).2.1 (hFS t.mem).2.2.1) fun t => (hFS t.mem).2.1 [GOAL] case inr E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F this : Nonempty ↑F t u : ↑F ⊢ ∃ z, (fun x x_1 => x ⊇ x_1) ↑t ↑z ∧ (fun x x_1 => x ⊇ x_1) ↑u ↑z [PROOFSTEP] obtain htu | hut := hF.total t.mem u.mem [GOAL] case inr.inl E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F this : Nonempty ↑F t u : ↑F htu : ↑t ⊆ ↑u ⊢ ∃ z, (fun x x_1 => x ⊇ x_1) ↑t ↑z ∧ (fun x x_1 => x ⊇ x_1) ↑u ↑z case inr.inr E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hsnemp : Set.Nonempty s S : Set (Set E) := {t | Set.Nonempty t ∧ IsClosed t ∧ IsExtreme ℝ s t} F : Set (Set E) hFS : F ⊆ S hF : IsChain (fun x x_1 => x ⊆ x_1) F hFnemp : Set.Nonempty F this : Nonempty ↑F t u : ↑F hut : ↑u ⊆ ↑t ⊢ ∃ z, (fun x x_1 => x ⊇ x_1) ↑t ↑z ∧ (fun x x_1 => x ⊇ x_1) ↑u ↑z [PROOFSTEP] exacts [⟨t, Subset.rfl, htu⟩, ⟨u, hut, Subset.rfl⟩] [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s ⊢ closure (↑(convexHull ℝ) (extremePoints ℝ s)) = s [PROOFSTEP] apply (closure_minimal (convexHull_min extremePoints_subset hAconv) hscomp.isClosed).antisymm [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s ⊢ s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) [PROOFSTEP] by_contra hs [GOAL] E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s hs : ¬s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) ⊢ False [PROOFSTEP] obtain ⟨x, hxA, hxt⟩ := not_subset.1 hs [GOAL] case intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s hs : ¬s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) x : E hxA : x ∈ s hxt : ¬x ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) ⊢ False [PROOFSTEP] obtain ⟨l, r, hlr, hrx⟩ := geometric_hahn_banach_closed_point (convex_convexHull _ _).closure isClosed_closure hxt [GOAL] case intro.intro.intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s hs : ¬s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) x : E hxA : x ∈ s hxt : ¬x ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) l : E →L[ℝ] ℝ r : ℝ hlr : ∀ (a : E), a ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) → ↑l a < r hrx : r < ↑l x ⊢ False [PROOFSTEP] have h : IsExposed ℝ s ({y ∈ s | ∀ z ∈ s, l z ≤ l y}) := fun _ => ⟨l, rfl⟩ [GOAL] case intro.intro.intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s hs : ¬s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) x : E hxA : x ∈ s hxt : ¬x ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) l : E →L[ℝ] ℝ r : ℝ hlr : ∀ (a : E), a ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) → ↑l a < r hrx : r < ↑l x h : IsExposed ℝ s {y | y ∈ s ∧ ∀ (z : E), z ∈ s → ↑l z ≤ ↑l y} ⊢ False [PROOFSTEP] obtain ⟨z, hzA, hz⟩ := hscomp.exists_forall_ge ⟨x, hxA⟩ l.continuous.continuousOn [GOAL] case intro.intro.intro.intro.intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s hs : ¬s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) x : E hxA : x ∈ s hxt : ¬x ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) l : E →L[ℝ] ℝ r : ℝ hlr : ∀ (a : E), a ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) → ↑l a < r hrx : r < ↑l x h : IsExposed ℝ s {y | y ∈ s ∧ ∀ (z : E), z ∈ s → ↑l z ≤ ↑l y} z : E hzA : z ∈ s hz : ∀ (y : E), y ∈ s → ↑l y ≤ ↑l z ⊢ False [PROOFSTEP] obtain ⟨y, hy⟩ := (h.isCompact hscomp).has_extreme_point ⟨z, hzA, hz⟩ [GOAL] case intro.intro.intro.intro.intro.intro.intro.intro E : Type u_1 inst✝⁶ : AddCommGroup E inst✝⁵ : Module ℝ E inst✝⁴ : TopologicalSpace E inst✝³ : T2Space E inst✝² : TopologicalAddGroup E inst✝¹ : ContinuousSMul ℝ E inst✝ : LocallyConvexSpace ℝ E s : Set E hscomp : IsCompact s hAconv : Convex ℝ s hs : ¬s ⊆ closure (↑(convexHull ℝ) (extremePoints ℝ s)) x : E hxA : x ∈ s hxt : ¬x ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) l : E →L[ℝ] ℝ r : ℝ hlr : ∀ (a : E), a ∈ closure (↑(convexHull ℝ) (extremePoints ℝ s)) → ↑l a < r hrx : r < ↑l x h : IsExposed ℝ s {y | y ∈ s ∧ ∀ (z : E), z ∈ s → ↑l z ≤ ↑l y} z : E hzA : z ∈ s hz : ∀ (y : E), y ∈ s → ↑l y ≤ ↑l z y : E hy : y ∈ extremePoints ℝ {y | y ∈ s ∧ ∀ (z : E), z ∈ s → ↑l z ≤ ↑l y} ⊢ False [PROOFSTEP] linarith [hlr _ (subset_closure <| subset_convexHull _ _ <| h.isExtreme.extremePoints_subset_extremePoints hy), hy.1.2 x hxA]
open import Agda.Builtin.Equality open import Agda.Primitive record R a : Set (lsuc a) where field P : {A : Set a} → A → A → Set a r : ∀ ℓ → R ℓ R.P (r _) = _≡_ postulate cong : ∀ {a b} {A : Set a} {B : Set b} {x y : A} (f : A → B) → R.P (r a) x y → R.P (r b) (f x) (f y) magic : ∀ {a} {A : Set a} {x y : A} (z : A) → y ≡ z → x ≡ z record Raw-monad {f : Level → Level} (M : ∀ {ℓ} → Set ℓ → Set (f ℓ)) ℓ₁ ℓ₂ : Set (f ℓ₁ ⊔ f ℓ₂ ⊔ lsuc (ℓ₁ ⊔ ℓ₂)) where infixl 5 _>>=_ field return : {A : Set ℓ₁} → A → M A _>>=_ : {A : Set ℓ₁} {B : Set ℓ₂} → M A → (A → M B) → M B module Raw-monad⁺ {f : Level → Level} {M : ∀ {ℓ} → Set ℓ → Set (f ℓ)} (m : ∀ {ℓ₁ ℓ₂} → Raw-monad M ℓ₁ ℓ₂) where private module M′ {ℓ₁ ℓ₂} = Raw-monad (m {ℓ₁ = ℓ₁} {ℓ₂ = ℓ₂}) open M′ public using (_>>=_) return : ∀ {a} {A : Set a} → A → M A return = M′.return {ℓ₂ = lzero} open Raw-monad⁺ ⦃ … ⦄ public record Monad⁻ {f : Level → Level} (M : ∀ {ℓ} → Set ℓ → Set (f ℓ)) ⦃ raw-monad : ∀ {ℓ₁ ℓ₂} → Raw-monad M ℓ₁ ℓ₂ ⦄ ℓ₁ ℓ₂ ℓ₃ : Set (f ℓ₁ ⊔ f ℓ₂ ⊔ f ℓ₃ ⊔ lsuc (ℓ₁ ⊔ ℓ₂ ⊔ ℓ₃)) where field associativity : {A : Set ℓ₁} {B : Set ℓ₂} {C : Set ℓ₃} → (x : M A) (f : A → M B) (g : B → M C) → x >>= (λ x → f x >>= g) ≡ x >>= f >>= g module Monad⁻⁺ {f : Level → Level} {M : ∀ {ℓ} → Set ℓ → Set (f ℓ)} ⦃ raw-monad : ∀ {ℓ₁ ℓ₂} → Raw-monad M ℓ₁ ℓ₂ ⦄ (m : ∀ {ℓ₁ ℓ₂ ℓ₃} → Monad⁻ M ℓ₁ ℓ₂ ℓ₃) where private module M′ {ℓ₁ ℓ₂ ℓ₃} = Monad⁻ (m {ℓ₁ = ℓ₁} {ℓ₂ = ℓ₂} {ℓ₃ = ℓ₃}) open M′ public open Monad⁻⁺ ⦃ … ⦄ public data Maybe {a} (A : Set a) : Set a where nothing : Maybe A just : A → Maybe A postulate maybe : ∀ {a b} {A : Set a} {B : Maybe A → Set b} → ((x : A) → B (just x)) → B nothing → (x : Maybe A) → B x record MaybeT {ℓ} (f : Level → Level) (M : Set ℓ → Set (f ℓ)) (A : Set ℓ) : Set (f ℓ) where constructor wrap field run : M (Maybe A) open MaybeT instance transformʳ : ∀ {ℓ₁ ℓ₂} {f : Level → Level} {M : ∀ {ℓ} → Set ℓ → Set (f ℓ)} → ⦃ raw-monad : ∀ {ℓ₁ ℓ₂} → Raw-monad M ℓ₁ ℓ₂ ⦄ → Raw-monad (MaybeT f M) ℓ₁ ℓ₂ run (Raw-monad.return transformʳ x) = return (just x) run (Raw-monad._>>=_ transformʳ x f) = run x >>= maybe (λ x → run (f x)) (return nothing) transformᵐ : {f : Level → Level} {M : ∀ {ℓ} → Set ℓ → Set (f ℓ)} ⦃ raw-monad : ∀ {ℓ₁ ℓ₂} → Raw-monad M ℓ₁ ℓ₂ ⦄ ⦃ monad : ∀ {ℓ₁ ℓ₂ ℓ₃} → Monad⁻ M ℓ₁ ℓ₂ ℓ₃ ⦄ → Monad⁻ (MaybeT f M) lzero lzero lzero Monad⁻.associativity transformᵐ x f g = cong wrap ( magic ((run x >>= maybe (λ x → run (f x)) (return nothing)) >>= maybe (λ x → run (g x)) (return nothing)) (associativity _ _ _)) -- WAS: rejected in 2.6.0 with -- No instance of type Raw-monad _M_345 ℓ₁ ℓ₂ was found in scope. -- Should succeed.
library(ggplot2) library(scales) library(ggthemes) # fig 1 set.seed(42) demog_data_camcan <- data.frame( age = c(rgamma(300, 90, 2), rgamma(320, 100, 2)), gender = c(rep("F", 300), rep("M", 320)), dataset = "cam-can" ) demog_data_tuab <- data.frame( age = c(rgamma(700, 100, 2), rgamma(639, 95, 2)), gender = c(rep("F", 700), rep("M", 639)), dataset = "tuab" ) demog_data_lemon <- data.frame( age = c(rgamma(90, 105, 2), rgamma(100, 100, 2)), gender = c(rep("F", 90), rep("M", 100)), dataset = "lemon" ) demog_data_chpb <- data.frame( age = c(rgamma(120, 95, 2), rgamma(130, 105, 2)), gender = c(rep("F", 120), rep("M", 130)), dataset = "chbp" ) demog_data <- rbind( demog_data_camcan, demog_data_tuab, demog_data_lemon, demog_data_chpb) ggplot( aes(x = age, color = gender, fill = gender), data = demog_data) + geom_density(alpha=0.4, size=1) + facet_wrap(.~dataset, ncol=2) + theme_minimal(base_size = 16) + scale_color_colorblind() + scale_fill_colorblind() + labs(x="Age [years]", y="Density") ggsave("demographic_hypothesis.png", dpi=150, height = 6, width = 8) out_grid <- expand.grid( data = c("tuab", "chbp", "lemon", "cam-can"), benchmarks = c("dummy", "hand-crafted", "cov-riemann", "cov-mne", "deep") ) expected_mae <- expand.grid( data_delta = c(0.5, -2, -1, 1), bench_mu = c(16, 10, 8.3, 7.5, 8.7) ) expected_mae_cv <- cbind(out_grid, expected_mae) CV <- 10 expected_mae_cv <- do.call( rbind, lapply( seq(nrow(expected_mae_cv)), function(ii){ this_res <- expected_mae_cv[ii,] data.frame(data=this_res$data, benchmark=this_res$benchmarks, fold=seq(CV), MAE=rgamma( CV, (this_res$bench_mu + this_res$data_delta) * 2, 2)) })) ggplot( aes(x = MAE, y = interaction(rev(benchmark), data), color = benchmark, fill = benchmark, shape = data) , data = expected_mae_cv) + geom_jitter() + geom_boxplot(alpha=0.1) + theme_minimal(base_size = 16) + scale_color_colorblind() + scale_fill_colorblind() + scale_y_discrete( labels = rep(rev(c("dummy", "hand-crafted", "cov-riemann", "cov-mne", "deep")), times = 5)) + theme(legend.position = c(.9, .5)) + labs(y = element_blank(), x = "age prediction MAE [10-fold CV]") ggsave("benchmark_hypothesis.png", dpi=150, height = 6, width = 8)
## Solution for $\mathbb{H}_{u,v}$ In this notebook we validate our recursive solution to the integral $\mathbb{H}$. ```python import sympy from sympy import * import numpy as np np.random.seed(0) ``` ```python # Initialize the session init_session(quiet=True) print("Using sympy version", sympy.__version__) # Define our symbols phi, lam1, lam2 = symbols('phi lambda_1 lambda_2') lam = Array((lam1, lam2)) ``` Using sympy version 1.4 Here's the exact version of the integral, computed with `sympy`: ```python def Hexact(u, v): return integrate(cos(phi) ** u * sin(phi) ** v, (phi, lam1, lam2)) ``` Here's our recursive version: ```python def Delta(x): return x[1] - x[0] def H(u, v): if u == v == 0: return Delta(lam) elif u == 1 and v == 0: return Delta(lam.applyfunc(sin)) elif u == 0 and v == 1: return Delta(lam.applyfunc(lambda x: -cos(x))) elif u == 1 and v == 1: return Delta(lam.applyfunc(lambda x: -cos(x) ** 2 / 2)) elif u < 2 and v >= 2: return ( Delta(lam.applyfunc(lambda x: -cos(x) ** (u + 1) * sin(x) ** (v - 1))) + (v - 1) * H(u, v - 2) ) / (u + v) else: return ( Delta(lam.applyfunc(lambda x: cos(x) ** (u - 1) * sin(x) ** (v + 1))) + (u - 1) * H(u - 2, v) ) / (u + v) ``` `sympy` has a little trouble checking for the analytical equivalence of the expressions as `u` and `v` get large, so let's check that the expressions agree numerically for several different values of $\lambda$: ```python for i in range(10): x1, x2 = np.random.random(2) * 2 * np.pi for u in range(5): for v in range(5): diff = (H(u, v) - Hexact(u, v)).replace(lam1, x1).replace(lam2, x2) assert abs(diff) < 1e-15 ```
[STATEMENT] lemma glue_in_lists_hull [intro]: "us = \<epsilon> \<or> last us \<noteq> w \<Longrightarrow> us \<in> lists G \<Longrightarrow> glue w us \<in> lists \<langle>G\<rangle>" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>us = \<epsilon> \<or> last us \<noteq> w; us \<in> lists G\<rbrakk> \<Longrightarrow> glue w us \<in> lists \<langle>G\<rangle> [PROOF STEP] by (induction rule: last_neq_induct) (simp_all add: Let_def tl_in_lists prod_cl gen_in) \<comment> \<open>Gluing from the right (gluing a letter with its predecessor)\<close>
> module Ordering.Properties > %default total > %access public export > %auto_implicits on > ||| > Uninhabited (LT = EQ) where > uninhabited Refl impossible > ||| > Uninhabited (Prelude.Interfaces.LT = GT) where > uninhabited Refl impossible > ||| > Uninhabited (EQ = GT) where > uninhabited Refl impossible > ||| > Uninhabited (EQ = LT) where > uninhabited Refl impossible > ||| > Uninhabited (Prelude.Interfaces.GT = LT) where > uninhabited Refl impossible > ||| > Uninhabited (GT = EQ) where > uninhabited Refl impossible
> module Nat.Coprime > import Nat.GCD > import Nat.GCDAlgorithm > import Unique.Predicates > import Equality.Properties > import Nat.GCDEuclid > import Pairs.Operations > import Sigma.Sigma > %default total > %access public export > ||| > data Coprime : (m : Nat) -> (n : Nat) -> Type where > MkCoprime : {m, n : Nat} -> gcdAlg m n = S Z -> Coprime m n > ||| > CoprimeUnique : {m, n : Nat} -> Unique (Coprime m n) > CoprimeUnique {m} {n} (MkCoprime p) (MkCoprime q) = cong (uniqueEq (gcdAlg m n) (S Z) p q)
% demo_e2s2_full() % % Trains and tests a Region-based semantic segmentation with end-to-end training on SIFT Flow. % Requires the version of VGG-16 pretrained with MatConvNet's beta16, and does not % work with beta20. This is most likely due to exploding gradients, although the architecture is identical. % % Copyright by Holger Caesar, 2016 % Add folders to path setup(); % Settings global glFeaturesFolder; % Define global variables to be used in all scripts labelingsFolder = fullfile(glFeaturesFolder, 'CNN-Models', 'E2S2', 'SiftFlow', 'Run1', sprintf('%s_e2s2_run1_exp2', 'SiftFlow'), 'labelings-test-epoch25'); % Download dataset downloadSiftFlow(); % Download base network downloadNetwork('version', 'beta16'); % Download Selective Search downloadSelectiveSearch(); % Extract region proposals and labels setupE2S2Regions(); % Train and test network e2s2_wrapper_SiftFlow_full(); % Show example segmentation fileList = dirSubfolders(labelingsFolder); image = imread(fullfile(labelingsFolder, fileList{1})); figure(); imshow(image);
# HW1.R # Betty Malloy # 9.11.2020 # Code I used for HW 1 problem 1. library(mosaic) library(ggplot2) lead <- read.csv("lead.csv",header=T) dim(lead) # number of observations by number of variables summary(lead$MAXFT) # note the NA's are missing values! summary(lead$iqf) # no NA's so no missing values # MAXFT favstats(MAXFT ~ factor(GROUP), data = lead) # also gives missing values histogram(~MAXFT | factor(GROUP), data = lead,col="light blue") qplot(x = factor(lead$GROUP),y = lead$MAXFT, geom = "boxplot",xlab='exposure group', ylab='MAXFT') # the warning you get reiterates there are missing values! # iqf favstats(iqf ~ factor(GROUP), data = lead) histogram(~iqf | factor(GROUP), data = lead,col="light blue") qplot(x = factor(lead$GROUP),y = lead$iqf, geom = "boxplot",xlab='exposure group', ylab='iqf')
import LMT variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)] example {a1 a2 a3 : A I E} : ((((a3).write i2 (v1)).write i3 (v1)).read i2) ≠ (v1) → False := by arr
[STATEMENT] lemma while_vrt_hoare_r [hoare_safe]: assumes "\<And> z::nat. \<lbrace>p \<and> b \<and> v =\<^sub>u \<guillemotleft>z\<guillemotright>\<rbrace>S\<lbrace>p \<and> v <\<^sub>u \<guillemotleft>z\<guillemotright>\<rbrace>\<^sub>u" "`pre \<Rightarrow> p`" "`(\<not>b \<and> p) \<Rightarrow> post`" shows "\<lbrace>pre\<rbrace>while b invr p vrt v do S od\<lbrace>post\<rbrace>\<^sub>u" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrace>pre\<rbrace> while b invr p vrt v do S od \<lbrace>post\<rbrace>\<^sub>u [PROOF STEP] apply (rule hoare_r_conseq[OF assms(2) _ assms(3)]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrace>p\<rbrace> while b invr p vrt v do S od \<lbrace>\<not> b \<and> p\<rbrace>\<^sub>u [PROOF STEP] apply (simp add: while_vrt_def) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrace>p\<rbrace> while\<^sub>\<bottom> b do S od \<lbrace>\<not> b \<and> p\<rbrace>\<^sub>u [PROOF STEP] apply (rule while_term_hoare_r[where v="v", OF assms(1)]) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
module Simpson export simpson function simpson(n) # parameters f(x) = (3/2)*sin(x)^3 a = 0 b = π # calculation h = (b-a)/n sum = f(a)+f(b) for i in 1:2:n ai = muladd(h,i,a) sum += 4f(ai) sum += 2f(ai+h) end h*sum/3 end end
C PROGRAM TO CALCULATE AN AGE SPECTRUM FROM A GIVEN THERMAL C HISTORY. (AGES.F) (SPHERES) C R= GAS CONSTANT KCAL/(MOL*K) C XLAMBD= DECAY CONSTANT OF POTASSIUM IN 1/MYRS. C NUSA=# OF SAMPLES, TOTIME = TOTAL TIME OF Ar ACCUMULATION C C40WD= TOTAL ARGON RADIOGENIC 40Ar PRODUCED POR UNIT VOL. FROM TIME=0. C C39WD= FRACTION OF 39Ar AT PRESENT. C NEND=TIME AT WHICH THE SYSTEM IS EFFECTIVELY CLOSED, TEMPERATURE C IS ASSUME CONSTANT FROM THIS TIME UNTIL PRESENT. C STEP= DURATION OF THE TIME STEP, PEND AND TEMIN DEFINE C THE DIFFERENT SEGMENTS OF THE COOLING HISTORY C NI=# OF HEATING STEPS C TELAB = TEMPERATURE STEP (*K), TILAB= DURATION OF THE HEATING STEP (MIN) C NSAMP=# OF DIFFERENT DIFFUSION DOMAIN SIZES C D0(J)= FREQUENCY FACTOR (1/SEC) C E(J)= ACTIVACTION ENERGY (KCAL/MOL) C C(J)= VOLUME FRACION C SUBROUTINE GEOSEC CALCULATE THE DISTRIBUTION OF 40Ar AT PRESENT WHICH C IS GIVEN BY THE COEFFICIENT XI(N). C SUBROUTINE LAB CALCULATE THE RELEASED OF 40Ar and 39Ar AT LAB. C FOR EACH DIFFUSION DOMAIN SIZE. (REA40 AND REA39) C CURA= CUMULATIVE RATE OF A40 T0 A39 RELEASE. C RATE= STEP RATE OF A40 T0 A39 RELEASE C DR39 AND DR40 ARE THE STEP RELEASE OF A39 AND A40 RESPECTIVELY. C========================================================================= implicit double precision (a-h,o-z) parameter(nn=340,nch=1005,ntp=100,pi=3.141592654, $xlambd=0.0005543,R= 1.987d-03,x1=1.2d0,x2=3.d0,acc=1.d-5) dimension r40(ntp),r39(ntp),dr39(ntp) dimension temp(nch),time(nch) dimension c(10),tra40(0:ntp),tra39(0:ntp),sra40(ntp) dimension sra39(ntp),scura(ntp),tilab(ntp),telab(ntp) dimension E(10),d0(10),tmin(50),tpin(50) double precision zero, bessj0, bessj1, rtsafe external zero, bessj0, bessj1, rtsafe character*9 tab1, yes*1 common /var/ an(nn),xi(nn),b,c40 common /integ/ lc(0:nn),imod tab1=char(09) open(unit=14,file='ages-me.out',status='unknown') open(unit=15,file='agesme.in',status='old') open(unit=16,file='ages-me.dat',status='unknown') open(unit=17,file='temstep.in',status='old') open(unit=19,file='each-me.out',status='unknown') open(unit=20,file='chist-me.dat',status='unknown') lc(0)=0. C CALCULATION OF THE COOLING HISTORY read(15,*)np do 2 j=1,np read(15,*)tmin(j),tpin(j) write(20,105)tmin(j),tab1,tpin(j) 2 tpin(j)=tpin(j) + 273. write(20,*)'&' dt=2 dtdt=(tpin(1)-tpin(2))/(tmin(1)-tmin(2)) call chist(np,tmin,tpin,time,temp,dt,ns,nch) c40=1.-dexp(-xlambd*tmin(1)) c39wd=dexp(-xlambd*tmin(1)) print *, 'If you want to see the CH?, type ''y''' read *,yes if (yes.eq.'y')stop print *, 'slabs= 1, spheres= 2 , cilinders= 3' read *, imod print *, 'model =', imod b = 10.d0 - 2.d0 * imod C DEFINITION OF STEP HEATING SCHEDULED AT LAB. read(17,110)ni do 12 j=1,ni read(17,*)telab(j),tilab(j) if(telab(j).gt.1373.)goto 11 12 tilab(j)=tilab(j)/5.256e11 11 ni=j-1 close(17) C DEFINITION OF DISTRIBUTION PARAMETERS read(15,110)nsamp do 14 js=1,nsamp read(15,*)e(js),d0(js),c(js) d0(js)= 10.**d0(js) 14 d0(js)=d0(js)*(24.*3600.*365e06) C CALCULATION OF LC nsq=1 nsum=0 m=0 do 32 j=1,nn-1 if(nsum.gt.20)then nsum = 1 nsq = nsq*2 endif m=m+nsq if(m.gt.100)nsum=nsum+1 lc(j)=m if(imod.eq.1)an(j) = ((2*m-1)*pi)**2 if(imod.eq.2)an(j) = (m*pi)**2 if(imod.eq.3)an(j) = zero(m)**2 32 continue lc(nn)=lc(nn-1)+1 if(imod.eq.3)an(1)=rtsafe(x1,x2,acc)**2 C CALCULATION OF THE AGE SPECTRUM do 16 je=1,nsamp if(imod.eq.1)d0(je)=d0(je)/4.d0 C tau=r*550.**2/(e(1)*dtdt) C tc= e(1)/r/dlog(8.7*tau*d0(1))-273. call geosec(ns,xlambd,d0(je),E(je),temp,time) call lab(d0(je),E(je),r40,r39,telab,tilab,dr39,ni,tab1) C SUMMATION OF THE CONTRIBUTION OF EACH DIFFUSION DOMAIN SIZE. do 18 k=1,ni tra40(k)=c(je)*r40(k)+tra40(k) 18 tra39(k)=c(je)*r39(k)+tra39(k) 16 continue do 20 j=1,ni sra40(j)=tra40(j)-tra40(j-1) sra39(j)=tra39(j)-tra39(j-1) if (sra40(j).gt.0.and.sra39(j).gt.0)goto 21 age=0. goto 19 21 continue scura(j)=sra40(j)/sra39(j) age=dlog(1.+scura(j)/c39wd)/xlambd 19 write(16,130)tra39(j-1)*100.,tab1,age av=(tra39(j-1)+tra39(j))*50. write(14,130)av,tab1,age C write(20,105)age,tab1,tc 20 write(16,130)tra39(j)*100.,tab1,age do 22 j=1,ni tra39(j)=0. 22 tra40(j)=0. 110 format(i20) 105 format(g20.8,a1,g20.8) 100 format(g20.8) 120 format(1x,3(f12.6,a1)) 130 format(1x,3(g20.8,a1)) stop end subroutine geosec(nend,xlambd,d0,E,temp,time) implicit double precision (a-h,o-z) parameter(nch=1005, nn=340, pi=3.141592654,R= 1.987d-03) dimension time(nend+4),temp(nend+4),dzita(nch),d(nch) common /var/ an(nn),xi(nn),b,c40 common /integ/ lc(0:nn),imod zit=0. do 10 j=1,nend avtemp=(temp(j+1)+temp(j))/2. if(j.eq.1.and.avtemp.lt.800)then print *,"WARNING: the sample could had been" print *,"retaining argon at ages >",time(1)," Ma" print *,"The program assume zero argon concentration" print *,"at the initial age:",time(1)," Ma" endif d(j)=d0*dexp(-e/r/avtemp) 10 continue dzita(nend+1)=0. do 20 j=nend,1,-1 20 dzita(j)=dzita(j+1)+dabs(time(j+1)-time(j))*d(j) C COMPUTO OF XI(M) - M<80000 --> nn=340 do 30 mi=1,nn-1 xlogm=dlog(an(mi)) sum=0.d0 do 40 n=1,nend if(d(n).eq.0.)goto 40 uplus=an(mi)*dzita(n+1)+xlambd*(time(1)-time(n+1)) if (uplus-xlogm.gt.25.)goto 40 al=an(mi)*d(n)-xlambd xal= al *(time(n)-time(n+1)) if (dabs(xal).gt.30)then camal=1.d0/al else if (dabs(xal).gt.0.001)then camal=(1.d0-dexp(-xal))/al else camal=(time(n)-time(n+1))*(1-xal/2+xal**2/6.d0) endif endif sum=sum+d(n)*dexp(-uplus)*camal 40 continue tzita = dzita(1)*an(mi) if(tzita.lt.30.)then xfact = dexp(-tzita) else xfact = 0.d0 endif xi(mi)=sum*an(mi) + xfact 30 continue 80 continue return end subroutine lab(d0,e,r40,r39,telab,tilab,dr39,ni,tab1) implicit double precision (a-h,o-z) parameter(nn=340,ntp=200,pi=3.141592654,xlambd=0.0005543, $R=1.987d-03) dimension r40(ni),zita(ntp),r39(ni),ages(ntp) dimension dr39(ni),dr40(ntp),rate(ntp),tilab(ni),telab(ni) character*9 tab1 common /var/ an(nn),xi(nn),b,c40 common /integ/ lc(0:nn),imod c39wd=1-c40 zii=0. do 10 nt=1,ni zita(nt)=zii+d0*tilab(nt)*dexp(-e/(r*telab(nt))) 10 zii=zita(nt) do 20 j=1,ni r39(j)=1. r40(j)=0. sumck = 0. do 20 k=1,nn-1 xmat=0.d0 do 22 k1=lc(k-1)+1,lc(k)-1 if(imod.eq.1)an2 = ((2*k1-1)*pi)**2 if(imod.eq.2)an2 = (k1*pi)**2 if(imod.eq.3)an2 = zero(k1)**2 if (zita(j)*an2.gt.100.) then ab = 0. else ab= dexp(-zita(j)*an2)/an2 endif xmat= xmat+(1.d0-(lc(k)-k1)/(lc(k)-lc(k-1)))*(1./an2-ab) 22 continue do 24 k1=lc(k),lc(k+1)-1 if(imod.eq.1)an2 = ((2*k1-1)*pi)**2 if(imod.eq.2)an2 = (k1*pi)**2 if(imod.eq.3)an2 = zero(k1)**2 if(imod.eq.3.and.k1.eq.1)an2=an(1) if (zita(j)*an2.gt.100.) then ab = 0. else ab= dexp(-zita(j)*an2)/an2 r39(j)=r39(j)-b*ab endif sumck = sumck + b*1.d0/an2 xmat= xmat+(lc(k+1)-k1)/(lc(k+1)-lc(k))*(1./an2-ab) r40(j)=r40(j)+b*(c40-1)*(1./an2-ab) 24 continue r40(j)=r40(j)+b*xmat*xi(k) 20 continue rate(1)=r40(1)/r39(1) dr39(1)=r39(1) dr40(1)=r40(1) do 50 j=2,ni dr39(j)=r39(j)-r39(j-1) dr40(j)=r40(j)-r40(j-1) if (dr39(j).gt.0.and.dr40(j).gt.0)goto 70 ages(j)=0. goto 50 70 rate(j)=dr40(j)/dr39(j) ages(j)=dlog(1.+rate(j)/c39wd)/xlambd 50 continue ages(1)=dlog(1.+rate(1)/c39wd)/xlambd rnum = 1. - 1.0e-07 do 80 j=1,ni if(r39(j).le.rnum)then write(19,140)r39(j)*100,tab1,ages(j) endif 80 continue 140 format(1x,4(f12.4,a1)) return end C SUBROUTINE TO CALCULATE THE THERMAL HISTORY. C (SUBROUTINE SUBCHIST.F) subroutine chist(np,tmin,tpin,time,temp,dt,ns,nch) implicit double precision (a-h,o-z) dimension temp(nch),time(nch) dimension tpin(np),tmin(np) CHARACTER TAB1*9 TAB1=CHAR(09) open(unit=18,file='chist.dat') c DEFINITION OF THE TEMPERATURE STEP IN CENTIDEGREE. C CALCULATION OF THE COOLING HISTORY ns=0. temp(1)=tpin(1) time(1)=tmin(1) tem0=tpin(1) do 4 k=1,np-1 nt=dabs(tpin(k)-tpin(k+1))/dt + ns snt=(tpin(k)-tpin(k+1)) if(dabs(snt).lt.dt)then temp(nt+2)=tpin(k+1) time(nt+2)=tmin(k+1) ns = ns + 1 tem0=tpin(k+1) goto 4 endif snt=snt/dabs(tpin(k)-tpin(k+1)) do 6 j=ns+2,nt+1 temp(j)=tem0 - snt*dt time(j)= age(temp(j),tmin(k),tmin(k+1),tpin(k),tpin(k+1)) tem0 = temp(j) 6 continue ns = nt if(dmod(tpin(k)-tpin(k+1),dt).ne.0.)then temp(nt+2)=tpin(k+1) time(nt+2)=tmin(k+1) tem0=temp(nt+2) ns = ns + 1 endif if(ns.gt.nch-2)stop 'Number of step larger than 1000' 4 continue do 8 jk=1,ns+1 write(18,100)time(jk),tab1,temp(jk)-273. 8 continue 100 format(g20.8,a1,g20.8) return end double precision function age(y,a1,a2,t1,t2) implicit double precision (a-h,o-z) if(y.lt.0.)pause 'temperature less than zero' age=a1 + (y - t1)*(a2-a1)/(t2-t1) return end double precision function zero(n) implicit double precision (a-h,o-z) parameter(pi=3.14159265) den=pi*(4*n-1) zero= den/4.+1./(2.*den)-31./(6*den**3)+3779./(15*den**5) return end subroutine funcd(x1,f,df) implicit double precision (a-h,o-z) f=bessj0(x1) df= - bessj1(x1) return end double precision function bessj0(x) implicit double precision (a-h,o-z) c real*8 y,p1,p2,p3,p4,p5,q1,q2,q3,q4,q5,r1,r2,r3,r4,r5,r6, C * s1,s2,s3,s4,s5,s6 data p1,p2,p3,p4,p5/1.d0,-.1098628627d-2,.2734510407d-4, * -.2073370639d-5,.2093887211d-6/, q1,q2,q3,q4,q5/-.1562499995d- *1, * .1430488765d-3,-.6911147651d-5,.7621095161d-6,-.934945152d-7/ data r1,r2,r3,r4,r5,r6/57568490574.d0,-13362590354.d0,651619640.7d *0, * -11214424.18d0,77392.33017d0,-184.9052456d0/, * s1,s2,s3,s4,s5,s6/57568490411.d0,1029532985.d0, * 9494680.718d0,59272.64853d0,267.8532712d0,1.d0/ if(dabs(x).lt.8.)then y=x**2 bessj0=(r1+y*(r2+y*(r3+y*(r4+y*(r5+y*r6))))) * /(s1+y*(s2+y*(s3+y*(s4+y*(s5+y*s6))))) else ax=dabs(x) z=8./ax y=z**2 xx=ax-.785398164 bessj0=dsqrt(.636619772/ax)*(dcos(xx)*(p1+y*(p2+y*(p3+y*(p4+y * *p5))))-z*dsin(xx)*(q1+y*(q2+y*(q3+y*(q4+y*q5))))) endif return end double precision function bessj1(x) implicit double precision (a-h,o-z) C real*8 y,p1,p2,p3,p4,p5,q1,q2,q3,q4,q5,r1,r2,r3,r4,r5,r6, c * s1,s2,s3,s4,s5,s6 data r1,r2,r3,r4,r5,r6/72362614232.d0,-7895059235.d0,242396853.1d0 *, * -2972611.439d0,15704.48260d0,-30.16036606d0/, * s1,s2,s3,s4,s5,s6/144725228442.d0,2300535178.d0, * 18583304.74d0,99447.43394d0,376.9991397d0,1.d0/ data p1,p2,p3,p4,p5/1.d0,.183105d-2,-.3516396496d-4,.2457520174d-5 *, * -.240337019d-6/, q1,q2,q3,q4,q5/.04687499995d0,-.2002690873d-3 *, * .8449199096d-5,-.88228987d-6,.105787412d-6/ if(dabs(x).lt.8.)then y=x**2 bessj1=x*(r1+y*(r2+y*(r3+y*(r4+y*(r5+y*r6))))) * /(s1+y*(s2+y*(s3+y*(s4+y*(s5+y*s6))))) else ax=dabs(x) z=8./ax y=z**2 xx=ax-2.356194491 bessj1=dsqrt(.636619772/ax)*(dcos(xx)*(p1+y*(p2+y*(p3+y*(p4+y * *p5))))-z*dsin(xx)*(q1+y*(q2+y*(q3+y*(q4+y*q5))))) * *dsign(1.d0,x) endif return end double precision function rtsafe(x1,x2,xacc) implicit double precision (a-h,o-z) parameter (maxit=100) call funcd(x1,fl,df) call funcd(x2,fh,df) if(fl*fh.ge.0.) pause 'root must be bracketed' if(fl.lt.0.)then xl=x1 xh=x2 else xh=x1 xl=x2 swap=fl fl=fh fh=swap endif rtsafe=.5*(x1+x2) dxold=dabs(x2-x1) dx=dxold call funcd(rtsafe,f,df) do 11 j=1,maxit if(((rtsafe-xh)*df-f)*((rtsafe-xl)*df-f).ge.0. * .or. dabs(2.*f).gt.dabs(dxold*df) ) then dxold=dx dx=0.5*(xh-xl) rtsafe=xl+dx if(xl.eq.rtsafe)return else dxold=dx dx=f/df temp=rtsafe rtsafe=rtsafe-dx if(temp.eq.rtsafe)return endif if(dabs(dx).lt.xacc) return call funcd(rtsafe,f,df) if(f.lt.0.) then xl=rtsafe fl=f else xh=rtsafe fh=f endif 11 continue pause 'rtsafe exceeding maximum iterations' return end
The large city skylines and Statue of Liberty is more than just a far-off view for sisters serving in the New Jersey Morristown Mission. As part of their proselyting responsibilities, some companionships spend a few hours a week with people from around the world in the American Family Immigration History Center located on Ellis Island, New York. Ellis Island, known for being the gateway for many immigrants between the years 1892-1924, has become a destination for many from around the United States and world to visit and learn more about their ancestors. But for many patrons, it is more than a chance to learn about their family — it is a chance for a positive exposure to the Church. The American Family Immigration History Center has had strong ties with the Church from the very beginning. A collaborative effort, done by 12,000 members of the Church before the center opened in 2001, helped to research, document and transcribe historical immigration records from microfilm. The records included the names of people who immigrated to the U.S., the ships they traveled in and other personal information. The time Church members spent documenting the records and manifests, which spanned seven years and millions of hours of work, produced 24 million names of people who had immigrated to the United States specifically through Ellis Island (See Church News, April 21, 2001). That work continues to benefit visitors today. From May to October, Wednesdays through Saturdays, different companionships of sisters serving in the New Jersey Morristown Mission take one day a week and travel to the island to volunteer from 11 a.m. to 4 p.m. in helping people do their family research. Through volunteering their time, missionaries are able to introduce people to the Church, just by wearing a missionary tag. "These missionaries are there to serve and help," said President A. Lee Bahr, who presides over the New Jersey Morristown Mission. "And hopefully help people more likely to be interested [in the Church] later, although that isn't the purpose. It is really just to help people." The American Family Immigration History Center opened on April 17, 2001, and has been a great resource for tourists and locals alike to learn more about their ancestors. Although missionaries are not allowed to actively proselyte while working in the family history center, they are able to answer questions patrons have about the Church and lead them to more information. "We explain how to search and find the most information about their family that they can," said Sister Maxine Fonua, who is from Salt Lake City. "Some people ask about more information and we can give them the Church Web sites. Some have more questions [about the Church] and we explain about being a missionary." In addition, missionaries explain why the Church spends so much time focusing on finding families. "Just connecting people to their ancestors gives people a sense of family and of being a part of Heavenly Father's family," said President Bahr. "People have a natural sense of that, whether they are members of the Church or not." Even without much talk of the Church, visitors are touched by the spirit of Elijah — that of turning hearts of father and children to each other — as they learn about generations of family that came before them. "I've been there and watched people with tears in their eyes as they find their ancestors and realize the importance of their family," said Sister Carol Ann Bahr, President Bahr's wife. "It is a very spiritual experience for them. They have a sense of gratitude and honor for their ancestors." Above all, the service rendered by missionaries is a great opportunity for people to come closer to Christ. "As I've watched the people look at the name tag," said Sister Bahr, "they can relate the service to that of Jesus Christ."
This guide outlines all of the classes available at UC Davis for a given quarter. Information regarding classes includes: meeting times, class locations, enrollment capacities, and final examination times. Since classes, its locations, and its times will change every quarter, this guide is printed every quarter, compared to the General Catalog which is printed every two years. See http://registrar.ucdavis.edu/csrg/ to view the guide online. The site also lists updates to the CSRG that happened after press time. If youre registered in the class, youll see these changes on http://sisweb.ucdavis.edu/ SISWeb, anyway. Organizing your class schedule can be hard and overwhelming considering the number of classes available, which is why a site like http://siscast.com can be very useful.
# See # http://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/ exp_cool <- function(i, ntot, a, b) { (1-b)*exp(-a*i/ntot)+b } pow_cool <- function(i, ntot, a, b) { (1-b)*(a^(i/ntot))+b } lin_cool <- function(i, ntot, a, b) { (1-b)*(1/(1+a*i))+b } quad_cool <- function(i, ntot, a, b) { (1-b)*(1/(1+a*(i^2)))+b } log_cool <- function(i, ntot, a, b) { (1-b)*(1/(1+a*log(1+i)))+b } ntot <- 10000 x <- seq(0, ntot, by=1) # plot( # x, # pow_cool(x, ntot, 0.001, 0), # type="l" # ) plot( x, exp_cool(x, ntot, 3, 0), type="l" ) lines( x, pow_cool(x, ntot, 1e-10, 0), col="red" ) lines( x, lin_cool(x, ntot, 0.01, 0.01), col="green" ) lines( x, quad_cool(x, ntot, 0.0000002, 0.05), col="blue" ) lines( x, log_cool(x, ntot, 3, 0), col="purple" ) # plot( # x, # 0.2*cos(100*x*pi/ntot)+0.3, # type="l", # ylim=c(0, 1) # ) # plot( x, ((exp(-5*x/ntot)+0.05*cos(100*x*pi/ntot))+0.05)/1.1, type="l" ) # # plot( # seq(-1, 1, by=0.01), # seq(-1, 1, by=0.01)^2, # type="l" # ) # 1) Lift the map # 2) Lift-decay the map # 3) Discussion: adaptive # 4) Discussion: partial (parts) of metric # 5) Discussion: scale with data and parameters
From iris.heap_lang Require Export proofmode notation. (* make these print *) Notation NONE := (InjL (LitV LitUnit)). Notation NONEV := (InjLV (LitV LitUnit)). Notation SOME x := (InjR x). Notation SOMEV x := (InjRV x). Export Set Default Goal Selector "!". Export Set Default Proof Using "Type". Section proof. Context `{!heapGS Σ}. Lemma wp_frame (e: expr) (Φ Φ': val → iProp Σ) : WP e {{Φ}} ∗ (∀ r, Φ r -∗ Φ' r) ⊢ WP e {{Φ'}}. Proof. iIntros "[Hwp Himpl]". iApply (wp_strong_mono with "Hwp [Himpl]"). - auto. - auto. - iIntros (v) "HΦ !>". iApply "Himpl"; auto. Qed. Lemma wp_store_axiom (l: loc) (v0 v: val) : l ↦ v0 ⊢ WP (#l <- v) {{ λ _, l ↦ v }}. Proof. iIntros "Hl". wp_store. auto. Qed. Lemma wp_load_axiom (l: loc) (v: val) : l ↦ v ⊢ WP ! #l {{ λ r, ⌜r = v⌝ ∗ l ↦ v }}. Proof. iIntros "Hl". wp_load. auto. Qed. Lemma wp_free_axiom (l: loc) (v: val) : l ↦ v ⊢ WP Free #l {{ λ _, emp }}. Proof. iIntros "Hl". wp_free. auto. Qed. End proof.
{- Byzantine Fault Tolerant Consensus Verification in Agda, version 0.9. Copyright (c) 2021, Oracle and/or its affiliates. Licensed under the Universal Permissive License v 1.0 as shown at https://opensource.oracle.com/licenses/upl -} import LibraBFT.Impl.OBM.Crypto as Crypto open import LibraBFT.Impl.OBM.Logging.Logging open import LibraBFT.Impl.Types.ValidatorVerifier as ValidatorVerifier open import LibraBFT.ImplShared.Consensus.Types open import Optics.All import Util.KVMap as Map open import Util.PKCS open import Util.Prelude module LibraBFT.Impl.Types.LedgerInfoWithSignatures where obmNewNoSigs : LedgerInfo → LedgerInfoWithSignatures obmNewNoSigs li = LedgerInfoWithSignatures∙new li Map.empty -- HC-TODO : refactor this and TimeoutCertificate addSignature : AccountAddress → Signature → LedgerInfoWithSignatures → LedgerInfoWithSignatures addSignature validator sig liws = case Map.lookup validator (liws ^∙ liwsSignatures) of λ where (just _) → liws nothing → liws & liwsSignatures ∙~ Map.kvm-insert-Haskell validator sig (liws ^∙ liwsSignatures) verifySignatures : LedgerInfoWithSignatures → ValidatorVerifier → Either ErrLog Unit verifySignatures self validator = withErrCtx' ("LedgerInfoWithSignatures" ∷ "verify" ∷ []) (ValidatorVerifier.batchVerifyAggregatedSignatures validator (self ^∙ liwsLedgerInfo) (self ^∙ liwsSignatures))
# This file was generated, do not modify it. # hide X3 = select(X2, [:Lag1, :Lag2]) clf = machine(LogisticClassifier(), X3, y) fit!(clf, rows=train) ŷ = predict_mode(clf, rows=test) mean(ŷ .== y[test])
Inductive ForallT {A : Type} (P : A -> Type) : list A -> Type := | ForallT_nil : ForallT P nil | ForallT_cons a l : P a -> ForallT P l -> ForallT P (cons a l). (* A non-empty rose-tree. If empty rose-trees are necessary, use [option] of this type, or add a nil constructor. (These two approaches yield different results.) *) Inductive RTree (A : Type) : Type := | RTree_cons : A -> list (RTree A) -> RTree A. Arguments RTree_cons {_} _ _. Require Import List. Import ListNotations. Inductive RTForallT {A : Type} (P : A -> Type) : RTree A -> Type := | RTF_nil a : P a -> RTForallT P (RTree_cons a []) | RTF_cons a l b : RTForallT P b -> RTForallT P (RTree_cons a l) -> RTForallT P (RTree_cons a (b :: l)). Lemma RTForallT_inv_root A P a l : @RTForallT A P (RTree_cons a l) -> P a. Proof. intros. induction l. { inversion X; subst; clear X. assumption. } inversion X; subst; clear X. auto. Qed. Lemma RTForallT_inv_list A P a l : @RTForallT A P (RTree_cons a l) -> ForallT (RTForallT P) l. Proof. intros. induction l. { constructor. } constructor. { inversion X; subst; clear X. assumption. } inversion X; subst; clear X. auto. Qed. Inductive RTForallT0 {A : Type} (P : A -> Type) : RTree A -> Type := | RTF0_cons (a : A) (l : list (RTree A)) : P a -> ForallT (RTForallT0 P) l -> RTForallT0 P (RTree_cons a l). Lemma RTForallT0_complete {A : Type} (P : A -> Type) t : RTForallT P t -> RTForallT0 P t. Proof. intros. induction X. { constructor; try assumption. constructor. } inversion IHX2; subst; clear IHX2. constructor; try assumption. constructor; try assumption. Qed. Section RTree_rect. Context {A : Type}. Variable (P : RTree A -> Type). Variable (Q : A -> Type). Hypothesis Hcons : forall (a : A) (l : list (RTree A)), Q a -> ForallT P l -> P (RTree_cons a l). Fixpoint RTree_rect1 (t : RTree A) (H : RTForallT0 Q t) : P t. Proof. intros. induction H. apply Hcons; try assumption. induction f; constructor. { now apply RTree_rect1. } assumption. Defined. Corollary RTree_rect0 (t : RTree A) (H : RTForallT Q t) : P t. Proof. apply RTree_rect1. apply RTForallT0_complete. assumption. Defined. End RTree_rect. Definition RTree_root {A : Type} (t : RTree A) : A := match t with | RTree_cons e _ => e end. Fixpoint RTForallT_True {A : Type} t : RTForallT (fun _ : A => True) t. Proof. induction t. induction l. { constructor. constructor. } constructor. { apply RTForallT_True. } assumption. Defined. Lemma RTForallT_forall {A : Type} (P : A -> Type) : (forall a : A, P a) -> forall t, RTForallT P t. Proof. intros. apply RTree_rect0 with (Q := (fun _ => True)). 2: { apply RTForallT_True. } intros. induction X0; constructor; auto. Qed. Lemma ForallT_dec {A : Type} (P : A -> Type) : (forall a : A, P a + (P a -> False)) -> forall l, ForallT P l + (ForallT P l -> False). Proof. Admitted. Lemma ForallT_dec_lift {A : Type} (P : A -> Type) l : ForallT (fun D => (P D) + (P D -> False))%type l -> ForallT P l + (ForallT P l -> False). Proof. intros. induction X. { left. constructor. } destruct p. 2: { right. intros. inversion X0; subst; clear X0. contradiction. } destruct IHX. - left. constructor; assumption. - right. intros. inversion X0; subst; clear X0. contradiction. Qed. Fixpoint ForallT_map {A : Type} {P : A -> Type} {Q : A -> Type} (f : forall a, P a -> Q a) (l : list A) (H : ForallT P l) : list { a & { b : P a & Q a } } := match H with | ForallT_nil _ => [] | ForallT_cons _ a l Ha Hl => (existT _ a (existT _ Ha (f a Ha))) :: (ForallT_map f l Hl) end. Lemma ForallT_impl {A : Type} {P Q : A -> Type} : (forall a, P a -> Q a) -> forall l, ForallT P l -> ForallT Q l. Proof. intros. induction X0; constructor; auto. Defined. Lemma ForallT_map0 {A B : Type} (f : A -> B) (P : B -> Type) (l : list A) : ForallT (fun x : A => P (f x)) l -> ForallT P (map f l). Proof. intros. induction X. { constructor. } simpl. constructor; assumption. Qed.
lemma is_first_power' [simp]: "is_nth_power (Suc 0) x"
(* Copyright 2014 Cornell University Copyright 2015 Cornell University This file is part of VPrl (the Verified Nuprl project). VPrl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. VPrl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with VPrl. If not, see <http://www.gnu.org/licenses/>. Website: http://nuprl.org/html/verification/ Authors: Abhishek Anand & Vincent Rahli & Mark Bickford *) Require Export computation8. Require Export computation_seq. Lemma compute_step_cbv_ncan {o} : forall lib n l x b, @compute_step o lib (mk_cbv (oterm (NCan n) l) x b ) = match compute_step lib (oterm (NCan n) l) with | csuccess p => csuccess (mk_cbv p x b) | cfailure str ts => cfailure str ts end. Proof. introv; csunf; simpl; sp. Qed. Lemma compute_step_cbv_abs {o} : forall lib n l x b, @compute_step o lib (mk_cbv (oterm (Abs n) l) x b ) = match compute_step lib (oterm (Abs n) l) with | csuccess p => csuccess (mk_cbv p x b) | cfailure str ts => cfailure str ts end. Proof. introv; csunf; simpl; sp. Qed. Lemma compute_step_cbv_exc {o} : forall lib l x b, @compute_step o lib (mk_cbv (oterm Exc l) x b ) = csuccess (oterm Exc l). Proof. introv; csunf; simpl; sp. Qed. Lemma compute_step_cbv_can {o} : forall lib c l x b, @compute_step o lib (mk_cbv (oterm (Can c) l) x b ) = csuccess (apply_bterm (bterm [x] b) [oterm (Can c) l]). Proof. introv; unfold mk_arithop; csunf; simpl; sp. Qed. Lemma compute_step_cbv_can_success {o} : forall lib c l x b u, @compute_step o lib (mk_cbv (oterm (Can c) l) x b ) = csuccess u -> u = (apply_bterm (bterm [x] b) [oterm (Can c) l]). Proof. introv cs. csunf cs; allsimpl. allsimpl. inversion cs. auto. Qed. Lemma if_computes_to_exc_cbv {q} : forall lib n x (t b : @NTerm q) e, isprogram t -> computes_to_exception lib n (mk_cbv t x b) e -> computes_to_exception lib n t e [+] hasvalue lib t. Proof. unfold computes_to_exception, reduces_to. introv ispt re; exrepnd. revert dependent b. revert dependent t. induction k; introv ispt r. - apply reduces_in_atmost_k_steps_0 in r; inversion r. - rw @reduces_in_atmost_k_steps_S in r; exrepnd. destruct t as [z|f|op1 bs]; try (complete (inversion r1)). { right; eauto 3 with slow. } dopid op1 as [can|ncan|exc|abs] Case; try (complete (inversion r1)). + Case "Can". right. exists (oterm (Can can) bs). unfold computes_to_value. sp. exists 0. apply reduces_in_atmost_k_steps_0. auto. + Case "NCan". rw @compute_step_cbv_ncan in r1. remember (compute_step lib (oterm (NCan ncan) bs)) as c; destruct c; allsimpl; ginv; symmetry in Heqc. applydup @preserve_compute_step in Heqc; auto. apply IHk in r0; auto. repndors; exrepnd. { left. exists (S k0). rw @reduces_in_atmost_k_steps_S. exists n0; auto. } { right. allunfold @hasvalue. exrepnd. exists t'; sp. eapply computes_to_value_step; eauto. } + Case "Exc". rw @compute_step_cbv_exc in r1. inversion r1; subst. left. exists 0. apply reduces_in_atmost_k_steps_0. apply reduces_in_atmost_k_steps_exception in r0. auto. + Case "Abs". rw @compute_step_cbv_abs in r1. remember (compute_step lib (oterm (Abs abs) bs)) as c; destruct c; allsimpl; ginv; symmetry in Heqc. applydup @preserve_compute_step in Heqc; auto. apply IHk in r0; auto. repndors; exrepnd. { left. exists (S k0). rw @reduces_in_atmost_k_steps_S. exists n0; auto. } { right. allunfold @hasvalue. exrepnd. exists t'; sp. eapply computes_to_value_step; eauto. } Qed. (* !!MOVE *) Lemma if_raises_exception_cbv {o} : forall lib x(t b: @NTerm o), isprogram t -> raises_exception lib (mk_cbv t x b) -> raises_exception lib t [+] hasvalue lib t. Proof. introv ispt re. unfold raises_exception in re; exrepnd. pose proof (if_computes_to_exc_cbv lib a x t b e ispt re1 ) as h. repndors; exrepnd. - left; exists a e; auto. - right. auto. Qed. (* !!MOVE *) Lemma if_raises_exceptionc_cbv {o} : forall lib x t (b: @CVTerm o [x]), raises_exceptionc lib (mkc_cbv t x b) -> raises_exceptionc lib t [+] hasvaluec lib t. Proof. introv re. destruct_cterms. allsimpl. allunfold @raises_exceptionc. allunfold @computes_to_valc. allsimpl. pose proof (if_raises_exception_cbv lib x x0 x1 ) as h. repeat (autodimp h hyp); eauto 3 with slow. Qed. Lemma hasvaluec_mkc_cbv {q} : forall lib x t ( b : @CVTerm q [x]), hasvaluec lib (mkc_cbv t x b) -> hasvaluec lib t. Proof. introv hv. destruct_cterms. unfold hasvaluec in hv; allsimpl. rename x0 into t. rename x1 into b. destruct hv as [t' c]. destruct c as [rt iv]. destruct rt as [k comp]. unfold hasvaluec. simpl. revert dependent x. revert dependent b. revert dependent t. revert dependent t'. induction k ; introv isv ispt ispb comp. - rw @reduces_in_atmost_k_steps_0 in comp; subst. inversion isv; allsimpl; tcsp. - rw @reduces_in_atmost_k_steps_S in comp; exrepnd. destruct t as [v|f|op bs]. + inversion comp1. + eauto 3 with slow. + dopid op as [can | ncan | ex | abs] Case. * Case "Can". exists (oterm (Can can) bs). apply computes_to_value_isvalue_refl; eauto 3 with slow. * Case "NCan". rw @compute_step_cbv_ncan in comp1. remember (compute_step lib (oterm (NCan ncan) bs)). destruct c; ginv. symmetry in Heqc. allrw @isprog_eq. applydup @preserve_compute_step in Heqc; auto. apply IHk in comp0; auto; exrepnd; try (complete (apply isprog_eq; auto)). unfold hasvalue in comp0. exrepnd. exists t'0. eapply computes_to_value_step; eauto. * Case "Exc". rw @compute_step_cbv_exc in comp1. inversion comp1. subst. apply reduces_in_atmost_k_steps_exception in comp0. subst. inversion isv; allsimpl; tcsp. * Case "Abs". rw @compute_step_cbv_abs in comp1. remember (compute_step lib (oterm (Abs abs) bs)). destruct c; ginv. symmetry in Heqc. allrw @isprog_eq. applydup @preserve_compute_step in Heqc; auto. apply IHk in comp0; auto; exrepnd; try (complete (apply isprog_eq; auto)). unfold hasvalue in comp0. exrepnd. exists t'0. eapply computes_to_value_step; eauto. Qed.
#!/usr/bin/env julia using Gadfly using RDatasets iris = dataset("datasets", "iris") p = plot(iris, x=:SepalLength, y=:SepalWidth, Geom.point); img = SVG("iris_plot.svg", 14cm, 8cm) draw(img, p) # Look at this, coloring by species. #p2 = plot(iris, x=:SepalLength, y=:SepalWidth, color=:Species, Geom.point); #img2 = SVG("iris_plot2.svg", 14cm, 8cm) #draw(img2, p2) # Egads. # ./hello.jl 42.91s # Same time for 2 plots, though. # ./hello.jl 49.89s # Load iris data alone. # ./hello.jl 15.18s # With using Gadfly # hello.jl 20.15s # entire first plot. # 48.74 # So plotting is about 28 seconds.
require(rms) d <- expand.grid(a=c('a1','a2'), b=c('b1','b2')) d$y <- Surv(c(1,3,2,4)) f <- y ~ a * strat(b) m <- model.frame(f, data=d) Terms <- terms(f, specials='strat', data=d) specials <- attr(Terms, 'specials') temp <- survival:::untangle.specials(Terms, 'strat', 1) Terms <- Terms[- temp$terms] # X <- rms:::Design(m) # atr <- attr(X, 'Design') # atr$colnames model.matrix(Terms, m) colnames(model.matrix(Terms, m)[, -1, drop=FALSE]) cph(f, data=d)
module Examples where import Control.Lens hiding (para) import Prelude hiding (id, (.)) import System.Random import Control.Monad import Numeric.LinearAlgebra.Array import Numeric.LinearAlgebra.Array.Util import CategoricDefinitions import Autodiff.GAD import Autodiff.D import Ops import Para import TrainUtils import TensorUtils import OnesLike {- f (p, q) a = (p + q*a) -} linRegFn :: (Additive a, Num a) => DType ((a, a), a) a linRegFn = addC . (id `x` mulC) . assocL -- returns (inp, out) pair we want to learn sampleData :: IO (Double, Double) sampleData = do x <- randomIO :: IO Double return (x, 3 + 7*x) run :: IO () run = do initialParams <- randomIO :: IO (Double, Double) let initialLearner = Learner initialParams (Para linRegFn) sgd sampler = zip3 [0..] (repeat sampleData) (repeat sqDiff) finalLearner <- foldM trainStepWithCost initialLearner (take 10000 sampler) putStrLn $ "Starting network parameters:\n" ++ show initialParams putStrLn $ "Final network parameters:\n" ++ show (finalLearner ^. p) return () sampleDataTensor :: IO (Tensor, Tensor) sampleDataTensor = do d <- randomTensor [5, 3] "bf" return (d, 3 + 7 * d) -- multiply two arrays you get and sum the "b" axis l :: _ => ParaDType (Tensor, Tensor) Tensor Tensor l = Para $ sumAxes "b" . linRegFn run1 :: IO _ run1 = do p1 <- randomTensor [3, 2] "fo" p2 <- randomTensor [2] "o" let initialLearner = Learner (p1, p2) l sgd sampler = zip3 [0..] (repeat sampleDataTensor) (repeat (sumAxes "b" . sqDiff)) finalLearner <- foldM trainStepWithCost initialLearner (take 1 sampler) putStrLn $ "Starting network parameters:\n" ++ arrShow (p1, p2) putStrLn $ "Final network parameters:\n" ++ arrShow (finalLearner ^. p) return finalLearner
/*!@file * @copyright This code is licensed under the 3-clause BSD license. * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group. * See LICENSE.txt for details. */ #include <boost/test/unit_test.hpp> #include "Molassembler/Temple/Adaptors/Zip.h" #include "Molassembler/Temple/Functional.h" #include "Molassembler/Temple/Random.h" #include "Molassembler/Temple/Stringify.h" #include "Molassembler/Temple/constexpr/Array.h" #include "Molassembler/Temple/constexpr/BTree.h" #include "Molassembler/Temple/constexpr/Jsf.h" #include <set> #include <iostream> using namespace Scine::Molassembler; extern Temple::Generator<> generator; namespace BTreeStaticTests { constexpr Temple::BTree<unsigned, 3, 20> generateTree() { Temple::BTree<unsigned, 3, 20> tree; tree.insert(9); tree.insert(3); tree.insert(5); tree.insert(20); return tree; } constexpr auto testTree = generateTree(); static_assert(testTree.size() == 4, "Size of generated tree is wrong!"); static_assert( /* BTree of minimum order 3 has max 5 keys per node and max 6 children per node * * height nodes keys * 0 1 5 * 1 1 + 6 5 + 6*5 * 2 1 + 6 + 36 5 + 6*5 + 36*5 * * #nodes(h) = sum_{i = 0}^{h} (2t)^i * * (2t)^{h + 1} - 1 * N = ---------------- * 2t - 1 * * -> N * (2t - 1) + 1 = (2t)^{h + 1} * * -> log_2t [N * (2t - 1) + 1] = h + 1 * * -> h = log_2t [N * (2t - 1) + 1] - 1 * */ Temple::BTreeProperties::minHeight(5, 3) == 0 && Temple::BTreeProperties::minHeight(35, 3) == 1 && Temple::BTreeProperties::minHeight(215, 3) == 2, "minHeight function is wrong" ); static_assert( Temple::BTreeProperties::maxNodesInTree(0, 3) == 1 && Temple::BTreeProperties::maxNodesInTree(1, 3) == 7 && Temple::BTreeProperties::maxNodesInTree(2, 3) == 43 && Temple::BTreeProperties::maxNodesInTree(3, 3) == 259, "maxNodesInTree is wrong" ); } // namespace BTreeStaticTests inline unsigned popRandom(std::set<unsigned>& values) { auto it = values.begin(); std::advance( it, Temple::Random::getSingle<unsigned>(0, values.size() - 1, generator.engine) ); auto value = *it; values.erase(it); return value; } BOOST_AUTO_TEST_CASE(ConstexprBTree, *boost::unit_test::label("Temple")) { constexpr unsigned nKeys = 100; using namespace std::string_literals; std::vector<unsigned> values (nKeys); std::iota( values.begin(), values.end(), 0 ); std::set<unsigned> notInTree {values.begin(), values.end()}; std::set<unsigned> inTree; Temple::BTree<unsigned, 3, nKeys> tree; std::string lastTreeGraph; std::vector<std::string> decisions; auto addElement = [&](const std::string& treeGraph) { // Add an element auto toAdd = popRandom(notInTree); decisions.emplace_back("i"s + std::to_string(toAdd)); BOOST_TEST_CONTEXT( "Element insertion threw. Operation sequence: " << Temple::condense(decisions) << ". Prior to last operation: \n" << treeGraph << "\n\n After last operation: \n" << tree.dumpGraphviz() ) { BOOST_REQUIRE_NO_THROW(tree.insert(toAdd)); } inTree.insert(toAdd); }; auto removeElement = [&](const std::string& treeGraph) { // Remove an element auto toRemove = popRandom(inTree); decisions.emplace_back("r"s + std::to_string(toRemove)); BOOST_TEST_CONTEXT( "Tree element removal failed. Operation sequence: " << Temple::condense(decisions) << ". Prior to last operation: \n" << treeGraph << "\n\n After last operation: \n" << tree.dumpGraphviz() ) { BOOST_REQUIRE_NO_THROW(tree.remove(toRemove)); } notInTree.insert(toRemove); }; auto fullValidation = [&](const std::string& treeGraph) { // Validate the tree BOOST_TEST_CONTEXT( "Tree validation failed. Operation sequence: " << Temple::condense(decisions) << ". Prior to last operation: \n" << treeGraph << "\n\n After last operation: \n" << tree.dumpGraphviz() ) { BOOST_REQUIRE_NO_THROW(tree.validate()); } // Check that elements that weren't inserted aren't falsely contained auto notInsertedButContained = Temple::copy_if( notInTree, [&](const auto& notInTreeValue) -> bool { return tree.contains(notInTreeValue); } ); // Check that all elements are truly contained or not BOOST_REQUIRE_MESSAGE( notInsertedButContained.empty(), "Not all elements recorded as not in the tree are recognized as such!\n" << "Found in the tree, but should not be present: " << Temple::condense(notInsertedButContained) << "\nSequence of operations: " << Temple::condense(decisions) << ". Prior to last operation: \n" << treeGraph << "\n\n After last operation: \n" << tree.dumpGraphviz() ); auto insertedNotContained = Temple::copy_if( inTree, [&](const auto& inTreeValue) -> bool { return !tree.contains(inTreeValue); } ); BOOST_REQUIRE_MESSAGE( insertedNotContained.empty(), "Not all elements recorded as contained in the tree are recognized as such!\n" << "Not found in the tree: " << Temple::condense(insertedNotContained) << "\nSequence of operations: " << Temple::condense(decisions) << ". Prior to last operation: \n" << treeGraph << "\n\n After last operation: \n" << tree.dumpGraphviz() ); }; for(unsigned i = 0; i < 10; ++i) { decisions.clear(); // Heavy insert-delete workload for(unsigned nSteps = 0; nSteps < 1000; ++nSteps) { lastTreeGraph = tree.dumpGraphviz(); // Decide whether to insert or remove a random item auto decisionFloat = Temple::Random::getSingle<double>(0.0, 1.0, generator.engine); if(decisionFloat >= static_cast<double>(inTree.size()) / nKeys) { addElement(lastTreeGraph); } else { removeElement(lastTreeGraph); } fullValidation(lastTreeGraph); } BOOST_REQUIRE_MESSAGE( Temple::all_of( Temple::Adaptors::zip(tree, inTree), [&](const unsigned treeValue, const unsigned testValue) -> bool { if(treeValue != testValue) { std::cout << "Expected " << testValue << ", got " << treeValue << std::endl; return false; } return true; } ), "BTree through-iteration does not yield the same elements as expected!\n" << tree.dumpGraphviz() ); // Fill'er up all the way while(inTree.size() != nKeys) { lastTreeGraph = tree.dumpGraphviz(); addElement(lastTreeGraph); fullValidation(lastTreeGraph); } // Empty the tree while(!inTree.empty()) { lastTreeGraph = tree.dumpGraphviz(); removeElement(lastTreeGraph); fullValidation(lastTreeGraph); } } } namespace { /* Test that if a BTree is instantiated with a specific size, that size * definitely fits in the tree */ template<size_t minOrder, size_t nElements> constexpr bool BTreeAllocatedSizeSufficient() { Temple::BTree<unsigned, minOrder, nElements> tree; for(unsigned i = 0; i < nElements; ++i) { tree.insert(i); } return true; } template<size_t minOrder, size_t ... nElements> constexpr bool testAllBTrees(std::index_sequence<nElements...> /* elements */) { Temple::Array<bool, sizeof...(nElements)> results {{ BTreeAllocatedSizeSufficient<minOrder, 5 + nElements>()... }}; for(unsigned i = 0; i < sizeof...(nElements); ++i) { if(!results.at(i)) { return false; } } return true; } template<size_t ... minOrders> constexpr bool testAllBTrees(std::index_sequence<minOrders...> /* elements */) { Temple::Array<bool, sizeof...(minOrders)> results {{ testAllBTrees<2 + minOrders>(std::make_index_sequence<45>{})... // Test sizes 5->50 }}; for(unsigned i = 0; i < sizeof...(minOrders); ++i) { if(!results.at(i)) { return false; } } return true; } constexpr bool testAllBTrees() { return testAllBTrees(std::make_index_sequence<3>{}); // Test min orders 2->5 } static_assert( testAllBTrees(), "For some B-Trees, you cannot fit as many elements in as requested at instantiation" ); } // namespace
import for_mathlib.locally_closed namespace topological_space variables (α β : Type*) [topological_space α] [topological_space β] (f : α → β) def closed_points : set α := { x : α | is_closed ({x} : set α) } lemma mem_closed_points {x} : x ∈ closed_points α ↔ is_closed ({x} : set α) := iff.rfl def is_jacobson : Prop := ∀ Z, is_closed Z → closure (Z ∩ closed_points α) = Z variables {α β f} lemma is_jacobson_iff_locally_closed : is_jacobson α ↔ ∀ Z : set α, Z.nonempty → is_locally_closed Z → (Z ∩ closed_points α).nonempty := begin split, { simp_rw [is_locally_closed_iff_is_open_coboundary, coboundary, is_open_compl_iff, ← set.ne_empty_iff_nonempty], intros H Z hZ hZ' e, have : Z ⊆ closure Z \ Z, { refine subset_closure.trans _, nth_rewrite 0 ← H (closure Z) is_closed_closure, rw [hZ'.closure_subset_iff, set.subset_diff, set.disjoint_iff, set.inter_assoc, set.inter_comm _ Z, e], exact ⟨set.inter_subset_left _ _, set.inter_subset_right _ _⟩ }, rw [set.subset_diff, disjoint_self, set.bot_eq_empty] at this, exact hZ this.2 }, { intros H Z hZ, refine subset_antisymm (hZ.closure_subset_iff.mpr $ set.inter_subset_left _ _) _, rw [← set.disjoint_compl_left_iff_subset, set.disjoint_iff_inter_eq_empty, ← set.not_nonempty_iff_eq_empty], intro H', have := H _ H' (is_closed_closure.is_open_compl.is_locally_closed.inter hZ.is_locally_closed), rw [← set.ne_empty_iff_nonempty, ne.def, set.inter_assoc, ← set.disjoint_iff_inter_eq_empty, set.disjoint_compl_left_iff_subset] at this, exact this subset_closure } end alias is_jacobson_iff_locally_closed ↔ is_jacobson.nonempty_inter_closed_points _ lemma is_jacobson.is_closed_of_is_locally_closed (hα : is_jacobson α) {x : α} (hx : is_locally_closed ({x} : set α)) : is_closed ({x} : set α) := begin obtain ⟨_, ⟨y, rfl : y = x, rfl⟩, hy'⟩ := hα.nonempty_inter_closed_points _ (set.singleton_nonempty x) hx, exact hy' end lemma preimage_closed_points_subset (hf : embedding f) : f ⁻¹' closed_points β ⊆ closed_points α := begin intros x hx, rw mem_closed_points, convert continuous_iff_is_closed.mp hf.continuous _ hx, rw [← set.image_singleton, set.preimage_image_eq _ hf.inj] end lemma closed_embedding.preimage_closed_points (hf : closed_embedding f) : f ⁻¹' closed_points β = closed_points α := begin ext x, simp [mem_closed_points, ← set.image_singleton, hf.closed_iff_image_closed], end lemma open_embedding.preimage_closed_points (hf : open_embedding f) (hβ : is_jacobson β) : f ⁻¹' closed_points β = closed_points α := begin apply subset_antisymm (preimage_closed_points_subset hf.to_embedding), intros x hx, apply hβ.is_closed_of_is_locally_closed, rw ← set.image_singleton, exact (hx.is_locally_closed.image hf.to_inducing hf.open_range.is_locally_closed) end lemma is_jacobson.of_open_embedding (hα : is_jacobson β) (hf : open_embedding f) : is_jacobson α := begin rw is_jacobson_iff_locally_closed, rw ← hf.preimage_closed_points hα, rw is_jacobson_iff_locally_closed at hα, intros Z hZ hZ', obtain ⟨_, ⟨x, hx, rfl⟩, hx'⟩ := hα _ (hZ.image f) (hZ'.image hf.to_inducing hf.open_range.is_locally_closed), exact ⟨_, hx, hx'⟩ end lemma is_jacobson.of_closed_embedding (hα : is_jacobson β) (hf : closed_embedding f) : is_jacobson α := begin rw is_jacobson_iff_locally_closed at hα ⊢, rw ← hf.preimage_closed_points, intros Z hZ hZ', obtain ⟨_, ⟨x, hx, rfl⟩, hx'⟩ := hα _ (hZ.image f) (hZ'.image hf.to_inducing hf.closed_range.is_locally_closed), exact ⟨_, hx, hx'⟩ end lemma is_jacobson.discrete_of_finite [finite α] (hα : is_jacobson α) : discrete_topology α := begin suffices : closed_points α = set.univ, { rw ← forall_open_iff_discrete, intro s, rw [← is_closed_compl_iff, ← set.bUnion_of_singleton sᶜ], refine is_closed_bUnion (set.to_finite _) (λ x hx, _), rw [← mem_closed_points, this], trivial }, rw [← set.univ_subset_iff, ← hα _ is_closed_univ, set.univ_inter, closure_subset_iff_is_closed, ← set.bUnion_of_singleton (closed_points α)], exact is_closed_bUnion (set.to_finite _) (λ _, id), end lemma {u} is_jacobson_iff_of_supr_eq_top {α : Type u} [topological_space α] {ι : Type u} {U : ι → opens α} (hU : supr U = ⊤) : is_jacobson α ↔ ∀ i, is_jacobson (U i) := begin refine ⟨λ h i, h.of_open_embedding (U i).2.open_embedding_subtype_coe, λ H, _⟩, rw is_jacobson_iff_locally_closed, intros Z hZ hZ', have : (⋃ i, (U i : set α)) = set.univ, { rw ← opens.coe_supr, injection hU }, have : (⋃ i, Z ∩ U i) = Z, { rw [← set.inter_Union, this, set.inter_univ] }, rw [← this, set.nonempty_Union] at hZ, obtain ⟨i, x, hx, hx'⟩ := hZ, obtain ⟨y, hy, hy'⟩ := (is_jacobson_iff_locally_closed.mp $ H i) (coe ⁻¹' Z) ⟨⟨x, hx'⟩, hx⟩ (hZ'.preimage continuous_subtype_coe), refine ⟨y, hy, (is_closed_iff_coe_preimage_of_supr_eq_top hU _).mpr $ λ j, _⟩, by_cases (y : α) ∈ U j, { convert_to is_closed {(⟨y, h⟩ : U j)}, { ext z, exact @subtype.coe_inj _ _ z ⟨y, h⟩ }, apply (H j).is_closed_of_is_locally_closed, convert (hy'.is_locally_closed.image embedding_subtype_coe.to_inducing (U i).2.open_embedding_subtype_coe.open_range.is_locally_closed).preimage continuous_subtype_coe, rw set.image_singleton, ext z, exact (@subtype.coe_inj _ _ z ⟨y, h⟩).symm }, { convert is_closed_empty, rw set.eq_empty_iff_forall_not_mem, rintros z (hz : ↑z = ↑y), rw ← hz at h, exact h z.2 } end end topological_space
! ################################################################################################################################## ! Begin MIT license text. ! _______________________________________________________________________________________________________ ! Copyright 2019 Dr William R Case, Jr ([email protected]) ! Permission is hereby granted, free of charge, to any person obtaining a copy of this software and ! associated documentation files (the "Software"), to deal in the Software without restriction, including ! without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ! copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to ! the following conditions: ! The above copyright notice and this permission notice shall be included in all copies or substantial ! portions of the Software and documentation. ! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ! OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ! THE SOFTWARE. ! _______________________________________________________________________________________________________ ! End MIT license text. SUBROUTINE PROCESS_INCLUDE_FILES ( NUM_INCL_FILES ) ! PROCESS_INCLUDE_FILES reads in the complete Bulk Data file, checks for INCLUDE files and calls 2 subrs to process them. ! At completion, a new data file is created (IN0FIL on unit IN0) which has the original Bulk Data file plus the contents of all of ! the INCLUDE files. This file then becomes the input file by re-opening it as INFILE (the normal input file) USE PENTIUM_II_KIND, ONLY : BYTE, LONG, DOUBLE USE IOUNT1, ONLY : ERR, F04, F06, IN0, IN1, INC, INFILE, WRT_LOG USE SCONTR, ONLY : BLNK_SUB_NAM, EC_ENTRY_LEN, FATAL_ERR USE TIMDAT, ONLY : TSEC USE SUBR_BEGEND_LEVELS, ONLY : PROCESS_INCLUDE_FILES_BEGEND USE PROCESS_INCLUDE_FILES_USE_IFs IMPLICIT NONE CHARACTER(LEN=LEN(BLNK_SUB_NAM)):: SUBR_NAME = 'PROCESS_INCLUDE_FILES' CHARACTER(LEN=EC_ENTRY_LEN) :: CARD ! Exec Control deck card CHARACTER(LEN=EC_ENTRY_LEN) :: CARD1 ! CARD shifted to begin in col 1 INTEGER(LONG), INTENT(OUT) :: NUM_INCL_FILES ! Number of INCLUDE files in the Bulk Data file INTEGER(LONG) :: CHAR_COL ! Column number on CARD where character CHAR is found INTEGER(LONG) :: IERR = 0 ! Error indicator. INTEGER(LONG) :: IOCHK ! IOSTAT error number when reading a Case Control card from unit IN1 INTEGER(LONG), PARAMETER :: SUBR_BEGEND = PROCESS_INCLUDE_FILES_BEGEND ! ********************************************************************************************************************************** IF (WRT_LOG >= SUBR_BEGEND) THEN CALL OURTIM WRITE(F04,9001) SUBR_NAME,TSEC 9001 FORMAT(1X,A,' BEGN ',F10.3) ENDIF ! ********************************************************************************************************************************** ! Initialize NUM_INCL_FILES = 0 main: DO READ(IN1,101,IOSTAT=IOCHK) CARD ! Exit when the complete Bulk Data file has been read IF (IOCHK < 0) THEN EXIT main ENDIF IF (IOCHK > 0) THEN ! Check if error occurs during read WRITE(ERR,1010) WRITE(F06,1010) WRITE(F06,'(A)') CARD FATAL_ERR = FATAL_ERR + 1 CYCLE main ELSE WRITE(IN0,101,IOSTAT=IOCHK) CARD ENDIF CALL CSHIFT ( CARD, ' ', CARD1, CHAR_COL, IERR ) IERR = 0 IF (CARD1(1:7) == 'INCLUDE' ) THEN NUM_INCL_FILES = NUM_INCL_FILES + 1 CALL READ_INCLUDE_FILNAM ( CARD1, IERR ) IF (IERR == 0) THEN CALL RW_INCLUDE_FILES ( INC, IN0 ) ENDIF ENDIF ENDDO main ! ********************************************************************************************************************************** IF (WRT_LOG >= SUBR_BEGEND) THEN CALL OURTIM WRITE(F04,9002) SUBR_NAME,TSEC 9002 FORMAT(1X,A,' END ',F10.3) ENDIF RETURN ! ********************************************************************************************************************************** 101 FORMAT(A) 1010 FORMAT(' *ERROR 1010: ERROR READING FOLLOWING ENTRY FROM BULK DATA FILE WHILE SEARCHING FOR INCLUDE FILES . ENTRY IGNORED') 1011 FORMAT(' *ERROR 1011: NO ',A10,' ENTRY FOUND BEFORE END OF FILE OR END OF RECORD IN INPUT FILE') ! ********************************************************************************************************************************** END SUBROUTINE PROCESS_INCLUDE_FILES
lemma locally_connected_UNIV: "locally connected (UNIV::'a :: real_normed_vector set)"
REBOL[] args: parse system/script/args "" exe: none payload: none output: none as-is: false ;don't compress, in case people try to avoid decompression to speed up bootup windows?: 3 = fourth system/version while [not tail? args] [ arg: first args case [ any [arg = "/rebol" arg = "/r"] [ exe: second args args: next args ] any [arg = "/payload" arg = "/p"] [ payload: second args args: next args ] any [arg = "/output" arg = "/o"] [ output: second args args: next args ] any [arg = "/as-is" arg = "/a"] [ as-is: true ] ] args: next args ] if any [none? exe none? payload none? output][ print ["pack.r"] print ["^-/rebol | /r^- path-to-rebol"] print ["^-/payload | /p^- path-to-payload"] print ["^-/output | /o^- path-to-output"] print ["^-/as-is | /a^- Do not compress the script"] quit ] payload-data: read to file! payload either as-is [ payload-data: join #{00000000} payload-data ][ payload-data: join #{01000000} compress payload-data ] tmp: join payload ".tmp" write to file! tmp payload-data either windows? [ unicodify: function [ s [string!] ][ ret: copy #{} foreach c s [ append ret join to binary! c #{00} ] join ret #{0000} ;NULL terminator ] kernel32: make library! %kernel32 print ["kernel:" mold kernel32] BeginUpdateResource: make routine! compose [[ filename [pointer] delete-existing-resources [int32] return: [pointer] ] (kernel32) "BeginUpdateResourceW"] UpdateResource: make routine! compose [[ hUpdate [pointer] lpType [pointer] lpName [pointer] wLanguage [uint16] lpData [pointer] cbData [uint32] return: [int32] ] (kernel32) "UpdateResourceW"] EndUpdateResource: make routine! compose [[ hUpdate [pointer] fDiscard [uint8] return: [int32] ] (kernel32) "EndUpdateResourceW"] GetLastError: make routine! compose [[ return: [uint32] ] (kernel32) "GetLastError"] write to file! output read to file! exe h: BeginUpdateResource unicodify output 0 if zero? h [ print ["failed to open exe"] halt ] if zero? UpdateResource h 10 unicodify "EmbEddEdREbol" 0 payload-data length? payload-data [ print ["failed to update resource"] halt ] if zero? EndUpdateResource h 0 [ print ["failed to write change back to the file due to " GetLastError] halt ] ][ magic: ".EmbEddEdREbol" call reform ["objcopy -R" magic exe] call rejoin ["objcopy --add-section " magic "=" tmp " " exe " " output] delete to file! tmp ]
Require Export P05. (** **** Exercise: 2 stars (slow_assignment) *) (** A roundabout way of assigning a number currently stored in [X] to the variable [Y] is to start [Y] at [0], then decrement [X] until it hits [0], incrementing [Y] at each step. Here is a program that implements this idea: {{ X = m }} Y ::= 0;; WHILE X <> 0 DO X ::= X - 1;; Y ::= Y + 1 END {{ Y = m }} Write an informal decorated program showing that this is correct. *) Theorem slow_assignment : forall m, {{ fun st => st X = m }} Y ::= ANum 0;; WHILE BNot (BEq (AId X) (ANum 0)) DO X ::= AMinus (AId X) (ANum 1);; Y ::= APlus (AId Y) (ANum 1) END {{ fun st => st Y = m }}. Proof. intros. (* {{P}} c;;while {{R}} *) eapply hoare_seq with (Q:= (fun st => st X + st Y= m)). (* Q = P /\ Y=0 *) Case "{{Q}} while {{R}} ". eapply hoare_consequence_post. SCase "{{Q}} while {{R'}}". apply hoare_while. (* R' = Q/\~b *) (* now need to show that {{Q/\b}} c1;;c2 {{Q}} *) simpl. eapply hoare_seq. SSCase "{{Q'}} c2 {{R'}}". apply hoare_asgn. SSCase "{{Q/\b}} c1 {{Q'}}". eapply hoare_consequence_pre. (* {{Q''}} c1 {{Q'}} *) apply hoare_asgn. (* Q/\b ->> Q'' *) unfold assert_implies, assn_sub. intros; simpl. unfold update. simpl. destruct H. rewrite<-H. apply negb_true_iff in H0. apply beq_nat_false_iff in H0. (* We need the condition that xt X > 0 to use omega here *) omega. SCase "R' ->> R". unfold hoare_triple, assert_implies. intros. destruct H. simpl in H0. apply negb_false in H0. apply beq_nat_true_iff in H0. omega. Case "{{P}} c {{Q}}". unfold hoare_triple. intros. inversion H; subst. simpl. unfold update. simpl. omega. Qed.
Require Export Fiat.Common.Coq__8_4__8_5__Compat. (** * Implementation of simply-typed interface of the parser *) Require Import Coq.ZArith.ZArith. Require Export Fiat.Parsers.ParserInterface. Require Import Fiat.Parsers.ContextFreeGrammar.Core. Require Import Fiat.Parsers.ContextFreeGrammar.Properties. Require Import Fiat.Parsers.ContextFreeGrammar.PreNotations. Require Import Fiat.Parsers.BooleanRecognizer Fiat.Parsers.BooleanRecognizerCorrect. Require Import Fiat.Parsers.RecognizerPreOptimized. Require Fiat.Parsers.SimpleRecognizer. Require Fiat.Parsers.SimpleRecognizerExt. Require Fiat.Parsers.SimpleBooleanRecognizerEquality. Require Fiat.Parsers.SimpleRecognizerCorrect. Require Import Fiat.Parsers.Splitters.RDPList. Require Import Fiat.Parsers.BaseTypes Fiat.Parsers.CorrectnessBaseTypes. Require Import Fiat.Parsers.StringLike.Properties. Require Import Fiat.Parsers.MinimalParseOfParse. Require Import Fiat.Common. Set Implicit Arguments. Local Open Scope list_scope. Section implementation. Context {Char} {G : pregrammar' Char}. Context (splitter : Splitter G). Let predata := @rdp_list_predata _ G. Local Existing Instance predata. Let parser_presplit_data : @split_dataT Char (string_type_min splitter) _. Proof. refine {| split_string_for_production idx str := splits_for splitter str idx |}. Defined. Local Instance parser_split_data : @split_dataT Char splitter predata := @optsplitdata _ _ _ parser_presplit_data. Local Instance preparser_data : @boolean_parser_dataT Char _ := { predata := rdp_list_predata (G := G); split_data := parser_presplit_data }. Local Instance parser_data : @boolean_parser_dataT Char _ := { predata := rdp_list_predata (G := G); split_data := parser_split_data }. Local Arguments split_string_for_production : simpl never. Local Obligation Tactic := intros. Local Program Instance parser_precompleteness_data : @boolean_parser_completeness_dataT' Char _ _ G preparser_data := { split_string_for_production_complete len0 valid str offset len pf nt Hvalid := _ }. Next Obligation. apply initial_nonterminals_correct in Hvalid. generalize (fun it its idx offset len Hvalid' Heqb n pf pf' pit pits prefix H' => @splits_for_complete Char G splitter str idx offset len Hvalid' Heqb it its n pf pf' (ex_intro _ nt (ex_intro _ prefix (conj Hvalid H'))) pit pits). clear Hvalid. induction (G nt) as [ | x xs IHxs ]. { intros; constructor. } { intros H'. simpl. split; [ clear IHxs | apply IHxs; trivial; intros; eapply H'; try eassumption; [ right; eassumption ] ]. specialize (fun prefix idx it its H Hvalid' n offset len Heqb pf pf' pit pits => H' it its idx offset len Hvalid' Heqb n pf pf' pit pits prefix (or_introl H)). clear -H' H. induction x as [ | it its IHx ]. { simpl; constructor. } { simpl. split; [ clear IHx | apply IHx; intros; subst; eapply (H' (_::_)); try eassumption; reflexivity ]. intros idx Hvalid Heqb. specialize (H' nil idx _ _ eq_refl). specialize_by assumption. specialize (H' _ _ H). hnf. intros [ n [ pit pits ] ]; simpl in * |- . destruct (Compare_dec.le_ge_dec n (length (substring offset len str))). { exists n; repeat split; eauto. specialize (fun pf => H' _ pf (parse_of_item__of__minimal_parse_of_item pit) (parse_of_production__of__minimal_parse_of_production pits)). specialize_by assumption. rewrite Min.min_r by assumption. apply H'; eauto. } { exists (length (substring offset len str)). specialize (H' _ (reflexivity _)). rewrite Min.min_idempotent. rewrite !substring_length_no_min in * by assumption. repeat match goal with | [ H : context[length (substring _ _ _)] |- _ ] => rewrite !substring_length_no_min in H by assumption end. pose proof (fun H => expand_minimal_parse_of_item (str' := take len (substring offset len str)) (or_introl (reflexivity _)) (reflexivity _) (or_introl (reflexivity _)) H pit) as pit'; clear pit. pose proof (fun H => expand_minimal_parse_of_production (str' := drop len (substring offset len str)) (or_introl (reflexivity _)) (reflexivity _) (or_introl (reflexivity _)) H pits) as pits'; clear pits. set (s := substring offset len str) in *. specialize_by (first [ rewrite ?take_long, ?drop_long by first [ subst s; reflexivity | subst s; rewrite substring_length_no_min by assumption; omega ]; reflexivity | apply bool_eq_empty; rewrite ?drop_length; subst s; rewrite substring_length_no_min by assumption; omega ]). specialize_by assumption. repeat split; try assumption. apply H'. { eapply (@parse_of_item__of__minimal_parse_of_item Char splitter _ _ _ _); eassumption. } { eapply (@parse_of_production__of__minimal_parse_of_production Char splitter _ _ _ _ _); eassumption. } } } } Qed. Local Instance parser_completeness_data : @boolean_parser_completeness_dataT' Char _ _ G parser_data := optsplitdata_correct. Local Obligation Tactic := program_simpl. Program Definition parser : Parser G splitter := {| has_parse str := parse_nonterminal (data := parser_data) str (Start_symbol G); parse str := option_map (SimpleParseNonTerminal (Start_symbol G)) (SimpleRecognizer.parse_nonterminal (data := parser_data) str (Start_symbol G)); has_parse_sound str Hparse := parse_nonterminal_sound (data := parser_data) _ _ Hparse; has_parse_complete str p := _; parse_sound str p := _ |}. Next Obligation. Proof. dependent destruction p. pose proof (fun pf => @parse_of_nonterminal_complete Char splitter _ _ G _ _ rdp_list_rdata' str (Start_symbol G) pf p) as H'. apply H'; assumption. Qed. Next Obligation. Proof. erewrite SimpleBooleanRecognizerEquality.parse_nonterminal_eq; simpl; unfold option_map. destruct SimpleRecognizer.parse_nonterminal; reflexivity. Qed. Next Obligation. Proof. eapply SimpleRecognizerCorrect.parse_item_correct. unfold option_map in *; simpl in *. unfold SimpleRecognizer.parse_nonterminal, GenericRecognizer.parse_nonterminal in *; simpl in *. rewrite <- H; clear H p. repeat match goal with | _ => reflexivity | [ |- context[match ?e with _ => _ end] ] => destruct e eqn:? | _ => progress simpl in * end. unfold SimpleRecognizer.parse_nonterminal', SimpleRecognizer.parse_nonterminal_or_abort, GenericRecognizer.parse_nonterminal', GenericRecognizer.parse_nonterminal_or_abort in *. let H := match goal with H : context[Fix] |- _ => H end in rewrite Common.Wf1.Fix5_eq in H by (intros; eapply SimpleRecognizerExt.parse_nonterminal_step_ext; assumption); unfold GenericRecognizer.parse_nonterminal_step at 1 in H. simpl in *. edestruct Compare_dec.lt_dec; simpl in *; try omega; []. edestruct dec; simpl in *; try congruence; []. edestruct negb; simpl in *; congruence. Unshelve. assumption. assumption. Qed. End implementation.
Formal statement is: lemma connectedD_const: "connected S \<Longrightarrow> continuous_on S P \<Longrightarrow> \<exists>c. \<forall>s\<in>S. P s = c" for P :: "'a::topological_space \<Rightarrow> bool" Informal statement is: If $S$ is a connected set and $P$ is a continuous function on $S$, then $P$ is constant.
subroutine init_ipi(n_a1,n_alpha,n_beta,n_iPHI,n_ipsidot,Nx,res) implicit none integer i integer Nx real*8 n_a1(Nx) real*8 n_alpha(Nx) real*8 n_beta(Nx) real*8 n_iPHI(Nx) real*8 n_ipsidot(Nx) real*8 res(Nx) real*8 qb do i=1, Nx, 1 qb = n_a1(i) / n_alpha(i) * (n_ipsidot(i) - 0.1D1 * n_beta(i) * n_ #iPHI(i)) res(i)=qb end do END
import LMT variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)] example {a1 a2 a3 : A I E} : ((((a1).write i1 (v2)).write i3 (v2)).read i1) ≠ (v2) → False := by arr
lemmas continuous_of_real [continuous_intros] = bounded_linear.continuous [OF bounded_linear_of_real]
Require Import Integers. Require Import Coqlib. Require Import Coq.Strings.String. Require Import Coq.Strings.Ascii. Require Import List. Require Import sha.SHA256. Require Import sha.functional_prog. Notation "[ ]" := nil. Notation "[ x , .. , y ]" := (cons x .. (cons y []) ..). (*SHA256: blocksize = 64bytes corresponds to #define SHA_LBLOCK 16 #define SHA256_CBLOCK (SHA_LBLOCK*4) *) Fixpoint Nlist {A} (i:A) n: list A:= match n with O => nil | S m => i :: Nlist i m end. Definition sixtyfour {A} (i:A): list A:= Nlist i 64%nat. Definition SHA256_DIGEST_LENGTH := 32. Definition SHA256_BlockSize := 64%nat. Definition Ipad := Byte.repr 54. (*0x36*) Definition Opad := Byte.repr 92. (*0x5c*) Module HMAC_FUN. (*Reading rfc4231 reveals that padding happens on the right*) Definition zeroPad (k: list Z) : list Z := k ++ Nlist Z0 (SHA256_BlockSize-length k). Definition mkKey (l:list Z) : list Z := if Z.gtb (Zlength l) (Z.of_nat SHA256_BlockSize) then (zeroPad (SHA_256' l)) else zeroPad l. Definition mkArg (key:list byte) (pad:byte): list byte := (map (fun p => Byte.xor (fst p) (snd p)) (combine key (sixtyfour pad))). Definition mkArgZ key (pad:byte): list Z := map Byte.unsigned (mkArg key pad). (*innerArg to be applied to message, (map Byte.repr (mkKey password)))*) Definition innerArg (text: list Z) key : list Z := (mkArgZ key Ipad) ++ text. Definition INNER k text := SHA_256' (innerArg text k). Definition outerArg (innerRes: list Z) key: list Z := (mkArgZ key Opad) ++ innerRes. Definition OUTER k innerRes := SHA_256' (outerArg innerRes k). Definition HMAC txt password: list Z := let key := map Byte.repr (mkKey password) in OUTER key (INNER key txt). Definition HMACString (txt passwd:string): list Z := HMAC (str_to_Z txt) (str_to_Z passwd). Definition HMACHex (text password:string): list Z := HMAC (hexstring_to_Zlist text) (hexstring_to_Zlist password). Definition check password text digest := listZ_eq (HMACString text password) (hexstring_to_Zlist digest) = true. (*a random example, solution obtained via http://www.freeformatter.com/hmac-generator.html#ad-output*) Goal check "bb" "aa" "c1201d3dccfb84c069771d07b3eda4dc26e5b34a4d8634b2bba84fb54d11e265". vm_compute. reflexivity. Qed. Lemma RFC4231_exaple4_2: check "Jefe" "what do ya want for nothing?" "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843". vm_compute. reflexivity. Qed. Definition checkHex password text digest := listZ_eq (HMACHex text password) (hexstring_to_Zlist digest) = true. Lemma RFC6868_example4_2hex: checkHex "4a656665" "7768617420646f2079612077616e7420666f72206e6f7468696e673f" "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843". vm_compute. reflexivity. Qed. Lemma RFC6868_example4_5hex: checkHex "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a65204b6579202d2048617368204b6579204669727374" "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54". vm_compute. reflexivity. Qed. Lemma RFC6868_exampleAUTH256_2: checkHex "4a6566654a6566654a6566654a6566654a6566654a6566654a6566654a656665" "7768617420646f2079612077616e7420666f72206e6f7468696e673f" "167f928588c5cc2eef8e3093caa0e87c9ff566a14794aa61648d81621a2a40c6". vm_compute. reflexivity. Qed. End HMAC_FUN.
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import analysis.calculus.mean_value import data.complex.exponential import formal_ml.convex_optimization --import formal_ml.analytic_function import analysis.special_functions.exp_log import formal_ml.nnreal /- Note: after I proved this, I found that it already was in mathlib. -/ --TODO: lift this until it doesn't depend upon has_derivative lemma has_derivative_exp:has_derivative real.exp real.exp := begin unfold has_derivative, intro x, apply real.has_deriv_at_exp, end lemma exp_bound3 (x:real):0 ≤ real.exp x - (x + 1) := begin let f:=λ x,real.exp x - (x + 1), let f':=λ x,real.exp x - 1, let f'':=λ x,real.exp x, begin have f_def:f=λ x,real.exp x - (x + 1), { refl, }, have f_def':f'=λ x,real.exp x - 1, { refl, }, have f_def'':f''=λ x,real.exp x, { refl, }, have A1:has_derivative f f', { rw f_def, rw f_def', apply has_derivative_sub real.exp real.exp (λ x, (x + 1)) (1), { apply has_derivative_exp, }, { apply has_derivative_add_const, apply has_derivative_id, }, }, have A2:has_derivative f' f'', { apply has_derivative_add_const, apply has_derivative_exp, }, have A3:∀ y, f 0 ≤ f y, { intro y, apply is_minimum, { apply A1, }, { apply A2, }, { intro z, rw f_def'', apply le_of_lt, apply real.exp_pos, }, have A3D:f' 0 = real.exp 0 - 1, { refl, }, rw A3D, simp, }, have A4:f 0 = 0, { rw f_def, simp, }, rw A4 at A3, have A5:f x = real.exp x - (x + 1), { refl, }, rw ← A5, apply A3, end end lemma exp_bound2 (x:real):1 - x ≤ real.exp(-x) := begin have A1:0 ≤ real.exp(-x) - ((-x) + 1), { apply exp_bound3, }, have A2:((-x) + 1) ≤ real.exp(-x) := le_of_sub_nonneg A1, rw add_comm at A2, rw sub_eq_add_neg, exact A2, end --TODO: verify this is exactly what we need first. lemma nnreal_exp_bound (x:nnreal):(1-x) ≤ nnreal.exp(-x) := begin apply nnreal.coe_le_coe.mp, rw nnreal_exp_eq, have A1:((x:real) ≤ 1) ∨ (1 ≤ (x:real)), { apply linear_order.le_total, }, cases A1, { rw nnreal.coe_sub, apply exp_bound2 (↑x), apply A1, }, { rw nnreal.sub_eq_zero, { apply le_of_lt, apply real.exp_pos, }, { apply A1, } } end --This exact theorem is used for PAC bounds. lemma nnreal_exp_bound2 (x:nnreal) (k:ℕ):(1 - x)^k ≤ nnreal.exp(-x * k) := begin have A1:(1-x) ≤ nnreal.exp(-x), { apply nnreal_exp_bound, }, have A2:(1 - x)^k ≤ (nnreal.exp(-x))^k, { apply nnreal_pow_mono, exact A1, }, have A3:nnreal.exp(-x)^k=nnreal.exp(-x * k), { symmetry, rw mul_comm, apply nnreal_exp_pow, }, rw ← A3, apply A2, end
(******************************************************************************) (* Project: Isabelle/UTP: Unifying Theories of Programming in Isabelle/HOL *) (* File: unrest_sf.thy *) (* Authors: Frank Zeyda and Simon Foster (University of York, UK) *) (* Emails: [email protected] and [email protected] *) (******************************************************************************) (* LAST REVIEWED: 09 Jun 2022 *) section \<open>Unrestriction\<close> theory unrest_sf imports uvar ustate begin default_sort type subsection \<open>Definition of Unrestriction\<close> definition unrest_sf :: "uvar set \<Rightarrow> (ustate \<Rightarrow> 'a) \<Rightarrow> bool" where "unrest_sf vs f = (\<forall>v\<in>vs. \<forall>s x. f s(v :=\<^sub>u x)\<^sub>s = f s)" subsection \<open>Theorems\<close> theorem unrest_sf_empty: "unrest_sf {} f" apply (unfold unrest_sf_def) apply (clarsimp) done theorem unrest_sf_subset: "vs1 \<subseteq> vs2 \<Longrightarrow> unrest_sf vs2 f \<Longrightarrow> unrest_sf vs1 f" apply (unfold unrest_sf_def) apply (blast) done theorem unrest_sf_const: "unrest_sf vs (\<lambda>_. c)" apply (unfold unrest_sf_def) apply (clarsimp) done theorem unrest_sf_uvar: "unrest_sf (vs - {v}) (\<lambda>s. f s\<cdot>v)" apply (unfold unrest_sf_def) apply (transfer) apply (clarsimp) done theorem unrest_sf_var: "unrest_sf (vs - {v\<down>}) (\<lambda>s. f s\<star>v)" apply (unfold unrest_sf_def) apply (transfer) apply (clarsimp) done end
(* Title: HOL/Divides.thy Author: Lawrence C Paulson, Cambridge University Computer Laboratory Copyright 1999 University of Cambridge *) section \<open>The division operators div and mod\<close> theory Divides imports Parity begin subsection \<open>Abstract division in commutative semirings.\<close> class semiring_div = semidom + semiring_modulo + assumes div_by_0: "a div 0 = 0" and div_0: "0 div a = 0" and div_mult_self1 [simp]: "b \<noteq> 0 \<Longrightarrow> (a + c * b) div b = c + a div b" and div_mult_mult1 [simp]: "c \<noteq> 0 \<Longrightarrow> (c * a) div (c * b) = a div b" begin subclass algebraic_semidom proof fix b a assume "b \<noteq> 0" then show "a * b div b = a" using div_mult_self1 [of b 0 a] by (simp add: ac_simps div_0) qed (simp add: div_by_0) text \<open>@{const divide} and @{const modulo}\<close> lemma mod_by_0 [simp]: "a mod 0 = a" using div_mult_mod_eq [of a zero] by simp lemma mod_0 [simp]: "0 mod a = 0" using div_mult_mod_eq [of zero a] div_0 by simp lemma div_mult_self2 [simp]: assumes "b \<noteq> 0" shows "(a + b * c) div b = c + a div b" using assms div_mult_self1 [of b a c] by (simp add: mult.commute) lemma div_mult_self3 [simp]: assumes "b \<noteq> 0" shows "(c * b + a) div b = c + a div b" using assms by (simp add: add.commute) lemma div_mult_self4 [simp]: assumes "b \<noteq> 0" shows "(b * c + a) div b = c + a div b" using assms by (simp add: add.commute) lemma mod_mult_self1 [simp]: "(a + c * b) mod b = a mod b" proof (cases "b = 0") case True then show ?thesis by simp next case False have "a + c * b = (a + c * b) div b * b + (a + c * b) mod b" by (simp add: div_mult_mod_eq) also from False div_mult_self1 [of b a c] have "\<dots> = (c + a div b) * b + (a + c * b) mod b" by (simp add: algebra_simps) finally have "a = a div b * b + (a + c * b) mod b" by (simp add: add.commute [of a] add.assoc distrib_right) then have "a div b * b + (a + c * b) mod b = a div b * b + a mod b" by (simp add: div_mult_mod_eq) then show ?thesis by simp qed lemma mod_mult_self2 [simp]: "(a + b * c) mod b = a mod b" by (simp add: mult.commute [of b]) lemma mod_mult_self3 [simp]: "(c * b + a) mod b = a mod b" by (simp add: add.commute) lemma mod_mult_self4 [simp]: "(b * c + a) mod b = a mod b" by (simp add: add.commute) lemma mod_mult_self1_is_0 [simp]: "b * a mod b = 0" using mod_mult_self2 [of 0 b a] by simp lemma mod_mult_self2_is_0 [simp]: "a * b mod b = 0" using mod_mult_self1 [of 0 a b] by simp lemma mod_by_1 [simp]: "a mod 1 = 0" proof - from div_mult_mod_eq [of a one] div_by_1 have "a + a mod 1 = a" by simp then have "a + a mod 1 = a + 0" by simp then show ?thesis by (rule add_left_imp_eq) qed lemma mod_self [simp]: "a mod a = 0" using mod_mult_self2_is_0 [of 1] by simp lemma div_add_self1: assumes "b \<noteq> 0" shows "(b + a) div b = a div b + 1" using assms div_mult_self1 [of b a 1] by (simp add: add.commute) lemma div_add_self2: assumes "b \<noteq> 0" shows "(a + b) div b = a div b + 1" using assms div_add_self1 [of b a] by (simp add: add.commute) lemma mod_add_self1 [simp]: "(b + a) mod b = a mod b" using mod_mult_self1 [of a 1 b] by (simp add: add.commute) lemma mod_add_self2 [simp]: "(a + b) mod b = a mod b" using mod_mult_self1 [of a 1 b] by simp lemma dvd_imp_mod_0 [simp]: assumes "a dvd b" shows "b mod a = 0" proof - from assms obtain c where "b = a * c" .. then have "b mod a = a * c mod a" by simp then show "b mod a = 0" by simp qed lemma mod_eq_0_iff_dvd: "a mod b = 0 \<longleftrightarrow> b dvd a" proof assume "b dvd a" then show "a mod b = 0" by simp next assume "a mod b = 0" with div_mult_mod_eq [of a b] have "a div b * b = a" by simp then have "a = b * (a div b)" by (simp add: ac_simps) then show "b dvd a" .. qed lemma dvd_eq_mod_eq_0 [nitpick_unfold, code]: "a dvd b \<longleftrightarrow> b mod a = 0" by (simp add: mod_eq_0_iff_dvd) lemma mod_div_trivial [simp]: "a mod b div b = 0" proof (cases "b = 0") assume "b = 0" thus ?thesis by simp next assume "b \<noteq> 0" hence "a div b + a mod b div b = (a mod b + a div b * b) div b" by (rule div_mult_self1 [symmetric]) also have "\<dots> = a div b" by (simp only: mod_div_mult_eq) also have "\<dots> = a div b + 0" by simp finally show ?thesis by (rule add_left_imp_eq) qed lemma mod_mod_trivial [simp]: "a mod b mod b = a mod b" proof - have "a mod b mod b = (a mod b + a div b * b) mod b" by (simp only: mod_mult_self1) also have "\<dots> = a mod b" by (simp only: mod_div_mult_eq) finally show ?thesis . qed lemma dvd_mod_imp_dvd: assumes "k dvd m mod n" and "k dvd n" shows "k dvd m" proof - from assms have "k dvd (m div n) * n + m mod n" by (simp only: dvd_add dvd_mult) then show ?thesis by (simp add: div_mult_mod_eq) qed text \<open>Addition respects modular equivalence.\<close> lemma mod_add_left_eq: \<comment> \<open>FIXME reorient\<close> "(a + b) mod c = (a mod c + b) mod c" proof - have "(a + b) mod c = (a div c * c + a mod c + b) mod c" by (simp only: div_mult_mod_eq) also have "\<dots> = (a mod c + b + a div c * c) mod c" by (simp only: ac_simps) also have "\<dots> = (a mod c + b) mod c" by (rule mod_mult_self1) finally show ?thesis . qed lemma mod_add_right_eq: \<comment> \<open>FIXME reorient\<close> "(a + b) mod c = (a + b mod c) mod c" proof - have "(a + b) mod c = (a + (b div c * c + b mod c)) mod c" by (simp only: div_mult_mod_eq) also have "\<dots> = (a + b mod c + b div c * c) mod c" by (simp only: ac_simps) also have "\<dots> = (a + b mod c) mod c" by (rule mod_mult_self1) finally show ?thesis . qed lemma mod_add_eq: \<comment> \<open>FIXME reorient\<close> "(a + b) mod c = (a mod c + b mod c) mod c" by (rule trans [OF mod_add_left_eq mod_add_right_eq]) lemma mod_add_cong: assumes "a mod c = a' mod c" assumes "b mod c = b' mod c" shows "(a + b) mod c = (a' + b') mod c" proof - have "(a mod c + b mod c) mod c = (a' mod c + b' mod c) mod c" unfolding assms .. thus ?thesis by (simp only: mod_add_eq [symmetric]) qed text \<open>Multiplication respects modular equivalence.\<close> lemma mod_mult_left_eq: \<comment> \<open>FIXME reorient\<close> "(a * b) mod c = ((a mod c) * b) mod c" proof - have "(a * b) mod c = ((a div c * c + a mod c) * b) mod c" by (simp only: div_mult_mod_eq) also have "\<dots> = (a mod c * b + a div c * b * c) mod c" by (simp only: algebra_simps) also have "\<dots> = (a mod c * b) mod c" by (rule mod_mult_self1) finally show ?thesis . qed lemma mod_mult_right_eq: \<comment> \<open>FIXME reorient\<close> "(a * b) mod c = (a * (b mod c)) mod c" proof - have "(a * b) mod c = (a * (b div c * c + b mod c)) mod c" by (simp only: div_mult_mod_eq) also have "\<dots> = (a * (b mod c) + a * (b div c) * c) mod c" by (simp only: algebra_simps) also have "\<dots> = (a * (b mod c)) mod c" by (rule mod_mult_self1) finally show ?thesis . qed lemma mod_mult_eq: \<comment> \<open>FIXME reorient\<close> "(a * b) mod c = ((a mod c) * (b mod c)) mod c" by (rule trans [OF mod_mult_left_eq mod_mult_right_eq]) lemma mod_mult_cong: assumes "a mod c = a' mod c" assumes "b mod c = b' mod c" shows "(a * b) mod c = (a' * b') mod c" proof - have "(a mod c * (b mod c)) mod c = (a' mod c * (b' mod c)) mod c" unfolding assms .. thus ?thesis by (simp only: mod_mult_eq [symmetric]) qed text \<open>Exponentiation respects modular equivalence.\<close> lemma power_mod: "(a mod b) ^ n mod b = a ^ n mod b" apply (induct n, simp_all) apply (rule mod_mult_right_eq [THEN trans]) apply (simp (no_asm_simp)) apply (rule mod_mult_eq [symmetric]) done lemma mod_mod_cancel: assumes "c dvd b" shows "a mod b mod c = a mod c" proof - from \<open>c dvd b\<close> obtain k where "b = c * k" by (rule dvdE) have "a mod b mod c = a mod (c * k) mod c" by (simp only: \<open>b = c * k\<close>) also have "\<dots> = (a mod (c * k) + a div (c * k) * k * c) mod c" by (simp only: mod_mult_self1) also have "\<dots> = (a div (c * k) * (c * k) + a mod (c * k)) mod c" by (simp only: ac_simps) also have "\<dots> = a mod c" by (simp only: div_mult_mod_eq) finally show ?thesis . qed lemma div_mult_mult2 [simp]: "c \<noteq> 0 \<Longrightarrow> (a * c) div (b * c) = a div b" by (drule div_mult_mult1) (simp add: mult.commute) lemma div_mult_mult1_if [simp]: "(c * a) div (c * b) = (if c = 0 then 0 else a div b)" by simp_all lemma mod_mult_mult1: "(c * a) mod (c * b) = c * (a mod b)" proof (cases "c = 0") case True then show ?thesis by simp next case False from div_mult_mod_eq have "((c * a) div (c * b)) * (c * b) + (c * a) mod (c * b) = c * a" . with False have "c * ((a div b) * b + a mod b) + (c * a) mod (c * b) = c * a + c * (a mod b)" by (simp add: algebra_simps) with div_mult_mod_eq show ?thesis by simp qed lemma mod_mult_mult2: "(a * c) mod (b * c) = (a mod b) * c" using mod_mult_mult1 [of c a b] by (simp add: mult.commute) lemma mult_mod_left: "(a mod b) * c = (a * c) mod (b * c)" by (fact mod_mult_mult2 [symmetric]) lemma mult_mod_right: "c * (a mod b) = (c * a) mod (c * b)" by (fact mod_mult_mult1 [symmetric]) lemma dvd_mod: "k dvd m \<Longrightarrow> k dvd n \<Longrightarrow> k dvd (m mod n)" unfolding dvd_def by (auto simp add: mod_mult_mult1) lemma dvd_mod_iff: "k dvd n \<Longrightarrow> k dvd (m mod n) \<longleftrightarrow> k dvd m" by (blast intro: dvd_mod_imp_dvd dvd_mod) lemma div_div_eq_right: assumes "c dvd b" "b dvd a" shows "a div (b div c) = a div b * c" proof - from assms have "a div b * c = (a * c) div b" by (subst dvd_div_mult) simp_all also from assms have "\<dots> = (a * c) div ((b div c) * c)" by simp also have "a * c div (b div c * c) = a div (b div c)" by (cases "c = 0") simp_all finally show ?thesis .. qed lemma div_div_div_same: assumes "d dvd a" "d dvd b" "b dvd a" shows "(a div d) div (b div d) = a div b" using assms by (subst dvd_div_mult2_eq [symmetric]) simp_all lemma cancel_div_mod_rules: "((a div b) * b + a mod b) + c = a + c" "(b * (a div b) + a mod b) + c = a + c" by (simp_all add: div_mult_mod_eq mult_div_mod_eq) end class ring_div = comm_ring_1 + semiring_div begin subclass idom_divide .. text \<open>Negation respects modular equivalence.\<close> lemma mod_minus_eq: "(- a) mod b = (- (a mod b)) mod b" proof - have "(- a) mod b = (- (a div b * b + a mod b)) mod b" by (simp only: div_mult_mod_eq) also have "\<dots> = (- (a mod b) + - (a div b) * b) mod b" by (simp add: ac_simps) also have "\<dots> = (- (a mod b)) mod b" by (rule mod_mult_self1) finally show ?thesis . qed lemma mod_minus_cong: assumes "a mod b = a' mod b" shows "(- a) mod b = (- a') mod b" proof - have "(- (a mod b)) mod b = (- (a' mod b)) mod b" unfolding assms .. thus ?thesis by (simp only: mod_minus_eq [symmetric]) qed text \<open>Subtraction respects modular equivalence.\<close> lemma mod_diff_left_eq: "(a - b) mod c = (a mod c - b) mod c" using mod_add_cong [of a c "a mod c" "- b" "- b"] by simp lemma mod_diff_right_eq: "(a - b) mod c = (a - b mod c) mod c" using mod_add_cong [of a c a "- b" "- (b mod c)"] mod_minus_cong [of "b mod c" c b] by simp lemma mod_diff_eq: "(a - b) mod c = (a mod c - b mod c) mod c" using mod_add_cong [of a c "a mod c" "- b" "- (b mod c)"] mod_minus_cong [of "b mod c" c b] by simp lemma mod_diff_cong: assumes "a mod c = a' mod c" assumes "b mod c = b' mod c" shows "(a - b) mod c = (a' - b') mod c" using assms mod_add_cong [of a c a' "- b" "- b'"] mod_minus_cong [of b c "b'"] by simp lemma dvd_neg_div: "y dvd x \<Longrightarrow> -x div y = - (x div y)" apply (case_tac "y = 0") apply simp apply (auto simp add: dvd_def) apply (subgoal_tac "-(y * k) = y * - k") apply (simp only:) apply (erule nonzero_mult_div_cancel_left) apply simp done lemma dvd_div_neg: "y dvd x \<Longrightarrow> x div -y = - (x div y)" apply (case_tac "y = 0") apply simp apply (auto simp add: dvd_def) apply (subgoal_tac "y * k = -y * -k") apply (erule ssubst, rule nonzero_mult_div_cancel_left) apply simp apply simp done lemma div_diff [simp]: "z dvd x \<Longrightarrow> z dvd y \<Longrightarrow> (x - y) div z = x div z - y div z" using div_add [of _ _ "- y"] by (simp add: dvd_neg_div) lemma div_minus_minus [simp]: "(-a) div (-b) = a div b" using div_mult_mult1 [of "- 1" a b] unfolding neg_equal_0_iff_equal by simp lemma mod_minus_minus [simp]: "(-a) mod (-b) = - (a mod b)" using mod_mult_mult1 [of "- 1" a b] by simp lemma div_minus_right: "a div (-b) = (-a) div b" using div_minus_minus [of "-a" b] by simp lemma mod_minus_right: "a mod (-b) = - ((-a) mod b)" using mod_minus_minus [of "-a" b] by simp lemma div_minus1_right [simp]: "a div (-1) = -a" using div_minus_right [of a 1] by simp lemma mod_minus1_right [simp]: "a mod (-1) = 0" using mod_minus_right [of a 1] by simp lemma minus_mod_self2 [simp]: "(a - b) mod b = a mod b" by (simp add: mod_diff_right_eq) lemma minus_mod_self1 [simp]: "(b - a) mod b = - a mod b" using mod_add_self2 [of "- a" b] by simp end subsubsection \<open>Parity and division\<close> class semiring_div_parity = semiring_div + comm_semiring_1_cancel + numeral + assumes parity: "a mod 2 = 0 \<or> a mod 2 = 1" assumes one_mod_two_eq_one [simp]: "1 mod 2 = 1" assumes zero_not_eq_two: "0 \<noteq> 2" begin lemma parity_cases [case_names even odd]: assumes "a mod 2 = 0 \<Longrightarrow> P" assumes "a mod 2 = 1 \<Longrightarrow> P" shows P using assms parity by blast lemma one_div_two_eq_zero [simp]: "1 div 2 = 0" proof (cases "2 = 0") case True then show ?thesis by simp next case False from div_mult_mod_eq have "1 div 2 * 2 + 1 mod 2 = 1" . with one_mod_two_eq_one have "1 div 2 * 2 + 1 = 1" by simp then have "1 div 2 * 2 = 0" by (simp add: ac_simps add_left_imp_eq del: mult_eq_0_iff) then have "1 div 2 = 0 \<or> 2 = 0" by simp with False show ?thesis by auto qed lemma not_mod_2_eq_0_eq_1 [simp]: "a mod 2 \<noteq> 0 \<longleftrightarrow> a mod 2 = 1" by (cases a rule: parity_cases) simp_all lemma not_mod_2_eq_1_eq_0 [simp]: "a mod 2 \<noteq> 1 \<longleftrightarrow> a mod 2 = 0" by (cases a rule: parity_cases) simp_all subclass semiring_parity proof (unfold_locales, unfold dvd_eq_mod_eq_0 not_mod_2_eq_0_eq_1) show "1 mod 2 = 1" by (fact one_mod_two_eq_one) next fix a b assume "a mod 2 = 1" moreover assume "b mod 2 = 1" ultimately show "(a + b) mod 2 = 0" using mod_add_eq [of a b 2] by simp next fix a b assume "(a * b) mod 2 = 0" then have "(a mod 2) * (b mod 2) = 0" by (cases "a mod 2 = 0") (simp_all add: mod_mult_eq [of a b 2]) then show "a mod 2 = 0 \<or> b mod 2 = 0" by (rule divisors_zero) next fix a assume "a mod 2 = 1" then have "a = a div 2 * 2 + 1" using div_mult_mod_eq [of a 2] by simp then show "\<exists>b. a = b + 1" .. qed lemma even_iff_mod_2_eq_zero: "even a \<longleftrightarrow> a mod 2 = 0" by (fact dvd_eq_mod_eq_0) lemma odd_iff_mod_2_eq_one: "odd a \<longleftrightarrow> a mod 2 = 1" by (auto simp add: even_iff_mod_2_eq_zero) lemma even_succ_div_two [simp]: "even a \<Longrightarrow> (a + 1) div 2 = a div 2" by (cases "a = 0") (auto elim!: evenE dest: mult_not_zero) lemma odd_succ_div_two [simp]: "odd a \<Longrightarrow> (a + 1) div 2 = a div 2 + 1" by (auto elim!: oddE simp add: zero_not_eq_two [symmetric] add.assoc) lemma even_two_times_div_two: "even a \<Longrightarrow> 2 * (a div 2) = a" by (fact dvd_mult_div_cancel) lemma odd_two_times_div_two_succ [simp]: "odd a \<Longrightarrow> 2 * (a div 2) + 1 = a" using mult_div_mod_eq [of 2 a] by (simp add: even_iff_mod_2_eq_zero) end subsection \<open>Generic numeral division with a pragmatic type class\<close> text \<open> The following type class contains everything necessary to formulate a division algorithm in ring structures with numerals, restricted to its positive segments. This is its primary motiviation, and it could surely be formulated using a more fine-grained, more algebraic and less technical class hierarchy. \<close> class semiring_numeral_div = semiring_div + comm_semiring_1_cancel + linordered_semidom + assumes div_less: "0 \<le> a \<Longrightarrow> a < b \<Longrightarrow> a div b = 0" and mod_less: " 0 \<le> a \<Longrightarrow> a < b \<Longrightarrow> a mod b = a" and div_positive: "0 < b \<Longrightarrow> b \<le> a \<Longrightarrow> a div b > 0" and mod_less_eq_dividend: "0 \<le> a \<Longrightarrow> a mod b \<le> a" and pos_mod_bound: "0 < b \<Longrightarrow> a mod b < b" and pos_mod_sign: "0 < b \<Longrightarrow> 0 \<le> a mod b" and mod_mult2_eq: "0 \<le> c \<Longrightarrow> a mod (b * c) = b * (a div b mod c) + a mod b" and div_mult2_eq: "0 \<le> c \<Longrightarrow> a div (b * c) = a div b div c" assumes discrete: "a < b \<longleftrightarrow> a + 1 \<le> b" fixes divmod :: "num \<Rightarrow> num \<Rightarrow> 'a \<times> 'a" and divmod_step :: "num \<Rightarrow> 'a \<times> 'a \<Rightarrow> 'a \<times> 'a" assumes divmod_def: "divmod m n = (numeral m div numeral n, numeral m mod numeral n)" and divmod_step_def: "divmod_step l qr = (let (q, r) = qr in if r \<ge> numeral l then (2 * q + 1, r - numeral l) else (2 * q, r))" \<comment> \<open>These are conceptually definitions but force generated code to be monomorphic wrt. particular instances of this class which yields a significant speedup.\<close> begin subclass semiring_div_parity proof fix a show "a mod 2 = 0 \<or> a mod 2 = 1" proof (rule ccontr) assume "\<not> (a mod 2 = 0 \<or> a mod 2 = 1)" then have "a mod 2 \<noteq> 0" and "a mod 2 \<noteq> 1" by simp_all have "0 < 2" by simp with pos_mod_bound pos_mod_sign have "0 \<le> a mod 2" "a mod 2 < 2" by simp_all with \<open>a mod 2 \<noteq> 0\<close> have "0 < a mod 2" by simp with discrete have "1 \<le> a mod 2" by simp with \<open>a mod 2 \<noteq> 1\<close> have "1 < a mod 2" by simp with discrete have "2 \<le> a mod 2" by simp with \<open>a mod 2 < 2\<close> show False by simp qed next show "1 mod 2 = 1" by (rule mod_less) simp_all next show "0 \<noteq> 2" by simp qed lemma divmod_digit_1: assumes "0 \<le> a" "0 < b" and "b \<le> a mod (2 * b)" shows "2 * (a div (2 * b)) + 1 = a div b" (is "?P") and "a mod (2 * b) - b = a mod b" (is "?Q") proof - from assms mod_less_eq_dividend [of a "2 * b"] have "b \<le> a" by (auto intro: trans) with \<open>0 < b\<close> have "0 < a div b" by (auto intro: div_positive) then have [simp]: "1 \<le> a div b" by (simp add: discrete) with \<open>0 < b\<close> have mod_less: "a mod b < b" by (simp add: pos_mod_bound) define w where "w = a div b mod 2" with parity have w_exhaust: "w = 0 \<or> w = 1" by auto have mod_w: "a mod (2 * b) = a mod b + b * w" by (simp add: w_def mod_mult2_eq ac_simps) from assms w_exhaust have "w = 1" by (auto simp add: mod_w) (insert mod_less, auto) with mod_w have mod: "a mod (2 * b) = a mod b + b" by simp have "2 * (a div (2 * b)) = a div b - w" by (simp add: w_def div_mult2_eq minus_mod_eq_mult_div ac_simps) with \<open>w = 1\<close> have div: "2 * (a div (2 * b)) = a div b - 1" by simp then show ?P and ?Q by (simp_all add: div mod add_implies_diff [symmetric]) qed lemma divmod_digit_0: assumes "0 < b" and "a mod (2 * b) < b" shows "2 * (a div (2 * b)) = a div b" (is "?P") and "a mod (2 * b) = a mod b" (is "?Q") proof - define w where "w = a div b mod 2" with parity have w_exhaust: "w = 0 \<or> w = 1" by auto have mod_w: "a mod (2 * b) = a mod b + b * w" by (simp add: w_def mod_mult2_eq ac_simps) moreover have "b \<le> a mod b + b" proof - from \<open>0 < b\<close> pos_mod_sign have "0 \<le> a mod b" by blast then have "0 + b \<le> a mod b + b" by (rule add_right_mono) then show ?thesis by simp qed moreover note assms w_exhaust ultimately have "w = 0" by auto with mod_w have mod: "a mod (2 * b) = a mod b" by simp have "2 * (a div (2 * b)) = a div b - w" by (simp add: w_def div_mult2_eq minus_mod_eq_mult_div ac_simps) with \<open>w = 0\<close> have div: "2 * (a div (2 * b)) = a div b" by simp then show ?P and ?Q by (simp_all add: div mod) qed lemma fst_divmod: "fst (divmod m n) = numeral m div numeral n" by (simp add: divmod_def) lemma snd_divmod: "snd (divmod m n) = numeral m mod numeral n" by (simp add: divmod_def) text \<open> This is a formulation of one step (referring to one digit position) in school-method division: compare the dividend at the current digit position with the remainder from previous division steps and evaluate accordingly. \<close> lemma divmod_step_eq [simp]: "divmod_step l (q, r) = (if numeral l \<le> r then (2 * q + 1, r - numeral l) else (2 * q, r))" by (simp add: divmod_step_def) text \<open> This is a formulation of school-method division. If the divisor is smaller than the dividend, terminate. If not, shift the dividend to the right until termination occurs and then reiterate single division steps in the opposite direction. \<close> lemma divmod_divmod_step: "divmod m n = (if m < n then (0, numeral m) else divmod_step n (divmod m (Num.Bit0 n)))" proof (cases "m < n") case True then have "numeral m < numeral n" by simp then show ?thesis by (simp add: prod_eq_iff div_less mod_less fst_divmod snd_divmod) next case False have "divmod m n = divmod_step n (numeral m div (2 * numeral n), numeral m mod (2 * numeral n))" proof (cases "numeral n \<le> numeral m mod (2 * numeral n)") case True with divmod_step_eq have "divmod_step n (numeral m div (2 * numeral n), numeral m mod (2 * numeral n)) = (2 * (numeral m div (2 * numeral n)) + 1, numeral m mod (2 * numeral n) - numeral n)" by simp moreover from True divmod_digit_1 [of "numeral m" "numeral n"] have "2 * (numeral m div (2 * numeral n)) + 1 = numeral m div numeral n" and "numeral m mod (2 * numeral n) - numeral n = numeral m mod numeral n" by simp_all ultimately show ?thesis by (simp only: divmod_def) next case False then have *: "numeral m mod (2 * numeral n) < numeral n" by (simp add: not_le) with divmod_step_eq have "divmod_step n (numeral m div (2 * numeral n), numeral m mod (2 * numeral n)) = (2 * (numeral m div (2 * numeral n)), numeral m mod (2 * numeral n))" by auto moreover from * divmod_digit_0 [of "numeral n" "numeral m"] have "2 * (numeral m div (2 * numeral n)) = numeral m div numeral n" and "numeral m mod (2 * numeral n) = numeral m mod numeral n" by (simp_all only: zero_less_numeral) ultimately show ?thesis by (simp only: divmod_def) qed then have "divmod m n = divmod_step n (numeral m div numeral (Num.Bit0 n), numeral m mod numeral (Num.Bit0 n))" by (simp only: numeral.simps distrib mult_1) then have "divmod m n = divmod_step n (divmod m (Num.Bit0 n))" by (simp add: divmod_def) with False show ?thesis by simp qed text \<open>The division rewrite proper -- first, trivial results involving \<open>1\<close>\<close> lemma divmod_trivial [simp]: "divmod Num.One Num.One = (numeral Num.One, 0)" "divmod (Num.Bit0 m) Num.One = (numeral (Num.Bit0 m), 0)" "divmod (Num.Bit1 m) Num.One = (numeral (Num.Bit1 m), 0)" "divmod num.One (num.Bit0 n) = (0, Numeral1)" "divmod num.One (num.Bit1 n) = (0, Numeral1)" using divmod_divmod_step [of "Num.One"] by (simp_all add: divmod_def) text \<open>Division by an even number is a right-shift\<close> lemma divmod_cancel [simp]: "divmod (Num.Bit0 m) (Num.Bit0 n) = (case divmod m n of (q, r) \<Rightarrow> (q, 2 * r))" (is ?P) "divmod (Num.Bit1 m) (Num.Bit0 n) = (case divmod m n of (q, r) \<Rightarrow> (q, 2 * r + 1))" (is ?Q) proof - have *: "\<And>q. numeral (Num.Bit0 q) = 2 * numeral q" "\<And>q. numeral (Num.Bit1 q) = 2 * numeral q + 1" by (simp_all only: numeral_mult numeral.simps distrib) simp_all have "1 div 2 = 0" "1 mod 2 = 1" by (auto intro: div_less mod_less) then show ?P and ?Q by (simp_all add: fst_divmod snd_divmod prod_eq_iff split_def * [of m] * [of n] mod_mult_mult1 div_mult2_eq [of _ _ 2] mod_mult2_eq [of _ _ 2] add.commute del: numeral_times_numeral) qed text \<open>The really hard work\<close> lemma divmod_steps [simp]: "divmod (num.Bit0 m) (num.Bit1 n) = (if m \<le> n then (0, numeral (num.Bit0 m)) else divmod_step (num.Bit1 n) (divmod (num.Bit0 m) (num.Bit0 (num.Bit1 n))))" "divmod (num.Bit1 m) (num.Bit1 n) = (if m < n then (0, numeral (num.Bit1 m)) else divmod_step (num.Bit1 n) (divmod (num.Bit1 m) (num.Bit0 (num.Bit1 n))))" by (simp_all add: divmod_divmod_step) lemmas divmod_algorithm_code = divmod_step_eq divmod_trivial divmod_cancel divmod_steps text \<open>Special case: divisibility\<close> definition divides_aux :: "'a \<times> 'a \<Rightarrow> bool" where "divides_aux qr \<longleftrightarrow> snd qr = 0" lemma divides_aux_eq [simp]: "divides_aux (q, r) \<longleftrightarrow> r = 0" by (simp add: divides_aux_def) lemma dvd_numeral_simp [simp]: "numeral m dvd numeral n \<longleftrightarrow> divides_aux (divmod n m)" by (simp add: divmod_def mod_eq_0_iff_dvd) text \<open>Generic computation of quotient and remainder\<close> lemma numeral_div_numeral [simp]: "numeral k div numeral l = fst (divmod k l)" by (simp add: fst_divmod) lemma numeral_mod_numeral [simp]: "numeral k mod numeral l = snd (divmod k l)" by (simp add: snd_divmod) lemma one_div_numeral [simp]: "1 div numeral n = fst (divmod num.One n)" by (simp add: fst_divmod) lemma one_mod_numeral [simp]: "1 mod numeral n = snd (divmod num.One n)" by (simp add: snd_divmod) end subsection \<open>Division on @{typ nat}\<close> context begin text \<open> We define @{const divide} and @{const modulo} on @{typ nat} by means of a characteristic relation with two input arguments @{term "m::nat"}, @{term "n::nat"} and two output arguments @{term "q::nat"}(uotient) and @{term "r::nat"}(emainder). \<close> definition divmod_nat_rel :: "nat \<Rightarrow> nat \<Rightarrow> nat \<times> nat \<Rightarrow> bool" where "divmod_nat_rel m n qr \<longleftrightarrow> m = fst qr * n + snd qr \<and> (if n = 0 then fst qr = 0 else if n > 0 then 0 \<le> snd qr \<and> snd qr < n else n < snd qr \<and> snd qr \<le> 0)" text \<open>@{const divmod_nat_rel} is total:\<close> qualified lemma divmod_nat_rel_ex: obtains q r where "divmod_nat_rel m n (q, r)" proof (cases "n = 0") case True with that show thesis by (auto simp add: divmod_nat_rel_def) next case False have "\<exists>q r. m = q * n + r \<and> r < n" proof (induct m) case 0 with \<open>n \<noteq> 0\<close> have "(0::nat) = 0 * n + 0 \<and> 0 < n" by simp then show ?case by blast next case (Suc m) then obtain q' r' where m: "m = q' * n + r'" and n: "r' < n" by auto then show ?case proof (cases "Suc r' < n") case True from m n have "Suc m = q' * n + Suc r'" by simp with True show ?thesis by blast next case False then have "n \<le> Suc r'" by auto moreover from n have "Suc r' \<le> n" by auto ultimately have "n = Suc r'" by auto with m have "Suc m = Suc q' * n + 0" by simp with \<open>n \<noteq> 0\<close> show ?thesis by blast qed qed with that show thesis using \<open>n \<noteq> 0\<close> by (auto simp add: divmod_nat_rel_def) qed text \<open>@{const divmod_nat_rel} is injective:\<close> qualified lemma divmod_nat_rel_unique: assumes "divmod_nat_rel m n qr" and "divmod_nat_rel m n qr'" shows "qr = qr'" proof (cases "n = 0") case True with assms show ?thesis by (cases qr, cases qr') (simp add: divmod_nat_rel_def) next case False have aux: "\<And>q r q' r'. q' * n + r' = q * n + r \<Longrightarrow> r < n \<Longrightarrow> q' \<le> (q::nat)" apply (rule leI) apply (subst less_iff_Suc_add) apply (auto simp add: add_mult_distrib) done from \<open>n \<noteq> 0\<close> assms have *: "fst qr = fst qr'" by (auto simp add: divmod_nat_rel_def intro: order_antisym dest: aux sym) with assms have "snd qr = snd qr'" by (simp add: divmod_nat_rel_def) with * show ?thesis by (cases qr, cases qr') simp qed text \<open> We instantiate divisibility on the natural numbers by means of @{const divmod_nat_rel}: \<close> qualified definition divmod_nat :: "nat \<Rightarrow> nat \<Rightarrow> nat \<times> nat" where "divmod_nat m n = (THE qr. divmod_nat_rel m n qr)" qualified lemma divmod_nat_rel_divmod_nat: "divmod_nat_rel m n (divmod_nat m n)" proof - from divmod_nat_rel_ex obtain qr where rel: "divmod_nat_rel m n qr" . then show ?thesis by (auto simp add: divmod_nat_def intro: theI elim: divmod_nat_rel_unique) qed qualified lemma divmod_nat_unique: assumes "divmod_nat_rel m n qr" shows "divmod_nat m n = qr" using assms by (auto intro: divmod_nat_rel_unique divmod_nat_rel_divmod_nat) qualified lemma divmod_nat_zero: "divmod_nat m 0 = (0, m)" by (simp add: Divides.divmod_nat_unique divmod_nat_rel_def) qualified lemma divmod_nat_zero_left: "divmod_nat 0 n = (0, 0)" by (simp add: Divides.divmod_nat_unique divmod_nat_rel_def) qualified lemma divmod_nat_base: "m < n \<Longrightarrow> divmod_nat m n = (0, m)" by (simp add: divmod_nat_unique divmod_nat_rel_def) qualified lemma divmod_nat_step: assumes "0 < n" and "n \<le> m" shows "divmod_nat m n = apfst Suc (divmod_nat (m - n) n)" proof (rule divmod_nat_unique) have "divmod_nat_rel (m - n) n (divmod_nat (m - n) n)" by (fact divmod_nat_rel_divmod_nat) then show "divmod_nat_rel m n (apfst Suc (divmod_nat (m - n) n))" unfolding divmod_nat_rel_def using assms by auto qed end instantiation nat :: semiring_div begin definition divide_nat where div_nat_def: "m div n = fst (Divides.divmod_nat m n)" definition modulo_nat where mod_nat_def: "m mod n = snd (Divides.divmod_nat m n)" lemma fst_divmod_nat [simp]: "fst (Divides.divmod_nat m n) = m div n" by (simp add: div_nat_def) lemma snd_divmod_nat [simp]: "snd (Divides.divmod_nat m n) = m mod n" by (simp add: mod_nat_def) lemma divmod_nat_div_mod: "Divides.divmod_nat m n = (m div n, m mod n)" by (simp add: prod_eq_iff) lemma div_nat_unique: assumes "divmod_nat_rel m n (q, r)" shows "m div n = q" using assms by (auto dest!: Divides.divmod_nat_unique simp add: prod_eq_iff) lemma mod_nat_unique: assumes "divmod_nat_rel m n (q, r)" shows "m mod n = r" using assms by (auto dest!: Divides.divmod_nat_unique simp add: prod_eq_iff) lemma divmod_nat_rel: "divmod_nat_rel m n (m div n, m mod n)" using Divides.divmod_nat_rel_divmod_nat by (simp add: divmod_nat_div_mod) text \<open>The ''recursion'' equations for @{const divide} and @{const modulo}\<close> lemma div_less [simp]: fixes m n :: nat assumes "m < n" shows "m div n = 0" using assms Divides.divmod_nat_base by (simp add: prod_eq_iff) lemma le_div_geq: fixes m n :: nat assumes "0 < n" and "n \<le> m" shows "m div n = Suc ((m - n) div n)" using assms Divides.divmod_nat_step by (simp add: prod_eq_iff) lemma mod_less [simp]: fixes m n :: nat assumes "m < n" shows "m mod n = m" using assms Divides.divmod_nat_base by (simp add: prod_eq_iff) lemma le_mod_geq: fixes m n :: nat assumes "n \<le> m" shows "m mod n = (m - n) mod n" using assms Divides.divmod_nat_step by (cases "n = 0") (simp_all add: prod_eq_iff) instance proof fix m n :: nat show "m div n * n + m mod n = m" using divmod_nat_rel [of m n] by (simp add: divmod_nat_rel_def) next fix m n q :: nat assume "n \<noteq> 0" then show "(q + m * n) div n = m + q div n" by (induct m) (simp_all add: le_div_geq) next fix m n q :: nat assume "m \<noteq> 0" hence "\<And>a b. divmod_nat_rel n q (a, b) \<Longrightarrow> divmod_nat_rel (m * n) (m * q) (a, m * b)" unfolding divmod_nat_rel_def by (auto split: if_split_asm, simp_all add: algebra_simps) moreover from divmod_nat_rel have "divmod_nat_rel n q (n div q, n mod q)" . ultimately have "divmod_nat_rel (m * n) (m * q) (n div q, m * (n mod q))" . thus "(m * n) div (m * q) = n div q" by (rule div_nat_unique) next fix n :: nat show "n div 0 = 0" by (simp add: div_nat_def Divides.divmod_nat_zero) next fix n :: nat show "0 div n = 0" by (simp add: div_nat_def Divides.divmod_nat_zero_left) qed end instantiation nat :: normalization_semidom begin definition normalize_nat where [simp]: "normalize = (id :: nat \<Rightarrow> nat)" definition unit_factor_nat where "unit_factor n = (if n = 0 then 0 else 1 :: nat)" lemma unit_factor_simps [simp]: "unit_factor 0 = (0::nat)" "unit_factor (Suc n) = 1" by (simp_all add: unit_factor_nat_def) instance by standard (simp_all add: unit_factor_nat_def) end lemma divmod_nat_if [code]: "Divides.divmod_nat m n = (if n = 0 \<or> m < n then (0, m) else let (q, r) = Divides.divmod_nat (m - n) n in (Suc q, r))" by (simp add: prod_eq_iff case_prod_beta not_less le_div_geq le_mod_geq) text \<open>Simproc for cancelling @{const divide} and @{const modulo}\<close> ML_file "~~/src/Provers/Arith/cancel_div_mod.ML" ML \<open> structure Cancel_Div_Mod_Nat = Cancel_Div_Mod ( val div_name = @{const_name divide}; val mod_name = @{const_name modulo}; val mk_binop = HOLogic.mk_binop; val mk_plus = HOLogic.mk_binop @{const_name Groups.plus}; val dest_plus = HOLogic.dest_bin @{const_name Groups.plus} HOLogic.natT; fun mk_sum [] = HOLogic.zero | mk_sum [t] = t | mk_sum (t :: ts) = mk_plus (t, mk_sum ts); fun dest_sum tm = if HOLogic.is_zero tm then [] else (case try HOLogic.dest_Suc tm of SOME t => HOLogic.Suc_zero :: dest_sum t | NONE => (case try dest_plus tm of SOME (t, u) => dest_sum t @ dest_sum u | NONE => [tm])); val div_mod_eqs = map mk_meta_eq @{thms cancel_div_mod_rules}; val prove_eq_sums = Arith_Data.prove_conv2 all_tac (Arith_Data.simp_all_tac @{thms add_0_left add_0_right ac_simps}) ) \<close> simproc_setup cancel_div_mod_nat ("(m::nat) + n") = \<open>K Cancel_Div_Mod_Nat.proc\<close> subsubsection \<open>Quotient\<close> lemma div_geq: "0 < n \<Longrightarrow> \<not> m < n \<Longrightarrow> m div n = Suc ((m - n) div n)" by (simp add: le_div_geq linorder_not_less) lemma div_if: "0 < n \<Longrightarrow> m div n = (if m < n then 0 else Suc ((m - n) div n))" by (simp add: div_geq) lemma div_mult_self_is_m [simp]: "0<n ==> (m*n) div n = (m::nat)" by simp lemma div_mult_self1_is_m [simp]: "0<n ==> (n*m) div n = (m::nat)" by simp lemma div_positive: fixes m n :: nat assumes "n > 0" assumes "m \<ge> n" shows "m div n > 0" proof - from \<open>m \<ge> n\<close> obtain q where "m = n + q" by (auto simp add: le_iff_add) with \<open>n > 0\<close> show ?thesis by (simp add: div_add_self1) qed lemma div_eq_0_iff: "(a div b::nat) = 0 \<longleftrightarrow> a < b \<or> b = 0" by (metis div_less div_positive div_by_0 gr0I less_numeral_extra(3) not_less) subsubsection \<open>Remainder\<close> lemma mod_less_divisor [simp]: fixes m n :: nat assumes "n > 0" shows "m mod n < (n::nat)" using assms divmod_nat_rel [of m n] unfolding divmod_nat_rel_def by auto lemma mod_Suc_le_divisor [simp]: "m mod Suc n \<le> n" using mod_less_divisor [of "Suc n" m] by arith lemma mod_less_eq_dividend [simp]: fixes m n :: nat shows "m mod n \<le> m" proof (rule add_leD2) from div_mult_mod_eq have "m div n * n + m mod n = m" . then show "m div n * n + m mod n \<le> m" by auto qed lemma mod_geq: "\<not> m < (n::nat) \<Longrightarrow> m mod n = (m - n) mod n" by (simp add: le_mod_geq linorder_not_less) lemma mod_if: "m mod (n::nat) = (if m < n then m else (m - n) mod n)" by (simp add: le_mod_geq) lemma mod_by_Suc_0 [simp]: "m mod Suc 0 = 0" by (induct m) (simp_all add: mod_geq) lemma mod_le_divisor[simp]: "0 < n \<Longrightarrow> m mod n \<le> (n::nat)" apply (drule mod_less_divisor [where m = m]) apply simp done subsubsection \<open>Quotient and Remainder\<close> lemma divmod_nat_rel_mult1_eq: "divmod_nat_rel b c (q, r) \<Longrightarrow> divmod_nat_rel (a * b) c (a * q + a * r div c, a * r mod c)" by (auto simp add: split_ifs divmod_nat_rel_def algebra_simps) lemma div_mult1_eq: "(a * b) div c = a * (b div c) + a * (b mod c) div (c::nat)" by (blast intro: divmod_nat_rel_mult1_eq [THEN div_nat_unique] divmod_nat_rel) lemma divmod_nat_rel_add1_eq: "divmod_nat_rel a c (aq, ar) \<Longrightarrow> divmod_nat_rel b c (bq, br) \<Longrightarrow> divmod_nat_rel (a + b) c (aq + bq + (ar + br) div c, (ar + br) mod c)" by (auto simp add: split_ifs divmod_nat_rel_def algebra_simps) (*NOT suitable for rewriting: the RHS has an instance of the LHS*) lemma div_add1_eq: "(a+b) div (c::nat) = a div c + b div c + ((a mod c + b mod c) div c)" by (blast intro: divmod_nat_rel_add1_eq [THEN div_nat_unique] divmod_nat_rel) lemma divmod_nat_rel_mult2_eq: assumes "divmod_nat_rel a b (q, r)" shows "divmod_nat_rel a (b * c) (q div c, b *(q mod c) + r)" proof - { assume "r < b" and "0 < c" then have "b * (q mod c) + r < b * c" apply (cut_tac m = q and n = c in mod_less_divisor) apply (drule_tac [2] m = "q mod c" in less_imp_Suc_add, auto) apply (erule_tac P = "%x. lhs < rhs x" for lhs rhs in ssubst) apply (simp add: add_mult_distrib2) done then have "r + b * (q mod c) < b * c" by (simp add: ac_simps) } with assms show ?thesis by (auto simp add: divmod_nat_rel_def algebra_simps add_mult_distrib2 [symmetric]) qed lemma div_mult2_eq: "a div (b * c) = (a div b) div (c::nat)" by (force simp add: divmod_nat_rel [THEN divmod_nat_rel_mult2_eq, THEN div_nat_unique]) lemma mod_mult2_eq: "a mod (b * c) = b * (a div b mod c) + a mod (b::nat)" by (auto simp add: mult.commute divmod_nat_rel [THEN divmod_nat_rel_mult2_eq, THEN mod_nat_unique]) instantiation nat :: semiring_numeral_div begin definition divmod_nat :: "num \<Rightarrow> num \<Rightarrow> nat \<times> nat" where divmod'_nat_def: "divmod_nat m n = (numeral m div numeral n, numeral m mod numeral n)" definition divmod_step_nat :: "num \<Rightarrow> nat \<times> nat \<Rightarrow> nat \<times> nat" where "divmod_step_nat l qr = (let (q, r) = qr in if r \<ge> numeral l then (2 * q + 1, r - numeral l) else (2 * q, r))" instance by standard (auto intro: div_positive simp add: divmod'_nat_def divmod_step_nat_def mod_mult2_eq div_mult2_eq) end declare divmod_algorithm_code [where ?'a = nat, code] subsubsection \<open>Further Facts about Quotient and Remainder\<close> lemma div_by_Suc_0 [simp]: "m div Suc 0 = m" using div_by_1 [of m] by simp (* Monotonicity of div in first argument *) lemma div_le_mono [rule_format (no_asm)]: "\<forall>m::nat. m \<le> n --> (m div k) \<le> (n div k)" apply (case_tac "k=0", simp) apply (induct "n" rule: nat_less_induct, clarify) apply (case_tac "n<k") (* 1 case n<k *) apply simp (* 2 case n >= k *) apply (case_tac "m<k") (* 2.1 case m<k *) apply simp (* 2.2 case m>=k *) apply (simp add: div_geq diff_le_mono) done (* Antimonotonicity of div in second argument *) lemma div_le_mono2: "!!m::nat. [| 0<m; m\<le>n |] ==> (k div n) \<le> (k div m)" apply (subgoal_tac "0<n") prefer 2 apply simp apply (induct_tac k rule: nat_less_induct) apply (rename_tac "k") apply (case_tac "k<n", simp) apply (subgoal_tac "~ (k<m) ") prefer 2 apply simp apply (simp add: div_geq) apply (subgoal_tac "(k-n) div n \<le> (k-m) div n") prefer 2 apply (blast intro: div_le_mono diff_le_mono2) apply (rule le_trans, simp) apply (simp) done lemma div_le_dividend [simp]: "m div n \<le> (m::nat)" apply (case_tac "n=0", simp) apply (subgoal_tac "m div n \<le> m div 1", simp) apply (rule div_le_mono2) apply (simp_all (no_asm_simp)) done (* Similar for "less than" *) lemma div_less_dividend [simp]: "\<lbrakk>(1::nat) < n; 0 < m\<rbrakk> \<Longrightarrow> m div n < m" apply (induct m rule: nat_less_induct) apply (rename_tac "m") apply (case_tac "m<n", simp) apply (subgoal_tac "0<n") prefer 2 apply simp apply (simp add: div_geq) apply (case_tac "n<m") apply (subgoal_tac "(m-n) div n < (m-n) ") apply (rule impI less_trans_Suc)+ apply assumption apply (simp_all) done text\<open>A fact for the mutilated chess board\<close> lemma mod_Suc: "Suc(m) mod n = (if Suc(m mod n) = n then 0 else Suc(m mod n))" apply (case_tac "n=0", simp) apply (induct "m" rule: nat_less_induct) apply (case_tac "Suc (na) <n") (* case Suc(na) < n *) apply (frule lessI [THEN less_trans], simp add: less_not_refl3) (* case n \<le> Suc(na) *) apply (simp add: linorder_not_less le_Suc_eq mod_geq) apply (auto simp add: Suc_diff_le le_mod_geq) done lemma mod_eq_0_iff: "(m mod d = 0) = (\<exists>q::nat. m = d*q)" by (auto simp add: dvd_eq_mod_eq_0 [symmetric] dvd_def) lemmas mod_eq_0D [dest!] = mod_eq_0_iff [THEN iffD1] (*Loses information, namely we also have r<d provided d is nonzero*) lemma mod_eqD: fixes m d r q :: nat assumes "m mod d = r" shows "\<exists>q. m = r + q * d" proof - from div_mult_mod_eq obtain q where "q * d + m mod d = m" by blast with assms have "m = r + q * d" by simp then show ?thesis .. qed lemma split_div: "P(n div k :: nat) = ((k = 0 \<longrightarrow> P 0) \<and> (k \<noteq> 0 \<longrightarrow> (!i. !j<k. n = k*i + j \<longrightarrow> P i)))" (is "?P = ?Q" is "_ = (_ \<and> (_ \<longrightarrow> ?R))") proof assume P: ?P show ?Q proof (cases) assume "k = 0" with P show ?Q by simp next assume not0: "k \<noteq> 0" thus ?Q proof (simp, intro allI impI) fix i j assume n: "n = k*i + j" and j: "j < k" show "P i" proof (cases) assume "i = 0" with n j P show "P i" by simp next assume "i \<noteq> 0" with not0 n j P show "P i" by(simp add:ac_simps) qed qed qed next assume Q: ?Q show ?P proof (cases) assume "k = 0" with Q show ?P by simp next assume not0: "k \<noteq> 0" with Q have R: ?R by simp from not0 R[THEN spec,of "n div k",THEN spec, of "n mod k"] show ?P by simp qed qed lemma split_div_lemma: assumes "0 < n" shows "n * q \<le> m \<and> m < n * Suc q \<longleftrightarrow> q = ((m::nat) div n)" (is "?lhs \<longleftrightarrow> ?rhs") proof assume ?rhs with minus_mod_eq_mult_div [symmetric] have nq: "n * q = m - (m mod n)" by simp then have A: "n * q \<le> m" by simp have "n - (m mod n) > 0" using mod_less_divisor assms by auto then have "m < m + (n - (m mod n))" by simp then have "m < n + (m - (m mod n))" by simp with nq have "m < n + n * q" by simp then have B: "m < n * Suc q" by simp from A B show ?lhs .. next assume P: ?lhs then have "divmod_nat_rel m n (q, m - n * q)" unfolding divmod_nat_rel_def by (auto simp add: ac_simps) then have "m div n = q" by (rule div_nat_unique) then show ?rhs by simp qed theorem split_div': "P ((m::nat) div n) = ((n = 0 \<and> P 0) \<or> (\<exists>q. (n * q \<le> m \<and> m < n * (Suc q)) \<and> P q))" apply (cases "0 < n") apply (simp only: add: split_div_lemma) apply simp_all done lemma split_mod: "P(n mod k :: nat) = ((k = 0 \<longrightarrow> P n) \<and> (k \<noteq> 0 \<longrightarrow> (!i. !j<k. n = k*i + j \<longrightarrow> P j)))" (is "?P = ?Q" is "_ = (_ \<and> (_ \<longrightarrow> ?R))") proof assume P: ?P show ?Q proof (cases) assume "k = 0" with P show ?Q by simp next assume not0: "k \<noteq> 0" thus ?Q proof (simp, intro allI impI) fix i j assume "n = k*i + j" "j < k" thus "P j" using not0 P by (simp add: ac_simps) qed qed next assume Q: ?Q show ?P proof (cases) assume "k = 0" with Q show ?P by simp next assume not0: "k \<noteq> 0" with Q have R: ?R by simp from not0 R[THEN spec,of "n div k",THEN spec, of "n mod k"] show ?P by simp qed qed lemma div_eq_dividend_iff: "a \<noteq> 0 \<Longrightarrow> (a :: nat) div b = a \<longleftrightarrow> b = 1" apply rule apply (cases "b = 0") apply simp_all apply (metis (full_types) One_nat_def Suc_lessI div_less_dividend less_not_refl3) done lemma (in field_char_0) of_nat_div: "of_nat (m div n) = ((of_nat m - of_nat (m mod n)) / of_nat n)" proof - have "of_nat (m div n) = ((of_nat (m div n * n + m mod n) - of_nat (m mod n)) / of_nat n :: 'a)" unfolding of_nat_add by (cases "n = 0") simp_all then show ?thesis by simp qed subsubsection \<open>An ``induction'' law for modulus arithmetic.\<close> lemma mod_induct_0: assumes step: "\<forall>i<p. P i \<longrightarrow> P ((Suc i) mod p)" and base: "P i" and i: "i<p" shows "P 0" proof (rule ccontr) assume contra: "\<not>(P 0)" from i have p: "0<p" by simp have "\<forall>k. 0<k \<longrightarrow> \<not> P (p-k)" (is "\<forall>k. ?A k") proof fix k show "?A k" proof (induct k) show "?A 0" by simp \<comment> "by contradiction" next fix n assume ih: "?A n" show "?A (Suc n)" proof (clarsimp) assume y: "P (p - Suc n)" have n: "Suc n < p" proof (rule ccontr) assume "\<not>(Suc n < p)" hence "p - Suc n = 0" by simp with y contra show "False" by simp qed hence n2: "Suc (p - Suc n) = p-n" by arith from p have "p - Suc n < p" by arith with y step have z: "P ((Suc (p - Suc n)) mod p)" by blast show "False" proof (cases "n=0") case True with z n2 contra show ?thesis by simp next case False with p have "p-n < p" by arith with z n2 False ih show ?thesis by simp qed qed qed qed moreover from i obtain k where "0<k \<and> i+k=p" by (blast dest: less_imp_add_positive) hence "0<k \<and> i=p-k" by auto moreover note base ultimately show "False" by blast qed lemma mod_induct: assumes step: "\<forall>i<p. P i \<longrightarrow> P ((Suc i) mod p)" and base: "P i" and i: "i<p" and j: "j<p" shows "P j" proof - have "\<forall>j<p. P j" proof fix j show "j<p \<longrightarrow> P j" (is "?A j") proof (induct j) from step base i show "?A 0" by (auto elim: mod_induct_0) next fix k assume ih: "?A k" show "?A (Suc k)" proof assume suc: "Suc k < p" hence k: "k<p" by simp with ih have "P k" .. with step k have "P (Suc k mod p)" by blast moreover from suc have "Suc k mod p = Suc k" by simp ultimately show "P (Suc k)" by simp qed qed qed with j show ?thesis by blast qed lemma div2_Suc_Suc [simp]: "Suc (Suc m) div 2 = Suc (m div 2)" by (simp add: numeral_2_eq_2 le_div_geq) lemma mod2_Suc_Suc [simp]: "Suc (Suc m) mod 2 = m mod 2" by (simp add: numeral_2_eq_2 le_mod_geq) lemma add_self_div_2 [simp]: "(m + m) div 2 = (m::nat)" by (simp add: mult_2 [symmetric]) lemma mod2_gr_0 [simp]: "0 < (m::nat) mod 2 \<longleftrightarrow> m mod 2 = 1" proof - { fix n :: nat have "(n::nat) < 2 \<Longrightarrow> n = 0 \<or> n = 1" by (cases n) simp_all } moreover have "m mod 2 < 2" by simp ultimately have "m mod 2 = 0 \<or> m mod 2 = 1" . then show ?thesis by auto qed text\<open>These lemmas collapse some needless occurrences of Suc: at least three Sucs, since two and fewer are rewritten back to Suc again! We already have some rules to simplify operands smaller than 3.\<close> lemma div_Suc_eq_div_add3 [simp]: "m div (Suc (Suc (Suc n))) = m div (3+n)" by (simp add: Suc3_eq_add_3) lemma mod_Suc_eq_mod_add3 [simp]: "m mod (Suc (Suc (Suc n))) = m mod (3+n)" by (simp add: Suc3_eq_add_3) lemma Suc_div_eq_add3_div: "(Suc (Suc (Suc m))) div n = (3+m) div n" by (simp add: Suc3_eq_add_3) lemma Suc_mod_eq_add3_mod: "(Suc (Suc (Suc m))) mod n = (3+m) mod n" by (simp add: Suc3_eq_add_3) lemmas Suc_div_eq_add3_div_numeral [simp] = Suc_div_eq_add3_div [of _ "numeral v"] for v lemmas Suc_mod_eq_add3_mod_numeral [simp] = Suc_mod_eq_add3_mod [of _ "numeral v"] for v lemma Suc_times_mod_eq: "1<k ==> Suc (k * m) mod k = 1" apply (induct "m") apply (simp_all add: mod_Suc) done declare Suc_times_mod_eq [of "numeral w", simp] for w lemma mod_greater_zero_iff_not_dvd: fixes m n :: nat shows "m mod n > 0 \<longleftrightarrow> \<not> n dvd m" by (simp add: dvd_eq_mod_eq_0) lemma Suc_div_le_mono [simp]: "n div k \<le> (Suc n) div k" by (simp add: div_le_mono) lemma Suc_n_div_2_gt_zero [simp]: "(0::nat) < n ==> 0 < (n + 1) div 2" by (cases n) simp_all lemma div_2_gt_zero [simp]: assumes A: "(1::nat) < n" shows "0 < n div 2" proof - from A have B: "0 < n - 1" and C: "n - 1 + 1 = n" by simp_all from Suc_n_div_2_gt_zero [OF B] C show ?thesis by simp qed lemma mod_mult_self4 [simp]: "Suc (k*n + m) mod n = Suc m mod n" proof - have "Suc (k * n + m) mod n = (k * n + Suc m) mod n" by simp also have "... = Suc m mod n" by (rule mod_mult_self3) finally show ?thesis . qed lemma mod_Suc_eq_Suc_mod: "Suc m mod n = Suc (m mod n) mod n" apply (subst mod_Suc [of m]) apply (subst mod_Suc [of "m mod n"], simp) done lemma mod_2_not_eq_zero_eq_one_nat: fixes n :: nat shows "n mod 2 \<noteq> 0 \<longleftrightarrow> n mod 2 = 1" by (fact not_mod_2_eq_0_eq_1) lemma even_Suc_div_two [simp]: "even n \<Longrightarrow> Suc n div 2 = n div 2" using even_succ_div_two [of n] by simp lemma odd_Suc_div_two [simp]: "odd n \<Longrightarrow> Suc n div 2 = Suc (n div 2)" using odd_succ_div_two [of n] by simp lemma odd_two_times_div_two_nat [simp]: assumes "odd n" shows "2 * (n div 2) = n - (1 :: nat)" proof - from assms have "2 * (n div 2) + 1 = n" by (rule odd_two_times_div_two_succ) then have "Suc (2 * (n div 2)) - 1 = n - 1" by simp then show ?thesis by simp qed lemma parity_induct [case_names zero even odd]: assumes zero: "P 0" assumes even: "\<And>n. P n \<Longrightarrow> P (2 * n)" assumes odd: "\<And>n. P n \<Longrightarrow> P (Suc (2 * n))" shows "P n" proof (induct n rule: less_induct) case (less n) show "P n" proof (cases "n = 0") case True with zero show ?thesis by simp next case False with less have hyp: "P (n div 2)" by simp show ?thesis proof (cases "even n") case True with hyp even [of "n div 2"] show ?thesis by simp next case False with hyp odd [of "n div 2"] show ?thesis by simp qed qed qed lemma Suc_0_div_numeral [simp]: fixes k l :: num shows "Suc 0 div numeral k = fst (divmod Num.One k)" by (simp_all add: fst_divmod) lemma Suc_0_mod_numeral [simp]: fixes k l :: num shows "Suc 0 mod numeral k = snd (divmod Num.One k)" by (simp_all add: snd_divmod) lemma cut_eq_simps: \<comment> \<open>rewriting equivalence on \<open>n mod 2 ^ q\<close>\<close> fixes m n q :: num shows "numeral n mod numeral Num.One = (0::nat) \<longleftrightarrow> True" "numeral (Num.Bit0 n) mod numeral (Num.Bit0 q) = (0::nat) \<longleftrightarrow> numeral n mod numeral q = (0::nat)" "numeral (Num.Bit1 n) mod numeral (Num.Bit0 q) = (0::nat) \<longleftrightarrow> False" "numeral m mod numeral Num.One = (numeral n mod numeral Num.One :: nat) \<longleftrightarrow> True" "numeral Num.One mod numeral (Num.Bit0 q) = (numeral Num.One mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> True" "numeral Num.One mod numeral (Num.Bit0 q) = (numeral (Num.Bit0 n) mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> False" "numeral Num.One mod numeral (Num.Bit0 q) = (numeral (Num.Bit1 n) mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> (numeral n mod numeral q :: nat) = 0" "numeral (Num.Bit0 m) mod numeral (Num.Bit0 q) = (numeral Num.One mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> False" "numeral (Num.Bit0 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit0 n) mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> numeral m mod numeral q = (numeral n mod numeral q :: nat)" "numeral (Num.Bit0 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit1 n) mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> False" "numeral (Num.Bit1 m) mod numeral (Num.Bit0 q) = (numeral Num.One mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> (numeral m mod numeral q :: nat) = 0" "numeral (Num.Bit1 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit0 n) mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> False" "numeral (Num.Bit1 m) mod numeral (Num.Bit0 q) = (numeral (Num.Bit1 n) mod numeral (Num.Bit0 q) :: nat) \<longleftrightarrow> numeral m mod numeral q = (numeral n mod numeral q :: nat)" by (auto simp add: case_prod_beta Suc_double_not_eq_double double_not_eq_Suc_double) subsection \<open>Division on @{typ int}\<close> definition divmod_int_rel :: "int \<Rightarrow> int \<Rightarrow> int \<times> int \<Rightarrow> bool" \<comment> \<open>definition of quotient and remainder\<close> where "divmod_int_rel a b = (\<lambda>(q, r). a = b * q + r \<and> (if 0 < b then 0 \<le> r \<and> r < b else if b < 0 then b < r \<and> r \<le> 0 else q = 0))" lemma unique_quotient_lemma: "b * q' + r' \<le> b * q + r \<Longrightarrow> 0 \<le> r' \<Longrightarrow> r' < b \<Longrightarrow> r < b \<Longrightarrow> q' \<le> (q::int)" apply (subgoal_tac "r' + b * (q'-q) \<le> r") prefer 2 apply (simp add: right_diff_distrib) apply (subgoal_tac "0 < b * (1 + q - q') ") apply (erule_tac [2] order_le_less_trans) prefer 2 apply (simp add: right_diff_distrib distrib_left) apply (subgoal_tac "b * q' < b * (1 + q) ") prefer 2 apply (simp add: right_diff_distrib distrib_left) apply (simp add: mult_less_cancel_left) done lemma unique_quotient_lemma_neg: "b * q' + r' \<le> b*q + r \<Longrightarrow> r \<le> 0 \<Longrightarrow> b < r \<Longrightarrow> b < r' \<Longrightarrow> q \<le> (q'::int)" by (rule_tac b = "-b" and r = "-r'" and r' = "-r" in unique_quotient_lemma) auto lemma unique_quotient: "divmod_int_rel a b (q, r) \<Longrightarrow> divmod_int_rel a b (q', r') \<Longrightarrow> q = q'" apply (simp add: divmod_int_rel_def linorder_neq_iff split: if_split_asm) apply (blast intro: order_antisym dest: order_eq_refl [THEN unique_quotient_lemma] order_eq_refl [THEN unique_quotient_lemma_neg] sym)+ done lemma unique_remainder: "divmod_int_rel a b (q, r) \<Longrightarrow> divmod_int_rel a b (q', r') \<Longrightarrow> r = r'" apply (subgoal_tac "q = q'") apply (simp add: divmod_int_rel_def) apply (blast intro: unique_quotient) done instantiation int :: modulo begin definition divide_int where "k div l = (if l = 0 \<or> k = 0 then 0 else if k > 0 \<and> l > 0 \<or> k < 0 \<and> l < 0 then int (nat \<bar>k\<bar> div nat \<bar>l\<bar>) else if l dvd k then - int (nat \<bar>k\<bar> div nat \<bar>l\<bar>) else - int (Suc (nat \<bar>k\<bar> div nat \<bar>l\<bar>)))" definition modulo_int where "k mod l = (if l = 0 then k else if l dvd k then 0 else if k > 0 \<and> l > 0 \<or> k < 0 \<and> l < 0 then sgn l * int (nat \<bar>k\<bar> mod nat \<bar>l\<bar>) else sgn l * (\<bar>l\<bar> - int (nat \<bar>k\<bar> mod nat \<bar>l\<bar>)))" instance .. end lemma divmod_int_rel: "divmod_int_rel k l (k div l, k mod l)" unfolding divmod_int_rel_def divide_int_def modulo_int_def apply (cases k rule: int_cases3) apply (simp add: mod_greater_zero_iff_not_dvd not_le algebra_simps) apply (cases l rule: int_cases3) apply (simp add: mod_greater_zero_iff_not_dvd not_le algebra_simps) apply (simp_all del: of_nat_add of_nat_mult add: mod_greater_zero_iff_not_dvd not_le algebra_simps int_dvd_iff of_nat_add [symmetric] of_nat_mult [symmetric]) apply (cases l rule: int_cases3) apply (simp_all del: of_nat_add of_nat_mult add: not_le algebra_simps int_dvd_iff of_nat_add [symmetric] of_nat_mult [symmetric]) done instantiation int :: ring_div begin subsubsection \<open>Uniqueness and Monotonicity of Quotients and Remainders\<close> lemma divmod_int_unique: assumes "divmod_int_rel k l (q, r)" shows div_int_unique: "k div l = q" and mod_int_unique: "k mod l = r" using assms divmod_int_rel [of k l] using unique_quotient [of k l] unique_remainder [of k l] by auto instance proof fix a b :: int show "a div b * b + a mod b = a" using divmod_int_rel [of a b] unfolding divmod_int_rel_def by (simp add: mult.commute) next fix a b c :: int assume "b \<noteq> 0" hence "divmod_int_rel (a + c * b) b (c + a div b, a mod b)" using divmod_int_rel [of a b] unfolding divmod_int_rel_def by (auto simp: algebra_simps) thus "(a + c * b) div b = c + a div b" by (rule div_int_unique) next fix a b c :: int assume c: "c \<noteq> 0" have "\<And>q r. divmod_int_rel a b (q, r) \<Longrightarrow> divmod_int_rel (c * a) (c * b) (q, c * r)" unfolding divmod_int_rel_def by (rule linorder_cases [of 0 b]) (use c in \<open>auto simp: algebra_simps mult_less_0_iff zero_less_mult_iff mult_strict_right_mono mult_strict_right_mono_neg zero_le_mult_iff mult_le_0_iff\<close>) hence "divmod_int_rel (c * a) (c * b) (a div b, c * (a mod b))" using divmod_int_rel [of a b] . thus "(c * a) div (c * b) = a div b" by (rule div_int_unique) next fix a :: int show "a div 0 = 0" by (rule div_int_unique, simp add: divmod_int_rel_def) next fix a :: int show "0 div a = 0" by (rule div_int_unique, auto simp add: divmod_int_rel_def) qed end lemma is_unit_int: "is_unit (k::int) \<longleftrightarrow> k = 1 \<or> k = - 1" by auto instantiation int :: normalization_semidom begin definition normalize_int where [simp]: "normalize = (abs :: int \<Rightarrow> int)" definition unit_factor_int where [simp]: "unit_factor = (sgn :: int \<Rightarrow> int)" instance proof fix k :: int assume "k \<noteq> 0" then have "\<bar>sgn k\<bar> = 1" by (cases "0::int" k rule: linorder_cases) simp_all then show "is_unit (unit_factor k)" by simp qed (simp_all add: sgn_mult mult_sgn_abs) end text\<open>Basic laws about division and remainder\<close> lemma zdiv_int: "int (a div b) = int a div int b" by (simp add: divide_int_def) lemma zmod_int: "int (a mod b) = int a mod int b" by (simp add: modulo_int_def int_dvd_iff) text \<open>Tool setup\<close> ML \<open> structure Cancel_Div_Mod_Int = Cancel_Div_Mod ( val div_name = @{const_name divide}; val mod_name = @{const_name modulo}; val mk_binop = HOLogic.mk_binop; val mk_sum = Arith_Data.mk_sum HOLogic.intT; val dest_sum = Arith_Data.dest_sum; val div_mod_eqs = map mk_meta_eq @{thms cancel_div_mod_rules}; val prove_eq_sums = Arith_Data.prove_conv2 all_tac (Arith_Data.simp_all_tac @{thms diff_conv_add_uminus add_0_left add_0_right ac_simps}) ) \<close> simproc_setup cancel_div_mod_int ("(k::int) + l") = \<open>K Cancel_Div_Mod_Int.proc\<close> lemma pos_mod_conj: "(0::int) < b \<Longrightarrow> 0 \<le> a mod b \<and> a mod b < b" using divmod_int_rel [of a b] by (auto simp add: divmod_int_rel_def prod_eq_iff) lemmas pos_mod_sign [simp] = pos_mod_conj [THEN conjunct1] and pos_mod_bound [simp] = pos_mod_conj [THEN conjunct2] lemma neg_mod_conj: "b < (0::int) \<Longrightarrow> a mod b \<le> 0 \<and> b < a mod b" using divmod_int_rel [of a b] by (auto simp add: divmod_int_rel_def prod_eq_iff) lemmas neg_mod_sign [simp] = neg_mod_conj [THEN conjunct1] and neg_mod_bound [simp] = neg_mod_conj [THEN conjunct2] subsubsection \<open>General Properties of div and mod\<close> lemma div_pos_pos_trivial: "[| (0::int) \<le> a; a < b |] ==> a div b = 0" apply (rule div_int_unique) apply (auto simp add: divmod_int_rel_def) done lemma div_neg_neg_trivial: "[| a \<le> (0::int); b < a |] ==> a div b = 0" apply (rule div_int_unique) apply (auto simp add: divmod_int_rel_def) done lemma div_pos_neg_trivial: "[| (0::int) < a; a+b \<le> 0 |] ==> a div b = -1" apply (rule div_int_unique) apply (auto simp add: divmod_int_rel_def) done (*There is no div_neg_pos_trivial because 0 div b = 0 would supersede it*) lemma mod_pos_pos_trivial: "[| (0::int) \<le> a; a < b |] ==> a mod b = a" apply (rule_tac q = 0 in mod_int_unique) apply (auto simp add: divmod_int_rel_def) done lemma mod_neg_neg_trivial: "[| a \<le> (0::int); b < a |] ==> a mod b = a" apply (rule_tac q = 0 in mod_int_unique) apply (auto simp add: divmod_int_rel_def) done lemma mod_pos_neg_trivial: "[| (0::int) < a; a+b \<le> 0 |] ==> a mod b = a+b" apply (rule_tac q = "-1" in mod_int_unique) apply (auto simp add: divmod_int_rel_def) done text\<open>There is no \<open>mod_neg_pos_trivial\<close>.\<close> subsubsection \<open>Laws for div and mod with Unary Minus\<close> lemma zminus1_lemma: "divmod_int_rel a b (q, r) ==> b \<noteq> 0 ==> divmod_int_rel (-a) b (if r=0 then -q else -q - 1, if r=0 then 0 else b-r)" by (force simp add: split_ifs divmod_int_rel_def linorder_neq_iff right_diff_distrib) lemma zdiv_zminus1_eq_if: "b \<noteq> (0::int) ==> (-a) div b = (if a mod b = 0 then - (a div b) else - (a div b) - 1)" by (blast intro: divmod_int_rel [THEN zminus1_lemma, THEN div_int_unique]) lemma zmod_zminus1_eq_if: "(-a::int) mod b = (if a mod b = 0 then 0 else b - (a mod b))" apply (case_tac "b = 0", simp) apply (blast intro: divmod_int_rel [THEN zminus1_lemma, THEN mod_int_unique]) done lemma zmod_zminus1_not_zero: fixes k l :: int shows "- k mod l \<noteq> 0 \<Longrightarrow> k mod l \<noteq> 0" unfolding zmod_zminus1_eq_if by auto lemma zdiv_zminus2_eq_if: "b \<noteq> (0::int) ==> a div (-b) = (if a mod b = 0 then - (a div b) else - (a div b) - 1)" by (simp add: zdiv_zminus1_eq_if div_minus_right) lemma zmod_zminus2_eq_if: "a mod (-b::int) = (if a mod b = 0 then 0 else (a mod b) - b)" by (simp add: zmod_zminus1_eq_if mod_minus_right) lemma zmod_zminus2_not_zero: fixes k l :: int shows "k mod - l \<noteq> 0 \<Longrightarrow> k mod l \<noteq> 0" unfolding zmod_zminus2_eq_if by auto subsubsection \<open>Monotonicity in the First Argument (Dividend)\<close> lemma zdiv_mono1: "[| a \<le> a'; 0 < (b::int) |] ==> a div b \<le> a' div b" using mult_div_mod_eq [symmetric, of a b] using mult_div_mod_eq [symmetric, of a' b] apply - apply (rule unique_quotient_lemma) apply (erule subst) apply (erule subst, simp_all) done lemma zdiv_mono1_neg: "[| a \<le> a'; (b::int) < 0 |] ==> a' div b \<le> a div b" using mult_div_mod_eq [symmetric, of a b] using mult_div_mod_eq [symmetric, of a' b] apply - apply (rule unique_quotient_lemma_neg) apply (erule subst) apply (erule subst, simp_all) done subsubsection \<open>Monotonicity in the Second Argument (Divisor)\<close> lemma q_pos_lemma: "[| 0 \<le> b'*q' + r'; r' < b'; 0 < b' |] ==> 0 \<le> (q'::int)" apply (subgoal_tac "0 < b'* (q' + 1) ") apply (simp add: zero_less_mult_iff) apply (simp add: distrib_left) done lemma zdiv_mono2_lemma: "[| b*q + r = b'*q' + r'; 0 \<le> b'*q' + r'; r' < b'; 0 \<le> r; 0 < b'; b' \<le> b |] ==> q \<le> (q'::int)" apply (frule q_pos_lemma, assumption+) apply (subgoal_tac "b*q < b* (q' + 1) ") apply (simp add: mult_less_cancel_left) apply (subgoal_tac "b*q = r' - r + b'*q'") prefer 2 apply simp apply (simp (no_asm_simp) add: distrib_left) apply (subst add.commute, rule add_less_le_mono, arith) apply (rule mult_right_mono, auto) done lemma zdiv_mono2: "[| (0::int) \<le> a; 0 < b'; b' \<le> b |] ==> a div b \<le> a div b'" apply (subgoal_tac "b \<noteq> 0") prefer 2 apply arith using mult_div_mod_eq [symmetric, of a b] using mult_div_mod_eq [symmetric, of a b'] apply - apply (rule zdiv_mono2_lemma) apply (erule subst) apply (erule subst, simp_all) done lemma q_neg_lemma: "[| b'*q' + r' < 0; 0 \<le> r'; 0 < b' |] ==> q' \<le> (0::int)" apply (subgoal_tac "b'*q' < 0") apply (simp add: mult_less_0_iff, arith) done lemma zdiv_mono2_neg_lemma: "[| b*q + r = b'*q' + r'; b'*q' + r' < 0; r < b; 0 \<le> r'; 0 < b'; b' \<le> b |] ==> q' \<le> (q::int)" apply (frule q_neg_lemma, assumption+) apply (subgoal_tac "b*q' < b* (q + 1) ") apply (simp add: mult_less_cancel_left) apply (simp add: distrib_left) apply (subgoal_tac "b*q' \<le> b'*q'") prefer 2 apply (simp add: mult_right_mono_neg, arith) done lemma zdiv_mono2_neg: "[| a < (0::int); 0 < b'; b' \<le> b |] ==> a div b' \<le> a div b" using mult_div_mod_eq [symmetric, of a b] using mult_div_mod_eq [symmetric, of a b'] apply - apply (rule zdiv_mono2_neg_lemma) apply (erule subst) apply (erule subst, simp_all) done subsubsection \<open>More Algebraic Laws for div and mod\<close> text\<open>proving (a*b) div c = a * (b div c) + a * (b mod c)\<close> lemma zmult1_lemma: "[| divmod_int_rel b c (q, r) |] ==> divmod_int_rel (a * b) c (a*q + a*r div c, a*r mod c)" by (auto simp add: split_ifs divmod_int_rel_def linorder_neq_iff distrib_left ac_simps) lemma zdiv_zmult1_eq: "(a*b) div c = a*(b div c) + a*(b mod c) div (c::int)" apply (case_tac "c = 0", simp) apply (blast intro: divmod_int_rel [THEN zmult1_lemma, THEN div_int_unique]) done text\<open>proving (a+b) div c = a div c + b div c + ((a mod c + b mod c) div c)\<close> lemma zadd1_lemma: "[| divmod_int_rel a c (aq, ar); divmod_int_rel b c (bq, br) |] ==> divmod_int_rel (a+b) c (aq + bq + (ar+br) div c, (ar+br) mod c)" by (force simp add: split_ifs divmod_int_rel_def linorder_neq_iff distrib_left) (*NOT suitable for rewriting: the RHS has an instance of the LHS*) lemma zdiv_zadd1_eq: "(a+b) div (c::int) = a div c + b div c + ((a mod c + b mod c) div c)" apply (case_tac "c = 0", simp) apply (blast intro: zadd1_lemma [OF divmod_int_rel divmod_int_rel] div_int_unique) done lemma zmod_eq_0_iff: "(m mod d = 0) = (EX q::int. m = d*q)" by (simp add: dvd_eq_mod_eq_0 [symmetric] dvd_def) (* REVISIT: should this be generalized to all semiring_div types? *) lemmas zmod_eq_0D [dest!] = zmod_eq_0_iff [THEN iffD1] subsubsection \<open>Proving @{term "a div (b * c) = (a div b) div c"}\<close> (*The condition c>0 seems necessary. Consider that 7 div ~6 = ~2 but 7 div 2 div ~3 = 3 div ~3 = ~1. The subcase (a div b) mod c = 0 seems to cause particular problems.*) text\<open>first, four lemmas to bound the remainder for the cases b<0 and b>0\<close> lemma zmult2_lemma_aux1: "[| (0::int) < c; b < r; r \<le> 0 |] ==> b * c < b * (q mod c) + r" apply (subgoal_tac "b * (c - q mod c) < r * 1") apply (simp add: algebra_simps) apply (rule order_le_less_trans) apply (erule_tac [2] mult_strict_right_mono) apply (rule mult_left_mono_neg) using add1_zle_eq[of "q mod c"]apply(simp add: algebra_simps) apply (simp) apply (simp) done lemma zmult2_lemma_aux2: "[| (0::int) < c; b < r; r \<le> 0 |] ==> b * (q mod c) + r \<le> 0" apply (subgoal_tac "b * (q mod c) \<le> 0") apply arith apply (simp add: mult_le_0_iff) done lemma zmult2_lemma_aux3: "[| (0::int) < c; 0 \<le> r; r < b |] ==> 0 \<le> b * (q mod c) + r" apply (subgoal_tac "0 \<le> b * (q mod c) ") apply arith apply (simp add: zero_le_mult_iff) done lemma zmult2_lemma_aux4: "[| (0::int) < c; 0 \<le> r; r < b |] ==> b * (q mod c) + r < b * c" apply (subgoal_tac "r * 1 < b * (c - q mod c) ") apply (simp add: right_diff_distrib) apply (rule order_less_le_trans) apply (erule mult_strict_right_mono) apply (rule_tac [2] mult_left_mono) apply simp using add1_zle_eq[of "q mod c"] apply (simp add: algebra_simps) apply simp done lemma zmult2_lemma: "[| divmod_int_rel a b (q, r); 0 < c |] ==> divmod_int_rel a (b * c) (q div c, b*(q mod c) + r)" by (auto simp add: mult.assoc divmod_int_rel_def linorder_neq_iff zero_less_mult_iff distrib_left [symmetric] zmult2_lemma_aux1 zmult2_lemma_aux2 zmult2_lemma_aux3 zmult2_lemma_aux4 mult_less_0_iff split: if_split_asm) lemma zdiv_zmult2_eq: fixes a b c :: int shows "0 \<le> c \<Longrightarrow> a div (b * c) = (a div b) div c" apply (case_tac "b = 0", simp) apply (force simp add: le_less divmod_int_rel [THEN zmult2_lemma, THEN div_int_unique]) done lemma zmod_zmult2_eq: fixes a b c :: int shows "0 \<le> c \<Longrightarrow> a mod (b * c) = b * (a div b mod c) + a mod b" apply (case_tac "b = 0", simp) apply (force simp add: le_less divmod_int_rel [THEN zmult2_lemma, THEN mod_int_unique]) done lemma div_pos_geq: fixes k l :: int assumes "0 < l" and "l \<le> k" shows "k div l = (k - l) div l + 1" proof - have "k = (k - l) + l" by simp then obtain j where k: "k = j + l" .. with assms show ?thesis by (simp add: div_add_self2) qed lemma mod_pos_geq: fixes k l :: int assumes "0 < l" and "l \<le> k" shows "k mod l = (k - l) mod l" proof - have "k = (k - l) + l" by simp then obtain j where k: "k = j + l" .. with assms show ?thesis by simp qed subsubsection \<open>Splitting Rules for div and mod\<close> text\<open>The proofs of the two lemmas below are essentially identical\<close> lemma split_pos_lemma: "0<k ==> P(n div k :: int)(n mod k) = (\<forall>i j. 0\<le>j & j<k & n = k*i + j --> P i j)" apply (rule iffI, clarify) apply (erule_tac P="P x y" for x y in rev_mp) apply (subst mod_add_eq) apply (subst zdiv_zadd1_eq) apply (simp add: div_pos_pos_trivial mod_pos_pos_trivial) txt\<open>converse direction\<close> apply (drule_tac x = "n div k" in spec) apply (drule_tac x = "n mod k" in spec, simp) done lemma split_neg_lemma: "k<0 ==> P(n div k :: int)(n mod k) = (\<forall>i j. k<j & j\<le>0 & n = k*i + j --> P i j)" apply (rule iffI, clarify) apply (erule_tac P="P x y" for x y in rev_mp) apply (subst mod_add_eq) apply (subst zdiv_zadd1_eq) apply (simp add: div_neg_neg_trivial mod_neg_neg_trivial) txt\<open>converse direction\<close> apply (drule_tac x = "n div k" in spec) apply (drule_tac x = "n mod k" in spec, simp) done lemma split_zdiv: "P(n div k :: int) = ((k = 0 --> P 0) & (0<k --> (\<forall>i j. 0\<le>j & j<k & n = k*i + j --> P i)) & (k<0 --> (\<forall>i j. k<j & j\<le>0 & n = k*i + j --> P i)))" apply (case_tac "k=0", simp) apply (simp only: linorder_neq_iff) apply (erule disjE) apply (simp_all add: split_pos_lemma [of concl: "%x y. P x"] split_neg_lemma [of concl: "%x y. P x"]) done lemma split_zmod: "P(n mod k :: int) = ((k = 0 --> P n) & (0<k --> (\<forall>i j. 0\<le>j & j<k & n = k*i + j --> P j)) & (k<0 --> (\<forall>i j. k<j & j\<le>0 & n = k*i + j --> P j)))" apply (case_tac "k=0", simp) apply (simp only: linorder_neq_iff) apply (erule disjE) apply (simp_all add: split_pos_lemma [of concl: "%x y. P y"] split_neg_lemma [of concl: "%x y. P y"]) done text \<open>Enable (lin)arith to deal with @{const divide} and @{const modulo} when these are applied to some constant that is of the form @{term "numeral k"}:\<close> declare split_zdiv [of _ _ "numeral k", arith_split] for k declare split_zmod [of _ _ "numeral k", arith_split] for k subsubsection \<open>Computing \<open>div\<close> and \<open>mod\<close> with shifting\<close> lemma pos_divmod_int_rel_mult_2: assumes "0 \<le> b" assumes "divmod_int_rel a b (q, r)" shows "divmod_int_rel (1 + 2*a) (2*b) (q, 1 + 2*r)" using assms unfolding divmod_int_rel_def by auto lemma neg_divmod_int_rel_mult_2: assumes "b \<le> 0" assumes "divmod_int_rel (a + 1) b (q, r)" shows "divmod_int_rel (1 + 2*a) (2*b) (q, 2*r - 1)" using assms unfolding divmod_int_rel_def by auto text\<open>computing div by shifting\<close> lemma pos_zdiv_mult_2: "(0::int) \<le> a ==> (1 + 2*b) div (2*a) = b div a" using pos_divmod_int_rel_mult_2 [OF _ divmod_int_rel] by (rule div_int_unique) lemma neg_zdiv_mult_2: assumes A: "a \<le> (0::int)" shows "(1 + 2*b) div (2*a) = (b+1) div a" using neg_divmod_int_rel_mult_2 [OF A divmod_int_rel] by (rule div_int_unique) (* FIXME: add rules for negative numerals *) lemma zdiv_numeral_Bit0 [simp]: "numeral (Num.Bit0 v) div numeral (Num.Bit0 w) = numeral v div (numeral w :: int)" unfolding numeral.simps unfolding mult_2 [symmetric] by (rule div_mult_mult1, simp) lemma zdiv_numeral_Bit1 [simp]: "numeral (Num.Bit1 v) div numeral (Num.Bit0 w) = (numeral v div (numeral w :: int))" unfolding numeral.simps unfolding mult_2 [symmetric] add.commute [of _ 1] by (rule pos_zdiv_mult_2, simp) lemma pos_zmod_mult_2: fixes a b :: int assumes "0 \<le> a" shows "(1 + 2 * b) mod (2 * a) = 1 + 2 * (b mod a)" using pos_divmod_int_rel_mult_2 [OF assms divmod_int_rel] by (rule mod_int_unique) lemma neg_zmod_mult_2: fixes a b :: int assumes "a \<le> 0" shows "(1 + 2 * b) mod (2 * a) = 2 * ((b + 1) mod a) - 1" using neg_divmod_int_rel_mult_2 [OF assms divmod_int_rel] by (rule mod_int_unique) (* FIXME: add rules for negative numerals *) lemma zmod_numeral_Bit0 [simp]: "numeral (Num.Bit0 v) mod numeral (Num.Bit0 w) = (2::int) * (numeral v mod numeral w)" unfolding numeral_Bit0 [of v] numeral_Bit0 [of w] unfolding mult_2 [symmetric] by (rule mod_mult_mult1) lemma zmod_numeral_Bit1 [simp]: "numeral (Num.Bit1 v) mod numeral (Num.Bit0 w) = 2 * (numeral v mod numeral w) + (1::int)" unfolding numeral_Bit1 [of v] numeral_Bit0 [of w] unfolding mult_2 [symmetric] add.commute [of _ 1] by (rule pos_zmod_mult_2, simp) lemma zdiv_eq_0_iff: "(i::int) div k = 0 \<longleftrightarrow> k=0 \<or> 0\<le>i \<and> i<k \<or> i\<le>0 \<and> k<i" (is "?L = ?R") proof assume ?L have "?L \<longrightarrow> ?R" by (rule split_zdiv[THEN iffD2]) simp with \<open>?L\<close> show ?R by blast next assume ?R thus ?L by(auto simp: div_pos_pos_trivial div_neg_neg_trivial) qed lemma zmod_trival_iff: fixes i k :: int shows "i mod k = i \<longleftrightarrow> k = 0 \<or> 0 \<le> i \<and> i < k \<or> i \<le> 0 \<and> k < i" proof - have "i mod k = i \<longleftrightarrow> i div k = 0" by safe (insert div_mult_mod_eq [of i k], auto) with zdiv_eq_0_iff show ?thesis by simp qed subsubsection \<open>Quotients of Signs\<close> lemma div_eq_minus1: "(0::int) < b ==> -1 div b = -1" by (simp add: divide_int_def) lemma zmod_minus1: "(0::int) < b ==> -1 mod b = b - 1" by (simp add: modulo_int_def) lemma div_neg_pos_less0: "[| a < (0::int); 0 < b |] ==> a div b < 0" apply (subgoal_tac "a div b \<le> -1", force) apply (rule order_trans) apply (rule_tac a' = "-1" in zdiv_mono1) apply (auto simp add: div_eq_minus1) done lemma div_nonneg_neg_le0: "[| (0::int) \<le> a; b < 0 |] ==> a div b \<le> 0" by (drule zdiv_mono1_neg, auto) lemma div_nonpos_pos_le0: "[| (a::int) \<le> 0; b > 0 |] ==> a div b \<le> 0" by (drule zdiv_mono1, auto) text\<open>Now for some equivalences of the form \<open>a div b >=< 0 \<longleftrightarrow> \<dots>\<close> conditional upon the sign of \<open>a\<close> or \<open>b\<close>. There are many more. They should all be simp rules unless that causes too much search.\<close> lemma pos_imp_zdiv_nonneg_iff: "(0::int) < b ==> (0 \<le> a div b) = (0 \<le> a)" apply auto apply (drule_tac [2] zdiv_mono1) apply (auto simp add: linorder_neq_iff) apply (simp (no_asm_use) add: linorder_not_less [symmetric]) apply (blast intro: div_neg_pos_less0) done lemma pos_imp_zdiv_pos_iff: "0<k \<Longrightarrow> 0 < (i::int) div k \<longleftrightarrow> k \<le> i" using pos_imp_zdiv_nonneg_iff[of k i] zdiv_eq_0_iff[of i k] by arith lemma neg_imp_zdiv_nonneg_iff: "b < (0::int) ==> (0 \<le> a div b) = (a \<le> (0::int))" apply (subst div_minus_minus [symmetric]) apply (subst pos_imp_zdiv_nonneg_iff, auto) done (*But not (a div b \<le> 0 iff a\<le>0); consider a=1, b=2 when a div b = 0.*) lemma pos_imp_zdiv_neg_iff: "(0::int) < b ==> (a div b < 0) = (a < 0)" by (simp add: linorder_not_le [symmetric] pos_imp_zdiv_nonneg_iff) (*Again the law fails for \<le>: consider a = -1, b = -2 when a div b = 0*) lemma neg_imp_zdiv_neg_iff: "b < (0::int) ==> (a div b < 0) = (0 < a)" by (simp add: linorder_not_le [symmetric] neg_imp_zdiv_nonneg_iff) lemma nonneg1_imp_zdiv_pos_iff: "(0::int) <= a \<Longrightarrow> (a div b > 0) = (a >= b & b>0)" apply rule apply rule using div_pos_pos_trivial[of a b]apply arith apply(cases "b=0")apply simp using div_nonneg_neg_le0[of a b]apply arith using int_one_le_iff_zero_less[of "a div b"] zdiv_mono1[of b a b]apply simp done lemma zmod_le_nonneg_dividend: "(m::int) \<ge> 0 ==> m mod k \<le> m" apply (rule split_zmod[THEN iffD2]) apply(fastforce dest: q_pos_lemma intro: split_mult_pos_le) done subsubsection \<open>Computation of Division and Remainder\<close> instantiation int :: semiring_numeral_div begin definition divmod_int :: "num \<Rightarrow> num \<Rightarrow> int \<times> int" where "divmod_int m n = (numeral m div numeral n, numeral m mod numeral n)" definition divmod_step_int :: "num \<Rightarrow> int \<times> int \<Rightarrow> int \<times> int" where "divmod_step_int l qr = (let (q, r) = qr in if r \<ge> numeral l then (2 * q + 1, r - numeral l) else (2 * q, r))" instance by standard (auto intro: zmod_le_nonneg_dividend simp add: divmod_int_def divmod_step_int_def pos_imp_zdiv_pos_iff div_pos_pos_trivial mod_pos_pos_trivial zmod_zmult2_eq zdiv_zmult2_eq) end declare divmod_algorithm_code [where ?'a = int, code] context begin qualified definition adjust_div :: "int \<times> int \<Rightarrow> int" where "adjust_div qr = (let (q, r) = qr in q + of_bool (r \<noteq> 0))" qualified lemma adjust_div_eq [simp, code]: "adjust_div (q, r) = q + of_bool (r \<noteq> 0)" by (simp add: adjust_div_def) qualified definition adjust_mod :: "int \<Rightarrow> int \<Rightarrow> int" where [simp]: "adjust_mod l r = (if r = 0 then 0 else l - r)" lemma minus_numeral_div_numeral [simp]: "- numeral m div numeral n = - (adjust_div (divmod m n) :: int)" proof - have "int (fst (divmod m n)) = fst (divmod m n)" by (simp only: fst_divmod divide_int_def) auto then show ?thesis by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def) qed lemma minus_numeral_mod_numeral [simp]: "- numeral m mod numeral n = adjust_mod (numeral n) (snd (divmod m n) :: int)" proof - have "int (snd (divmod m n)) = snd (divmod m n)" if "snd (divmod m n) \<noteq> (0::int)" using that by (simp only: snd_divmod modulo_int_def) auto then show ?thesis by (auto simp add: split_def Let_def adjust_div_def divides_aux_def modulo_int_def) qed lemma numeral_div_minus_numeral [simp]: "numeral m div - numeral n = - (adjust_div (divmod m n) :: int)" proof - have "int (fst (divmod m n)) = fst (divmod m n)" by (simp only: fst_divmod divide_int_def) auto then show ?thesis by (auto simp add: split_def Let_def adjust_div_def divides_aux_def divide_int_def) qed lemma numeral_mod_minus_numeral [simp]: "numeral m mod - numeral n = - adjust_mod (numeral n) (snd (divmod m n) :: int)" proof - have "int (snd (divmod m n)) = snd (divmod m n)" if "snd (divmod m n) \<noteq> (0::int)" using that by (simp only: snd_divmod modulo_int_def) auto then show ?thesis by (auto simp add: split_def Let_def adjust_div_def divides_aux_def modulo_int_def) qed lemma minus_one_div_numeral [simp]: "- 1 div numeral n = - (adjust_div (divmod Num.One n) :: int)" using minus_numeral_div_numeral [of Num.One n] by simp lemma minus_one_mod_numeral [simp]: "- 1 mod numeral n = adjust_mod (numeral n) (snd (divmod Num.One n) :: int)" using minus_numeral_mod_numeral [of Num.One n] by simp lemma one_div_minus_numeral [simp]: "1 div - numeral n = - (adjust_div (divmod Num.One n) :: int)" using numeral_div_minus_numeral [of Num.One n] by simp lemma one_mod_minus_numeral [simp]: "1 mod - numeral n = - adjust_mod (numeral n) (snd (divmod Num.One n) :: int)" using numeral_mod_minus_numeral [of Num.One n] by simp end subsubsection \<open>Further properties\<close> text \<open>Simplify expresions in which div and mod combine numerical constants\<close> lemma int_div_pos_eq: "\<lbrakk>(a::int) = b * q + r; 0 \<le> r; r < b\<rbrakk> \<Longrightarrow> a div b = q" by (rule div_int_unique [of a b q r]) (simp add: divmod_int_rel_def) lemma int_div_neg_eq: "\<lbrakk>(a::int) = b * q + r; r \<le> 0; b < r\<rbrakk> \<Longrightarrow> a div b = q" by (rule div_int_unique [of a b q r], simp add: divmod_int_rel_def) lemma int_mod_pos_eq: "\<lbrakk>(a::int) = b * q + r; 0 \<le> r; r < b\<rbrakk> \<Longrightarrow> a mod b = r" by (rule mod_int_unique [of a b q r], simp add: divmod_int_rel_def) lemma int_mod_neg_eq: "\<lbrakk>(a::int) = b * q + r; r \<le> 0; b < r\<rbrakk> \<Longrightarrow> a mod b = r" by (rule mod_int_unique [of a b q r], simp add: divmod_int_rel_def) lemma abs_div: "(y::int) dvd x \<Longrightarrow> \<bar>x div y\<bar> = \<bar>x\<bar> div \<bar>y\<bar>" by (unfold dvd_def, cases "y=0", auto simp add: abs_mult) text\<open>Suggested by Matthias Daum\<close> lemma int_power_div_base: "\<lbrakk>0 < m; 0 < k\<rbrakk> \<Longrightarrow> k ^ m div k = (k::int) ^ (m - Suc 0)" apply (subgoal_tac "k ^ m = k ^ ((m - Suc 0) + Suc 0)") apply (erule ssubst) apply (simp only: power_add) apply simp_all done text \<open>by Brian Huffman\<close> lemma zminus_zmod: "- ((x::int) mod m) mod m = - x mod m" by (rule mod_minus_eq [symmetric]) lemma zdiff_zmod_left: "(x mod m - y) mod m = (x - y) mod (m::int)" by (rule mod_diff_left_eq [symmetric]) lemma zdiff_zmod_right: "(x - y mod m) mod m = (x - y) mod (m::int)" by (rule mod_diff_right_eq [symmetric]) lemmas zmod_simps = mod_add_left_eq [symmetric] mod_add_right_eq [symmetric] mod_mult_right_eq[symmetric] mod_mult_left_eq [symmetric] power_mod zminus_zmod zdiff_zmod_left zdiff_zmod_right text \<open>Distributive laws for function \<open>nat\<close>.\<close> lemma nat_div_distrib: "0 \<le> x \<Longrightarrow> nat (x div y) = nat x div nat y" apply (rule linorder_cases [of y 0]) apply (simp add: div_nonneg_neg_le0) apply simp apply (simp add: nat_eq_iff pos_imp_zdiv_nonneg_iff zdiv_int) done (*Fails if y<0: the LHS collapses to (nat z) but the RHS doesn't*) lemma nat_mod_distrib: "\<lbrakk>0 \<le> x; 0 \<le> y\<rbrakk> \<Longrightarrow> nat (x mod y) = nat x mod nat y" apply (case_tac "y = 0", simp) apply (simp add: nat_eq_iff zmod_int) done text \<open>transfer setup\<close> lemma transfer_nat_int_functions: "(x::int) >= 0 \<Longrightarrow> y >= 0 \<Longrightarrow> (nat x) div (nat y) = nat (x div y)" "(x::int) >= 0 \<Longrightarrow> y >= 0 \<Longrightarrow> (nat x) mod (nat y) = nat (x mod y)" by (auto simp add: nat_div_distrib nat_mod_distrib) lemma transfer_nat_int_function_closures: "(x::int) >= 0 \<Longrightarrow> y >= 0 \<Longrightarrow> x div y >= 0" "(x::int) >= 0 \<Longrightarrow> y >= 0 \<Longrightarrow> x mod y >= 0" apply (cases "y = 0") apply (auto simp add: pos_imp_zdiv_nonneg_iff) apply (cases "y = 0") apply auto done declare transfer_morphism_nat_int [transfer add return: transfer_nat_int_functions transfer_nat_int_function_closures ] lemma transfer_int_nat_functions: "(int x) div (int y) = int (x div y)" "(int x) mod (int y) = int (x mod y)" by (auto simp add: zdiv_int zmod_int) lemma transfer_int_nat_function_closures: "is_nat x \<Longrightarrow> is_nat y \<Longrightarrow> is_nat (x div y)" "is_nat x \<Longrightarrow> is_nat y \<Longrightarrow> is_nat (x mod y)" by (simp_all only: is_nat_def transfer_nat_int_function_closures) declare transfer_morphism_int_nat [transfer add return: transfer_int_nat_functions transfer_int_nat_function_closures ] text\<open>Suggested by Matthias Daum\<close> lemma int_div_less_self: "\<lbrakk>0 < x; 1 < k\<rbrakk> \<Longrightarrow> x div k < (x::int)" apply (subgoal_tac "nat x div nat k < nat x") apply (simp add: nat_div_distrib [symmetric]) apply (rule Divides.div_less_dividend, simp_all) done lemma zmod_eq_dvd_iff: "(x::int) mod n = y mod n \<longleftrightarrow> n dvd x - y" proof assume H: "x mod n = y mod n" hence "x mod n - y mod n = 0" by simp hence "(x mod n - y mod n) mod n = 0" by simp hence "(x - y) mod n = 0" by (simp add: mod_diff_eq[symmetric]) thus "n dvd x - y" by (simp add: dvd_eq_mod_eq_0) next assume H: "n dvd x - y" then obtain k where k: "x-y = n*k" unfolding dvd_def by blast hence "x = n*k + y" by simp hence "x mod n = (n*k + y) mod n" by simp thus "x mod n = y mod n" by (simp add: mod_add_left_eq) qed lemma nat_mod_eq_lemma: assumes xyn: "(x::nat) mod n = y mod n" and xy:"y \<le> x" shows "\<exists>q. x = y + n * q" proof- from xy have th: "int x - int y = int (x - y)" by simp from xyn have "int x mod int n = int y mod int n" by (simp add: zmod_int [symmetric]) hence "int n dvd int x - int y" by (simp only: zmod_eq_dvd_iff[symmetric]) hence "n dvd x - y" by (simp add: th zdvd_int) then show ?thesis using xy unfolding dvd_def apply clarsimp apply (rule_tac x="k" in exI) by arith qed lemma nat_mod_eq_iff: "(x::nat) mod n = y mod n \<longleftrightarrow> (\<exists>q1 q2. x + n * q1 = y + n * q2)" (is "?lhs = ?rhs") proof assume H: "x mod n = y mod n" {assume xy: "x \<le> y" from H have th: "y mod n = x mod n" by simp from nat_mod_eq_lemma[OF th xy] have ?rhs apply clarify apply (rule_tac x="q" in exI) by (rule exI[where x="0"], simp)} moreover {assume xy: "y \<le> x" from nat_mod_eq_lemma[OF H xy] have ?rhs apply clarify apply (rule_tac x="0" in exI) by (rule_tac x="q" in exI, simp)} ultimately show ?rhs using linear[of x y] by blast next assume ?rhs then obtain q1 q2 where q12: "x + n * q1 = y + n * q2" by blast hence "(x + n * q1) mod n = (y + n * q2) mod n" by simp thus ?lhs by simp qed subsubsection \<open>Dedicated simproc for calculation\<close> text \<open> There is space for improvement here: the calculation itself could be carried outside the logic, and a generic simproc (simplifier setup) for generic calculation would be helpful. \<close> simproc_setup numeral_divmod ("0 div 0 :: 'a :: semiring_numeral_div" | "0 mod 0 :: 'a :: semiring_numeral_div" | "0 div 1 :: 'a :: semiring_numeral_div" | "0 mod 1 :: 'a :: semiring_numeral_div" | "0 div - 1 :: int" | "0 mod - 1 :: int" | "0 div numeral b :: 'a :: semiring_numeral_div" | "0 mod numeral b :: 'a :: semiring_numeral_div" | "0 div - numeral b :: int" | "0 mod - numeral b :: int" | "1 div 0 :: 'a :: semiring_numeral_div" | "1 mod 0 :: 'a :: semiring_numeral_div" | "1 div 1 :: 'a :: semiring_numeral_div" | "1 mod 1 :: 'a :: semiring_numeral_div" | "1 div - 1 :: int" | "1 mod - 1 :: int" | "1 div numeral b :: 'a :: semiring_numeral_div" | "1 mod numeral b :: 'a :: semiring_numeral_div" | "1 div - numeral b :: int" |"1 mod - numeral b :: int" | "- 1 div 0 :: int" | "- 1 mod 0 :: int" | "- 1 div 1 :: int" | "- 1 mod 1 :: int" | "- 1 div - 1 :: int" | "- 1 mod - 1 :: int" | "- 1 div numeral b :: int" | "- 1 mod numeral b :: int" | "- 1 div - numeral b :: int" | "- 1 mod - numeral b :: int" | "numeral a div 0 :: 'a :: semiring_numeral_div" | "numeral a mod 0 :: 'a :: semiring_numeral_div" | "numeral a div 1 :: 'a :: semiring_numeral_div" | "numeral a mod 1 :: 'a :: semiring_numeral_div" | "numeral a div - 1 :: int" | "numeral a mod - 1 :: int" | "numeral a div numeral b :: 'a :: semiring_numeral_div" | "numeral a mod numeral b :: 'a :: semiring_numeral_div" | "numeral a div - numeral b :: int" | "numeral a mod - numeral b :: int" | "- numeral a div 0 :: int" | "- numeral a mod 0 :: int" | "- numeral a div 1 :: int" | "- numeral a mod 1 :: int" | "- numeral a div - 1 :: int" | "- numeral a mod - 1 :: int" | "- numeral a div numeral b :: int" | "- numeral a mod numeral b :: int" | "- numeral a div - numeral b :: int" | "- numeral a mod - numeral b :: int") = \<open> let val if_cong = the (Code.get_case_cong @{theory} @{const_name If}); fun successful_rewrite ctxt ct = let val thm = Simplifier.rewrite ctxt ct in if Thm.is_reflexive thm then NONE else SOME thm end; in fn phi => let val simps = Morphism.fact phi (@{thms div_0 mod_0 div_by_0 mod_by_0 div_by_1 mod_by_1 one_div_numeral one_mod_numeral minus_one_div_numeral minus_one_mod_numeral one_div_minus_numeral one_mod_minus_numeral numeral_div_numeral numeral_mod_numeral minus_numeral_div_numeral minus_numeral_mod_numeral numeral_div_minus_numeral numeral_mod_minus_numeral div_minus_minus mod_minus_minus Divides.adjust_div_eq of_bool_eq one_neq_zero numeral_neq_zero neg_equal_0_iff_equal arith_simps arith_special divmod_trivial divmod_cancel divmod_steps divmod_step_eq fst_conv snd_conv numeral_One case_prod_beta rel_simps Divides.adjust_mod_def div_minus1_right mod_minus1_right minus_minus numeral_times_numeral mult_zero_right mult_1_right} @ [@{lemma "0 = 0 \<longleftrightarrow> True" by simp}]); fun prepare_simpset ctxt = HOL_ss |> Simplifier.simpset_map ctxt (Simplifier.add_cong if_cong #> fold Simplifier.add_simp simps) in fn ctxt => successful_rewrite (Simplifier.put_simpset (prepare_simpset ctxt) ctxt) end end; \<close> subsubsection \<open>Code generation\<close> code_identifier code_module Divides \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith lemma dvd_eq_mod_eq_0_numeral: "numeral x dvd (numeral y :: 'a) \<longleftrightarrow> numeral y mod numeral x = (0 :: 'a::semiring_div)" by (fact dvd_eq_mod_eq_0) declare minus_div_mult_eq_mod [symmetric, nitpick_unfold] hide_fact (open) div_0 div_by_0 end
/- Author: <Redacted for anonymized submission> -/ import data.mv_polynomial.comm_ring import data.polynomial.div import data.polynomial.field_division import algebra.polynomial.big_operators import .vars import ...attributes import ...integral_domain_tactic /-! # Knowledge Soundness This file proves the knowledge-soundness property of the second, refined protocol described in the Pinocchio paper. -/ open_locale big_operators section noncomputable theory universes u /-- The finite field parameter of our SNARK -/ parameter {F : Type u} parameter [field F] /-- The naturals representing: m - m from paper - The QAP size n_in - n from paper - the number of inputs n_out - n' from paper - the number of outputs n_mid - (m - N) from paper - the number of internal gates d - the degree of h -/ parameters {n_in n_out n_mid d : ℕ} -- N from paper def n_stmt := n_in + n_out -- Alternative name def n_wit := n_mid def m := n_stmt + n_wit /-- fin-indexed collections of polynomials from the quadratic arithmetic program -/ parameter {v_stmt : fin n_stmt → polynomial F } parameter {w_stmt : fin n_stmt → polynomial F } parameter {y_stmt : fin n_stmt → polynomial F } parameter {v_wit : fin n_wit → polynomial F } parameter {w_wit : fin n_wit → polynomial F } parameter {y_wit : fin n_wit → polynomial F } parameter {v_0 : polynomial F } parameter {w_0 : polynomial F } parameter {y_0 : polynomial F } /-- The roots of the polynomial t -/ parameter {r : fin m → F} /-- t is the polynomial divisibility by which is used to verify satisfaction of the QAP -/ def t : polynomial F := ∏ i in (finset.fin_range m), (polynomial.X - polynomial.C (r i)) /-- t has degree m -/ lemma nat_degree_t : t.nat_degree = m := begin -- rw polynomial.nat_degree, rw t, rw polynomial.nat_degree_prod, simp, intros i hi, exact polynomial.X_sub_C_ne_zero (r i), end lemma monic_t : t.monic := begin rw t, apply polynomial.monic_prod_of_monic, intros i hi, exact polynomial.monic_X_sub_C (r i), end lemma degree_t_pos : 0 < m → 0 < t.degree := begin intro hm, suffices h : t.degree = some m, rw h, apply with_bot.some_lt_some.2, exact hm, have h := nat_degree_t, rw polynomial.nat_degree at h, induction h1 : t.degree, rw h1 at h, rw option.get_or_else at h, rw h at hm, have h2 := has_lt.lt.false hm, exfalso, exact h2, rw h1 at h, rw option.get_or_else at h, rw h, end -- -- Single variable form of V_wit -- def V_wit_sv (a_wit : fin n_wit → F) : polynomial F -- := ∑ i in finset.fin_range n_wit, a_wit i • u_wit i -- /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ -- def V_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F -- := ∑ i in (finset.fin_range n_stmt), a_stmt i • u_stmt i /-- Definition 2 from Pinocchio -/ def satisfying (c_stmt : fin n_stmt → F) (c_wit : fin n_wit → F) := ( (v_0 + (∑ i in (finset.fin_range n_stmt), c_stmt i • v_stmt i) + ∑ i in (finset.fin_range n_wit), c_wit i • v_wit i) * (w_0 + (∑ i in (finset.fin_range n_stmt), c_stmt i • w_stmt i) + (∑ i in (finset.fin_range n_wit), c_wit i • w_wit i)) - (y_0 + (∑ i in (finset.fin_range n_stmt), c_stmt i • y_stmt i) + (∑ i in (finset.fin_range n_wit), c_wit i • y_wit i))) %ₘ t = 0 /- Multivariable polynomial definititons and ultilities -/ run_cmd mk_simp_attr `poly run_cmd tactic.add_doc_string `simp_attr.poly "Attribute for defintions of poly elements" -- Helpers for representing vars as polynomials @[poly] def r_v_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.r_v @[poly] def r_w_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.r_w @[poly] def s_poly : mv_polynomial vars (polynomial F) := mv_polynomial.C (polynomial.X) @[poly] def α_v_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.α_v @[poly] def α_w_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.α_w @[poly] def α_y_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.α_y @[poly] def β_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.β @[poly] def γ_poly : mv_polynomial vars (polynomial F) := mv_polynomial.X vars.γ /-- Additional variable defined in terms of others -/ @[poly] def r_y_poly : mv_polynomial vars (polynomial F) := r_v_poly * r_w_poly -- The crs elements as multivariate polynomials of the toxic waste samples: Evaluation key elements @[poly] def crs_v_wit_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := r_v_poly * mv_polynomial.C (v_wit k) @[poly] def crs_w_wit_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := r_w_poly * mv_polynomial.C (w_wit k) @[poly] def crs_y_wit_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := r_y_poly * mv_polynomial.C (y_wit k) @[poly] def crs_α_v_wit_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := α_v_poly * r_v_poly * mv_polynomial.C (v_wit k) @[poly] def crs_α_w_wit_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := α_w_poly * r_w_poly * mv_polynomial.C (w_wit k) @[poly] def crs_α_y_wit_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := α_y_poly * r_y_poly * mv_polynomial.C (y_wit k) @[poly] def crs_powers (i : fin d) : (mv_polynomial vars (polynomial F)) := mv_polynomial.C (polynomial.X ^ (i : ℕ)) @[poly] def crs_β_v_w_y_k (k : fin n_wit) : mv_polynomial vars (polynomial F) := β_poly * r_v_poly * mv_polynomial.C (v_wit k) + β_poly * r_w_poly * mv_polynomial.C (w_wit k) + β_poly * r_y_poly * mv_polynomial.C (y_wit k) -- The crs elements as multivariate polynomials of the toxic waste samples: Verification key elements @[poly] def crs_α_v : mv_polynomial vars (polynomial F) := α_v_poly @[poly] def crs_α_w : mv_polynomial vars (polynomial F) := α_w_poly @[poly] def crs_α_y : mv_polynomial vars (polynomial F) := α_y_poly @[poly] def crs_γ : mv_polynomial vars (polynomial F) := γ_poly @[poly] def crs_βγ : mv_polynomial vars (polynomial F) := β_poly * γ_poly @[poly] def crs_t : mv_polynomial vars (polynomial F) := r_y_poly * mv_polynomial.C (t) @[poly] def crs_v_0 : mv_polynomial vars (polynomial F) := r_v_poly * mv_polynomial.C (v_0) @[poly] def crs_w_0 : mv_polynomial vars (polynomial F) := r_w_poly * mv_polynomial.C (w_0) @[poly] def crs_y_0 : mv_polynomial vars (polynomial F) := r_y_poly * mv_polynomial.C (y_0) @[poly] def crs_v_stmt (i : fin n_stmt) : mv_polynomial vars (polynomial F) := r_v_poly * mv_polynomial.C (v_stmt i) @[poly] def crs_w_stmt (i : fin n_stmt) : mv_polynomial vars (polynomial F) := r_w_poly * mv_polynomial.C (w_stmt i) @[poly] def crs_y_stmt (i : fin n_stmt) : mv_polynomial vars (polynomial F) := r_y_poly * mv_polynomial.C (y_stmt i) -- Coefficients of the CRS elements in the representation of the v_wit proof element in the AGM parameters {v_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {v_wit_comp_crs_powers : fin d → F} parameters {v_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {v_wit_comp_crs_α_v : F} parameters {v_wit_comp_crs_α_w : F} parameters {v_wit_comp_crs_α_y : F} parameters {v_wit_comp_crs_γ : F} parameters {v_wit_comp_crs_βγ : F} parameters {v_wit_comp_crs_t : F} parameters {v_wit_comp_crs_v_0 : F} parameters {v_wit_comp_crs_w_0 : F} parameters {v_wit_comp_crs_y_0 : F} parameters {v_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {v_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {v_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the v_wit proof element in the AGM -/ def proof_v_wit : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (v_wit_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (v_wit_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (v_wit_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (v_wit_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (v_wit_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (v_wit_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (v_wit_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (v_wit_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (v_wit_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (v_wit_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the w_wit proof element in the AGM parameters {w_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {w_wit_comp_crs_powers : fin d → F} parameters {w_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {w_wit_comp_crs_α_v : F} parameters {w_wit_comp_crs_α_w : F} parameters {w_wit_comp_crs_α_y : F} parameters {w_wit_comp_crs_γ : F} parameters {w_wit_comp_crs_βγ : F} parameters {w_wit_comp_crs_t : F} parameters {w_wit_comp_crs_v_0 : F} parameters {w_wit_comp_crs_w_0 : F} parameters {w_wit_comp_crs_y_0 : F} parameters {w_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {w_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {w_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the w_wit proof element in the AGM -/ def proof_w_wit : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (w_wit_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (w_wit_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (w_wit_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (w_wit_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (w_wit_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (w_wit_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (w_wit_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (w_wit_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (w_wit_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (w_wit_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the y_wit proof element in the AGM parameters {y_wit_comp_crs_v_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_w_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_y_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_α_v_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_α_w_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_α_y_wit_k : fin n_wit → F} parameters {y_wit_comp_crs_powers : fin d → F} parameters {y_wit_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {y_wit_comp_crs_α_v : F} parameters {y_wit_comp_crs_α_w : F} parameters {y_wit_comp_crs_α_y : F} parameters {y_wit_comp_crs_γ : F} parameters {y_wit_comp_crs_βγ : F} parameters {y_wit_comp_crs_t : F} parameters {y_wit_comp_crs_v_0 : F} parameters {y_wit_comp_crs_w_0 : F} parameters {y_wit_comp_crs_y_0 : F} parameters {y_wit_comp_crs_v_stmt : fin n_stmt → F} parameters {y_wit_comp_crs_w_stmt : fin n_stmt → F} parameters {y_wit_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the w_wit proof element in the AGM -/ def proof_y_wit : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (y_wit_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (y_wit_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (y_wit_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (y_wit_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (y_wit_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (y_wit_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (y_wit_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (y_wit_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (y_wit_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (y_wit_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the h proof element in the AGM parameters {h_comp_crs_v_wit_k : fin n_wit → F} parameters {h_comp_crs_w_wit_k : fin n_wit → F} parameters {h_comp_crs_y_wit_k : fin n_wit → F} parameters {h_comp_crs_α_v_wit_k : fin n_wit → F} parameters {h_comp_crs_α_w_wit_k : fin n_wit → F} parameters {h_comp_crs_α_y_wit_k : fin n_wit → F} parameters {h_comp_crs_powers : fin d → F} parameters {h_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {h_comp_crs_α_v : F} parameters {h_comp_crs_α_w : F} parameters {h_comp_crs_α_y : F} parameters {h_comp_crs_γ : F} parameters {h_comp_crs_βγ : F} parameters {h_comp_crs_t : F} parameters {h_comp_crs_v_0 : F} parameters {h_comp_crs_w_0 : F} parameters {h_comp_crs_y_0 : F} parameters {h_comp_crs_v_stmt : fin n_stmt → F} parameters {h_comp_crs_w_stmt : fin n_stmt → F} parameters {h_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the h proof element in the AGM -/ def proof_h : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (h_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (h_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (h_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (h_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (h_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (h_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (h_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (h_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (h_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (h_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (h_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (h_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (h_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (h_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the α_v_wit proof element in the AGM parameters {v_wit'_comp_crs_v_wit_k : fin n_wit → F} parameters {v_wit'_comp_crs_w_wit_k : fin n_wit → F} parameters {v_wit'_comp_crs_y_wit_k : fin n_wit → F} parameters {v_wit'_comp_crs_α_v_wit_k : fin n_wit → F} parameters {v_wit'_comp_crs_α_w_wit_k : fin n_wit → F} parameters {v_wit'_comp_crs_α_y_wit_k : fin n_wit → F} parameters {v_wit'_comp_crs_powers : fin d → F} parameters {v_wit'_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {v_wit'_comp_crs_α_v : F} parameters {v_wit'_comp_crs_α_w : F} parameters {v_wit'_comp_crs_α_y : F} parameters {v_wit'_comp_crs_γ : F} parameters {v_wit'_comp_crs_βγ : F} parameters {v_wit'_comp_crs_t : F} parameters {v_wit'_comp_crs_v_0 : F} parameters {v_wit'_comp_crs_w_0 : F} parameters {v_wit'_comp_crs_y_0 : F} parameters {v_wit'_comp_crs_v_stmt : fin n_stmt → F} parameters {v_wit'_comp_crs_w_stmt : fin n_stmt → F} parameters {v_wit'_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the α_v_wit proof element in the AGM -/ def proof_v_wit' : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (v_wit'_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the α_w_wit proof element in the AGM parameters {w_wit'_comp_crs_v_wit_k : fin n_wit → F} parameters {w_wit'_comp_crs_w_wit_k : fin n_wit → F} parameters {w_wit'_comp_crs_y_wit_k : fin n_wit → F} parameters {w_wit'_comp_crs_α_v_wit_k : fin n_wit → F} parameters {w_wit'_comp_crs_α_w_wit_k : fin n_wit → F} parameters {w_wit'_comp_crs_α_y_wit_k : fin n_wit → F} parameters {w_wit'_comp_crs_powers : fin d → F} parameters {w_wit'_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {w_wit'_comp_crs_α_v : F} parameters {w_wit'_comp_crs_α_w : F} parameters {w_wit'_comp_crs_α_y : F} parameters {w_wit'_comp_crs_γ : F} parameters {w_wit'_comp_crs_βγ : F} parameters {w_wit'_comp_crs_t : F} parameters {w_wit'_comp_crs_v_0 : F} parameters {w_wit'_comp_crs_w_0 : F} parameters {w_wit'_comp_crs_y_0 : F} parameters {w_wit'_comp_crs_v_stmt : fin n_stmt → F} parameters {w_wit'_comp_crs_w_stmt : fin n_stmt → F} parameters {w_wit'_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the α_w_wit proof element in the AGM -/ def proof_w_wit' : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (w_wit'_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the α_y_wit proof element in the AGM parameters {y_wit'_comp_crs_v_wit_k : fin n_wit → F} parameters {y_wit'_comp_crs_w_wit_k : fin n_wit → F} parameters {y_wit'_comp_crs_y_wit_k : fin n_wit → F} parameters {y_wit'_comp_crs_α_v_wit_k : fin n_wit → F} parameters {y_wit'_comp_crs_α_w_wit_k : fin n_wit → F} parameters {y_wit'_comp_crs_α_y_wit_k : fin n_wit → F} parameters {y_wit'_comp_crs_powers : fin d → F} parameters {y_wit'_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {y_wit'_comp_crs_α_v : F} parameters {y_wit'_comp_crs_α_w : F} parameters {y_wit'_comp_crs_α_y : F} parameters {y_wit'_comp_crs_γ : F} parameters {y_wit'_comp_crs_βγ : F} parameters {y_wit'_comp_crs_t : F} parameters {y_wit'_comp_crs_v_0 : F} parameters {y_wit'_comp_crs_w_0 : F} parameters {y_wit'_comp_crs_y_0 : F} parameters {y_wit'_comp_crs_v_stmt : fin n_stmt → F} parameters {y_wit'_comp_crs_w_stmt : fin n_stmt → F} parameters {y_wit'_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the α_y_wit proof element in the AGM -/ def proof_y_wit' : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (y_wit'_comp_crs_w_stmt i)) -- Coefficients of the CRS elements in the representation of the Z proof element in the AGM parameters {Z_comp_crs_v_wit_k : fin n_wit → F} parameters {Z_comp_crs_w_wit_k : fin n_wit → F} parameters {Z_comp_crs_y_wit_k : fin n_wit → F} parameters {Z_comp_crs_α_v_wit_k : fin n_wit → F} parameters {Z_comp_crs_α_w_wit_k : fin n_wit → F} parameters {Z_comp_crs_α_y_wit_k : fin n_wit → F} parameters {Z_comp_crs_powers : fin d → F} parameters {Z_comp_crs_β_v_w_y_k : fin n_wit → F} parameters {Z_comp_crs_α_v : F} parameters {Z_comp_crs_α_w : F} parameters {Z_comp_crs_α_y : F} parameters {Z_comp_crs_γ : F} parameters {Z_comp_crs_βγ : F} parameters {Z_comp_crs_t : F} parameters {Z_comp_crs_v_0 : F} parameters {Z_comp_crs_w_0 : F} parameters {Z_comp_crs_y_0 : F} parameters {Z_comp_crs_v_stmt : fin n_stmt → F} parameters {Z_comp_crs_w_stmt : fin n_stmt → F} parameters {Z_comp_crs_y_stmt : fin n_stmt → F} /-- Polynomial form of the representation of the Z proof element in the AGM -/ def proof_Z : mv_polynomial vars (polynomial F) := ∑ i in (finset.fin_range n_wit), (crs_v_wit_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_y_wit_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_w_wit_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_w_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_v_wit_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_α_v_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_y_wit_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_α_y_wit_k i)) + ∑ i in (finset.fin_range n_wit), (crs_α_w_wit_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_α_w_wit_k i)) + ∑ i in (finset.fin_range d), (crs_powers i) * mv_polynomial.C (polynomial.C (Z_comp_crs_powers i)) + ∑ i in (finset.fin_range n_wit), (crs_β_v_w_y_k i) * mv_polynomial.C (polynomial.C (Z_comp_crs_β_v_w_y_k i)) + crs_α_v * mv_polynomial.C (polynomial.C (Z_comp_crs_α_v)) + crs_α_w * mv_polynomial.C (polynomial.C (Z_comp_crs_α_w)) + crs_α_y * mv_polynomial.C (polynomial.C (Z_comp_crs_α_y)) + crs_γ * mv_polynomial.C (polynomial.C (Z_comp_crs_γ)) + crs_βγ * mv_polynomial.C (polynomial.C (Z_comp_crs_βγ)) + crs_t * mv_polynomial.C (polynomial.C (Z_comp_crs_t)) + crs_v_0 * mv_polynomial.C (polynomial.C (Z_comp_crs_v_0)) + crs_w_0 * mv_polynomial.C (polynomial.C (Z_comp_crs_w_0)) + crs_y_0 * mv_polynomial.C (polynomial.C (Z_comp_crs_y_0)) + ∑ i in (finset.fin_range n_stmt), (crs_v_stmt i) * mv_polynomial.C (polynomial.C (Z_comp_crs_v_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_y_stmt i) * mv_polynomial.C (polynomial.C (Z_comp_crs_y_stmt i)) + ∑ i in (finset.fin_range n_stmt), (crs_w_stmt i) * mv_polynomial.C (polynomial.C (Z_comp_crs_w_stmt i)) -- Single variable form of V_wit def v_wit_sv (a_wit : fin n_wit → F) : polynomial F := ∑ i in finset.fin_range n_wit, a_wit i • v_wit i /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ def v_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F := ∑ i in (finset.fin_range n_stmt), a_stmt i • v_stmt i /-- V_stmt as a multivariable polynomial of vars.X -/ @[poly] def v_stmt_mv (a_stmt : fin n_stmt → F) : mv_polynomial vars (polynomial F) := mv_polynomial.C (v_stmt_sv a_stmt) /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ def y_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F := ∑ i in (finset.fin_range n_stmt), a_stmt i • y_stmt i /-- V_stmt as a multivariable polynomial of vars.X -/ @[poly] def y_stmt_mv (a_stmt : fin n_stmt → F) : mv_polynomial vars (polynomial F) := mv_polynomial.C (y_stmt_sv a_stmt) /-- The statement polynomial that the verifier computes from the statement bits, as a single variable polynomial -/ def w_stmt_sv (a_stmt : fin n_stmt → F) : polynomial F := ∑ i in (finset.fin_range n_stmt), a_stmt i • w_stmt i /-- V_stmt as a multivariable polynomial of vars.X -/ @[poly] def w_stmt_mv (a_stmt : fin n_stmt → F) : mv_polynomial vars (polynomial F) := mv_polynomial.C (w_stmt_sv a_stmt) -- /-- V as a multivariable polynomial -/ -- def proof_v (a_stmt : fin n_stmt → F) : mv_polynomial vars (polynomial F) -- := v_stmt_mv a_stmt + proof_v_wit /-- Multivariable version of t -/ @[poly] def t_mv : mv_polynomial vars (polynomial F) := mv_polynomial.C t -- Equations def eqnI (c_stmt : fin n_stmt → F ) : Prop := (crs_v_0 + r_v_poly * v_stmt_mv c_stmt + proof_v_wit) * (crs_w_0 + r_w_poly * w_stmt_mv c_stmt + proof_w_wit) = ((r_y_poly * t_mv) * proof_h) + (crs_y_0 + r_y_poly * y_stmt_mv c_stmt + proof_y_wit) def eqnII : Prop := proof_v_wit' = proof_v_wit * crs_α_v def eqnIII : Prop := proof_w_wit' = proof_w_wit * crs_α_w def eqnIV : Prop := proof_y_wit' = proof_y_wit * crs_α_y def eqnV : Prop := proof_Z * crs_γ = (proof_v_wit + proof_w_wit + proof_y_wit) * crs_βγ -- Coefficients open mv_polynomial finsupp -- lemma sadojfh (a b c : mv_polynomial vars (polynomial F)) : a + b - c = a -c + b := -- begin -- ring, -- end lemma eqnIIresults (eqnII_verified : eqnII) : proof_v_wit = r_v_poly * mv_polynomial.C ( ∑ i in (finset.fin_range n_wit), (v_wit i) * (polynomial.C (v_wit_comp_crs_v_wit_k i)) + v_0 * (polynomial.C v_wit_comp_crs_v_0) + ∑ i in finset.fin_range n_stmt, (v_stmt i) * (polynomial.C (v_wit_comp_crs_v_stmt i)) ) + ∑ x in finset.fin_range d, mv_polynomial.C (polynomial.X ^ (x : ℕ)) * mv_polynomial.C ( polynomial.C (v_wit_comp_crs_powers x)) := begin rw eqnII at eqnII_verified, simp_rw [proof_v_wit, proof_v_wit'] at eqnII_verified ⊢, -- simp_rw [proof_v_wit, proof_w_wit, proof_y_wit, proof_h, -- proof_v_wit', proof_w_wit', proof_y_wit', proof_Z] at eqnII_verified, simp only [] with poly at eqnII_verified ⊢, -- simp only [] with polynomial_nf_3 at eqn', simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnII_verified ⊢, have h11eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.β 1 + single vars.γ 1)) eqnII_verified, have h19eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.γ 1)) eqnII_verified, have h21eqnII := congr_arg (coeff (single vars.r_w 1 + single vars.α_v 1 + single vars.β 1)) eqnII_verified, have h22eqnII := congr_arg (coeff (single vars.α_v 2)) eqnII_verified, have h32eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.α_w 1)) eqnII_verified, have h38eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_v 1 + single vars.β 1)) eqnII_verified, have h52eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 2)) eqnII_verified, have h54eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.α_y 1)) eqnII_verified, have h71eqnII := congr_arg (coeff (single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, have h74eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 1 + single vars.β 1)) eqnII_verified, have h93eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, have h94eqnII := congr_arg (coeff (single vars.α_w 1 + single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, have h95eqnII := congr_arg (coeff (single vars.α_v 1)) eqnII_verified, have h96eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_v 1)) eqnII_verified, have h101eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_v 1 + single vars.α_y 1)) eqnII_verified, clear eqnII_verified, simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, simp only [] with finsupp_simp at *, simp only [h11eqnII, h19eqnII, h21eqnII, h22eqnII, h32eqnII, h38eqnII, h52eqnII, h54eqnII, h71eqnII, h74eqnII, h93eqnII, h94eqnII, h95eqnII, h96eqnII, h101eqnII], simp only [monomial_zero, add_zero, zero_add, <-monomial_add], rw <-sub_eq_zero, have h71eqnII' := congr_arg (monomial (single vars.r_w 1)) h71eqnII, have h93eqnII' := congr_arg (monomial (single vars.r_v 1 + single vars.r_w 1)) h93eqnII, simp only [monomial_zero, add_zero, zero_add, <-monomial_add] at h71eqnII' h93eqnII', rw <-h71eqnII', rw <-sub_eq_zero, rw <-h93eqnII', rw <-sub_eq_zero, abel, abel, -- Why two needed here? end -- lemma eqnIIresultsBetter (eqnII_verified : eqnII) (eqnV_verified : eqnV) : -- proof_v_wit -- = r_v_poly -- * ( -- ∑ i in (finset.fin_range n_wit), mv_polynomial.C (v_wit i) * mv_polynomial.C (polynomial.C (Z_comp_crs_β_v_w_y_k i)) -- ) -- + ∑ x in finset.fin_range d, mv_polynomial.C (polynomial.X ^ (x : ℕ)) * mv_polynomial.C ( polynomial.C (v_wit_comp_crs_powers x)) := -- begin -- rw eqnII at eqnII_verified, -- rw eqnV at eqnV_verified, -- simp_rw [proof_v_wit, proof_v_wit'] at eqnII_verified ⊢, -- simp_rw [proof_v_wit, proof_w_wit, proof_y_wit, proof_Z] at eqnV_verified, -- simp only [] with poly at eqnII_verified eqnV_verified ⊢, -- -- simp only [] with polynomial_nf_3 at eqn', -- simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnII_verified eqnV_verified ⊢, -- have h11eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.β 1 + single vars.γ 1)) eqnII_verified, -- have h19eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.γ 1)) eqnII_verified, -- have h21eqnII := congr_arg (coeff (single vars.r_w 1 + single vars.α_v 1 + single vars.β 1)) eqnII_verified, -- have h22eqnII := congr_arg (coeff (single vars.α_v 2)) eqnII_verified, -- have h32eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.α_w 1)) eqnII_verified, -- have h38eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_v 1 + single vars.β 1)) eqnII_verified, -- have h52eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 2)) eqnII_verified, -- have h54eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.α_y 1)) eqnII_verified, -- have h71eqnII := congr_arg (coeff (single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, -- have h74eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 1 + single vars.β 1)) eqnII_verified, -- have h93eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, -- have h94eqnII := congr_arg (coeff (single vars.α_w 1 + single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, -- -- have h95eqnII := congr_arg (coeff (single vars.α_v 1)) eqnII_verified, -- -- have h96eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_v 1)) eqnII_verified, -- have h101eqnII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_v 1 + single vars.α_y 1)) eqnII_verified, -- have h2eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, -- clear eqnII_verified, -- clear eqnV_verified, -- simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, -- simp only [] with finsupp_simp at *, -- rw [h11eqnII, h19eqnII, h21eqnII, h22eqnII, h32eqnII, h38eqnII, h52eqnII, h54eqnII, h74eqnII, h94eqnII, h101eqnII, h2eqnV], -- h95eqnII, h96eqnII, -- simp only [monomial_zero, add_zero, zero_add, <-monomial_add], -- rw <-sub_eq_zero, -- have h71eqnII' := congr_arg (monomial (single vars.r_w 1)) h71eqnII, -- have h93eqnII' := congr_arg (monomial (single vars.r_v 1 + single vars.r_w 1)) h93eqnII, -- simp only [monomial_zero, add_zero, zero_add, <-monomial_add] at h71eqnII' h93eqnII', -- rw <-h71eqnII', -- rw <-sub_eq_zero, -- rw <-h93eqnII', -- rw <-sub_eq_zero, -- abel, -- end lemma eqnIIIresults (eqnIII_verified : eqnIII) : proof_w_wit = r_w_poly * mv_polynomial.C ( ∑ i in (finset.fin_range n_wit), (w_wit i) * (polynomial.C (w_wit_comp_crs_w_wit_k i)) + w_0 * (polynomial.C w_wit_comp_crs_w_0) + ∑ i in finset.fin_range n_stmt, (w_stmt i) * (polynomial.C (w_wit_comp_crs_w_stmt i)) ) + ∑ x in finset.fin_range d, mv_polynomial.C (polynomial.X ^ (x : ℕ)) * mv_polynomial.C ( polynomial.C (w_wit_comp_crs_powers x)) := begin rw eqnIII at eqnIII_verified, simp_rw [proof_w_wit, proof_w_wit'] at eqnIII_verified ⊢, -- simp_rw [proof_v_wit, proof_w_wit, proof_y_wit, proof_h, -- proof_v_wit', proof_w_wit', proof_y_wit', proof_Z] at eqnIII_verified, simp only [] with poly at eqnIII_verified ⊢, -- simp only [] with polynomial_nf_3 at eqn', simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnIII_verified ⊢, have h27eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_w 1)) eqnIII_verified, have h32eqnIII := congr_arg (coeff (single vars.α_v 1 + single vars.α_w 1)) eqnIII_verified, have h33eqnIII := congr_arg (coeff (single vars.r_w 1 + single vars.α_w 1)) eqnIII_verified, have h34eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.α_w 1 + single vars.β 1)) eqnIII_verified, have h35eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_w 1 + single vars.α_y 1)) eqnIII_verified, have h53eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.β 1 + single vars.γ 1)) eqnIII_verified, have h61eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.γ 1)) eqnIII_verified, have h75eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_w 1 + single vars.β 1)) eqnIII_verified, have h81eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.α_w 1)) eqnIII_verified, have h88eqnIII := congr_arg (coeff (single vars.r_w 1 + single vars.α_w 1 + single vars.β 1)) eqnIII_verified, have h89eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.α_y 1)) eqnIII_verified, have h96eqnIII := congr_arg (coeff (single vars.α_w 2)) eqnIII_verified, have h97eqnIII := congr_arg (coeff (single vars.α_w 2 + single vars.r_w 1)) eqnIII_verified, have h98eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.α_v 1 + single vars.r_v 1)) eqnIII_verified, clear eqnIII_verified, simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, simp only [] with finsupp_simp at *, simp only [h27eqnIII, h32eqnIII, h33eqnIII, h34eqnIII, h35eqnIII, h53eqnIII, h61eqnIII, h75eqnIII, h81eqnIII, h88eqnIII, h89eqnIII, h96eqnIII, h97eqnIII, h98eqnIII], simp only [monomial_zero, add_zero, zero_add, <-monomial_add], rw <-sub_eq_zero, have h81eqnIII' := congr_arg (monomial (single vars.r_v 1)) h81eqnIII, have h27eqnIII' := congr_arg (monomial (single vars.r_v 1 + single vars.r_w 1)) h27eqnIII, simp only [monomial_zero, add_zero, zero_add, <-monomial_add] at h81eqnIII' h27eqnIII', rw <-h81eqnIII', rw <-sub_eq_zero, rw <-h27eqnIII', rw <-sub_eq_zero, abel, abel, end lemma eqnIVresults (eqnIV_verified : eqnIV) : proof_y_wit = r_y_poly * mv_polynomial.C ( ∑ i in (finset.fin_range n_wit), (y_wit i) * (polynomial.C (y_wit_comp_crs_y_wit_k i)) + y_0 * (polynomial.C y_wit_comp_crs_y_0) + ∑ i in finset.fin_range n_stmt, (y_stmt i) * (polynomial.C (y_wit_comp_crs_y_stmt i)) + t * (polynomial.C y_wit_comp_crs_t) ) + ∑ x in finset.fin_range d, mv_polynomial.C (polynomial.X ^ (x : ℕ)) * mv_polynomial.C ( polynomial.C (y_wit_comp_crs_powers x)) := begin rw eqnIV at eqnIV_verified, simp_rw [proof_y_wit, proof_y_wit'] at eqnIV_verified ⊢, -- simp_rw [proof_v_wit, proof_w_wit, proof_y_wit, proof_h, -- proof_v_wit', proof_w_wit', proof_y_wit', proof_Z] at eqnIV_verified, simp only [] with poly at eqnIV_verified ⊢, -- simp only [] with polynomial_nf_3 at eqn', simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnIV_verified ⊢, have h2eqnIV := congr_arg (coeff (single vars.r_w 1 + single vars.α_y 1 + single vars.β 1)) eqnIV_verified, have h4eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 1 + single vars.α_y 1)) eqnIV_verified, have h23eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 2)) eqnIV_verified, have h25eqnIV := congr_arg (coeff (single vars.r_w 1 + single vars.α_w 1 + single vars.α_y 1)) eqnIV_verified, have h30eqnIV := congr_arg (coeff (single vars.α_y 1 + single vars.β 1 + single vars.γ 1)) eqnIV_verified, have h37eqnIV := congr_arg (coeff (single vars.α_y 1 + single vars.γ 1)) eqnIV_verified, have h54eqnIV := congr_arg (coeff (single vars.α_v 1 + single vars.α_y 1)) eqnIV_verified, have h55eqnIV := congr_arg (coeff (single vars.r_w 1 + single vars.α_y 1)) eqnIV_verified, have h56eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 1 + single vars.β 1)) eqnIV_verified, have h57eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.α_y 1 + single vars.β 1)) eqnIV_verified, have h59eqnIV := congr_arg (coeff (single vars.α_y 2)) eqnIV_verified, have h89eqnIV := congr_arg (coeff (single vars.α_w 1 + single vars.α_y 1)) eqnIV_verified, have h102eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.α_y 1)) eqnIV_verified, clear eqnIV_verified, simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, simp only [] with finsupp_simp at *, simp only [h2eqnIV, h4eqnIV, h23eqnIV, h25eqnIV, h30eqnIV, h37eqnIV, h54eqnIV, h55eqnIV, h56eqnIV, h57eqnIV, h59eqnIV, h89eqnIV, h102eqnIV], simp only [monomial_zero, add_zero, zero_add, <-monomial_add], rw <-sub_eq_zero, have h55eqnIV' := congr_arg (monomial (single vars.r_w 1)) h55eqnIV, have h102eqnIV' := congr_arg (monomial (single vars.r_v 1)) h102eqnIV, simp only [monomial_zero, add_zero, zero_add, <-monomial_add] at h55eqnIV' h102eqnIV', rw <-h55eqnIV', rw <-sub_eq_zero, rw <-h102eqnIV', rw <-sub_eq_zero, abel, abel, end lemma polynomial.mul_mod_by_monic (t p : polynomial F) (mt : t.monic) : (t * p) %ₘ t = 0 := begin rw polynomial.dvd_iff_mod_by_monic_eq_zero, apply dvd_mul_right, exact mt, end lemma move_C_left (p : polynomial F) (f : F) : p * polynomial.C f = polynomial.C f * p := begin ring, end lemma soundness (c_stmt : fin n_stmt → F ) (eqnI_verified : eqnI c_stmt) (eqnII_verified : eqnII) (eqnIII_verified : eqnIII) (eqnIV_verified : eqnIV) (eqnV_verified : eqnV) : (satisfying c_stmt Z_comp_crs_β_v_w_y_k) := begin rw eqnV at eqnV_verified, have eqnII' := eqnIIresults eqnII_verified, have eqnIII' := eqnIIIresults eqnIII_verified, have eqnIV' := eqnIVresults eqnIV_verified, simp_rw [eqnII', eqnIII', eqnIV', proof_Z] at eqnV_verified, -- simp_rw [proof_v_wit, proof_w_wit, proof_y_wit, proof_h, -- proof_v_wit', proof_w_wit', proof_y_wit', proof_Z] at eqnV_verified, simp only [] with poly at eqnV_verified, -- simp only [] with polynomial_nf_3 at eqn', simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnV_verified, have h2eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, have h3eqnV := congr_arg (coeff (single vars.r_w 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, have h4eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, -- have h4eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 1 + single vars.α_y 1)) eqnV_verified, -- have h23eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 2)) eqnV_verified, -- have h25eqnV := congr_arg (coeff (single vars.r_w 1 + single vars.α_w 1 + single vars.α_y 1)) eqnV_verified, -- have h30eqnV := congr_arg (coeff (single vars.α_y 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, -- have h37eqnV := congr_arg (coeff (single vars.α_y 1 + single vars.γ 1)) eqnV_verified, -- have h54eqnV := congr_arg (coeff (single vars.α_v 1 + single vars.α_y 1)) eqnV_verified, -- have h55eqnV := congr_arg (coeff (single vars.r_w 1 + single vars.α_y 1)) eqnV_verified, -- have h56eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 1 + single vars.β 1)) eqnV_verified, -- have h57eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.α_y 1 + single vars.β 1)) eqnV_verified, -- have h59eqnV := congr_arg (coeff (single vars.α_y 2)) eqnV_verified, -- have h89eqnV := congr_arg (coeff (single vars.α_w 1 + single vars.α_y 1)) eqnV_verified, -- have h102eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.α_y 1)) eqnV_verified, clear eqnV_verified, simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, simp only [] with finsupp_simp at *, rw [<-h2eqnV] at eqnII', rw [<-h3eqnV] at eqnIII', rw [<-h4eqnV] at eqnIV', rw [eqnI] at eqnI_verified, rw satisfying, simp_rw [eqnII', eqnIII', eqnIV', proof_h] at eqnI_verified, simp only [] with poly at eqnI_verified, -- simp only [] with polynomial_nf_3 at eqn', simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnI_verified, have h1eqnI := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1)) eqnI_verified, clear eqnI_verified, simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at h1eqnI, simp only [] with finsupp_simp at h1eqnI, rw <-sub_eq_iff_eq_add at h1eqnI, -- rw <-sub_eq_zero at h1eqnI, -- rw polynomial.dvd_iff_mod_by_monic_eq_zero, have h2eqnI := congr_arg (%ₘ t) h1eqnI, simp only [polynomial.zero_mod_by_monic] at h2eqnI, rw polynomial.mul_mod_by_monic at h2eqnI, rw <- h2eqnI, congr' 1, simp_rw [v_stmt_sv, w_stmt_sv, y_stmt_sv, polynomial.smul_eq_C_mul], simp only [add_mul, mul_add], simp_rw [move_C_left], -- congr' 1, -- rw <-sub_eq_zero, abel, exact monic_t, end #exit /-- Show that if the adversary polynomials obey the equations, then the coefficients give a satisfying witness. -/ theorem soundness (c_stmt : fin n_stmt → F ) : (0 < m) -> eqnI c_stmt -> eqnII -> eqnIII -> eqnIV -> eqnV -> (satisfying c_stmt Z_comp_crs_β_v_w_y_k) -- This shows that (a`+1, . . . , am) = (C`+1, . . . , Cm) is a witness for the statement (a1, . . . , a`) := begin intros hm eqnI_verified eqnII_verified eqnIII_verified eqnIV_verified eqnV_verified, -- have foo := congr_arg (mv_polynomial.coeff (finsupp.single vars.r_v 1)) eqnII_verified, -- rw [proof_v_wit', proof_v_wit, crs_α_v] at foo, -- simp [crs_v_wit_k] at foo, -- simp only with coeff_simp at foo, rw eqnI at eqnI_verified, rw eqnII at eqnII_verified, rw eqnIII at eqnIII_verified, rw eqnIV at eqnIV_verified, rw eqnV at eqnV_verified, -- done, simp_rw [proof_v_wit, proof_w_wit, proof_y_wit, proof_h, proof_v_wit', proof_w_wit', proof_y_wit', proof_Z] at eqnI_verified eqnII_verified eqnIII_verified eqnIV_verified eqnV_verified, simp only [] with poly at eqnI_verified eqnII_verified eqnIII_verified eqnIV_verified eqnV_verified, -- simp only [] with polynomial_nf_3 at eqn', simp only [mv_polynomial.X, C_apply, mv_polynomial.monomial_mul, one_mul, mul_one, add_zero, zero_add, finset.sum_add_distrib, finset.sum_hom, mul_add, add_mul, sum_monomial_hom] at eqnI_verified eqnII_verified eqnIII_verified eqnIV_verified eqnV_verified, -- clear eqnI_verified, -- From II, II and IV, telling us that many coefficients of v_wit, w_wit, y_wit are 0. have h1eqnI := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1)) eqnI_verified, have h11eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.β 1 + single vars.γ 1)) eqnII_verified, have h19eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.γ 1)) eqnII_verified, have h21eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_w 1 + single vars.β 1)) eqnII_verified, have h22eqnII := congr_arg (coeff (single vars.α_v 2)) eqnII_verified, have h32eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.α_w 1)) eqnII_verified, have h38eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_v 1 + single vars.r_w 1 + single vars.β 1)) eqnII_verified, have h52eqnII := congr_arg (coeff (single vars.α_v 2 + single vars.r_v 1)) eqnII_verified, have h54eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.α_y 1)) eqnII_verified, have h71eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_w 1)) eqnII_verified, have h74eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_v 1 + single vars.β 1)) eqnII_verified, have h93eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_v 1 + single vars.r_w 1)) eqnII_verified, have h94eqnII := congr_arg (coeff (single vars.α_w 1 + single vars.r_w 1 + single vars.α_v 1)) eqnII_verified, have h101eqnII := congr_arg (coeff (single vars.α_v 1 + single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 1)) eqnII_verified, have h27eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.r_v 1 + single vars.r_w 1)) eqnIII_verified, have h32eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.α_v 1)) eqnIII_verified, have h33eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.r_w 1)) eqnIII_verified, have h34eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.α_w 1 + single vars.β 1)) eqnIII_verified, have h35eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_w 1 + single vars.α_y 1)) eqnIII_verified, have h53eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.β 1 + single vars.γ 1)) eqnIII_verified, have h61eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.γ 1)) eqnIII_verified, have h75eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_w 1 + single vars.β 1)) eqnIII_verified, have h81eqnIII := congr_arg (coeff (single vars.r_v 1 + single vars.α_w 1)) eqnIII_verified, have h88eqnIII := congr_arg (coeff (single vars.r_w 1 + single vars.α_w 1 + single vars.β 1)) eqnIII_verified, have h89eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.α_y 1)) eqnIII_verified, have h96eqnIII := congr_arg (coeff (single vars.α_w 2)) eqnIII_verified, have h97eqnIII := congr_arg (coeff (single vars.α_w 2 + single vars.r_w 1)) eqnIII_verified, have h98eqnIII := congr_arg (coeff (single vars.α_w 1 + single vars.α_v 1 + single vars.r_v 1)) eqnIII_verified, have h2eqnIV := congr_arg (coeff (single vars.r_w 1 + single vars.α_y 1 + single vars.β 1)) eqnIV_verified, have h4eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.α_v 1 + single vars.α_y 1)) eqnIV_verified, have h23eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 2)) eqnIV_verified, have h25eqnIV := congr_arg (coeff (single vars.r_w 1 + single vars.α_w 1 + single vars.α_y 1)) eqnIV_verified, have h30eqnIV := congr_arg (coeff (single vars.α_y 1 + single vars.β 1 + single vars.γ 1)) eqnIV_verified, have h37eqnIV := congr_arg (coeff (single vars.α_y 1 + single vars.γ 1)) eqnIV_verified, have h54eqnIV := congr_arg (coeff (single vars.α_v 1 + single vars.α_y 1)) eqnIV_verified, have h55eqnIV := congr_arg (coeff (single vars.r_w 1 + single vars.α_y 1)) eqnIV_verified, have h56eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.α_y 1 + single vars.β 1)) eqnIV_verified, have h57eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.α_y 1 + single vars.β 1)) eqnIV_verified, have h59eqnIV := congr_arg (coeff (single vars.α_y 2)) eqnIV_verified, have h89eqnIV := congr_arg (coeff (single vars.α_w 1 + single vars.α_y 1)) eqnIV_verified, have h102eqnIV := congr_arg (coeff (single vars.r_v 1 + single vars.α_y 1)) eqnIV_verified, have h2eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, have h3eqnV := congr_arg (coeff (single vars.r_w 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, have h4eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, clear eqnI_verified, clear eqnII_verified, clear eqnIII_verified, clear eqnIV_verified, clear eqnV_verified, simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, simp only [] with finsupp_simp at *, rw [h2eqnV, h3eqnV, h4eqnV] at h1eqnI, done, clear h2eqnV h3eqnV h4eqnV, simp only [h11eqnII, h19eqnII, h21eqnII, h22eqnII, h32eqnII, h38eqnII, h52eqnII, h54eqnII, h71eqnII, h74eqnII, h93eqnII, h94eqnII, h101eqnII, h27eqnIII, h32eqnIII, h33eqnIII, h34eqnIII, h35eqnIII, h53eqnIII, h61eqnIII, h75eqnIII, h81eqnIII, h88eqnIII, h89eqnIII, h96eqnIII, h97eqnIII, h98eqnIII, h2eqnIV, h4eqnIV, h23eqnIV, h25eqnIV, h30eqnIV, h37eqnIV, h54eqnIV, h55eqnIV, h56eqnIV, h57eqnIV, h59eqnIV, h89eqnIV, h102eqnIV] at h1eqnI, --TODO bring back eqnI -- have h12eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, -- have h13eqnV := congr_arg (coeff (single vars.r_w 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, -- have h14eqnV := congr_arg (coeff (single vars.r_v 1 + single vars.r_w 1 + single vars.β 1 + single vars.γ 1)) eqnV_verified, -- clear eqnV_verified, -- simp only [finsupp_vars_eq_ext] with coeff_simp finsupp_eq at *, -- simp only [] with finsupp_simp at *, -- simp only [*, zero_add, add_zero] at h12eqnV, clear h11eqnII h19eqnII h21eqnII h22eqnII h32eqnII h38eqnII h52eqnII h54eqnII h71eqnII h74eqnII h93eqnII h101eqnII h27eqnIII h32eqnIII h33eqnIII h34eqnIII h35eqnIII h53eqnIII h61eqnIII h75eqnIII h81eqnIII h88eqnIII h89eqnIII h96eqnIII h2eqnIV h4eqnIV h23eqnIV h25eqnIV h30eqnIV h37eqnIV h54eqnIV h55eqnIV h56eqnIV h57eqnIV h59eqnIV h89eqnIV h102eqnIV, done, -- Step 2: Recursively simplify and case-analyze the equations trace "Moving Cs right", simp only [simplifier1, simplifier2] at *, trace "Grouping distributivity", simp only [<-mul_add, <-add_mul, <-add_assoc, add_mul_distrib, add_mul_distrib'] at *, trace "Main simplification", simp only [*] with integral_domain_simp at *, tactic.integral_domain_tactic_v4, done, -- Solve remaining four cases by hand -- { rw [<-h1022, <-h0122, <-h0022], -- simp only [B_β_mul], -- simp only [<-mul_assoc], -- simp only [A_α_mul], -- simp only [<-mul_assoc], -- rw h1122, -- ring, }, end end
#!/usr/bin/env stack -- stack runghc --package reanimate {-# LANGUAGE OverloadedStrings #-} module Main (main) where import Data.Complex import qualified Data.Text as T import Graphics.SvgTree import Linear.V2 import Reanimate main :: IO () main = reanimate $ pauseAtEnd 2 fourierAnimation_ sWidth :: Double sWidth = 0.02 piFourier :: Fourier piFourier = mkFourier piPoints piPoints :: [RPoint] piPoints = lineToPoints 500 $ toLineCommands $ extractPath $ scale 10 $ center $ latexAlign "\\pi" fourierAnimation_ :: Animation fourierAnimation_ = mkAnimation 50 $ \t -> let fLength = t circles = setFourierLength (fLength*maxLength) piFourier maxLength = sum $ map magnitude $ take 499 $ drop 1 $ fourierCoefficients piFourier phi = fromToS 0 15 t in mkGroup [ mkBackground "black" , drawCircles $ fourierCoefficients $ rotateFourier phi circles , withStrokeColor "green" $ withFillOpacity 0 $ mkLinePath $ mkFourierOutline circles , withFillColor "white" $ translate (-screenWidth/16*7) (screenHeight/16*7) $ latex $ T.pack $ "Circles: " ++ show (length $ fourierCoefficients circles) ] newtype Fourier = Fourier {fourierCoefficients :: [Complex Double]} pointAtFourier :: Fourier -> Complex Double pointAtFourier = sum . fourierCoefficients mkFourier :: [RPoint] -> Fourier mkFourier points = Fourier $ findCoefficient 0 : concat [ [findCoefficient n, findCoefficient (-n)] | n <- [1..] ] where findCoefficient :: Int -> Complex Double findCoefficient n = sum [ toComplex point * exp (negate (fromIntegral n) * 2 *pi * i*t) * deltaT | (idx, point) <- zip [0::Int ..] points, let t = fromIntegral idx/nPoints ] i = 0 :+ 1 toComplex (V2 x y) = x :+ y deltaT = recip nPoints nPoints = fromIntegral (length points) -- setFourierCircles :: Double -> Fourier -> Fourier -- setFourierCircles n _ | n < 1 = error "Invalid argument. Need at least one circle." -- setFourierCircles n (Fourier coeffs) = -- Fourier $ take iCircles coeffs ++ [coeffs!!iCircles * realToFrac fCircle] -- where -- (iCircles, fCircle) = divMod' n 1 setFourierLength :: Double -> Fourier -> Fourier setFourierLength _ (Fourier []) = Fourier [] setFourierLength len0 (Fourier (first:lst)) = Fourier $ first : worker len0 lst where worker _len [] = [] worker len (c:cs) = if magnitude c < len then c : worker (len - magnitude c) cs else [c * realToFrac (len / magnitude c)] rotateFourier :: Double -> Fourier -> Fourier rotateFourier phi (Fourier coeffs) = Fourier $ worker coeffs (0::Integer) where worker [] _ = [] worker (x:rest) 0 = x : worker rest 1 worker [left] n = worker [left,0] n worker (left:right:rest) n = let n' = fromIntegral n in left * exp (negate n' * 2 * pi * i * phi') : right * exp (n' * 2 * pi * i * phi') : worker rest (n+1) i = 0 :+ 1 -- n = length coeffs `div` 2 phi' = realToFrac phi drawCircles :: [Complex Double] -> SVG drawCircles circles = mkGroup [ worker circles , withStrokeWidth sWidth $ withStrokeColor "white" $ withStrokeLineJoin JoinRound $ withFillOpacity 0 $ mkLinePath [ (x, y) | x :+ y <- scanl (+) 0 circles ] ] where worker [] = None worker (x :+ y : rest) = let radius = sqrt(x*x+y*y) in mkGroup [ withStrokeWidth sWidth $ withStrokeColor "dimgrey" $ withFillOpacity 0 $ mkCircle radius , translate x y $ worker rest ] mkFourierOutline :: Fourier -> [(Double, Double)] mkFourierOutline fourier = [ (x, y) | idx <- [0 .. granularity] , let x :+ y = pointAtFourier $ rotateFourier (idx/granularity) fourier ] where granularity = 500
#include "actions/Action.h" #include "actions/ActionFactory.h" #include "actions/LogicalNavigation.h" #include "actions/Load.h" #include "actions/Unload.h" #include "actions/Greet.h" #include "actions/Order.h" #include "actions/ChooseFloor.h" #include "kr_interface.h" #include <ros/ros.h> #include <iostream> #include <boost/concept_check.hpp> #include <boost/graph/graph_concepts.hpp> #include <list> using namespace bwi_actexec; using namespace std; std::list<Action *> computePlan(const std::string& ,unsigned int); bool checkPlan(const std::list<Action *> & plan, const std::string& goalSpecification); int main(int argc, char** argv) { ros::init(argc, argv, "bwi_action_executor"); ros::NodeHandle n; ros::Rate loop(10); //noop updates the fluents with the current position LogicalNavigation setInitialState("noop"); setInitialState.run(); //forever //TODO wait for a goal //string goal = ":- not served(alice,coffee,n)."; //string goal = ":- not at(f3_410,n)."; string goal; n.getParam("/bwi_action_executor/goal", goal); std::cerr << "Plan Goal is: "<< goal << endl; const unsigned int MAX_N = 40; std::cerr << "Comuputing inital plan"; std::list<Action *> plan = computePlan(goal, MAX_N); std::cerr << "Plan finished computing"; std::list< Action *>::iterator planit1 = plan.begin(); std::string ss1; int mycounter = 0; for (; planit1 != plan.end(); ++planit1){ ss1 = ss1 + (*planit1)->toASP(0) + " "; } for (; planit1 != plan.end(); ++planit1){ if ( (*planit1) == NULL ) { mycounter++; } } cerr << "[BWI_ACTION_EXECUTOR] Counter of nulls: " << mycounter << endl; std::cerr << "Plan Length is: " << plan.size() << std::endl; std::cerr << "The list of all the actions is: " << ss1 << std::endl; if(plan.empty()) throw runtime_error("The plan to achieve " + goal + " is empty!"); Action * currentAction = plan.front(); plan.pop_front(); while (ros::ok()) { ros::spinOnce(); if (!currentAction->hasFinished()) { cerr << "Executing the current action: " << currentAction->toASP(0) << endl; currentAction->run(); } else { // Move on to next action cerr << "Action " << currentAction->toASP(0) << "hasfinished()" << std::endl; delete currentAction; cerr << "Forward Projecting Plan to Check Validity..." << endl; bool valid = checkPlan(plan,goal); if(!valid) { //TODO consider plan repair //Destroy all actions still in the plan cerr << "Forward projection failed, destroying the plan" << endl; list<Action *>::iterator actIt = plan.begin(); for(; actIt != plan.end(); ++actIt) delete *actIt; plan.clear(); plan = computePlan(goal,MAX_N); // Print new plan std::list< Action *>::iterator planit2 = plan.begin(); std::string ss2; for (; planit2 != plan.end(); ++planit2){ ss2 = ss2 + (*planit2)->toASP(0) + " "; } std::cerr << "Plan Length is: " << plan.size() << std::endl; std::cerr << "The list of all the actions is: " << ss2 << std::endl; } if (plan.empty()) return 0; currentAction = plan.front(); plan.pop_front(); } loop.sleep(); } return 0; } std::list<Action *> computePlan(const std::string& goalSpecification, unsigned int max_n) { bwi_kr::AnswerSetMsg answerSet; for (int i=0; i<max_n && !answerSet.satisfied ; ++i) { stringstream goal; goal << goalSpecification << endl; goal << "#hide." << endl; ActionFactory::ActionMap::const_iterator actIt = ActionFactory::actions().begin(); for( ; actIt != ActionFactory::actions().end(); ++actIt) { //the last parameter is always the the step number goal << "#show " << actIt->second->getName() << "/" << actIt->second->paramNumber() + 1 << "." << endl; } answerSet = kr_query(goal.str(),i,"planQuery.asp"); } vector<bwi_kr::Predicate> &preds = answerSet.predicates; vector<Action *> planVector(preds.size()); for (int j=0 ; j<preds.size() ; ++j) { Action *act = ActionFactory::byName(preds[j].name); act->init(preds[j].parameters); planVector[preds[j].timeStep] = act; } list<Action *> plan(planVector.begin(),planVector.end()); return plan; } bool checkPlan(const std::list<Action *> & plan, const std::string& goalSpecification) { stringstream queryStream; list<Action *>::const_iterator planIt = plan.begin(); for(unsigned int timeStep = 0; planIt != plan.end(); ++planIt, ++timeStep) { queryStream << (*planIt)->toASP(timeStep) << "." << endl; } queryStream << goalSpecification << endl; bwi_kr::AnswerSetMsg answerSet = kr_query(queryStream.str(),plan.size(), "checkPlan.asp"); return answerSet.satisfied; }
Formal statement is: lemma convex_finite: assumes "finite S" shows "convex S \<longleftrightarrow> (\<forall>u. (\<forall>x\<in>S. 0 \<le> u x) \<and> sum u S = 1 \<longrightarrow> sum (\<lambda>x. u x *\<^sub>R x) S \<in> S)" (is "?lhs = ?rhs") Informal statement is: A finite set $S$ is convex if and only if for every function $u$ such that $u(x) \geq 0$ for all $x \in S$ and $\sum_{x \in S} u(x) = 1$, we have $\sum_{x \in S} u(x) x \in S$.
[GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι ι✝ : Type ?u.1725 v : ComplexShape ι✝ ⊢ Category.{?u.1722, max (max u v) ?u.1725} (HomotopyCategory V v) [PROOFSTEP] dsimp only [HomotopyCategory] [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι ι✝ : Type ?u.1725 v : ComplexShape ι✝ ⊢ Category.{?u.1722, max (max u v) ?u.1725} (CategoryTheory.Quotient (homotopic V v)) [PROOFSTEP] infer_instance -- TODO the homotopy_category is preadditive [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c f : C ⟶ D ⊢ Homotopy (Quot.out ((quotient V c).map f)) f [PROOFSTEP] apply homotopyOfEq [GOAL] case w ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c f : C ⟶ D ⊢ (quotient V c).map (Quot.out ((quotient V c).map f)) = (quotient V c).map f [PROOFSTEP] simp [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D E : HomotopyCategory V c f : C ⟶ D g : D ⟶ E ⊢ (quotient V c).map (Quot.out f ≫ Quot.out g) = f ≫ g [PROOFSTEP] simp [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c f : HomotopyEquiv C D ⊢ (quotient V c).map f.hom ≫ (quotient V c).map f.inv = 𝟙 ((quotient V c).obj C) [PROOFSTEP] rw [← (quotient V c).map_comp, ← (quotient V c).map_id] [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c f : HomotopyEquiv C D ⊢ (quotient V c).map (f.hom ≫ f.inv) = (quotient V c).map (𝟙 C) [PROOFSTEP] exact eq_of_homotopy _ _ f.homotopyHomInvId [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c f : HomotopyEquiv C D ⊢ (quotient V c).map f.inv ≫ (quotient V c).map f.hom = 𝟙 ((quotient V c).obj D) [PROOFSTEP] rw [← (quotient V c).map_comp, ← (quotient V c).map_id] [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c f : HomotopyEquiv C D ⊢ (quotient V c).map (f.inv ≫ f.hom) = (quotient V c).map (𝟙 D) [PROOFSTEP] exact eq_of_homotopy _ _ f.homotopyInvHomId [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c i : (quotient V c).obj C ≅ (quotient V c).obj D ⊢ (quotient V c).map (Quot.out i.hom ≫ Quot.out i.inv) = (quotient V c).map (𝟙 C) [PROOFSTEP] rw [quotient_map_out_comp_out, i.hom_inv_id, (quotient V c).map_id] [GOAL] ι : Type u_1 V : Type u inst✝¹ : Category.{v, u} V inst✝ : Preadditive V c : ComplexShape ι C D : HomologicalComplex V c i : (quotient V c).obj C ≅ (quotient V c).obj D ⊢ (quotient V c).map (Quot.out i.inv ≫ Quot.out i.hom) = (quotient V c).map (𝟙 D) [PROOFSTEP] rw [quotient_map_out_comp_out, i.inv_hom_id, (quotient V c).map_id] [GOAL] ι : Type u_1 V : Type u inst✝⁵ : Category.{v, u} V inst✝⁴ : Preadditive V c✝ : ComplexShape ι W : Type u_2 inst✝³ : Category.{?u.46796, u_2} W inst✝² : Preadditive W F G : V ⥤ W inst✝¹ : Functor.Additive F inst✝ : Functor.Additive G α : F ⟶ G c : ComplexShape ι ⊢ ∀ ⦃X Y : HomotopyCategory V c⦄ (f : X ⟶ Y), (Functor.mapHomotopyCategory F c).map f ≫ (fun C => (HomotopyCategory.quotient W c).map (app (mapHomologicalComplex α c) C.as)) Y = (fun C => (HomotopyCategory.quotient W c).map (app (mapHomologicalComplex α c) C.as)) X ≫ (Functor.mapHomotopyCategory G c).map f [PROOFSTEP] rintro ⟨C⟩ ⟨D⟩ ⟨f : C ⟶ D⟩ [GOAL] case mk.mk.mk ι : Type u_1 V : Type u inst✝⁵ : Category.{v, u} V inst✝⁴ : Preadditive V c✝ : ComplexShape ι W : Type u_2 inst✝³ : Category.{?u.46796, u_2} W inst✝² : Preadditive W F G : V ⥤ W inst✝¹ : Functor.Additive F inst✝ : Functor.Additive G α : F ⟶ G c : ComplexShape ι C D : HomologicalComplex V c f✝ : { as := C } ⟶ { as := D } f : C ⟶ D ⊢ (Functor.mapHomotopyCategory F c).map (Quot.mk (Quotient.CompClosure (homotopic V c)) f) ≫ (fun C => (HomotopyCategory.quotient W c).map (app (mapHomologicalComplex α c) C.as)) { as := D } = (fun C => (HomotopyCategory.quotient W c).map (app (mapHomologicalComplex α c) C.as)) { as := C } ≫ (Functor.mapHomotopyCategory G c).map (Quot.mk (Quotient.CompClosure (homotopic V c)) f) [PROOFSTEP] simp only [HomotopyCategory.quot_mk_eq_quotient_map, Functor.mapHomotopyCategory_map, ← Functor.map_comp, NatTrans.naturality] [GOAL] ι : Type u_1 V : Type u inst✝⁴ : Category.{v, u} V inst✝³ : Preadditive V c✝ : ComplexShape ι W : Type u_2 inst✝² : Category.{u_3, u_2} W inst✝¹ : Preadditive W c : ComplexShape ι F : V ⥤ W inst✝ : Functor.Additive F ⊢ mapHomotopyCategory (𝟙 F) c = 𝟙 (Functor.mapHomotopyCategory F c) [PROOFSTEP] aesop_cat [GOAL] ι : Type u_1 V : Type u inst✝⁶ : Category.{v, u} V inst✝⁵ : Preadditive V c✝ : ComplexShape ι W : Type u_2 inst✝⁴ : Category.{u_3, u_2} W inst✝³ : Preadditive W c : ComplexShape ι F G H : V ⥤ W inst✝² : Functor.Additive F inst✝¹ : Functor.Additive G inst✝ : Functor.Additive H α : F ⟶ G β : G ⟶ H ⊢ mapHomotopyCategory (α ≫ β) c = mapHomotopyCategory α c ≫ mapHomotopyCategory β c [PROOFSTEP] aesop_cat
> module NonNegDouble.open_issues.Main > import Data.So > %default total > %access public export > data NonNegative : Double -> Type where > MkNonNegative : {x : Double} -> So (0.0 <= x) -> NonNegative x > NonNegDouble : Type > NonNegDouble = Subset Double NonNegative > plus : NonNegDouble -> NonNegDouble -> NonNegDouble > mult : NonNegDouble -> NonNegDouble -> NonNegDouble > fromNat : Nat -> NonNegDouble > implementation Num NonNegDouble where > (+) = plus > (*) = mult > fromInteger = fromNat . fromIntegerNat
import game.limits.L01defs import game.sup_inf.GLBprop_if_LUBprop namespace xena -- hide notation `|` x `|` := abs x -- hide /- Another basic result for working with sequences. -/ /- Lemma If $\lim_{n \to \infty} a_n = \alpha$ and $\lim_{n \to \infty} b_n = \beta$, then $\lim_{n \to \infty} (a_n + b_n) = \alpha + \beta$ -/ lemma lim_add (a : ℕ → ℝ) (b : ℕ → ℝ) (α β : ℝ) (ha : is_limit a α) (hb : is_limit b β) : is_limit ( λ n, (a n) + (b n) ) (α + β) := begin intros ε hε, set e := ε / 2 with hedef, have he : 0 < e, linarith, have Ha := ha e he, have Hb := hb e he, cases Ha with na hna, cases Hb with nb hnb, set m := max na nb with hm, have hm1 : m ≥ na, norm_num, left, linarith, have hm2 : m ≥ nb, norm_num, right, linarith, use m, intros n hn, have hn1 : n ≥ na, linarith, have hn2 : n ≥ nb, linarith, have H1 := hna n hn1, have H2 := hnb n hn2, have H := abs_add (a n - α) (b n - β), simp, have G : a n - α + (b n - β) = a n + b n - (α + β), linarith, rw G at H, have F : |a n - α| + |b n - β| < 2 * e, linarith, have E : |a n + b n - (α + β)| < 2 * e, linarith, have D : 2 * e = ε, linarith, rw D at E, exact E, done end end xena -- hide
module Mandelbrot where import Data.Complex import Graphics.Gloss import Graphics.Gloss.Data.Color import Graphics.Gloss.Raster.Field -- import qualified Graphics.Image.Interface as Hip -- import qualified Graphics.Image as Hip -- type Point = (Float, Float) pointOfIndex :: Int -> Int -> Point pointOfIndex w i = (x, y) where x = fromIntegral $ i `mod` w y = fromIntegral $ i `quot` w offset :: Point -> Point -> Point offset (a, b) (c, d) = (a+c, b+d) multiply :: Point -> Point -> Point multiply (a, b) (c, d) = (a*c, b*d) dasBrot :: RealFloat a => Complex a -> Complex a -> Complex a dasBrot c z_n = z_n^2 + c isBrot :: Int -> Point -> Bool isBrot n (r, i) = aux 0 0 -- z_n `elem` (init set) where c = r :+ i aux m z | magnitude successor > 16 = False | m > n = True | otherwise = aux (m+1) successor where successor = dasBrot c z z_n = last set set = take (n+1) $ iterate (dasBrot c) 0 qualBrot :: Int -> Point -> Int qualBrot n (r, i) = aux 0 0 -- z_n `elem` (init set) where c = r :+ i aux m z | willDiverge || m > n = m | otherwise = aux (m+1) next where next = dasBrot c z willDiverge = magnitude next > 16 renderSet :: Int -> Int -> Int -> Picture -> IO () renderSet w h n _ = display (InWindow "Mandelbrot set" (w, h) (10, 10) ) white (pictures dots) where (sc_w, sc_h) = (1.3, 1.3) (f_w, f_h) = (fromIntegral w, fromIntegral h) (t_w, t_h) = multiply (-1.5, 0.0) (f_w, f_h) (s_w, s_h) = (1/(f_w*sc_w), 1/(f_h*sc_h)) (r_w, r_h) = ((f_w)*s_w, f_h * s_h) pixels = [(x + t_w*s_w, y + t_h*s_h) | x <- [-r_w,(-r_w+s_w)..r_w] , y <- [-r_h,(-r_h+s_h)..r_h] ] dots = map aux pixels aux p = translate x y $ color (makeColor 0 0 0 (1-shade)) $ rectangleSolid 1 1 where s = fromIntegral $ qualBrot n p f_n = fromIntegral n (x, y) = offset (-t_w, -t_h) $ multiply (1/s_w, 1/s_h) p shade = if s == f_n then 0 else s/f_n
module LatticeSymmetries.IO where import Data.Aeson import Data.Aeson.Types (typeMismatch) import Data.Complex import Data.Scientific data SymmetrySpec = SymmetrySpec !(NonEmpty Int) !Int deriving stock (Read, Show, Eq) instance FromJSON SymmetrySpec where parseJSON = withObject "symmetry" $ \v -> SymmetrySpec <$> v .: "permutation" <*> v .: "sector" instance ToJSON SymmetrySpec where toJSON (SymmetrySpec permutation sector) = object ["permutation" .= permutation, "sector" .= sector] data BasisSpec = BasisSpec !Int !(Maybe Int) !(Maybe Int) ![SymmetrySpec] deriving stock (Read, Show, Eq) instance FromJSON BasisSpec where parseJSON = withObject "basis" $ \v -> BasisSpec <$> v .: "number_spins" <*> v .:? "hamming_weight" <*> v .:? "spin_inversion" <*> v .:! "symmetries" .!= [] instance ToJSON BasisSpec where toJSON (BasisSpec numberSpins hammingWeight spinInversion symmetries) = object [ "number_spins" .= numberSpins, "hamming_weight" .= maybe Null toJSON hammingWeight, "spin_inversion" .= maybe Null toJSON spinInversion, "symmetries" .= symmetries ] newtype WrappedBasisSpec = WrappedBasisSpec BasisSpec instance FromJSON WrappedBasisSpec where parseJSON = withObject "config" $ \v -> WrappedBasisSpec <$> v .: "basis" instance FromJSON (Complex Double) where parseJSON (Number x) = pure . fromReal . toRealFloat $ x where fromReal :: Num a => a -> Complex a fromReal x' = x' :+ 0 parseJSON v@(Array xs) = case (toList xs) of [re, im] -> (:+) <$> parseJSON re <*> parseJSON im _ -> typeMismatch "Complex" v parseJSON v = typeMismatch "Complex" v newtype DenseMatrixSpec = DenseMatrixSpec [[Complex Double]] deriving stock (Read, Show, Eq) deriving newtype (FromJSON) data InteractionSpec = InteractionSpec ![[Complex Double]] ![[Int]] deriving stock (Read, Show, Eq) instance FromJSON InteractionSpec where parseJSON = withObject "interaction" $ \v -> InteractionSpec <$> v .: "matrix" <*> v .: "sites" data OperatorSpec = OperatorSpec !Text !(NonEmpty InteractionSpec) deriving stock (Read, Show) instance FromJSON OperatorSpec where parseJSON = withObject "operator" $ \v -> OperatorSpec <$> v .: "name" <*> v .: "terms" data ConfigSpec = ConfigSpec !BasisSpec !OperatorSpec deriving stock (Read, Show) instance FromJSON ConfigSpec where parseJSON = withObject "config" $ \v -> ConfigSpec <$> v .: "basis" <*> v .: "hamiltonian"
{-# OPTIONS --without-K #-} open import Base open import Homotopy.Pushout open import Homotopy.VanKampen.Guide module Homotopy.VanKampen.Code {i} (d : pushout-diag i) (l : legend i (pushout-diag.C d)) where open pushout-diag d open legend l open import Homotopy.Truncation open import Homotopy.PathTruncation -- Code from A. import Homotopy.VanKampen.SplitCode d l as SC import Homotopy.VanKampen.Code.LemmaPackA d l as C -- Code from B. Code flipped. import Homotopy.VanKampen.SplitCode (pushout-diag-flip d) l as SCF import Homotopy.VanKampen.Code.LemmaPackA (pushout-diag-flip d) l as CF P : Set i P = pushout d module _ where -- Things that can be directly re-exported -- FIXME Ideally, this should be ‵SC'. -- Somehow that doesn′t work. open import Homotopy.VanKampen.SplitCode d l public using () renaming ( code to a-code ; code-a to a-code-a ; code-b to a-code-b ; code-rec to a-code-rec ; code-rec-nondep to a-code-rec-nondep ; code-is-set to a-code-is-set ; code-a-is-set to a-code-a-is-set ; code-b-is-set to a-code-b-is-set ) module _ {a₁ : A} where open import Homotopy.VanKampen.SplitCode d l a₁ public using () renaming ( code-a-refl-refl to a-code-a-refl-refl ; code-b-refl-refl to a-code-b-refl-refl ; code-ab-swap to a-code-ab-swap ; trans-a to trans-a-code-a ; trans-ba to trans-a-code-ba ; trans-ab to trans-a-code-ab ; a⇒b to aa⇒ab ; b⇒a to ab⇒aa ) a-a : ∀ {a₁} {a₂} → a₁ ≡₀ a₂ → a-code-a a₁ a₂ a-a = SC.a _ infixl 6 a-a syntax a-a co = ⟧a co a-ba : ∀ {a₁} {a₂} n → a-code-b a₁ (g $ loc n) → f (loc n) ≡₀ a₂ → a-code-a a₁ a₂ a-ba = SC.ba _ infixl 6 a-ba syntax a-ba n co p = co ab⟦ n ⟧a p a-ab : ∀ {a₁} {b₂} n → a-code-a a₁ (f $ loc n) → g (loc n) ≡₀ b₂ → a-code-b a₁ b₂ a-ab = SC.ab _ infixl 6 a-ab syntax a-ab n co p = co aa⟦ n ⟧b p module _ where -- Things that can be directly re-exported open import Homotopy.VanKampen.SplitCode (pushout-diag-flip d) l public using () renaming ( code-a to b-code-b ; code-b to b-code-a ; code-rec to b-code-rec ; code-rec-nondep to b-code-rec-nondep ; code-a-is-set to b-code-b-is-set ; code-b-is-set to b-code-a-is-set ) b-code : B → P → Set i b-code b = SCF.code b ◯ pushout-flip module _ {b₁ : B} where open import Homotopy.VanKampen.SplitCode (pushout-diag-flip d) l b₁ public using () renaming ( code-a-refl-refl to b-code-b-refl-refl ; code-b-refl-refl to b-code-a-refl-refl ; code-ab-swap to b-code-ba-swap ; trans-a to trans-b-code-b ; trans-ba to trans-b-code-ab ; trans-ab to trans-b-code-ba ; a⇒b to bb⇒ba ; b⇒a to ba⇒bb ) b-b : ∀ {b₁} {b₂} → b₁ ≡₀ b₂ → b-code-b b₁ b₂ b-b = SCF.a _ infixl 6 b-b syntax b-b co = ⟧b co b-ab : ∀ {b₁} {b₂} n → b-code-a b₁ (f $ loc n) → g (loc n) ≡₀ b₂ → b-code-b b₁ b₂ b-ab = SCF.ba _ infixl 6 b-ab syntax b-ab c co p = co ba⟦ c ⟧b p b-ba : ∀ {b₁} {a₂} n → b-code-b b₁ (g $ loc n) → f (loc n) ≡₀ a₂ → b-code-a b₁ a₂ b-ba = SCF.ab _ infixl 6 b-ba syntax b-ba c co p = co bb⟦ c ⟧a p b-code-is-set : ∀ b₁ p₂ → is-set (b-code b₁ p₂) b-code-is-set b₁ = SCF.code-is-set b₁ ◯ pushout-flip -- Tail flipping open import Homotopy.VanKampen.Code.LemmaPackA d l public using () renaming ( aa⇒ba to aa⇒ba ; ab⇒bb to ab⇒bb ; ap⇒bp to ap⇒bp ) open import Homotopy.VanKampen.Code.LemmaPackA (pushout-diag-flip d) l public using () renaming ( aa⇒ba to bb⇒ab ; ab⇒bb to ba⇒aa ) -- Tail drifting open import Homotopy.VanKampen.Code.LemmaPackB d l public using () renaming ( trans-q-code-a to trans-q-a-code-a ; trans-!q-code-a to trans-!q-a-code-a ; trans-q-code-ba to trans-q-a-code-ba ; trans-q-code-ab to trans-q-a-code-ab ) open import Homotopy.VanKampen.Code.LemmaPackB (pushout-diag-flip d) l public using () renaming ( trans-q-code-a to trans-q-b-code-b ; trans-!q-code-a to trans-!q-b-code-b ; trans-q-code-ba to trans-q-b-code-ab ; trans-q-code-ab to trans-q-b-code-ba ) bp⇒ap : ∀ n {p} → b-code (g $ loc n) p → a-code (f $ loc n) p bp⇒ap n {p} = transport (λ x → b-code (g $ loc n) p → a-code (f $ loc n) x) (pushout-flip-flip p) (CF.ap⇒bp n {pushout-flip p}) private Laba : name → P → Set i Laba = λ n p → ∀ (co : a-code (f $ loc n) p) → bp⇒ap n {p} (ap⇒bp n {p} co) ≡ co private aba-glue-code : ∀ c {p} → Laba c p abstract aba-glue-code n {p} = pushout-rec (Laba n) (λ _ → C.aba-glue-code-a n) (λ _ → C.aba-glue-code-b n) (λ _ → funext λ _ → prop-has-all-paths (a-code-b-is-set (f $ loc n) _ _ _) _ _) p private Lbab : name → P → Set i Lbab = λ n p → ∀ (co : b-code (g $ loc n) p) → ap⇒bp n {p} (bp⇒ap n {p} co) ≡ co private bab-glue-code : ∀ n {p} → Lbab n p abstract bab-glue-code n {p} = pushout-rec (Lbab n) (λ _ → CF.aba-glue-code-b n) (λ _ → CF.aba-glue-code-a n) (λ _ → funext λ _ → prop-has-all-paths (b-code-b-is-set (g $ loc n) _ _ _) _ _) p private glue-code-loc : ∀ n p → a-code (f $ loc n) p ≃ b-code (g $ loc n) p glue-code-loc n p = ap⇒bp n {p} , iso-is-eq (ap⇒bp n {p}) (bp⇒ap n {p}) (bab-glue-code n {p}) (aba-glue-code n {p}) private TapbpTa : ∀ n₁ n₂ (r : loc n₁ ≡ loc n₂) {a} → a-code-a (f $ loc n₂) a → Set i TapbpTa n₁ n₂ r {a} co = transport (λ x → b-code-a x a) (ap g r) (aa⇒ba n₁ {a} $ transport (λ x → a-code-a x a) (! $ ap f r) co) ≡ aa⇒ba n₂ {a} co TapbpTb : ∀ n₁ n₂ (r : loc n₁ ≡ loc n₂) {b} → a-code-b (f $ loc n₂) b → Set i TapbpTb n₁ n₂ r {b} co = transport (λ x → b-code-b x b) (ap g r) (ab⇒bb n₁ {b} $ transport (λ x → a-code-b x b) (! $ ap f r) co) ≡ ab⇒bb n₂ {b} co TapbpTp : ∀ n₁ n₂ (r : loc n₁ ≡ loc n₂) {p} → a-code (f $ loc n₂) p → Set i TapbpTp n₁ n₂ r {p} co = transport (λ x → b-code x p) (ap g r) (ap⇒bp n₁ {p} $ transport (λ x → a-code x p) (! $ ap f r) co) ≡ ap⇒bp n₂ {p} co private ap⇒bp-shift-split : ∀ n₁ n₂ r → (∀ {a₂} co → TapbpTa n₁ n₂ r {a₂} co) × (∀ {b₂} co → TapbpTb n₁ n₂ r {b₂} co) abstract ap⇒bp-shift-split n₁ n₂ r = a-code-rec (f $ loc n₂) (TapbpTa n₁ n₂ r) ⦃ λ _ → ≡-is-set $ b-code-a-is-set _ _ ⦄ (TapbpTb n₁ n₂ r) ⦃ λ _ → ≡-is-set $ b-code-b-is-set _ _ ⦄ (λ {a} p → transport (λ x → b-code-a x a) (ap g r) (aa⇒ba n₁ {a} $ transport (λ x → a-code-a x a) (! $ ap f r) $ ⟧a p) ≡⟨ ap (transport (λ x → b-code-a x a) (ap g r) ◯ aa⇒ba n₁ {a}) $ trans-!q-a-code-a (ap f r) p ⟩ transport (λ x → b-code-a x a) (ap g r) (⟧b refl₀ bb⟦ n₁ ⟧a proj (ap f r) ∘₀ p) ≡⟨ trans-q-b-code-ba (ap g r) _ _ _ ⟩ transport (λ x → b-code-b x (g $ loc n₁)) (ap g r) (⟧b refl₀) bb⟦ n₁ ⟧a proj (ap f r) ∘₀ p ≡⟨ ap (λ x → x bb⟦ n₁ ⟧a proj (ap f r) ∘₀ p) $ trans-q-b-code-b (ap g r) _ ⟩ ⟧b proj (! (ap g r)) ∘₀ refl₀ bb⟦ n₁ ⟧a proj (ap f r) ∘₀ p ≡⟨ ap (λ x → ⟧b x bb⟦ n₁ ⟧a proj (ap f r) ∘₀ p) $ refl₀-right-unit _ ⟩ ⟧b proj (! (ap g r)) bb⟦ n₁ ⟧a proj (ap f r) ∘₀ p ≡⟨ ! $ SCF.code-a-shift (g $ loc n₂) n₁ (proj (! (ap g r))) n₂ (proj r) p ⟩ ⟧b proj (! (ap g r) ∘ ap g r) bb⟦ n₂ ⟧a p ≡⟨ ap (λ x → ⟧b proj x bb⟦ n₂ ⟧a p) $ opposite-left-inverse $ ap g r ⟩∎ aa⇒ba n₂ {a} (⟧a p) ∎) (λ {a} n {co} pco p → transport (λ x → b-code-a x a) (ap g r) (aa⇒ba n₁ {a} $ transport (λ x → a-code-a x a) (! $ ap f r) $ co ab⟦ n ⟧a p) ≡⟨ ap (transport (λ x → b-code-a x a) (ap g r) ◯ aa⇒ba n₁ {a}) $ trans-q-a-code-ba (! $ ap f r) n co p ⟩ transport (λ x → b-code-a x a) (ap g r) (ab⇒bb n₁ {g $ loc n} (transport (λ x → a-code-b x (g $ loc n)) (! $ ap f r) co) bb⟦ n ⟧a p) ≡⟨ trans-q-b-code-ba (ap g r) _ _ _ ⟩ transport (λ x → b-code-b x (g $ loc n)) (ap g r) (ab⇒bb n₁ {g $ loc n} (transport (λ x → a-code-b x (g $ loc n)) (! $ ap f r) co)) bb⟦ n ⟧a p ≡⟨ ap (λ x → x bb⟦ n ⟧a p) pco ⟩∎ ab⇒bb n₂ {g $ loc n} co bb⟦ n ⟧a p ∎) (λ {b} n {co} pco p → transport (λ x → b-code-b x b) (ap g r) (ab⇒bb n₁ {b} $ transport (λ x → a-code-b x b) (! $ ap f r) $ co aa⟦ n ⟧b p) ≡⟨ ap (transport (λ x → b-code-b x b) (ap g r) ◯ ab⇒bb n₁ {b}) $ trans-q-a-code-ab (! $ ap f r) n co p ⟩ transport (λ x → b-code-b x b) (ap g r) (aa⇒ba n₁ {f $ loc n} (transport (λ x → a-code-a x (f $ loc n)) (! $ ap f r) co) ba⟦ n ⟧b p) ≡⟨ trans-q-b-code-ab (ap g r) _ _ _ ⟩ transport (λ x → b-code-a x (f $ loc n)) (ap g r) (aa⇒ba n₁ {f $ loc n} (transport (λ x → a-code-a x (f $ loc n)) (! $ ap f r) co)) ba⟦ n ⟧b p ≡⟨ ap (λ x → x ba⟦ n ⟧b p) pco ⟩∎ aa⇒ba n₂ {f $ loc n} co ba⟦ n ⟧b p ∎) (λ _ _ → prop-has-all-paths (b-code-a-is-set _ _ _ _) _ _) (λ _ _ → prop-has-all-paths (b-code-b-is-set _ _ _ _) _ _) (λ _ _ _ _ → prop-has-all-paths (b-code-a-is-set _ _ _ _) _ _) private ap⇒bp-shift : ∀ n₁ n₂ r {p} co → TapbpTp n₁ n₂ r {p} co abstract ap⇒bp-shift n₁ n₂ r {p} co = pushout-rec (λ p → ∀ co → TapbpTp n₁ n₂ r {p} co) (λ a → π₁ (ap⇒bp-shift-split n₁ n₂ r) {a}) (λ b → π₂ (ap⇒bp-shift-split n₁ n₂ r) {b}) (λ c → funext λ _ → prop-has-all-paths (b-code-is-set (g $ loc n₂) (right $ g c) _ _) _ _) p co glue-code-eq-route : ∀ p n₁ n₂ (r : loc n₁ ≡ loc n₂) → transport (λ c → a-code (f c) p ≃ b-code (g c) p) r (glue-code-loc n₁ p) ≡ glue-code-loc n₂ p abstract glue-code-eq-route p n₁ n₂ r = equiv-eq $ funext λ co → π₁ (transport (λ c → a-code (f c) p ≃ b-code (g c) p) r (glue-code-loc n₁ p)) co ≡⟨ ap (λ x → x co) $ app-trans (λ c → a-code (f c) p ≃ b-code (g c) p) (λ c → a-code (f c) p → b-code (g c) p) (λ _ → π₁) r (glue-code-loc n₁ p) ⟩ transport (λ c → a-code (f c) p → b-code (g c) p) r (ap⇒bp n₁ {p}) co ≡⟨ trans-→ (λ c → a-code (f c) p) (λ c → b-code (g c) p) r (ap⇒bp n₁ {p}) co ⟩ transport (λ c → b-code (g c) p) r (ap⇒bp n₁ {p} $ transport (λ c → a-code (f c) p) (! r) co) ≡⟨ ap (transport (λ c → b-code (g c) p) r ◯ ap⇒bp n₁ {p}) $ ! $ trans-ap (λ x → a-code x p) f (! r) co ⟩ transport (λ c → b-code (g c) p) r (ap⇒bp n₁ {p} $ transport (λ x → a-code x p) (ap f (! r)) co) ≡⟨ ap (λ x → transport (λ c → b-code (g c) p) r $ ap⇒bp n₁ {p} $ transport (λ x → a-code x p) x co) $ ap-opposite f r ⟩ transport (λ c → b-code (g c) p) r (ap⇒bp n₁ {p} $ transport (λ x → a-code x p) (! $ ap f r) co) ≡⟨ ! $ trans-ap (λ x → b-code x p) g r _ ⟩ transport (λ x → b-code x p) (ap g r) (ap⇒bp n₁ {p} $ transport (λ x → a-code x p) (! $ ap f r) co) ≡⟨ ap⇒bp-shift n₁ n₂ r {p} co ⟩∎ ap⇒bp n₂ {p} co ∎ glue-code-eq : ∀ c p → a-code (f c) p ≃ b-code (g c) p glue-code-eq c p = visit-fiber-rec l (λ c → a-code (f c) p ≃ b-code (g c) p) ⦃ λ c → ≃-is-set (a-code-is-set (f c) p) (b-code-is-set (g c) p) ⦄ (λ n → glue-code-loc n p) (glue-code-eq-route p) c code : P → P → Set i code = pushout-rec-nondep (P → Set i) a-code b-code (λ c → funext λ p → eq-to-path $ glue-code-eq c p) open import HLevelBis abstract code-is-set : ∀ p₁ p₂ → is-set (code p₁ p₂) code-is-set = pushout-rec (λ p₁ → ∀ p₂ → is-set $ code p₁ p₂) a-code-is-set b-code-is-set (λ _ → prop-has-all-paths (Π-is-prop λ _ → is-set-is-prop) _ _) -- Useful lemma module _ {a₁ : A} where open import Homotopy.VanKampen.SplitCode d l a₁ public using () renaming ( trans-code-glue-loc to trans-a-code-glue-loc ; trans-code-!glue-loc to trans-a-code-!glue-loc ) abstract trans-b-code-glue-loc : ∀ {b₁} n₂ co → transport (b-code b₁) (glue $ loc n₂) co ≡ ba⇒bb n₂ co trans-b-code-glue-loc {b₁} n₂ co = transport (b-code b₁) (glue $ loc n₂) co ≡⟨ ! $ trans-ap (SCF.code b₁) pushout-flip (glue $ loc n₂) co ⟩ transport (SCF.code b₁) (ap pushout-flip (glue $ loc n₂)) co ≡⟨ ap (λ x → transport (SCF.code b₁) x co) $ pushout-β-glue-nondep _ right left (! ◯ glue) (loc n₂) ⟩ transport (SCF.code b₁) (! (glue $ loc n₂)) co ≡⟨ SCF.trans-code-!glue-loc b₁ n₂ co ⟩∎ ba⇒bb n₂ co ∎ abstract trans-b-code-!glue-loc : ∀ {b₁} n₂ co → transport (b-code b₁) (! (glue $ loc n₂)) co ≡ bb⇒ba n₂ co trans-b-code-!glue-loc {b₁} n₂ co = transport (b-code b₁) (! (glue $ loc n₂)) co ≡⟨ ! $ trans-ap (SCF.code b₁) pushout-flip (! (glue $ loc n₂)) co ⟩ transport (SCF.code b₁) (ap pushout-flip (! (glue $ loc n₂))) co ≡⟨ ap (λ x → transport (SCF.code b₁) x co) $ pushout-β-!glue-nondep _ right left (! ◯ glue) (loc n₂) ⟩ transport (SCF.code b₁) (! (! (glue $ loc n₂))) co ≡⟨ ap (λ x → transport (SCF.code b₁) x co) $ opposite-opposite $ glue $ loc n₂ ⟩ transport (SCF.code b₁) (glue $ loc n₂) co ≡⟨ SCF.trans-code-glue-loc b₁ n₂ co ⟩∎ bb⇒ba n₂ co ∎ abstract trans-glue-code-loc : ∀ n {p} (co : a-code (f $ loc n) p) → transport (λ x → code x p) (glue $ loc n) co ≡ ap⇒bp n {p} co trans-glue-code-loc n {p} co = transport (λ x → code x p) (glue $ loc n) co ≡⟨ ! $ trans-ap (λ f → f p) code (glue $ loc n) co ⟩ transport (λ f → f p) (ap code (glue $ loc n)) co ≡⟨ ap (λ x → transport (λ f → f p) x co) $ pushout-β-glue-nondep (P → Set i) a-code b-code (λ c → funext λ p → eq-to-path $ glue-code-eq c p) $ loc n ⟩ transport (λ f → f p) (funext λ p → eq-to-path $ glue-code-eq (loc n) p) co ≡⟨ ! $ trans-ap (λ X → X) (λ f → f p) (funext λ p → eq-to-path $ glue-code-eq (loc n) p) co ⟩ transport (λ X → X) (happly (funext λ p → eq-to-path $ glue-code-eq (loc n) p) p) co ≡⟨ ap (λ x → transport (λ X → X) (x p) co) $ happly-funext (λ p → eq-to-path $ glue-code-eq (loc n) p) ⟩ transport (λ X → X) (eq-to-path $ glue-code-eq (loc n) p) co ≡⟨ trans-id-eq-to-path (glue-code-eq (loc n) p) co ⟩ π₁ (glue-code-eq (loc n) p) co ≡⟨ ap (λ x → π₁ x co) $ visit-fiber-β-loc l (λ c → a-code (f c) p ≃ b-code (g c) p) ⦃ λ c → ≃-is-set (a-code-is-set (f c) p) (b-code-is-set (g c) p) ⦄ (λ n → glue-code-loc n p) (glue-code-eq-route p) n ⟩∎ ap⇒bp n {p} co ∎ abstract trans-!glue-code-loc : ∀ n {p} (co : b-code (g $ loc n) p) → transport (λ x → code x p) (! $ glue $ loc n) co ≡ bp⇒ap n {p} co trans-!glue-code-loc n {p} co = move!-transp-right (λ x → code x p) (glue $ loc n) co (bp⇒ap n {p} co) $ ! $ transport (λ x → code x p) (glue $ loc n) (bp⇒ap n {p} co) ≡⟨ trans-glue-code-loc n {p} (bp⇒ap n {p} co) ⟩ ap⇒bp n {p} (bp⇒ap n {p} co) ≡⟨ bab-glue-code n {p} co ⟩∎ co ∎
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash ! This file was ported from Lean 3 source module algebra.lie.skew_adjoint ! leanprover-community/mathlib commit 075b3f7d19b9da85a0b54b3e33055a74fc388dec ! Please do not edit these lines, except to modify the commit id ! if you have ported upstream changes. -/ import Mathbin.Algebra.Lie.Matrix import Mathbin.LinearAlgebra.Matrix.BilinearForm /-! # Lie algebras of skew-adjoint endomorphisms of a bilinear form When a module carries a bilinear form, the Lie algebra of endomorphisms of the module contains a distinguished Lie subalgebra: the skew-adjoint endomorphisms. Such subalgebras are important because they provide a simple, explicit construction of the so-called classical Lie algebras. This file defines the Lie subalgebra of skew-adjoint endomorphims cut out by a bilinear form on a module and proves some basic related results. It also provides the corresponding definitions and results for the Lie algebra of square matrices. ## Main definitions * `skew_adjoint_lie_subalgebra` * `skew_adjoint_lie_subalgebra_equiv` * `skew_adjoint_matrices_lie_subalgebra` * `skew_adjoint_matrices_lie_subalgebra_equiv` ## Tags lie algebra, skew-adjoint, bilinear form -/ universe u v w w₁ section SkewAdjointEndomorphisms open BilinForm variable {R : Type u} {M : Type v} [CommRing R] [AddCommGroup M] [Module R M] variable (B : BilinForm R M) theorem BilinForm.is_skew_adjoint_bracket (f g : Module.End R M) (hf : f ∈ B.skewAdjointSubmodule) (hg : g ∈ B.skewAdjointSubmodule) : ⁅f, g⁆ ∈ B.skewAdjointSubmodule := by rw [mem_skew_adjoint_submodule] at * have hfg : is_adjoint_pair B B (f * g) (g * f) := by rw [← neg_mul_neg g f] exact hf.mul hg have hgf : is_adjoint_pair B B (g * f) (f * g) := by rw [← neg_mul_neg f g] exact hg.mul hf change BilinForm.IsAdjointPair B B (f * g - g * f) (-(f * g - g * f)) rw [neg_sub] exact hfg.sub hgf #align bilin_form.is_skew_adjoint_bracket BilinForm.is_skew_adjoint_bracket /-- Given an `R`-module `M`, equipped with a bilinear form, the skew-adjoint endomorphisms form a Lie subalgebra of the Lie algebra of endomorphisms. -/ def skewAdjointLieSubalgebra : LieSubalgebra R (Module.End R M) := { B.skewAdjointSubmodule with lie_mem' := B.is_skew_adjoint_bracket } #align skew_adjoint_lie_subalgebra skewAdjointLieSubalgebra variable {N : Type w} [AddCommGroup N] [Module R N] (e : N ≃ₗ[R] M) /-- An equivalence of modules with bilinear forms gives equivalence of Lie algebras of skew-adjoint endomorphisms. -/ def skewAdjointLieSubalgebraEquiv : skewAdjointLieSubalgebra (B.comp (↑e : N →ₗ[R] M) ↑e) ≃ₗ⁅R⁆ skewAdjointLieSubalgebra B := by apply LieEquiv.ofSubalgebras _ _ e.lie_conj ext f simp only [LieSubalgebra.mem_coe, Submodule.mem_map_equiv, LieSubalgebra.mem_map_submodule, coe_coe] exact (BilinForm.isPairSelfAdjoint_equiv (-B) B e f).symm #align skew_adjoint_lie_subalgebra_equiv skewAdjointLieSubalgebraEquiv @[simp] theorem skewAdjointLieSubalgebraEquiv_apply (f : skewAdjointLieSubalgebra (B.comp ↑e ↑e)) : ↑(skewAdjointLieSubalgebraEquiv B e f) = e.lieConj f := by simp [skewAdjointLieSubalgebraEquiv] #align skew_adjoint_lie_subalgebra_equiv_apply skewAdjointLieSubalgebraEquiv_apply @[simp] theorem skewAdjointLieSubalgebraEquiv_symm_apply (f : skewAdjointLieSubalgebra B) : ↑((skewAdjointLieSubalgebraEquiv B e).symm f) = e.symm.lieConj f := by simp [skewAdjointLieSubalgebraEquiv] #align skew_adjoint_lie_subalgebra_equiv_symm_apply skewAdjointLieSubalgebraEquiv_symm_apply end SkewAdjointEndomorphisms section SkewAdjointMatrices open Matrix variable {R : Type u} {n : Type w} [CommRing R] [DecidableEq n] [Fintype n] variable (J : Matrix n n R) theorem Matrix.lie_transpose (A B : Matrix n n R) : ⁅A, B⁆ᵀ = ⁅Bᵀ, Aᵀ⁆ := show (A * B - B * A)ᵀ = Bᵀ * Aᵀ - Aᵀ * Bᵀ by simp #align matrix.lie_transpose Matrix.lie_transpose theorem Matrix.is_skew_adjoint_bracket (A B : Matrix n n R) (hA : A ∈ skewAdjointMatricesSubmodule J) (hB : B ∈ skewAdjointMatricesSubmodule J) : ⁅A, B⁆ ∈ skewAdjointMatricesSubmodule J := by simp only [mem_skewAdjointMatricesSubmodule] at * change ⁅A, B⁆ᵀ ⬝ J = J ⬝ (-⁅A, B⁆); change Aᵀ ⬝ J = J ⬝ (-A) at hA; change Bᵀ ⬝ J = J ⬝ (-B) at hB simp only [← Matrix.mul_eq_mul] at * rw [Matrix.lie_transpose, LieRing.of_associative_ring_bracket, LieRing.of_associative_ring_bracket, sub_mul, mul_assoc, mul_assoc, hA, hB, ← mul_assoc, ← mul_assoc, hA, hB] noncomm_ring #align matrix.is_skew_adjoint_bracket Matrix.is_skew_adjoint_bracket /-- The Lie subalgebra of skew-adjoint square matrices corresponding to a square matrix `J`. -/ def skewAdjointMatricesLieSubalgebra : LieSubalgebra R (Matrix n n R) := { skewAdjointMatricesSubmodule J with lie_mem' := J.is_skew_adjoint_bracket } #align skew_adjoint_matrices_lie_subalgebra skewAdjointMatricesLieSubalgebra @[simp] theorem mem_skewAdjointMatricesLieSubalgebra (A : Matrix n n R) : A ∈ skewAdjointMatricesLieSubalgebra J ↔ A ∈ skewAdjointMatricesSubmodule J := Iff.rfl #align mem_skew_adjoint_matrices_lie_subalgebra mem_skewAdjointMatricesLieSubalgebra /-- An invertible matrix `P` gives a Lie algebra equivalence between those endomorphisms that are skew-adjoint with respect to a square matrix `J` and those with respect to `PᵀJP`. -/ def skewAdjointMatricesLieSubalgebraEquiv (P : Matrix n n R) (h : Invertible P) : skewAdjointMatricesLieSubalgebra J ≃ₗ⁅R⁆ skewAdjointMatricesLieSubalgebra (Pᵀ ⬝ J ⬝ P) := LieEquiv.ofSubalgebras _ _ (P.lieConj h).symm (by ext A suffices P.lie_conj h A ∈ skewAdjointMatricesSubmodule J ↔ A ∈ skewAdjointMatricesSubmodule (Pᵀ ⬝ J ⬝ P) by simp only [LieSubalgebra.mem_coe, Submodule.mem_map_equiv, LieSubalgebra.mem_map_submodule, coe_coe] exact this simp [Matrix.IsSkewAdjoint, J.is_adjoint_pair_equiv' _ _ P (isUnit_of_invertible P)]) #align skew_adjoint_matrices_lie_subalgebra_equiv skewAdjointMatricesLieSubalgebraEquiv theorem skewAdjointMatricesLieSubalgebraEquiv_apply (P : Matrix n n R) (h : Invertible P) (A : skewAdjointMatricesLieSubalgebra J) : ↑(skewAdjointMatricesLieSubalgebraEquiv J P h A) = P⁻¹ ⬝ ↑A ⬝ P := by simp [skewAdjointMatricesLieSubalgebraEquiv] #align skew_adjoint_matrices_lie_subalgebra_equiv_apply skewAdjointMatricesLieSubalgebraEquiv_apply /-- An equivalence of matrix algebras commuting with the transpose endomorphisms restricts to an equivalence of Lie algebras of skew-adjoint matrices. -/ def skewAdjointMatricesLieSubalgebraEquivTranspose {m : Type w} [DecidableEq m] [Fintype m] (e : Matrix n n R ≃ₐ[R] Matrix m m R) (h : ∀ A, (e A)ᵀ = e Aᵀ) : skewAdjointMatricesLieSubalgebra J ≃ₗ⁅R⁆ skewAdjointMatricesLieSubalgebra (e J) := LieEquiv.ofSubalgebras _ _ e.toLieEquiv (by ext A suffices J.is_skew_adjoint (e.symm A) ↔ (e J).IsSkewAdjoint A by simpa [this] simp [Matrix.IsSkewAdjoint, Matrix.IsAdjointPair, ← Matrix.mul_eq_mul, ← h, ← Function.Injective.eq_iff e.injective]) #align skew_adjoint_matrices_lie_subalgebra_equiv_transpose skewAdjointMatricesLieSubalgebraEquivTranspose @[simp] theorem skewAdjointMatricesLieSubalgebraEquivTranspose_apply {m : Type w} [DecidableEq m] [Fintype m] (e : Matrix n n R ≃ₐ[R] Matrix m m R) (h : ∀ A, (e A)ᵀ = e Aᵀ) (A : skewAdjointMatricesLieSubalgebra J) : (skewAdjointMatricesLieSubalgebraEquivTranspose J e h A : Matrix m m R) = e A := rfl #align skew_adjoint_matrices_lie_subalgebra_equiv_transpose_apply skewAdjointMatricesLieSubalgebraEquivTranspose_apply theorem mem_skewAdjointMatricesLieSubalgebra_unit_smul (u : Rˣ) (J A : Matrix n n R) : A ∈ skewAdjointMatricesLieSubalgebra (u • J) ↔ A ∈ skewAdjointMatricesLieSubalgebra J := by change A ∈ skewAdjointMatricesSubmodule (u • J) ↔ A ∈ skewAdjointMatricesSubmodule J simp only [mem_skewAdjointMatricesSubmodule, Matrix.IsSkewAdjoint, Matrix.IsAdjointPair] constructor <;> intro h · simpa using congr_arg (fun B => u⁻¹ • B) h · simp [h] #align mem_skew_adjoint_matrices_lie_subalgebra_unit_smul mem_skewAdjointMatricesLieSubalgebra_unit_smul end SkewAdjointMatrices
(* in Coq 8.8.0 with "-no-is" *) (* 除去規則が自動的に定義されるのを止める。 *) Unset Elimination Schemes. (* タクティックを使う。 *) Declare ML Module "ltac_plugin". (* 証明の仕方を設定する。 *) Export Set Default Proof Mode "Classic". (* 関数型の記法 *) Notation "x -> y" := (forall (_ : x), y) (at level 99, right associativity, y at level 200) . (* 等式を表す型 Haskellでの(:~:)に対応する。 *) Inductive eq (A : Type) (a : A) : A -> Type := | eq_refl : eq A a a . (* eqの除去規則 *) Definition eq_elim (A : Type) (x : A) (P : forall y : A, eq A x y -> Type) (c : P x (eq_refl A x)) (y : A) (p : eq A x y) : P y p := match p as p' in eq _ _ y' return P y' p' with | eq_refl _ _ => c end . Definition eq_elim_nodep (A : Type) (x : A) (P : A -> Type) (c : P x) (y : A) (p : eq A x y) : P y := eq_elim A x (fun y' _ => P y') c y p . Definition eq_sym (A : Type) (x y : A) (p : eq A x y) : eq A y x := eq_elim_nodep A x (fun y' => eq A y' x) (eq_refl A x) y p . Definition eq_trans (A : Type) (x y z : A) (p : eq A y z) (q : eq A x y) : eq A x z . Proof. refine ( eq_elim_nodep A y (fun z' => eq A x z') _ z p ). refine ( eq_elim_nodep A x (fun y' => eq A x y') _ y q ). refine ( eq_refl A x ). Defined. (* Heteroな等式を表す型 Haskellでの(:~~:)に対応する *) Inductive JMeq (A : Type) (a : A) : forall B : Type, B -> Type := | JMeq_refl : JMeq A a A a . (* JMeqの除去規則 *) Definition JMeq_elim (A : Type) (a : A) (P : forall (B : Type) (b : B), JMeq A a B b -> Type) (c : P A a (JMeq_refl A a)) (B : Type) (b : B) (p : JMeq A a B b) : P B b p := match p as p' in JMeq _ _ B' b' return P B' b' p' with | JMeq_refl _ _ => c end . Definition JMeq_elim_nodep (A : Type) (a : A) (P : forall (B : Type), B -> Type) (c : P A a) (B : Type) (b : B) (p : JMeq A a B b) : P B b := JMeq_elim A a (fun B' b' _ => P B' b') c B b p . Definition JMeq_sym (A B : Type) (a : A) (b : B) (p : JMeq A a B b) : JMeq B b A a := JMeq_elim_nodep A a (fun B' b' => JMeq B' b' A a) (JMeq_refl A a) B b p . Definition JMeq_trans (A B C : Type) (a : A) (b : B) (c : C) (p : JMeq B b C c) (q : JMeq A a B b) : JMeq A a C c . Proof. refine ( JMeq_elim_nodep B b (fun C' c' => JMeq A a C' c') _ C c p ). refine ( JMeq_elim_nodep A a (fun B' b' => JMeq A a B' b') _ B b q ). refine ( JMeq_refl A a ). Defined. (* JMeqからeqを導く 証明不可能で公理として追加するしかない。 Coq.Logic.JMeq.JMeq_eqとしてライブラリに存在。 *) Definition JMeq_eq (A : Type) (x y : A) (p : JMeq A x A y) : eq A x y . Proof. Abort. (* JMeqのeqのような依存無しの除去規則 *) Definition JMeq_elim_eqlike_nodep (A : Type) (x : A) (P : A -> Type) (c : P x) (y : A) (p : JMeq A x A y) : P y . Proof. Abort. (* JMeqのeqのような除去規則 *) Definition JMeq_elim_eqlike (A : Type) (x : A) (P : forall y : A, JMeq A x A y -> Type) (c : P x (JMeq_refl A x)) (y : A) (p : JMeq A x A y) : P y p . Proof. Abort. (* axiom UIP (UIP axiom, the axiom of uniqueness of identity proofs) 全てのeqは等しいという公理。 https://ncatlab.org/nlab/show/axiom+UIP *) Definition UIP (A : Type) (x y : A) (p q : eq A x y) : eq (eq A x y) p q. Proof. Abort. (* axiom K https://ncatlab.org/nlab/show/axiom+K+%28type+theory%29 *) Definition K (A : Type) (x : A) (P : eq A x x -> Type) (c : P (eq_refl A x)) (p : eq A x x) : P p . Proof. Abort. (* UIPの等しい対象がeq_reflになったバージョン Kから簡単に導ける。 http://adam.chlipala.net/cpdt/html/Equality.html (Heterogeneous Equality) *) Definition UIP_refl (A : Type) (x : A) (p : eq A x x) : eq (eq A x x) (eq_refl A x) p . Proof. Abort. (* UIPをJMeqを使って定義したバージョン *) Definition UIP' (A : Type) (x y : A) (p q : eq A x y) : JMeq (eq A x y) p (eq A x y) q. Proof. refine ( eq_elim A x (fun y' p' => JMeq (eq A x y') p' (eq A x y) q) _ y p ). refine ( eq_elim A x (fun y' q' => JMeq (eq A x x) (eq_refl A x) (eq A x y') q') _ y q ). refine ( JMeq_refl (eq A x x) (eq_refl A x) ). Defined. (* UIP_reflをJMeqで定義したバージョン *) Definition UIP'_refl (A : Type) (x : A) (p : eq A x x) : JMeq (eq A x x) (eq_refl A x) (eq A x x) p . Proof. refine ( eq_elim A x (fun x' p' => JMeq (eq A x x) (eq_refl A x) (eq A x x') p') _ x p ). refine ( JMeq_refl (eq A x x) (eq_refl A x) ). Defined. Definition JMeq_UIP (A B : Type) (a : A) (b : B) (p q : JMeq A a B b) : eq (JMeq A a B b) p q . Proof. Abort. Definition JMeq_K (A : Type) (x : A) (P : JMeq A x A x -> Type) (c : P (JMeq_refl A x)) (p : JMeq A x A x) : P p . Proof. Abort. Definition JMeq_UIP_refl (A : Type) (x : A) (p : JMeq A x A x) : eq (JMeq A x A x) (JMeq_refl A x) p . Proof. Abort. Definition JMeq_UIP' (A B : Type) (a : A) (b : B) (p q : JMeq A a B b) : JMeq (JMeq A a B b) p (JMeq A a B b) q . Proof. refine ( JMeq_elim A a (fun B' b' p' => JMeq (JMeq A a B' b') p' (JMeq A a B b) q) _ B b p ). refine ( JMeq_elim A a (fun B' b' q' => JMeq (JMeq A a A a) (JMeq_refl A a) (JMeq A a B' b') q') _ B b q ). refine ( JMeq_refl (JMeq A a A a) (JMeq_refl A a) ). Defined. Definition JMeq_UIP'_refl (A : Type) (x : A) (p : JMeq A x A x) : JMeq (JMeq A x A x) (JMeq_refl A x) (JMeq A x A x) p . Proof. refine ( JMeq_elim A x (fun A' x' p' => JMeq (JMeq A x A x) (JMeq_refl A x) (JMeq A x A' x') p') _ A x p ). refine ( JMeq_refl (JMeq A x A x) (JMeq_refl A x) ). Defined. (* eqからJMeqを導く *) Definition eq_JMeq (A : Type) (x y : A) (p : eq A x y) : JMeq A x A y := eq_elim_nodep A x (fun y' => JMeq A x A y') (JMeq_refl A x) y p . (* JMeq_eqを仮定して他の公理を導く *) Section Declare_JMeq_eq. Variable JMeq_eq : forall A x y, JMeq A x A y -> eq A x y. Definition JMeq_elim_eqlike_nodep_from_ (A : Type) (x : A) (P : A -> Type) (c : P x) (y : A) (p : JMeq A x A y) : P y . Proof. refine ( eq_elim_nodep A x P c y (JMeq_eq A x y p) ). Defined. (* 証明不可能? *) Definition JMeq_elim_eqlike (A : Type) (x : A) (P : forall y : A, JMeq A x A y -> Type) (c : P x (JMeq_refl A x)) (y : A) (p : JMeq A x A y) : P y p . Proof. Abort. Definition UIP (A : Type) (x y : A) (p q : eq A x y) : eq (eq A x y) p q. Proof. refine (JMeq_eq (eq A x y) p q _). refine (UIP' A x y p q). Defined. Definition K (A : Type) (x : A) (P : eq A x x -> Type) (c : P (eq_refl A x)) (p : eq A x x) : P p . Proof. refine ( eq_elim_nodep (eq A x x) (eq_refl A x) (fun p' => P p') c p (UIP A x x (eq_refl A x) p) ). Defined. Definition UIP_refl (A : Type) (x : A) (p : eq A x x) : eq (eq A x x) (eq_refl A x) p . Proof. refine (JMeq_eq (eq A x x) (eq_refl A x) p _). refine (UIP'_refl A x p). Defined. Definition JMeq_UIP (A B : Type) (a : A) (b : B) (p q : JMeq A a B b) : eq (JMeq A a B b) p q . Proof. refine (JMeq_eq (JMeq A a B b) p q _). refine (JMeq_UIP' A B a b p q). Defined. Definition JMeq_K (A : Type) (x : A) (P : JMeq A x A x -> Type) (c : P (JMeq_refl A x)) (p : JMeq A x A x) : P p . Proof. refine ( eq_elim_nodep (JMeq A x A x) (JMeq_refl A x) P c p (JMeq_UIP A A x x (JMeq_refl A x) p) ). Defined. Definition JMeq_UIP_refl (A : Type) (x : A) (p : JMeq A x A x) : eq (JMeq A x A x) (JMeq_refl A x) p . Proof. refine (JMeq_eq (JMeq A x A x) (JMeq_refl A x) p _). refine (JMeq_UIP'_refl A x p). Defined. (* JMeq_eqがどう簡約されるか *) Definition reduce_JMeq_eq (A : Type) (x : A) : eq (eq A x x) (JMeq_eq A x x (JMeq_refl A x)) (eq_refl A x) . Proof. refine (eq_sym (eq A x x) (eq_refl A x) (JMeq_eq A x x (JMeq_refl A x)) _). refine (UIP_refl A x (JMeq_eq A x x (JMeq_refl A x))). Defined. (* JMeq_eqを適用してeq_JMeqを適用すると元に戻る 証明不可能? *) Definition JMeq_eq_JMeq (A : Type) (x y : A) (p : JMeq A x A y) : eq (JMeq A x A y) (eq_JMeq A x y (JMeq_eq A x y p)) p . Proof. Abort. Definition eq_JMeq_eq (A : Type) (x y : A) (p : eq A x y) : eq (eq A x y) (JMeq_eq A x y (eq_JMeq A x y p)) p . Proof. refine ( eq_elim A x (fun y' p' => eq (eq A x y') (JMeq_eq A x y' (eq_JMeq A x y' p')) p') _ y p ). refine ( reduce_JMeq_eq A x ). Defined. Section Declare_JMeq_elim_eqlike. Variable JMeq_elim_eqlike : forall A x (P : forall y, JMeq A x A y -> Type), P x (JMeq_refl A x) -> forall y p, P y p. Definition JMeq_eq_JMeq (A : Type) (x y : A) (p : JMeq A x A y) : eq (JMeq A x A y) (eq_JMeq A x y (JMeq_eq A x y p)) p . Proof. refine ( JMeq_elim_eqlike A x (fun y' p' => eq (JMeq A x A y') (eq_JMeq A x y' (JMeq_eq A x y' p')) p') _ y p ). refine ( eq_elim_nodep (eq A x x) (eq_refl A x) (fun p' => eq (JMeq A x A x) (eq_JMeq A x x p') (JMeq_refl A x)) _ (JMeq_eq A x x (JMeq_refl A x)) (eq_sym (eq A x x) (JMeq_eq A x x (JMeq_refl A x)) (eq_refl A x) (reduce_JMeq_eq A x)) ). refine ( eq_refl (JMeq A x A x) (JMeq_refl A x) ). Defined. End Declare_JMeq_elim_eqlike. Section Declare_JMeq_eq_JMeq. (* この仮定をさらに弱められるかどうかは分かんない *) Variable JMeq_eq_JMeq : forall A x y p, eq (JMeq A x A y) (eq_JMeq A x y (JMeq_eq A x y p)) p. Definition JMeq_elim_eqlike (A : Type) (x : A) (P : forall y : A, JMeq A x A y -> Type) (c : P x (JMeq_refl A x)) (y : A) (p : JMeq A x A y) : P y p . Proof. refine ( eq_elim (JMeq A x A y) (eq_JMeq A x y (JMeq_eq A x y p)) (fun p' _ => P y p') _ p (JMeq_eq_JMeq A x y p) ). refine ( eq_elim A x (fun y' p' => P y' (eq_JMeq A x y' p')) _ y (JMeq_eq A x y p) ). refine c. Defined. End Declare_JMeq_eq_JMeq. End Declare_JMeq_eq. (* JMeq_elim_nodep_eqlikeを仮定して他の公理を導く *) Section Declare_JMeq_elim_nodep_eqlike. Variable JMeq_elim_nodep_eqlike : forall A x P, P x -> forall y, JMeq A x A y -> P y. Definition JMeq_eq_from_JMeq_elim_nodep_eqlike (A : Type) (x y : A) (p : JMeq A x A y) : eq A x y . Proof. refine ( JMeq_elim_nodep_eqlike A x (fun y' => eq A x y') (eq_refl A x) y p ). Defined. (* 証明不可能? *) Definition reduce_JMeq_elim_nodep_eqlike (A : Type) (x : A) (P : A -> Type) (c : P x) : eq (P x) (JMeq_elim_nodep_eqlike A x P c x (JMeq_refl A x)) c . Proof. Abort. End Declare_JMeq_elim_nodep_eqlike. (* JMeqを使って定義されたeq Coq.Logic.JMeq.JMeq_homとしてライブラリに存在。 *) Definition JMeqH (A : Type) (x y : A) := JMeq A x A y. (* eqと違い、示せる *) Definition JMeq_JMeqH (A : Type) (x y : A) (p : JMeq A x A y) : JMeqH A x y := p . Inductive ex (A : Type) (P : A -> Type) : Type := | ex_pair : forall x : A, P x -> ex A P . Definition ex_elim (A : Type) (P : A -> Type) (Q : ex A P -> Type) (c : forall (x : A) (xH : P x), Q (ex_pair A P x xH)) (x : ex A P) : Q x := match x as x' return Q x' with | ex_pair _ _ a aH => c a aH end . Definition ex_elim_nodep (A : Type) (P : A -> Type) (Q : Type) (c : forall (x : A), P x -> Q) (x : ex A P) : Q := match x with | ex_pair _ _ a aH => c a aH end . Definition eq_elim_nopoint (A : Type) (P : forall (x y : A), eq A x y -> Type) (c : forall a : A, P a a (eq_refl A a)) (x y : A) (p : eq A x y) : P x y p := match p as p' in eq _ _ y' return P x y' p' with | eq_refl _ _ => c x end . Definition eq_elim_nopoint_nodep (A : Type) (P : A -> A -> Type) (c : forall a : A, P a a) (x y : A) (p : eq A x y) : P x y := match p with | eq_refl _ _ => c x end . (* eqを使って定義されたJMeqもどき *) Definition eqJM (A : Type) (a : A) (B : Type) (b : B) := ex (eq Type A B) (fun p => (eq_elim_nopoint_nodep Type (fun A' B' => A' -> B' -> Type) eq A B p) a b) . (* 証明不可能? *) Definition eqJM_JMeq (A B : Type) (a : A) (b : B) (p : eqJM A a B b) : JMeq A a B b . Proof. Abort. Definition JMeq_eqJM (A B : Type) (a : A) (b : B) (p : JMeq A a B b) : eqJM A a B b . Proof. refine ( JMeq_elim_nodep A a (eqJM A a) _ B b p ). refine ( ex_pair (eq Type A A) (fun p => (eq_elim_nopoint_nodep Type (fun A' A'' => A' -> A'' -> Type) eq A A p) a a) (eq_refl Type A) _ ). refine ( eq_refl A a ). Defined. (* https://homotopytypetheory.org/2012/11/21/on-heterogeneous-equality/ *) Definition pointed_type : Type := ex Type (fun A => A). Definition unpointed (A : pointed_type) : Type := ex_elim_nodep Type (fun A => A) Type (fun A a => A) A . Definition base_point (A : pointed_type) : unpointed A := ex_elim Type (fun A => A) (fun A => unpointed A) (fun A a => a) A . Definition at_home (A : Type) (a : A) : pointed_type := ex_pair Type (fun A => A) A a. Definition ptEq_JMeq (A B : pointed_type) (p : eq pointed_type A B) : JMeq (unpointed A) (base_point A) (unpointed B) (base_point B) . Proof. refine ( eq_elim_nodep pointed_type A (fun B' => JMeq (unpointed A) (base_point A) (unpointed B') (base_point B')) _ B p ). refine ( JMeq_refl (unpointed A) (base_point A) ). Defined. Definition eqPt (A : Type) (a : A) (B : Type) (b : B) := eq pointed_type (at_home A a) (at_home B b) . Definition JMeq_eqPt (A B : Type) (a : A) (b : B) (p : JMeq A a B b) : eqPt A a B b . Proof. refine ( JMeq_elim_nodep A a (fun B' b' => eqPt A a B' b') _ B b p ). refine ( eq_refl pointed_type (at_home A a) ). Defined. Definition eqPt_JMeq (A B : Type) (a : A) (b : B) (p : eqPt A a B b) : JMeq A a B b . Proof. pose (pA := at_home A a). pose (pB := at_home B b). change (JMeq (unpointed pA) (base_point pA) (unpointed pB) (base_point pB)). refine (ptEq_JMeq pA pB p). Defined. (* この後さらにhequivであることがわかる *) Inductive JMeqE (A : Type) (a : A) : forall B : Type, B -> eq Type A B -> Type := | JMeqE_refl : JMeqE A a A a (eq_refl Type A) .
include("../../test/runtests.jl") import Makie include(joinpath(pkgdir(Makie), "test", "test_for_precompile.jl"))
{-# OPTIONS --without-K #-} open import HoTT open import lib.cubical.elims.CubeMove open import lib.cubical.elims.CofWedge module lib.cubical.elims.SuspSmash where module _ {i j k} {X : Ptd i} {Y : Ptd j} {C : Type k} (f : Suspension (X ∧ Y) → C) (g : Suspension (X ∧ Y) → C) (north* : f (north _) == g (north _)) (south* : f (south _) == g (south _)) (cod* : (s : fst X × fst Y) → Square north* (ap f (merid _ (cfcod _ s))) (ap g (merid _ (cfcod _ s))) south*) where private base* = transport (λ κ → Square north* (ap f (merid _ κ)) (ap g (merid _ κ)) south*) (! (cfglue _ (winl (snd X)))) (cod* (snd X , snd Y)) CubeType : (w : X ∨ Y) → Square north* (ap f (merid _ (cfcod _ (∨-in-× X Y w)))) (ap g (merid _ (cfcod _ (∨-in-× X Y w)))) south* → Type _ CubeType w sq = Cube base* sq (natural-square (λ _ → north*) (cfglue _ w)) (natural-square (ap f ∘ merid _) (cfglue _ w)) (natural-square (ap g ∘ merid _) (cfglue _ w)) (natural-square (λ _ → south*) (cfglue _ w)) fill : (w : X ∨ Y) (sq : Square north* (ap f (merid _ (cfcod _ (∨-in-× X Y w)))) (ap g (merid _ (cfcod _ (∨-in-× X Y w)))) south*) → Σ (Square north* idp idp north*) (λ p → CubeType w (p ⊡h sq)) fill w sq = (fst fill' , cube-right-from-front (fst fill') sq (snd fill')) where fill' = fill-cube-right _ _ _ _ _ fill0 = fill (winl (snd X)) (cod* (snd X , snd Y)) fillX = λ x → fill (winl x) (fst fill0 ⊡h cod* (x , snd Y)) fillY = λ y → fill (winr y) (fst fill0 ⊡h cod* (snd X , y)) fillX0 : fst (fillX (snd X)) == hid-square fillX0 = ⊡h-unit-l-unique _ (fst fill0 ⊡h cod* (snd X , snd Y)) (fill-cube-right-unique (snd (fillX (snd X))) ∙ ! (fill-cube-right-unique (snd fill0))) fillY0 : fst (fillY (snd Y)) == hid-square fillY0 = ⊡h-unit-l-unique _ (fst fill0 ⊡h cod* (snd X , snd Y)) (fill-cube-right-unique (snd (fillY (snd Y))) ∙ ! (fill-cube-right-unique (snd (fill (winr (snd Y)) (cod* (snd X , snd Y))))) ∙ ! (ap (λ w → fst (fill w (cod* (∨-in-× X Y w))) ⊡h cod* (snd X , snd Y)) wglue)) where fill-square : (w : X ∨ Y) → Square north* (ap f (merid _ (cfcod _ (∨-in-× X Y w)))) (ap g (merid _ (cfcod _ (∨-in-× X Y w)))) south* fill-square w = fst (fill-cube-right base* (natural-square (λ _ → north*) (cfglue _ w)) (natural-square (ap f ∘ merid _) (cfglue _ w)) (natural-square (ap g ∘ merid _) (cfglue _ w)) (natural-square (λ _ → south*) (cfglue _ w))) abstract coh : (s : X ∧ Y) → north* == south* [ (λ z → f z == g z) ↓ merid _ s ] coh = ↓-='-from-square ∘ cof-wedge-square-elim _ _ _ _ base* (λ {(x , y) → fst (fillX x) ⊡h fst (fillY y) ⊡h fst fill0 ⊡h cod* (x , y)}) (λ x → transport (λ sq → CubeType (winl x) (fst (fillX x) ⊡h sq)) (! (ap (λ sq' → sq' ⊡h fst fill0 ⊡h cod* (x , snd Y)) fillY0 ∙ ⊡h-unit-l (fst fill0 ⊡h cod* (x , snd Y)))) (snd (fillX x))) (λ y → transport (CubeType (winr y)) (! (ap (λ sq' → sq' ⊡h fst (fillY y) ⊡h fst fill0 ⊡h cod* (snd X , y)) fillX0 ∙ ⊡h-unit-l (fst (fillY y) ⊡h fst fill0 ⊡h cod* (snd X , y)))) (snd (fillY y))) susp-smash-path-elim : ((σ : Suspension (X ∧ Y)) → f σ == g σ) susp-smash-path-elim = Suspension-elim _ north* south* coh
2010 marked the first time the majority of the world’s population was living in urban areas (52%), up from 47% in 2000. The global share of population living in urban areas is projected to increase to two-thirds by 2050. In 1990, the nation’s population was heavily urban (78%). By 2010, more than four of every five U.S. residents was living in an urban area. In some states, such as California (95%) and New Jersey (94.7%), nearly all of the state’s population resides in urban areas. North Carolina has a significantly smaller share of its population living in urban areas than the national average, but has increasingly urbanized over the past two decades. In 2010, two of every three North Carolina residents was living in an urban area, up from 60% in 2000. Among North Carolina’s 100 counties, only 8 are as urbanized (or more) as the nation. Mecklenburg is the most urbanized county: 99% of Mecklenburg’s population lives in an urban area and 86% of the land area was classified as urban in 2010. Among the other 10 most urban counties in the state, only New Hanover, Wake, and Forsyth have more than half of their land area classified as urban. In 2010, North Carolina had the second largest rural population (3.2 million) after Texas (3.8 million). Fourteen counties in the state have no urban areas at all. They contained 191,000 residents—2% of the state’s population—in 2010. Nationwide, there are 486 urbanized areas and 3,087 urban clusters. The population classified as urban includes all individuals living in urbanized areas and urban clusters. This entry was posted in Carolina Demographics and tagged rural, trends, urban, urbanization. Bookmark the permalink.
import Lean macro "t" t:interpolatedStr(term) : doElem => `(Macro.trace[Meta.debug] $t) macro "tstcmd" : command => do t "hello" `(example : Nat := 1) set_option trace.Meta.debug true in tstcmd open Lean Meta macro "r" r:interpolatedStr(term) : doElem => `(trace[Meta.debug] $r) set_option trace.Meta.debug true in #eval show MetaM _ from do r "world"
(* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) *) (* * Tactic for solving monadic equalities, such as: * * (liftE (return 3) = returnOk 3 * * Theorems of the form: * * ((a, s') \<in> fst (A s)) = P a s s' * * and * * snd (A s) = P s * * are added to the "monad_eq" set. *) theory MonadEq imports "wp/NonDetMonadVCG" begin (* Setup "monad_eq" attributes. *) ML {* structure MonadEqThms = Named_Thms ( val name = Binding.name "monad_eq" val description = "monad equality-prover theorems" ) *} attribute_setup monad_eq = {* Attrib.add_del (Thm.declaration_attribute MonadEqThms.add_thm) (Thm.declaration_attribute MonadEqThms.del_thm) *} "Monad equality-prover theorems" (* Setup tactic. *) ML {* fun monad_eq_tac ctxt = let (* Set a simpset as being hidden, so warnings are not printed from it. *) val ctxt' = Context_Position.set_visible false ctxt in CHANGED (clarsimp_tac (ctxt' addsimps (MonadEqThms.get ctxt')) 1) end *} method_setup monad_eq = {* Method.sections Clasimp.clasimp_modifiers >> (K (SIMPLE_METHOD o monad_eq_tac)) *} "prove equality on monads" lemma monad_eq_simp_state [monad_eq]: "((A :: ('s, 'a) nondet_monad) s = B s') = ((\<forall>r t. (r, t) \<in> fst (A s) \<longrightarrow> (r, t) \<in> fst (B s')) \<and> (\<forall>r t. (r, t) \<in> fst (B s') \<longrightarrow> (r, t) \<in> fst (A s)) \<and> (snd (A s) = snd (B s')))" apply (auto intro!: set_eqI prod_eqI) done lemma monad_eq_simp [monad_eq]: "((A :: ('s, 'a) nondet_monad) = B) = ((\<forall>r t s. (r, t) \<in> fst (A s) \<longrightarrow> (r, t) \<in> fst (B s)) \<and> (\<forall>r t s. (r, t) \<in> fst (B s) \<longrightarrow> (r, t) \<in> fst (A s)) \<and> (\<forall>x. snd (A x) = snd (B x)))" apply (auto intro!: set_eqI prod_eqI) done declare in_monad [monad_eq] declare in_bindE [monad_eq] (* Test *) lemma "returnOk 3 = liftE (return 3)" apply monad_eq oops end
Require Import Events. Require Import TraceModel. Require Import Properties. Require Import CommonST. Require Import Robustdef. Require Import Criteria. Require Import Setoid. Require Import ClassicalExtras. Require Import Logic.ClassicalFacts. Require Import TechnicalLemmas. (** This file proves that R2RTP implies RTEP *) (** *our assumptions *) (**********************************************************) Hypothesis input_totality_tgt : input_totality tgt. Hypothesis determinacy_src : determinacy src. Hypothesis tgt_sem : semantics_safety_like tgt. (**********************************************************) Theorem R2rTP_RTIP : R2rTP -> RTIP. Proof. intros r2rpp. unfold RTIP. apply NNPP. intros hf. rewrite not_forall_ex_not in hf. destruct hf as [P1 hf]. rewrite not_forall_ex_not in hf. destruct hf as [P2 hf]. rewrite not_imp in hf. destruct hf as [H1 hf]. unfold "⊆" in *. rewrite not_forall_ex_not in hf. destruct hf as [Ct hf]. rewrite not_forall_ex_not in hf. destruct hf as [t hf]. rewrite not_imp in hf. destruct hf as [k1 k2]. specialize (r2rpp P1 P2 traces_match). assert (Hsat : rsat2 P1 P2 traces_match). { intros C b1 b2 Hb1 Hb2. apply (H1 C b1) in Hb1. unfold beh in Hb1. now apply (determinacy_src (C [P2])). } specialize (r2rpp Hsat Ct t); clear Hsat. assert (H : forall t2, sem tgt (Ct [P2 ↓]) t2 -> traces_match t t2). { intros t2 H. now apply r2rpp. } clear r2rpp H1. destruct (longest_in_psem tgt_sem (Ct [P2 ↓]) t k2) as [l [Hmt [Hpsem_m Hmax_m]]]. destruct Hpsem_m as [t2 [Hmt2 Hsem_t2]]. specialize (H t2 Hsem_t2). destruct H; try now subst. destruct H as [ll [i1 [i2 [Hi1 [Hi2 [Hdiffi [Hpref1 Hpref2]]]]]]]. assert (psem (Ct [P2 ↓]) (ftbd (snoc ll i1))). { apply (input_totality_tgt (Ct [P2 ↓]) ll i2 i1); auto. now exists t2. } assert (fpr (ftbd (snoc ll i1)) l) by now apply Hmax_m. apply (fpr_pref_pref _ _ t2) in H0; auto. destruct (same_ext (ftbd (snoc ll i1)) (ftbd (snoc ll i2)) t2); auto; simpl in H1. ++ apply (list_snoc_pointwise ll ll i1 i2 i2 i2) in H1; auto. inversion H1. congruence. now apply list_list_prefix_ref. ++ apply (list_snoc_pointwise ll ll i2 i1 i1 i1) in H1; auto. inversion H1. congruence. now apply list_list_prefix_ref. Qed. Theorem R2rTP_RTEP : R2rTP -> RTEP. Proof. intros H. apply RTIP_RTEP. exact (R2rTP_RTIP H). Qed.
function display(anno) fprintf(1,'\n %s = \n', inputname(1)); fprintf(1,'\tdim = %d\n', anno.dim); fprintf(1,'\t#points = %d\n', anno.npts); fprintf(1,'\tclass = %s\n', anno.ccls); fprintf(1,'\tkd_ptr = %lu\n', anno.kd_ptr);
namespace prop_09 variables X Y : Prop theorem prop_9 (h : X ∨ Y) (h2 : ¬ X) : Y := show Y, from or.elim h (assume h1: X, show Y, from (classical.by_contradiction (assume Y, h2 h1))) (assume h3: Y, h3) -- end namespace end prop_09
plotFootprint <- function(x,SensorName,rn=NULL,MyMap=NULL,type=c("CE","wCE","uCE"),use.avg=FALSE,use.sym=FALSE,use.var=TRUE,wTDcutoff=NULL,origin=NULL, dx=2,dy=dx,breaks=function(x)quantile(c(0,max(x)),c(0.01,0.1,0.5,0.9)),xlim=c(-100,100),ylim=c(-100,100),add=FALSE,alpha=0.3,axs=c("r","i"), main=NULL,asp=1,fill=TRUE,sub=NULL,bg.col=NULL,addSource=TRUE,showMax=FALSE,showSensor=TRUE,dispSname=showSensor, N0 = NULL, lpos=NULL,showPerc=FALSE,leg.bg.col=grey(0.9),cpal=NULL,decPlaces=0,sigNums=1,addWR=FALSE,WRpos=2,WRfrac=20,WRscale=1,xy_transform=NULL,transformArgs=NULL, useSTRtree=TRUE,avoidGEOS = FALSE,addSB=FALSE,SBpos=3,StaticMapArgs=NULL,showLegend=TRUE){ if(!requireNamespace("maptools")){ stop("please install package maptools: install.packages('maptools')") } if(!requireNamespace("rgeos")){ stop("please install package rgeos: install.packages('rgeos')") } # Notizen: # - Sources spaeter hinzufuegen # - Methode fuer Catalog hinzufuegen # - arguments besser organisieren # - main auch bei MyMap # - xlim/ylim xy_transform WGS84 etc... besser organisieren!!! # - xy_transform --> coords_2_WGS84 oder so # - TrueProj als Argument, oder besser: if add=TRUE, par()$usr -> MyMap$size??? sx <- as.character(substitute(x)) if(inherits(x, "footprint")){ # breaks=rev(brks) xy_transform <- x$xy_transform transformArgs <- x$transformArgs SensorPosition <- x$SensorPosition WDmean <- x$WDmean xlimOriginal <- x$xlimOriginal ylimOriginal <- x$ylimOriginal xm <- x$xm ym <- x$ym xy <- x$xy if(!add){ stop("only add=TRUE supported when providing a footprint object") } } else { # convert old versions x <- copy(x) setDT(x) switchNames(x) if(is.null(attr(x, "Version"))){ warning(paste0("Object '", sx[min(length(sx), 2)], "' has not yet been converted to version 4.2+")) convert(x) } # checks: if(missing(SensorName)){ stop("SensorName must be provided") } else { getThisSensor <- as.character(SensorName[1]) if(!nrow(x[Sensor==getThisSensor]))stop("No results for Sensor: ",getThisSensor," availabe!") } stopifnot(type[1] %in% c("CE","wCE","uCE")) if(is.null(rn)){ getThisRows <- x[Sensor==getThisSensor,unique(rn)] } else { getThisRows <- as.integer(rn) } getThisSource <- x[rn%in%getThisRows&Sensor==getThisSensor,Source[1]] index <- x[,which(rn%in%getThisRows&Sensor==getThisSensor&Source==getThisSource)] WD <- x[index,WD] if(is.null(N0)){ N0 <- x[index[1],N0] } else { if(any(x[index,N0]<N0))stop("Choose N0 smaller or equal to original N0!") } Ustar <- x[index,Ustar] Suu <- x[index,sUu] Svu <- x[index,sVu] bw <- x[index,bw] z <- x[index,SensorHeight] L <- x[index,L] Zo <- x[index,Zo] Source <- attr(procSources(attr(x,"ModelInput")$Sources),"SourceList") if(length(index)>1){ WDmean <- (360 + atan2(sum(sin(WD/180*pi)*Ustar)/sum(Ustar),sum(cos(WD/180*pi)*Ustar)/sum(Ustar))/pi*180) %% 360 } else { WDmean <- WD } Calc.Sensors <- procSensors(attr(x,"ModelInput")$Sensors)$"Calc.Sensors" SensorPosition <- Calc.Sensors[Calc.Sensors[, "Sensor Name"] %chin% SensorName, c("Sensor Name", "x-Coord (m)", "y-Coord (m)", "Sensor ID", "Node")] SPR <- rotate(SensorPosition[,2:3],Angle=-WDmean) if(is.null(origin)){ origin <- colMeans(SensorPosition[,2:3]) } if(!add){ if(is.null(main))main <- switch(type[1], "CE"="C-Footprint", "wCE"="w'C'-Footprint", "uCE"="u'C'-Footprint") if(is.null(MyMap)){ plot(SensorPosition[,2],SensorPosition[,3],type="n",xlim=xlim + origin[1],ylim=ylim + origin[2],xlab="",ylab="",asp=asp,yaxt="n",xaxt="n",main=main,sub=sub) pr <- par() if(!is.null(bg.col))polygon(pr$usr[c(1,2,2,1)],pr$usr[c(3,3,4,4)],col=bg.col) axis(1,at=atx<-pretty(pr$usr[1:2])) axis(2,at=aty<-pretty(pr$usr[3:4])) } else { do.call(PlotOnStaticMap,c(list(MyMap=MyMap),StaticMapArgs)) pr <- par() add <- TRUE } } else { pr <- par() } if(!is.null(MyMap)){ if(!("TrueProj" %in% names(StaticMapArgs))||!StaticMapArgs$TrueProj){ xy_transformOriginal <- xy_transform if(is.null(xy_transform)){ xy_transform <- function(x,y,mymap=MyMap,...){ LatLon2XY.centered(mymap,y,x) } } else { xy_transform <- function(x,y,mymap=MyMap,...){ xy <- xy_transformOriginal(x,y,...) LatLon2XY.centered(mymap,xy$y,xy$x) } } } } if(addSource){ for(i in Source){ pg <- i if(!is.null(xy_transform)){ pg[1:2] <- do.call(xy_transform,c(list(x=pg[,1],y=pg[,2]),transformArgs)) } upg <- unique(pg[,3]) for(j in upg){ ind <- which(pg[,3]==j) polygon(pg[ind,1],pg[ind,2],col="#006837") } } } # transform x/y: if(!is.null(xy_transform)){ SensorPosition[, 2:3] <- do.call(xy_transform,c(list(x=SensorPosition[,2],y=SensorPosition[,3]),transformArgs)) } if(showSensor){ sp_dt <- setnames(as.data.table(attr(x,"ModelInput")$Sensors[, c("Sensor Name", "x-Coord (m)", "y-Coord (m)", "Sensor ID", "Node")]), c("name", "x", "y", "id", "node"))[name == getThisSensor] # cat("hier stimmt's noch nicht falls google maps!\n") if(dispSname){ if(sp_dt[, length(unique(id)) > 1]){ sp_dt[, { ind <- order(node) lines(x[ind], y[ind], lty = 2, cex = 1.5) points(x[ind], y[ind], pch = 20, cex = 1.5) text(mean(x), mean(y), paste0(name[1], " (", .BY$id, ")"), cex = 0.6, pos = 4) }, by = id] } else { sp_dt[, { ind <- order(node) lines(x[ind], y[ind], lty = 2, cex = 1.5) points(x[ind], y[ind], pch = 20, cex = 1.5) text(mean(x), mean(y), name[1], cex = 0.6, pos = 4) }, by = id] } } else { sp_dt[, { ind <- order(node) lines(x[ind], y[ind], lty = 2, cex = 1.5) points(x[ind], y[ind], pch = 20, cex = 1.5) }, by = id] } } xlim <- pr$usr[1:2] ylim <- pr$usr[3:4] xlimOriginal <- xlim ylimOriginal <- ylim if(!is.null(xy_transform)){ parscale1 <- max(c(xlim[1],ylim[1])) parscale2 <- max(c(xlim[2],ylim[2])) lim1 <- optim(c(-1,-1),function(x)sum((unlist(do.call(xy_transform,c(list(x=x[1],y=x[2]),transformArgs))) - c(xlim[1],ylim[1]))^2),control=list(reltol=sqrt(.Machine$double.eps)/parscale1))$par lim2 <- optim(c(1,1),function(x)sum((unlist(do.call(xy_transform,c(list(x=x[1],y=x[2]),transformArgs))) - c(xlim[2],ylim[2]))^2),control=list(reltol=sqrt(.Machine$double.eps)/parscale2))$par xlim <- c(lim1[1],lim2[1]) ylim <- c(lim1[2],lim2[2]) } xylim <- cbind(x=c(xlim,rev(xlim)),y=rep(ylim,each=2)) xylim <- rotate(xylim,Angle=-WDmean) xb <- seq(min(xylim[,1])-10*dx,max(xylim[,1])+10*dx,dx) yb <- seq(min(xylim[,2])-10*dy,max(xylim[,2])+10*dy,dy) xm <- xb[-1] - dx/2 ym <- yb[-1] - dy/2 xy <- matrix(0,nrow=length(xm),ncol=length(ym)) # loop over index for(j in seq_along(index)){ cat(j,"/",length(index),"\n") Catalogs <- getCatalogs(x,index[j]) CatNames <- Catalogs[,Catalog] Subset_seed <- Catalogs[, seed] dummy <- "" Ustardummy <- -9999 # loop over point sensors for(i in seq_along(CatNames)){ # i <- 1 xytemp <- matrix(0,nrow=length(xm),ncol=length(ym)) if(dummy!=CatNames[i]|x[index[j],Ustar!=Ustardummy]){ dummy <- CatNames[i] Catalog <- readCatalog(CatNames[i]) initializeCatalog(x[index[j],], Catalog=Catalog) uvw <- uvw0(Catalog) # subset? if(attr(Catalog,"N0")>N0){ env <- globalenv() oseed <- env$.Random.seed set.seed(Subset_seed,kind="L'Ecuyer-CMRG") takeSub <- sort(sample.int(attr(Catalog,"N0"),N0)) if (is.null(oseed)) { rm(list = ".Random.seed", envir = env) } else { assign(".Random.seed", value = oseed, envir = env) } attCat <- attributes(Catalog) indexNew <- 1:N0 names(indexNew) <- takeSub Catalog <- Catalog[Traj_ID %in% takeSub,] Catalog[,":="(Traj_ID=indexNew[as.character(Traj_ID)])] for(ac in (names(attCat) %w/o% c("names","row.names",".internal.selfref","uvw0")))setattr(Catalog,ac,attCat[[ac]]) uvw <- uvw[takeSub,] setattr(Catalog,"uvw0",uvw) HeaderSub <- paste(attr(Catalog,"header"),"\n*** Subset of ",N0," Trajectories ***\n\n",sep="") class(HeaderSub) <- c("TDhead","character") setattr(Catalog,"N0",N0) setattr(Catalog,"header",HeaderSub) } if(!is.null(wTDcutoff)) Catalog[wTD<wTDcutoff,wTD:=wTDcutoff] Catalog[,CE:=2/wTD/N0] if(use.avg)Catalog[,CE:=mean(CE)] if(type[1]!="CE"){ if(type[1]=="wCE"){ w0 <- uvw0(Catalog)[,"w0"] } else { w0 <- uvw0(Catalog)[,"u0"] - calcU(Ustar, Zo, L, z) } Catalog[,CE:=w0[Traj_ID]*CE] } if(use.sym){ Catalog <- Catalog[rep(1:.N,2)] Catalog[1:(.N/2),y:=-y] Catalog[,CE:=CE/2] } } Ctlg <- copy(Catalog) rotateCatalog(Ctlg,WD[j]-WDmean) Ctlg <- Ctlg[,":="(x=x+SPR[i,1],y=y+SPR[i,2],CE=CE/length(CatNames)/length(index))][ x>=xb[1]&x<=xb[length(xb)]&y>=yb[1]&y<=yb[length(yb)] ] Ctlg[,":="(xtag=findInterval(x,xb, rightmost.closed = TRUE), ytag=findInterval(y,yb, rightmost.closed = TRUE))] Cat <- Ctlg[,sum(CE),by=.(xtag,ytag)] xytemp[Cat[,cbind(xtag,ytag)]] <- Cat[,V1] if(use.var){ xb2l <- Ctlg[,c(rev(seq(SPR[i,1]-3*dx/2,min(x,SPR[i,1])-10*dx,-2*dx)),seq(SPR[i,1]+dx/2,max(x,SPR[i,1])+10*dx,2*dx))] yb2l <- Ctlg[,c(rev(seq(SPR[i,2]-3*dy/2,min(y,SPR[i,2])-10*dy,-2*dy)),seq(SPR[i,2]+dy/2,max(y,SPR[i,2])+10*dy,2*dy))] xb2r <- xb2l + dx yb2r <- yb2l + dx Ctlg[,":="( xtag_ll=findInterval(x,xb2l),ytag_ll=findInterval(y,yb2l) ,xtag_lr=findInterval(x,xb2l),ytag_lr=findInterval(y,yb2r) ,xtag_rl=findInterval(x,xb2r),ytag_rl=findInterval(y,yb2l) ,xtag_rr=findInterval(x,xb2r),ytag_rr=findInterval(y,yb2r) )] Cat_ll <- Ctlg[,sum(CE),by=.(xtag_ll,ytag_ll)] Cat_lr <- Ctlg[,sum(CE),by=.(xtag_lr,ytag_lr)] Cat_rl <- Ctlg[,sum(CE),by=.(xtag_rl,ytag_rl)] Cat_rr <- Ctlg[,sum(CE),by=.(xtag_rr,ytag_rr)] xy_ll <- xy_lr <- xy_rl <- xy_rr <- matrix(0,nrow=length(xb2r)-1,ncol=length(yb2r)-1) xy_ll[Cat_ll[,cbind(xtag_ll,ytag_ll)]] <- Cat_ll[,V1] xy_lr[Cat_lr[,cbind(xtag_lr,ytag_lr)]] <- Cat_lr[,V1] xy_rl[Cat_rl[,cbind(xtag_rl,ytag_rl)]] <- Cat_rl[,V1] xy_rr[Cat_rr[,cbind(xtag_rr,ytag_rr)]] <- Cat_rr[,V1] xmil <- findInterval(xm,xb2l,all.inside = TRUE) ymil <- findInterval(ym,yb2l,all.inside = TRUE) xmir <- findInterval(xm,xb2r,all.inside = TRUE) ymir <- findInterval(ym,yb2r,all.inside = TRUE) xyi_ll <- as.matrix(expand.grid(x=xmil,y=ymil,KEEP.OUT.ATTRS=FALSE)) xyi_rr <- as.matrix(expand.grid(x=xmir,y=ymir,KEEP.OUT.ATTRS=FALSE)) xyi_lr <- as.matrix(expand.grid(x=xmil,y=ymir,KEEP.OUT.ATTRS=FALSE)) xyi_rl <- as.matrix(expand.grid(x=xmir,y=ymil,KEEP.OUT.ATTRS=FALSE)) Mu <- (xy_ll[xyi_ll] + xy_lr[xyi_lr] + xy_rl[xyi_rl] + xy_rr[xyi_rr])/4 Var <- (4*xytemp - Mu)^2 xytemp <- (xytemp*Var + (max(Var)-Var)/4*Mu)/(max(Var)) } xy <- xy + xytemp/(dx*dy) } } rm(Catalog,Ctlg,Cat) xy[,c(1,ncol(xy))] <- 0 xy[c(1,nrow(xy)),] <- 0 } brks <- breaks(xy) cl <- contourLines(xm,ym,xy,levels=brks) clRot <- lapply(cl,rotate,Angle=WDmean) clFac <- as.factor(sapply(clRot,"[[","level")) uclFac <- unique(clFac) # transform x/y: if(!is.null(xy_transform)){ clRot <- lapply(clRot,function(x){ a <- do.call(xy_transform,c(list(x=x$x,y=x$y),transformArgs)) list(level=x$level,x=a[[1]],y=a[[2]]) }) } clP <- lapply(clRot,function(x)sp::Polygon(cbind(x$x,x$y))) clPs <- lapply(uclFac,function(x,y,z,a,b)maptools::checkPolygonsHoles(sp::Polygons(y[z==x],as.character(x)),useSTRtree=a,avoidGEOS=b),y=clP,z=clFac,a=useSTRtree,b=avoidGEOS) clSp <- sp::SpatialPolygons(clPs,as.integer(uclFac)) # if(is.null(xlim)&is.null(ylim)){ # xyr <- rotate(cbind(x=range(xm),y=range(ym)),Angle=WDmean+180) # xlim <- range(xyr[,1]) + range(SensorPosition[,2]) # ylim <- range(xyr[,2]) + range(SensorPosition[,3]) # } # Loesung: mlt <- switch(axs[1], "i"=1.08, 1 ) xlim2 <- xlimOriginal - diff(xlimOriginal)*(1-1/mlt)/2;ylim2 <- ylimOriginal - diff(ylimOriginal)*(1-1/mlt)/2 c1 <- sp::Polygon(cbind(c(xlim2[1],xlim2[2],xlim2[2],xlim2[1], xlim2[1]),c(ylim2[1],ylim2[1],ylim2[2],ylim2[2],ylim2[1]))) c2 <- sp::Polygons(list(c1), "sclip") Pclip <- sp::SpatialPolygons(list(c2)) SpPclip <- rgeos::gIntersection(clSp, Pclip, byid = TRUE) alphachar <- as.hexmode(round(alpha*255)) if(is.null(cpal)){ cpal <- if(type[1]=="CE") ConcPalette(length(brks)) else FluxPalette(length(brks)) } else { cpal <- cpal(length(brks)) } if(!add){abline(h=aty,lty="dotted",col="lightgrey");abline(v=atx,lty="dotted",col="lightgrey")} if(fill)fillcol <- paste0(cpal,alphachar) else fillcol <- NA sp::plot(SpPclip,col=fillcol,border=cpal,add=TRUE) box() if(showMax){ mi <- which(xy==max(xy),arr.ind=T) maxli <- rotate(cbind(x=xm[mi[1]],y=ym[mi[2]]),Angle=WD+90,Center=origin)+c(SensorPosition[,2],SensorPosition[,3]) points(maxli,pch=20,cex=0.4,col="red") text(maxli[1],maxli[2],"max.",cex=0.6,pos=4,offset=0.2,col="red") } if(showLegend){ if(is.null(lpos))lpos <- c("bottomleft","topleft","topright","bottomright")[floor(WDmean/90)+1] if(showPerc){ ltex <- sprintf(paste0("%2.",decPlaces,"f%%"),rev(brks)/max(xy)*100) ltex <- paste0(">",ltex) temp <- legend(lpos,legend=rep(" ",length(ltex)),title="% of max.",text.width=strwidth(paste0("00",if(decPlaces>0){paste0(".",paste0(rep("0",decPlaces),collapse=""))}else{""}," %")),fill=paste0(rev(cpal),alphachar),border=rev(cpal),bg=leg.bg.col) text(temp$rect$left + temp$rect$w, temp$text$y,ltex, pos = 2) } else { ltex <- signif(rev(brks),sigNums) ltex <- paste0(">",ltex) legend(lpos,legend=ltex,xjust=0,fill=paste0(rev(cpal),alphachar),border=rev(cpal),bg=leg.bg.col) } } if(addWR)addWindrose(WDmean,pos=WRpos,frac=WRfrac,scF=WRscale) scale <- if(is.null(MyMap)) 1 else MyMap if(addSB)addScaleBar(SBpos,scale) wm <- which(xy==max(xy),arr.ind=TRUE) WDrad <- WDmean/180*pi out <- structure(list( breaks=rev(brks), range.z=range(xy), max.pos=cbind(x=-xm[wm[1]]*sin(WDrad)+ym[wm[2]]*cos(WDrad)+SensorPosition[,2],y=-xm[wm[1]]*cos(WDrad)-ym[wm[2]]*sin(WDrad)+SensorPosition[,3]), xy_transform = xy_transform, transformArgs = transformArgs, SensorPosition = SensorPosition, WDmean = WDmean, xlimOriginal = xlimOriginal, ylimOriginal = ylimOriginal, xm = xm, ym = ym, xy = xy), class = "footprint" ) return(invisible(out)) }
(* File: Buffons_Needle.thy Author: Manuel Eberl <[email protected]> A formal solution of Buffon's needle problem. *) section \<open>Buffon's Needle Problem\<close> theory Buffons_Needle imports "HOL-Probability.Probability" begin subsection \<open>Auxiliary material\<close> lemma sin_le_zero': "sin x \<le> 0" if "x \<ge> -pi" "x \<le> 0" for x by (metis minus_le_iff neg_0_le_iff_le sin_ge_zero sin_minus that(1) that(2)) subsection \<open>Problem definition\<close> text \<open> Consider a needle of length $l$ whose centre has the $x$-coordinate $x$. The following then defines the set of all $x$-coordinates that the needle covers (i.e. the projection of the needle onto the $x$-axis.) \<close> definition needle :: "real \<Rightarrow> real \<Rightarrow> real \<Rightarrow> real set" where "needle l x \<phi> = closed_segment (x - l / 2 * sin \<phi>) (x + l / 2 * sin \<phi>)" text_raw \<open> \begin{figure} \begin{center} \begin{tikzpicture} \coordinate (lefttick) at (-3,0); \coordinate (righttick) at (3,0); \draw (lefttick) -- (righttick); \draw [thick] (lefttick) ++ (0,0.4) -- ++(0,3); \draw [thick] (righttick) ++ (0,0.4) -- ++(0,3); \coordinate (needle) at (1,2); \newcommand{\needleangle}{55} \newcommand{\needlelength}{{1}} \newcommand{\needlethickness}{0.6pt} \draw ($(lefttick)+(0,4pt)$) -- ($(lefttick)-(0,4pt)$); \draw ($(righttick)+(0,4pt)$) -- ($(righttick)-(0,4pt)$); \draw (0,4pt) -- (0,-4pt); \draw [densely dashed, thin] let \p1 = (needle) in (\x1, 0) -- (needle); \draw [densely dashed, thin] let \p1 = (needle) in (needle) -- (3, \y1); \draw (needle) ++ (15pt,0) arc(0:\needleangle:15pt); \path (needle) -- ++(15pt,0) node [above, midway, yshift=-1.9pt, xshift=1.8pt] {$\scriptstyle\varphi$}; \node [below, xshift=-3.5pt] at ($(lefttick)-(0,4pt)$) {$-\nicefrac{d}{2}$}; \node [below] at ($(righttick)-(0,4pt)$) {$\nicefrac{d}{2}$}; \node [below,yshift=-1pt] at (0,-4pt) {$0$}; \node [below,yshift=-2pt] at (needle |- 0,-4pt) {$x$}; \draw[<->] (needle) ++({\needleangle+90}:5pt) ++(\needleangle:{-\needlelength}) -- ++(\needleangle:2) node [midway, above, rotate=\needleangle] {$\scriptstyle l$}; \draw [line width=0.7pt,fill=white] (needle) ++({\needleangle+90}:\needlethickness) -- ++(\needleangle:\needlelength) arc({\needleangle+90}:{\needleangle-90}:\needlethickness) -- ++(\needleangle:-\needlelength) -- ++(\needleangle:-\needlelength) arc({\needleangle+270}:{\needleangle+90}:\needlethickness) -- ++(\needleangle:\needlelength); \end{tikzpicture} \end{center} \caption{A sketch of the situation in Buffon's needle experiment. There is a needle of length $l$ with its centre at a certain $x$ coordinate, angled at an angle $\varphi$ off the horizontal axis. The two vertical lines are a distance of $d$ apart, each being $\nicefrac{d}{2}$ away from the origin.} \label{fig:buffon} \end{figure} \definecolor{myred}{HTML}{cc2428} \begin{figure}[h] \begin{center} \begin{tikzpicture} \begin{axis}[ xmin=0, xmax=7, ymin=0, ymax=1, width=\textwidth, height=0.6\textwidth, xlabel={$l/d$}, ylabel={$\mathcal P$}, tick style={thin,black}, ylabel style = {rotate=270,anchor=west}, ] \addplot [color=myred, line width=1pt, mark=none,domain=0:1,samples=200] ({x}, {2/pi*x}); \addplot [color=myred, line width=1pt, mark=none,domain=1:7,samples=200] ({x}, {2/pi*(x-sqrt(x*x-1)+acos(1/x)/180*pi)}); \end{axis} \end{tikzpicture} \caption{The probability $\mathcal P$ of the needle hitting one of the lines, as a function of the quotient $l/d$ (where $l$ is the length of the needle and $d$ the horizontal distance between the lines).} \label{fig:buffonplot} \end{center} \end{figure} \<close> text \<open> Buffon's Needle problem is then this: Assuming the needle's $x$ position is chosen uniformly at random in a strip of width $d$ centred at the origin, what is the probability that the needle crosses at least one of the left/right boundaries of that strip (located at $x = \pm\frac{1}{2}d$)? We will show that, if we let $x := \nicefrac{l}{d}$, the probability of this is \[ \mathcal P_{l,d} = \begin{cases} \nicefrac{2}{\pi} \cdot x & \text{if}\ l \leq d\\ \nicefrac{2}{\pi}\cdot(x - \sqrt{x^2 - 1} + \arccos (\nicefrac{1}{x})) & \text{if}\ l \geq d \end{cases} \] A plot of this function can be found in Figure~\ref{fig:buffonplot}. \<close> locale Buffon = fixes d l :: real assumes d: "d > 0" and l: "l > 0" begin definition Buffon :: "(real \<times> real) measure" where "Buffon = uniform_measure lborel ({-d/2..d/2} \<times> {-pi..pi})" lemma space_Buffon [simp]: "space Buffon = UNIV" by (simp add: Buffon_def) definition Buffon_set :: "(real \<times> real) set" where "Buffon_set = {(x,\<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}}" subsection \<open>Derivation of the solution\<close> text \<open> The following form is a bit easier to handle. \<close> lemma Buffon_set_altdef1: "Buffon_set = {(x,\<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}. let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi> in min a b + d/2 \<le> 0 \<and> max a b + d/2 \<ge> 0 \<or> min a b - d/2 \<le> 0 \<and> max a b - d/2 \<ge> 0}" proof - have "(\<lambda>(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) = (\<lambda>(x,\<phi>). let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi> in -d/2 \<ge> min a b \<and> -d/2 \<le> max a b \<or> min a b \<le> d/2 \<and> max a b \<ge> d/2)" by (auto simp: needle_def Let_def closed_segment_eq_real_ivl min_def max_def) also have "\<dots> = (\<lambda>(x,\<phi>). let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi> in min a b + d/2 \<le> 0 \<and> max a b + d/2 \<ge> 0 \<or> min a b - d/2 \<le> 0 \<and> max a b - d/2 \<ge> 0)" by (auto simp add: algebra_simps Let_def) finally show ?thesis unfolding Buffon_set_def case_prod_unfold by (intro Collect_cong conj_cong refl) meson qed lemma Buffon_set_altdef2: "Buffon_set = {(x,\<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}. abs x \<ge> d / 2 - abs (sin \<phi>) * l / 2}" unfolding Buffon_set_altdef1 proof (intro Collect_cong prod.case_cong refl conj_cong) fix x \<phi> assume *: "(x, \<phi>) \<in> {-d/2..d/2} \<times> {-pi..pi}" let ?P = "\<lambda>x \<phi>. let a = x - l / 2 * sin \<phi>; b = x + l / 2 * sin \<phi> in min a b + d/2 \<le> 0 \<and> max a b + d/2 \<ge> 0 \<or> min a b - d/2 \<le> 0 \<and> max a b - d/2 \<ge> 0" show "?P x \<phi> \<longleftrightarrow> (d / 2 - \<bar>sin \<phi>\<bar> * l / 2 \<le> \<bar>x\<bar>)" proof (cases "\<phi> \<ge> 0") case True have "x - l / 2 * sin \<phi> \<le> x + l / 2 * sin \<phi>" using l True * by (auto simp: sin_ge_zero) moreover from True and * have "sin \<phi> \<ge> 0" by (auto simp: sin_ge_zero) ultimately show ?thesis using * True by (force simp: field_simps Let_def min_def max_def case_prod_unfold abs_if) next case False with * have "x - l / 2 * sin \<phi> \<ge> x + l / 2 * sin \<phi>" using l by (auto simp: sin_le_zero' mult_nonneg_nonpos) moreover from False and * have "sin \<phi> \<le> 0" by (auto simp: sin_le_zero') ultimately show ?thesis using * False l d by (force simp: field_simps Let_def min_def max_def case_prod_unfold abs_if) qed qed text \<open> By using the symmetry inherent in the problem, we can reduce the problem to the following set, which corresponds to one quadrant of the original set: \<close> definition Buffon_set' :: "(real \<times> real) set" where "Buffon_set' = {(x,\<phi>) \<in> {0..d/2} \<times> {0..pi}. x \<ge> d / 2 - sin \<phi> * l / 2}" lemma closed_buffon_set [simp, intro, measurable]: "closed Buffon_set" proof - have "Buffon_set = ({-d/2..d/2} \<times> {-pi..pi}) \<inter> (\<lambda>z. abs (fst z) + abs (sin (snd z)) * l / 2 - d / 2) -` {0..}" (is "_ = ?A") unfolding Buffon_set_altdef2 by auto also have "closed \<dots>" by (intro closed_Int closed_vimage closed_Times) (auto intro!: continuous_intros) finally show ?thesis by simp qed lemma closed_buffon_set' [simp, intro, measurable]: "closed Buffon_set'" proof - have "Buffon_set' = ({0..d/2} \<times> {0..pi}) \<inter> (\<lambda>z. fst z + sin (snd z) * l / 2 - d / 2) -` {0..}" (is "_ = ?A") unfolding Buffon_set'_def by auto also have "closed \<dots>" by (intro closed_Int closed_vimage closed_Times) (auto intro!: continuous_intros) finally show ?thesis by simp qed lemma measurable_buffon_set [measurable]: "Buffon_set \<in> sets borel" by measurable lemma measurable_buffon_set' [measurable]: "Buffon_set' \<in> sets borel" by measurable sublocale prob_space Buffon unfolding Buffon_def proof - have "emeasure lborel ({- d / 2..d / 2} \<times> {- pi..pi}) = ennreal (2 * d * pi)" unfolding lborel_prod [symmetric] using d by (subst lborel.emeasure_pair_measure_Times) (auto simp: ennreal_mult mult_ac simp flip: ennreal_numeral) also have "\<dots> \<noteq> 0 \<and> \<dots> \<noteq> \<infinity>" using d by auto finally show "prob_space (uniform_measure lborel ({- d / 2..d / 2} \<times> {- pi..pi}))" by (intro prob_space_uniform_measure) auto qed lemma buffon_prob_aux: "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} = emeasure lborel Buffon_set / ennreal (2 * d * pi)" proof - have [measurable]: "A \<times> B \<in> sets borel" if "A \<in> sets borel" "B \<in> sets borel" for A B :: "real set" using that unfolding borel_prod [symmetric] by simp have "{(x, \<phi>). needle l x \<phi> \<inter> {- d / 2, d / 2} \<noteq> {}} \<in> sets borel" by (intro pred_Collect_borel) (simp add: borel_prod [symmetric] needle_def closed_segment_eq_real_ivl case_prod_unfold) hence "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} = emeasure lborel (({-d/2..d/2} \<times> {- pi..pi}) \<inter> {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}}) / emeasure lborel ({-(d/2)..d/2} \<times> {-pi..pi})" unfolding Buffon_def Buffon_set_def by (subst emeasure_uniform_measure) simp_all also have "({-d/2..d/2} \<times> {- pi..pi}) \<inter> {(x, \<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} = Buffon_set" unfolding Buffon_set_def by auto also have "emeasure lborel ({-(d/2)..d/2} \<times> {-pi..pi}) = ennreal (2 * d * pi)" using d by (simp flip: lborel_prod ennreal_mult add: lborel.emeasure_pair_measure_Times) finally show ?thesis . qed lemma emeasure_buffon_set_conv_buffon_set': "emeasure lborel Buffon_set = 4 * emeasure lborel Buffon_set'" proof - have distr_lborel [simp]: "distr M lborel f = distr M borel f" for M and f :: "real \<Rightarrow> real" by (rule distr_cong) simp_all define A where "A = Buffon_set'" define B C D where "B = (\<lambda>x. (-fst x, snd x)) -` A" and "C = (\<lambda>x. (fst x, -snd x)) -` A" and "D = (\<lambda>x. (-fst x, -snd x)) -` A" have meas [measurable]: "(\<lambda>x::real \<times> real. (-fst x, snd x)) \<in> borel_measurable borel" "(\<lambda>x::real \<times> real. (fst x, -snd x)) \<in> borel_measurable borel" "(\<lambda>x::real \<times> real. (-fst x, -snd x)) \<in> borel_measurable borel" unfolding borel_prod [symmetric] by measurable have meas' [measurable]: "A \<in> sets borel" "B \<in> sets borel" "C \<in> sets borel" "D \<in> sets borel" unfolding A_def B_def C_def D_def by (rule measurable_buffon_set' measurable_sets_borel meas)+ have *: "Buffon_set = A \<union> B \<union> C \<union> D" proof (intro equalityI subsetI, goal_cases) case (1 z) show ?case proof (cases "fst z \<ge> 0"; cases "snd z \<ge> 0") assume "fst z \<ge> 0" "snd z \<ge> 0" with 1 have "z \<in> A" by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_ge_zero A_def B_def) thus ?thesis by blast next assume "\<not>(fst z \<ge> 0)" "snd z \<ge> 0" with 1 have "z \<in> B" by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_ge_zero A_def B_def) thus ?thesis by blast next assume "fst z \<ge> 0" "\<not>(snd z \<ge> 0)" with 1 have "z \<in> C" by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_le_zero' A_def B_def C_def) thus ?thesis by blast next assume "\<not>(fst z \<ge> 0)" "\<not>(snd z \<ge> 0)" with 1 have "z \<in> D" by (auto split: prod.splits simp: Buffon_set_altdef2 Buffon_set'_def sin_le_zero' A_def B_def D_def) thus ?thesis by blast qed next case (2 z) thus ?case using d l by (auto simp: Buffon_set_altdef2 Buffon_set'_def sin_ge_zero sin_le_zero' A_def B_def C_def D_def) qed have "A \<inter> B = {0} \<times> ({0..pi} \<inter> {\<phi>. sin \<phi> * l - d \<ge> 0})" using d l by (auto simp: Buffon_set'_def A_def B_def C_def D_def) moreover have "emeasure lborel \<dots> = 0" unfolding lborel_prod [symmetric] by (subst lborel.emeasure_pair_measure_Times) simp_all ultimately have AB: "(A \<inter> B) \<in> null_sets lborel" unfolding lborel_prod [symmetric] by (simp add: null_sets_def) have "C \<inter> D = {0} \<times> ({-pi..0} \<inter> {\<phi>. -sin \<phi> * l - d \<ge> 0})" using d l by (auto simp: Buffon_set'_def A_def B_def C_def D_def) moreover have "emeasure lborel \<dots> = 0" unfolding lborel_prod [symmetric] by (subst lborel.emeasure_pair_measure_Times) simp_all ultimately have CD: "(C \<inter> D) \<in> null_sets lborel" unfolding lborel_prod [symmetric] by (simp add: null_sets_def) have "A \<inter> D = {}" "B \<inter> C = {}" using d l by (auto simp: Buffon_set'_def A_def D_def B_def C_def) moreover have "A \<inter> C = {(d/2, 0)}" "B \<inter> D = {(-d/2, 0)}" using d l by (auto simp: case_prod_unfold Buffon_set'_def A_def B_def C_def D_def) ultimately have AD: "A \<inter> D \<in> null_sets lborel" and BC: "B \<inter> C \<in> null_sets lborel" and AC: "A \<inter> C \<in> null_sets lborel" and BD: "B \<inter> D \<in> null_sets lborel" by auto note * also have "emeasure lborel (A \<union> B \<union> C \<union> D) = emeasure lborel (A \<union> B \<union> C) + emeasure lborel D" using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2) also have "emeasure lborel (A \<union> B \<union> C) = emeasure lborel (A \<union> B) + emeasure lborel C" using AB AC BC using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2) also have "emeasure lborel (A \<union> B) = emeasure lborel A + emeasure lborel B" using AB using AB AC AD BC BD CD by (intro emeasure_Un') (auto simp: Int_Un_distrib2) also have "emeasure lborel B = emeasure (distr lborel lborel (\<lambda>(x,y). (-x, y))) A" (is "_ = emeasure ?M _") unfolding B_def by (subst emeasure_distr) (simp_all add: case_prod_unfold) also have "?M = lborel" unfolding lborel_prod [symmetric] by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus) also have "emeasure lborel C = emeasure (distr lborel lborel (\<lambda>(x,y). (x, -y))) A" (is "_ = emeasure ?M _") unfolding C_def by (subst emeasure_distr) (simp_all add: case_prod_unfold) also have "?M = lborel" unfolding lborel_prod [symmetric] by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus) also have "emeasure lborel D = emeasure (distr lborel lborel (\<lambda>(x,y). (-x, -y))) A" (is "_ = emeasure ?M _") unfolding D_def by (subst emeasure_distr) (simp_all add: case_prod_unfold) also have "?M = lborel" unfolding lborel_prod [symmetric] by (subst pair_measure_distr [symmetric]) (simp_all add: sigma_finite_lborel lborel_distr_uminus) finally have "emeasure lborel Buffon_set = of_nat (Suc (Suc (Suc (Suc 0)))) * emeasure lborel A" unfolding of_nat_Suc ring_distribs by simp also have "of_nat (Suc (Suc (Suc (Suc 0)))) = (4 :: ennreal)" by simp finally show ?thesis unfolding A_def . qed text \<open> It only remains now to compute the measure of @{const Buffon_set'}. We first reduce this problem to a relatively simple integral: \<close> lemma emeasure_buffon_set': "emeasure lborel Buffon_set' = ennreal (integral {0..pi} (\<lambda>x. min (d / 2) (sin x * l / 2)))" (is "emeasure lborel ?A = _") proof - have "emeasure lborel ?A = nn_integral lborel (\<lambda>x. indicator ?A x)" by (intro nn_integral_indicator [symmetric]) simp_all also have "(lborel :: (real \<times> real) measure) = lborel \<Otimes>\<^sub>M lborel" by (simp only: lborel_prod) also have "nn_integral \<dots> (indicator ?A) = (\<integral>\<^sup>+\<phi>. \<integral>\<^sup>+x. indicator ?A (x, \<phi>) \<partial>lborel \<partial>lborel)" by (subst lborel_pair.nn_integral_snd [symmetric]) (simp_all add: lborel_prod borel_prod) also have "\<dots> = (\<integral>\<^sup>+\<phi>. \<integral>\<^sup>+x. indicator {0..pi} \<phi> * indicator {max 0 (d/2 - sin \<phi> * l / 2) .. d/2} x \<partial>lborel \<partial>lborel)" using d l by (intro nn_integral_cong) (auto simp: indicator_def field_simps Buffon_set'_def) also have "\<dots> = \<integral>\<^sup>+ \<phi>. indicator {0..pi} \<phi> * emeasure lborel {max 0 (d / 2 - sin \<phi> * l / 2)..d / 2} \<partial>lborel" by (subst nn_integral_cmult) simp_all also have "\<dots> = \<integral>\<^sup>+ \<phi>. ennreal (indicator {0..pi} \<phi> * min (d / 2) (sin \<phi> * l / 2)) \<partial>lborel" (is "_ = ?I") using d l by (intro nn_integral_cong) (auto simp: indicator_def sin_ge_zero max_def min_def) also have "integrable lborel (\<lambda>\<phi>. (d / 2) * indicator {0..pi} \<phi>)" by simp hence int: "integrable lborel (\<lambda>\<phi>. indicator {0..pi} \<phi> * min (d / 2) (sin \<phi> * l / 2))" by (rule Bochner_Integration.integrable_bound) (insert l d, auto intro!: AE_I2 simp: indicator_def min_def sin_ge_zero) hence "?I = set_lebesgue_integral lborel {0..pi} (\<lambda>\<phi>. min (d / 2) (sin \<phi> * l / 2))" by (subst nn_integral_eq_integral, assumption) (insert d l, auto intro!: AE_I2 simp: sin_ge_zero min_def indicator_def set_lebesgue_integral_def) also have "\<dots> = ennreal (integral {0..pi} (\<lambda>x. min (d / 2) (sin x * l / 2)))" (is "_ = ennreal ?I") using int by (subst set_borel_integral_eq_integral) (simp_all add: set_integrable_def) finally show ?thesis by (simp add: lborel_prod) qed text \<open> We now have to distinguish two cases: The first and easier one is that where the length of the needle, $l$, is less than or equal to the strip width, $d$: \<close> context assumes l_le_d: "l \<le> d" begin lemma emeasure_buffon_set'_short: "emeasure lborel Buffon_set' = ennreal l" proof - have "emeasure lborel Buffon_set' = ennreal (integral {0..pi} (\<lambda>x. min (d / 2) (sin x * l / 2)))" (is "_ = ennreal ?I") by (rule emeasure_buffon_set') also have *: "sin \<phi> * l \<le> d" if "\<phi> \<ge> 0" "\<phi> \<le> pi" for \<phi> using mult_mono[OF l_le_d sin_le_one _ sin_ge_zero] that d by (simp add: algebra_simps) have "?I = integral {0..pi} (\<lambda>x. (l / 2) * sin x)" using l d l_le_d by (intro integral_cong) (auto dest: * simp: min_def sin_ge_zero) also have "\<dots> = l / 2 * integral {0..pi} sin" by simp also have "(sin has_integral (-cos pi - (- cos 0))) {0..pi}" by (intro fundamental_theorem_of_calculus) (auto intro!: derivative_eq_intros simp: has_real_derivative_iff_has_vector_derivative [symmetric]) hence "integral {0..pi} sin = -cos pi - (-cos 0)" by (simp add: has_integral_iff) finally show ?thesis by (simp add: lborel_prod) qed lemma emeasure_buffon_set_short: "emeasure lborel Buffon_set = 4 * ennreal l" by (simp add: emeasure_buffon_set_conv_buffon_set' emeasure_buffon_set'_short l_le_d) lemma prob_short_aux: "Buffon {(x, \<phi>). needle l x \<phi> \<inter> {- d / 2, d / 2} \<noteq> {}} = ennreal (2 * l / (d * pi))" unfolding buffon_prob_aux emeasure_buffon_set_short using d l by (simp flip: ennreal_mult ennreal_numeral add: divide_ennreal) lemma prob_short: "\<P>((x,\<phi>) in Buffon. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) = 2 * l / (d * pi)" using prob_short_aux unfolding emeasure_eq_measure using l d by (subst (asm) ennreal_inj) auto end text \<open> The other case where the needle is at least as long as the strip width is more complicated: \<close> context assumes l_ge_d: "l \<ge> d" begin lemma emeasure_buffon_set'_long: shows "l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d \<ge> 0" and "emeasure lborel Buffon_set' = ennreal (l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d)" proof - define \<phi>' where "\<phi>' = arcsin (d / l)" have \<phi>'_nonneg: "\<phi>' \<ge> 0" unfolding \<phi>'_def using d l l_ge_d arcsin_le_mono[of 0 "d/l"] by (simp add: \<phi>'_def) have \<phi>'_le: "\<phi>' \<le> pi / 2" unfolding \<phi>'_def using arcsin_bounded[of "d/l"] d l l_ge_d by (simp add: field_simps) have ge_phi': "sin \<phi> \<ge> d / l" if "\<phi> \<ge> \<phi>'" "\<phi> \<le> pi / 2" for \<phi> using arcsin_le_iff[of "d / l" "\<phi>"] d l_ge_d that \<phi>'_nonneg by (auto simp: \<phi>'_def field_simps) have le_phi': "sin \<phi> \<le> d / l" if "\<phi> \<le> \<phi>'" "\<phi> \<ge> 0" for \<phi> using le_arcsin_iff[of "d / l" "\<phi>"] d l_ge_d that \<phi>'_le by (auto simp: \<phi>'_def field_simps) have "cos \<phi>' = sqrt (1 - (d / l)^2)" unfolding \<phi>'_def by (rule cos_arcsin) (insert d l l_ge_d, auto simp: field_simps) have "l * (1 - cos \<phi>') + arccos (d / l) * d \<ge> 0" using l d l_ge_d by (intro add_nonneg_nonneg mult_nonneg_nonneg arccos_lbound) (auto simp: field_simps) thus "l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d \<ge> 0" by (simp add: \<open>cos \<phi>' = sqrt (1 - (d / l)^2)\<close>) let ?f = "(\<lambda>x. min (d / 2) (sin x * l / 2))" have "emeasure lborel Buffon_set' = ennreal (integral {0..pi} ?f)" (is "_ = ennreal ?I") by (rule emeasure_buffon_set') also have "?I = integral {0..pi/2} ?f + integral {pi/2..pi} ?f" by (rule Henstock_Kurzweil_Integration.integral_combine [symmetric]) (auto intro!: integrable_continuous_real continuous_intros) also have "integral {pi/2..pi} ?f = integral {-pi/2..0} (?f \<circ> (\<lambda>\<phi>. \<phi> + pi))" by (subst integral_shift) (auto intro!: continuous_intros) also have "\<dots> = integral {-(pi/2)..-0} (\<lambda>x. min (d / 2) (sin (-x) * l / 2))" by (simp add: o_def) also have "\<dots> = integral {0..pi/2} ?f" (is "_ = ?I") by (subst Henstock_Kurzweil_Integration.integral_reflect_real) simp_all also have "\<dots> + \<dots> = 2 * \<dots>" by simp also have "?I = integral {0..\<phi>'} ?f + integral {\<phi>'..pi/2} ?f" using l d l_ge_d \<phi>'_nonneg \<phi>'_le by (intro Henstock_Kurzweil_Integration.integral_combine [symmetric]) (auto intro!: integrable_continuous_real continuous_intros) also have "integral {0..\<phi>'} ?f = integral {0..\<phi>'} (\<lambda>x. l / 2 * sin x)" using l by (intro integral_cong) (auto simp: min_def field_simps dest: le_phi') also have "((\<lambda>x. l / 2 * sin x) has_integral (- (l / 2 * cos \<phi>') - (- (l / 2 * cos 0)))) {0..\<phi>'}" using \<phi>'_nonneg by (intro fundamental_theorem_of_calculus) (auto simp: has_real_derivative_iff_has_vector_derivative [symmetric] intro!: derivative_eq_intros) hence "integral {0..\<phi>'} (\<lambda>x. l / 2 * sin x) = (1 - cos \<phi>') * l / 2" by (simp add: has_integral_iff algebra_simps) also have "integral {\<phi>'..pi/2} ?f = integral {\<phi>'..pi/2} (\<lambda>_. d / 2)" using l by (intro integral_cong) (auto simp: min_def field_simps dest: ge_phi') also have "\<dots> = arccos (d / l) * d / 2" using \<phi>'_le d l l_ge_d by (subst arccos_arcsin_eq) (auto simp: field_simps \<phi>'_def) also note \<open>cos \<phi>' = sqrt (1 - (d / l)^2)\<close> also have "2 * ((1 - sqrt (1 - (d / l)\<^sup>2)) * l / 2 + arccos (d / l) * d / 2) = l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d" using d l by (simp add: field_simps) finally show "emeasure lborel Buffon_set' = ennreal (l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d)" . qed lemma emeasure_set_long: "emeasure lborel Buffon_set = 4 * ennreal (l * (1 - sqrt (1 - (d / l)\<^sup>2)) + arccos (d / l) * d)" by (simp add: emeasure_buffon_set_conv_buffon_set' emeasure_buffon_set'_long l_ge_d) lemma prob_long_aux: shows "2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)) \<ge> 0" and "Buffon {(x, \<phi>). needle l x \<phi> \<inter> {- d / 2, d / 2} \<noteq> {}} = ennreal (2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)))" using emeasure_buffon_set'_long(1) proof - have *: "l * sqrt ((l\<^sup>2 - d\<^sup>2) / l\<^sup>2) + 0 \<le> l + d * arccos (d / l)" using d l_ge_d by (intro add_mono mult_nonneg_nonneg arccos_lbound) (auto simp: field_simps) have "l / d \<ge> sqrt ((l / d)\<^sup>2 - 1)" using l d l_ge_d by (intro real_le_lsqrt) (auto simp: field_simps) thus "2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)) \<ge> 0" using d l l_ge_d by (intro mult_nonneg_nonneg add_nonneg_nonneg arccos_lbound) (auto simp: field_simps) have "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} = ennreal (4 * (l - l * sqrt (1 - (d / l)\<^sup>2) + arccos (d / l) * d)) / ennreal (2 * d * pi)" using d l l_ge_d * unfolding buffon_prob_aux emeasure_set_long ennreal_numeral [symmetric] by (subst ennreal_mult [symmetric]) (auto intro!: add_nonneg_nonneg mult_nonneg_nonneg simp: field_simps) also have "\<dots> = ennreal ((4 * (l - l * sqrt (1 - (d / l)\<^sup>2) + arccos (d / l) * d)) / (2 * d * pi))" using d l * by (subst divide_ennreal) (auto simp: field_simps) also have "(4 * (l - l * sqrt (1 - (d / l)\<^sup>2) + arccos (d / l) * d)) / (2 * d * pi) = 2 / pi * (l / d - l / d * sqrt ((d / l)^2 * ((l / d)^2 - 1)) + arccos (d / l))" using d l by (simp add: field_simps) also have "l / d * sqrt ((d / l)^2 * ((l / d)^2 - 1)) = sqrt ((l / d) ^ 2 - 1)" using d l l_ge_d unfolding real_sqrt_mult real_sqrt_abs by simp finally show "emeasure Buffon {(x,\<phi>). needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}} = ennreal (2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l)))" . qed lemma prob_long: "\<P>((x,\<phi>) in Buffon. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) = 2 / pi * ((l / d) - sqrt ((l / d)\<^sup>2 - 1) + arccos (d / l))" using prob_long_aux unfolding emeasure_eq_measure by (subst (asm) ennreal_inj) simp_all end theorem prob_eq: defines "x \<equiv> l / d" shows "\<P>((x,\<phi>) in Buffon. needle l x \<phi> \<inter> {-d/2, d/2} \<noteq> {}) = (if l \<le> d then 2 / pi * x else 2 / pi * (x - sqrt (x\<^sup>2 - 1) + arccos (1 / x)))" using prob_short prob_long unfolding x_def by auto end end
A function has a trivial limit at $a$ within $S$ if and only if $a$ is not a limit point of $S$.
include("lib_for_practic_10.jl") #r = Robot() #r = BorderRobot{CoordRobot}(r) #show!(r.robot) function movements_mark!(r,side::HorizonSide) while (isborder(r,side) == false) && (ismarker(r) == false) putmarker!(r) move!(r,side) end end function kvadro!(r) count = movements!(r,Ost) for side in [Sud, West, Nord, Ost, Sud] movements_mark!(r.robot,side) end movements!(r, West, count) end kvadro!(r) show(r.robot)
theory prop_08 imports Main "$HIPSTER_HOME/IsaHipster" begin datatype Nat = Z | S "Nat" fun plus :: "Nat => Nat => Nat" where "plus (Z) y = y" | "plus (S z) y = S (plus z y)" fun minus :: "Nat => Nat => Nat" where "minus (Z) y = Z" | "minus (S z) (Z) = S z" | "minus (S z) (S x2) = minus z x2" (*hipster plus minus *) theorem x0 : "(minus (plus k m) (plus k n)) = (minus m n)" by (tactic \<open>Subgoal.FOCUS_PARAMS (K (Tactic_Data.hard_tac @{context})) @{context} 1\<close>) end
/- Copyright (c) 2020 Ruben Van de Velde. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. -/ import tactic.interval_cases import .primes import .edwards /-! # Fermat's Last Theorem for the case n = 3 There are no non-zero integers `a`, `b` and `c` such that `a ^ 3 + b ^ 3 = c ^ 3`. This follows the proof by Euler as presented by H. M. Edwards in *Fermat's Last Theorem: A Genetic Introduction to Algebraic Number Theory*, pp. 39-54. -/ /-- solutions to Fermat's last theorem for the exponent `3`. -/ def flt_solution (n : ℕ) (a b c : ℤ) := a ≠ 0 ∧ b ≠ 0 ∧ c ≠ 0 ∧ a ^ n + b ^ n = c ^ n /-- Coprime solutions to Fermat's last theorem for the exponent `3`. -/ def flt_coprime (n : ℕ) (a b c : ℤ) := flt_solution n a b c ∧ is_coprime a b ∧ is_coprime a c ∧ is_coprime b c lemma exists_coprime {n : ℕ} (hn : 0 < n) {a b c : ℤ} (ha' : a ≠ 0) (hb' : b ≠ 0) (hc' : c ≠ 0) (h : a ^ n + b ^ n = c ^ n) : ∃ a' b' c' : ℤ, a'.nat_abs ≤ a.nat_abs ∧ b'.nat_abs ≤ b.nat_abs ∧ c'.nat_abs ≤ c.nat_abs ∧ flt_coprime n a' b' c' := begin set d := int.gcd a b with hd', obtain ⟨A, HA⟩ : ↑d ∣ a := int.gcd_dvd_left a b, obtain ⟨B, HB⟩ : ↑d ∣ b := int.gcd_dvd_right a b, obtain ⟨C, HC⟩ : ↑d ∣ c, { rw [←int.pow_dvd_pow_iff hn, ←h, HA, HB, mul_pow, mul_pow, ←mul_add], exact dvd_mul_right (↑d ^ n) (A ^ n + B ^ n) }, have hdpos : 0 < d := int.gcd_pos_of_non_zero_left _ ha', have hd := int.coe_nat_ne_zero_iff_pos.mpr hdpos, have hsoln : A ^ n + B ^ n = C ^ n, { apply int.eq_of_mul_eq_mul_left (pow_ne_zero n hd), simp only [mul_add, ←mul_pow, ←HA, ←HB, ←HC, h] }, have hsoln' : B ^ n + A ^ n = C ^ n, { rwa add_comm at hsoln }, have hcoprime : is_coprime A B, { rw ←int.gcd_eq_one_iff_coprime, apply nat.eq_of_mul_eq_mul_left hdpos, rw [←int.nat_abs_of_nat d, ←int.gcd_mul_left, ←HA, ←HB, hd', int.nat_abs_of_nat, mul_one] }, have HA' : A.nat_abs ≤ a.nat_abs, { rw HA, simp only [int.nat_abs_of_nat, int.nat_abs_mul], exact le_mul_of_one_le_left' (nat.succ_le_iff.mpr hdpos) }, have HB' : B.nat_abs ≤ b.nat_abs, { rw HB, simp only [int.nat_abs_of_nat, int.nat_abs_mul], exact le_mul_of_one_le_left' (nat.succ_le_iff.mpr hdpos) }, have HC' : C.nat_abs ≤ c.nat_abs, { rw HC, simp only [int.nat_abs_of_nat, int.nat_abs_mul], exact le_mul_of_one_le_left' (nat.succ_le_iff.mpr hdpos) }, exact ⟨ A, B, C, HA', HB', HC', ⟨ right_ne_zero_of_mul (by rwa HA at ha'), right_ne_zero_of_mul (by rwa HB at hb'), right_ne_zero_of_mul (by rwa HC at hc'), hsoln ⟩, hcoprime, coprime_add_self_pow hn hsoln hcoprime, coprime_add_self_pow hn hsoln' hcoprime.symm ⟩, end lemma descent1a {a b c : ℤ} (h : a ^ 3 + b ^ 3 = c ^ 3) (habcoprime : is_coprime a b) (haccoprime : is_coprime a c) (hbccoprime : is_coprime b c) : (even a ∧ ¬even b ∧ ¬even c ∨ ¬even a ∧ even b ∧ ¬even c) ∨ ¬even a ∧ ¬even b ∧ even c := begin have contra : ∀ {x y : ℤ}, is_coprime x y → even x → even y → false, { intros x y hcoprime hx hy, rw even_iff_two_dvd at hx hy, have := int.is_unit_eq_one_or (hcoprime.is_unit_of_dvd' hx hy), norm_num at this }, by_cases haparity : even a; by_cases hbparity : even b; by_cases hcparity : even c, { exact false.elim (contra habcoprime ‹_› ‹_›) }, { exact false.elim (contra habcoprime ‹_› ‹_›) }, { exact false.elim (contra haccoprime ‹_› ‹_›) }, { tauto }, { exact false.elim (contra hbccoprime ‹_› ‹_›) }, { tauto }, { tauto }, { exfalso, apply hcparity, rw [←int.even_pow' three_ne_zero, ←h], simp [haparity, hbparity, three_ne_zero] with parity_simps }, end lemma flt_not_add_self {a b c : ℤ} (ha : a ≠ 0) (h : a ^ 3 + b ^ 3 = c ^ 3) : a ≠ b := begin rintro rfl, rw ←mul_two at h, obtain ⟨d, rfl⟩ : a ∣ c, { rw [←int.pow_dvd_pow_iff (by norm_num : 0 < 3), ←h], apply dvd_mul_right }, apply int.two_not_cube d, rwa [mul_pow, mul_right_inj' (pow_ne_zero 3 ha), eq_comm] at h, end lemma descent1left {a b c : ℤ} (hapos : a ≠ 0) (h : a ^ 3 + b ^ 3 = c ^ 3) (hbccoprime : is_coprime b c) (hb : ¬even b) (hc : ¬even c) : ∃ (p q : ℤ), p ≠ 0 ∧ q ≠ 0 ∧ is_coprime p q ∧ (even p ↔ ¬even q) ∧ 2 * p * (p ^ 2 + 3 * q ^ 2) = a ^ 3 := begin obtain ⟨p, hp⟩ : even (c - b), { simp [hb, hc] with parity_simps}, obtain ⟨q, hq⟩ : even (c + b), { simp [hb, hc] with parity_simps}, rw ←two_mul at hp hq, obtain rfl : p + q = c, { apply int.eq_of_mul_eq_mul_left two_ne_zero, rw [mul_add, ←hp, ←hq], ring }, obtain rfl : q - p = b, { apply int.eq_of_mul_eq_mul_left two_ne_zero, rw [mul_sub, ←hp, ←hq], ring }, have hpnezero : p ≠ 0, { rintro rfl, rw [sub_zero, zero_add, add_left_eq_self] at h, exact hapos (pow_eq_zero h) }, have hqnezero : q ≠ 0, { rintro rfl, rw [zero_sub, add_zero, neg_pow_bit1, ←sub_eq_add_neg, sub_eq_iff_eq_add] at h, exact flt_not_add_self hpnezero h.symm rfl }, refine ⟨p, q, hpnezero, hqnezero, _, _, _⟩, { apply is_coprime_of_dvd _ _ (not_and_of_not_left _ hpnezero), intros z hznu hznz hzp hzq, apply hznu, exact hbccoprime.is_unit_of_dvd' (dvd_sub hzq hzp) (dvd_add hzp hzq) }, { split; intro H; simpa [H] with parity_simps using hc }, { rw [eq_sub_of_add_eq h], ring }, end lemma descent1 (a b c : ℤ) (h : flt_coprime 3 a b c) : ∃ (p q : ℤ), p ≠ 0 ∧ q ≠ 0 ∧ is_coprime p q ∧ (even p ↔ ¬even q) ∧ (2 * p * (p ^ 2 + 3 * q ^ 2) = a ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = b ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = c ^ 3) := begin obtain ⟨⟨hapos, hbpos, hcpos, h⟩, habcoprime, haccoprime, hbccoprime⟩ := h, obtain (⟨ha, hb, hc⟩|⟨ha, hb, hc⟩)|⟨ha, hb, hc⟩ := descent1a h habcoprime haccoprime hbccoprime, { obtain ⟨p, q, hp, hq, hcoprime, hodd, hcube⟩ := descent1left hapos h hbccoprime hb hc, exact ⟨p, q, hp, hq, hcoprime, hodd, or.inl hcube⟩ }, { rw add_comm at h, obtain ⟨p, q, hp, hq, hcoprime, hodd, hcube⟩ := descent1left hbpos h haccoprime ha hc, refine ⟨p, q, hp, hq, hcoprime, hodd, or.inr $ or.inl hcube⟩ }, { obtain ⟨p, q, hp, hq, hcoprime, hodd, hcube⟩ := descent1left hcpos _ habcoprime.neg_left _ hb, exact ⟨p, q, hp, hq, hcoprime, hodd, or.inr $ or.inr hcube⟩, { rw ←h, ring }, { simp [ha] with parity_simps } }, end lemma descent11 {a b c d : ℤ} (h : d = a ∨ d = b ∨ d = c) : d ∣ (a * b * c) := begin rcases h with rfl | rfl | rfl, { exact (dvd_mul_right _ _).mul_right _ }, { exact (dvd_mul_left _ _).mul_right _ }, { exact dvd_mul_left _ _ } end lemma descent2 (a b c : ℤ) (h : flt_coprime 3 a b c) : ∃ (p q : ℤ), p ≠ 0 ∧ q ≠ 0 ∧ is_coprime p q ∧ (even p ↔ ¬even q) ∧ (2 * p * (p ^ 2 + 3 * q ^ 2) = a ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = b ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = c ^ 3) ∧ ((2 * p).nat_abs < (a ^ 3 * b ^ 3 * c ^ 3).nat_abs) := begin obtain ⟨p, q, hp, hq, hcoprime, hodd, hcube⟩ := descent1 a b c h, refine ⟨p, q, hp, hq, hcoprime, hodd, hcube, _⟩, obtain ⟨⟨hapos, hbpos, hcpos, h⟩, -⟩ := h, set P : ℤ√-3 := ⟨p, q⟩, calc (2 * p).nat_abs < (2 * p * P.norm).nat_abs : _ ... ≤ (a ^ 3 * b ^ 3 * c ^ 3).nat_abs : _, { rw [int.nat_abs_mul (2 * p)], apply lt_mul_of_one_lt_right (int.nat_abs_pos_of_ne_zero (mul_ne_zero two_ne_zero hp)), rw [← int.coe_nat_lt_coe_nat_iff], rw int.nat_abs_of_nonneg (zsqrtd.norm_nonneg (by norm_num) P), exact spts.one_lt_of_im_ne_zero ⟨p, q⟩ hq }, { apply nat.le_of_dvd, { rw [pos_iff_ne_zero, int.nat_abs_ne_zero, ←mul_pow, ←mul_pow], exact pow_ne_zero 3 (mul_ne_zero (mul_ne_zero hapos hbpos) hcpos) }, { rw int.nat_abs_dvd_iff_dvd, convert descent11 hcube, rw [zsqrtd.norm], ring } } end lemma gcd1or3 (p q : ℤ) (hp : p ≠ 0) (hcoprime : is_coprime p q) (hparity : even p ↔ ¬even q) : int.gcd (2 * p) (p ^ 2 + 3 * q ^ 2) = 1 ∨ int.gcd (2 * p) (p ^ 2 + 3 * q ^ 2) = 3 := begin set g := int.gcd (2 * p) (p ^ 2 + 3 * q ^ 2) with hg', suffices H : ∃ k, g = 3 ^ k ∧ k < 2, { obtain ⟨k, hg, hk⟩ := H, interval_cases k, { left, rw pow_zero at hg, exact hg }, { right, rw pow_one at hg, exact hg } }, have basic : ∀ f, nat.prime f → (f : ℤ) ∣ 2 * p → (f : ℤ) ∣ (p ^ 2 + 3 * q ^ 2) → f = 3, { intros d hdprime hdleft hdright, by_contra hne3, rw ←ne.def at hne3, apply (nat.prime_iff_prime_int.mp hdprime).not_unit, have hne2 : d ≠ 2, { rintro rfl, rw [int.coe_nat_bit0, int.coe_nat_one, ←even_iff_two_dvd] at hdright, simpa [hparity, two_ne_zero] with parity_simps using hdright }, have : 2 < d := lt_of_le_of_ne (hdprime.two_le) hne2.symm, have : 3 < d := lt_of_le_of_ne (this) hne3.symm, obtain ⟨P, hP⟩ := hdleft, obtain ⟨Q, hQ⟩ := hdright, obtain ⟨H, hH⟩ : 2 ∣ P, { have H := dvd_mul_right 2 p, rw [hP] at H, apply (prime.dvd_or_dvd int.prime_two H).resolve_left, rw int.coe_nat_dvd_right, change ¬(2 ∣ d), rw nat.prime_dvd_prime_iff_eq nat.prime_two hdprime, exact hne2.symm }, have hp : p = d * H, { rw [←mul_right_inj' (two_ne_zero' ℤ), hP, hH, mul_left_comm] }, apply hcoprime.is_unit_of_dvd', { rw hp, exact dvd_mul_right d H }, { have h000 : d ∣ 3 * q.nat_abs ^ 2, { rw [←int.coe_nat_dvd, int.coe_nat_mul, int.coe_nat_pow, int.nat_abs_sq, int.coe_nat_bit1, int.coe_nat_one], use (Q - d * H ^ 2), rw [mul_sub, ←hQ, hp], ring }, cases (nat.prime.dvd_mul hdprime).mp h000 with h000 h000, { rw nat.prime_dvd_prime_iff_eq hdprime nat.prime_three at h000, exact absurd h000 hne3 }, { rw int.coe_nat_dvd_left, exact nat.prime.dvd_of_dvd_pow hdprime h000 } } }, set k := g.factors.length, have hg : g = 3 ^ k, { apply nat.eq_prime_pow_of_unique_prime_dvd, { apply ne_of_gt, apply nat.gcd_pos_of_pos_left, rw int.nat_abs_mul, apply nat.mul_pos zero_lt_two, rwa [pos_iff_ne_zero, int.nat_abs_ne_zero], }, intros d hdprime hddvdg, rw ←int.coe_nat_dvd at hddvdg, apply basic _ hdprime; apply dvd_trans hddvdg; rw hg', exacts [int.gcd_dvd_left _ _, int.gcd_dvd_right _ _] }, refine ⟨k, hg, _⟩, by_contra' H, rw ←pow_mul_pow_sub _ H at hg, have : ¬is_unit (3 : ℤ), { rw int.is_unit_iff_nat_abs_eq, norm_num }, apply this, have hdvdp : 3 ∣ p, { suffices : 3 ∣ 2 * p, { apply int.dvd_mul_cancel_prime' _ dvd_rfl int.prime_two this, norm_num, }, have : 3 ∣ (g : ℤ), { rw [hg, pow_two, mul_assoc, int.coe_nat_mul], apply dvd_mul_right }, exact dvd_trans this (int.gcd_dvd_left _ _) }, apply is_coprime.is_unit_of_dvd' hcoprime hdvdp, { rw ←int.pow_dvd_pow_iff zero_lt_two at hdvdp, apply prime.dvd_of_dvd_pow int.prime_three, rw [←mul_dvd_mul_iff_left (three_ne_zero' ℤ), ←pow_two, dvd_add_iff_right hdvdp], refine dvd_trans _ (int.gcd_dvd_right (2 * p) (p ^ 2 + 3 * q ^ 2)), rw [←hg', hg, int.coe_nat_mul], apply dvd_mul_right } end lemma obscure' (p q : ℤ) (hp : p ≠ 0) (hcoprime : is_coprime p q) (hparity : even p ↔ ¬even q) (hcube : ∃ r, p ^ 2 + 3 * q ^ 2 = r ^ 3) : ∃ a b, p = a * (a - 3 * b) * (a + 3 * b) ∧ q = 3 * b * (a - b) * (a + b) ∧ is_coprime a b ∧ (even a ↔ ¬even b) := begin obtain ⟨u, hu⟩ := hcube, obtain ⟨a, b, hp', hq'⟩ := step6 p q u hcoprime hu.symm, refine ⟨a, b, _, _, _, _⟩, { rw hp', ring }, { rw hq', ring }, { apply is_coprime_of_dvd, { rintro ⟨rfl, rfl⟩, norm_num at hp' }, intros k hknu hknezero hkdvdleft hkdvdright, apply hknu, apply hcoprime.is_unit_of_dvd', { rw hp', apply dvd_sub, { exact dvd_pow hkdvdleft (by norm_num) }, { rw [mul_comm (9 : ℤ), mul_assoc], exact hkdvdleft.mul_right _ } }, { rw hq', apply dvd_sub, { exact hkdvdright.mul_left _ }, { exact (hkdvdright.pow (by norm_num)).mul_left _ } } }, { by_cases haparity : even a; by_cases hbparity : even b; [skip, tauto, tauto, skip]; { exfalso, have : even p, { rw [hp'], simp [haparity, hbparity, three_ne_zero] with parity_simps }, have : even q, { rw [hq'], simp [haparity, hbparity, three_ne_zero] with parity_simps }, tauto } } end lemma int.cube_of_coprime (a b c s : ℤ) (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) (hcoprimeab : is_coprime a b) (hcoprimeac : is_coprime a c) (hcoprimebc : is_coprime b c) (hs : a * b * c = s ^ 3) : ∃ A B C, A ≠ 0 ∧ B ≠ 0 ∧ C ≠ 0 ∧ a = A ^ 3 ∧ b = B ^ 3 ∧ c = C ^ 3 := begin obtain ⟨⟨AB, HAB⟩, ⟨C, HC⟩⟩ := int.eq_pow_of_mul_eq_pow_bit1 (is_coprime.mul_left hcoprimeac hcoprimebc) hs, obtain ⟨⟨A, HA⟩, ⟨B, HB⟩⟩ := int.eq_pow_of_mul_eq_pow_bit1 hcoprimeab HAB, refine ⟨A, B, C, _, _, _, HA, HB, HC⟩; apply ne_zero_pow three_ne_zero, { rwa [←HA] }, { rwa [←HB] }, { rwa [←HC] }, end lemma int.gcd1_coprime12 (u v : ℤ) (huvcoprime : is_coprime u v) (notdvd_2_2 : ¬2 ∣ u - 3 * v) (not_3_dvd_2 : ¬3 ∣ u - 3 * v) : is_coprime (2 * u) (u - 3 * v) := begin apply is_coprime_of_prime_dvd, { rintro ⟨-, h2⟩, norm_num [h2] at notdvd_2_2 }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, apply huvcoprime.is_unit_of_dvd', { exact int.dvd_mul_cancel_prime' notdvd_2_2 hkdvdright int.prime_two hkdvdleft }, { apply int.dvd_mul_cancel_prime' not_3_dvd_2 hkdvdright int.prime_three, apply int.dvd_mul_cancel_prime' notdvd_2_2 hkdvdright int.prime_two, convert dvd_sub hkdvdleft (hkdvdright.mul_left 2), ring }, end lemma int.gcd1_coprime13 (u v : ℤ) (huvcoprime : is_coprime u v) (this : ¬even (u + 3 * v)) (notdvd_3_3 : ¬3 ∣ u + 3 * v) : is_coprime (2 * u) (u + 3 * v) := begin rw even_iff_two_dvd at this, apply is_coprime_of_prime_dvd, { rintro ⟨-, h2⟩, norm_num [h2] at this }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, apply huvcoprime.is_unit_of_dvd', { exact int.dvd_mul_cancel_prime' this hkdvdright int.prime_two hkdvdleft }, { apply int.dvd_mul_cancel_prime' notdvd_3_3 hkdvdright int.prime_three, apply int.dvd_mul_cancel_prime' this hkdvdright int.prime_two, convert dvd_sub (hkdvdright.mul_left 2) hkdvdleft, ring }, end lemma int.gcd1_coprime23 (u v : ℤ) (huvcoprime : is_coprime u v) (notdvd_2_2 : ¬2 ∣ u - 3 * v) (notdvd_3_3 : ¬3 ∣ u + 3 * v) : is_coprime (u - 3 * v) (u + 3 * v) := begin apply is_coprime_of_prime_dvd, { rintro ⟨h1, -⟩, norm_num [h1] at notdvd_2_2 }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, apply huvcoprime.is_unit_of_dvd', { apply int.dvd_mul_cancel_prime' notdvd_2_2 hkdvdleft int.prime_two, convert dvd_add hkdvdleft hkdvdright, ring }, { apply int.dvd_mul_cancel_prime' notdvd_3_3 hkdvdright int.prime_three, apply int.dvd_mul_cancel_prime' notdvd_2_2 hkdvdleft int.prime_two, convert dvd_sub hkdvdright hkdvdleft, ring }, end lemma descent_gcd1 (a b c p q : ℤ) (hp : p ≠ 0) (hcoprime : is_coprime p q) (hodd : even p ↔ ¬even q) (hcube : 2 * p * (p ^ 2 + 3 * q ^ 2) = a ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = b ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = c ^ 3) (h : flt_coprime 3 a b c) (hgcd : is_coprime (2 * p) (p ^ 2 + 3 * q ^ 2)) : ∃ (a' b' c' : ℤ), a' ≠ 0 ∧ b' ≠ 0 ∧ c' ≠ 0 ∧ (a' ^ 3 * b' ^ 3 * c' ^ 3).nat_abs ≤ (2 * p).nat_abs ∧ a' ^ 3 + b' ^ 3 = c' ^ 3 := begin -- 2. have h' := h, obtain ⟨⟨hapos, hbpos, hcpos, h⟩, habcoprime, haccoprime, hbccoprime⟩ := h, -- 5. obtain ⟨r, hr⟩ : ∃ r, 2 * p * (p ^ 2 + 3 * q ^ 2) = r ^ 3, { rcases hcube with (_|_|_); [use a, use b, use c]; exact hcube }, obtain ⟨hcubeleft, hcuberight⟩ := int.eq_pow_of_mul_eq_pow_bit1 hgcd hr, -- todo shadowing hq obtain ⟨u, v, hpfactor, hq, huvcoprime, huvodd⟩ := obscure' p q hp hcoprime hodd hcuberight, have u_ne_zero : u ≠ 0, { rintro rfl, rw [zero_mul, zero_mul] at hpfactor, contradiction }, have haaa : 2 * p = (2 * u) * (u - 3 * v) * (u + 3 * v), { rw hpfactor, ring }, have : ¬even (u - 3 * v), { simp [huvodd] with parity_simps }, have : ¬even (u + 3 * v), { simp [huvodd] with parity_simps }, have notdvd_2_2 : ¬(2 ∣ u - 3 * v), { rw ←even_iff_two_dvd, exact ‹¬even (u - 3 * v)› }, have hddd : ¬(3 ∣ p), { intro H, have : 3 ∣ p ^ 2 + 3 * q ^ 2, { apply dvd_add, { rw pow_two, exact H.mul_left _ }, { apply dvd_mul_right } }, have : 3 ∣ 2 * p := H.mul_left 2, have := is_coprime.is_unit_of_dvd' hgcd ‹_› ‹_›, rw is_unit_iff_dvd_one at this, norm_num at this }, have not_3_dvd_2 : ¬(3 ∣ (u - 3 * v)), { intro hd2, apply hddd, rw hpfactor, exact (hd2.mul_left _).mul_right _ }, have notdvd_3_3 : ¬(3 ∣ (u + 3 * v)), { intro hd3, apply hddd, rw hpfactor, exact hd3.mul_left _ }, obtain ⟨s, hs⟩ := hcubeleft, obtain ⟨C, A, B, HCpos, HApos, HBpos, HC, HA, HB⟩ : ∃ X Y Z : ℤ, X ≠ 0 ∧ Y ≠ 0 ∧ Z ≠ 0 ∧ 2 * u = X ^ 3 ∧ u - 3 * v = Y ^ 3 ∧ u + 3 * v = Z ^ 3, { apply int.cube_of_coprime (2 * u) (u - 3 * v) (u + 3 * v) s, { apply mul_ne_zero two_ne_zero u_ne_zero }, { rw sub_ne_zero, rintro rfl, simpa only [int.not_even_bit1, false_or, iff_not_self] with parity_simps using huvodd }, { intro H, rw add_eq_zero_iff_eq_neg at H, simpa [H] with parity_simps using huvodd }, { apply int.gcd1_coprime12 u v; assumption }, { apply int.gcd1_coprime13 u v; assumption }, { apply int.gcd1_coprime23 u v; assumption }, { rw ←haaa, exact hs } }, refine ⟨A, B, C, HApos, HBpos, HCpos, _, _⟩, { rw [mul_comm, ←mul_assoc (C ^ 3), ←HA, ←HB, ←HC, ←haaa] }, { rw [←HA, ←HB, ←HC], ring }, end lemma gcd3_coprime {u v : ℤ} (huvcoprime: is_coprime u v) (huvodd : even u ↔ ¬even v) : is_coprime (2 * v) (u + v) ∧ is_coprime (2 * v) (u - v) ∧ is_coprime (u - v) (u + v) := begin have haddodd : ¬even (u + v), { simp [huvodd] with parity_simps }, have hsubodd : ¬even (u - v), { simp [huvodd] with parity_simps }, have haddcoprime : is_coprime (u + v) (2 * v), { apply is_coprime_of_prime_dvd, { rintro ⟨h1, -⟩, norm_num [h1] at haddodd }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, have hkdvdright' : k ∣ v, { rw even_iff_two_dvd at haddodd, exact int.dvd_mul_cancel_prime' haddodd hkdvdleft int.prime_two hkdvdright }, apply huvcoprime.is_unit_of_dvd' _ hkdvdright', rw [←add_sub_cancel u v], apply dvd_sub hkdvdleft hkdvdright' }, have hsubcoprime : is_coprime (u - v) (2 * v), { apply is_coprime_of_prime_dvd, { rintro ⟨h1, -⟩, norm_num [h1] at hsubodd }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, have hkdvdright' : k ∣ v, { rw even_iff_two_dvd at hsubodd, exact int.dvd_mul_cancel_prime' hsubodd hkdvdleft int.prime_two hkdvdright }, apply huvcoprime.is_unit_of_dvd' _ hkdvdright', rw [←sub_add_cancel u v], exact dvd_add hkdvdleft hkdvdright' }, have haddsubcoprime : is_coprime (u + v) (u - v), { apply is_coprime_of_prime_dvd, { rintro ⟨h1, -⟩, norm_num [h1] at haddodd }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, rw even_iff_two_dvd at haddodd, apply huvcoprime.is_unit_of_dvd'; apply int.dvd_mul_cancel_prime' haddodd hkdvdleft int.prime_two, { convert dvd_add hkdvdleft hkdvdright, ring }, { convert dvd_sub hkdvdleft hkdvdright, ring } }, exact ⟨haddcoprime.symm, hsubcoprime.symm, haddsubcoprime.symm⟩, end lemma descent_gcd3_coprime {q s : ℤ} (h3_ndvd_q : ¬3 ∣ q) (hspos : s ≠ 0) (hcoprime' : is_coprime s q) (hodd' : even q ↔ ¬even s) : is_coprime (3 ^ 2 * 2 * s) (q ^ 2 + 3 * s ^ 2) := begin have h2ndvd : ¬(2 ∣ (q ^ 2 + 3 * s ^ 2)), { rw ←even_iff_two_dvd, simp [two_ne_zero, hodd'] with parity_simps }, have h3ndvd : ¬(3 ∣ (q ^ 2 + 3 * s ^ 2)), { intro H, apply h3_ndvd_q, rw ←dvd_add_iff_left (dvd_mul_right _ _) at H, exact prime.dvd_of_dvd_pow int.prime_three H }, apply is_coprime_of_prime_dvd, { rintro ⟨h1, -⟩, rw mul_eq_zero at h1, exact hspos (h1.resolve_left (by norm_num)) }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, have : k ∣ s, { apply int.dvd_mul_cancel_prime' h2ndvd hkdvdright int.prime_two, apply int.dvd_mul_cancel_prime' h3ndvd hkdvdright int.prime_three, apply int.dvd_mul_cancel_prime' h3ndvd hkdvdright int.prime_three, convert hkdvdleft using 1, ring }, apply hcoprime'.is_unit_of_dvd' this, apply hkprime.dvd_of_dvd_pow, rw dvd_add_iff_left ((this.pow two_ne_zero).mul_left _), exact hkdvdright end lemma descent_gcd3 (a b c p q : ℤ) (hp : p ≠ 0) (hq : q ≠ 0) (hcoprime : is_coprime p q) (hodd : even p ↔ ¬even q) (hcube : 2 * p * (p ^ 2 + 3 * q ^ 2) = a ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = b ^ 3 ∨ 2 * p * (p ^ 2 + 3 * q ^ 2) = c ^ 3) (h : flt_coprime 3 a b c) (hgcd : (2 * p).gcd (p ^ 2 + 3 * q ^ 2) = 3) : ∃ (a' b' c' : ℤ), a' ≠ 0 ∧ b' ≠ 0 ∧ c' ≠ 0 ∧ (a' ^ 3 * b' ^ 3 * c' ^ 3).nat_abs ≤ (2 * p).nat_abs ∧ a' ^ 3 + b' ^ 3 = c' ^ 3 := begin obtain ⟨⟨hapos, hbpos, hcpos, h⟩, habcoprime, haccoprime, hbccoprime⟩ := h, -- 1. have h3_dvd_p : 3 ∣ p, { apply int.dvd_mul_cancel_prime' _ dvd_rfl int.prime_two, { zify at hgcd, rw ← hgcd, exact int.gcd_dvd_left _ _}, { norm_num } }, have h3_ndvd_q : ¬(3 ∣ q), { intro H, have := hcoprime.is_unit_of_dvd' h3_dvd_p H, rw int.is_unit_iff_nat_abs_eq at this, norm_num at this }, -- 2. obtain ⟨s, rfl⟩ := h3_dvd_p, have hspos : s ≠ 0 := right_ne_zero_of_mul hp, have hps : 2 * (3 * s) * ((3 * s) ^ 2 + 3 * q ^ 2) = 3 ^ 2 * 2 * s * (q ^ 2 + 3 * s ^ 2), { ring }, -- 3. have hcoprime' : is_coprime s q, { apply is_coprime_of_prime_dvd, { rintro ⟨h1, -⟩, exact hspos h1 }, intros k hkprime hkdvdleft hkdvdright, apply hkprime.not_unit, apply hcoprime.is_unit_of_dvd' _ hkdvdright, exact hkdvdleft.mul_left 3 }, have hodd' : even q ↔ ¬even s, { rw [iff.comm, not_iff_comm, iff.comm], simpa with parity_simps using hodd }, have hcoprime'' : is_coprime (3^2 * 2 * s) (q ^ 2 + 3 * s ^ 2), { exact descent_gcd3_coprime h3_ndvd_q hspos hcoprime' hodd' }, -- 4. obtain ⟨r, hr⟩ : ∃ r, 2 * (3 * s) * ((3 * s) ^ 2 + 3 * q ^ 2) = r ^ 3, { rcases hcube with (_|_|_); [use a, use b, use c]; exact hcube }, rw hps at hr, obtain ⟨hcubeleft, hcuberight⟩ := int.eq_pow_of_mul_eq_pow_bit1 hcoprime'' hr, -- 5. -- todo shadows hq hq obtain ⟨u, v, hq, hs, huvcoprime, huvodd⟩ := obscure' q s hq hcoprime'.symm hodd' hcuberight, have hu : u ≠ 0, { rintro rfl, norm_num at hq }, have hv : v ≠ 0, { rintro rfl, norm_num at hs }, -- 6. obtain ⟨haddcoprime, hsubcoprime, haddsubcoprime⟩ := gcd3_coprime huvcoprime huvodd, -- 7. obtain ⟨e, he⟩ := hcubeleft, obtain ⟨t, rfl⟩ : 3 ∣ e, { rw [←int.pow_dvd_pow_iff (by norm_num : 0 < 3), ←he, hs], convert dvd_mul_right _ (2 * v * (u - v) * (u + v)) using 1, norm_num, ring }, have ht : 2 * v * (u - v) * (u + v) = t ^ 3, { have : (3 ^ 3 : ℤ) ≠ 0, { norm_num }, rw [←mul_right_inj' this, ←mul_pow, ←he, hs], ring }, obtain ⟨A, B, C, HApos, HBpos, HCpos, HA, HB, HC⟩ : ∃ X Y Z : ℤ, X ≠ 0 ∧ Y ≠ 0 ∧ Z ≠ 0 ∧ 2 * v = X ^ 3 ∧ u - v = Y ^ 3 ∧ u + v = Z ^ 3, { apply int.cube_of_coprime, { exact mul_ne_zero two_ne_zero hv, }, { intro H, rw sub_eq_zero at H, simpa [H] with parity_simps using huvodd, }, { intro H, rw add_eq_zero_iff_eq_neg at H, simpa [H] with parity_simps using huvodd }, { exact hsubcoprime }, { exact haddcoprime }, { exact haddsubcoprime }, { exact ht } }, refine ⟨A, B, C, HApos, HBpos, HCpos, _, _⟩, -- 9. { rw [←mul_assoc, mul_comm, ←mul_assoc (C ^ 3), ←HA, ←HB, ←HC], set x := v * (u - v) * (u + v) with hx, calc ((u + v) * (2 * v) * (u - v)).nat_abs = (2 * x).nat_abs : by { rw hx, congr' 1, ring } ... = 2 * x.nat_abs : by { rw [int.nat_abs_mul 2], refl } ... ≤ 3 * x.nat_abs : nat.mul_le_mul_right _ (by norm_num) ... = (3 * x).nat_abs : by { rw [int.nat_abs_mul 3], refl } ... = s.nat_abs : by { rw [hx, hs], congr' 1, ring } ... ≤ (2 * 3) * s.nat_abs : nat.le_mul_of_pos_left (by norm_num) ... = (2 * 3 * s).nat_abs : by { rw [int.nat_abs_mul (2 * 3)], refl } }, { rw [←HA, ←HB, ←HC], ring }, end lemma descent (a b c : ℤ) (h : flt_coprime 3 a b c) : ∃ a' b' c' : ℤ, a' ≠ 0 ∧ b' ≠ 0 ∧ c' ≠ 0 ∧ (a' * b' * c').nat_abs < (a * b * c).nat_abs ∧ a' ^ 3 + b' ^ 3 = c' ^ 3 := begin -- 3. have := descent2 a b c h, obtain ⟨p, q, hp, hq, hcoprime, hodd, hcube, haaa⟩ := this, suffices : ∃ a' b' c' : ℤ, a' ≠ 0 ∧ b' ≠ 0 ∧ c' ≠ 0 ∧ (a' ^ 3 * b' ^ 3 * c' ^ 3).nat_abs ≤ (2 * p).nat_abs ∧ a' ^ 3 + b' ^ 3 = c' ^ 3, { obtain ⟨a', b', c', ha', hb', hc', hsmaller, hsolution⟩ := this, refine ⟨a', b', c', ha', hb', hc', _, hsolution⟩, rw ←nat.pow_lt_iff_lt_left (by norm_num : 1 ≤ 3), convert lt_of_le_of_lt hsmaller haaa; simp [mul_pow, int.nat_abs_mul, int.nat_abs_pow] }, -- 4. cases gcd1or3 p q hp hcoprime hodd with hgcd hgcd, -- 5. { rw int.gcd_eq_one_iff_coprime at hgcd, apply descent_gcd1 a b c p q hp hcoprime hodd hcube h hgcd }, { apply descent_gcd3 a b c p q hp hq hcoprime hodd hcube h hgcd }, end lemma flt_three {a b c : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) (hc : c ≠ 0) : a ^ 3 + b ^ 3 ≠ c ^ 3 := begin induction h : (a * b * c).nat_abs using nat.strong_induction_on with k' IH generalizing a b c, intro H, obtain ⟨x'', y'', z'', hxle, hyle, hzle, hcoprime⟩ := exists_coprime zero_lt_three ha hb hc H, obtain ⟨x', y', z', hx'pos, hy'pos, hz'pos, hsmaller, hsolution⟩ := descent x'' y'' z'' hcoprime, refine IH (x' * y' * z').nat_abs _ hx'pos hy'pos hz'pos rfl hsolution, apply lt_of_lt_of_le hsmaller, rw ←h, simp only [int.nat_abs_mul], exact nat.mul_le_mul (nat.mul_le_mul hxle hyle) hzle, end
Formal statement is: lemma sgn_one [simp]: "sgn (1::'a::real_normed_algebra_1) = 1" Informal statement is: The sign of 1 is 1.
! The length of the line below is exactly 73 characters program aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa end
%% Copyright (C) 2016-2017 Lagu %% Copyright (C) 2017, 2022 Colin B. Macdonald %% %% This file is part of OctSymPy. %% %% OctSymPy is free software; you can redistribute it and/or modify %% it under the terms of the GNU General Public License as published %% by the Free Software Foundation; either version 3 of the License, %% or (at your option) any later version. %% %% This software is distributed in the hope that it will be useful, %% but WITHOUT ANY WARRANTY; without even the implied warranty %% of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See %% the GNU General Public License for more details. %% %% You should have received a copy of the GNU General Public %% License along with this software; see the file COPYING. %% If not, see <http://www.gnu.org/licenses/>. %% -*- texinfo -*- %% @documentencoding UTF-8 %% @defmethod @@sym [@var{K}, @var{E}] = ellipke (@var{m}) %% Complete elliptic integrals of the first and second kinds. %% %% Example: %% @example %% @group %% syms m %% [K, E] = ellipke (m) %% @result{} K = (sym) K(m) %% @result{} E = (sym) E(m) %% @end group %% @end example %% %% @seealso{ellipke, @@sym/ellipticK, @@sym/ellipticE} %% @end defmethod function varargout = ellipke(m) if (nargin ~= 1 || nargout > 2) print_usage (); end if (nargout == 0 || nargout == 1) varargout = {ellipticK(m)}; else varargout = {ellipticK(m) ellipticE(m)}; end end %!error ellipke (sym(1), 2) %!test %! for i = 2:10 %! [K E] = ellipke (sym (1)/i); %! [k e] = ellipke (1/i); %! assert (double ([K E]), [k e], 2*eps) %! end
Module Type A. Axiom f : True. End A. Module M8416 : A. Definition f := I. End M8416.
program test_tan use lfortran_intrinsic_math, only: tan implicit none real :: x x = tan(1.5) print *, x if (abs(x - 14.1014204) > 1e-5) error stop end program
#include <boost/multiprecision/cpp_int/bitwise.hpp>
--- author: Nathan Carter ([email protected]) --- This answer assumes you have imported SymPy as follows. ```python from sympy import * # load all math functions init_printing( use_latex='mathjax' ) # use pretty math output ``` We define here the same sequence we defined in the task entitled how to define a mathematical sequence. ```python var( 'n' ) # use n as a symbol a_n = 1 / ( n + 1 ) # formula for a term seq = sequence( a_n, (n,0,oo) ) # build the sequence seq ``` $\displaystyle \left[1, \frac{1}{2}, \frac{1}{3}, \frac{1}{4}, \ldots\right]$ We can turn it into a mathematical series by simply replacing the word `sequence` with the word `Sum`. This does not compute the answer, but just writes the series for us to view. In this case, it is an infinite series. ```python Sum( a_n, (n,0,oo) ) ``` $\displaystyle \sum_{n=0}^{\infty} \frac{1}{n + 1}$ You can compute the answer by appending the code `.doit()` to the above code, which asks SymPy to "do" (or evaluate) the sum. ```python Sum( a_n, (n,0,oo) ).doit() ``` $\displaystyle \infty$ In this case, the series diverges. We can also create and evaluate finite series by replacing the `oo` with a number. ```python Sum( a_n, (n,0,10) ).doit() ``` $\displaystyle \frac{83711}{27720}$
State Before: z : ℂ ⊢ 0 ≤ arg z ↔ 0 ≤ z.im State After: case inl ⊢ 0 ≤ arg 0 ↔ 0 ≤ 0.im case inr z : ℂ h₀ : z ≠ 0 ⊢ 0 ≤ arg z ↔ 0 ≤ z.im Tactic: rcases eq_or_ne z 0 with (rfl | h₀) State Before: case inr z : ℂ h₀ : z ≠ 0 ⊢ 0 ≤ arg z ↔ 0 ≤ z.im State After: no goals Tactic: calc 0 ≤ arg z ↔ 0 ≤ Real.sin (arg z) := ⟨fun h => Real.sin_nonneg_of_mem_Icc ⟨h, arg_le_pi z⟩, by contrapose! intro h exact Real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_arg _)⟩ _ ↔ _ := by rw [sin_arg, le_div_iff (abs.pos h₀), MulZeroClass.zero_mul] State Before: case inl ⊢ 0 ≤ arg 0 ↔ 0 ≤ 0.im State After: no goals Tactic: simp State Before: z : ℂ h₀ : z ≠ 0 ⊢ 0 ≤ Real.sin (arg z) → 0 ≤ arg z State After: z : ℂ h₀ : z ≠ 0 ⊢ arg z < 0 → Real.sin (arg z) < 0 Tactic: contrapose! State Before: z : ℂ h₀ : z ≠ 0 ⊢ arg z < 0 → Real.sin (arg z) < 0 State After: z : ℂ h₀ : z ≠ 0 h : arg z < 0 ⊢ Real.sin (arg z) < 0 Tactic: intro h State Before: z : ℂ h₀ : z ≠ 0 h : arg z < 0 ⊢ Real.sin (arg z) < 0 State After: no goals Tactic: exact Real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_arg _) State Before: z : ℂ h₀ : z ≠ 0 ⊢ 0 ≤ Real.sin (arg z) ↔ 0 ≤ z.im State After: no goals Tactic: rw [sin_arg, le_div_iff (abs.pos h₀), MulZeroClass.zero_mul]
library(rhdf5) library(qvalue) library(dplyr) library(readr) filterFile <- "C:/OnlineFolders/BitSync/Current_Work/EBI_HipSci/Trans_iPSC/Expression/FeatureCounts_Genes/Paired/Filter_Min_tpm_0.5_Abundant_in_20perc_Samp.txt" #filterFile <- "/nfs/research2/hipsci/processed_data/rna_seq/intersectionProteomics/PEER/TestOptimal_N_Factors/Filter_Abundant_in_50perc_Samp.txt" filterFeatures <- NULL if(!(filterFile=="" || is.na(filterFile))){ filterFeatures = read.delim(filterFile,as.is=T,header=F)[,1] } ##Settings baseFolder <- "C:/OnlineFolders/BitSync/Current_Work/EBI_HipSci/QTL_Output/Replication_eQTL_Gen/eQTL_Gen_Cis/" baseFolder <- "C:/OnlineFolders/BitSync/Current_Work/EBI_HipSci/QTL_Output/Replication_eQTL_Gen/eQTL_Gen_Cis_5p/" writeGlobalSig = T writeGlobalSigTop = T writeFeatureSig = T writeNominalSig = F topResultBased = T threshold = 0.05 threshold2 = 1.0 multipleTestingGlobal = "ST" # multipleTestingGlobal = "BF" ################# ##Read files. setwd(baseFolder) results <- NULL # filesToRead <- list.files(".",pattern = ".gz",full.names = T) # # for(i in filesToRead){ # tmp <- readr::read_delim(file = i,delim="\t") # if(length(tmp)>0){ # #if(length(grep(colnames(df),pattern = "n_samples"))>0){ # # df <- df[,-grep(colnames(df),pattern = "n_samples")] # #} # if(!is.null(filterFeatures)){ # tmp <- tmp[which(tmp$feature_id%in%filterFeatures),] # } # # if(nrow(tmp)>0){ # results = rbind(results,tmp) # } # } # } results <- read.delim("./top_qtl_results_all.txt",as.is=T) results <- results[which(results$feature_id %in% filterFeatures),] ##Remove NaN values and other failed empirical recalibrations. results <- results[-which(is.na(results$empirical_feature_p_value)),] results <- results[-which(results$empirical_feature_p_value<0),] results <- results[order(results$empirical_feature_p_value, results$p_value,decreasing = F),] if(topResultBased){ resultsFull <- results results <- resultsFull[which(!duplicated(resultsFull$feature_id)),] } ##Multiple testing if(multipleTestingGlobal=="ST"){ results["global_corr_p_value"] <- qvalue(results$empirical_feature_p_value)$qvalues } else if (multipleTestingGlobal=="BF"){ observedFeatures <- length(unique(results$feature_id)) results["global_corr_p_value"] <- results$empirical_feature_p_value*observedFeatures results$global_corr_p_value[results$global_corr_p_value>1]<-1 } results <- results[order(results$global_corr_p_value,results$empirical_feature_p_value, results$p_value,decreasing = F),] length(which(results$global_corr_p_value<threshold)) if(writeGlobalSigTop){ write.table(paste(baseFolder,"top_results_global_level_",threshold,".txt",sep=""),x = results[intersect(which(results$global_corr_p_value<threshold),which(!duplicated(results$feature))),],sep="\t",row.names=F,quote=F) } if(writeGlobalSigTop & topResultBased){ write.table(paste(baseFolder,"top_results_global_level_",threshold,".txt",sep=""),x = results[intersect(which(results$global_corr_p_value<threshold),which(!duplicated(results$feature))),],sep="\t",row.names=F,quote=F) } if(writeGlobalSig & !topResultBased){ write.table(paste(baseFolder,"results_global_level_",threshold,".txt",sep=""),x = results[results$global_corr_p_value<threshold,],sep="\t",row.names=F,quote=F) } if(writeFeatureSig & !topResultBased){ write.table(paste(baseFolder,"results_gene_level_",threshold,".txt",sep=""),x = results[results$feature_corr_p_value<threshold,],sep="\t",row.names=F,quote=F) } if(writeNominalSig){ write.table(paste(baseFolder,"results_nominal_level_",threshold2,".txt",sep=""),x = resultsFull[resultsFull$p_value<threshold2,],sep="\t",row.names=F,quote=F) } if(writeGlobalSig & topResultBased){ if(length(which(results$global_corr_p_value<threshold))>0){ minFeatureCorrected <- max(results$empirical_feature_p_value[which(results$global_corr_p_value<threshold)]) write.table(paste(baseFolder,"results_global_level_",threshold,".txt",sep=""),x = resultsFull[resultsFull$empirical_feature_p_value<minFeatureCorrected,],sep="\t",row.names=F,quote=F) } }
/home/s/rtl_work/fpga_lib/axi/rtl/example/axi_full_v1_S00_AXI.v /home/s/rtl_work/fpga_lib/axi/rtl/example/axi_full_v1.v /home/s/rtl_work/fpga_lib/axi/rtl/example/tb_AXI_full.v /home/s/rtl_work/fpga_lib/axi/rtl/example/axi_full_v1_M00_AXI.v
import numpy as np import time import Adafruit_GPIO.I2C as I2C from Adafruit_PCA9685 import * from Adafruit_BNO055 import BNO055 from nxp_imu import IMU import VL53L1X import threading from ahrs import * FRONT_RIGHT = 0 REAR_RIGHT = 1 REAR_LEFT = 2 FRONT_LEFT = 3 FORE = 0 STARBOARD = 1 AFT = 2 PORT = 3 PWM_FREQ_HZ = 60 # cycles per second, do not exceed 240! ESC_PWM_MIN = int((0.001 / (1/PWM_FREQ_HZ)) * 4096) # esc off = pulse width of 1,000us = 0.001s # 0.001/(1/freq) = pulse width as % of time frame # 4096 ticks per frame; provide value in ticks ESC_PWM_MAX = ESC_PWM_MIN * 2 # max throttle = 2000us (min x 2, in ticks) PID_XYZ_ROLL = [[0.030,0.0000,0.000],[0.030,0.0000,0.000],[0,0,0]] PID_GYRO_ONLY = [[0.0080,0.0000,0.000],[0.0080,0.0000,0.000],[0,0,0]] PID_XYZ_OFF = [[0,0,0],[0,0,0],[0,0,0]] PID_AHRS = [[0.01,0.0,0.0],[0.01,0.0,0.0],[0.0,0.0,0.0]] class Thrust: def __init__(self, thrust_limit=1.0): if thrust_limit > 1.0 or thrust_limit < 0.0: print("WARNING: Thrust limit is out of bounds; disabling thrust", thrust_limit) self.thrust_limit = 0.0 else: self.thrust_limit = max(min(thrust_limit, 1.0), 0.0) self.esc_range = ESC_PWM_MAX - ESC_PWM_MIN self.pwm = Adafruit_PCA9685.PCA9685() # 16-channel PWM controller self.pwm.set_pwm_freq(PWM_FREQ_HZ) self.armed = self.arm() self.v_pwm = ([ESC_PWM_MIN,ESC_PWM_MIN,ESC_PWM_MIN,ESC_PWM_MIN]) self.pwm.set_pwm self.i = 0 self.start_time = None self.stop_time = None # setting must be [FORE,STARBOARD,AFT,PORT], each value 0.0 to 100.0 def set_throttle(self, setting): if self.start_time == None: self.start_time = time.time() setting = setting if self.armed else [0,0,0,0] self.throttle = np.maximum(setting, 0.0) self.throttle = np.minimum(self.throttle, self.thrust_limit) self.v_pwm[FRONT_RIGHT] = (self.throttle[FORE] + self.throttle[STARBOARD])/2 self.v_pwm[REAR_RIGHT] = (self.throttle[AFT] + self.throttle[STARBOARD])/2 self.v_pwm[REAR_LEFT] = (self.throttle[AFT] + self.throttle[PORT])/2 self.v_pwm[FRONT_LEFT] = (self.throttle[FORE] + self.throttle[PORT])/2 self.v_pwm = np.multiply(self.v_pwm, self.esc_range) self.v_pwm = np.rint(self.v_pwm) self.v_pwm = np.add(self.v_pwm, ESC_PWM_MIN) self.pwm.set_pwm(FRONT_RIGHT, 0, int(self.v_pwm[FRONT_RIGHT])) self.pwm.set_pwm(REAR_RIGHT, 0, int(self.v_pwm[REAR_RIGHT])) self.pwm.set_pwm(REAR_LEFT, 0, int(self.v_pwm[REAR_LEFT])) self.pwm.set_pwm(FRONT_LEFT, 0, int(self.v_pwm[FRONT_LEFT])) print(self) self.i += 1 self.stop_time = time.time() def throttle_off(self): self.pwm.set_pwm(FRONT_RIGHT, 0, ESC_PWM_MIN) self.pwm.set_pwm(REAR_RIGHT, 0, ESC_PWM_MIN) self.pwm.set_pwm(REAR_LEFT, 0, ESC_PWM_MIN) self.pwm.set_pwm(FRONT_LEFT, 0, ESC_PWM_MIN) def arm(self): print('Arming ESCs') for n in range(4): self.pwm.set_pwm(FRONT_RIGHT, 0, ESC_PWM_MIN) time.sleep(1) for n in range(4): self.pwm.set_pwm(FRONT_RIGHT, 0, int(ESC_PWM_MIN + self.esc_range * 0.32)) time.sleep(1) for n in range(4): self.pwm.set_pwm(FRONT_RIGHT, 0, ESC_PWM_MIN) return True def disarm(self): self.throttle_off() self.armed = False def __str__(self): esc_pct = np.subtract(self.v_pwm, ESC_PWM_MIN) esc_pct = np.divide(esc_pct, self.esc_range) return 'FR,RR,RL,FL' + str(esc_pct) + ', armed = ' + str(self.armed) ''' 3-axis PID controller - requires [kp,ki,kd] for each of 3 axes (x,y,z) - accepts translation matrix to apply pid output to motor speeds [fore, starboard, aft, port] - default translation matrix assumes controller is applied to angular velocity - return value from update() is a vector of motor speed adjustments [fore, starboard, aft, port] ''' class PidController: t_angular = [[0,-1,0,1],[1,0,-1,0],[-1,1,-1,1]] # translation matrix to apply angular values to motors t_linear = [[1,0,-1,0],[0,1,0,-1],[-1,-1,-1,-1]] # translation matrix to apply linear values to motors def __init__(self, k_3_3, f_state, target=[0.0,0.0,0.0], t=t_angular): self.k = k_3_3 # [kp,ki,kd] for each of 3 axes (x,y,z) self.f_state = f_state # function that returns current state (x,y,z) self.target = target # target setpoints for 3 axes (x,y,z) self.p = [None,None,None] # p for 3 axes (x,y,z) self.i = [0.0,0.0,0.0] # i for 3 axes (x,y,z) self.d = [0.0,0.0,0.0] # d for 3 axes (x,y,z) self.pid = [0.0,0.0,0.0] # resulting pid values for 3 axes (x,y,z) self.t = t # translation matrix to apply pid to motor speeds self.count = 0 self.throttle_adj = [None,None,None,None] self.log = [] self.start_time = None self.stop_time = None def update(self): if self.start_time == None: self.start_time = time.time() self.count += 1 xyz, xyz_dot, dt = self.f_state() self.throttle_adj = [0.0,0.0,0.0,0.0] for n in range(3): error = xyz[n] - self.target[n] self.p[n] = error self.i[n] = xyz_dot[n] * dt self.d[n] = -xyz_dot[n] self.pid[n] = self.k[n][0] * self.p[n] + self.k[n][1] * self.i[n] + self.k[n][2] * self.d[n] self.throttle_adj = np.add(self.throttle_adj, np.multiply(self.pid[n], self.t[n])) self.stop_time = time.time() return self.throttle_adj def abs_max(self, v, l): return max(min(v,l), -l) def set_target(self, k_3): self.target = k_3 def set_limit(self, limit): self.limit = limit def __str__(self): out = str(self.count) out += ' p,i,d(x,y,z) = ' out += str(self.p) out += str(self.i) out += str(self.d) out += ' pid(x,y,z) = ' out += str(self.pid) return out class BoundedPid(PidController): def __init__(self, k_3_3, f_state, target, t, b_state, b_3): super().__init__(k_3_3, f_state, target, t) self.b_state = b_state self.b_3 = b_3 def update(self, dt): self.throttle_adj = super().update(dt) vals = self.b_state() for n in range(3): cap = 1.0 - ((vals[n] - self.b_3[n]) / self.b_3[n]) self.throttle_adj = np.minimum(self.throttle_adj, cap) return self.throttle_adj class QuadQav250: def __init__(self): try: self.thrust = Thrust() self.ahrs = AHRS() self.angular_pid_ahrs = PidController(PID_AHRS,self.ahrs.get) self.ahrs.start() except Exception: self.shutdown() print('Failed to initialize') def shutdown(self): try: self.thrust.disarm finally: print('===DISARMED===') try: self.ahrs.stop() self.altimeter.stop() finally: print('===SHUTDOWN COMPLETE===') def test(self): for n in range(100): self.angular_pid_ahrs.update() print(self.angular_pid_ahrs) def kill(self): self.shutdown() def fly(self): try: print('============================') print('STARTING TEST FLIGHT') base_throttle = [.32,.32,.32,.32] t0 = time.time() i = 0 while time.time() < t0 + 6.0: pid_update = self.angular_pid_ahrs.update() v_throttle = np.add(base_throttle, pid_update) self.thrust.set_throttle(base_throttle) #print(self.thrust) #self.thrust.set_throttle(base_throttle) print(self.ahrs.i, self.ahrs.stop_time - self.ahrs.start_time, (self.ahrs.stop_time - self.ahrs.start_time)/self.ahrs.i) print(self.angular_pid_ahrs.count, self.angular_pid_ahrs.stop_time - self.angular_pid_ahrs.start_time, (self.angular_pid_ahrs.stop_time - self.angular_pid_ahrs.start_time)/self.angular_pid_ahrs.count) print(self.thrust.i, self.thrust.stop_time - self.thrust.start_time, (self.thrust.stop_time - self.thrust.start_time)/self.thrust.i) finally: self.shutdown() q = QuadQav250() #q.test() q.fly() q.kill()
[SAMPLE ESSAY: ARTICLE How Internet Affects Life. How Internet Affects Life. By: Syawalynn Zain. Nowadays, the use of Internet is increasing especially among adolescence or more accurately, students. The Internet issue is discussed by the adults and parents. # Please take note that this is an example of an essay for ARTICLE in SPM 2. 0 Advantages of the Internet Firstly, the internet can let a person to communicate with people in virtually any parts of the world through the internet or email, without having to leave his room. Email allowed peoples to communicate with minimum of times. I think using internet has more advantages then disadvantages. First of all, Internet provides access to a lot of information. Some of them are very useful in your job other helps in your hobby. Searching the net with Google, you can find everything you want. You can also do shopping using Internet. Advantages and Disadvantages of the Internet (Essay 1) Ten years ago, the Internet was practically unheard of by most people. Today, the Internet is one of the most powerful tools throughout the world. The Internet is a collection of various services and resources. The Internets main components are Email and the World Wide Web. The possible advantages of implementing the Internet in the classroom are as diverse as the services and tools offered by the network. The Internet offers many resources that are not usually available in any geographic location. In addition to these resources, the Internet also enhances various Mar 19, 2011 Advantages of the using the internet. These days, life without the internet is very difficult. People do a lot of woks on the internet. At this time, the internet seems as small as a village. Everyone can knows more and finds any information, easily. In the modern world, people help each others on the internet. Benefits Of Internet Essay Examples. 15 total results. A Report on the Benefits of the Internet in Business.